musli-zerocopy 0.0.77

Refreshingly simple zero copy primitives by Müsli.
Documentation
use crate::buf::{Buf, Load};
use crate::error::Error;

/// Trait used for accessing the value behind a reference when interacting with
/// higher level containers such as [`phf`] or [`swiss`].
///
/// This is a high level trait which can be implemented safely, typically it's
/// used to build facade types for when you want some type to behave like a
/// different type, but have a different layout.
///
/// See the [module level documentation][crate::buf#extension-traits] for an
/// example.
///
/// [`phf`]: crate::phf
/// [`swiss`]: crate::swiss
pub trait Visit {
    /// The target type being visited.
    type Target: ?Sized;

    /// Validate the value.
    fn visit<V, O>(&self, buf: &Buf, visitor: V) -> Result<O, Error>
    where
        V: FnOnce(&Self::Target) -> O;
}

impl<T: ?Sized> Visit for T
where
    T: Load,
{
    type Target = T::Target;

    #[inline]
    fn visit<V, O>(&self, buf: &Buf, visitor: V) -> Result<O, Error>
    where
        V: FnOnce(&Self::Target) -> O,
    {
        let value = buf.load(self)?;
        Ok(visitor(value))
    }
}

impl Visit for str {
    type Target = str;

    #[inline]
    fn visit<V, O>(&self, _: &Buf, visitor: V) -> Result<O, Error>
    where
        V: FnOnce(&Self::Target) -> O,
    {
        Ok(visitor(self))
    }
}

impl<T> Visit for [T] {
    type Target = [T];

    #[inline]
    fn visit<V, O>(&self, _: &Buf, visitor: V) -> Result<O, Error>
    where
        V: FnOnce(&Self::Target) -> O,
    {
        Ok(visitor(self))
    }
}