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
//! A generic `Text` implementation for chaining underlying chunks by using a
//! linked list of `Datum`s provided by a `DatumAllocator`.  This is useful when
//! heap allocation isn't available (or desired) and a `Parser`'s
//! `DatumAllocator` is the only available (or desired) dynamic allocator.

use core::ops::Deref;
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};

use crate::text;
use crate::{Text, TextBase, TextChunk, TextConcat, Datum, DerefTryMut};
use crate::datum::premade::DatumMutRef;
use crate::parser::{DatumAllocator, AllocError};


/// A generic `Text` implementation for chaining underlying chunks by using a
/// linked list of `Datum`s provided by a `DatumAllocator`.  The chunk type can
/// be any `TextChunk`.  This is useful when heap allocation isn't available (or
/// desired) and a `Parser`'s `DatumAllocator` is the only available (or
/// desired) dynamic allocator.
///
/// It is a `TextConcat` and so can be used with `Parser`s as the text type of
/// `Datum`s, where a `Parser` allocates the same type of `Datum` as this
/// references as its links.
///
/// [`DatumMutRef`] is used as the `Datum` reference type used as the links,
/// because it is the type for allocating `Datum`s from arrays instead of the
/// heap.  This effectively restricts the genericity of what `Datum` types can
/// be used to only being generic over the "extra" type, which is fine because
/// this isn't intended for any other types.
#[derive(Debug)]
pub struct TextDatumList<'d, C, ET> {
    chunk: C,
    next: Option<DatumMutRef<'d, Self, ET>>,
}


impl<C, ET> From<C> for TextDatumList<'_, C, ET>
    where C: TextChunk,
{
    #[inline]
    fn from(chunk: C) -> Self {
        Self {
            chunk,
            next: None,
        }
    }

}


impl<TT, C, ET> PartialEq<TT> for TextDatumList<'_, C, ET>
    where TT: Text,
          C: TextChunk,
{
    #[inline]
    fn eq(&self, other: &TT) -> bool {
        Text::eq(self, other)
    }
}

impl<C, ET> Eq for TextDatumList<'_, C, ET>
    where C: TextChunk,
{}

impl<TT, C, ET> PartialOrd<TT> for TextDatumList<'_, C, ET>
    where TT: Text,
          C: TextChunk,
{
    #[inline]
    fn partial_cmp(&self, other: &TT) -> Option<Ordering> {
        Some(Text::cmp(self, other))
    }
}

impl<C, ET> Ord for TextDatumList<'_, C, ET>
    where C: TextChunk,
{
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        Text::cmp(self, other)
    }
}

impl<C, ET> Hash for TextDatumList<'_, C, ET>
    where C: TextChunk,
{
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        Text::hash(self, state)
    }
}


/// Enables iterating the chunks of a `TextDatumList`, by traversing the linked
/// list of them.
///
/// This type is its own `iter::chunks::State` because the links are contained
/// in it.
impl<C, ET> text::iter::chunks::State for TextDatumList<'_, C, ET>
    where C: TextChunk,
{
    type Chunk = C;

    fn next(&self) -> Option<(&Self::Chunk, Option<&Self>)> {
        Some((&self.chunk,
              self.next.as_ref().map(
                  |datum_ref|
                  if let Datum::Text(next) = Deref::deref(datum_ref) {
                      next
                  } else {
                      // Note: This won't ever fail because we always construct the
                      // `Datum::Text` variant.
                      unreachable!()
                  })))
    }
}


impl<C, ET> TextBase for TextDatumList<'_, C, ET>
    where C: TextChunk,
{
    type Pos = C::Pos;

    #[inline]
    fn empty() -> Self {
        Self::from(C::empty())
    }

    #[inline]
    fn is_empty(&self) -> bool {
        self.iter_chunks().all(TextBase::is_empty)
    }
}

impl<C, ET> Text for TextDatumList<'_, C, ET>
    where C: TextChunk,
{
    type Chunk = C;
    type IterChunksState = Self;

    #[inline]
    fn iter_chunks_state(&self) -> Option<&Self::IterChunksState> {
        Some(self)
    }
}


/// Enables `TextDatumList` to be used with `Parser`s as the produced `Datum`s'
/// text type.  This can only be used with `Parser`s that allocate the same type
/// of `Datum` that `Self` uses, which is required by this `impl`'s `where`
/// bounds.
impl<'d, DA, C, ET> TextConcat<DA> for TextDatumList<'d, C, ET>
    where C: TextChunk,
          DA: DatumAllocator<TT = Self, ET = ET, DR = DatumMutRef<'d, Self, ET>>,
{
    /// Link two `TextDatumList`s to form a single `TextDatumList` that
    /// represents their logical concatenation.  Unlike most implementations of
    /// `TextConcat`, this does use the `datum_alloc` argument to allocate the
    /// new `Datum`s that are used as the storage of the nodes of our
    /// linked-list approach.
    fn concat(mut self, other: Self, datum_alloc: &mut DA) -> Result<Self, AllocError>
    {
        // If either is empty, optimize.
        if self.is_empty() {
            return Ok(other);
        } else if other.is_empty() {
            return Ok(self)
        }

        // Find the end of the linked-list and link `other` from it.
        let mut cur = &mut self;
        loop {
            match &mut cur.next {
                Some(dr) =>
                    if let Some(Datum::Text(next)) = DerefTryMut::get_mut(dr) {
                        cur = next;
                    } else {
                        // Note: This won't ever fail because we never share the
                        // datum references and always construct the
                        // `Datum::Text` variant.
                        unreachable!()
                    }
                last_next @ None => {
                    *last_next = Some(datum_alloc.new_datum(Datum::Text(other))?);
                    break Ok(self)
                }
            }
        }
    }
}


#[cfg(test)]
mod tests {
    // TODO
}