Re: Checking if a structs .init value is zero bits only
On Wednesday, 28 March 2018 at 01:39:40 UTC, Seb wrote: Have a look at: https://github.com/dlang/phobos/pull/6024 (review/feedbackon this PR is welcome!) Exactly what I wanted. Thanks! In use here https://github.com/nordlow/phobos-next/blob/41b9e0dcfbb4eed6b2ee52d0465425556f14c00f/src/open_hashmap_or_hashset.d#L242
Re: Checking if a structs .init value is zero bits only
On Wednesday, 28 March 2018 at 00:50:31 UTC, Ali Çehreli wrote: 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*))[0..T.sizeof]) { if (b) { return false; } } return true; } Yes, of course, thanks. But my goal is (always) to have it done at compile-time.
Re: Checking if a structs .init value is zero bits only
On Wednesday, 28 March 2018 at 00:15:34 UTC, 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? Have a look at: https://github.com/dlang/phobos/pull/6024 (review/feedbackon this PR is welcome!)
Re: Checking if a structs .init value is zero bits only
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*))[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
Checking if a structs .init value is zero bits only
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?