Recent

Author Topic: How to clear a TMemoryStream..  (Read 809 times)

cdbc

  • Hero Member
  • *****
  • Posts: 1025
    • http://www.cdbc.dk
How to clear a TMemoryStream..
« on: June 30, 2020, 08:25:14 pm »
Hi
How does one go about, clearing a memorystream, without 'Free'ing' it?!?
I need some input on this one  :)
Regards Benny
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE5 -> FPC 3.2.2 -> Lazarus 2.2.6 up until Jan 2024 from then on it's: KDE5/QT5 -> FPC 3.3.1 -> Lazarus 3.0

Remy Lebeau

  • Hero Member
  • *****
  • Posts: 1312
    • Lebeau Software
Re: How to clear a TMemoryStream..
« Reply #1 on: June 30, 2020, 08:37:34 pm »
How does one go about, clearing a memorystream, without 'Free'ing' it?!?

TMemoryStream has a Clear() method:

Quote
Clear sets the position and size to 0, and sets the capacity of the stream to 0, thus freeing all memory allocated for the stream.

Unfortunately, you cannot clear the stream's internal buffer while leaving its Capacity as-is.  Setting the Size property to 0 also sets the Capacity property to 0, freeing the buffer.  One would think that shrinking the Size would leave the Capacity at its current value, but that is not actually the case.  Setting a new Size sets a new Capacity as well, so the Capacity will always be at least the Size (it may be higher, due to the algorithm used to grow the buffer in incremental steps, but that does not apply when setting the new Size/Capacity to 0).

If you don't want to free the buffer, then don't use the Size property.  Reset the Position property to 0, write as needed, and use the Position rather than the Size to know how many bytes are in the stream.
« Last Edit: June 30, 2020, 08:52:45 pm by Remy Lebeau »
Remy Lebeau
Lebeau Software - Owner, Developer
Internet Direct (Indy) - Admin, Developer (Support forum)

 

TinyPortal © 2005-2018