Bitfield accessors
bearophile
bearophileHUGS at lycos.com
Tue Nov 20 03:10:19 PST 2007
Thank you very much Jarrett Billingsley, that's even better. I'll use a modified version of it in my code (with your name attached). Lately I tend to use compile-time functions more than templates, because I think they are a bit more readable. I have added another test, on the sum of the lens to see if they are equal to data.sizeof*8, because I like to avoid bugs all the times it's possible:
template Bitfield(alias data, Args...) {
static assert(!(Args.length & 1), "Bitfield arguments must be an even number");
static assert(data.sizeof*8 == _SumLens!(Args),
"The sum of bit fields is different from data.sizeof*8");
const char[] Bitfield = _BitfieldShim!((typeof(data)).stringof, data, Args).Ret;
}
private template _SumLens(Args...) {
static if(Args.length == 0)
const uint _SumLens = 0;
else
const uint _SumLens = Args[1] + _SumLens!(Args[2 .. $]);
}
I have also added a newline at the end of Getter and Setter, so the methods become listed in separated lines and you can see them better if you print the whole string result:
const char[] Getter = "public " ~ typeStr ~ " " ~ Name ~ "() { return ( " ~
nameStr ~ " >> " ~ Itoh!(offset) ~ " ) & " ~ Itoh!(Mask) ~ "; }\n";
const char[] Setter = "public void " ~ Name ~ "(" ~ typeStr ~ " val) { " ~
nameStr ~ " = (" ~ nameStr ~ " & " ~ Itoh!(~(Mask << offset)) ~
") | ((val & " ~ Itoh!(Mask) ~ ") << " ~ Itoh!(offset) ~ "); }\n";
Currently I am writing the module tests for Bitfield(), to see if it works when data is a ubyte/ushort/ulong too.
I don't know if I'll need to make it optimize some the produced code, probably the compiler is enough to optimize it in most cases.
I'd also like to do some speed comparison with the bitfields management of GCC.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list