From e8ef3454880b92a5485a339b3b6fe7b64cfe5305 Mon Sep 17 00:00:00 2001 From: Lam Wei Lun Date: Wed, 21 Jan 2026 19:35:12 +0800 Subject: Add length, clear, is_empty to Stack and Queue --- std/queue.zc | 14 ++++++++++++-- std/stack.zc | 12 ++++++++++++ tests/std/test_queue.zc | 14 ++++++++++++++ tests/std/test_stack.zc | 14 ++++++++++++++ 4 files changed, 52 insertions(+), 2 deletions(-) diff --git a/std/queue.zc b/std/queue.zc index 2bbcfaa..31e5dbd 100644 --- a/std/queue.zc +++ b/std/queue.zc @@ -38,8 +38,6 @@ impl Queue { self.cap = self.cap * 2; self.data = realloc(self.data, sizeof(T) * self.cap); } - - // Assigns it at the back of self.data[self.len] = value; self.len = self.len + 1; } @@ -56,6 +54,18 @@ impl Queue { } return Option::None(); } + + fn length(self) -> usize { + return self.len; + } + + fn clear(self) { + self.len = 0; + } + + fn is_empty(self) -> bool { + return self.len == 0; + } } impl Drop for Queue { diff --git a/std/stack.zc b/std/stack.zc index 3d7c3c5..7df77f1 100644 --- a/std/stack.zc +++ b/std/stack.zc @@ -50,6 +50,18 @@ impl Stack { } return Option::None(); } + + fn length(self) -> usize { + return self.len; + } + + fn clear(self) { + self.len = 0; + } + + fn is_empty(self) -> bool { + return self.len == 0; + } } impl Drop for Stack { diff --git a/tests/std/test_queue.zc b/tests/std/test_queue.zc index 4d40c42..131eb05 100644 --- a/tests/std/test_queue.zc +++ b/tests/std/test_queue.zc @@ -28,6 +28,20 @@ test "Queue Push/Pop" { assert(v.is_none(), "v should not have a valid value"); } +test "Queue Length and Clear" { + print "Testing Queue clear"; + var queue = Queue::new(); + defer queue.free(); + + assert(queue.is_empty() && queue.length() == 0, "queue should be empty"); + + queue.push(123); + assert(!queue.is_empty() && queue.length() == 1, "queue should have 1 value"); + + queue.clear(); + assert(queue.is_empty() && queue.length() == 0, "queue should be empty"); +} + test "Queue Clone" { print "Testing Queue Cloning"; var queue = Queue::new(); diff --git a/tests/std/test_stack.zc b/tests/std/test_stack.zc index ecc9d3c..03e51a4 100644 --- a/tests/std/test_stack.zc +++ b/tests/std/test_stack.zc @@ -28,6 +28,20 @@ test "Stack Push/Pop" { assert(v.is_none(), "v should not have a valid value"); } +test "Stack Length and Clear" { + print "Testing Stack clear"; + var stack = Stack::new(); + defer stack.free(); + + assert(stack.is_empty() && stack.length() == 0, "Stack should be empty"); + + stack.push(123); + assert(!stack.is_empty() && stack.length() == 1, "Stack should have 1 value"); + + stack.clear(); + assert(stack.is_empty() && stack.length() == 0, "Stack should be empty"); +} + test "Stack Clone" { print "Testing Stack Cloning"; var stack = Stack::new(); -- cgit v1.2.3