File: stores.go

package info (click to toggle)
golang-github-biogo-graph 0.0~git20150317.057c198-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 124 kB
  • sloc: makefile: 2
file content (93 lines) | stat: -rw-r--r-- 1,778 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright ©2012 The bíogo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package graph

import (
	"errors"
)

var (
	queueIndexOutOfRange = errors.New("graph: queue index out of range")
	emptyQueue           = errors.New("graph: queue empty")
	stackIndexOutOfRange = errors.New("graph: stack index out of range")
	emptyStack           = errors.New("graph: stack empty")
)

type queue struct {
	head int
	data []Node
}

func (q *queue) Enqueue(n Node) {
	if len(q.data) == cap(q.data) && q.head > 0 {
		l := q.Len()
		copy(q.data, q.data[q.head:])
		q.head = 0
		q.data = append(q.data[:l], n)
	} else {
		q.data = append(q.data, n)
	}
}

func (q *queue) Dequeue() (Node, error) {
	if q.Len() == 0 {
		return nil, emptyQueue
	}

	var n Node
	n, q.data[q.head] = q.data[q.head], nil
	q.head++

	if q.Len() == 0 {
		q.head = 0
		q.data = q.data[:0]
	}

	return n, nil
}

func (q *queue) Peek(i int) (Node, error) {
	if i < q.head || i >= len(q.data) {
		return nil, queueIndexOutOfRange
	}
	return q.data[i+q.head], nil
}

func (q *queue) Clear() {
	q.head = 0
	q.data = q.data[:0]
}

func (q *queue) Len() int { return len(q.data) - q.head }

type stack struct {
	data []Node
}

func (s *stack) Push(n Node) { s.data = append(s.data, n) }

func (s *stack) Pop() (Node, error) {
	if len(s.data) == 0 {
		return nil, emptyStack
	}

	var n Node
	n, s.data, s.data[len(s.data)-1] = s.data[len(s.data)-1], s.data[:len(s.data)-1], nil

	return n, nil
}

func (s *stack) Peek(i int) (Node, error) {
	if i < 0 || i >= len(s.data) {
		return nil, stackIndexOutOfRange
	}
	return s.data[i], nil
}

func (s *stack) Clear() {
	s.data = s.data[:0]
}

func (s *stack) Len() int { return len(s.data) }