[fpc-pascal] Best way to insert bytes into a TBytes variable?

Michael Van Canneyt michael at freepascal.org
Tue Jul 25 11:15:31 CEST 2017

On Tue, 25 Jul 2017, Bo Berglund wrote:

> I am working on moving away from using AnsiString as communications
> buffer in an old application, so I need to write efficient
> replacements for certain string functions (Delete, Insert, Copy etc).
> Now I am wondering if there is a better way to do the Insert() command
> than this:
> procedure InsertBytes(var Dest: TBytes; Src: TBytes; Index: integer);
> var
>  Len, LenA: integer;
> begin
>  Len := Length(Dest);
>  LenA := Length(Src);
>  if LenA = 0 then exit; //Do nothing
>  if Index > Len then Index := Len;  //Make an append instead
>  SetLength(Dest, Len + LenA);
>  Move(Dest[Index], Dest[Index + LenA], LenA);  //Create space
>  Move(Src[0], Dest[Index], LenA);  //Insert data
> end;
> Ideally the function should be portable between FPC and Delphi XE5...

There is no better way if you only want to use TBytes. 
If you want less reallocations, you must reserve more memory for the array 
from the start (so length is a "capacity"), and keep a second count, the 
count of the number of bytes  actually used.

Then you're maybe better off working with a TMemory stream, which does all this
for you. Or write a TBuffer class.


More information about the fpc-pascal mailing list