BinaryInsert()?

Started by JTaylor, April 07, 2019, 05:15:51 PM

Previous topic - Next topic

JTaylor

Am I missing something or is there no way to Insert a string into a Binary Buffer.   BinaryPokeStr() seems to overwrite rather than Insert.  Thanks.

Jim

kdmoyers

In the past I've used BinaryPoke to put in an unlikely byte, and then BinaryReplace to replace it with the full length string I wanted.  A little roundabout, but effective in some cases.
-K
The mind is everything; What you think, you become.

JTaylor

Thanks.  Hopefully they will consider adding such a function.   Seems odd there isn't one???

Jim

td

Very lightly tested so contains bugs.
Code (winbatch) Select
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; BinaryInsertStr
;;
;; Inserts text into a binary buffer.
;;   _phBin - In - ptr to target binary buffer.
;;            Out - ptr to new buffer with inserted string.
;;   _hStr  - string to insert in binary buffer.
;;   _nOff  - insertion point of string in buffer.
;;
;; Returns new buffer size
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#DefineFunction BinaryInsertStr(_phBin, _Str, _nOff)
   hSrc = *_phBin
   nStrLen = StrLen(_str)
   nBinLen = BinaryBufInfo(hSrc, 0)
   hTmp = BinaryAlloc(nStrLen+nBinLen)
   if _nOff < nBinLen then nCnt = _nOff + 1
   else nCnt = nBinLen
   BinaryCopy(hTmp, 0, hSrc, 0, nCnt)
   BinaryPokeStr(hTmp, _nOff, _str)
   if nBinLen > _nOff then  BinaryCopy(hTmp, _nOff+nStrLen, hSrc, _nOff, nBinLen-_nOff)
   BinaryFree(hSrc)
   *_phBin = hTmp
   return BinaryBufInfo(hTmp, 0)
#EndFunction


;; Test
str = 'This is the best of all possible worlds.'
hTest = BinaryAlloc(Strlen(str))
BinaryPokeStr(hTest, 0, str)

BinaryInsertStr(&hTest, 'might not be ', 8)

str2 = BinaryPeekStr(hTest, 0 , BinaryBufInfo(hTest, 0))
Pause('BinaryInsertStr Test', str:@lf:str2)
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

JTaylor

Thanks.   This should help until the next release when you add it as a function  ;)

Jim

kdmoyers

Quote from: td on April 09, 2019, 11:12:18 AM
Code (winbatch) Select
#DefineFunction BinaryInsertStr(_phBin, _Str, _nOff)

This is super interesting, the way you swap the buffers around.  I'm going to study it carefully.
-Kirby
The mind is everything; What you think, you become.

td

Let me know when you find a bug.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade