lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
Documentation
/// Half-open UTF-8 byte range relative to one source file.
///
/// A span covers `start..end`. Offsets are bytes, not Unicode scalar or display
/// columns, and are only meaningful with the source that produced them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
    /// Inclusive start byte offset.
    pub start: u32,
    /// Exclusive end byte offset.
    pub end: u32,
}

impl Span {
    /// Creates a half-open byte span.
    pub const fn new(start: u32, end: u32) -> Self {
        Self { start, end }
    }

    /// Converts this span to an indexing range.
    pub const fn range(self) -> std::ops::Range<usize> {
        self.start as usize..self.end as usize
    }

    /// Returns the covered source slice when both offsets are valid UTF-8
    /// boundaries and lie within `source`.
    pub fn slice<'source>(self, source: &'source str) -> Option<&'source str> {
        source.get(self.range())
    }
}

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

    #[test]
    fn spans_use_half_open_utf8_byte_offsets() {
        let source = "a✓z";
        let checkmark = Span::new(1, 4);

        assert_eq!(checkmark.slice(source), Some("✓"));
        assert_eq!(checkmark.range(), 1..4);
        assert_eq!(Span::new(1, 3).slice(source), None);
    }
}

impl chumsky::span::Span for Span {
    type Context = ();

    type Offset = u32;

    fn new(_context: Self::Context, range: std::ops::Range<Self::Offset>) -> Self {
        Self {
            start: range.start,
            end: range.end,
        }
    }

    fn context(&self) -> Self::Context {
        ()
    }

    fn start(&self) -> Self::Offset {
        self.start
    }

    fn end(&self) -> Self::Offset {
        self.end
    }
}