Getting byte size of POD classes and dynamic arrays

Byron Heads byron.heads at gmail.com
Thu May 16 06:09:04 PDT 2013


I am working on d-leveldb wrapper (https://github.com/bheads/d-leveldb) 
and I need to be able to pass blocks of data between D and leveldb API.
I am having rouble getting the byte size of dynamic arrays and POD 
classes.

I can get the right size for 1D dynamic arrays, need a way to compute the 
total size.

POD Classes always give me the size of the ref, is it possible?

-Byron

You can see in my example code:
----------------------------
module sizeof;

import std.stdio,
        std.traits;

align(1)
struct SBlock
{
    ubyte b[13];
}

align(1)
class CBlock
{
    ubyte b[13];
}

size_t size(P)(in P p)
{
	// Working so far
    static if(isStaticArray!P || isBasicType!P || isPODStruct!P) 
		return P.sizeof;
	// works if *p is not another pointer, 
    else static if(isPointer!P) 
		return typeof(*p).sizeof;
	// works on 1D arrays
    else static if(isDynamicArray!P) 
		return (p.length ? typeof(p[0]).sizeof * p.length : 0 );
	// does not work, only gets size of the class ref
    else static if(__traits(isPOD, P) && is(P == class)) 
		return typeid(P).tsize;
    else assert(0);
}

template isPODStruct(T)
{
    static if(is(T == struct))
        enum isPODStruct = __traits(isPOD, T);
    else
        enum isPODStruct = false;
}

@property
void Size(alias V)()
{
    writeln(V, ": ", size(V));
}


void main()
{
    Size!55;
    Size!"Hello World";

    Size!(SBlock());

    auto c = new CBlock();
    Size!c;

    real x = 3.14;
    writeln(x, ": ", size(&x));
    auto _x = &x;
    Size!_x;
    writeln(x, ": ", size(&_x));

    ubyte[5][5] a;
    Size!a;

    ubyte[2][2][3] b;
    Size!b;

    ubyte[][] d;
    d ~= [1, 2, 3, 4, 5];
    d ~= [6, 7, 8];
    Size!d;

    SBlock[] e;
    e ~= SBlock();
    e ~= SBlock();
    Size!e;

    SBlock[][] f;
    f ~= [SBlock()];
    f ~= [SBlock()];
    Size!f;
}
s
-------------------------
5: 4
Hello World: 11
SBlock([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]): 13
sizeof.CBlock: 8
3.14: 16
7FFF51B64820: 16
3.14: 8
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 
0, 0, 0, 0]]: 25
[[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]]: 12
[[1, 2, 3, 4, 5], [6, 7, 8]]: 32
[SBlock([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), SBlock([0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0])]: 26
[[SBlock([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])], [SBlock([0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0])]]: 32






More information about the Digitalmars-d-learn mailing list