I guess that you all already worked with a TBytesStream. It is derived from a TMemoryStream and offers direct access to the underlying TBytes:

So far so good, the problem is that a TMemoryStream allocates more memory than the current Size. The reason is that not necessary to realloc memory for every write operation. You can see this in the Realloc method

As you can see the NewCapacity is larger than the Size of the Stream. If you look deeper at the code you can see that the NewCapacity is of power of 2.

But anyway, the point is that the property Bytes can include more bytes than the Size of the Stream. That’s why you must be very careful if you want to access directly to the Bytes property.

In order to avoid any issues I created a record helper for TBytes with the property BytesReal that includes the used bytes:

If you like than add the TBytesStreamHelper to your project and use the new property BytesReal.

This entry was posted in Delphi, RAD Studio 10.4 Sydney, Tips and Tricks, Uncategorized. Bookmark the permalink.