WriteStream.st
author Claus Gittinger <cg@exept.de>
Tue, 02 Sep 1997 22:56:14 +0200
changeset 2894 344aec8ba014
parent 2883 ee0eb799bd3e
child 2899 431d8830445b
permissions -rw-r--r--
*** empty log message ***

"
 COPYRIGHT (c) 1989 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"

PositionableStream subclass:#WriteStream
	instanceVariableNames:''
	classVariableNames:''
	poolDictionaries:''
	category:'Streams'
!

!WriteStream class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (c) 1989 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"
!

documentation
"
    Streams for writing into.
    WriteStreams are especially useful, if big strings are to be constructed
    from pieces - create a writeStream, add the pieces (with #nextPut or
    #nextPutAll) and finally fetch the concatenated string via #contents.
    This is much better than constructing the big string by concatenating via
    the comma (,) operator, since less intermediate garbage objects are created.

    This implementation currently DOES change the 
    identity if the streamed-upon collection IF it cannot grow easily. 
    Collections which cannot grow easily are for example: Array, ByteArray and String.
    Thus it is slightly incompatible to ST-80 since 'aStream contents' does 
    not always return the original collection. This may change.

    [author:]
        Claus Gittinger
"
!

examples
"
                                                                [exBegin]
     |s|

     s := WriteStream on:''.
     s nextPutAll:'hello';
       space;
       nextPutAll:'world'.

     s contents inspect
                                                                [exEnd]

                                                                [exBegin]
     |s|

     s := WriteStream on:''.
     s nextPutAll:'hello';
       space;
       nextPutAll:'world'.

     Transcript nextPutLine:(s contents)
                                                                [exEnd]

                                                                [exBegin]
     |s|

     s := '' writeStream.
     s nextPutAll:'hello';
       space;
       nextPutAll:'world'.

     Transcript nextPutLine:(s contents)
                                                                [exEnd]
"

! !

!WriteStream methodsFor:'accessing'!

contents
    "return the current contents (a collection) of the stream.
     Currently, this returns the actual collection if possible
     (and reset is implemented to create a new one) in contrast to
     ST80, where contents returns a copy and reset only sets the writePointer.
     The ST/X behavior creates less temporary garbage in the normal case
     (where things are written for the contents only) but may be incompatible
     with some applications. Time will show, if this is to be changed."

    |lastIndex|

    lastIndex := position - 1.
    collection size == lastIndex ifFalse:[
        collection isFixedSize ifTrue:[
            "
             grow is expensive - return a copy.
             (is this what users of writeStream expect ?
            "
            collection := collection copyFrom:1 to:lastIndex
        ] ifFalse:[
            collection grow:lastIndex
        ]
    ].
    ^ collection

    "Modified: 19.2.1997 / 08:57:28 / stefan"
!

reset
    "reset the stream; write anew.
     See the comment in WriteStream>>contents"

    collection := collection species new:(collection size).
    super reset

    "Modified: 19.2.1997 / 08:57:00 / stefan"
! !

!WriteStream methodsFor:'positioning'!

position:index
    "redefined to allow positioning past the readLimit"

    ((index > (collection size + 1)) or:[index < 0]) ifTrue: [^ self positionError].
    position := index
! !

!WriteStream methodsFor:'private'!

growCollection
    "grow the streamed collection to at least 10 elements"

    self growCollection:10

    "Modified: 19.8.1997 / 17:53:28 / cg"
!

growCollection:minNewSize
    "grow the streamed collection to at least minNewSize"

    |oldSize newSize newColl|

    oldSize := collection size.
    (oldSize == 0) ifTrue:[
        newSize := minNewSize
    ] ifFalse:[
        newSize := oldSize * 2.
        (newSize < minNewSize) ifTrue:[newSize := minNewSize].
    ].
    collection isFixedSize ifTrue:[
        newColl := collection species new:newSize.
        newColl replaceFrom:1 to:oldSize with:collection startingAt:1.
        collection := newColl
    ] ifFalse:[
        collection grow:newSize
    ].

    "Modified: 19.8.1997 / 17:53:11 / cg"
! !

!WriteStream methodsFor:'private accessing'!

on:aCollection from:start to:last
    "create and return a new stream for writing onto aCollection, where
     writing is limited to the elements in the range start to last."

    super on:aCollection from:start to:last.
    writeLimit := last.
! !

!WriteStream methodsFor:'queries'!

isWritable
    "return true, if writing is supported by the recevier.
     Always return true here"

    ^ true

    "Modified: 16.5.1996 / 14:44:49 / cg"
! !

!WriteStream methodsFor:'reading'!

next
    "catch read access to write stream - report an error"

    self shouldNotImplement
!

peek
    "catch read access to write stream - report an error"

    self shouldNotImplement
! !

!WriteStream methodsFor:'writing'!

next:count put:anObject
    "append anObject count times to the receiver.
     Redefined to avoid count grows of the underlying collection -
     instead a single grow on the final size is performed."

    |final|

    (collection isNil or:[writeLimit notNil]) ifTrue:[
	^ super next:count put:anObject
    ].

    final := position + count - 1.
    (final > collection size) ifTrue:[
	self growCollection:final
    ].

    position to:final do:[:index |
	collection at:index put:anObject.
    ].
    position := position + count.
    (position > readLimit) ifTrue:[readLimit := position - 1].
    ^ anObject
!

nextPut:anObject
    "append the argument, anObject to the stream.
     Specially tuned for appending to String, ByteArray and Array streams."

%{  /* NOCONTEXT */

    REGISTER int pos;
    unsigned ch;
    OBJ coll;
    OBJ p, wL, rL;
    int __readLimit = -1;

    coll = __INST(collection);
    p = __INST(position);

#define NO_PRIM_STREAM
#ifndef NO_PRIM_STREAM
    if (__isNonNilObject(coll) && __isSmallInteger(p)) {
        pos = __intVal(p);
        wL = __INST(writeLimit);

        if ((wL == nil)
         || (__isSmallInteger(wL) && (pos <= __intVal(wL)))) {
            OBJ cls;

            cls = __qClass(coll);

            rL = __INST(readLimit);
            if (__isSmallInteger(rL)) {
                __readLimit = __intVal(rL);
            }

            if (cls == @global(String)) {
                if (__isCharacter(anObject) 
                 && ((ch = __intVal(__characterVal(anObject))) <= 255) /* ch is unsigned */
                 && (pos <= __stringSize(coll))) {
                    __StringInstPtr(coll)->s_element[pos-1] = ch;
                    __INST(position) = __MKSMALLINT(pos + 1);
                    if ((__readLimit >= 0) && (pos >= __readLimit)) {
                        __INST(readLimit) = __MKSMALLINT(pos);
                    }
                    RETURN ( anObject );
                }
            } else if (cls == @global(ByteArray)) {
                if (__isSmallInteger(anObject) 
                 && ((ch = __intVal(anObject)) <= 255) /* ch is unsigned */
                 && (pos <= __byteArraySize(coll))) {
                    __ByteArrayInstPtr(coll)->ba_element[pos-1] = ch;
                    __INST(position) = __MKSMALLINT(pos + 1);
                    if ((__readLimit >= 0) && (pos >= __readLimit)) {
                        __INST(readLimit) = __MKSMALLINT(pos);
                    }
                    RETURN ( anObject );
                }
            } else if (cls == @global(Array)) {
                if (pos <= __arraySize(coll)) {
                     __ArrayInstPtr(coll)->a_element[pos-1] = anObject;
                    __STORE(coll, anObject);
                    __INST(position) = __MKSMALLINT(pos + 1);
                    if ((__readLimit >= 0) && (pos >= __readLimit)) {
                        __INST(readLimit) = __MKSMALLINT(pos);
                    }
                    RETURN ( anObject );
                }
            }
        }
    }
#endif
%}.
    (writeLimit isNil
    or:[position <= writeLimit]) ifTrue:[
        (position > collection size) ifTrue:[self growCollection].
        collection at:position put:anObject.
        (position > readLimit) ifTrue:[readLimit := position].
        position := position + 1.
    ] ifFalse:[
        WriteErrorSignal raiseErrorString:'write beyond writeLimit'
    ].
    ^anObject
!

nextPutAll:aCollection
    "append all elements of the argument, aCollection to the stream.
     Redefined to avoid count grows of the underlying collection -
     instead a single grow on the final size is performed."

    |nMore final|

    collection isNil ifTrue:[
	^ super nextPutAll:aCollection
    ].

    nMore := aCollection size.
    final := position + nMore - 1.
    (writeLimit notNil
    and:[final > writeLimit]) ifTrue:[
	final := writeLimit.
	nMore := final - position + 1
    ].
    (final > collection size) ifTrue:[
	self growCollection:final
    ].
    collection replaceFrom:position
			to:final
		      with:aCollection 
		startingAt:1.

    position := position + nMore.
    (position > readLimit) ifTrue:[readLimit := position - 1].
    ^ aCollection
!

nextPutAll:aCollection startingAt:pos1 to:pos2
    "append some elements of the argument, aCollection to the stream.
     Redefined to avoid count grows of the underlying collection -
     instead a single grow on the final size is performed."

    |nMore final|

    collection isNil ifTrue:[
        ^ super nextPutAll:aCollection startingAt:pos1 to:pos2
    ].

    nMore := pos2 - pos1 + 1.
    final := position + nMore - 1.
    (writeLimit notNil
    and:[final > writeLimit]) ifTrue:[
        final := writeLimit.
        nMore := final - position + 1
    ].
    (final > collection size) ifTrue:[
        self growCollection:final
    ].

    collection replaceFrom:position
                        to:final
                      with:aCollection 
                startingAt:pos1.

    position := position + nMore.
    (position > readLimit) ifTrue:[readLimit := position - 1].
    ^ aCollection

    "
     |s|

     s := '' writeStream.
     s nextPutAll:'hello '.
     s nextPutAll:'1234world012345' startingAt:5 to:9.
     s contents
    "

    "Modified: 12.7.1996 / 10:31:36 / cg"
! !

!WriteStream class methodsFor:'documentation'!

version
    ^ '$Header: /cvs/stx/stx/libbasic/WriteStream.st,v 1.37 1997-09-02 20:56:14 cg Exp $'
! !