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
//! This is **not** a public api.
//!
//! Make `Cons` flat.

use cons::*;

/// Convert
///
///    [A, B, [C, Nil], [[D, Nil], Nil], Nil]
/// to [A, B, C, D, Nil]
///
///
/// Recursion trait for `Tail`.
pub trait Fix: Node + Sized {
    // type Fixed: Fix<Fixed = <Self as Fix>::Fixed>;
    type Fixed: ValidNode;

    fn fix(self) -> Self::Fixed;
}

/// Fixed `Tail`.
pub type Fixed<T> = <T as Fix>::Fixed;

/// Recursion trait for `Head`.
pub trait FixHead {
    type Fixed: ValidNode;
    fn fix_head(self) -> Self::Fixed;
}

/// Fixed `Head`.
pub type FixedHead<T> = <T as FixHead>::Fixed;

/// Termination of recursion for `Head`.
impl<V> FixHead for V
where
    V: ValidHead,
{
    type Fixed = Cons<Self, Nil>;
    #[inline(always)]
    fn fix_head(self) -> Self::Fixed {
        Cons {
            head: self,
            tail: Nil,
        }
    }
}

impl<H: FixHead, T: Node> FixHead for Cons<H, T>
where
    FixedHead<H>: Append<Fixed<T>>,
    T: Fix,
{
    type Fixed = ConcatFixed<H, T>;
    #[inline(always)]
    fn fix_head(self) -> Self::Fixed {
        self.head.fix_head().append(self.tail.fix())
    }
}

/// Concat `Head` and `Tail` dropping `Nil`.
pub type Concat<Head, Tail> = <Head as Append<Tail>>::Output;

pub type ConcatFixed<Head, Tail> = Concat<FixedHead<Head>, Fixed<Tail>>;

/// Termination of recursion for `Tail`.
impl Fix for Nil {
    type Fixed = Nil;
    #[inline(always)]
    fn fix(self) -> Self {
        self
    }
}

impl<Head, Tail> Fix for Cons<Head, Tail>
where
    Head: FixHead,
    Tail: Node + Fix,
    FixedHead<Head>: Append<Fixed<Tail>>,
{
    type Fixed = ConcatFixed<Head, Tail>;
    #[inline(always)]
    fn fix(self) -> Self::Fixed {
        self.head.fix_head().append(self.tail.fix())
    }
}

/// Compile time assertion.
trait AssertFix<Res: Node>: Fix<Fixed = Res>
where
    Res: ValidNode + Fix<Fixed = Res>,
{
}
trait AssertValid: Node + ValidNode + Fix<Fixed = Self> {}

impl AssertValid for Cons<usize, Nil> {}

impl AssertFix<Cons<usize, Nil>> for Cons<Cons<usize, Nil>, Nil> {}
impl AssertFix<Cons<usize, Nil>> for Cons<Cons<Cons<usize, Nil>, Nil>, Nil> {}

impl AssertFix<Cons<usize, Cons<u64, Nil>>> for Cons<Cons<Cons<usize, Nil>, Cons<u64, Nil>>, Nil> {}