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
//! Patterns.

use std::io;
use futures::{self, Future};

pub mod read;
pub mod write;
pub mod combinators {
    //! Patterns to combinate other patterns.

    pub use super::combinators_impl::Then;
    pub use super::combinators_impl::AndThen;
    pub use super::combinators_impl::OrElse;
    pub use super::combinators_impl::Map;
    pub use super::combinators_impl::Chain;
    pub use super::combinators_impl::IterFold;
    pub use super::combinators_impl::BE;
    pub use super::combinators_impl::LE;
    pub use super::combinators_impl::PartialBuf;
    pub use super::combinators_impl::Repeat;
}
mod combinators_impl;

/// Pattern.
pub trait Pattern: Sized {
    /// The value type associated to the pattern.
    type Value;

    /// Takes a closure which maps a `Result<Self::Value>` to a pattern, and
    /// creates a pattern which calls that closure on the evaluation result of `self`.
    fn then<F, P>(self, f: F) -> combinators::Then<Self, F>
        where F: FnOnce(io::Result<Self::Value>) -> P
    {
        combinators_impl::then(self, f)
    }

    /// Takes a closure which maps a value to a pattern, and
    /// creates a pattern which calls that closure if the evaluation of `self` was succeeded.
    fn and_then<F, P>(self, f: F) -> combinators::AndThen<Self, F>
        where F: FnOnce(Self::Value) -> P
    {
        combinators_impl::and_then(self, f)
    }

    /// Takes a closure which maps an error to a pattern, and
    /// creates a pattern which calls that closure if the evaluation of `self` failed.
    fn or_else<F, P>(self, f: F) -> combinators::OrElse<Self, F>
        where F: FnOnce(io::Error) -> P
    {
        combinators_impl::or_else(self, f)
    }

    /// Takes a closure which maps a value to another value, and
    /// creates a pattern which calls that closure on the evaluated value of `self`.
    fn map<F, T>(self, f: F) -> combinators::Map<Self, F>
        where F: FnOnce(Self::Value) -> T
    {
        combinators_impl::map(self, f)
    }

    /// Takes two patterns and creates a new pattern over both in sequence.
    ///
    /// In generally, using the tuple pattern `(self, P)` is more convenient way to
    /// achieve the same effect.
    fn chain<P>(self, other: P) -> combinators::Chain<Self, P>
        where P: Pattern
    {
        combinators_impl::chain(self, other)
    }

    /// Creates `Repeat` pattern to represent an infinite stream of this pattern.
    fn repeat(self) -> combinators::Repeat<Self>
        where Self: Clone
    {
        combinators_impl::repeat(self)
    }
}

/// A pattern which represents a sequence of a pattern `P`.
#[derive(Debug)]
pub struct Iter<I>(pub I);
impl<I, P> Iter<I>
    where I: Iterator<Item = P>,
          P: Pattern
{
    /// Creates `IterFold` combinator to fold the values of
    /// the patterns contained in the iterator `I`.
    pub fn fold<F, T>(self, init: T, f: F) -> combinators::IterFold<I, F, T>
        where F: Fn(T, P::Value) -> T
    {
        combinators_impl::iter_fold(self.0, f, init)
    }
}
impl<I, P> Pattern for Iter<I>
    where I: Iterator<Item = P>,
          P: Pattern
{
    type Value = ();
}

impl<P> Pattern for Option<P>
    where P: Pattern
{
    type Value = Option<P::Value>;
}

impl<T, E> Pattern for Result<T, E> {
    type Value = T;
}

macro_rules! impl_tuple_pattern{
    ($($p:ident),*) => {
        impl <$($p:Pattern),*> Pattern for ($($p),*,) {
            type Value = ($($p::Value),*);
        }
    }
}

impl Pattern for () {
    type Value = ();
}
impl_tuple_pattern!(P0, P1);
impl_tuple_pattern!(P0, P1, P2);
impl_tuple_pattern!(P0, P1, P2, P3);
impl_tuple_pattern!(P0, P1, P2, P3, P4);
impl_tuple_pattern!(P0, P1, P2, P3, P4, P5);
impl_tuple_pattern!(P0, P1, P2, P3, P4, P5, P6);
impl_tuple_pattern!(P0, P1, P2, P3, P4, P5, P6, P7);
impl_tuple_pattern!(P0, P1, P2, P3, P4, P5, P6, P7, P8);
impl_tuple_pattern!(P0, P1, P2, P3, P4, P5, P6, P7, P8, P9);

/// A pattern which represents branches in a pattern.
///
/// All branches must have the same resulting value type.
#[allow(missing_docs)]
pub enum Branch<A, B = A, C = A, D = A, E = A, F = A, G = A, H = A> {
    A(A),
    B(B),
    C(C),
    D(D),
    E(E),
    F(F),
    G(G),
    H(H),
}
impl<A, B, C, D, E, F, G, H> Pattern for Branch<A, B, C, D, E, F, G, H>
    where A: Pattern,
          B: Pattern<Value = A::Value>,
          C: Pattern<Value = A::Value>,
          D: Pattern<Value = A::Value>,
          E: Pattern<Value = A::Value>,
          F: Pattern<Value = A::Value>,
          G: Pattern<Value = A::Value>,
          H: Pattern<Value = A::Value>
{
    type Value = A::Value;
}
impl<A, B, C, D, E, F, G, H> Future for Branch<A, B, C, D, E, F, G, H>
    where A: Future,
          B: Future<Item = A::Item, Error = A::Error>,
          C: Future<Item = A::Item, Error = A::Error>,
          D: Future<Item = A::Item, Error = A::Error>,
          E: Future<Item = A::Item, Error = A::Error>,
          F: Future<Item = A::Item, Error = A::Error>,
          G: Future<Item = A::Item, Error = A::Error>,
          H: Future<Item = A::Item, Error = A::Error>
{
    type Item = A::Item;
    type Error = A::Error;
    fn poll(&mut self) -> futures::Poll<Self::Item, Self::Error> {
        match *self {
            Branch::A(ref mut f) => f.poll(),
            Branch::B(ref mut f) => f.poll(),
            Branch::C(ref mut f) => f.poll(),
            Branch::D(ref mut f) => f.poll(),
            Branch::E(ref mut f) => f.poll(),
            Branch::F(ref mut f) => f.poll(),
            Branch::G(ref mut f) => f.poll(),
            Branch::H(ref mut f) => f.poll(),
        }
    }
}

/// A trait to indicate that a pattern is partially evaluable.
pub trait AllowPartial: Sized {
    /// Indicates that this pattern is partially evaluable.
    fn allow_partial(self) -> combinators::PartialBuf<Self> {
        combinators_impl::PartialBuf(self)
    }
}

impl Pattern for Vec<u8> {
    type Value = Self;
}
impl AllowPartial for Vec<u8> {}

impl Pattern for String {
    type Value = Self;
}

/// A pattern which represents byte oriented buffer like values.
#[derive(Debug, Clone)]
pub struct Buf<B>(pub B);
impl<B> AllowPartial for Buf<B> {}
impl<B: AsRef<[u8]>> AsRef<[u8]> for Buf<B> {
    fn as_ref(&self) -> &[u8] {
        &self.0.as_ref()[..]
    }
}
impl<B: AsMut<[u8]>> AsMut<[u8]> for Buf<B> {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0.as_mut()[..]
    }
}
impl<B> Pattern for Buf<B> {
    type Value = B;
}

/// A pattern which represents a window of a byte oriented buffer.
#[derive(Debug, Clone)]
pub struct Window<B> {
    inner: B,
    start: usize,
    end: usize,
}
impl<B> AllowPartial for Window<B> {}
impl<B: AsRef<[u8]> + AsMut<[u8]>> Window<B> {
    /// Makes new window.
    pub fn new(buf: B) -> Self {
        Self::new_ref(buf)
    }
}
impl<B: AsRef<[u8]>> Window<B> {
    /// Makes new window for an immutable buffer.
    pub fn new_ref(buf: B) -> Self {
        let end = buf.as_ref().len();
        Window {
            inner: buf,
            start: 0,
            end: end,
        }
    }

    /// Sets end position of the window.
    pub fn set_end(mut self, end: usize) -> Self {
        assert!(end >= self.start);
        assert!(end <= self.as_ref().len());
        self.end = end;
        self
    }
}
impl<B: AsMut<[u8]>> Window<B> {
    /// Makes new window for an mutable buffer.
    pub fn new_mut(mut buf: B) -> Self {
        let end = buf.as_mut().len();
        Window {
            inner: buf,
            start: 0,
            end: end,
        }
    }
}
impl<B> Window<B> {
    /// Returns the immutable reference of the internal buffer.
    pub fn inner_ref(&self) -> &B {
        &self.inner
    }

    /// Returns the mutable reference of the internal buffer.
    pub fn inner_mut(&mut self) -> &mut B {
        &mut self.inner
    }

    /// Converts to the internal buffer.
    pub fn into_inner(self) -> B {
        self.inner
    }

    /// Returns the start point of the window.
    pub fn start(&self) -> usize {
        self.start
    }

    /// Returns the end point of the window.
    pub fn end(&self) -> usize {
        self.end
    }

    /// Converts to new window which skipped first `size` bytes of `self`.
    pub fn skip(mut self, size: usize) -> Self {
        assert!(self.start + size <= self.end);
        self.start += size;
        self
    }

    /// Converts to new window which took first `size` bytes of `self`.
    pub fn take(mut self, size: usize) -> Self {
        assert!(size <= self.end);
        assert!(self.start <= self.end - size);
        self.end -= size;
        self
    }

    /// Sets start position of the window.
    pub fn set_start(mut self, start: usize) -> Self {
        assert!(start <= self.end);
        self.start = start;
        self
    }
}
impl<B: AsRef<[u8]>> AsRef<[u8]> for Window<B> {
    fn as_ref(&self) -> &[u8] {
        &self.inner.as_ref()[self.start..self.end]
    }
}
impl<B: AsMut<[u8]>> AsMut<[u8]> for Window<B> {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.inner.as_mut()[self.start..self.end]
    }
}
impl<B> Pattern for Window<B> {
    type Value = Self;
}

/// A trait to indicates endianness of a pattern.
pub trait Endian: Sized {
    /// Indicates that "This is a little endian pattern".
    fn le(self) -> combinators::LE<Self> {
        combinators::LE(self)
    }

    /// Indicates that "This is a big endian pattern".
    fn be(self) -> combinators::BE<Self> {
        combinators::BE(self)
    }
}