/*
@file Include/Classes/System/IO/StreamWriter.ab
@brief StreamWriterの実装。
*/

Namespace System
Namespace IO

/*
@brief ストリームへの書き込みを行うTextWriterの派生。
@date 2008/03/09
@auther Egtra
*/
Class StreamWriter
	Inherits TextWriter
Public
	/*
	@date 2008/03/09
	@auther Egtra
	*/
	Sub StreamWriter(path As String)
		init(New FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
	End Sub

	/*
	@date 2008/03/09
	@auther Egtra
	*/
	Sub StreamWriter(stream As Stream)
		init(stream)
	End Sub

	Override Sub Flush()
		Dim len = buf.Length
		If len > 0 Then
			s.Write(StrPtr(buf) As *Byte, 0, len)
			buf.Length = 0
		End If
	End Sub

	Override Sub Write(str As String)
		buf.Append(str)
		Dim len = buf.Length
		If len >= 2048 Then
			s.Write(StrPtr(buf) As *Byte, 0, len)
			buf.Length = 0
		End If
	End Sub

	Override Sub Write(x As Boolean)
		buf.Append(x)
	End Sub
	
	Override Sub Write(x As Char)
		buf.Append(x)
	End Sub

	Override Sub Write(x As Byte)
		buf.Append(x)
	End Sub
#ifdef UNICODE
	Override Sub Write(x As SByte)
		buf.Append(x)
	End Sub
#else
	Override Sub Write(x As Word)
		buf.Append(x)
	End Sub
#endif
	Override Sub Write(x As Integer)
		buf.Append(x)
	End Sub

	Override Sub Write(x As DWord)
		buf.Append(x)
	End Sub

	Override Sub Write(x As Long)
		buf.Append(x)
	End Sub

	Override Sub Write(x As QWord)
		buf.Append(x)
	End Sub

	Override Sub Write(x As Int64)
		buf.Append(x)
	End Sub

	Override Sub Write(x As Single)
		buf.Append(x)
	End Sub

	Override Sub Write(x As Double)
		buf.Append(x)
	End Sub

	Override Sub Write(x As Object)
		Write(x.ToString)
	End Sub

Protected
	Override Sub Dispose(disposing As Boolean)
		If disposing Then
			Dim len = buf.Length
			If len > 0 Then
				s.Write(StrPtr(buf) As *Byte, 0, len)
			End If
			s.Dispose()
		End If
	End Sub

Private
	Sub init(stream As Stream)
		s = stream
		buf = New System.Text.StringBuilder(4096)
	End Sub

	buf As Text.StringBuilder
	s As System.IO.Stream
End Class

End Namespace
End Namespace
