Skip to content

Instantly share code, notes, and snippets.

@aldanor
Created December 12, 2014 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aldanor/a724d06149e482cf8c49 to your computer and use it in GitHub Desktop.
Save aldanor/a724d06149e482cf8c49 to your computer and use it in GitHub Desktop.
Template for return value based error checking
import std.traits;
import std.exception;
bool maybeError(T)(T v) {
static if (is(T == function) || is (T : void *))
return v is null;
else static if (isIntegral!T)
static if (isSigned!T)
return v < 0;
else
return v == 0;
else
return false;
}
unittest {
assert(maybeError(-1));
assert(!maybeError(0));
assert(!maybeError(1));
assert(maybeError(0u));
assert(!maybeError(1u));
assert(!maybeError(cast(uint) -1));
assert(maybeError(null));
char c = 'c';
assert(!maybeError(&c));
assert(maybeError(cast(char *) null));
}
auto errorCheck(alias func)(ParameterTypeTuple!(func) args) {
static if (is(ReturnType!(func) == void))
func(args);
else {
auto result = func(args);
if (maybeError(result))
throw new Exception("not valid");
return result;
}
}
unittest {
void void_func() {};
assertNotThrown!Exception(errorCheck!void_func());
auto int_func = (int x) => x;
assertNotThrown!Exception(errorCheck!int_func(1));
assertNotThrown!Exception(errorCheck!int_func(0));
assertThrown!Exception(errorCheck!int_func(-1));
assert(errorCheck!int_func(1) == 1);
auto uint_func = (uint x) => x;
assertNotThrown!Exception(errorCheck!uint_func(1));
assertThrown!Exception(errorCheck!uint_func(0));
assertNotThrown!Exception(errorCheck!uint_func(-1));
assert(errorCheck!uint_func(1) == 1);
static int y = 1;
auto ptr_func = (bool x) => x ? &y : null;
assertNotThrown!Exception(errorCheck!ptr_func(true));
assertThrown!Exception(errorCheck!ptr_func(false));
assert(*errorCheck!ptr_func(true) == 1);
auto other_func = () => "foo";
assertNotThrown!Exception(errorCheck!other_func());
assert(errorCheck!other_func() == "foo");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment