Skip to content

Getter Macro Improvements#87

Merged
soareschen merged 7 commits intomainfrom
mref-getter
Apr 16, 2025
Merged

Getter Macro Improvements#87
soareschen merged 7 commits intomainfrom
mref-getter

Conversation

@soareschen
Copy link
Collaborator

@soareschen soareschen commented Apr 16, 2025

Summary

This PR brings improvements to the #[cgp_getter] macro to support new kinds of getter fields to be derived.

Slice Field

A getter method that returns slice reference, e.g. &[u8] can now be implemented with field types that implement AsRef.

Example:

#[cgp_auto_getter]
pub trait HasBytes {
    fn bytes(&self) -> &[u8];
}

Maybe Reference

A new MRef type is introduced to allow either reference or owned value to be returned:

pub enum MRef<'a, T> {
    Ref(&'a T),
    Owned(T),
}

This type will be useful for custom field getter implementations, so that they can return owned values in case when it is a virtual field that is not directly present within a context.

The default UseField implementation will still require an actual field to be present, and use MRef::Ref to return the borrowed value.

Example:

#[cgp_getter {
    provider: NameGetter,
}]
pub trait HasName {
    fn name(&self) -> MRef<'_, String>;
}

@soareschen soareschen merged commit 55882f2 into main Apr 16, 2025
5 checks passed
@soareschen soareschen deleted the mref-getter branch April 16, 2025 21:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant