Skip to content

Instantly share code, notes, and snippets.

@paulbuis
Created May 21, 2014 17:05
Show Gist options
  • Save paulbuis/7b3f47079e0e99589abc to your computer and use it in GitHub Desktop.
Save paulbuis/7b3f47079e0e99589abc to your computer and use it in GitHub Desktop.
Example code in D for imlementing a Stack template with a non-GC'ed linked list that minimizes invocations of "new"
module stacks;
class Stack(T) {
private StackNode!T* front = null;
~this() {
while (!empty()) {
pop();
}
}
public T top() /*const*/ nothrow {
assert(!this.empty());
return front.data;
}
public bool empty() const nothrow {
return front is null;
}
public void push(T value) {
front = StackNode!T.allocate(value, front);
}
public void pop() nothrow {
assert(!empty());
front = front.remove();
}
}
private struct StackNode(T) {
private StackNode!T *next;
public T data;
@disable this();
private this(T data, StackNode!T *next) {
this.data = data;
this.next = next;
}
public StackNode!T *remove() {
StackNode!T *next = this.next;
this.next = freeNode;
this.data = T.init;
freeNode = &this;
return next;
}
public static StackNode!T *freeNode = cast(StackNode!T *)null;
public static StackNode!T *allocate(T data, StackNode!T *next) {
if (freeNode is null) {
return new StackNode!T(data, next);
}
else {
StackNode!T *newNode = freeNode;
freeNode = freeNode.next;
newNode.data = data;
newNode.next = next;
return newNode;
}
}
}
@paulbuis
Copy link
Author

This is one of the first D language modules I've written. Probably looks too much like Java and/or C/C++ and is not as idiomatic as it should be.

Mostly, this was an attempt to learn the syntax. Missing unittest!

The idea was to implement an efficient Stack template. Using the standard library SList for a singly linked list looked horribly awkward. Using list with struct-based nodes to avoid garbage collection. Also, maintains a free list of allocated nodes to minimize invocations of "new" for memory allocation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment