bitfields VS pure nothrow

Guillaume Chatelet chatelet.guillaume at gmail.com
Sun May 13 12:51:35 PDT 2012


Sure enough bitfields is a strange beast and I ran into some subtleties
with purity and nothrow.

Consider the following code :
------------------------------
struct POD {
   int a;
}

int getA(POD o) pure nothrow {
   return o.a;
}

POD setA(POD o, int value) pure nothrow {
   o.a = value;
   return o;
}
------------------------------

It compiles fine. But now with a bitfield :
struct POD {
	mixin(std.bitmanip.bitfields!(
        int, "a",10,
        int, "", 22));
}

The compiler complains about missing pure and nothrow attributes
Error: pure function 'getA' cannot call impure function 'a'
Error: o.a is not nothrow
Error: function test.getA 'getA' is nothrow yet may throw
Error: pure function 'setA' cannot call impure function 'a'
Error: o.a is not nothrow
Error: function test.setA 'setA' is nothrow yet may throw

Which makes sense as the mixin outputs :
------------------------------
@property uint a() const {
   auto result = (_a_ & 1023U) >>0U;
   return cast(uint) result;
}
@property void a(uint v){
   assert(v >= a_min);
   assert(v <= a_max);
   _a_ = cast(typeof(_a_))
         ((_a_ & ~1023U) | ((cast(typeof(_a_)) v << 0U) & 1023U));
}
enum uint a_min = cast(uint)0U;
enum uint a_max = cast(uint)1023U;
private uint _a_;
------------------------------

IMHO getters and setters could be nothrow but what about purity ? Looks
like it's a bit far-fetched to qualify member methods as pure right ?
Yet it makes sense regarding the semantic. What's your take on that ?


More information about the Digitalmars-d mailing list