2

Is it possible to cast Foo to ubyte[size] at compile time?

Here is a bit more context:

struct Algebraic(Types...)
if(Types.length < char.max - 1){
    import std.traits: Largest;
    import std.meta: IndexOf;
    static immutable maxSize = Largest!(Types).sizeof;

    this(T)(in T t)
    if(IndexOf!(T, Types) !is -1){
        type = IndexOf!(T, Types);
        data = *cast(ubyte[maxSize]*)&t;
    }

    void opAssign(T)(in T t)
    if(IndexOf!(T, Types) !is -1){
        type = IndexOf!(T, Types);
        data = *cast(ubyte[maxSize]*)&t;
    }

    inout(T*) peek(T)() inout{
        if(type is IndexOf!(T, Types)){
            return cast(inout(T*))&data;
        }
        return null;
    }
private:
    ubyte[maxSize] data;
    char type = char.max;
}

struct Branch{
    int index;
    int left;
    int right;
}
struct Leaf{
    int index;
}
struct Foo{
    alias Node = Algebraic!(Branch, Leaf);
    Node n = Branch(1,2,3); 
    //Error: cannot convert &const(Branch) to ubyte[12]* at compile time
}

The problem is that I can not cast Branch to ubyte[maxSize] at compile time.

1 Answer 1

4

I am not aware of any "clean" approach (one that would make use of compiler knowledge of ABI) because CTFE is very conservative in preventing reinterpretation. However, if this is a blocker, it is possible to build up byte array manually making use of the fact struct ABI is very simple:

import std.traits;

ubyte[T.sizeof] reinterpret (T) ( T x )
    if (!hasIndirections!T)
{
    typeof(return) result;

    static if (is(T == struct))
    {
        size_t offset = 0;
        foreach (ref field; x.tupleof)
        {
            result[offset .. offset + field.sizeof] = reinterpret(field);
            offset += field.sizeof;
        }
    }
    else static if (is(T : ulong))
    {
        for (auto i = 0; i < x.sizeof; ++i)
            result[i] = cast(ubyte) (x >> 8*i);
    }
    else
    {
        // handle floating types, arrays etc.
    }

    return result;
}

struct S
{
    int x, y;
}

static immutable bytes = reinterpret(S(42, 42));

pragma(msg, bytes);

There is one huge limitation with this approach: you are required to adjust to proper ABI manually. Stuff like endianess is trivial, but handling field alignment properly is likely to be a pain (I am not even trying to do so in this snippet).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.