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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
use std::fmt::Debug;
use std::marker::PhantomData;
use std::rc::*;
use std::cell::*;
use std::hash::{Hash, Hasher};
use std::collections::*;
use either::Either::{self, Left, Right};
use itertools::Itertools;
use ss_web_utils::js::console;


///////////////////////////////////////////////////////////////////////////////
// CLIENT API
///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Clone)]
pub enum InsertOp<M> {
    InsertBefore {
        new: Vec<M>,
        old: M,
    },
    InsertAfter {
        new: Vec<M>,
        old: M,
    },
    Swap {
        parent: M,
        current: M,
        target: M,
    },
    Append {
        parent: M,
        new: Vec<M>,
    }
}

#[derive(Debug, Clone)]
pub struct Update<S, I> {
    pub old: S,
    pub new: I,
}


pub trait TreeApi<M, SN, SL, IN, IL> {
    fn node_unchanged(&self, new: &IN, old: &SN) -> bool;
    fn node_recyclable(&self, new: &IN, old: &SN) -> bool;
    fn node_update(&self, update: Update<&mut SN, IN>);
    fn node_crate(&self, new: IN) -> SN;

    fn leaf_unchanged(&self, new: &IL, old: &SL) -> bool;
    fn leaf_recyclable(&self, new: &IL, old: &SL) -> bool;
    fn leaf_update(&self, update: Update<&mut SL, IL>);
    fn leaf_crate(&self, new: IL) -> SL;

    fn get_meta(&self, value: Either<&SN, &SL>) -> M;
    fn insert(&self, op: InsertOp<M>);
    fn remove(&self, x: M);
}

///////////////////////////////////////////////////////////////////////////////
// INTERNAL UTILS
///////////////////////////////////////////////////////////////////////////////

fn get_meta_option<'a, M, SN, SL, IN, IL>(
    api: &TreeApi<M, SN, SL, IN, IL>,
    value: Option<&SN>,
) -> Option<M>
where
    M: Clone,
    SN: PartialEq + Debug,
    SL: PartialEq + Debug,
    IN: PartialEq + Debug,
    IL: PartialEq + Debug
{
    match value {
        None => None,
        Some(x) => Some(api.get_meta(Left(x)))
    }
}




///////////////////////////////////////////////////////////////////////////////
// INSERTION TREE
///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Clone, PartialEq)]
pub enum ITree<N, L> {
    Leaf(ILeaf<L>),
    Node(INode<N, L>),
}

#[derive(Debug, Clone, PartialEq)]
pub struct ILeaf<L> {
    data: L
}

#[derive(Debug, Clone, PartialEq)]
pub struct INode<N, L> {
    data: N,
    children: IChildren<N, L>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IChildren<N, L>(pub Vec<ITree<N, L>>);

///////////////////////////////////////////////////////////////////////////////
// INSERTION TREE HELPERS
///////////////////////////////////////////////////////////////////////////////

impl<N, L> ITree<N, L> {
    fn unpack_node_mut(&mut self) -> Option<&mut INode<N, L>> {
        match self {
            ITree::Node(node) => Some(node),
            _ => None
        }
    }
    pub fn new(value: Either<N, L>) -> Self {
        match value {
            Left(data) => ITree::Node(INode {
                data,
                children: IChildren(Vec::new()),
            }),
            Right(data) => ITree::Leaf(ILeaf{
                data,
            }),
        }
    }
    pub fn add_child(&mut self, value: Self) {
        if let Some(node) = self.unpack_node_mut() {
            node.children.0.push(value);
        }
    }
    pub fn get_node_mut(&mut self) -> Option<&mut N> {
        match self {
            ITree::Node(node) => Some(&mut node.data),
            _ => None
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
// SYNC TREE
///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Clone, PartialEq)]
pub enum STree<M, SN, SL, IN, IL>{
    Leaf(SLeaf<M, SN, SL, IN, IL>),
    Node(SNode<M, SN, SL, IN, IL>),
}

#[derive(Debug, Clone, PartialEq)]
pub struct SLeaf<M, SN, SL, IN, IL> {
    mark: PhantomData<(M, SN, SL, IN, IL)>,
    data: SL,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SNode<M, SN, SL, IN, IL> {
    mark: PhantomData<(M, SN, SL, IN, IL)>,
    data: SN,
    children: SChildren<M, SN, SL, IN, IL>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SChildren<M, SN, SL, IN, IL> {
    data: Vec<STree<M, SN, SL, IN, IL>>,
}


///////////////////////////////////////////////////////////////////////////////
// SYNC TREE HELPERS 
///////////////////////////////////////////////////////////////////////////////

impl<M, SN, SL, IN, IL> STree<M, SN, SL, IN, IL> {
    pub fn get_meta(&self, api: &TreeApi<M, SN, SL, IN, IL>) -> M {
        match self {
            STree::Leaf(x) => api.get_meta(Right(&x.data)),
            STree::Node(x) => api.get_meta(Left(&x.data)),
        }
    }
    pub fn to_either(&self) -> Either<&SNode<M, SN, SL, IN, IL>, &SLeaf<M, SN, SL, IN, IL>> {
        match self {
            STree::Leaf(x) => Right(x),
            STree::Node(x) => Left(x),
        }
    }
    pub fn to_either_mut(&mut self) -> Either<&mut SNode<M, SN, SL, IN, IL>, &mut SLeaf<M, SN, SL, IN, IL>> {
        match self {
            STree::Leaf(x) => Right(x),
            STree::Node(x) => Left(x),
        }
    }
    pub fn to_either_inner(&self) -> Either<&SN, &SL> {
        match self {
            STree::Leaf(x) => Right(&x.data),
            STree::Node(x) => Left(&x.data),
        }
    }
    pub fn to_either_inner_mut(&mut self) -> Either<&mut SN, &mut SL> {
        match self {
            STree::Leaf(x) => Right(&mut x.data),
            STree::Node(x) => Left(&mut x.data),
        }
    }
    pub fn unpack_leaf(&self) -> Option<(&SLeaf<M, SN, SL, IN, IL>)> {
        match self {
            STree::Leaf(x) => Some(x),
            STree::Node(_) => None,
        }
    }
    pub fn unpack_node(&self) -> Option<(&SNode<M, SN, SL, IN, IL>)> {
        match self {
            STree::Node(x) => Some(x),
            STree::Leaf(_) => None,
        }
    }
    pub fn unpack_leaf_mut(&mut self) -> Option<(&mut SLeaf<M, SN, SL, IN, IL>)> {
        match self {
            STree::Leaf(x) => Some(x),
            STree::Node(_) => None,
        }
    }
    pub fn unpack_node_mut(&mut self) -> Option<(&mut SNode<M, SN, SL, IN, IL>)> {
        match self {
            STree::Node(x) => Some(x),
            STree::Leaf(_) => None,
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
// INIT IMPLEMENTATION
///////////////////////////////////////////////////////////////////////////////

impl<M, SN, SL, IN, IL> STree<M, SN, SL, IN, IL>
where
    M: PartialEq + Clone + Debug,
    SN: PartialEq + Debug,
    SL: PartialEq + Debug,
    IN: PartialEq + Debug,
    IL: PartialEq + Debug
{
    pub fn from(api: &TreeApi<M, SN, SL, IN, IL>, parent: &M, new: ITree<IN, IL>) -> Self {
        let new = create_tree(api, parent, new);
        let insert_op = InsertOp::Append {
            parent: parent.clone(),
            new: vec![new.get_meta(api)],
        };
        api.insert(insert_op);
        new
    }
}


///////////////////////////////////////////////////////////////////////////////
// SYNC IMPLEMENTATION
///////////////////////////////////////////////////////////////////////////////

impl<M, SN, SL, IN, IL> STree<M, SN, SL, IN, IL>
where
    M: PartialEq + Clone + Debug,
    SN: PartialEq + Debug,
    SL: PartialEq + Debug,
    IN: PartialEq + Debug,
    IL: PartialEq + Debug
{
    pub fn unchanged(&self, api: &TreeApi<M, SN, SL, IN, IL>, other: &ITree<IN, IL>) -> bool {
        match (self, other) {
            (STree::Node(old), ITree::Node(new)) => old.unchanged(api, new),
            (STree::Leaf(old), ITree::Leaf(new)) => old.unchanged(api, new),
            _ => false
        }
    }
    pub fn recyclable(&self, api: &TreeApi<M, SN, SL, IN, IL>, other: &ITree<IN, IL>) -> bool {
        match (self, other) {
            (STree::Node(old), ITree::Node(new)) => old.recyclable(api, new),
            (STree::Leaf(old), ITree::Leaf(new)) => old.recyclable(api, new),
            _ => false
        }
    }
    pub fn sync(&mut self, api: &TreeApi<M, SN, SL, IN, IL>, parent: &M, new: ITree<IN, IL>) {
        match new {
            ITree::Leaf(new) => {
                match self {
                    STree::Leaf(old) => {old.sync(api, parent, new)}
                    old @ STree::Node(_) => {
                        let new_tree = create_tree(api, parent, ITree::Leaf(new));
                        let insert_op = InsertOp::Swap {
                            parent: parent.clone(),
                            current: old.get_meta(api),
                            target: new_tree.get_meta(api),
                        };
                        api.insert(insert_op);
                        *old = new_tree;
                    }
                }
            }
            ITree::Node(new) => {
                match self {
                    STree::Node(old) => {old.sync(api, parent, new)}
                    old @ STree::Leaf(_) => {
                        let new_tree = create_tree(api, parent, ITree::Node(new));
                        let insert_op = InsertOp::Swap {
                            parent: parent.clone(),
                            current: old.get_meta(api),
                            target: new_tree.get_meta(api),
                        };
                        api.insert(insert_op);
                        *old = new_tree;
                    }
                }
            }
        }
    }
}


impl<M, SN, SL, IN, IL> SLeaf<M, SN, SL, IN, IL>
where
    M: PartialEq + Clone + Debug,
    SN: PartialEq + Debug,
    SL: PartialEq + Debug,
    IN: PartialEq + Debug,
    IL: PartialEq + Debug
{
    pub fn unchanged(&self, api: &TreeApi<M, SN, SL, IN, IL>, other: &ILeaf<IL>) -> bool {
        api.leaf_unchanged(&other.data, &self.data)
    }
    pub fn recyclable(&self, api: &TreeApi<M, SN, SL, IN, IL>, other: &ILeaf<IL>) -> bool {
        api.leaf_recyclable(&other.data, &self.data)
    }
    pub fn sync(&mut self, api: &TreeApi<M, SN, SL, IN, IL>, parent: &M, new: ILeaf<IL>) {
        if self.recyclable(api, &new) {
            api.leaf_update(Update {
                old: &mut self.data,
                new: new.data,
            });
        } else {
            unimplemented!()
        }
    }
}

impl<M, SN, SL, IN, IL> SNode<M, SN, SL, IN, IL>
where
    M: PartialEq + Clone + Debug,
    SN: PartialEq + Debug,
    SL: PartialEq + Debug,
    IN: PartialEq + Debug,
    IL: PartialEq + Debug
{
    pub fn unchanged(&self, api: &TreeApi<M, SN, SL, IN, IL>, other: &INode<IN, IL>) -> bool {
        api.node_unchanged(&other.data, &self.data) && self.children.unchanged(api, &other.children)
    }
    pub fn recyclable(&self, api: &TreeApi<M, SN, SL, IN, IL>, other: &INode<IN, IL>) -> bool {
        api.node_recyclable(&other.data, &self.data)
    }
    pub fn sync(&mut self, api: &TreeApi<M, SN, SL, IN, IL>, parent: &M, new: INode<IN, IL>) {
        if self.recyclable(api, &new) {
            api.node_update(Update {
                old: &mut self.data,
                new: new.data,
            });
            self.children.sync(api, &api.get_meta(Left(&self.data)), new.children);
        } else {
            let new_tree = create_tree(api, parent, ITree::Node(new));
            let insert_op = InsertOp::Swap {
                parent: parent.clone(),
                current: api.get_meta(Left(&self.data)),
                target: new_tree.get_meta(api),
            };
            api.insert(insert_op);
            // EXTRACT
            let new_tree = match new_tree {
                STree::Node(node) => node,
                _ => panic!()
            };
            // SAVE
            *self = new_tree;
        }
    }
}


///////////////////////////////////////////////////////////////////////////////
// SYNC IMPLEMENTATION - CHILDREN
///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Clone, PartialEq)]
pub enum ItemType {
    Unchanged,
    Changed,
    New,
}

#[derive(Debug, Clone)]
pub enum Item<S> {
    Unchanged(S),
    Changed(S),
    New(S),
}

impl<S> Item<S> {
    pub fn is_unchanged(&self) -> bool {
        match self {
            Item::Unchanged(_) => true,
            _ => false
        }
    }
    pub fn get_type(&self) -> ItemType {
        match self {
            Item::Unchanged(_) => ItemType::Unchanged,
            Item::Changed(_) => ItemType::Changed,
            Item::New(_) => ItemType::New,
        }
    }
}

#[derive(Debug, Clone)]
pub enum ItemGroup<M, S> {
    Unchanged {
        items: Vec<S>,
    },
    Changed {
        items: Vec<S>,
    },
    New {
        insert_op: InsertOp<M>,
        items: Vec<S>,
    }
}

impl<M, S> ItemGroup<M, S> {
    pub fn extract_items(self) -> Vec<S> {
        match self {
            ItemGroup::Unchanged{items} => items,
            ItemGroup::Changed{items} => items,
            ItemGroup::New{items, ..} => items,
        }
    }
}


impl<M, SN, SL, IN, IL> SChildren<M, SN, SL, IN, IL>
where
    M: PartialEq + Clone + Debug,
    SN: PartialEq + Debug,
    SL: PartialEq + Debug,
    IN: PartialEq + Debug,
    IL: PartialEq + Debug
{
    pub fn unchanged(&self, api: &TreeApi<M, SN, SL, IN, IL>, other: &IChildren<IN, IL>) -> bool {
        if self.data.len() == other.0.len() {
            self.data
                .iter()
                .zip(other.0.iter())
                .all(|(x, y)| x.unchanged(api, y))
        } else {
            false
        }
    }
    pub fn recyclable(&self, api: &TreeApi<M, SN, SL, IN, IL>, other: &IChildren<IN, IL>) -> bool {
        if self.data.len() == other.0.len() {
            self.data
                .iter()
                .zip(other.0.iter())
                .all(|(x, y)| x.recyclable(api, y))
        } else {
            false
        }
    }
    pub fn sync(&mut self, api: &TreeApi<M, SN, SL, IN, IL>, parent: &M, new: IChildren<IN, IL>) {
        let mut xs = new.0
            .into_iter()
            .map(|new| -> Item<STree<M, SN, SL, IN, IL>> {
                let mut unchanged = |olds| remove_item_by(olds, |old| {
                    match (&new, &old) {
                        (ITree::Leaf(x), STree::Leaf(y)) => {
                            api.leaf_unchanged(&x.data, &y.data)
                        }
                        (ITree::Node(x), STree::Node(y)) => {
                            api.node_unchanged(&x.data, &y.data)
                        }
                        _ => false
                    }
                });
                let mut changed = |olds| remove_item_by(olds, |old| {
                    match (&new, &old) {
                        (ITree::Leaf(x), STree::Leaf(y)) => {
                            api.leaf_recyclable(&x.data, &y.data)
                        }
                        (ITree::Node(x), STree::Node(y)) => {
                            api.node_recyclable(&x.data, &y.data)
                        }
                        _ => false
                    }
                });
                if let Some(unchanged) = unchanged(&mut self.data) {
                    Item::Unchanged(unchanged)
                } else {
                    if let Some(mut changed) = changed(&mut self.data) {
                        changed.sync(api, parent, new);
                        Item::Changed(changed)
                    } else {
                        Item::New(create_tree(api, parent, new))
                    }
                }
            })
            .group_by(|x| x.get_type())
            .into_iter()
            .map(|(key, group)| -> (ItemType, Vec<Item<STree<M, SN, SL, IN, IL>>>) {
                (key, group.collect_vec())
            })
            .collect_vec();
        let mut ys: Vec<(ItemType, Vec<M>)> = xs
            .iter()
            .map(|(key, group)| -> (ItemType, Vec<M>) {
                let group_ms = group
                    .iter()
                    .map(|x| -> M {
                        match x {
                            Item::Unchanged(x) => api.get_meta(x.to_either_inner()),
                            Item::Changed(x) => api.get_meta(x.to_either_inner()),
                            Item::New(x) => api.get_meta(x.to_either_inner()),
                        }
                    })
                    .collect_vec();
                (key.clone(), group_ms)
            })
            .collect_vec();
        let mut xs = {
            if self.data.is_empty() && xs.len() == 1 {
                let (key, group) = xs.remove(0);
                let group_ms: Vec<M> = group
                    .iter()
                    .map(|x| -> M {
                        match x {
                            Item::Unchanged(x) => api.get_meta(x.to_either_inner()),
                            Item::Changed(x) => api.get_meta(x.to_either_inner()),
                            Item::New(x) => api.get_meta(x.to_either_inner()),
                        }
                    })
                    .collect_vec();
                let insert_op = InsertOp::Append{
                    parent: parent.clone(),
                    new: group_ms,
                };
                let items: Vec<STree<M, SN, SL, IN, IL>> = group
                    .into_iter()
                    .map(|x| {
                        match x {
                            Item::Unchanged(x) => x,
                            Item::Changed(x) => x,
                            Item::New(x) => x,
                        }
                    })
                    .collect_vec();
                api.insert(insert_op.clone());
                vec![items]
            } else {
                xs  .into_iter()
                    .enumerate()
                    .map(|(ix, (key, group))| -> Vec<STree<M, SN, SL, IN, IL>> {
                        let group_ms: Vec<M> = group
                            .iter()
                            .map(|x| -> M {
                                match x {
                                    Item::Unchanged(x) => api.get_meta(x.to_either_inner()),
                                    Item::Changed(x) => api.get_meta(x.to_either_inner()),
                                    Item::New(x) => api.get_meta(x.to_either_inner()),
                                }
                            })
                            .collect_vec();
                        let insert_op: InsertOp<M> = {
                            if ix == 0 {
                                match ys.get(ix + 1) {
                                    Some((_, after)) => {
                                        match after.first() {
                                            Some(old) => InsertOp::InsertBefore{
                                                new: group_ms,
                                                old: old.clone(),
                                            },
                                            None => panic!()
                                        }
                                    }
                                    None => {
                                        // console::log(format!("length: {:#?}", ys.len()));
                                        // console::log(format!("{:#?}", (ix, (key, group))));
                                        panic!()
                                    }
                                }
                            } else {
                                match ys.get(ix - 1) {
                                    Some((_, before)) => {
                                        match before.last() {
                                            Some(old) => InsertOp::InsertAfter{
                                                new: group_ms,
                                                old: old.clone(),
                                            },
                                            None => panic!()
                                        }
                                    }
                                    None => match ys.get(ix + 1) {
                                        Some((_, after)) => {
                                            match after.first() {
                                                Some(old) => InsertOp::InsertBefore{
                                                    new: group_ms,
                                                    old: old.clone(),
                                                },
                                                None => panic!()
                                            }
                                        }
                                        None => panic!()
                                    }
                                }
                            }
                        };
                        let items: Vec<STree<M, SN, SL, IN, IL>> = group
                            .into_iter()
                            .map(|x| {
                                match x {
                                    Item::Unchanged(x) => x,
                                    Item::Changed(x) => x,
                                    Item::New(x) => x,
                                }
                            })
                            .collect_vec();
                        match &key {
                            ItemType::New => {
                                console::log(format!("tree: {:#?}", (key, insert_op.clone())));
                                api.insert(insert_op.clone());
                            }
                            _ => {}
                        };
                        items
                    })
                    .collect_vec()
            }
        };
        // REMOVE UNUSED
        let mut removed = Vec::new();
        std::mem::swap(&mut self.data, &mut removed);
        for r in removed {
            api.remove(api.get_meta(r.to_either_inner()));
        }
        // SAVE CHANGES
        for mut group in xs {
            self.data.append(&mut group);
        }
    }
}


///////////////////////////////////////////////////////////////////////////////
// SYNC IMPLEMENTATION - CHILDREN HELPERS
///////////////////////////////////////////////////////////////////////////////

pub fn remove_item_by<T: PartialEq>(xs: &mut Vec<T>, f: impl Fn(&T)->bool) -> Option<T> {
    let pos = xs.iter().position(|x| f(x))?;
    Some(xs.remove(pos))
}

pub fn unsafe_unpack_same_type<M, SN, SL, IN, IL>(
    new: ITree<IN, IL>,
    old: STree<M, SN, SL, IN, IL>
) -> Either<(INode<IN, IL>, SNode<M, SN, SL, IN, IL>), (ILeaf<IL>, SLeaf<M, SN, SL, IN, IL>)>
where
    M: PartialEq + Clone + Debug,
    SN: PartialEq + Debug,
    SL: PartialEq + Debug,
    IN: PartialEq + Debug,
    IL: PartialEq + Debug

{
    match new {
        ITree::Leaf(new) => {
            match old {
                STree::Leaf(old) => {
                    Either::Right((new, old))
                }
                old @ STree::Node(_) => {
                    panic!()
                }
            }
        }
        ITree::Node(new) => {
            match old {
                STree::Node(old) => {
                    Either::Left((new, old))
                }
                old @ STree::Leaf(_) => {
                    panic!()
                }
            }
        }
    }   
}

pub fn create_tree<M, SN, SL, IN, IL>(api: &TreeApi<M, SN, SL, IN, IL>, parent: &M, new: ITree<IN, IL>) -> STree<M, SN, SL, IN, IL>
where
    M: PartialEq + Clone + Debug,
    SN: PartialEq + Debug,
    SL: PartialEq + Debug,
    IN: PartialEq + Debug,
    IL: PartialEq + Debug
{
    match new {
        ITree::Leaf(leaf) => {
            let data = api.leaf_crate(leaf.data);
            STree::Leaf(SLeaf {
                mark: PhantomData,
                data,
            })
        }
        ITree::Node(node) => {
            let data = api.node_crate(node.data);
            let mut children_ms = Vec::new();
            let children = node.children.0
                .into_iter()
                .map(|c| {
                    let c = create_tree(api, &api.get_meta(Left(&data)), c);
                    children_ms.push(c.get_meta(api));
                    c
                })
                .collect_vec();
            let children_insert_op = InsertOp::Append {
                parent: api.get_meta(Left(&data)),
                new: children_ms,
            };
            api.insert(children_insert_op);
            let mut children = SChildren{data: children};
            STree::Node(SNode {
                mark: PhantomData,
                data,
                children,
            })
        }
    }
}