oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
Documentation
//! Byte spans and source locations.

/// Stable index of a source registered in a source map.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FileId(pub u32);

/// A half-open UTF-8 byte range in one source.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Span {
    /// Source containing the range.
    pub file: FileId,
    /// Inclusive byte offset.
    pub start: u32,
    /// Exclusive byte offset.
    pub end: u32,
}

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

    /// Returns the smallest range containing both spans in this source.
    /// If the spans belong to different sources, returns this span.
    pub fn cover(self, other: Self) -> Self {
        if self.file != other.file {
            return self;
        }
        Self::new(
            self.file,
            self.start.min(other.start),
            self.end.max(other.end),
        )
    }

    /// Retrieves the range from its source text.
    pub fn slice(self, text: &str) -> Option<&str> {
        text.get(self.start as usize..self.end as usize)
    }
}

/// A human-readable source location.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Location<'a> {
    /// Source name or path.
    pub name: &'a str,
    /// One-based line number.
    pub line: usize,
    /// One-based column in Unicode scalar values.
    pub column: usize,
}

#[derive(Debug)]
struct File {
    name: String,
    text: String,
    lines: Vec<usize>,
}

/// Sources with indexed line starts. CRLF counts as one newline.
#[derive(Debug, Default)]
pub struct SourceMap {
    files: Vec<File>,
}

impl SourceMap {
    /// Creates an empty map.
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn next_file_id(&self) -> Option<FileId> {
        u32::try_from(self.files.len()).ok().map(FileId)
    }

    /// Registers a source. Returns `None` if its bytes or identifier cannot fit in a span.
    pub fn add(&mut self, name: impl Into<String>, text: impl Into<String>) -> Option<FileId> {
        let text = text.into();
        u32::try_from(text.len()).ok()?;
        let id = FileId(u32::try_from(self.files.len()).ok()?);
        let mut lines = vec![0];
        let mut bytes = text.bytes().enumerate().peekable();
        while let Some((index, byte)) = bytes.next() {
            if byte == b'\r' && bytes.peek().is_some_and(|(_, next)| *next == b'\n') {
                bytes.next();
                lines.push(index + 2);
            } else if matches!(byte, b'\r' | b'\n') {
                lines.push(index + 1);
            }
        }
        self.files.push(File {
            name: name.into(),
            text,
            lines,
        });
        Some(id)
    }

    /// Returns the source text associated with the identifier.
    pub fn source(&self, id: FileId) -> Option<&str> {
        Some(&self.files.get(id.0 as usize)?.text)
    }

    /// Looks up the start of a span.
    pub fn location(&self, span: Span) -> Option<Location<'_>> {
        let file = self.files.get(span.file.0 as usize)?;
        let offset = span.start as usize;
        let line = file.lines.partition_point(|start| *start <= offset);
        let prefix = file.text.get(file.lines[line - 1]..offset)?;
        Some(Location {
            name: &file.name,
            line,
            column: prefix.chars().count() + 1,
        })
    }
}