Stringbuilder
Posted: Fri Jan 24, 2014 5:39 pm
Hi,
I'm trying to write my own stringbuilder routine but it won't work as it should. The resulting string differs from the input (I guess while copying it with CopyMemory to the string buffer). Still, I can't figure out why...
Here's the code:
Any idea, where the problem hides??
Greetz,
Fenix
I'm trying to write my own stringbuilder routine but it won't work as it should. The resulting string differs from the input (I guess while copying it with CopyMemory to the string buffer). Still, I can't figure out why...
Here's the code:
Code: Select all
Structure _structStringManagement
iBlockSize.i ; minimum bytes we allocate if we need more space to add a string to the buffer
iBufferSize.i ; total memory size we've allocated
iPositionInBuffer.i ; actual position in the buffer
iBufferAddress.i ; address of the buffer (aka allocated memory)
iInitDone.i ; true if the string builder has been initilized (memory was reserved)
EndStructure
Procedure _sbInit(iBlocksize.i)
Global _StringBuffer._structStringManagement
With _StringBuffer
\iBlockSize = 1024
\iBufferAddress = AllocateMemory(iBlocksize)
If \iBufferAddress
\iInitDone = #True
EndIf
EndWith
EndProcedure
Procedure.i _sbAddString(sString.s)
; --- adds a new string to the buffer
Protected iStringAddress.i
Protected iStringLength.i
Protected iNewStringSize.i
Protected iNewStringBufferAddress.i
iStringAddress = @sString
iStringLength = MemoryStringLength(iStringAddress, #PB_Unicode)
With _StringBuffer
iNewStringSize = iStringLength + \iPositionInBuffer
If iNewStringSize + 1 > \iBlockSize
iNewStringBufferAddress = AllocateMemory(\iBufferSize + \iBlockSize)
If iNewStringSize
CopyMemory(\iBufferAddress, iNewStringBufferAddress, \iPositionInBuffer)
FreeMemory(\iBufferAddress)
\iBufferAddress = iNewStringBufferAddress
\iBufferSize = \iBufferSize + \iBlockSize
Else
ProcedureReturn #False
EndIf
EndIf
CopyMemory(iStringAddress, \iBufferAddress + \iPositionInBuffer, iStringLength * 2)
\iPositionInBuffer + iStringLength
Debug "string length = " + iStringLength
Debug "string4buffer = " + PeekS(iStringAddress)
Debug "buffer (ascii) = " + PeekS(\iBufferAddress, -1, #PB_Ascii)
Debug "buffer (uni) = " + PeekS(\iBufferAddress, -1, #PB_Unicode)
Debug "buffer (utf-8) = " + PeekS(\iBufferAddress, -1, #PB_UTF8)
Debug "buffer (def) = " + PeekS(\iBufferAddress)
Debug "bufferpos = " + \iPositionInBuffer
Debug ""
EndWith
EndProcedure
_sbInit(4096)
For iCounter = 1 To 100
_sbAddString(Str(iCounter))
_sbAddString(" , ")
_sbAddString(" 123 #'+~")
Next
Debug _sbGetString()
Greetz,
Fenix