Checking if a structs .init value is zero bits only
Ali Çehreli
acehreli at yahoo.com
Wed Mar 28 00:50:31 UTC 2018
On 03/27/2018 05:15 PM, Per Nordlöw wrote:
> Is there a way to check if a struct `S` can be initialized using zero
> bits only, so that we can allocate and initialize an array of `S` in one
> go using `calloc`? If not, what should such a trait look like?
The following idea should work. One question that I'm not certain about
is whether padding bytes inside .init can ever be non-zero in D. I
assumed they are always zero. If not, the same idea must be applied
recursively to individual members.
bool allZeros(T)() {
// Yes, this can be implemented as a range algorithm. :)
T t;
foreach (b; (cast(ubyte*)&t)[0..T.sizeof]) {
if (b) {
return false;
}
}
return true;
}
unittest {
static struct A {
int i;
long l;
}
static struct B {
double d;
}
assert(allZeros!A);
assert(!allZeros!B);
}
void main() {
}
Ali
More information about the Digitalmars-d-learn
mailing list