Accessor

Struct Accessor 

Source
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>

Source

pub const unsafe fn from_offset(offset: isize) -> Accessor<T, F>

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 T to the target field F within the same allocation (i.e., derived from an actual field projection of T).
  • The resulting pointer computed as (&T as *const u8).offset(offset) as *const F is properly aligned for F and points to initialized memory owned by the same T object.
  • The accessor will only ever be used with values of type T that have the same layout with respect to the field F (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.

Source

pub fn from_fns( get_ref: fn(&T) -> &F, _get_mut: fn(&mut T) -> &mut F, ) -> Accessor<T, F>

Runtime constructor from field-selection functions. Computes the offset using raw pointer projection without dereferencing invalid memory.

Source

pub fn get<'a>(&self, root: &'a T) -> &'a F

Borrow the focused field immutably.

Examples found in repository?
examples/derive_deep.rs (line 58)
37fn main() {
38    let mut user = User {
39        profile: Profile {
40            address: Address {
41                city: "berlin".into(),
42                zip: 10115,
43            },
44            stats: Stats { logins: 1 },
45        },
46        settings: Settings {
47            theme: Theme {
48                name: "light".into(),
49            },
50        },
51    };
52
53    // Compose a deep accessor: User -> Profile -> Address -> city
54    let acc_city = User::acc_profile()
55        .compose(Profile::acc_address())
56        .compose(Address::acc_city());
57
58    println!("city before: {}", acc_city.get(&user));
59
60    // In-place deep mutation via set_mut
61    acc_city.set_mut(&mut user, |c| c.make_ascii_uppercase());
62    println!("city upper: {}", acc_city.get(&user));
63
64    // Set via cloning only the leaf value
65    let new_city = String::from("Lund");
66    acc_city.set_clone(&mut user, &new_city);
67    println!("city after set_clone: {}", acc_city.get(&user));
68
69    // Compose another deep accessor: User -> Settings -> Theme -> name
70    let acc_theme_name = User::acc_settings()
71        .compose(Settings::acc_theme())
72        .compose(Theme::acc_name());
73
74    acc_theme_name.set(&mut user, "dark".to_string());
75    println!("theme after set: {}", acc_theme_name.get(&user));
76
77    // Show a non-string leaf with arithmetic updates
78    let acc_zip = User::acc_profile()
79        .compose(Profile::acc_address())
80        .compose(Address::acc_zip());
81
82    acc_zip.set_mut(&mut user, |z| *z += 5);
83    println!("zip after +5: {}", acc_zip.get(&user));
84}
Source

pub fn get_mut<'a>(&self, root: &'a mut T) -> &'a mut F

Borrow the focused field mutably.

Source

pub fn set(&self, root: &mut T, value: F)

Set by moving a new value into the focused location.

Examples found in repository?
examples/derive_deep.rs (line 74)
37fn main() {
38    let mut user = User {
39        profile: Profile {
40            address: Address {
41                city: "berlin".into(),
42                zip: 10115,
43            },
44            stats: Stats { logins: 1 },
45        },
46        settings: Settings {
47            theme: Theme {
48                name: "light".into(),
49            },
50        },
51    };
52
53    // Compose a deep accessor: User -> Profile -> Address -> city
54    let acc_city = User::acc_profile()
55        .compose(Profile::acc_address())
56        .compose(Address::acc_city());
57
58    println!("city before: {}", acc_city.get(&user));
59
60    // In-place deep mutation via set_mut
61    acc_city.set_mut(&mut user, |c| c.make_ascii_uppercase());
62    println!("city upper: {}", acc_city.get(&user));
63
64    // Set via cloning only the leaf value
65    let new_city = String::from("Lund");
66    acc_city.set_clone(&mut user, &new_city);
67    println!("city after set_clone: {}", acc_city.get(&user));
68
69    // Compose another deep accessor: User -> Settings -> Theme -> name
70    let acc_theme_name = User::acc_settings()
71        .compose(Settings::acc_theme())
72        .compose(Theme::acc_name());
73
74    acc_theme_name.set(&mut user, "dark".to_string());
75    println!("theme after set: {}", acc_theme_name.get(&user));
76
77    // Show a non-string leaf with arithmetic updates
78    let acc_zip = User::acc_profile()
79        .compose(Profile::acc_address())
80        .compose(Address::acc_zip());
81
82    acc_zip.set_mut(&mut user, |z| *z += 5);
83    println!("zip after +5: {}", acc_zip.get(&user));
84}
Source

pub fn set_mut(&self, root: &mut T, f: impl FnOnce(&mut F))

Mutate the focused location in-place using the provided closure.

Examples found in repository?
examples/derive_deep.rs (line 61)
37fn main() {
38    let mut user = User {
39        profile: Profile {
40            address: Address {
41                city: "berlin".into(),
42                zip: 10115,
43            },
44            stats: Stats { logins: 1 },
45        },
46        settings: Settings {
47            theme: Theme {
48                name: "light".into(),
49            },
50        },
51    };
52
53    // Compose a deep accessor: User -> Profile -> Address -> city
54    let acc_city = User::acc_profile()
55        .compose(Profile::acc_address())
56        .compose(Address::acc_city());
57
58    println!("city before: {}", acc_city.get(&user));
59
60    // In-place deep mutation via set_mut
61    acc_city.set_mut(&mut user, |c| c.make_ascii_uppercase());
62    println!("city upper: {}", acc_city.get(&user));
63
64    // Set via cloning only the leaf value
65    let new_city = String::from("Lund");
66    acc_city.set_clone(&mut user, &new_city);
67    println!("city after set_clone: {}", acc_city.get(&user));
68
69    // Compose another deep accessor: User -> Settings -> Theme -> name
70    let acc_theme_name = User::acc_settings()
71        .compose(Settings::acc_theme())
72        .compose(Theme::acc_name());
73
74    acc_theme_name.set(&mut user, "dark".to_string());
75    println!("theme after set: {}", acc_theme_name.get(&user));
76
77    // Show a non-string leaf with arithmetic updates
78    let acc_zip = User::acc_profile()
79        .compose(Profile::acc_address())
80        .compose(Address::acc_zip());
81
82    acc_zip.set_mut(&mut user, |z| *z += 5);
83    println!("zip after +5: {}", acc_zip.get(&user));
84}
Source

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 Clone of that value, then move it into the field.
  • Only F: Clone is required; the root type T does not need to implement Clone.
  • This behavior composes: for a composed accessor focusing T -> ... -> V, calling set_clone only requires V: Clone.
Examples found in repository?
examples/derive_deep.rs (line 66)
37fn main() {
38    let mut user = User {
39        profile: Profile {
40            address: Address {
41                city: "berlin".into(),
42                zip: 10115,
43            },
44            stats: Stats { logins: 1 },
45        },
46        settings: Settings {
47            theme: Theme {
48                name: "light".into(),
49            },
50        },
51    };
52
53    // Compose a deep accessor: User -> Profile -> Address -> city
54    let acc_city = User::acc_profile()
55        .compose(Profile::acc_address())
56        .compose(Address::acc_city());
57
58    println!("city before: {}", acc_city.get(&user));
59
60    // In-place deep mutation via set_mut
61    acc_city.set_mut(&mut user, |c| c.make_ascii_uppercase());
62    println!("city upper: {}", acc_city.get(&user));
63
64    // Set via cloning only the leaf value
65    let new_city = String::from("Lund");
66    acc_city.set_clone(&mut user, &new_city);
67    println!("city after set_clone: {}", acc_city.get(&user));
68
69    // Compose another deep accessor: User -> Settings -> Theme -> name
70    let acc_theme_name = User::acc_settings()
71        .compose(Settings::acc_theme())
72        .compose(Theme::acc_name());
73
74    acc_theme_name.set(&mut user, "dark".to_string());
75    println!("theme after set: {}", acc_theme_name.get(&user));
76
77    // Show a non-string leaf with arithmetic updates
78    let acc_zip = User::acc_profile()
79        .compose(Profile::acc_address())
80        .compose(Address::acc_zip());
81
82    acc_zip.set_mut(&mut user, |z| *z += 5);
83    println!("zip after +5: {}", acc_zip.get(&user));
84}
Source

pub fn compose<V>(self, next: Accessor<F, V>) -> Accessor<T, V>

Compose this accessor with another, yielding an accessor from T to V.

Given self: Accessor<T, U> and next: Accessor<U, V>, returns Accessor<T, V> that focuses by first going through self then next.

Examples found in repository?
examples/derive_deep.rs (line 55)
37fn main() {
38    let mut user = User {
39        profile: Profile {
40            address: Address {
41                city: "berlin".into(),
42                zip: 10115,
43            },
44            stats: Stats { logins: 1 },
45        },
46        settings: Settings {
47            theme: Theme {
48                name: "light".into(),
49            },
50        },
51    };
52
53    // Compose a deep accessor: User -> Profile -> Address -> city
54    let acc_city = User::acc_profile()
55        .compose(Profile::acc_address())
56        .compose(Address::acc_city());
57
58    println!("city before: {}", acc_city.get(&user));
59
60    // In-place deep mutation via set_mut
61    acc_city.set_mut(&mut user, |c| c.make_ascii_uppercase());
62    println!("city upper: {}", acc_city.get(&user));
63
64    // Set via cloning only the leaf value
65    let new_city = String::from("Lund");
66    acc_city.set_clone(&mut user, &new_city);
67    println!("city after set_clone: {}", acc_city.get(&user));
68
69    // Compose another deep accessor: User -> Settings -> Theme -> name
70    let acc_theme_name = User::acc_settings()
71        .compose(Settings::acc_theme())
72        .compose(Theme::acc_name());
73
74    acc_theme_name.set(&mut user, "dark".to_string());
75    println!("theme after set: {}", acc_theme_name.get(&user));
76
77    // Show a non-string leaf with arithmetic updates
78    let acc_zip = User::acc_profile()
79        .compose(Profile::acc_address())
80        .compose(Address::acc_zip());
81
82    acc_zip.set_mut(&mut user, |z| *z += 5);
83    println!("zip after +5: {}", acc_zip.get(&user));
84}

Trait Implementations§

Source§

impl<T, F> Clone for Accessor<T, F>
where T: Clone, F: Clone,

Source§

fn clone(&self) -> Accessor<T, F>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T, F> Debug for Accessor<T, F>
where T: Debug, F: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<T, E> Indexing<T, E> for Accessor<T, Vec<E>>

Source§

fn get_at<'a>(&self, root: &'a T, idx: usize) -> &'a E

Source§

fn get_mut_at<'a>(&self, root: &'a mut T, idx: usize) -> &'a mut E

Source§

fn set_at(&self, root: &mut T, idx: usize, value: E)

Source§

fn set_mut_at(&self, root: &mut T, idx: usize, f: impl FnOnce(&mut E))

Source§

fn set_clone_at(&self, root: &mut T, idx: usize, value: &E)
where E: Clone,

Source§

impl<T, F> Copy for Accessor<T, F>
where T: Copy, F: Copy,

Auto Trait Implementations§

§

impl<T, F> Freeze for Accessor<T, F>

§

impl<T, F> RefUnwindSafe for Accessor<T, F>

§

impl<T, F> Send for Accessor<T, F>

§

impl<T, F> Sync for Accessor<T, F>

§

impl<T, F> Unpin for Accessor<T, F>

§

impl<T, F> UnwindSafe for Accessor<T, F>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.