import std.algorithm; auto stack = BoundedStack!int(5); stack.pushFront(1); stack.pushFront(2); stack.pushFront(3); stack.pushFront(4); stack.pushFront(5); assert(stack.front == 5); assert(equal(stack, [5, 4, 3, 2, 1]));
A custom buffer may be used.
import std.algorithm; auto stack = BoundedStack!int(new int[5]); stack.pushFront(1); stack.pushFront(2); stack.pushFront(3); stack.pushFront(4); stack.pushFront(5); assert(stack.front == 5); assert(equal(stack, [5, 4, 3, 2, 1]));
Ring buffer may have a static size.
import std.algorithm; auto stack = BoundedStack!(int, 5)(); stack.pushFront(1); stack.pushFront(2); stack.pushFront(3); stack ~= 4; stack ~= 5; assert(stack.front == 5); assert(equal(stack, [5, 4, 3, 2, 1]));
Elements can be removed.
import std.algorithm; auto stack = BoundedStack!int(5); stack.pushFront(1); stack.pushFront(2); stack.pushFront(3); stack.pushFront(4); stack.pushFront(5); stack.popFront(); stack.popFront(); stack.popFront(); stack.popFront(); assert(stack.front == 1);
The stack can be used as an output range.
import std.algorithm; import std.range; auto stack = BoundedStack!int(5); iota(5).copy(&stack); assert(equal(stack, iota(5).retro));
The stack can be resized but that may relocate the underlying buffer.
import std.algorithm; auto stack = BoundedStack!int(5); stack.pushFront(1); stack.pushFront(2); stack.pushFront(3); stack.pushFront(4); stack.pushFront(5); assert(stack.front == 5); assert(stack.length == stack.capacity); stack.reserve(10); stack.pushFront(6); stack.pushFront(7); stack.pushFront(8); stack.pushFront(9); stack.pushFront(10); assert(stack.front == 10);
The buffer may be accessed directly
auto stack = BoundedStack!int(5); stack.pushFront(1); stack.pushFront(2); stack.pushFront(3); stack.pushFront(4); stack.pushFront(5); assert(stack.buffer == stack[]); assert(stack[] == [1, 2, 3, 4, 5]);
An array-based implementation of a ring buffer.