SelectingReadStream.st
author Claus Gittinger <cg@exept.de>
Sat, 05 Dec 2009 12:15:39 +0100
changeset 2362 eb7b174334c2
child 2366 45a774d5420c
permissions -rw-r--r--
initial checkin

"{ Package: 'stx:libbasic2' }"

Stream subclass:#SelectingReadStream
	instanceVariableNames:'selectBlock hasReadAhead readAhead inStream'
	classVariableNames:''
	poolDictionaries:''
	category:'Streams'
!

!SelectingReadStream class methodsFor:'documentation'!

documentation
"
    A stream which only delivers elements for which a select block returns true
    from an underlying stream. 

    Needs readAhead for proper atEnd handling.

    [instance variables:]
        hasReadAhead        - because nil is a valid read-element,
                            this is used to know if readAhead is valid.
"
!

examples
"
    |s|

    s := SelectingReadStream 
            on:#(1 2 3 4 5 6 7 8) readStream
            selecting:[:each | each even].
    s upToEnd  
"
! !

!SelectingReadStream class methodsFor:'instance creation'!

on:aStream selecting:aBlock
    ^ self basicNew on:aStream selecting:aBlock
! !

!SelectingReadStream methodsFor:'instance creation'!

on:aStream selecting:aBlock
    inStream := aStream.
    selectBlock := aBlock.
    hasReadAhead := false.
! !

!SelectingReadStream methodsFor:'queries'!

atEnd
    |el|

    hasReadAhead ifTrue:[^ false].

    [
        inStream atEnd ifTrue:[
            ^ true
        ].
        el := inStream next.
        (selectBlock value:el)
    ] whileFalse.
    readAhead := el.
    hasReadAhead := true.
    ^ false.
! !

!SelectingReadStream methodsFor:'reading'!

next
    |el|
    
    hasReadAhead ifTrue:[
        hasReadAhead := false.
        ^ readAhead
    ].
    [
        inStream atEnd ifTrue:[
            ^ self pastEndRead
        ].
        el := inStream next.
        (selectBlock value:el)
    ] whileFalse.
    ^ el
! !

!SelectingReadStream class methodsFor:'documentation'!

version_CVS
    ^ '$Header: /cvs/stx/stx/libbasic2/SelectingReadStream.st,v 1.1 2009-12-05 11:15:39 cg Exp $'
! !