Import Upstream version 20180207
[hcoop/debian/mlton.git] / lib / mlton / queue / ephemeral.fun
1 (* Copyright (C) 1999-2006 Henry Cejtin, Matthew Fluet, Suresh
2 * Jagannathan, and Stephen Weeks.
3 *
4 * MLton is released under a BSD-style license.
5 * See the file MLton-LICENSE for details.
6 *)
7 (*-------------------------------------------------------------------*)
8 (* Queue Ephemeral *)
9 (*-------------------------------------------------------------------*)
10
11 functor QueueEphemeral(): BASIC_QUEUE =
12 struct
13
14 val {error, ...} = Error.errors("queue", "ephemeral")
15
16 structure L = MutableList
17
18 datatype 'a t = T of {head: 'a L.t ref,
19 tail: 'a L.t ref}
20
21 fun destruct(q as T{head, tail}) =
22 case L.destruct(!head) of
23 NONE => NONE
24 | SOME(x, _) =>
25 (if L.eqTail(!head, !tail)
26 then (head := L.empty() ; tail := L.empty())
27 else head := L.tail(!head) ;
28 SOME(x, q))
29
30 fun empty() = T{head = ref(L.empty()), tail = ref(L.empty())}
31
32 fun isEmpty(T{head, ...}) = L.isEmpty(!head)
33
34 fun enque(q as T{head, tail}, x) =
35 (let val cell = L.cons(x, L.empty())
36 in (if isEmpty q then head := cell
37 else L.setTail(!tail, cell) ;
38 tail := cell)
39 end ;
40 q)
41
42 end