im_ternary_tree 0.0.20

Structural sharing ternary tree, i.e. immutable data structure
Documentation
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
//! internal implementation of this tree.
//! this file should be optimized for speed, even to skip some checks repeatedly down the tree,
//! checks can be added at the struct that wraps this tree

mod finger;

use std::cell::Cell;
use std::cmp::Ordering;
use std::fmt;
use std::fmt::{Debug, Display};
use std::hash::{Hash, Hasher};
use std::ops::Index;
use std::sync::Arc;

use crate::util::{divide_ternary_sizes, triple_size};

/// internal tree structure, it can't be empty
#[derive(Clone, Debug)]
pub enum TernaryTree<T> {
  Leaf(T),
  Branch2 {
    size: usize,
    left: Arc<TernaryTree<T>>,
    middle: Arc<TernaryTree<T>>,
  },
  Branch3 {
    size: usize,
    left: Arc<TernaryTree<T>>,
    middle: Arc<TernaryTree<T>>,
    right: Arc<TernaryTree<T>>,
  },
}

use TernaryTree::*;

impl<'a, T> TernaryTree<T>
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  pub fn len(&self) -> usize {
    match self {
      Leaf { .. } => 1,
      Branch2 { size, .. } => *size,
      Branch3 { size, .. } => *size,
    }
  }

  /// never empty in this tree
  pub fn is_empty(&self) -> bool {
    false
  }

  /// make list again from existed
  /// use a factor to control side branches to be shallow with smaller depth
  /// root node has a factor of 2
  pub fn rebuild_list(size: usize, offset: usize, xs: &[TernaryTree<T>], factor: u8) -> Self {
    match size {
      0 => unreachable!("Does not work for empty list"),
      1 => xs[offset].to_owned(),
      2 => Self::rebuild_list_side(size, offset, xs),
      3 => Self::rebuild_list_side(size, offset, xs),
      _ => {
        let side_capacity = triple_size(factor - 1);
        if side_capacity * 2 < size {
          let divided = (side_capacity, size - side_capacity - side_capacity, side_capacity);

          let left = Self::rebuild_list_side(divided.0, offset, xs);
          let middle = Self::rebuild_list(divided.1, offset + divided.0, xs, factor + 1);
          let right = Self::rebuild_list_side(divided.2, offset + divided.0 + divided.1, xs);

          Branch3 {
            size,
            left: Arc::new(left),
            middle: Arc::new(middle),
            right: Arc::new(right),
          }
        } else {
          Self::rebuild_list_side(size, offset, xs)
        }
      }
    }
  }

  // sides have different algorithm
  pub fn rebuild_list_side(size: usize, offset: usize, xs: &[TernaryTree<T>]) -> Self {
    match size {
      0 => unreachable!("Does not work for empty list"),
      1 => xs[offset].to_owned(),
      2 => {
        let left = &xs[offset];
        let middle = &xs[offset + 1];
        Branch2 {
          size: left.len() + middle.len(),
          left: Arc::new(left.to_owned()),
          middle: Arc::new(middle.to_owned()),
        }
      }
      3 => {
        let left = &xs[offset];
        let middle = &xs[offset + 1];
        let right = &xs[offset + 2];
        Branch3 {
          size: 3,
          left: Arc::new(left.to_owned()),
          middle: Arc::new(middle.to_owned()),
          right: Arc::new(right.to_owned()),
        }
      }
      _ => {
        let divided = divide_ternary_sizes(size);

        let left = Self::rebuild_list_side(divided.0, offset, xs);
        let middle = Self::rebuild_list_side(divided.1, offset + divided.0, xs);
        let right = Self::rebuild_list_side(divided.2, offset + divided.0 + divided.1, xs);

        Branch3 {
          size: left.len() + middle.len() + right.len(),
          left: Arc::new(left),
          middle: Arc::new(middle),
          right: Arc::new(right),
        }
      }
    }
  }

  /// turn into a representation in triples, with `_` for holes
  pub fn format_inline(&self) -> String {
    match self {
      Leaf(value) => value.to_string(),
      Branch2 { left, middle, .. } => {
        // TODO maybe need more informations here
        format!("({} {})", left.format_inline(), middle.format_inline())
      }
      Branch3 { left, middle, right, .. } => {
        // TODO maybe need more informations here
        format!("({} {} {})", left.format_inline(), middle.format_inline(), right.format_inline())
      }
    }
  }

  pub fn find_index(&self, f: Arc<dyn Fn(&T) -> bool>) -> Option<i64> {
    self.find_index_by(&*f)
  }

  fn find_index_by<F>(&self, f: &F) -> Option<i64>
  where
    F: Fn(&T) -> bool + ?Sized,
  {
    let mut stack: Vec<(&TernaryTree<T>, i64)> = vec![(self, 0)];
    while let Some((node, base)) = stack.pop() {
      match node {
        Leaf(value) => {
          if f(value) {
            return Some(base);
          }
        }
        Branch2 { left, middle, .. } => {
          stack.push((middle, base + left.len() as i64));
          stack.push((left, base));
        }
        Branch3 { left, middle, right, .. } => {
          stack.push((right, base + left.len() as i64 + middle.len() as i64));
          stack.push((middle, base + left.len() as i64));
          stack.push((left, base));
        }
      }
    }
    None
  }

  pub fn index_of(&self, item: &T) -> Option<usize> {
    let mut stack: Vec<(&TernaryTree<T>, usize)> = vec![(self, 0)];
    while let Some((node, base)) = stack.pop() {
      match node {
        Leaf(value) => {
          if item == value {
            return Some(base);
          }
        }
        Branch2 { left, middle, .. } => {
          stack.push((middle, base + left.len()));
          stack.push((left, base));
        }
        Branch3 { left, middle, right, .. } => {
          stack.push((right, base + left.len() + middle.len()));
          stack.push((middle, base + left.len()));
          stack.push((left, base));
        }
      }
    }
    None
  }

  // index from end, returns 0 when item found at end of original list
  pub fn last_index_of(&self, item: &T) -> Option<usize> {
    let mut stack: Vec<(&TernaryTree<T>, usize)> = vec![(self, 0)];
    while let Some((node, base)) = stack.pop() {
      match node {
        Leaf(value) => {
          if item == value {
            return Some(base);
          }
        }
        Branch2 { left, middle, .. } => {
          stack.push((left, base + middle.len()));
          stack.push((middle, base));
        }
        Branch3 { left, middle, right, .. } => {
          stack.push((left, base + middle.len() + right.len()));
          stack.push((middle, base + right.len()));
          stack.push((right, base));
        }
      }
    }
    None
  }

  /// recursively check structure
  pub fn eq_shape(&self, ys: &Self) -> bool {
    if self.len() != ys.len() {
      return false;
    }

    match (self, ys) {
      (Leaf(value), Leaf(v2)) => value == v2,
      (
        Branch2 { left, middle, .. },
        Branch2 {
          left: left2,
          middle: middle2,
          ..
        },
      ) => left.eq_shape(left2) && middle.eq_shape(middle2),
      (
        Branch3 { left, middle, right, .. },
        Branch3 {
          left: left2,
          middle: middle2,
          right: right2,
          ..
        },
      ) => left.eq_shape(left2) && middle.eq_shape(middle2) && right.eq_shape(right2),

      (_, _) => false,
    }
  }

  /// internal usages for rebuilding tree
  fn to_leaves(&self) -> Vec<TernaryTree<T>> {
    let mut acc: Vec<TernaryTree<T>> = Vec::with_capacity(self.len());
    let counter: Cell<usize> = Cell::new(0);
    write_leaves(self, &mut acc, &counter);
    assert_eq!(acc.len(), self.len());
    acc
  }

  /// get with reference, but index is not checked, returns last element if too large
  pub fn ref_get(&self, idx: usize) -> &T {
    // println!("get: {} {}", self.format_inline(), idx);
    // if idx >= self.len() {
    //   println!("get from out of bound: {} {}", idx, self.len());
    //   return None;
    // }
    match self {
      Branch3 { left, middle, right, .. } => {
        let base = left.len();
        if idx < base {
          return left.ref_get(idx);
        }
        let idx_in_middle = idx - base;
        if idx_in_middle < middle.len() {
          middle.ref_get(idx_in_middle)
        } else {
          right.ref_get(idx_in_middle - middle.len())
        }
      }
      Branch2 { left, middle, .. } => {
        let base = left.len();
        if idx < base {
          left.ref_get(idx)
        } else {
          middle.ref_get(idx - base)
        }
      }
      Leaf(value) => value,
    }
  }

  /// get am element via drilling down the branch with a mutable loop,
  /// supposed to be faster than `ref_get` since it's more like VM instructions
  pub fn loop_get(&'a self, original_idx: usize) -> &'a T {
    let mut tree_parent = self;
    let mut idx = original_idx;
    loop {
      match tree_parent {
        Leaf(value) => {
          return value;
        }
        Branch2 { left, middle, .. } => {
          let left_size = left.len();
          if idx < left_size {
            tree_parent = left;
          } else {
            tree_parent = middle;
            idx -= left_size;
          }
        }
        Branch3 { left, middle, right, .. } => {
          let left_size = left.len();
          if idx < left_size {
            tree_parent = left;
            continue;
          }
          idx -= left_size;

          let middle_size = middle.len();

          if idx < middle_size {
            tree_parent = middle;
            continue;
          }

          tree_parent = right;
          idx -= middle_size;
        }
      }
    }
  }

  pub fn loop_first(&'a self) -> &'a T {
    let mut tree_parent = self;
    loop {
      match tree_parent {
        Leaf(value) => return value,
        Branch2 { left, .. } => tree_parent = left,
        Branch3 { left, .. } => tree_parent = left,
      }
    }
  }

  pub fn loop_last(&'a self) -> &'a T {
    let mut tree_parent = self;
    loop {
      match tree_parent {
        Leaf(value) => return value,
        Branch2 { middle, .. } => tree_parent = middle,
        Branch3 { right, .. } => tree_parent = right,
      }
    }
  }

  pub fn first(&self) -> Option<&T> {
    match self {
      Leaf(value) => Some(value),
      Branch2 { left, .. } => left.first(),
      Branch3 { left, .. } => left.first(),
    }
  }

  pub fn last(&self) -> Option<&T> {
    match self {
      Leaf(value) => Some(value),
      Branch2 { middle, .. } => middle.last(),
      Branch3 { right, .. } => right.last(),
    }
  }

  // insert new element at position, does not check whether the index is out of bound
  pub fn assoc(&self, idx: usize, item: T) -> Result<Self, String> {
    match self {
      Leaf { .. } => {
        if idx == 0 {
          Ok(Leaf(item))
        } else {
          Err(format!("Cannot assoc leaf into index {idx}"))
        }
      }
      Branch2 { left, middle, size, .. } => {
        if idx < left.len() {
          let changed_branch = left.assoc(idx, item)?;
          Ok(Branch2 {
            size: size.to_owned(),
            left: Arc::new(changed_branch),
            middle: middle.to_owned(),
          })
        } else {
          let changed_branch = middle.assoc(idx - left.len(), item)?;
          Ok(Branch2 {
            size: size.to_owned(),
            left: left.to_owned(),
            middle: Arc::new(changed_branch),
          })
        }
      }
      Branch3 {
        left, middle, right, size, ..
      } => {
        if idx < left.len() {
          let changed_branch = left.assoc(idx, item)?;
          Ok(Branch3 {
            size: size.to_owned(),
            left: Arc::new(changed_branch),
            middle: middle.to_owned(),
            right: right.to_owned(),
          })
        } else if idx < left.len() + middle.len() {
          let changed_branch = middle.assoc(idx - left.len(), item)?;
          Ok(Branch3 {
            size: size.to_owned(),
            left: left.to_owned(),
            middle: Arc::new(changed_branch),
            right: right.to_owned(),
          })
        } else {
          let changed_branch = right.assoc(idx - left.len() - middle.len(), item)?;
          Ok(Branch3 {
            size: size.to_owned(),
            left: left.to_owned(),
            middle: middle.to_owned(),
            right: Arc::new(changed_branch),
          })
        }
      }
    }
  }

  // remove element from give position, does not check whether the index is out of bound
  pub fn dissoc(&self, idx: usize) -> Result<Self, String> {
    match self {
      Leaf { .. } => unreachable!("dissoc should be handled at branches"),
      Branch2 { left, middle, size, .. } => {
        if idx < left.len() {
          if left.len() == 1 {
            Ok((**middle).to_owned())
          } else {
            let changed_branch = left.dissoc(idx)?;
            Ok(Branch2 {
              size: *size - 1,
              left: Arc::new(changed_branch),
              middle: middle.to_owned(),
            })
          }
        } else if middle.len() == 1 {
          Ok((**left).to_owned())
        } else {
          let changed_branch = middle.dissoc(idx - left.len())?;
          Ok(Branch2 {
            size: *size - 1,
            left: left.to_owned(),
            middle: Arc::new(changed_branch),
          })
        }
      }

      Branch3 {
        left, middle, right, size, ..
      } => {
        if left.len() + middle.len() + right.len() != *size {
          return Err(format!(
            "tree {} does not match sum from branch sizes {}",
            self.format_inline(),
            self.len()
          ));
        }

        if idx < left.len() {
          if left.len() == 1 {
            Ok(Branch2 {
              size: *size - 1,
              left: middle.to_owned(),
              middle: right.to_owned(),
            })
          } else {
            let changed_branch = left.dissoc(idx)?;
            Ok(Branch3 {
              size: *size - 1,
              left: Arc::new(changed_branch),
              middle: middle.to_owned(),
              right: right.to_owned(),
            })
          }
        } else if idx < left.len() + middle.len() {
          if middle.len() == 1 {
            Ok(Branch2 {
              size: *size - 1,
              left: left.to_owned(),
              middle: right.to_owned(),
            })
          } else {
            let changed_branch = middle.dissoc(idx - left.len())?;
            Ok(Branch3 {
              size: *size - 1,
              left: left.to_owned(),
              middle: Arc::new(changed_branch),
              right: right.to_owned(),
            })
          }
        } else if right.len() == 1 {
          Ok(Branch2 {
            size: *size - 1,
            left: left.to_owned(),
            middle: middle.to_owned(),
          })
        } else {
          let changed_branch = right.dissoc(idx - left.len() - middle.len())?;
          Ok(Branch3 {
            size: *size - 1,
            left: left.to_owned(),
            middle: middle.to_owned(),
            right: Arc::new(changed_branch),
          })
        }
      }
    }
  }
  pub fn rest(&self) -> Result<Self, String> {
    if self.len() == 1 {
      Err(String::from("unexpected leaf for rest"))
    } else {
      self.dissoc(0)
    }
  }
  pub fn butlast(&self) -> Result<Self, String> {
    if self.len() == 1 {
      Err(String::from("unexpected leaf for butlast"))
    } else {
      self.dissoc(self.len() - 1)
    }
  }

  pub fn insert_before(&self, idx: usize, item: T) -> Result<Self, String> {
    match self {
      Leaf { .. } => Ok(Branch2 {
        size: 2,
        left: Arc::new(Leaf(item)),
        middle: Arc::new(self.to_owned()),
      }),

      Branch2 { left, middle, size, .. } => {
        if *size < 2 {
          unreachable!("no branch2 with size smaller than 2")
        }

        if *size == 2 {
          if idx == 0 {
            return Ok(Branch3 {
              size: 3,
              left: Arc::new(Leaf(item)),
              middle: left.to_owned(),
              right: middle.to_owned(),
            });
          } else if idx == 1 {
            return Ok(Branch3 {
              size: 3,
              left: left.to_owned(),
              middle: Arc::new(Leaf(item)),
              right: middle.to_owned(),
            });
          } else {
            return Err(String::from("cannot insert before position 2 since only 2 elements here"));
          }
        }

        if left.len() + middle.len() != *size {
          return Err(String::from("tree.size does not match sum case branch sizes"));
        }

        // echo "picking: ", idx, " ", left.len(), " ", middle.len(), " ", right.len()

        if idx == 0 {
          return Ok(Branch3 {
            size: *size + 1,
            left: Arc::new(Leaf(item)),
            middle: left.to_owned(),
            right: middle.to_owned(),
          });
        }

        if idx < left.len() {
          let changed_branch = left.insert_before(idx, item)?;
          Ok(Branch2 {
            size: *size + 1,
            left: Arc::new(changed_branch),
            middle: middle.to_owned(),
          })
        } else {
          let changed_branch = middle.insert_before(idx - left.len(), item)?;

          Ok(Branch2 {
            size: *size + 1,
            left: left.to_owned(),
            middle: Arc::new(changed_branch),
          })
        }
      }
      Branch3 {
        left, middle, right, size, ..
      } => {
        if *size < 3 {
          unreachable!("no branch3 with size smaller than 3")
        }

        if left.len() + middle.len() + right.len() != *size {
          return Err(String::from("tree.size does not match sum case branch sizes"));
        }

        // echo "picking: ", idx, " ", left.len(), " ", middle.len(), " ", right.len()

        if idx == 0 && left.len() >= middle.len() && left.len() >= right.len() {
          return Ok(Branch2 {
            size: *size + 1,
            left: Arc::new(Leaf(item)),
            middle: Arc::new(self.to_owned()),
          });
        }

        if idx == 0 && right.is_empty() && middle.len() >= right.len() {
          return Ok(Branch3 {
            size: *size + 1,
            left: Arc::new(Leaf(item)),
            middle: left.to_owned(),
            right: middle.to_owned(),
          });
        }

        if idx < left.len() {
          let changed_branch = left.insert_before(idx, item)?;
          Ok(Branch3 {
            size: *size + 1,
            left: Arc::new(changed_branch),
            middle: middle.to_owned(),
            right: right.to_owned(),
          })
        } else if idx < left.len() + middle.len() {
          let changed_branch = middle.insert_before(idx - left.len(), item)?;

          Ok(Branch3 {
            size: *size + 1,
            left: left.to_owned(),
            middle: Arc::new(changed_branch),
            right: right.to_owned(),
          })
        } else {
          let changed_branch = right.insert_before(idx - left.len() - middle.len(), item)?;

          Ok(Branch3 {
            size: *size + 1,
            left: left.to_owned(),
            middle: middle.to_owned(),
            right: Arc::new(changed_branch),
          })
        }
      }
    }
  }

  pub fn insert_after(&self, idx: usize, item: T) -> Result<Self, String> {
    match self {
      Leaf { .. } => Ok(Branch2 {
        size: 2,
        left: Arc::new(self.to_owned()),
        middle: Arc::new(Leaf(item)),
      }),

      Branch2 { left, middle, size, .. } => {
        if *size < 2 {
          unreachable!("no branch2 with size smaller than 2")
        }

        if *size == 2 {
          if idx == 0 {
            return Ok(Branch3 {
              size: 3,
              left: left.to_owned(),
              middle: Arc::new(Leaf(item)),
              right: middle.to_owned(),
            });
          }
          if idx == 1 {
            return Ok(Branch3 {
              size: 3,
              left: left.to_owned(),
              middle: middle.to_owned(),
              right: Arc::new(Leaf(item)),
            });
          } else {
            return Err(String::from("cannot insert after position 2 since only 2 elements here"));
          }
        }

        if left.len() + middle.len() != *size {
          return Err(String::from("tree.size does not match sum case branch sizes"));
        }

        // echo "picking: ", idx, " ", left.len(), " ", middle.len(), " ", right.len()

        if idx == *size - 1 {
          return Ok(Branch3 {
            size: *size + 1,
            left: left.to_owned(),
            middle: middle.to_owned(),
            right: Arc::new(Leaf(item)),
          });
        }

        if idx < left.len() {
          let changed_branch = left.insert_after(idx, item)?;
          Ok(Branch2 {
            size: *size + 1,
            left: Arc::new(changed_branch),
            middle: middle.to_owned(),
          })
        } else {
          let changed_branch = middle.insert_after(idx - left.len(), item)?;

          Ok(Branch2 {
            size: *size + 1,
            left: left.to_owned(),
            middle: Arc::new(changed_branch),
          })
        }
      }
      Branch3 {
        left, middle, right, size, ..
      } => {
        if *size < 3 {
          unreachable!("no branch3 with size smaller than 3")
        }

        if left.len() + middle.len() + right.len() != *size {
          return Err(String::from("tree.size does not match sum case branch sizes"));
        }

        // echo "picking: ", idx, " ", left.len(), " ", middle.len(), " ", right.len()

        if idx == *size - 1 && right.len() >= middle.len() && right.len() >= left.len() {
          return Ok(Branch2 {
            size: *size + 1,
            left: Arc::new(self.to_owned()),
            middle: Arc::new(Leaf(item)),
          });
        }

        if idx == *size - 1 && right.is_empty() && middle.len() >= left.len() {
          return Ok(Branch3 {
            size: *size + 1,
            left: left.to_owned(),
            middle: middle.to_owned(),
            right: Arc::new(Leaf(item)),
          });
        }

        if idx < left.len() {
          let changed_branch = left.insert_after(idx, item)?;
          Ok(Branch3 {
            size: *size + 1,
            left: Arc::new(changed_branch),
            middle: middle.to_owned(),
            right: right.to_owned(),
          })
        } else if idx < left.len() + middle.len() {
          let changed_branch = middle.insert_after(idx - left.len(), item)?;

          Ok(Branch3 {
            size: *size + 1,
            left: left.to_owned(),
            middle: Arc::new(changed_branch),
            right: right.to_owned(),
          })
        } else {
          let changed_branch = right.insert_after(idx - left.len() - middle.len(), item)?;

          Ok(Branch3 {
            size: *size + 1,
            left: left.to_owned(),
            middle: middle.to_owned(),
            right: Arc::new(changed_branch),
          })
        }
      }
    }
  }

  pub fn assoc_before(&self, idx: usize, item: T) -> Result<Self, String> {
    self.insert_before(idx, item)
  }
  pub fn assoc_after(&self, idx: usize, item: T) -> Result<Self, String> {
    self.insert_after(idx, item)
  }
  // this function mutates original tree to make it more balanced
  pub fn force_inplace_balancing(&mut self) -> Result<(), String> {
    let ys = self.to_leaves();
    *self = Self::rebuild_list(ys.len(), 0, &ys, 2);
    Ok(())
  }

  pub fn unshift(&self, item: T) -> Self {
    self.prepend(item)
  }
  pub fn prepend(&self, item: T) -> Self {
    match self.insert_before(0, item) {
      Ok(v) => v,
      Err(e) => unreachable!("{}", e),
    }
  }
  pub fn concat(raw: &[TernaryTree<T>]) -> Self {
    if raw.is_empty() {
      unreachable!("concat requires at least one non-empty tree");
    }
    let mut ys: Vec<TernaryTree<T>> = Vec::with_capacity(raw.len());
    for x in raw {
      ys.push(x.to_owned())
    }
    Self::concat_layers(&mut ys)
  }

  /// This was the old implementation of concat. It is not balanced and does not work with empty lists.
  pub fn concat_dumb(raw: &[TernaryTree<T>]) -> Self {
    let mut xs_groups: Vec<TernaryTree<T>> = Vec::with_capacity(raw.len());
    for x in raw {
      xs_groups.push(x.to_owned());
    }
    match xs_groups.len() {
      0 => unreachable!("does not work with empty list in ternary-tree"),
      1 => xs_groups[0].to_owned(),
      2 => {
        let left = xs_groups[0].to_owned();
        let middle = xs_groups[1].to_owned();
        TernaryTree::Branch2 {
          size: left.len() + middle.len(),
          left: Arc::new(left),
          middle: Arc::new(middle),
        }
      }
      3 => {
        let left = xs_groups[0].to_owned();
        let middle = xs_groups[1].to_owned();
        let right = xs_groups[2].to_owned();
        TernaryTree::Branch3 {
          size: left.len() + middle.len() + right.len(),
          left: Arc::new(left),
          middle: Arc::new(middle),
          right: Arc::new(right),
        }
      }
      _ => {
        let mut ys: Vec<TernaryTree<T>> = vec![];
        for x in xs_groups {
          ys.push(x.to_owned())
        }
        Self::rebuild_list(ys.len(), 0, &ys, 2)
      }
    }
  }

  /// a balanced way of building a tree from a list of trees
  pub fn concat_layers(raw: &mut Vec<TernaryTree<T>>) -> Self {
    if raw.is_empty() {
      unreachable!("concat_layers requires at least one tree and cannot process an empty list");
    }

    while raw.len() > 1 {
      let mut next_layer = Vec::with_capacity(raw.len().div_ceil(3));
      let mut iter = std::mem::take(raw).into_iter();
      while let Some(left) = iter.next() {
        if let Some(middle) = iter.next() {
          if let Some(right) = iter.next() {
            next_layer.push(Branch3 {
              size: left.len() + middle.len() + right.len(),
              left: Arc::new(left),
              middle: Arc::new(middle),
              right: Arc::new(right),
            });
          } else {
            next_layer.push(Branch2 {
              size: left.len() + middle.len(),
              left: Arc::new(left),
              middle: Arc::new(middle),
            });
          }
        } else {
          next_layer.push(left);
        }
      }
      *raw = next_layer;
    }
    raw.pop().expect("concat_layers should leave one root node")
  }

  pub fn check_structure(&self) -> Result<(), String> {
    match self {
      Leaf { .. } => Ok(()),
      Branch2 { left, middle, size } => {
        if *size != left.len() + middle.len() {
          return Err(format!("Bad size at branch {}", self.format_inline()));
        }

        left.check_structure()?;
        middle.check_structure()?;

        Ok(())
      }
      Branch3 { left, middle, right, size } => {
        if *size != left.len() + middle.len() + right.len() {
          return Err(format!("Bad size at branch {}", self.format_inline()));
        }

        left.check_structure()?;
        middle.check_structure()?;
        right.check_structure()?;

        Ok(())
      }
    }
  }

  /// excludes value at end_idx, kept aligned with JS & Clojure
  /// does not check at inside
  pub fn take_left(&self, end_idx: usize) -> Result<Self, String> {
    // echo "take_left {tree.formatListInline}: {start_idx}..{end_idx}"

    match self {
      Leaf { .. } => {
        if end_idx == 1 {
          Ok(self.to_owned())
        } else {
          Err(format!("Invalid take_left for a leaf: {end_idx}"))
        }
      }

      Branch2 { left, middle, size } => {
        if end_idx == *size {
          Ok(self.to_owned())
        } else if end_idx <= left.len() {
          left.take_left(end_idx)
        } else {
          // take whole left and part of middle
          let left_len = left.len();
          let middle_cut = middle.take_left(end_idx - left_len)?;
          Ok(TernaryTree::Branch2 {
            size: left_len + middle_cut.len(),
            left: left.to_owned(),
            middle: Arc::new(middle_cut),
          })
        }
      }
      Branch3 { left, right, middle, size } => {
        let base1 = left.len();
        let base2 = base1 + middle.len();
        if end_idx == *size {
          Ok(self.to_owned())
        } else if end_idx <= base1 {
          left.take_left(end_idx)
        } else if end_idx <= base2 {
          // take whole left and part of middle
          let middle_cut = middle.take_left(end_idx - base1)?;
          Ok(TernaryTree::Branch2 {
            size: left.len() + middle_cut.len(),
            left: left.to_owned(),
            middle: Arc::new(middle_cut),
          })
        } else {
          let right_cut = right.take_left(end_idx - base2)?;
          Ok(TernaryTree::Branch3 {
            size: left.len() + middle.len() + right_cut.len(),
            left: left.to_owned(),
            middle: middle.clone(),
            right: Arc::new(right_cut),
          })
        }
      }
    }
  }

  /// excludes value at end_idx, kept aligned with JS & Clojure
  /// does not check at inside
  pub fn take_right(&self, start_idx: usize) -> Result<Self, String> {
    // println!("take right {}: {start_idx}", self.format_inline());

    match self {
      Leaf { .. } => {
        if start_idx == 0 {
          Ok(self.to_owned())
        } else {
          Err(format!("Invalid take_right range for a leaf: {start_idx}",))
        }
      }

      Branch2 { left, middle, .. } => {
        if start_idx == 0 {
          Ok(self.to_owned())
        } else if start_idx >= left.len() {
          // echo "sizes: {left.len()} {middle.len()} {right.len()}"
          let left_len = left.len();
          middle.take_right(start_idx - left_len)
        } else {
          // take part of left and whole middle
          let left_cut = left.take_right(start_idx)?;
          Ok(TernaryTree::Branch2 {
            size: left_cut.len() + middle.len(),
            left: Arc::new(left_cut),
            middle: middle.to_owned(),
          })
        }
      }
      Branch3 { left, right, middle, .. } => {
        let base1 = left.len();
        let base2 = base1 + middle.len();
        if start_idx == 0 {
          Ok(self.to_owned())
        } else if start_idx >= base2 {
          right.take_right(start_idx - base2)
        } else if start_idx >= base1 {
          // take part of middle and whole right
          let middle_cut = middle.take_right(start_idx - base1)?;
          Ok(TernaryTree::Branch2 {
            size: middle_cut.len() + right.len(),
            left: Arc::new(middle_cut),
            middle: right.to_owned(),
          })
        } else {
          let left_cut = left.take_right(start_idx)?;
          Ok(TernaryTree::Branch3 {
            size: left_cut.len() + middle.len() + right.len(),
            left: Arc::new(left_cut),
            middle: middle.clone(),
            right: right.to_owned(),
          })
        }
      }
    }
  }

  /// excludes value at end_idx, kept aligned with JS & Clojure
  /// does not check at inside
  pub fn slice(&self, start_idx: usize, end_idx: usize) -> Result<Self, String> {
    // echo "slice {tree.formatListInline}: {start_idx}..{end_idx}"

    match self {
      Leaf { .. } => {
        if start_idx == 0 && end_idx == 1 {
          Ok(self.to_owned())
        } else {
          Err(format!("Invalid slice range for a leaf: {start_idx} {end_idx}"))
        }
      }

      Branch2 { left, middle, size } => {
        let left_size = left.len();
        if start_idx == 0 && end_idx == *size {
          Ok(self.to_owned())
        } else if start_idx >= left_size {
          // echo "sizes: {left_size} {middle.len()} {right.len()}"
          let left_len = left_size;
          middle.slice(start_idx - left_len, end_idx - left_len)
        } else if end_idx <= left_size {
          left.slice(start_idx, end_idx)
        } else if start_idx == 0 {
          // take whole left and part of middle
          let left_len = left_size;
          let middle_cut = middle.take_left(end_idx - left_len)?;
          Ok(TernaryTree::Branch2 {
            size: left_len + middle_cut.len(),
            left: left.to_owned(),
            middle: Arc::new(middle_cut),
          })
        } else if end_idx == *size {
          // take part of left and whole middle
          let left_cut = left.take_right(start_idx)?;
          Ok(TernaryTree::Branch2 {
            size: left_cut.len() + middle.len(),
            left: Arc::new(left_cut),
            middle: middle.to_owned(),
          })
        } else {
          let left_cut = left.take_right(start_idx)?;
          let middle_cut = middle.take_left(end_idx - left_size)?;

          Ok(TernaryTree::Branch2 {
            size: left_cut.len() + middle_cut.len(),
            left: Arc::new(left_cut),
            middle: Arc::new(middle_cut),
          })
        }
      }
      Branch3 { left, right, middle, size } => {
        let base1 = left.len();
        let base2 = base1 + middle.len();
        if start_idx == 0 && end_idx == *size {
          Ok(self.to_owned())
        } else if start_idx >= base2 {
          right.slice(start_idx - base2, end_idx - base2)
        } else if start_idx >= base1 {
          if end_idx <= base1 + middle.len() {
            middle.slice(start_idx - base1, end_idx - base1)
          } else if end_idx == *size {
            // take part of middle and whole right
            let middle_cut = middle.take_right(start_idx - base1)?;
            Ok(TernaryTree::Branch2 {
              size: middle_cut.len() + right.len(),
              left: Arc::new(middle_cut),
              middle: right.to_owned(),
            })
          } else {
            let middle_cut = middle.take_right(start_idx - base1)?;
            let right_cut = right.take_left(end_idx - base2)?;

            Ok(TernaryTree::Branch2 {
              size: middle_cut.len() + right_cut.len(),
              left: Arc::new(middle_cut),
              middle: Arc::new(right_cut),
            })
          }
        } else if end_idx <= base1 {
          left.slice(start_idx, end_idx)
        } else if end_idx <= base2 {
          if start_idx == 0 {
            // take whole left and part of middle
            let middle_cut = middle.take_left(end_idx - base1)?;
            Ok(TernaryTree::Branch2 {
              size: left.len() + middle_cut.len(),
              left: left.to_owned(),
              middle: Arc::new(middle_cut),
            })
          } else {
            let left_cut = left.take_right(start_idx)?;
            let middle_cut = middle.take_left(end_idx - base1)?;

            Ok(TernaryTree::Branch2 {
              size: left_cut.len() + middle_cut.len(),
              left: Arc::new(left_cut),
              middle: Arc::new(middle_cut),
            })
          }
        } else {
          let left_cut = left.take_right(start_idx)?;
          let right_cut = right.take_left(end_idx - base2)?;
          Ok(TernaryTree::Branch3 {
            size: left_cut.len() + middle.len() + right_cut.len(),
            left: Arc::new(left_cut),
            middle: middle.clone(),
            right: Arc::new(right_cut),
          })
        }
      }
    }
  }

  /// split at index, returns a tuple of two trees
  /// this function takes ownership of the tree, and returns two new trees, release the original one
  /// checks need to be done before calling this function
  pub fn split(&self, idx: usize) -> (Self, Self) {
    match self {
      Leaf(_value) => unreachable!("Invalid split index for a leaf: {}", idx),
      Branch2 { left, middle, size } => {
        if idx == 0 {
          unreachable!("Invalid split index 0 for a branch2: {}", idx)
        } else if idx < left.len() {
          let (cut_a, cut_b) = (*left).clone().split(idx);

          (
            cut_a,
            Branch2 {
              size: size - idx,
              left: Arc::new(cut_b),
              middle: middle.to_owned(),
            },
          )
        } else if idx == left.len() {
          ((**left).to_owned(), (**middle).to_owned())
        } else if idx >= *size {
          unreachable!("Invalid split index end for a branch2: {}", idx)
        } else if idx - left.len() < middle.len() {
          let (cut_a, cut_b) = middle.split(idx - left.len());

          (
            Branch2 {
              size: left.len() + cut_a.len(),
              left: left.to_owned(),
              middle: Arc::new(cut_a),
            },
            cut_b,
          )
        } else {
          unreachable!("Invalid split index end for a branch2: {}", idx)
        }
      }
      Branch3 { left, middle, right, size } => {
        if idx == 0 {
          unreachable!("Invalid split index 0 for a branch3: {}", idx)
        } else if idx < left.len() {
          let (cut_a, cut_b) = (*left).split(idx);

          (
            cut_a,
            Branch3 {
              size: size - idx,
              left: Arc::new(cut_b),
              middle: middle.to_owned(),
              right: right.to_owned(),
            },
          )
        } else if idx == left.len() {
          (
            (**left).to_owned(),
            Branch2 {
              size: middle.len() + right.len(),
              left: middle.to_owned(),
              middle: right.to_owned(),
            },
          )
        } else if idx - left.len() < middle.len() {
          let (cut_a, cut_b) = (*middle).split(idx - left.len());
          (
            Branch2 {
              size: left.len() + cut_a.len(),
              left: left.to_owned(),
              middle: Arc::new(cut_a),
            },
            Branch2 {
              size: cut_b.len() + right.len(),
              left: Arc::new(cut_b),
              middle: right.to_owned(),
            },
          )
        } else if idx == left.len() + middle.len() {
          (
            Branch2 {
              size: left.len() + middle.len(),
              left: left.to_owned(),
              middle: middle.to_owned(),
            },
            (**right).to_owned(),
          )
        } else if idx >= *size {
          unreachable!("Invalid split index end for a branch3: {}", idx)
        } else if idx - left.len() == middle.len() {
          (
            Branch2 {
              size: left.len() + middle.len(),
              left: left.to_owned(),
              middle: middle.to_owned(),
            },
            (**right).to_owned(),
          )
        } else {
          let (cut_a, cut_b) = (*right).split(idx - left.len() - middle.len());

          (
            Branch3 {
              size: left.len() + middle.len() + cut_a.len(),
              left: left.to_owned(),
              middle: middle.to_owned(),
              right: Arc::new(cut_a),
            },
            cut_b,
          )
        }
      }
    }
  }

  pub fn reverse(&self) -> Self {
    match self {
      Leaf { .. } => self.to_owned(),
      Branch2 { left, middle, size } => Branch2 {
        size: *size,
        left: Arc::new(middle.reverse()),
        middle: Arc::new(left.reverse()),
      },
      Branch3 { left, middle, right, size } => Branch3 {
        size: *size,

        left: Arc::new(right.reverse()),
        middle: Arc::new(middle.reverse()),
        right: Arc::new(left.reverse()),
      },
    }
  }
  pub fn map<V>(&self, f: Arc<dyn Fn(&T) -> V>) -> TernaryTree<V> {
    match self {
      Leaf(value) => Leaf(f(value)),
      Branch2 { left, middle, size } => Branch2 {
        size: *size,
        left: Arc::new(left.map(f.clone())),
        middle: Arc::new(middle.map(f.clone())),
      },
      Branch3 { left, middle, right, size } => Branch3 {
        size: *size,
        left: Arc::new(left.map(f.clone())),
        middle: Arc::new(middle.map(f.clone())),
        right: Arc::new(right.map(f.clone())),
      },
    }
  }

  pub fn to_vec(&self) -> Vec<T> {
    let mut xs = Vec::with_capacity(self.len());
    for item in self {
      xs.push(item.to_owned());
    }
    xs
  }

  pub fn traverse(&self, f: &mut dyn FnMut(&T)) {
    match self {
      Leaf(value) => f(value),
      Branch2 { left, middle, .. } => {
        left.traverse(f);
        middle.traverse(f);
      }
      Branch3 { left, middle, right, .. } => {
        left.traverse(f);
        middle.traverse(f);
        right.traverse(f);
      }
    }
  }

  pub fn traverse_result<S>(&self, f: &mut dyn FnMut(&T) -> Result<(), S>) -> Result<(), S> {
    match self {
      Leaf(value) => f(value),
      Branch2 { left, middle, .. } => {
        left.traverse_result(f)?;
        middle.traverse_result(f)?;
        Ok(())
      }
      Branch3 { left, middle, right, .. } => {
        left.traverse_result(f)?;
        middle.traverse_result(f)?;
        right.traverse_result(f)?;
        Ok(())
      }
    }
  }

  pub fn iter(&self) -> TernaryTreeIterator<T> {
    TernaryTreeIterator { stack: vec![(self, 0)] }
  }
}

impl<T> Display for TernaryTree<T>
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "(TernaryTree")?;
    for item in self.into_iter() {
      write!(f, " {item}")?;
    }
    write!(f, ")")
  }
}

// experimental code to turn `&TernaryTree<_>` into iterator
impl<'a, T> IntoIterator for &'a TernaryTree<T>
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  type Item = &'a T;
  type IntoIter = TernaryTreeIterator<'a, T>;

  fn into_iter(self) -> Self::IntoIter {
    TernaryTreeIterator { stack: vec![(self, 0)] }
  }
}

pub struct TernaryTreeIterator<'a, T> {
  stack: Vec<(&'a TernaryTree<T>, u8)>,
}

impl<'a, T> Iterator for TernaryTreeIterator<'a, T>
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  type Item = &'a T;
  fn next(&mut self) -> Option<Self::Item> {
    while let Some((node, stage)) = self.stack.pop() {
      match node {
        Leaf(value) => return Some(value),
        Branch2 { left, middle, .. } => {
          if stage == 0 {
            self.stack.push((node, 1));
            self.stack.push((left, 0));
          } else {
            self.stack.push((middle, 0));
          }
        }
        Branch3 { left, middle, right, .. } => {
          if stage == 0 {
            self.stack.push((node, 1));
            self.stack.push((left, 0));
          } else if stage == 1 {
            self.stack.push((node, 2));
            self.stack.push((middle, 0));
          } else {
            self.stack.push((right, 0));
          }
        }
      }
    }
    None
  }
}

impl<T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash> PartialEq for TernaryTree<T> {
  fn eq(&self, ys: &Self) -> bool {
    if self.len() != ys.len() {
      return false;
    }

    for (left, right) in self.iter().zip(ys.iter()) {
      if left != right {
        return false;
      }
    }

    true
  }
}

impl<T> Eq for TernaryTree<T> where T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash {}

impl<T> PartialOrd for TernaryTree<T>
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl<T> Ord for TernaryTree<T>
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  fn cmp(&self, other: &Self) -> Ordering {
    if self.len() == other.len() {
      for (left, right) in self.iter().zip(other.iter()) {
        match left.cmp(right) {
          Ordering::Equal => {}
          a => return a,
        }
      }

      Ordering::Equal
    } else {
      self.len().cmp(&other.len())
    }
  }
}

impl<T> Index<usize> for TernaryTree<T>
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  type Output = T;

  fn index<'b>(&self, idx: usize) -> &Self::Output {
    // println!("get: {} {}", self.format_inline(), idx);
    self.loop_get(idx)
  }
}

impl<T> Hash for TernaryTree<T>
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  fn hash<H: Hasher>(&self, state: &mut H) {
    match self {
      Leaf(value) => {
        value.hash(state);
      }
      Branch2 { left, middle, .. } => {
        left.hash(state);
        middle.hash(state);
      }
      Branch3 { left, middle, right, .. } => {
        left.hash(state);
        middle.hash(state);
        right.hash(state);
      }
    }
  }
}

/// internal function for mutable writing
fn write_leaves<T>(xs: &TernaryTree<T>, acc: &mut Vec<TernaryTree<T>>, counter: &Cell<usize>)
where
  T: Clone + Display + Eq + PartialEq + Debug + Ord + PartialOrd + Hash,
{
  match xs {
    Leaf { .. } => {
      let idx = counter.take();
      acc.push(xs.to_owned());

      counter.replace(idx + 1);
    }
    Branch2 { left, middle, .. } => {
      write_leaves(left, acc, counter);
      write_leaves(middle, acc, counter);
    }
    Branch3 { left, middle, right, .. } => {
      write_leaves(left, acc, counter);
      write_leaves(middle, acc, counter);
      write_leaves(right, acc, counter);
    }
  }
}