[fpc-pascal] Delete and Add for TBytes?

Michael Van Canneyt michael at freepascal.org
Wed Jul 12 16:26:31 CEST 2017



On Wed, 12 Jul 2017, Bo Berglund wrote:

> I would like to replace a buffer handling scheme in an old application
> (written in Delphi) where the buffer was originally of type string and
> later when unicode appeared changed to AnsiString.
>
> But AnsiString also causes potential headaches so I would like to get
> rid of it altogether by using a TBytes container instead.
> The problem is that the code utilizes heavily a few string oriented
> functions like:
>
> To remove Count processed bytes from the beginning:
>
> Buffer: AnsiString;
>
> Delete(Buffer, 1, Count)
> or worse:
> Buffer := Copy(Buffer, Count+1, Length(Buffer));
>
> For adding new data (c: AnsiChar) to the end:
>
> Buffer := Buffer + c;
>
> I would like to instead use TBytes as container but then I would not
> like to rewrite all of the code so I would like to be able to do
> something like:
>
> Buf: TBytes;
> b: byte;
>
> Delete(Buf, Index, Count);  //Removes Count bytes at Index 
>
> BufAdd(Buf, b); //Extends size of Buf and puts b last
>
> Is it possible to overload Delete() so it can be called with TBytes as
> argument?

It is.


> For adding data the + operator would have been fine but I have no idea
> how one could do that...

Just define an operator.  Plenty of examples.

uses sysutils;

operator + (a : TBytes; B : Char) c : TBytes;

begin
   SetLength(C,Length(A)+1);
   Move(A[0],C[0],Length(A));
   C[Length(A)]:=Ord(B);
end;

Procedure Dump(a : TBytes);

Var
   B : byte;

begin
   For B in A do
     Write(char(B));
   Writeln;
end;

Var
   A : TBytes;

begin
   A:=A+'c';
   Dump(A);
end.

outputs 'c' for me.



Michael.



More information about the fpc-pascal mailing list