pub struct Accessor<T, F> { /* private fields */ }Expand description
A small, copyable accessor that focuses into a field F inside a root T.
Representation: a byte offset from the start of T to the field F. This allows cheap composition by offset addition. All operations are implemented via unsafe pointer arithmetic but expose a safe API.
Implementations§
Source§impl<T, F> Accessor<T, F>
impl<T, F> Accessor<T, F>
Sourcepub const unsafe fn from_offset(offset: isize) -> Self
pub const unsafe fn from_offset(offset: isize) -> Self
Construct from a precomputed byte offset.
§Safety
The offset must satisfy all of the following conditions for every valid instance of T:
- It is the exact byte distance from the start of
Tto the target fieldFwithin the same allocation (i.e., derived from an actual field projection ofT). - The resulting pointer computed as
(&T as *const u8).offset(offset) as *const Fis properly aligned forFand points to initialized memory owned by the sameTobject. - The accessor will only ever be used with values of type
Tthat have the same layout with respect to the fieldF(e.g., not a different type or transmuted layout).
Violating any of these preconditions is undefined behavior. Prefer constructing accessors
via #[derive(Accessor)] or Accessor::from_fns, which compute valid offsets for you.
Sourcepub fn from_fns(get_ref: fn(&T) -> &F, _get_mut: fn(&mut T) -> &mut F) -> Self
pub fn from_fns(get_ref: fn(&T) -> &F, _get_mut: fn(&mut T) -> &mut F) -> Self
Runtime constructor from field-selection functions. Computes the offset using raw pointer projection without dereferencing invalid memory.
Sourcepub fn set_mut(&self, root: &mut T, f: impl FnOnce(&mut F))
pub fn set_mut(&self, root: &mut T, f: impl FnOnce(&mut F))
Mutate the focused location in-place using the provided closure.
Sourcepub fn set_clone(&self, root: &mut T, value: &F)where
F: Clone,
pub fn set_clone(&self, root: &mut T, value: &F)where
F: Clone,
Set by cloning the provided value into the focused location.
MVP semantics:
- The caller provides a shared reference to the value, and we perform a top-level
Cloneof that value, then move it into the field. - Only
F: Cloneis required; the root typeTdoes not need to implementClone. - This behavior composes: for a composed accessor focusing
T -> ... -> V, callingset_cloneonly requiresV: Clone.
Trait Implementations§
Source§impl<T, E> Indexing<T, E> for Accessor<T, Vec<E>>
impl<T, E> Indexing<T, E> for Accessor<T, Vec<E>>
Source§fn get_at<'a>(&self, root: &'a T, idx: usize) -> &'a E
fn get_at<'a>(&self, root: &'a T, idx: usize) -> &'a E
idx immutably. Read moreSource§fn get_mut_at<'a>(&self, root: &'a mut T, idx: usize) -> &'a mut E
fn get_mut_at<'a>(&self, root: &'a mut T, idx: usize) -> &'a mut E
idx mutably.Source§fn set_at(&self, root: &mut T, idx: usize, value: E)
fn set_at(&self, root: &mut T, idx: usize, value: E)
idx by moving value in.