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:22:52 PDT 2016
Am 04.07.2016 um 20:33 schrieb Ali Çehreli:
> On 07/04/2016 07:31 AM, 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 */
>> }
>
> Here's an option that overlays a struct on top of the bytes:
>
> struct Buf {
> union {
> struct {
> ubyte[4] sigma0 = [101, 120, 112, 97];
> ubyte[16] keyBeg;
> ubyte[4] sigma1 = [110, 100, 32, 51];
> ubyte[16] n;
> ubyte[4] sigma2 = [ 50, 45, 98, 121];
> ubyte[16] keyEnd;
> ubyte[4] sigma3 = [116, 101, 32, 107];
> }
>
> ubyte[64] bytes;
> }
>
> this(const ubyte[] key, const ubyte[] n) {
> this.keyBeg = key[0..16];
> this.keyEnd = key[16..$];
> this.n = n;
> }
> }
>
> static assert(Buf.sizeof == 64);
>
> void func(in ubyte[] key, in ubyte[] n) {
> auto buf = Buf(key, n);
> writeln(buf.bytes);
> }
>
> import std.stdio;
> import std.range;
> import std.array;
>
> void main() {
> func(ubyte(32).iota.array,
> ubyte(16).iota.array);
> }
>
> Prints:
>
> [101, 120, 112, 97, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
> 15, 110, 100, 32, 51, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
> 15, 50, 45, 98, 121, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
> 29, 30, 31, 116, 101, 32, 107]
>
> Ali
>
This looks really nice, but I have several occurences of this, with
different arrays (and lengths), so i would need to create several of
those structs. But it looks really clean :)
More information about the Digitalmars-d-learn
mailing list