Skip to content

Commit

Permalink
Add exception support to numem
Browse files Browse the repository at this point in the history
  • Loading branch information
LunaTheFoxgirl committed May 26, 2024
1 parent 869bea4 commit 313139c
Showing 1 changed file with 92 additions and 0 deletions.
92 changes: 92 additions & 0 deletions source/numem/mem/exception.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
Numem Exception support
*/
module numem.mem.exception;
import numem.mem.string;
import numem.mem;
import core.stdc.stdio;

@nogc:

/**
An exception which can be thrown from numem
*/
class NuException : Exception {
nothrow @nogc:
private:
nstring _msg;

public:

~this() {
// Debug build printing
debug printf("Exception freed! (msg=%s)\n", _msg.toCString());

nogc_delete(_msg);

// Free next-in-chain
Throwable t = this.next();
nogc_delete(t);
}

/**
Constructs a nogc exception
*/
this(nstring msg, Throwable nextInChain, string file = __FILE__, size_t line = __LINE__) {
this._msg = msg;
super(this._msg.toDString(), nextInChain, file, line);
}

/**
Constructs a nogc exception
*/
this(nstring msg, string file = __FILE__, size_t line = __LINE__) {
this(msg, null, file, line);
}

/**
Returns the error message
*/
override
@__future const(char)[] message() const @safe nothrow {
return this.msg;
}

/**
Helper function to free this exception
*/
void free() {
NuException ex = this;
nogc_delete(ex);
}
}

/**
Enforces the truthiness of a nstring
*/
void enforce(T)(T in_, nstring err) {
if (!in_) {
throw nogc_new!NuException(err);
}
}

/**
Enforces the truthiness of a nstring
*/
void enforce(T)(T in_, lazy NuException t) {
if (!in_) {
throw t;
}
}

@("Test catching exceptions")
unittest {
auto str = nstring("Ooops!");
try {
enforce(false, str);
} catch(NuException ex) {
assert(ex.message() == str.toDString());

ex.free();
}
}

0 comments on commit 313139c

Please sign in to comment.