Adam D. Ruppe:
> Trivial. I'll start with the code you posted on the bugzilla.
It's better to minimize the number of templates created by the code. I have
used CTFE here (not much tested):
import std.metastrings: toStringNow;
ulong octal_helper(string value) {
assert(value.length > 0);
ulong result;
foreach (digit; value) {
assert(digit >= '0' && digit < '8',
"Incorrect character in octal constant: '" ~ value[0] ~ "'");
result = result * 8 + (digit - '0');
}
return result;
}
template octal(string s) {
enum uint octal = octal_helper(s);
}
template octal(ulong s) {
enum uint octal = octal_helper(toStringNow!(s));
}
void main() {
//unittest {
static assert(octal!"45" == 37);
static assert(octal!"0" == 0);
static assert(octal!"7" == 7);
static assert(octal!"10" == 8);
static assert(octal!45 == 37);
static assert(octal!0 == 0);
static assert(octal!7 == 7);
static assert(octal!10 == 8);
//static assert(octal!(-2) == 8);
}
It needs many more unittests, to tests all the bounds, corner cases, etc. They
also have to test that the code actually asserts when the inputs are wrong in
various ways. This is how I test my D code.
Bye,
bearophile