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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//! Composed of a root `Node` and a list of its child `Node`s.
//!
//! 1. Support adding and storing nodes only once on tree creation, in a
//! contiguous memory address.
//!
//! 2. Support adding and storing nodes one by one, in scattered memory
//! allocations.
//!
//! 3. Tuple notations for construction.
//!
//! 4. `tr()`,`-`,`/` notations for construction.
//!
//! 5. Can be converted to `RcNode` which has shared ownership.

use crate::TupleTree;

use crate::rust::*;

use super::{Data, Forest, IterMut, Node, NodeVec, heap};

/// Composed of a root `Node` and a list of its child `Node`s.
pub struct Tree<T>{
    pub(crate) root : NonNull<Node<T>>,
    pub(crate) mark : PhantomData<Node<T>>,
}

impl<T> Tree<T> {
    /// Creates a `Tree` containing only root node associated with given data.
    pub fn new( data: T ) -> Tree<T> {
        Tree {
            root: heap::make_node( Data::Scattered{ data, owner: NonNull::dangling() }),
            mark: PhantomData,
        }
    }

    /// Constructs tree from tuple notations.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::{Tree, tr};
    ///
    /// let tree = Tree::<i32>::from_tuple(( 0, (1,2), (3,4) ));
    /// assert_eq!( tree, tr(0) /(tr(1)/tr(2)) /(tr(3)/tr(4)) );
    /// assert_eq!( tree.to_string(), "0( 1( 2 ) 3( 4 ) )" );
    /// ```
    pub fn from_tuple<Tuple,Shape>( tuple: Tuple ) -> Self
        where Tuple: TupleTree<T,Shape>
    {
        let node_count = <Tuple as TupleTree<T,Shape>>::SIZE.descendants+1;
        let mut node_vec = NodeVec::new_raw_non_null( node_count );
        unsafe{ node_vec.as_mut().construct_tree( tuple )};

        Tree::from_node( unsafe{ node_vec.as_ref().non_null_node(0) })
    }

    pub(crate) fn into_data( mut self ) -> T {
        let value = self.root_mut_().data.replace( Data::None ).into_inner();
        mem::forget( self );
        value
    }

    pub(crate) fn from_node( mut root: NonNull<Node<T>> ) -> Tree<T> {
        unsafe{ root.as_mut().up = None; }
        Tree{ root, mark: PhantomData }
    }

    /// Reference of the root node.
    pub fn root( &self ) -> &Node<T> { unsafe{ &*self.root.as_ptr() }}

    /// Mutable reference of the root node.
    pub fn root_mut( &mut self ) -> Pin<&mut Node<T>> { unsafe{ Pin::new_unchecked( self.root_mut_() )}}

    pub(crate) fn root_mut_( &mut self ) -> &mut Node<T> { unsafe{ &mut *self.root.as_ptr() }}

    /// Provides a forward iterator over child `Node`s with mutable references.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::Tree;
    ///
    /// let mut tree = Tree::<i32>::from_tuple(( 0, 1, 2, 3 ));
    /// tree.iter_mut().for_each( |mut child| *child.data_mut() *= 10 );
    /// assert_eq!( tree.to_string(), "0( 10 20 30 )" );
    /// ```
    pub fn iter_mut<'a, 's:'a>( &'s mut self ) -> IterMut<'a,T> { self.root_mut_().iter_mut() }

    /// Adds the tree as the first child.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::Tree;
    /// let mut tree = Tree::new(0);
    /// tree.push_front( Tree::new(1) );
    /// assert_eq!( tree.to_string(), "0( 1 )" );
    /// tree.push_front( Tree::new(2) );
    /// assert_eq!( tree.to_string(), "0( 2 1 )" );
    /// ```
    pub fn push_front( &mut self, tree: Tree<T> ) {
        self.root_mut_().push_front( tree );
    }

    /// Adds the tree as the last child.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::Tree;
    /// let mut tree = Tree::new(0);
    /// tree.push_back( Tree::new(1) );
    /// assert_eq!( tree.to_string(), "0( 1 )" );
    /// tree.push_back( Tree::new(2) );
    /// assert_eq!( tree.to_string(), "0( 1 2 )" );
    /// ```
    pub fn push_back( &mut self, tree: Tree<T> ) {
        self.root_mut_().push_back( tree );
    }

    /// Adds all the forest's trees at front of children list.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::{Forest, Tree};
    ///
    /// let mut tree = Tree::new(0);
    /// tree.push_back( Tree::new(1) );
    /// tree.push_back( Tree::new(2) );
    /// let mut forest = Forest::new();
    /// forest.push_back( Tree::new(3) );
    /// forest.push_back( Tree::new(4) );
    /// tree.prepend( forest );
    /// assert_eq!( tree.to_string(), "0( 3 4 1 2 )" );
    /// ```
    pub fn prepend( &mut self, forest: Forest<T> ) {
        self.root_mut_().prepend( forest );
    }

    /// Adds all the forest's trees at back of children list.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::{Forest, Tree};
    ///
    /// let mut tree = Tree::new(0);
    /// tree.push_back( Tree::new(1) );
    /// tree.push_back( Tree::new(2) );
    /// let mut forest = Forest::new();
    /// forest.push_back( Tree::new(3) );
    /// forest.push_back( Tree::new(4) );
    /// tree.root_mut().append( forest );
    /// assert_eq!( tree.to_string(), "0( 1 2 3 4 )" );
    /// ```
    pub fn append( &mut self, forest: Forest<T> ) {
        self.root_mut_().append( forest );
    }

    /// Removes and returns the given `Tree`'s children.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::{Forest, Tree};
    ///
    /// let mut tree = Tree::new(0);
    /// tree.push_back( Tree::new(1) );
    /// tree.push_back( Tree::new(2) );
    /// let forest = tree.abandon();
    /// assert_eq!( forest.to_string(), "( 1 2 )" );
    /// assert_eq!( tree, Tree::new(0) );
    /// ```
    pub fn abandon( &mut self ) -> Forest<T> {
        let new_root = heap::make_node( Data::Scattered{
            data  : self.root_mut_().data.take(),
            owner : NonNull::dangling(),
        });
        let forest = Forest::from_node( self.root );
        self.root = new_root;
        forest
    }

    /// Removes and returns the first child.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::Tree;
    ///
    /// let mut tree = Tree::new(0);
    /// tree.push_back( Tree::new(1) );
    /// tree.push_back( Tree::new(2) );
    /// assert_eq!( tree.to_string(), "0( 1 2 )" );
    /// assert_eq!( tree.pop_front(), Some( Tree::new(1) ));
    /// assert_eq!( tree.to_string(), "0( 2 )" );
    /// assert_eq!( tree.pop_front(), Some( Tree::new(2) ));
    /// assert_eq!( tree.to_string(), "0" );
    /// assert_eq!( tree.pop_front(), None );
    /// ```
    pub fn pop_front( &mut self ) -> Option<Tree<T>> { self.root_mut_().pop_front() }

    /// Removes and returns the last child.
    ///
    /// # Examples
    ///
    /// ```
    /// use trees::Tree;
    ///
    /// let mut tree = Tree::new(0);
    /// tree.push_back( Tree::new(1) );
    /// tree.push_back( Tree::new(2) );
    /// assert_eq!( tree.to_string(), "0( 1 2 )" );
    /// assert_eq!( tree.pop_back(), Some( Tree::new(2) ));
    /// assert_eq!( tree.to_string(), "0( 1 )" );
    /// assert_eq!( tree.pop_back(), Some( Tree::new(1) ));
    /// assert_eq!( tree.to_string(), "0" );
    /// assert_eq!( tree.pop_back(), None );
    /// ```
    pub fn pop_back( &mut self ) -> Option<Tree<T>> { self.root_mut_().pop_back() }

    /// Returns a mutable reference to the first child of this node,
    /// or None if it has no child.
    pub fn front_mut( &mut self ) -> Option<Pin<&mut Node<T>>> { self.root_mut_().front_mut() }

    /// Returns a mutable reference to the last child of this node,
    /// or None if it has no child.
    pub fn back_mut( &mut self ) -> Option<Pin<&mut Node<T>>> { self.root_mut_().back_mut() }
}

impl<T:Clone> Clone for Tree<T> {
    fn clone( &self ) -> Self {
        self.root().deep_clone()
    }
}

impl<T> Deref for Tree<T> {
    type Target = Node<T>;

    fn deref( &self ) -> &Self::Target { self.root() }
}

impl<T> Drop for Tree<T> {
    fn drop( &mut self ) {
        while let Some(_) = self.root_mut_().pop_front() {}
        heap::drop_node( self.root );
    }
}

impl_debug_display_for_collection!( Tree, root() );
impl_order_relations_for_collection!( Tree, root() );
impl_hash_for_collection!( Tree, root() );

#[cfg( test )]
mod tests {
    use super::*;

    #[test] fn piled_tree_from_tuple() {
        let tuple = ( 0, (1,2,3), (4,5,6) );
        let piled = Tree::<i32>::from_tuple( tuple );
        assert_eq!( piled.to_string(), "0( 1( 2 3 ) 4( 5 6 ) )" );
    }
}

#[cfg( miri )]
mod miri_tests {
    #[test] fn iter_mut() {
        use crate::Tree;

        let mut tree = Tree::<i32>::from_tuple(( 0, 1, 2, 3 ));
        tree.iter_mut().for_each( |mut child| *child.data_mut() *= 10 );
        assert_eq!( tree.to_string(), "0( 10 20 30 )" );
    }

    #[test] fn push_front() {
        use crate::Tree;

        let mut tree = Tree::new(0);
        tree.push_front( Tree::new(1) );
        assert_eq!( tree.to_string(), "0( 1 )" );
        tree.push_front( Tree::new(2) );
        assert_eq!( tree.to_string(), "0( 2 1 )" );
    }

    #[test] fn push_back() {
        use crate::Tree;

        let mut tree = Tree::new(0);
        tree.push_back( Tree::new(1) );
        assert_eq!( tree.to_string(), "0( 1 )" );
        tree.push_back( Tree::new(2) );
        assert_eq!( tree.to_string(), "0( 1 2 )" );
    }

    #[test] fn prepend() {
        use crate::{Forest, Tree};

        let mut tree = Tree::new(0);
        tree.push_back( Tree::new(1) );
        tree.push_back( Tree::new(2) );
        let mut forest = Forest::new();
        forest.push_back( Tree::new(3) );
        forest.push_back( Tree::new(4) );
        tree.prepend( forest );
        assert_eq!( tree.to_string(), "0( 3 4 1 2 )" );
    }

    #[test] fn append() {
        use crate::{Forest, Tree};

        let mut tree = Tree::new(0);
        tree.push_back( Tree::new(1) );
        tree.push_back( Tree::new(2) );
        let mut forest = Forest::new();
        forest.push_back( Tree::new(3) );
        forest.push_back( Tree::new(4) );
        tree.root_mut().append( forest );
        assert_eq!( tree.to_string(), "0( 1 2 3 4 )" );
    }

    #[test] fn abandon() {
        use crate::Tree;

        let mut tree = Tree::new(0);
        tree.push_back( Tree::new(1) );
        tree.push_back( Tree::new(2) );
        let forest = tree.abandon();
        assert_eq!( forest.to_string(), "( 1 2 )" );
        assert_eq!( tree, Tree::new(0) );
    }

    #[test] fn pop_front() {
        use crate::Tree;

        let mut tree = Tree::new(0);
        tree.push_back( Tree::new(1) );
        tree.push_back( Tree::new(2) );
        assert_eq!( tree.to_string(), "0( 1 2 )" );
        assert_eq!( tree.pop_front(), Some( Tree::new(1) ));
        assert_eq!( tree.to_string(), "0( 2 )" );
        assert_eq!( tree.pop_front(), Some( Tree::new(2) ));
        assert_eq!( tree.to_string(), "0" );
        assert_eq!( tree.pop_front(), None );
    }

    #[test] fn pop_back() {
        use crate::Tree;

        let mut tree = Tree::new(0);
        tree.push_back( Tree::new(1) );
        tree.push_back( Tree::new(2) );
        assert_eq!( tree.to_string(), "0( 1 2 )" );
        assert_eq!( tree.pop_back(), Some( Tree::new(2) ));
        assert_eq!( tree.to_string(), "0( 1 )" );
        assert_eq!( tree.pop_back(), Some( Tree::new(1) ));
        assert_eq!( tree.to_string(), "0" );
        assert_eq!( tree.pop_back(), None );
    }
    #[test] fn from_tuple() {
        use crate::{Tree, tr};

        let tree = Tree::<i32>::from_tuple(( 0, (1,2), (3,4) ));
        assert_eq!( tree, tr(0) /(tr(1)/tr(2)) /(tr(3)/tr(4)) );
        assert_eq!( tree.to_string(), "0( 1( 2 ) 3( 4 ) )" );
    }
}