summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2015-01-09 02:04:19 +0100
committerDimitri Sokolyuk <demon@dim13.org>2015-01-09 02:04:19 +0100
commitcc736093e7e4521ad392b13f74cf3da51308bf18 (patch)
tree6c0509090eced91488914ffe04e1cdcdfb4f2671
Initial import
-rw-r--r--stack.go19
-rw-r--r--stack_test.go53
2 files changed, 72 insertions, 0 deletions
diff --git a/stack.go b/stack.go
new file mode 100644
index 0000000..d8b5b6c
--- /dev/null
+++ b/stack.go
@@ -0,0 +1,19 @@
+package stack
+
+type Stack []interface{}
+
+func NewStack() Stack {
+ return Stack{}
+}
+
+func (s *Stack) Push(v interface{}) {
+ *s = append(*s, v)
+}
+
+func (s *Stack) Pop() (v interface{}, ok bool) {
+ size := len(*s) - 1
+ if ok = size >= 0; ok {
+ v, *s = (*s)[size], (*s)[:size]
+ }
+ return v, ok
+}
diff --git a/stack_test.go b/stack_test.go
new file mode 100644
index 0000000..773f6cf
--- /dev/null
+++ b/stack_test.go
@@ -0,0 +1,53 @@
+package stack
+
+import "testing"
+
+func TestInt(t *testing.T) {
+ s := NewStack()
+ s.Push(1)
+ i, _ := s.Pop()
+ if i != 1 {
+ t.Error("Expected 1, got ", i)
+ }
+}
+
+func TestComplex(t *testing.T) {
+ s := NewStack()
+ s.Push(1+1i)
+ i, _ := s.Pop()
+ if i != 1+1i {
+ t.Error("Expected 1+1i, got ", i)
+ }
+}
+
+func TestMeny(t *testing.T) {
+ s := NewStack()
+ s.Push(1)
+ s.Push(2)
+ i, _ := s.Pop()
+ if i != 2 {
+ t.Error("Expected 2, got ", i)
+ }
+ i, _ = s.Pop()
+ if i != 1 {
+ t.Error("Expected 1, got ", i)
+ }
+}
+
+func BenchmarkPushPopSingle(b *testing.B) {
+ s := NewStack()
+ for i := 0; i < b.N; i++ {
+ s.Push(1)
+ s.Pop()
+ }
+}
+
+func BenchmarkPushPopAlot(b *testing.B) {
+ s := NewStack()
+ for i := 0; i < b.N; i++ {
+ s.Push(i)
+ }
+ for i := 0; i < b.N; i++ {
+ s.Pop()
+ }
+}