From b7d78c09fe59b6f83a2c6afefeabe55461aee660 Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Sun, 14 Dec 2025 07:21:48 -0600 Subject: [PATCH] feat: add stack implementation --- internal/stack/stack.go | 75 ++++++++++++++++++++++++++++++++++++ internal/stack/stack_test.go | 1 + 2 files changed, 76 insertions(+) create mode 100644 internal/stack/stack.go create mode 100644 internal/stack/stack_test.go diff --git a/internal/stack/stack.go b/internal/stack/stack.go new file mode 100644 index 0000000..49407fc --- /dev/null +++ b/internal/stack/stack.go @@ -0,0 +1,75 @@ +// Package stack provides a thread-safe LIFO stack implementation. +package stack + +import "sync" + +type Stack[T any] interface { + Push(item T) + Peek() (T, bool) + Pop() (T, bool) + IsEmpty() bool + Size() int +} + +type stack[T any] struct { + items []T + lock sync.Mutex +} + +func New[T any]() Stack[T] { + return &stack[T]{items: []T{}} +} + +func (s *stack[T]) Push(item T) { + s.lock.Lock() + defer s.lock.Unlock() + + s.items = append(s.items, item) +} + +func (s *stack[T]) Pop() (T, bool) { + s.lock.Lock() + defer s.lock.Unlock() + + length := len(s.items) + + if len(s.items) == 0 { + var zero T + return zero, false + } + + lastItemIndex := length - 1 + item := s.items[lastItemIndex] + s.items = s.items[:lastItemIndex] + return item, true +} + +func (s *stack[T]) Peek() (T, bool) { + s.lock.Lock() + defer s.lock.Unlock() + + length := len(s.items) + + if len(s.items) == 0 { + var zero T + return zero, false + } + + lastItemIndex := length - 1 + item := s.items[lastItemIndex] + return item, true +} + +func (s *stack[T]) IsEmpty() bool { + s.lock.Lock() + defer s.lock.Unlock() + + return len(s.items) == 0 +} + +func (s *stack[T]) Size() int { + s.lock.Lock() + defer s.lock.Unlock() + + return len(s.items) +} diff --git a/internal/stack/stack_test.go b/internal/stack/stack_test.go new file mode 100644 index 0000000..33c2615 --- /dev/null +++ b/internal/stack/stack_test.go @@ -0,0 +1 @@ +package stack_test