terminals/Xtreams__BufferedWriteStream.st
author Martin Kobetic
Sun, 17 Nov 2013 00:22:31 -0500
changeset 144 e193a6772be4
parent 109 9587e2df7029
permissions -rw-r--r--
merging

"{ Package: 'stx:goodies/xtreams/terminals' }"

"{ NameSpace: Xtreams }"

WriteStream subclass:#BufferedWriteStream
	instanceVariableNames:'buffer'
	classVariableNames:''
	poolDictionaries:''
	category:'Xtreams-Terminals'
!

BufferedWriteStream comment:'Wraps a stream and buffers output to it based on the size of the ring-buffer it has. This is useful for doing "burst" writing, where you know exactly when you can flush the stream. To force the buffer to the underlying stream, use #flush.

Instance Variables
	buffer  <RingBuffer>    a fixed size RingBuffer to buffer up output, released when it is full or #flush/#close is sent.

'
!


!BufferedWriteStream class methodsFor:'instance creation'!

on: aDestination bufferSize: bufferSize
	^self new on: aDestination bufferSize: bufferSize
! !

!BufferedWriteStream methodsFor:'accessing'!

write: anInteger from: aSequenceableCollection at: startIndex

	| count amount |
	count := 0.
	[[amount := buffer write: (buffer writeSize min: (anInteger - count)) from: aSequenceableCollection at: startIndex + count.
	count := count + amount.
	count < anInteger] whileTrue: [self flush]]
		on: Incomplete do: [:exception | (Incomplete on: aSequenceableCollection count: count + exception count at: startIndex) raise].
	^anInteger
! !

!BufferedWriteStream methodsFor:'initialize-release'!

close
	super close.
	buffer recycle.
	buffer := nil
!

contentsSpecies
	^destination contentsSpecies
!

flush
	destination write: buffer
!

on: aDestination bufferSize: bufferSize
	buffer := RingBuffer new: bufferSize class: aDestination contentsSpecies.
	super on: aDestination
! !

!BufferedWriteStream methodsFor:'printing'!

streamingPrintOn: aStream
	super streamingPrintOn: aStream.
	aStream
		write: ' buffered: ';
		print: buffer writeSize.
	buffer writeSize isZero ifTrue: [^self].
	aStream
		cr; tab;
		print: buffer contentsPast
! !

!BufferedWriteStream class methodsFor:'documentation'!

version_HG

    ^ '$Changeset: <not expanded> $'
! !