Skip to main content

webc/v2/
span.rs

1use std::ops::Index;
2
3/// The location of something within a larger buffer.
4#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
5pub struct Span {
6    /// The start of an item, relative to the start of the file.
7    pub start: usize,
8    /// The number of bytes in this item.
9    pub len: usize,
10}
11
12impl Span {
13    /// Create a new [`Span`].
14    pub const fn new(start: usize, len: usize) -> Self {
15        Self { start, len }
16    }
17
18    /// Get the offset one past the end.
19    pub const fn end(self) -> usize {
20        self.start + self.len
21    }
22
23    pub const fn with_offset(self, delta: usize) -> Self {
24        Span::new(self.start + delta, self.len)
25    }
26}
27
28impl Index<Span> for [u8] {
29    type Output = [u8];
30
31    #[track_caller]
32    fn index(&self, index: Span) -> &Self::Output {
33        &self[index.start..index.end()]
34    }
35}