update stack (again)

This commit is contained in:
Matthew 2025-09-06 15:10:54 +10:00
parent 3046baee78
commit c7f77523c4

64
util.d
View File

@ -199,15 +199,30 @@ DLLPush(T, U)(T* list, U* node, U* nil)
struct Stack(T) struct Stack(T)
{ {
Node!(T)* top; Node!(T)* top;
Node!(T)* free;
Node!(T)* nil;
} }
void void
SPush(T)(Stack!(T)* stack, Node!(T)* node, Node!(T)* nil) SPush(T)(Arena* arena, Stack!(T)* stack, T value)
{ {
if (CheckNil(nil, stack.top)) Node!(T)* node;
if (!CheckNil(stack.nil, stack.free))
{
node = stack.free;
stack.free = node.next;
}
else
{
node = Alloc!(Node!(T))(arena);
}
node.value = value;
if (CheckNil(stack.nil, stack.top))
{ {
stack.top = node; stack.top = node;
node.next = nil; node.next = stack.nil;
} }
else else
{ {
@ -216,15 +231,22 @@ SPush(T)(Stack!(T)* stack, Node!(T)* node, Node!(T)* nil)
} }
} }
Node!(T)* T
SPop(T)(Stack!(T)* stack, Node!(T)* nil) SPop(T)(Stack!(T)* stack)
{ {
Node!(T)* node = stack.top; T result;
if (!CheckNil(nil, stack.top))
if (!CheckNil(stack.nil, stack.top))
{ {
stack.top = stack.top.next; result = stack.top.value;
Node!(T)* free_node = stack.top;
stack.top = free_node.next;
free_node.next = stack.free;
stack.free = free_node;
} }
return node;
return result;
} }
struct Node(T) struct Node(T)
@ -967,13 +989,19 @@ unittest
{ // Stack { // Stack
Stack!(u32) stack; Stack!(u32) stack;
Node!(u32) n1 = { value: 1 }; Arena arena = CreateArena(MB(1));
Node!(u32) n2 = { value: 2 };
Node!(u32) n3 = { value: 3 };
SPush(&stack, &n1, null); u32 v1 = 1;
SPush(&stack, &n2, null); u32 v2 = 2;
SPush(&stack, &n3, null); u32 v3 = 3;
Node!(u32) nil;
stack.nil = &nil;
SPush(&arena, &stack, v1);
SPush(&arena, &stack, v2);
SPush(&arena, &stack, v3);
u32 count = 3; u32 count = 3;
for (auto n = stack.top; !CheckNil(null, n); n = n.next, count -= 1) for (auto n = stack.top; !CheckNil(null, n); n = n.next, count -= 1)
@ -982,11 +1010,11 @@ unittest
} }
count = 3; count = 3;
for (auto n = SPop(&stack, cast(Node!(u32)*)null); !CheckNil(null, n); n = SPop(&stack, cast(Node!(u32)*)null), count -= 1) for (u32 n = SPop(&stack); n != 0; n = SPop(&stack), count -= 1)
{ {
assert(n.value == count); assert(n == count);
} }
assert(stack.top == null); assert(stack.top == &nil);
} }
} }