musli_zerocopy/buf/
visit.rs

1use crate::buf::{Buf, Load};
2use crate::endian::ByteOrder;
3use crate::error::Error;
4use crate::pointer::{Pointee, Ref, Size};
5
6/// Trait used for accessing the value behind a reference when interacting with
7/// higher level containers such as [`phf`] or [`swiss`].
8///
9/// This is a high level trait which can be implemented safely, typically it's
10/// used to build facade types for when you want some type to behave like a
11/// different type, but have a different layout.
12///
13/// See the [module level documentation][crate::buf#extension-traits] for an
14/// example.
15///
16/// [`phf`]: crate::phf
17/// [`swiss`]: crate::swiss
18pub trait Visit {
19    /// The target type being visited.
20    type Target: ?Sized;
21
22    /// Validate the value.
23    fn visit<V, O>(&self, buf: &Buf, visitor: V) -> Result<O, Error>
24    where
25        V: FnOnce(&Self::Target) -> O;
26}
27
28impl<T: ?Sized> Visit for &T {
29    type Target = T;
30
31    fn visit<V, O>(&self, _: &Buf, visitor: V) -> Result<O, Error>
32    where
33        V: FnOnce(&Self::Target) -> O,
34    {
35        Ok(visitor(*self))
36    }
37}
38
39impl<T, E, O> Visit for Ref<T, E, O>
40where
41    Self: Load,
42    T: ?Sized + Pointee,
43    E: ByteOrder,
44    O: Size,
45{
46    type Target = <Self as Load>::Target;
47
48    #[inline]
49    fn visit<V, U>(&self, buf: &Buf, visitor: V) -> Result<U, Error>
50    where
51        V: FnOnce(&Self::Target) -> U,
52    {
53        let value = buf.load(*self)?;
54        Ok(visitor(value))
55    }
56}
57
58impl Visit for str {
59    type Target = str;
60
61    #[inline]
62    fn visit<V, O>(&self, _: &Buf, visitor: V) -> Result<O, Error>
63    where
64        V: FnOnce(&Self::Target) -> O,
65    {
66        Ok(visitor(self))
67    }
68}
69
70impl<T> Visit for [T] {
71    type Target = [T];
72
73    #[inline]
74    fn visit<V, O>(&self, _: &Buf, visitor: V) -> Result<O, Error>
75    where
76        V: FnOnce(&Self::Target) -> O,
77    {
78        Ok(visitor(self))
79    }
80}