Skip to content

Instantly share code, notes, and snippets.

@pineapplemachine
Created April 15, 2016 20:48
Show Gist options
  • Select an option

  • Save pineapplemachine/2224d68df5396235c8bd959b044c220c to your computer and use it in GitHub Desktop.

Select an option

Save pineapplemachine/2224d68df5396235c8bd959b044c220c to your computer and use it in GitHub Desktop.
Assert using string formatting
/++
Written by Sophie Kirschner: sophiek@pineapplemachine.com
zlib/libpng license: https://opensource.org/licenses/Zlib
+/
module mach.error.assertf;
private:
import core.exception : AssertError;
import std.format : format;
public:
/// Throws an AssertError when the condition is not met.
void assertf(
size_t line = __LINE__, string file = __FILE__, Args...
)(
lazy bool condition, in string message, Args args
){
assert({
// Putting the function body in an assert statement means it only
// evaluates when assertions are normally evaluated, i.e. not in
// release mode.
if(!condition()) throw new AssertError(format(message, args), file, line, null);
return true;
}());
}
unittest{
void fail(in void function() test){
bool caught = false;
try{
test();
}catch(AssertError error){
caught = true;
}
assert(caught);
}
assertf(true, "hello %s", "world");
assertf((2 * 5) == (10 * 1), "hello %s", "world");
fail({assertf(false, "hello %s", "world");});
fail({assertf((2 * 5) != (10 * 1), "hello %s", "world");});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment