blob: 97f2c43970ae4499936c18a814603238b23760d6 (
plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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]
}
|