Assigning a static array

bearophile bearophileHUGS at lycos.com
Thu Apr 18 14:45:55 PDT 2013


Brad Anderson:

> Is this supposed to be allowed:
>
> ubyte[] a;
> ubyte[16] b;
> a = b;
> assert(a.ptr == b.ptr);

Yes, this is supposed to be allowed with the current design of D. 
But with the latest dmd 2.063alpha that code doesn't work, see 
below.

The Rust language removes this source of bugs because it manages 
accurately the memory zones. D will probably improve its error 
detection capabilities for such simple cases, but I think it will 
not solve this problem in general, unless it improves its type 
system, similarly to Rust.


> import std.digest.md;
> import std.stdio;
>
> struct Hash {
>   ubyte[] hash1;
>   ubyte[] hash2;
>
>   this (string str) {
>     auto md5 = new MD5Digest();
>     this.hash1 = md5.digest(str);
>     this.hash2 = digest!MD5(str);
>   }
> };
>
> void main() {
>   auto h = Hash("hello world!");
>   writeln(toHexString(h.hash1));
>   writeln(toHexString(h.hash2));
> }
>
>
> It's not obvious at all what the problem is.

Now that code gives a warning:

temp.d(11): Warning: explicit slice assignment this.hash2 = 
(digest(str))[] is better than this.hash2 = digest(str)

(This is the result of a small battle I have started years ago 
that is now half work, thanks to the work of Hara implementing my 
enhancement request. I am glad to see our time was not wasted.)

To remove that warning you have to write:

this.hash1 = md5.digest(str);
this.hash2 = digest!MD5(str)[];

Now it's visible that for hash2 you are slicing something that's 
probably a fixed-sized array. This gives you a significant help 
in understanding what's going on.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list