Search code examples
zig

Converting a slice to an array


I have a slice that I have guaranteed (in runtime) that its length is at least 8. I want to convert that slice to an array because I need to use std.mem.bytesAsValue() in order to create an f64 from raw bytes (for context, I'm implementing a binary serialization format).

I solved it like this, but I'd like to know if there is a better syntax for achieving the same goal:

    var array: [8]u8 = undefined;
    array[0] = slice[0];
    array[1] = slice[1];
    array[2] = slice[2];
    array[3] = slice[3];
    array[4] = slice[4];
    array[5] = slice[5];
    array[6] = slice[6];
    array[7] = slice[7];

Solution

  • Given your goal, if alignment works out, you could just cast the slice pointer to a pointer to a f64: @ptrCast(*f64, slice.ptr). This saves you from even having to copy anything, in case you don't need to do that at all.

    Note that bytesAsValues is a stdlib function that uses compiler builtins, if the signature doesn't match your needs, you can just skip it and use directly the builtins, like I mentioned above. Don't be afraid to read the stdlib source code.

    Here's a godbolt link with some examples on how to do the conversion in-place (by casting the pointer) and by copying everything immediately as a float: https://zig.godbolt.org/z/3Y9o5zvfe