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
use crate::lexer::token::Span;
#[derive(Debug)]
pub struct Source<'a> {
input: &'a [u8],
length: usize,
cursor: usize,
span: Span,
}
impl<'a> Source<'a> {
pub fn new(input: &'a [u8]) -> Self {
let input = input;
let length = input.len();
Self {
input,
length,
cursor: 0,
span: (1, 1),
}
}
pub fn from<B: ?Sized + AsRef<[u8]>>(input: &'a B) -> Self {
Self::new(input.as_ref())
}
pub const fn cursor(&self) -> usize {
self.cursor
}
pub const fn span(&self) -> Span {
self.span
}
pub const fn eof(&self) -> bool {
self.cursor >= self.length
}
pub fn next(&mut self) {
if !self.eof() {
match self.input[self.cursor] {
b'\n' => {
self.span.0 += 1;
self.span.1 = 1;
}
_ => self.span.1 += 1,
}
}
self.cursor += 1;
}
pub fn skip(&mut self, count: usize) {
for _ in 0..count {
self.next();
}
}
pub fn current(&self) -> Option<&'a u8> {
if self.cursor >= self.length {
None
} else {
Some(&self.input[self.cursor])
}
}
pub fn read(&self, n: usize) -> &'a [u8] {
let (from, until) = self.to_bound(n);
&self.input[from..until]
}
pub fn read_remaining(&self) -> &'a [u8] {
let from = self.current_bound();
&self.input[from..]
}
pub fn at(&self, search: &[u8], len: usize) -> bool {
self.read(len) == search
}
pub fn at_case_insensitive(&self, search: &[u8], len: usize) -> bool {
let (from, until) = self.to_bound(len);
let slice = &self.input[from..until];
slice.eq_ignore_ascii_case(search)
}
pub fn peek(&self, i: usize, n: usize) -> &'a [u8] {
let (from, until) = self.between_bound(i, n);
&self.input[from..until]
}
pub fn peek_ignoring_whitespace(&self, i: usize, n: usize) -> &'a [u8] {
let mut i = i;
loop {
let c = self.peek(i, 1);
if c.is_empty() {
return &[];
}
match c[0] {
b' ' | b'\t' | b'\r' | b'\n' => i += 1,
_ => break,
}
}
self.peek(i, n)
}
const fn between_bound(&self, i: usize, n: usize) -> (usize, usize) {
let from = self.cursor + i;
if from >= self.length {
return (self.length, self.length);
}
let mut until = from + n;
if until >= self.length {
until = self.length;
}
(from, until)
}
const fn to_bound(&self, n: usize) -> (usize, usize) {
if self.cursor >= self.length {
return (self.length, self.length);
}
let mut until = self.cursor + n;
if until >= self.length {
until = self.length;
}
(self.cursor, until)
}
const fn current_bound(&self) -> usize {
if self.cursor >= self.length {
self.length
} else {
self.cursor
}
}
}