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
//! Various parsing utilities.
use std::{borrow::Cow, mem};

use super::Error;

pub trait TakePrefix: Sized {
    fn take_prefix(&mut self, mid: usize) -> Result<Self, Error>;
}

impl<'a, T: 'a> TakePrefix for &'a [T] {
    fn take_prefix(&mut self, mid: usize) -> Result<Self, Error> {
        if let (Some(prefix), Some(rest)) = (self.get(..mid), self.get(mid..)) {
            *self = rest;
            Ok(prefix)
        } else {
            Err(Error::QuoteParseError(
                "unexpected end of quote".to_string(),
            ))
        }
    }
}

impl<'a, T: 'a + Clone> TakePrefix for Cow<'a, [T]> {
    fn take_prefix(&mut self, mid: usize) -> Result<Self, Error> {
        if mid <= self.len() {
            match *self {
                Cow::Borrowed(ref mut slice) => slice.take_prefix(mid).map(Cow::Borrowed),
                Cow::Owned(ref mut vec) => {
                    let rest = vec.split_off(mid);
                    Ok(Cow::Owned(mem::replace(vec, rest)))
                }
            }
        } else {
            Err(Error::QuoteParseError(
                "unexpected end of quote".to_string(),
            ))
        }
    }
}

impl<'a> TakePrefix for &'a str {
    fn take_prefix(&mut self, mid: usize) -> Result<Self, Error> {
        if let (Some(prefix), Some(rest)) = (self.get(..mid), self.get(mid..)) {
            *self = rest;
            Ok(prefix)
        } else {
            Err(Error::QuoteParseError(
                "unexpected end of quote".to_string(),
            ))
        }
    }
}

impl<'a> TakePrefix for Cow<'a, str> {
    fn take_prefix(&mut self, mid: usize) -> Result<Self, Error> {
        if mid <= self.len() {
            match *self {
                Cow::Borrowed(ref mut slice) => slice.take_prefix(mid).map(Cow::Borrowed),
                Cow::Owned(ref mut vec) => {
                    let rest = vec.split_off(mid);
                    Ok(Cow::Owned(mem::replace(vec, rest)))
                }
            }
        } else {
            Err(Error::QuoteParseError(
                "unexpected end of quote".to_string(),
            ))
        }
    }
}