terminals/Xtreams__BufferedWriteStream.st
author Martin Kobetic <mkobetic@gmail.com>
Mon, 22 Aug 2011 16:04:00 +0000
changeset 9 6c90659cf105
child 25 02e7c3b6f63c
permissions -rw-r--r--
first cut

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

"{ NameSpace: Xtreams }"

WriteStream subclass:#BufferedWriteStream
	instanceVariableNames:'buffer'
	classVariableNames:''
	poolDictionaries:''
	category:'My Classes'
!

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_SVN
    ^ '$Id$'
! !