2020-03-04 15:02:37 +01:00
|
|
|
|
|
|
|
|
(** Simple queue implemented using a ring buffer
|
|
|
|
|
|
|
|
|
|
From
|
|
|
|
|
Developing Verified Programs with Dafny.
|
|
|
|
|
K. Rustan M. Leino. Tutorial notes, ICSE 2013.
|
2025-11-07 14:29:31 +00:00
|
|
|
(cf, https://leino.science/papers/krml233.pdf)
|
2020-03-04 15:02:37 +01:00
|
|
|
|
|
|
|
|
For a similar data structure, see vstte12_ring_buffer.mlw
|
|
|
|
|
*)
|
|
|
|
|
|
|
|
|
|
use int.Int
|
2025-11-07 14:29:31 +00:00
|
|
|
use seq.Seq
|
2020-03-04 15:02:37 +01:00
|
|
|
use array.Array
|
2025-11-07 14:29:31 +00:00
|
|
|
use array.ToSeq
|
2020-03-04 15:02:37 +01:00
|
|
|
|
|
|
|
|
type t 'a = {
|
|
|
|
|
mutable data: array 'a;
|
|
|
|
|
mutable m: int;
|
|
|
|
|
mutable n: int;
|
2025-11-07 14:29:31 +00:00
|
|
|
ghost mutable contents: Seq.seq 'a; (* = data[m..n[ *)
|
2020-03-04 15:02:37 +01:00
|
|
|
}
|
|
|
|
|
invariant { 0 < length data }
|
|
|
|
|
invariant { 0 <= m <= n <= length data }
|
2025-11-07 14:29:31 +00:00
|
|
|
invariant { Seq.length contents = n - m }
|
|
|
|
|
invariant { contents == data[m..n] } (* coercion `to_seq` is inserted here *)
|
|
|
|
|
by { data = Array.make 1 (any 'a); m = 0; n = 0; contents = Seq.empty }
|
2020-03-04 15:02:37 +01:00
|
|
|
|
|
|
|
|
let create (x: 'a) : t 'a
|
2025-11-07 14:29:31 +00:00
|
|
|
ensures { Seq.(result.contents == empty) }
|
2020-03-04 15:02:37 +01:00
|
|
|
=
|
|
|
|
|
{ data = Array.make 10 x;
|
|
|
|
|
m = 0; n = 0;
|
2025-11-07 14:29:31 +00:00
|
|
|
contents = Seq.empty; }
|
2020-03-04 15:02:37 +01:00
|
|
|
|
2025-11-07 14:29:31 +00:00
|
|
|
let dequeue (q: t 'a) : (r: 'a)
|
|
|
|
|
requires { Seq.length q.contents > 0 }
|
2020-03-04 15:02:37 +01:00
|
|
|
writes { q.m, q.contents }
|
2025-11-07 14:29:31 +00:00
|
|
|
ensures { Seq.(old q.contents == cons r q.contents) }
|
2020-03-04 15:02:37 +01:00
|
|
|
=
|
|
|
|
|
let r = q.data[q.m] in
|
|
|
|
|
q.m <- q.m + 1;
|
2025-11-07 14:29:31 +00:00
|
|
|
ghost Seq.(q.contents <- q.contents[1..]);
|
2020-03-04 15:02:37 +01:00
|
|
|
r
|
|
|
|
|
|
|
|
|
|
let enqueue (q: t 'a) (x: 'a) : unit
|
|
|
|
|
requires { q.n < length q.data }
|
|
|
|
|
writes { q.data.elts, q.n, q.contents }
|
2025-11-07 14:29:31 +00:00
|
|
|
ensures { Seq.(q.contents == snoc (old q.contents) x) }
|
2020-03-04 15:02:37 +01:00
|
|
|
=
|
|
|
|
|
q.data[q.n] <- x;
|
|
|
|
|
q.n <- q.n + 1;
|
2025-11-07 14:29:31 +00:00
|
|
|
ghost Seq.(q.contents <- Seq.snoc q.contents x)
|