-
Notifications
You must be signed in to change notification settings - Fork 2
/
stacks.in
72 lines (66 loc) · 1.22 KB
/
stacks.in
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
#! /usr/bin/perl
while (<DATA>) {
/^%%\s*$/ and last;
print $_;
}
my $template = join('', <DATA>);
sub stack {
my ($stackt, $type) = @_;
my $out = $template;
$out =~ s/%%S/$stackt/g;
$out =~ s/%%T/$type/g;
print $out;
}
stack qw(Stack []byte);
stack qw(StrStack string);
__DATA__
// Stacks of different types.
package stacks
%%
type %%S interface {
Push(%%T)
Pop() %%T
Drop(int) (st []%%T)
Dump() []%%T
Depth() int
Index(p int) %%T
Clear()
}
type %%ST struct {
st []%%T
sp int
limit bool
}
func (st *%%ST) Push(s %%T) {
if st.sp >= len(st.st) && !st.limit {
t := make([]%%T, len(st.st)+1024)
st.sp = 0
for k := range st.st {
t[k] = st.st[k]
st.sp++
}
st.st = t
}
st.st[st.sp] = s
st.sp++
}
func (st *%%ST) Drop(n int) []%%T {
st.sp -= n
return st.st[st.sp : st.sp+n]
}
func (st *%%ST) Pop() %%T {
st.sp--
return st.st[st.sp]
}
func (st *%%ST) Dump() []%%T { return st.st[0:st.sp] }
func (st *%%ST) Depth() int { return st.sp }
func (st *%%ST) Index(p int) %%T { return st.st[st.sp-p] }
func (st *%%ST) Clear() { st.sp = 0 }
func New%%S(n int) *%%ST {
r := new(%%ST)
if r.limit = n >= 0; !r.limit {
n = 1024;
}
r.st = make([]%%T, n)
return r
}