summary refs log tree commit diff stats
path: root/src/strcursor.rs
blob: d733adea9a8d325446452d8ca873310b810ff573 (plain) (blame)
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
// Copyright (c) 2021 Soni L.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Documentation and comments licensed under CC BY-SA 4.0.

//! String Cursor (sorta).

use ::std::io::Cursor;
use ::std::str::FromStr;

use crate::error::ReadError;

/// Extension trait on [`Cursor`]s to help with command parsing.
///
/// All `read_*` methods reset the cursor on error.
///
/// Note that, compared to Brigadier, this lacks methods such as
/// `getRemainingLength` (use `get_remaining().len()` or
/// `remaining_slice().len()`) and `getTotalLength` (use `get_ref().len()`).
pub trait StringReader<'a>: Sized {
    /// Returns the part of the string that has been read so far.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    //#[inline]
    fn get_read(&self) -> &'a str;
    /// Returns the part of the string that has yet to be read.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    //#[inline]
    fn get_remaining(&self) -> &'a str;
    /// Returns whether there's anything left to read.
    #[inline]
    fn can_read(&self) -> bool {
        self.can_read_n(1)
    }
    /// Returns whether there's enough left to read, based on the passed length.
    //#[inline]
    fn can_read_n(&self, len: usize) -> bool;
    /// Returns the next char.
    ///
    /// # Panics
    ///
    /// Panics if there's nothing left to read, or if this cursor is not on an
    /// UTF-8 character boundary.
    #[inline]
    fn peek(&self) -> char {
        self.peek_n(0)
    }
    /// Returns the next nth **byte** (and, if needed, subsequent bytes) as a
    /// char.
    ///
    /// # Panics
    ///
    /// Panics if the offset is beyond the boundaries of the buffer, or if the
    /// offset is not on an UTF-8 character boundary.
    //#[inline]
    fn peek_n(&self, offset: usize) -> char;

    /// Advances to the next char.
    ///
    /// # Panics
    ///
    /// Panics if there's nothing left to read, or if this cursor is not on an
    /// UTF-8 character boundary.
    //#[inline]
    fn skip(&mut self);
    /// Attempts to read the next char.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    //#[inline]
    fn read_char(&mut self) -> Option<char>;
    /// Checks the next char.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    fn expect<E: ReadError<'a, Self>>(&mut self, c: char) -> Result<(), E> {
        if !self.can_read() || self.peek() != c {
            // because we want the error constructors to take &str.
            let mut buf = [0u8; 4];
            Err(E::expected_symbol(self, c.encode_utf8(&mut buf)))
        } else {
            Ok(self.skip())
        }
    }
    /// Skips whitespace.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    fn skip_whitespace(&mut self) {
        // FIXME figure out if we wanna use the same whitespace rules as
        // brigadier, because rust uses unicode whereas java uses java rules.
        while self.can_read() && self.peek().is_whitespace() {
            self.skip();
        }
    }

    /// Reads an integer.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    fn read_integer<T, E: ReadError<'a, Self>>(&mut self) -> Result<T, E>
    where T: FromStr<Err=::std::num::ParseIntError>;
    /// Reads a float.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    fn read_float<T, E: ReadError<'a, Self>>(&mut self) -> Result<T, E>
    where T: FromStr<Err=::std::num::ParseFloatError>;
    /// Reads a bool.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    fn read_bool<E: ReadError<'a, Self>>(&mut self) -> Result<bool, E>;
    /// Reads an unquoted string.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    // this is a bit of a weird one in that it can't error.
    fn read_unquoted_str(&mut self) -> &'a str;
    /// Reads a quoted string.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    fn read_quoted_string<E: ReadError<'a, Self>>(
        &mut self,
    ) -> Result<String, E>;
    /// Reads a quoted or an unquoted string.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is not on an UTF-8 character boundary.
    fn read_string<E: ReadError<'a, Self>>(&mut self) -> Result<String, E>;
}

impl<'a> StringReader<'a> for Cursor<&'a str> {
    #[inline]
    fn get_read(&self) -> &'a str {
        &self.get_ref()[..(self.position() as usize)]
    }
    #[inline]
    fn get_remaining(&self) -> &'a str {
        &self.get_ref()[(self.position() as usize)..]
    }
    #[inline]
    fn can_read_n(&self, len: usize) -> bool {
        // NOTE: NOT overflow-aware!
        self.position() as usize + len <= self.get_ref().len()
    }
    #[inline]
    fn peek_n(&self, offset: usize) -> char {
        // NOTE: NOT overflow-aware!
        self.get_ref()[(self.position() as usize + offset)..]
            .chars().next().unwrap()
    }

    #[inline]
    fn skip(&mut self) {
        self.set_position(self.position() + self.peek().len_utf8() as u64);
    }
    #[inline]
    fn read_char(&mut self) -> Option<char> {
        let res = self.get_ref()[(self.position() as usize)..].chars().next();
        if let Some(c) = res {
            self.set_position(self.position() + c.len_utf8() as u64);
        }
        res
    }

    fn read_integer<T, E: ReadError<'a, Self>>(&mut self) -> Result<T, E>
    where T: FromStr<Err=::std::num::ParseIntError> {
        // see read_unquoted_str for rationale
        let start = self.position() as usize;
        let total = self.get_ref().len();
        let end = total - {
            self.get_remaining().trim_start_matches(number_chars).len()
        };
        self.set_position(end as u64);

        let number = &self.get_ref()[start..end];
        if number.is_empty() {
            // don't need to set_position here, we haven't moved
            Err(E::expected_integer(self))
        } else {
            number.parse().map_err(|_| {
                self.set_position(start as u64);
                E::invalid_integer(self, number)
            })
        }
    }
    fn read_float<T, E: ReadError<'a, Self>>(&mut self) -> Result<T, E>
    where T: FromStr<Err=::std::num::ParseFloatError> {
        // see read_unquoted_str for rationale
        let start = self.position() as usize;
        let total = self.get_ref().len();
        let end = total - {
            self.get_remaining().trim_start_matches(number_chars).len()
        };
        self.set_position(end as u64);

        let number = &self.get_ref()[start..end];
        if number.is_empty() {
            // don't need to set_position here, we haven't moved
            Err(E::expected_float(self))
        } else {
            number.parse().map_err(|_| {
                self.set_position(start as u64);
                E::invalid_float(self, number)
            })
        }
    }
    fn read_bool<E: ReadError<'a, Self>>(&mut self) -> Result<bool, E> {
        let pos = self.position();
        // NOTE: brigadier also allows quoted strings for bools.
        // we consider that a bug, so we don't.
        let res = match self.read_unquoted_str() {
            "true" => Ok(true),
            "false" => Ok(false),
            "" => Err(E::expected_bool(self)),
            value => {
                self.set_position(pos);
                Err(E::invalid_bool(self, value))
            },
        };
        res
    }
    fn read_unquoted_str(&mut self) -> &'a str {
        // there's no easy way to grab start matches, so we have to do something
        // a bit more involved.
        let start = self.position() as usize;
        let total = self.get_ref().len();
        let end = total - {
            self.get_remaining().trim_start_matches(unquoted_chars).len()
        };
        self.set_position(end as u64);
        &self.get_ref()[start..end]
    }
    fn read_quoted_string<E: ReadError<'a, Self>>(
        &mut self,
    ) -> Result<String, E> {
        if !self.can_read() {
            Ok("".into())
        } else if quote_chars(self.peek()) {
            let start = self.position() as usize;
            let terminator = self.read_char().unwrap();
            let res = read_string_until(self, terminator);
            if res.is_err() {
                self.set_position(start as u64);
            }
            res
        } else {
            Err(E::expected_start_of_quote(self))
        }
    }
    fn read_string<E: ReadError<'a, Self>>(&mut self) -> Result<String, E> {
        if !self.can_read() {
            Ok("".into())
        } else if quote_chars(self.peek()) {
            let start = self.position() as usize;
            let terminator = self.read_char().unwrap();
            let res = read_string_until(self, terminator);
            if res.is_err() {
                self.set_position(start as u64);
            }
            res
        } else {
            Ok(self.read_unquoted_str().into())
        }
    }
}

fn read_string_until<'a, E: ReadError<'a, Cursor<&'a str>>>(
    this: &mut Cursor<&'a str>,
    terminator: char,
) -> Result<String, E> {
    let mut result = String::new();
    let mut escaped = false;

    while let Some(c) = this.read_char() {
        if escaped {
            if c == terminator || escape_char(c) {
                result.push(c);
                escaped = false;
            } else {
                let mut buf = [0u8; 4];
                // NOTE: brigadier unskips the escape. we don't bother.
                return Err(E::invalid_escape(this, c.encode_utf8(&mut buf)));
            }
        } else if escape_char(c) {
            escaped = true;
        } else if c == terminator {
            return Ok(result);
        } else {
            result.push(c);
        }
    }

    Err(E::expected_end_of_quote(this))
}

/// Symbols allowed in unquoted strings.
#[inline]
fn unquoted_chars(c: char) -> bool {
    matches!(
        c,
        '0' ..= '9' | 'A' ..= 'Z' | 'a' ..= 'z' | '_' | '-' | '.' | '+',
    )
}

/// Symbols allowed in numbers.
#[inline]
fn number_chars(c: char) -> bool {
    matches!(
        c,
        '0' ..= '9' | '-' | '.',
    )
}

/// Symbols allowed to start/end a quoted string.
#[inline]
fn quote_chars(c: char) -> bool {
    matches!(
        c,
        '"' | '\'',
    )
}

/// Symbol allowed to escape other symbols.
#[inline]
fn escape_char(c: char) -> bool {
    matches!(
        c,
        '\\',
    )
}