Initializing static array with contents of (static and dynamic) arrays

Johannes Loher via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 4 12:24:17 PDT 2016


Am 04.07.2016 um 19:24 schrieb ZombineDev:
> On Monday, 4 July 2016 at 14:31:41 UTC, Johannes Loher wrote:
>> In a project I am currently working on, I have lot's of code of the
>> following form:
>>
>> static immutable ubyte[4] sigma0 = [101, 120, 112,  97]; static
>> immutable ubyte[4] sigma1 = [110, 100,  32,  51]; static immutable
>> ubyte[4] sigma2 = [ 50,  45,  98, 121]; static immutable ubyte[4]
>> sigma3 = [116, 101,  32, 107];
>>
>> void func(in ubyte[32] key, in ubyte[16] n)
>> {
>>     ubyte[64] buf;
>>     buf[0..4] = sigma0;
>>     buf[4..20] = key[0..16];
>>     buf[20..24] = sigma1;
>>     buf[24..40] = n;
>>     buf[40..44] = sigma2;
>>     buf[44..60] = key[16..$];
>>     buf[60..64] = sigma3;
>>
>>    /* do something with buf */
>> }
>>
>> This looks really bad to me. I would like to initialize buf with the
>> corresponding values (the way it's done now, it is impossible to make
>> buf immutable...).
>>
>> One option for this would be to use ~ to concatenate the arrays. But
>> this obviously results in GC allocations, which I want to avoid here,
>> because the functions get called very often.
>>
>> Another option would be to to manually expand the arrays and
>> initialize buf with that:
>>
>> ubyte[64] buf = [sigma0[0], sigma0[1], /* ... */, sigma3[3]];
>>
>> This is obviously very annoying and error prone.
>>
>> Whe searching for a solution, I found this thread about automatic
>> expanding of arrays:
>>
>> http://forum.dlang.org/thread/hwellpcaomwbpnpofzlx@forum.dlang.org?page=1
>>
>> This would result in the following code for me:
>>
>> ubyte[64] buf = [
>>     expand!sigma0,
>>     expand!key[0..16],
>>     expand!sigma1,
>>     expand!n,
>>     expand!sigma2,
>>     expand!key[16..$],
>>     expand!sigma3
>> ];
>>
>> Is this the suggested solution (is it robust)? Is there anything like
>> this in Phobos?
>>
>> Thanks for your help!
> 
> You should be able to use
> http://dlang.org/phobos-prerelease/std_meta#aliasSeqOf for this.
> 
> I think it should work with the same syntax as expand, but with added
> bonus that it also handles ranges like those in std.range and
> std.algorithm.
I just tried that, but it does not work for arrays, which can not be
read at compile time.


More information about the Digitalmars-d-learn mailing list