summaryrefslogtreecommitdiff
path: root/src/lib/container/array/array.go
diff options
context:
space:
mode:
authorRobert Griesemer <gri@golang.org>2008-11-19 14:05:21 -0800
committerRobert Griesemer <gri@golang.org>2008-11-19 14:05:21 -0800
commit934e17dce1c4c4b0da5ac761efe2d426ebe42d78 (patch)
tree9203a2aac970a991620b395ad0e4801dcc208a50 /src/lib/container/array/array.go
parentf47e8ff5ad1e002c648d7af538b542912bd46bc1 (diff)
downloadgolang-934e17dce1c4c4b0da5ac761efe2d426ebe42d78.tar.gz
- array lib (essentially vector, more complete)
- TODO replace vector R=r DELTA=314 (313 added, 0 deleted, 1 changed) OCL=19592 CL=19609
Diffstat (limited to 'src/lib/container/array/array.go')
-rw-r--r--src/lib/container/array/array.go117
1 files changed, 117 insertions, 0 deletions
diff --git a/src/lib/container/array/array.go b/src/lib/container/array/array.go
new file mode 100644
index 000000000..97f2c4397
--- /dev/null
+++ b/src/lib/container/array/array.go
@@ -0,0 +1,117 @@
+// Copyright 2009 The Go 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 array
+
+export type Element interface {
+}
+
+
+export type Array struct {
+ // TODO do not export field
+ a *[]Element
+}
+
+
+func (p *Array) Init(initial_len int) *Array {
+ a := p.a;
+
+ if a == nil || cap(a) < initial_len {
+ n := 8; // initial capacity
+ if initial_len > n {
+ n = initial_len
+ }
+ a = new([]Element, n);
+ } else {
+ // nil out entries
+ for j := len(a) - 1; j >= 0; j-- {
+ a[j] = nil
+ }
+ }
+
+ p.a = a[0 : initial_len];
+ return p
+}
+
+
+export func New(len int) *Array {
+ return new(Array).Init(len)
+}
+
+
+func (p *Array) Len() int {
+ return len(p.a)
+}
+
+
+func (p *Array) At(i int) Element {
+ return p.a[i]
+}
+
+
+func (p *Array) Set(i int, x Element) {
+ p.a[i] = x
+}
+
+
+func (p *Array) Last() Element {
+ return p.a[len(p.a) - 1]
+}
+
+
+func (p *Array) Insert(i int, x Element) {
+ a := p.a;
+ n := len(a);
+
+ // grow array by doubling its capacity
+ if n == cap(a) {
+ b := new([]Element, 2*n);
+ for j := n-1; j >= 0; j-- {
+ b[j] = a[j];
+ }
+ a = b
+ }
+
+ // make a hole
+ a = a[0 : n+1];
+ for j := n; j > i; j-- {
+ a[j] = a[j-1]
+ }
+
+ a[i] = x;
+ p.a = a
+}
+
+
+func (p *Array) Remove(i int) Element {
+ a := p.a;
+ n := len(a);
+
+ x := a[i];
+ for j := i+1; j < n; j++ {
+ a[j-1] = a[j]
+ }
+
+ a[n-1] = nil; // support GC, nil out entry
+ p.a = a[0 : n-1];
+
+ return x
+}
+
+
+func (p *Array) Push(x Element) {
+ p.Insert(len(p.a), x)
+}
+
+
+func (p *Array) Pop() Element {
+ return p.Remove(len(p.a) - 1)
+}
+
+
+// Partial SortInterface support
+func (p *Array) Swap(i, j int) {
+ a := p.a;
+ a[i], a[j] = a[j], a[i]
+}