Merge branch '876-ide-crashes-when-clicking-on-goal' into 'master'
[why3.git] / examples / ring_buffer.mlw
blob9f7b2334cf181a671d4829bd595e59ab08ed0b35
2 (** Simple queue implemented using a ring buffer
4    From
5      Developing Verified Programs with Dafny.
6      K. Rustan M. Leino. Tutorial notes, ICSE 2013.
8    For a similar data structure, see vstte12_ring_buffer.mlw
9 *)
11 use int.Int
12 use seq.Seq as S
13 use array.Array
15 type t 'a = {
16   mutable data: array 'a;
17   mutable m: int;
18   mutable n: int;
19   ghost mutable contents: S.seq 'a; (* = data[m..n[ *)
21 invariant { 0 < length data }
22 invariant { 0 <= m <= n <= length data }
23 invariant { S.length contents = n - m }
24 invariant { forall i. 0 <= i < m - n -> S.get contents i = data[m + i] }
25 by { data = Array.make 1 (any 'a); m = 0; n = 0; contents = S.empty }
27 let create (x: 'a) : t 'a
28   ensures { S.(result.contents == empty) }
30   { data = Array.make 10 x;
31     m = 0; n = 0;
32     contents = S.empty; }
34 let dequeue (q: t 'a) : (_r: 'a)
35   requires { S.length q.contents > 0 }
36   writes   { q.m, q.contents }
37   ensures  { S.(q.contents == (old q.contents)[1..]) }
39   let r = q.data[q.m] in
40   q.m <- q.m + 1;
41   ghost S.(q.contents <- q.contents[1..]);
42   r
44 let enqueue (q: t 'a) (x: 'a) : unit
45   requires { q.n < length q.data }
46   writes   { q.data.elts, q.n, q.contents }
47   ensures  { S.(q.contents == snoc (old q.contents) x) }
49   q.data[q.n] <- x;
50   q.n <- q.n + 1;
51   ghost S.(q.contents <- S.snoc q.contents x)