Heres something i made many moons ago.
Its not thoroughly tested, and it doesnt scale to very large sizes as it reallocates the new size and copies the date over.
BUt it should you an idea as to how to do it.
SuperStrict
'
' TEST
'
Rem
Framework BRL.Blitz
Import BRL.Stream
Import BRL.StandardIO
Local stream:TStream = New TMemoryStream
stream.WriteString( "Hello")
stream.WriteString( "World")
stream.WriteString( "~n")
stream.Seek(0)
Print stream.ReadLine()
Print stream.Size()
Local stream2:TStream = WriteStream( "c:/test.txt")
stream.Seek(0)
CopyStream stream, stream2
stream.Close()
stream2.Close()
EndRem
Type TMemoryStream Extends TStream
Const DEFAULT_SEGMENT_SIZE:Int = 512
Field Buffer:Byte Ptr
Field Offset:Int
Field CurrSize:Int
Field MaxSize:Int
Field ExtendBuffer:Int = True
Field SegmentSize:Int = DEFAULT_SEGMENT_SIZE
Function Create:TMemoryStream( segmentsize:Int = DEFAULT_SEGMENT_SIZE)
Local stream:TMemoryStream = New TMemoryStream
stream.SegmentSize = segmentsize
Return stream
EndFunction
Method New()
MaxSize = SegmentSize
Buffer = MemAlloc( MaxSize)
EndMethod
Method Delete()
Close()
EndMethod
Method Close()
If Buffer <> Null Then
MemFree( Buffer)
Buffer = Null
Offset = 0
MaxSize = 0
CurrSize = 0
EndIf
EndMethod
Method Eof:Int()
Return (Buffer = Null) Or (Offset >= CurrSize)
EndMethod
Method Pos:Int()
Return Offset
EndMethod
Method Size:Int()
Return CurrSize
EndMethod
Method Seek:Int( pos:Int)
If pos < CurrSize Then Offset = pos
Return Offset
EndMethod
Method Read:Int( buf:Byte Ptr, count:Int)
Local index:Int = 0
While (count > 0) And (Offset < CurrSize)
buf[index] = Buffer[Offset]
count :- 1
Offset :+ 1
index :+ 1
Wend
Return index
EndMethod
Method Write:Int( buf:Byte Ptr, count:Int)
' extend memory if reached eof
Local sz:Int = Offset + count
If sz >= MaxSize Then
If Not ExtendBuffer Then RuntimeError "reached end of stream"
Local newsize:Int = MaxSize
Repeat
newsize :+ SegmentSize
Until sz < newsize
Buffer = MemExtend( Buffer, MaxSize, newsize)
MaxSize = newsize
EndIf
' write data
Local index:Int = 0
While (count > 0) And (Offset < MaxSize)
Buffer[Offset] = buf[index]
count :- 1
Offset :+ 1
index :+ 1
Wend
CurrSize = Offset
Return index
EndMethod
EndType