Testing array ptr for offset 0...
Era Scarecrow via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 26 00:51:46 PDT 2016
So I'm experimenting and want to override how arrays are managed
for a short duration, this is for optimization of not having to
make another array to keep track of lengths and then shorten them
when i can in fact just manage it myself *very* briefly.
So, I need to make sure the structure is compatible with the
built-in array structure (since the remainder of the calls are
via normal convention and no allocation/resizing is done except
by progressively smaller slices, so it should be compatible as
long as it's a valid pointer).
But i seem to have an issue trying to test if ptr is at offset 0
or not. Having the wrong order would be catastrophic, and if the
source changes (for whatever reason) i don't want to have to fix
it.
So... the obvious test: static if ([].ptr.offsetof == 0)
If the ptr is at offset 0, we declare it first, otherwise
second, simple... Except this fails since "no property 'offsetof'
for type 'void*'". SO... I make a template to test for it instead.
template isArrayPtrOffsetZero() {
auto check() {
static assert([].sizeof == (size_t.sizeof*2));
size_t[] arr = new size_t[1]; //length == 1.
return *(cast(size_t*) &arr) != 1;
}
enum isArrayPtrOffsetZero = check();
}
struct X {
static if (isArrayPtrOffsetZero!()) {
int* ptr;
size_t length;
} else { ... }
}
Except this blows up and always gives the wrong answer... ==1
length test reverses it but is now the wrong test, and changing
it to isArrayLengthOffsetZero will in turn give the wrong answer
again...
Am i going about this the wrong way?
More information about the Digitalmars-d-learn
mailing list