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
use core::fmt;
use core::marker::PhantomData;

use crate::error::{
    with_context, Context, ExpectedLength, ExpectedValid, ExpectedValue, FromContext,
    OperationContext, ToRetryRequirement, Value,
};
use crate::input::Input;

/// A `Reader` is created from and consumes a [`Input`].
///
/// You can only create a [`Reader`] from [`Input`] via [`Input::read_all()`] or
/// [`Input::read_partial()`].
pub struct Reader<'i, E> {
    input: &'i Input,
    error: PhantomData<E>,
}

impl<'i, E> Reader<'i, E> {
    /// Mutably use the reader with a given context.
    ///
    /// # Errors
    ///
    /// Returns any error returned by the provided function, and attaches the
    /// specified context to it.
    pub fn context<C, F, O>(&mut self, context: C, f: F) -> Result<O, E>
    where
        E: FromContext<'i>,
        C: Context,
        F: FnOnce(&mut Self) -> Result<O, E>,
    {
        with_context(self.input, context, || f(self))
    }

    /// Immutably use the reader with a given context.
    ///
    /// # Errors
    ///
    /// Returns any error returned by the provided function, and attaches the
    /// specified context to it.
    pub fn peek_context<C, F, O>(&self, context: C, f: F) -> Result<O, E>
    where
        E: FromContext<'i>,
        C: Context,
        F: FnOnce(&Self) -> Result<O, E>,
    {
        with_context(self.input, context, || f(self))
    }

    /// Returns `true` if the reader has no more input to consume.
    #[inline]
    pub fn at_end(&self) -> bool {
        self.input.is_empty()
    }

    /// Skip `len` number of bytes in the input.
    ///
    /// # Errors
    ///
    /// Returns an error if the input was not long enough.
    #[inline]
    pub fn skip(&mut self, len: usize) -> Result<(), E>
    where
        E: From<ExpectedLength<'i>>,
    {
        let (_, tail) = self.input.split_at(len, "skip")?;
        self.input = tail;
        Ok(())
    }

    /// Skip a length of input while a predicate check remains true.
    ///
    /// Returns the length of input skipped.
    ///
    /// # Errors
    ///
    /// Returns any error the provided function does.
    pub fn skip_while<F>(&mut self, pred: F) -> usize
    where
        F: FnMut(u8) -> bool,
    {
        let (head, tail) = self.input.split_while(pred);
        self.input = tail;
        head.len()
    }

    /// Try skip a length of input while a predicate check remains successful
    /// and true.
    ///
    /// Returns the length of input skipped.
    ///
    /// # Errors
    ///
    /// Returns any error the provided function does.
    pub fn try_skip_while<F>(&mut self, pred: F) -> Result<usize, E>
    where
        E: FromContext<'i>,
        F: FnMut(u8) -> Result<bool, E>,
    {
        let (head, tail) = self.input.try_split_while(pred, "try skip while")?;
        self.input = tail;
        Ok(head.len())
    }

    /// Read a length of input.
    ///
    /// # Errors
    ///
    /// Returns an error if the required length cannot be fulfilled.
    pub fn take(&mut self, len: usize) -> Result<&'i Input, E>
    where
        E: From<ExpectedLength<'i>>,
    {
        let (head, tail) = self.input.split_at(len, "take")?;
        self.input = tail;
        Ok(head)
    }

    /// Read all of the input left.
    pub fn take_remaining(&mut self) -> &'i Input {
        let all = self.input;
        self.input = all.end();
        all
    }

    /// Read a length of input while a predicate check remains true.
    pub fn take_while<F>(&mut self, pred: F) -> &'i Input
    where
        F: FnMut(u8) -> bool,
    {
        let (head, tail) = self.input.split_while(pred);
        self.input = tail;
        head
    }

    /// Try read a length of input while a predicate check remains successful
    /// and true.
    ///
    /// # Errors
    ///
    /// Returns any error the provided function does.
    pub fn try_take_while<F>(&mut self, pred: F) -> Result<&'i Input, E>
    where
        E: FromContext<'i>,
        F: FnMut(u8) -> Result<bool, E>,
    {
        let (head, tail) = self.input.try_split_while(pred, "try take while")?;
        self.input = tail;
        Ok(head)
    }

    /// Read a length of input that was successfully parsed.
    pub fn take_consumed<F>(&mut self, consumer: F) -> &'i Input
    where
        E: FromContext<'i>,
        F: FnMut(&mut Self),
    {
        let (head, tail) = self.input.split_consumed(consumer);
        self.input = tail;
        head
    }

    /// Try read a length of input that was successfully parsed.
    ///
    /// # Errors
    ///
    /// Returns an error if the provided function does.
    pub fn try_take_consumed<F>(&mut self, consumer: F) -> Result<&'i Input, E>
    where
        E: FromContext<'i>,
        F: FnMut(&mut Self) -> Result<(), E>,
    {
        let (head, tail) = self
            .input
            .try_split_consumed(consumer, "try take consumed")?;
        self.input = tail;
        Ok(head)
    }

    /// Peek a length of input.
    ///
    /// # Errors
    ///
    /// Returns an error if the required length cannot be fulfilled.
    pub fn peek<F, O>(&self, len: usize, f: F) -> Result<O, E>
    where
        E: From<ExpectedLength<'i>>,
        F: FnOnce(&Input) -> O,
    {
        let (head, _) = self.input.split_at(len, "peek")?;
        Ok(f(head))
    }

    /// Try peek a length of input.
    ///
    /// # Errors
    ///
    /// Returns an error if the required length cannot be fulfilled,
    /// or if the provided function returns one.
    pub fn try_peek<F, O>(&self, len: usize, f: F) -> Result<O, E>
    where
        E: FromContext<'i>,
        E: From<ExpectedLength<'i>>,
        F: FnOnce(&'i Input) -> Result<O, E>,

        O: 'static,
    {
        let (head, _) = self.input.split_at(len, "try peek")?;
        with_context(self.input, OperationContext("try peek"), || f(head))
    }

    /// Returns the next byte in the input without mutating the reader.
    ///
    /// # Errors
    ///
    /// Returns an error if the reader has no more input.
    #[inline]
    pub fn peek_u8(&self) -> Result<u8, E>
    where
        E: From<ExpectedLength<'i>>,
    {
        self.input.first("peek u8")
    }

    /// Returns `true` if `bytes` is next in the input.
    #[inline]
    pub fn peek_eq(&self, bytes: &[u8]) -> bool {
        self.input.has_prefix(bytes)
    }

    /// Consume expected bytes from the input.
    ///
    /// Doesn't effect the internal state if the input couldn't be consumed.
    ///
    /// # Errors
    ///
    /// Returns an error if the bytes could not be consumed from the input.
    pub fn consume(&mut self, bytes: &'i [u8]) -> Result<(), E>
    where
        E: From<ExpectedLength<'i>>,
        E: From<ExpectedValue<'i>>,
    {
        let prefix = Value::Bytes(bytes);
        let tail = self.input.split_prefix::<E>(prefix, "consume")?;
        self.input = tail;
        Ok(())
    }

    /// Consume expected bytes from the input.
    ///
    /// Doesn't effect the internal state if the input couldn't be consumed.
    ///
    /// # Errors
    ///
    /// Returns an error if the bytes could not be consumed from the input.
    pub fn consume_u8(&mut self, byte: u8) -> Result<(), E>
    where
        E: From<ExpectedLength<'i>>,
        E: From<ExpectedValue<'i>>,
    {
        let prefix = Value::Byte(byte);
        let tail = self.input.split_prefix::<E>(prefix, "consume u8")?;
        self.input = tail;
        Ok(())
    }

    /// Expect a value to be read and returned as `Some`.
    ///
    /// # Errors
    ///
    /// Returns an error if the returned value was `None`.
    pub fn expect<F, O>(&mut self, expected: &'static str, f: F) -> Result<O, E>
    where
        F: FnOnce(&mut Self) -> Option<O>,
        E: FromContext<'i>,
        E: From<ExpectedValid<'i>>,
    {
        let (ok, tail) = self.input.split_expect(f, expected, "expect")?;
        self.input = tail;
        Ok(ok)
    }

    /// Expect a value to be read successfully and returned as `Some`.
    ///
    /// # Errors
    ///
    /// Returns an error if failed to read, or the returned value was `None`.
    pub fn try_expect<F, O>(&mut self, expected: &'static str, f: F) -> Result<O, E>
    where
        E: FromContext<'i>,
        E: From<ExpectedValid<'i>>,
        F: FnOnce(&mut Self) -> Result<Option<O>, E>,
    {
        let (ok, tail) = self.input.try_split_expect(f, expected, "try expect")?;
        self.input = tail;
        Ok(ok)
    }

    /// Expect a value with any error's details erased except for an optional
    /// [`RetryRequirement`].
    ///
    /// This function is useful for reading custom/unsupported types easily
    /// without having to create custom errors.
    ///
    /// # Example
    ///
    /// ```
    /// use std::net::Ipv4Addr;
    ///
    /// use dangerous::{Invalid, Expected, Error};
    ///
    /// // Our custom reader function
    /// fn read_ipv4_addr<'i, E>(input: &'i dangerous::Input) -> Result<Ipv4Addr, E>
    /// where
    ///   E: Error<'i>,
    /// {
    ///     input.read_all(|r| {
    ///         r.try_expect_erased("ipv4 addr", |i| {
    ///             i.take_remaining()
    ///                 .to_dangerous_str()
    ///                 .and_then(|s| s.parse().map_err(|_| Invalid::fatal()))
    ///         })
    ///     })
    /// }
    ///
    /// let input = dangerous::input(b"192.168.1.x");
    /// let error: Expected = read_ipv4_addr(input).unwrap_err();
    ///
    /// // Prefer string input formatting
    /// println!("{:#}", error);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if either the provided function does, or there is
    /// trailing input.
    ///
    /// [`RetryRequirement`]: crate::error::RetryRequirement
    pub fn try_expect_erased<F, O, R>(&mut self, expected: &'static str, f: F) -> Result<O, E>
    where
        E: FromContext<'i>,
        E: From<ExpectedValid<'i>>,
        F: FnOnce(&mut Self) -> Result<O, R>,
        R: ToRetryRequirement,
    {
        let (ok, tail) = self
            .input
            .try_split_expect_erased(f, expected, "try expect erased")?;
        self.input = tail;
        Ok(ok)
    }

    /// Read a byte, consuming the input.
    ///
    /// # Errors
    ///
    /// Returns an error if there is no more input.
    #[inline]
    pub fn read_u8(&mut self) -> Result<u8, E>
    where
        E: From<ExpectedLength<'i>>,
    {
        let (byte, tail) = self.input.split_first::<E>("read u8")?;
        self.input = tail;
        Ok(byte)
    }

    impl_read_num!(i8, le: read_i8_le, be: read_i8_be);
    impl_read_num!(u16, le: read_u16_le, be: read_u16_be);
    impl_read_num!(i16, le: read_i16_le, be: read_i16_be);
    impl_read_num!(u32, le: read_u32_le, be: read_u32_be);
    impl_read_num!(i32, le: read_i32_le, be: read_i32_be);
    impl_read_num!(u64, le: read_u64_le, be: read_u64_be);
    impl_read_num!(i64, le: read_i64_le, be: read_i64_be);
    impl_read_num!(u128, le: read_u128_le, be: read_u128_be);
    impl_read_num!(i128, le: read_i128_le, be: read_i128_be);
    impl_read_num!(f32, le: read_f32_le, be: read_f32_be);
    impl_read_num!(f64, le: read_f64_le, be: read_f64_be);

    /// Create a sub reader with a given error type.
    #[inline]
    pub fn error<T>(&mut self) -> Reader<'_, T> {
        Reader {
            input: self.input,
            error: PhantomData,
        }
    }

    /// Create a `Reader` given `Input`.
    pub(crate) fn new(input: &'i Input) -> Self {
        Self {
            input,
            error: PhantomData,
        }
    }
}

impl<'i, E> fmt::Debug for Reader<'i, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Reader")
            .field("input", &self.input)
            .finish()
    }
}