-
Notifications
You must be signed in to change notification settings - Fork 1
/
vector.dfy
123 lines (103 loc) · 2.48 KB
/
vector.dfy
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
118
119
120
121
122
123
/*
abstract module Vec0 {
class Vector<T> {
ghost var contents: seq<T>
protected predicate Valid()
reads this
constructor ()
ensures contents == []
method push_back(obj: T)
requires Valid()
ensures contents == old(contents) + [obj]
ensures Valid()
method size() returns (s: int)
requires Valid()
ensures contents == old(contents)
ensures s == |contents|
ensures Valid()
}
}
*/
module Vec {
class Vector<T(0)> {
ghost var Contents: seq<T>;
ghost var Repr: set<object>;
var objs: array<T>;
var capacity: int;
var length: int;
predicate Valid()
reads this, objs
{
this in Repr && objs in Repr &&
capacity == objs.Length &&
0 <= length <= capacity &&
1 <= capacity &&
Contents == objs[..length]
}
constructor ()
ensures Contents == []
ensures Valid()
{
capacity := 1;
length := 0;
objs := new T[1];
Contents := [];
Repr := {this, objs};
}
method size() returns (s: int)
requires Valid()
ensures Contents == old(Contents) && Repr == old(Repr)
ensures s == |Contents|
ensures Valid()
{
s := length;
}
method resize(size: int)
modifies Repr
requires Valid()
requires size > 0
ensures size <= capacity
ensures Contents == old(Contents)
ensures Valid() && fresh(Repr - old(Repr))
{
if (size > capacity) {
capacity := size;
var newObjs := new T[capacity];
forall i | 0 <= i < length {
newObjs[i] := objs[i];
}
objs := newObjs;
Repr := Repr + {newObjs};
}
}
method push_back(obj: T)
modifies Repr
requires Valid()
ensures Contents == old(Contents) + [obj]
ensures Valid() && fresh(Repr - old(Repr))
{
if (length < capacity) {
objs[length] := obj;
length := length + 1;
}
else {
/*
// Works without Repr:
capacity := capacity * 2;
var newObjs := new T[capacity];
forall i | 0 <= i < length {
newObjs[i] := objs[i];
}
objs := newObjs;
*/
resize(capacity * 2);
assert capacity > length;
assert objs.Length == capacity;
assert objs.Length > length;
objs[length] := obj;
length := length + 1;
}
Contents := Contents + [obj];
}
}
}