foundation_core 0.0.5

Central crate for all foundation crates for the ewe-platform project
Documentation
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/// Bytes provides an abstraction of a slice of bytes (u8)
/// letting you advance, track and safely move through a slice
/// of bytes easily.
///
/// This is taking from the [httpparse](https://github.com/seanmonstar/httparse) crate.
pub struct Bytes<'a> {
    start: *const u8,
    end: *const u8,
    /// INVARIANT: start <= cursor && cursor <= end
    cursor: *const u8,
    phantom: core::marker::PhantomData<&'a ()>,
}

#[allow(missing_docs)]
impl<'a> Bytes<'a> {
    #[inline]
    #[must_use]
    pub fn new(slice: &'a [u8]) -> Bytes<'a> {
        let start = slice.as_ptr();
        // SAFETY: obtain pointer to slice end; start points to slice start.
        let end = unsafe { start.add(slice.len()) };
        let cursor = start;
        Bytes {
            start,
            end,
            cursor,
            phantom: core::marker::PhantomData,
        }
    }

    #[inline]
    #[must_use]
    pub fn pos(&self) -> usize {
        self.cursor as usize - self.start as usize
    }

    #[inline]
    #[must_use]
    pub fn peek(&self) -> Option<u8> {
        if self.cursor < self.end {
            // SAFETY:  bounds checked
            Some(unsafe { *self.cursor })
        } else {
            None
        }
    }

    #[inline]
    #[must_use]
    pub fn peek_ahead(&self, n: usize) -> Option<u8> {
        // SAFETY: obtain a potentially OOB pointer that is later compared against the `self.end`
        // pointer.
        let ptr = self.cursor.wrapping_add(n);
        if ptr < self.end {
            // SAFETY: bounds checked pointer dereference is safe
            Some(unsafe { *ptr })
        } else {
            None
        }
    }

    #[inline]
    #[must_use]
    pub fn peek_n<'b: 'a, U: TryFrom<&'a [u8]>>(&'b self, n: usize) -> Option<U> {
        // TODO: once we bump MSRC, use const generics to allow only [u8; N] reads
        // TODO: drop `n` arg in favour of const
        // let n = core::mem::size_of::<U>();
        self.as_ref().get(..n)?.try_into().ok()
    }

    /// Advance by 1, equivalent to calling `advance(1)`.
    ///
    /// # Safety
    ///
    /// Caller must ensure that Bytes hasn't been advanced/bumped by more than [`Bytes::len()`].
    #[inline]
    pub unsafe fn bump(&mut self) {
        self.advance(1);
    }

    /// Advance cursor by `n`
    ///
    /// # Safety
    ///
    /// Caller must ensure that Bytes hasn't been advanced/bumped by more than [`Bytes::len()`].
    #[inline]
    pub unsafe fn advance(&mut self, n: usize) {
        self.cursor = self.cursor.add(n);
        debug_assert!(self.cursor <= self.end, "overflow");
    }

    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.end as usize - self.cursor as usize
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[inline]
    pub fn slice(&mut self) -> &'a [u8] {
        // SAFETY: not moving position at all, so it's safe
        let slice = unsafe { slice_from_ptr_range(self.start, self.cursor) };
        self.commit();
        slice
    }

    // TODO: this is an anti-pattern, should be removed
    /// Deprecated. Do not use!
    /// # Safety
    ///
    /// Caller must ensure that `skip` is at most the number of advances (i.e., `bytes.advance(3)`
    /// implies a skip of at most 3).
    #[inline]
    pub unsafe fn slice_skip(&mut self, skip: usize) -> &'a [u8] {
        debug_assert!(skip <= self.cursor.offset_from(self.start).cast_unsigned());
        let head = slice_from_ptr_range(self.start, self.cursor.sub(skip));
        self.commit();
        head
    }

    #[inline]
    pub fn commit(&mut self) {
        self.start = self.cursor;
    }

    /// # Safety
    ///
    /// see [`Bytes::advance`] safety comment.
    #[inline]
    pub unsafe fn advance_and_commit(&mut self, n: usize) {
        self.advance(n);
        self.commit();
    }

    #[inline]
    #[must_use]
    pub fn as_ptr(&self) -> *const u8 {
        self.cursor
    }

    #[inline]
    #[must_use]
    pub fn start(&self) -> *const u8 {
        self.start
    }

    #[inline]
    #[must_use]
    pub fn end(&self) -> *const u8 {
        self.end
    }

    /// # Safety
    ///
    /// Must ensure invariant `bytes.start() <= ptr && ptr <= bytes.end()`.
    #[inline]
    pub unsafe fn set_cursor(&mut self, ptr: *const u8) {
        debug_assert!(ptr >= self.start);
        debug_assert!(ptr <= self.end);
        self.cursor = ptr;
    }
}

impl AsRef<[u8]> for Bytes<'_> {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        // SAFETY: not moving position at all, so it's safe
        unsafe { slice_from_ptr_range(self.cursor, self.end) }
    }
}

/// # Safety
///
/// Must ensure start and end point to the same memory object to uphold memory safety.
#[inline]
unsafe fn slice_from_ptr_range<'a>(start: *const u8, end: *const u8) -> &'a [u8] {
    debug_assert!(start <= end);
    core::slice::from_raw_parts(start, end as usize - start as usize)
}

impl Iterator for Bytes<'_> {
    type Item = u8;

    #[inline]
    fn next(&mut self) -> Option<u8> {
        if self.cursor < self.end {
            // SAFETY: bounds checked dereference
            unsafe {
                let b = *self.cursor;
                self.bump();
                Some(b)
            }
        } else {
            None
        }
    }
}

#[derive(Clone, Debug)]
pub struct BytesPointer<'a> {
    content: &'a [u8],
    pos: usize,
    peek_pos: usize,
}

impl<'a> BytesPointer<'a> {
    #[must_use]
    pub fn new(content: &'a [u8]) -> Self {
        Self {
            content,
            pos: 0,
            peek_pos: 0,
        }
    }

    #[inline]
    #[must_use]
    pub fn content(&self) -> &'a [u8] {
        self.content
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.content.is_empty()
    }

    /// Returns the total length of the string being accumulated on.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.content.len()
    }

    /// Returns the distance between the peek position and the actual cursor
    /// position.
    #[inline]
    #[must_use]
    pub fn distance(&self) -> usize {
        self.peek_pos - self.pos
    }

    /// `peek_rem_len` returns the remaining count of strings
    /// left from the current peeks's cursor.
    #[inline]
    #[must_use]
    pub fn peek_rem_len(&self) -> usize {
        (self.content[self.peek_pos..]).len()
    }

    /// `rem_len` returns the remaining count of strings
    /// left from the current position's cursor
    /// regardless of where the peek cursor is at.
    #[inline]
    #[must_use]
    pub fn rem_len(&self) -> usize {
        (self.content[self.pos..]).len()
    }

    /// resets resets the location of the cursors for both read and peek to 0.
    /// Basically moving them to the start position.
    #[inline]
    pub fn reset(&mut self) {
        self.reset_to(0);
    }

    /// `reset_to` lets you reset the position of the cursor for both
    /// position and peek to the to value.
    #[inline]
    pub fn reset_to(&mut self, to: usize) {
        self.pos = to;
        self.peek_pos = to;
    }

    /// `skip_with_position` will skip all the contents of the accumulator up to
    /// the current position of the peek cursor and return the difference
    /// between the `peek_pos` and position before moving the cursor forward.
    #[inline]
    pub fn skip_position(&mut self) -> usize {
        let diff = self.peek_pos - self.pos;
        self.pos = self.peek_pos;
        diff
    }

    /// skip will skip all the contents of the accumulator up to
    /// the current position of the peek cursor.
    #[inline]
    pub fn skip(&mut self) {
        self.pos = self.peek_pos;
    }

    /// peek pulls the next token at the current peek position
    /// cursor which will
    #[inline]
    pub fn peek(&mut self, by: usize) -> Option<&'a [u8]> {
        self.peek_slice(by)
    }

    /// `peek_next` allows you to increment the peek cursor, moving
    /// the peek cursor forward by a step and returns the next
    /// token string.
    #[inline]
    pub fn peek_next(&mut self) -> Option<&'a [u8]> {
        if let Some(res) = self.peek_slice(1) {
            self.peek_pos += 1;
            return Some(res);
        }
        None
    }

    /// `peek_next` allows you to increment the peek cursor, moving
    /// the peek cursor forward by a mount of step and returns the next
    /// token string.
    #[inline]
    pub fn peek_next_by(&mut self, by: usize) -> Option<&'a [u8]> {
        if let Some(res) = self.peek_slice(by) {
            self.peek_pos += by;
            return Some(res);
        }
        None
    }

    /// `unpeek_next` reverses the last forward move of the peek
    /// cursor by -1.
    #[inline]
    pub fn unpeek_next(&mut self) -> Option<&'a [u8]> {
        if let Some(res) = self.unpeek_slice(1) {
            return Some(res);
        }
        None
    }

    /// `unpeek_slice` lets you reverse the peek cursor position
    /// by a certain amount to reverse the forward movement.
    #[inline]
    fn unpeek_slice(&mut self, by: usize) -> Option<&'a [u8]> {
        if self.peek_pos == 0 {
            return None;
        }

        // unpeek only works when we are higher then current pos cursor.
        // it should have no effect when have not moved forward
        if self.peek_pos > self.pos {
            self.peek_pos -= 1;
        }

        let new_peek_pos = self.peek_pos + by;
        Some(&self.content[self.peek_pos..new_peek_pos])
    }

    /// scan returns the whole string slice currently at the points of where
    /// the main pos (position) cursor till the end.
    #[inline]
    pub fn scan_remaining(&mut self) -> Option<&'a [u8]> {
        Some(&self.content[self.pos..])
    }

    /// scan returns the whole string slice currently at the points of where
    /// the main pos (position) cursor and the peek cursor so you can
    /// pull the string right at the current range.
    #[inline]
    pub fn scan(&mut self) -> Option<&'a [u8]> {
        Some(&self.content[self.pos..self.peek_pos])
    }

    /// `ppeek_at` allows you to do a non-permant position cursor adjustment
    /// by taking the current position cursor index with an adjustment
    /// where we add the `from` (pos + from) to get the new
    /// position to start from and `to` is added (pos + from + to)
    /// the position to end at, if the total is more than the length of the string
    /// then its adjusted to be the string last index for the slice.
    ///
    /// It's a nice way to get to see whats at a given position without changing
    /// the current location of the peek cursor.
    #[cfg_attr(feature = "trace_block", tracing::instrument(level = "trace"))]
    #[inline]
    pub fn ppeek_at(&mut self, from: usize, to: usize) -> Option<&'a [u8]> {
        let new_peek_pos = self.pos + from;
        let until_pos = if new_peek_pos + to > self.content.len() {
            self.content.len()
        } else {
            new_peek_pos + to
        };

        if new_peek_pos > self.content.len() {
            return None;
        }

        Some(&self.content[new_peek_pos..until_pos])
    }

    /// `vpeek_at` allows you to do a non-permant peek cursor adjustment
    /// by taking the current peek cursor position with an adjustment
    /// where we add the `from` (`peek_cursor` + from) to get the new
    /// position to start from and `to` is added (`peek_cursor` + from + to)
    /// the position to end at, if the total is more than the length of the string
    /// then its adjusted to be the string last index for the slice.
    ///
    /// It's a nice way to get to see whats at a given position without changing
    /// the current location of the peek cursor.
    #[cfg_attr(feature = "trace_block", tracing::instrument(level = "trace"))]
    #[inline]
    pub fn vpeek_at(&mut self, from: usize, to: usize) -> Option<&'a [u8]> {
        let new_peek_pos = self.peek_pos + from;
        let until_pos = if new_peek_pos + to > self.content.len() {
            self.content.len()
        } else {
            new_peek_pos + to
        };

        if new_peek_pos > self.content.len() {
            return None;
        }

        Some(&self.content[new_peek_pos..until_pos])
    }

    /// `peek_slice` allows you to peek forward by an amount
    /// from the current peek cursor position.
    ///
    /// If we've exhausted the total string slice left or are trying to
    /// take more than available text length then we return None
    /// which can indicate no more text for processing.
    #[cfg_attr(feature = "trace_block", tracing::instrument(level = "trace"))]
    #[inline]
    fn peek_slice(&mut self, by: usize) -> Option<&'a [u8]> {
        if self.peek_pos + by > self.content.len() {
            return None;
        }
        let from = self.peek_pos;
        let until_pos = self.peek_pos + by;
        Some(&self.content[from..until_pos])
    }

    /// take returns the total string slice from the
    /// actual accumulators position cursor til the current
    /// peek cursor position with adjustment on `by` amount i.e
    /// [u8][position_cursor..(peek_cursor + by_value)].
    ///
    /// Allow you to collect the whole slice of strings that have been
    /// checked and peeked through.
    ///
    /// If we've exhausted the total string slice left or are trying to
    /// take more than available text length then we return None
    /// which can indicate no more text for processing.
    #[cfg_attr(feature = "trace_block", tracing::instrument(level = "trace"))]
    #[inline]
    pub fn take_with_amount(&mut self, by: usize) -> Option<(&'a [u8], (usize, usize))> {
        if self.peek_pos + by > self.content.len() {
            return None;
        }

        let until_pos = if self.peek_pos + by > self.content.len() {
            self.content.len()
        } else {
            self.peek_pos + by
        };

        if self.pos >= self.content.len() {
            return None;
        }

        let from = self.pos;
        // tracing::debug!(
        //     "take_with_amount: possibly shift in positions: org:({}, {}) then end in final:({},{})",
        //     self.content.len(),
        //     self.pos,
        //     from,
        //     until_pos,
        // );

        let position = (from, until_pos);

        // tracing::debug!(
        //     "take_with_amount: content len: {} with pos: {}, peek_pos: {}, by: {}, until: {}",
        //     self.content.len(),
        //     self.pos,
        //     self.peek_pos,
        //     by,
        //     until_pos,
        // );

        let content_slice = &self.content[from..until_pos];

        // tracing::debug!(
        //     "take_with_amount: sliced worked from: {}, by: {}, till loc: {} with text: '{:?}'",
        //     self.pos,
        //     by,
        //     until_pos,
        //     content_slice,
        // );

        let res = Some((content_slice, position));
        self.pos = self.peek_pos;
        res
    }

    /// `take_positional` returns the total string slice from the
    /// actual accumulators position cursor til the current
    /// peek cursor position, i.e. the range from `position_cursor` to `peek_cursor`.
    /// Allow you to collect the whole slice of strings that have been
    /// checked and peeked through.
    #[inline]
    pub fn take_positional(&mut self) -> Option<(&'a [u8], (usize, usize))> {
        self.take_with_amount(0)
    }

    /// take returns the total string slice from the
    /// actual accumulators position cursor til the current
    /// peek cursor position, i.e. the range from `position_cursor` to `peek_cursor`.
    /// Allow you to collect the whole slice of strings that have been
    /// checked and peeked through.
    #[inline]
    pub fn take(&mut self) -> Option<&'a [u8]> {
        match self.take_with_amount(0) {
            Some((text, _)) => Some(text),
            None => None,
        }
    }
}