initial commit

This commit is contained in:
Steve Dudenhoeffer 2022-07-17 03:04:04 -04:00
commit d4edaf94e3
4 changed files with 114 additions and 0 deletions

34
lockablequeue.go Normal file
View File

@ -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]{}
}

32
lockablestack.go Normal file
View File

@ -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]{}
}

25
queue.go Normal file
View File

@ -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]{}
}

23
stack.go Normal file
View File

@ -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]{}
}