-
Notifications
You must be signed in to change notification settings - Fork 1
/
050-encode_shift.dfy
76 lines (73 loc) · 1.79 KB
/
050-encode_shift.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
function encode_char(c: char): char
// pre-conditions-start
requires 'a' <= c <= 'z'
// pre-conditions-end
// post-conditions-start
ensures 'a' <= encode_char(c) <= 'z'
// post-conditions-end
{
// impl-start
((c as int - 'a' as int + 5) % 26 + 'a' as int) as char
// impl-end
}
function decode_char(c: char): char
// pre-conditions-start
requires 'a' <= c <= 'z'
// pre-conditions-end
// post-conditions-start
ensures 'a' <= decode_char(c) <= 'z'
ensures encode_char(decode_char(c)) == c
// post-conditions-end
{
// impl-start
((c as int - 'a' as int - 5) % 26 + 'a' as int) as char
// impl-end
}
method encode_shift(s: string) returns (t: string)
// pre-conditions-start
requires forall i :: 0 <= i < |s| ==> 'a' <= s[i] <= 'z'
// pre-conditions-end
// post-conditions-start
ensures |s| == |t|
ensures forall i :: 0 <= i < |s| ==> t[i] == encode_char(s[i])
// post-conditions-end
{
// impl-start
t := "";
var i := 0;
while i < |s|
// invariants-start
invariant 0 <= i <= |s|
invariant |t| == i
invariant forall j :: 0 <= j < i ==> t[j] == encode_char(s[j])
// invariants-end
{
t := t + [encode_char(s[i])];
i := i + 1;
}
// impl-end
}
method decode_shift(s: string) returns (t: string)
// pre-conditions-start
requires forall i :: 0 <= i < |s| ==> 'a' <= s[i] <= 'z'
// pre-conditions-end
// post-conditions-start
ensures |s| == |t|
ensures forall i :: 0 <= i < |s| ==> t[i] == decode_char(s[i])
// post-conditions-end
{
// impl-start
t := "";
var i := 0;
while i < |s|
// invariants-start
invariant 0 <= i <= |s|
invariant |t| == i
invariant forall j :: 0 <= j < i ==> t[j] == decode_char(s[j])
// invariants-end
{
t := t + [decode_char(s[i])];
i := i + 1;
}
// impl-end
}