safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! Fixed-buffer writing support for `no_std` / zero-allocation callers.
//!
//! [`SliceWriter`] implements [`core::fmt::Write`] over a caller-provided
//! `&mut [u8]`, so every `_to` function in this crate can format directly
//! into a stack buffer. It is the backing for the safe `*_into` constructors
//! on the borrowed safe types (e.g.
//! [`SafeHtmlStr::escape_into`](crate::SafeHtmlStr::escape_into)), which
//! wrap escaper output without any `unsafe` on the caller's side.

/// Error returned when a fixed-size buffer is too small for the output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CapacityError;

impl core::fmt::Display for CapacityError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("output exceeded the provided buffer capacity")
    }
}

impl core::error::Error for CapacityError {}

/// A [`core::fmt::Write`] implementation over a caller-provided byte buffer.
///
/// Writes are all-or-nothing: a `write_str` that does not fit leaves the
/// buffer contents and length unchanged and reports [`core::fmt::Error`], so
/// the written prefix is always complete, valid UTF-8.
///
/// ```rust
/// use core::fmt::Write;
/// use safehtml::{SliceWriter, escape_html_and_coerce_to};
///
/// let mut buf = [0u8; 64];
/// let mut w = SliceWriter::new(&mut buf);
/// escape_html_and_coerce_to("<b>", &mut w).unwrap();
/// assert_eq!(w.as_str(), "&lt;b&gt;");
/// ```
#[derive(Debug)]
pub struct SliceWriter<'a> {
    buf: &'a mut [u8],
    len: usize,
}

impl<'a> SliceWriter<'a> {
    /// Creates a writer over `buf`, starting empty.
    pub fn new(buf: &'a mut [u8]) -> Self {
        SliceWriter { buf, len: 0 }
    }

    /// Number of bytes written so far.
    pub fn len(&self) -> usize {
        self.len
    }

    /// True if nothing has been written yet.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Remaining capacity in bytes.
    pub fn remaining(&self) -> usize {
        self.buf.len() - self.len
    }

    /// The written prefix as a string slice.
    pub fn as_str(&self) -> &str {
        core::str::from_utf8(self.buf.get(..self.len).unwrap_or(&[])).unwrap_or("")
    }

    /// Consumes the writer, returning the written prefix with the buffer's
    /// lifetime.
    pub fn finish(self) -> &'a str {
        let end = self.len.min(self.buf.len());
        let (written, _) = self.buf.split_at(end);
        core::str::from_utf8(written).unwrap_or("")
    }
}

impl core::fmt::Write for SliceWriter<'_> {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        let bytes = s.as_bytes();
        let end = self.len.checked_add(bytes.len()).ok_or(core::fmt::Error)?;
        let dst = self.buf.get_mut(self.len..end).ok_or(core::fmt::Error)?;
        dst.copy_from_slice(bytes);
        self.len = end;
        Ok(())
    }
}