trick to make throwing method @nogc

ikod via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 25 11:59:29 PST 2017


Hello,

I have a method for range:

struct Range {
     immutable(ubyte[]) _buffer;
     size_t             _pos;

     @property void popFront() pure @safe {
         enforce(_pos < _buffer.length, "popFront from empty 
buffer");
         _pos++;
     }
}

I'd like to have @nogc here, but I can't because enforce() is 
non- at nogc.
I have a trick but not sure if it is valid, especially I don't 
know if optimization will preserve code, used for throwing:

import std.string;

struct Range {
     immutable(ubyte[]) _buffer;
     size_t  _pos;

     this(immutable(ubyte[]) s) {
         _buffer = s;
     }
     @property void popFront() pure @safe @nogc {
         if (_pos >= _buffer.length ) {
             auto _ = _buffer[$]; // throws RangeError
         }
         _pos++;
     }
}

void main() {
	auto r = Range("1".representation);
	r.popFront();
	r.popFront(); // throws
}

Is it ok to use it? Is there any better solution?

Thanks!



More information about the Digitalmars-d-learn mailing list