b6f0ae458e67bbb3d08156913f6b6bf6b4848d22
[tatoo.git] / src / naive_node_list.ml
1 (***********************************************************************)
2 (*                                                                     *)
3 (*                               TAToo                                 *)
4 (*                                                                     *)
5 (*                     Kim Nguyen, LRI UMR8623                         *)
6 (*                   Université Paris-Sud & CNRS                       *)
7 (*                                                                     *)
8 (*  Copyright 2010-2013 Université Paris-Sud and Centre National de la *)
9 (*  Recherche Scientifique. All rights reserved.  This file is         *)
10 (*  distributed under the terms of the GNU Lesser General Public       *)
11 (*  License, with the special exception on linking described in file   *)
12 (*  ../LICENSE.                                                        *)
13 (*                                                                     *)
14 (***********************************************************************)
15
16
17 type node = Naive_tree.node
18 type cell = { node : node;
19               mutable next : cell }
20
21 type iterator = cell
22
23 type t = { mutable length : int;
24            mutable head : cell;
25            mutable last : cell; }
26
27 let rec nil = { node = Naive_tree.nil;
28                 next = nil }
29
30 let create () = { length = 0;
31                   head = nil;
32                   last = nil }
33
34 let iter f l =
35   let rec loop c =
36     if c != nil then begin
37       f c.node;
38       loop c.next
39     end
40   in
41   loop l.head
42
43
44 let length l = l.length
45 let is_empty l = l.head == nil
46
47 let add n l =
48   let ncell = { node = n;
49                 next = nil }
50   in
51   if l.head == nil then begin
52     l.head <- ncell;
53     l.last <- ncell;
54     l.length <- 1
55   end else begin
56     l.last.next <- ncell;
57     l.last <- ncell;
58     l.length <- l.length + 1
59   end
60
61 let push_back n l = add n l
62 let push_front n l =
63   let ncell = { node = n;
64                 next = l.head }
65   in
66   if l.head == nil then begin
67     l.head <- ncell;
68     l.last <- ncell;
69     l.length <- 1;
70   end else begin
71     l.head <- ncell;
72     l.length <- l.length + 1;
73   end
74
75 let head l = l.head
76 let last l = l.last
77 let next i = i.next
78 let value i = i.node
79 let finished i = i == nil
80
81 let copy l =
82   let rec loop l2 i =
83     if finished i then l2 else begin
84       add (value i) l2;
85       loop l2 (next i)
86     end
87   in
88   loop (create ()) (head l)