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
//! This microcrate provides a Cursor usable over byte [`toad_array::Array`]s

// docs
#![doc(html_root_url = "https://docs.rs/toad-cursor/0.1.0")]
#![cfg_attr(any(docsrs, feature = "docs"), feature(doc_cfg))]
// -
// style
#![allow(clippy::unused_unit)]
// -
// deny
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(missing_copy_implementations)]
#![cfg_attr(not(test), deny(unsafe_code))]
// -
// warnings
#![cfg_attr(not(test), warn(unreachable_pub))]
// -
// features
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "alloc")]
extern crate alloc as std_alloc;

/// A cursor over a byte array (std- and alloc-less port of [`std::io::Cursor`])
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Cursor<T> {
  t: T,
  cursor: usize,
  len: usize,
}

impl<T: AsRef<[u8]>> Cursor<T> {
  fn is_exhausted_(cursor: usize, len: usize) -> bool {
    Self::remaining_(cursor, len) <= 0
  }

  fn remaining_(cursor: usize, len: usize) -> isize {
    len as isize - cursor as isize
  }

  fn peek_(len: usize, cursor: usize, t: &T, n: usize) -> Option<&[u8]> {
    if n as isize > Self::remaining_(cursor, len) {
      None
    } else {
      Some(&t.as_ref()[cursor..cursor + n])
    }
  }

  fn skip_(cursor: &mut usize, len: usize, n: usize) -> usize {
    if Self::is_exhausted_(*cursor, len) {
      0
    } else if *cursor + n > len {
      let left = len - *cursor;
      *cursor += left;
      left
    } else {
      *cursor += n;
      n
    }
  }

  fn peek_until_end_(cursor: usize, len: usize, t: &T) -> &[u8] {
    if Self::is_exhausted_(cursor, len) {
      &[]
    } else {
      &t.as_ref()[cursor..]
    }
  }

  fn seek_to_end_(cursor: &mut usize, len: usize) {
    *cursor = len;
  }

  fn take_until_end_<'a, 'b>(cursor: &'a mut usize, len: usize, t: &'b T) -> &'b [u8] {
    let out = Self::peek_until_end_(*cursor, len, t);
    Self::seek_to_end_(cursor, len);

    out
  }

  /// Creates a new cursor
  pub fn new(t: T) -> Cursor<T> {
    let len = t.as_ref().len();
    Cursor { t, cursor: 0, len }
  }

  /// Unwraps the cursor, discarding its internal position
  pub fn into_inner(self) -> T {
    self.t
  }

  /// Take the next byte in the cursor, returning None
  /// if the cursor is exhausted.
  ///
  /// Runs in O(1) time.
  #[allow(clippy::should_implement_trait)]
  pub fn next(&mut self) -> Option<u8> {
    self.take_exact(1).and_then(|a| match a {
                        | &[a] => Some(a),
                        | _ => None,
                      })
  }

  /// Take `n` bytes from the cursor, stopping early if
  /// the end of the buffer is encountered.
  ///
  /// Runs in O(1) time.
  pub fn take(&mut self, n: usize) -> &[u8] {
    Self::peek_(self.len, self.cursor, &self.t, n).map(|a| {
                                                    Self::skip_(&mut self.cursor, self.len, n);
                                                    a
                                                  })
                                                  .unwrap_or_else(|| {
                                                    Self::take_until_end_(&mut self.cursor,
                                                                          self.len,
                                                                          &self.t)
                                                  })
  }

  /// Take `n` bytes from the cursor, returning None if
  /// the end of the buffer is encountered.
  ///
  /// Runs in O(1) time.
  pub fn take_exact(&mut self, n: usize) -> Option<&[u8]> {
    Self::peek_(self.len, self.cursor, &self.t, n).map(|a| {
                                                    Self::skip_(&mut self.cursor, self.len, n);
                                                    a
                                                  })
  }

  /// Without advancing the position, look at the next
  /// `n` bytes, or until the end if there are less than `n` bytes
  /// remaining.
  ///
  /// Runs in O(1) time.
  pub fn peek(&self, n: usize) -> &[u8] {
    Self::peek_(self.len, self.cursor, &self.t, n).unwrap_or_else(|| self.peek_until_end())
  }

  /// Without advancing the position, look at the next
  /// `n` bytes, returning None if there are less than `n` bytes
  /// remaining.
  ///
  /// Runs in O(1) time.
  pub fn peek_exact(&self, n: usize) -> Option<&[u8]> {
    Self::peek_(self.len, self.cursor, &self.t, n)
  }

  /// Advance the cursor by `n` bytes.
  ///
  /// Returns the actual number of bytes skipped:
  ///  - Equal to n if there are at least n more bytes in the buffer
  ///  - Less than n if n would seek past the end
  ///  - Zero if the cursor is already exhausted
  ///
  /// Runs in O(1) time.
  pub fn skip(&mut self, n: usize) -> usize {
    Self::skip_(&mut self.cursor, self.len, n)
  }

  /// Consume bytes until a predicate returns `false` or the end is reached.
  ///
  /// Runs in O(n) time.
  pub fn take_while(&mut self, mut f: impl FnMut(u8) -> bool) -> &[u8] {
    if self.is_exhausted() {
      return &[];
    }

    (self.cursor..self.len).into_iter()
                           .take_while(|ix| f(self.t.as_ref()[*ix]))
                           .last()
                           .map(|end_ix| {
                             let out = &self.t.as_ref()[self.cursor..=end_ix];
                             self.cursor = end_ix + 1;
                             out
                           })
                           .unwrap_or(&[])
  }

  /// Whether the cursor has reached the end
  /// of the buffer.
  ///
  /// Runs in O(1) time.
  pub fn is_exhausted(&self) -> bool {
    Self::is_exhausted_(self.cursor, self.len)
  }

  /// The number of elements not yet consumed
  ///
  /// Runs in O(1) time.
  pub fn remaining(&self) -> usize {
    Self::remaining_(self.cursor, self.len).max(0) as usize
  }

  /// Get the bytes remaining in the buffer without advancing the position.
  ///
  /// Runs in O(1) time.
  pub fn peek_until_end(&self) -> &[u8] {
    Self::peek_until_end_(self.cursor, self.len, &self.t)
  }

  /// Get the bytes remaining in the buffer, advancing
  /// the position to the end.
  ///
  /// Runs in O(1) time.
  pub fn take_until_end(&mut self) -> &[u8] {
    Self::take_until_end_(&mut self.cursor, self.len, &self.t)
  }

  /// Get the position the cursor points to within
  /// the buffer
  pub fn position(&self) -> usize {
    self.cursor
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  pub fn peek_until_end() {
    let cur = Cursor::new(vec![]);
    assert_eq!(cur.peek_until_end(), &[]);

    let cur = Cursor::new(vec![1, 2, 3]);
    assert_eq!(cur.peek_until_end(), &[1, 2, 3]);

    let mut cur = Cursor::new(vec![1, 2, 3]);
    cur.skip(1);
    assert_eq!(cur.peek_until_end(), &[2, 3]);
  }

  #[test]
  pub fn take_until_end() {
    let mut cur = Cursor::new(vec![]);
    assert_eq!(cur.take_until_end(), &[]);
    assert_eq!(cur.take_until_end(), &[]);
    assert_eq!(cur.take_until_end(), &[]);

    let mut cur = Cursor::new(vec![1, 2, 3]);
    assert_eq!(cur.take_until_end(), &[1, 2, 3]);

    let mut cur = Cursor::new(vec![1, 2, 3]);
    cur.skip(1);
    assert_eq!(cur.take_until_end(), &[2, 3]);
    assert_eq!(cur.peek_until_end(), &[]);
  }

  #[test]
  pub fn next() {
    let mut cur = Cursor::new(vec![1]);
    assert_eq!(cur.next(), Some(1));
    assert_eq!(cur.next(), None);
    assert_eq!(cur.next(), None);
  }

  #[test]
  pub fn take() {
    let mut cur = Cursor::new(vec![1, 2, 3]);
    assert_eq!(cur.take(2), &[1, 2]);
    assert_eq!(cur.take(1), &[3]);
    assert_eq!(cur.take(1), &[]);
  }

  #[test]
  pub fn peek() {
    let mut cur = Cursor::new(vec![1, 2, 3]);
    assert_eq!(cur.peek(2), &[1, 2]);
    assert_eq!(cur.peek(1), &[1]);
    assert_eq!(cur.peek(4), &[1, 2, 3]);
    cur.take(3);
    assert_eq!(cur.peek(1), &[]);
  }

  #[test]
  pub fn take_exact() {
    let mut cur = Cursor::new(vec![1, 2, 3]);
    assert_eq!(cur.take_exact(2), Some([1, 2].as_ref()));
    assert_eq!(cur.take_exact(2), None);
    assert_eq!(cur.take_exact(1), Some([3].as_ref()));
  }

  #[test]
  pub fn peek_exact() {
    let cur = Cursor::new(vec![1, 2, 3]);
    assert_eq!(cur.peek_exact(3), Some([1, 2, 3].as_ref()));
    assert_eq!(cur.peek_exact(1), Some([1].as_ref()));
    assert_eq!(cur.peek_exact(4), None);
  }

  #[test]
  pub fn take_while() {
    let til_slash = |c: &mut Cursor<&str>| {
      core::str::from_utf8(c.take_while(|b| (b as char) != '/')).unwrap()
                                                                .to_string()
    };

    let mut cur = Cursor::new("abc/def");
    assert_eq!(til_slash(&mut cur), "abc".to_string());
    cur.skip(1);
    assert_eq!(til_slash(&mut cur), "def".to_string());
    assert_eq!(til_slash(&mut cur), "".to_string());

    let mut cur = Cursor::new("a");
    assert_eq!(til_slash(&mut cur), "a");

    let mut cur = Cursor::new("");
    assert_eq!(til_slash(&mut cur), "");

    let mut cur = Cursor::new("ab");
    assert_eq!(til_slash(&mut cur), "ab");

    let mut cur = Cursor::new("/abcd");
    assert_eq!(til_slash(&mut cur), "");
  }

  #[test]
  pub fn seek() {
    let mut cur = Cursor::new(vec![1, 2, 3, 4]);
    assert_eq!(cur.skip(0), 0); // 0 <- cursor
    assert_eq!(cur.skip(1), 1); // 1
    assert_eq!(cur.skip(2), 2); // 3
    assert_eq!(cur.skip(1), 1); // 4
    assert_eq!(cur.skip(1), 0); // 4
  }
}