Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a TArray to a array of T

How do I assign a TArray<Byte> to array of Byte and vice versa?

TEncoding.UTF8.GetBytes returns a TArray<Byte>. TIdHashMessageDigest5.HashBytes has a TIdBytes = array of Byte as parameter.

Can I assign these types to each other? Maybe with a copy? Or do I need to loop?

like image 409
r_j Avatar asked Jan 04 '17 12:01

r_j


1 Answers

These types are not assignment compatible. In an ideal world you would use TArray<T> exclusively, and it would be better if all libraries did so. I do not understand why Indy insists on using its own distinct type here.

If you cannot then you can make a copy. That's easy enough with a loop. If efficiency matters that you could copy using Move.

SetLength(Dest, Length(Source));
Move(Pointer(Source)^, Pointer(Dest)^, Length(Source));

I use Pointer(arr)^ here rather than arr[0] to avoid tripping range check exceptions in case of an empty array.

It is also possible to avoid a copy by using a typecast, since all dynamic arrays are implemented the same way. So you could write

Hash := HashBytes(TIdBytes(TEncoding.UTF8.GetBytes(...)));

Of course, this gives up type safety, but then so does the call to Move above.

Yet another approach, suggested by Remy's answer to another question, is to use TIdTextEncoding rather than TEncoding. That way you can work with TIdBytes exclusively.

like image 67
David Heffernan Avatar answered Sep 28 '22 06:09

David Heffernan