Skip to content

Commit

Permalink
Merge pull request #1 from enriquebris/tests
Browse files Browse the repository at this point in the history
Tests
  • Loading branch information
enriquebris authored Jan 14, 2019
2 parents 258d6a5 + 038f753 commit 4d575df
Show file tree
Hide file tree
Showing 5 changed files with 448 additions and 0 deletions.
83 changes: 83 additions & 0 deletions fifo_queue.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package goconcurrentqueue

import (
"fmt"
"sync"
)

// First In First Out (FIFO) concurrent queue
type FIFO struct {
slice []interface{}
rwmutex sync.RWMutex
}

// NewFIFO returns a new FIFO concurrent queue
func NewFIFO() *FIFO {
ret := &FIFO{}
ret.initialize()

return ret
}

func (st *FIFO) initialize() {
st.slice = make([]interface{}, 0)
}

// Enqueue enqueues an element
func (st *FIFO) Enqueue(value interface{}) {
st.rwmutex.Lock()
defer st.rwmutex.Unlock()

st.slice = append(st.slice, value)
}

// Dequeue dequeues an element
func (st *FIFO) Dequeue() (interface{}, error) {
st.rwmutex.Lock()
defer st.rwmutex.Unlock()

len := len(st.slice)
if len == 0 {
return nil, fmt.Errorf("queue is empty")
}

elementToReturn := st.slice[0]
st.slice = st.slice[1:]

return elementToReturn, nil
}

// Get returns an element's value and keeps the element at the queue
func (st *FIFO) Get(index int) (interface{}, error) {
st.rwmutex.RLock()
defer st.rwmutex.RUnlock()

if len(st.slice) <= index {
return nil, fmt.Errorf("index out of bounds: %v", index)
}

return st.slice[index], nil
}

// Remove removes an element from the queue
func (st *FIFO) Remove(index int) error {
st.rwmutex.Lock()
defer st.rwmutex.Unlock()

if len(st.slice) <= index {
return fmt.Errorf("index out of bounds: %v", index)
}

// remove the element
st.slice = append(st.slice[:index], st.slice[index+1:]...)

return nil
}

// GetLen returns the number of enqueued elements
func (st *FIFO) GetLen() int {
st.rwmutex.RLock()
defer st.rwmutex.RUnlock()

return len(st.slice)
}
Loading

0 comments on commit 4d575df

Please sign in to comment.