From d4edaf94e31c3efef916c06e42f7d3c7ac249ced Mon Sep 17 00:00:00 2001 From: Steve Dudenhoeffer Date: Sun, 17 Jul 2022 03:04:04 -0400 Subject: [PATCH] initial commit --- lockablequeue.go | 34 ++++++++++++++++++++++++++++++++++ lockablestack.go | 32 ++++++++++++++++++++++++++++++++ queue.go | 25 +++++++++++++++++++++++++ stack.go | 23 +++++++++++++++++++++++ 4 files changed, 114 insertions(+) create mode 100644 lockablequeue.go create mode 100644 lockablestack.go create mode 100644 queue.go create mode 100644 stack.go diff --git a/lockablequeue.go b/lockablequeue.go new file mode 100644 index 0000000..f01ec6a --- /dev/null +++ b/lockablequeue.go @@ -0,0 +1,34 @@ +package containers + +import "sync" + +type LockableQueue[T any] struct { + sync.Mutex + items []T +} + +func (q *LockableQueue[T]) Push(item T) { + q.Lock() + defer q.Unlock() + + q.items = append(q.items, item) +} + +func (q *LockableQueue[T]) Pop() (T, bool) { + q.Lock() + defer q.Unlock() + + if len(q.items) == 0 { + var res T + return res, false + } + + res := q.items[0] + q.items = q.items[1:] + + return res, true +} + +func NewLockableQueue[T any]() *LockableQueue[T] { + return &LockableQueue[T]{} +} diff --git a/lockablestack.go b/lockablestack.go new file mode 100644 index 0000000..b4d1605 --- /dev/null +++ b/lockablestack.go @@ -0,0 +1,32 @@ +package containers + +import "sync" + +type LockableStack[T any] struct { + sync.Mutex + data []T +} + +func (s *LockableStack[T]) Push(t T) { + s.Lock() + defer s.Unlock() + + s.data = append(s.data, t) +} + +func (s *LockableStack[T]) Pop() (T, bool) { + s.Lock() + defer s.Unlock() + + if len(s.data) == 0 { + var t T + return t, false + } + res := s.data[len(s.data)-1] + s.data = s.data[:len(s.data)-1] + return res, true +} + +func NewLockableStack[T any]() *LockableStack[T] { + return &LockableStack[T]{} +} diff --git a/queue.go b/queue.go new file mode 100644 index 0000000..aa79251 --- /dev/null +++ b/queue.go @@ -0,0 +1,25 @@ +package containers + +type Queue[T any] struct { + items []T +} + +func (q *Queue[T]) Push(item T) { + q.items = append(q.items, item) +} + +func (q *Queue[T]) Pop() (T, bool) { + if len(q.items) == 0 { + var res T + return res, false + } + + res := q.items[0] + q.items = q.items[1:] + + return res, true +} + +func NewQueue[T any]() *Queue[T] { + return &Queue[T]{} +} diff --git a/stack.go b/stack.go new file mode 100644 index 0000000..b7c3c91 --- /dev/null +++ b/stack.go @@ -0,0 +1,23 @@ +package containers + +type Stack[T any] struct { + data []T +} + +func (s *Stack[T]) Push(t T) { + s.data = append(s.data, t) +} + +func (s *Stack[T]) Pop() (T, bool) { + if len(s.data) == 0 { + var t T + return t, false + } + res := s.data[len(s.data)-1] + s.data = s.data[:len(s.data)-1] + return res, true +} + +func NewStack[T any]() *Stack[T] { + return &Stack[T]{} +}