MCPcopy Create free account
hub / github.com/ardanlabs/gotraining / Enqueue

Method Enqueue

topics/go/algorithms/data/queue/queue.go:40–71  ·  view source on GitHub ↗

Enqueue inserts data into the queue if there is available capacity.

(data *Data)

Source from the content-addressed store, hash-verified

38// Enqueue inserts data into the queue if there
39// is available capacity.
40func (q *Queue) Enqueue(data *Data) error {
41
42 // If the front of the queue is right behind the end or
43 // if the front is at the end of the capacity and the end
44 // is at the beginning of the capacity, the queue is full.
45 // F E - Enqueue (Full) | E F - Enqueue (Full)
46 // [A][B][C] | [A][B][C]
47 if q.front+1 == q.end ||
48 q.front == len(q.data) && q.end == 0 {
49 return errors.New("queue at capacity")
50 }
51
52 switch {
53 case q.front == len(q.data):
54
55 // If we are at the end of the capacity, then
56 // circle back to the beginning of the capacity by
57 // moving the front pointer to the beginning.
58 q.front = 0
59 q.data[q.front] = data
60 default:
61
62 // Add the data to the current front position
63 // and then move the front pointer.
64 q.data[q.front] = data
65 q.front++
66 }
67
68 q.Count++
69
70 return nil
71}
72
73// Dequeue removes data into the queue if data exists.
74func (q *Queue) Dequeue() (*Data, error) {

Callers 4

TestEnqueueFunction · 0.45
TestDequeueFunction · 0.45
TestEnqueueFullFunction · 0.45
TestDequeueEmptyFunction · 0.45

Calls

no outgoing calls

Tested by 4

TestEnqueueFunction · 0.36
TestDequeueFunction · 0.36
TestEnqueueFullFunction · 0.36
TestDequeueEmptyFunction · 0.36