summaryrefslogtreecommitdiff
path: root/src/input.rs
blob: 0857c8c7f495eb5589000517d8cca8ef83ea9437 (plain)
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
use core::{fmt, iter, slice, str::CharIndices};

use crate::Span;

pub trait Input: Clone {
    type Item;
    type Items: Clone + Iterator<Item = (usize, Self::Item)>;

    fn items(&self) -> Self::Items;

    fn slice(&self, span: Span) -> Self;

    fn len(&self) -> usize;
}

impl<'a> Input for &'a str {
    type Item = char;
    type Items = CharIndices<'a>;

    fn items(&self) -> Self::Items {
        self.char_indices()
    }

    fn slice(&self, span: Span) -> Self {
        &self[span]
    }

    fn len(&self) -> usize {
        (*self).len()
    }
}

impl<'a> Input for &'a [u8] {
    type Item = u8;
    type Items = iter::Enumerate<iter::Copied<slice::Iter<'a, u8>>>;

    fn items(&self) -> Self::Items {
        self.iter().copied().enumerate()
    }

    fn slice(&self, span: Span) -> Self {
        &self[span]
    }

    fn len(&self) -> usize {
        (*self).len()
    }
}

pub trait Character {
    fn is_alphabetic(&self) -> bool;

    fn is_numeric(&self) -> bool;

    fn is_whitespace(&self) -> bool;

    fn is_alphanumeric(&self) -> bool {
        self.is_alphabetic() || self.is_numeric()
    }
}

impl Character for char {
    fn is_alphabetic(&self) -> bool {
        (*self).is_ascii_alphabetic()
    }

    fn is_numeric(&self) -> bool {
        (*self).is_numeric()
    }

    fn is_whitespace(&self) -> bool {
        (*self).is_whitespace()
    }
}

#[derive(Clone)]
pub struct InputIter<I: Input> {
    pub it: I::Items,
    pub input: I,
}

impl<I> InputIter<I>
where
    I: Input,
{
    pub fn new(input: I) -> Self {
        Self {
            it: input.items(),
            input,
        }
    }

    pub fn position(&self) -> usize {
        match self.it.clone().next() {
            Some((i, _)) => i,
            None => self.input.len(),
        }
    }

    pub fn is_finished(&self) -> bool {
        self.clone().next().is_none()
    }

    pub fn rest(&self) -> I {
        self.input.slice(self.position()..self.input.len())
    }
}

impl<I> Iterator for InputIter<I>
where
    I: Input,
{
    type Item = (usize, I::Item);

    fn next(&mut self) -> Option<Self::Item> {
        self.it.next()
    }
}

impl<I> fmt::Debug for InputIter<I>
where
    I: Input + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.rest())
    }
}