Crates.io | delegate-attr |
lib.rs | delegate-attr |
version | 0.3.0 |
source | src |
created_at | 2020-05-19 12:02:49.294156 |
updated_at | 2023-09-17 08:35:22.923197 |
description | Attribute proc-macro to delegate method to a field |
homepage | |
repository | https://github.com/upsuper/delegate-attr |
max_upload_size | |
id | 243433 |
size | 25,501 |
Attribute proc-macro to delegate method to a field.
impl
blockuse delegate_attr::delegate;
struct Foo(String);
#[delegate(self.0)]
impl Foo {
fn as_str(&self) -> &str {}
fn into_bytes(self) -> Vec<u8> {}
}
let foo = Foo("hello".to_owned());
assert_eq!(foo.as_str(), "hello");
assert_eq!(foo.into_bytes(), b"hello");
impl
struct Iter(std::vec::IntoIter<u8>);
#[delegate(self.0)]
impl Iterator for Iter {
type Item = u8;
fn next(&mut self) -> Option<u8> {}
fn count(self) -> usize {}
fn size_hint(&self) -> (usize, Option<usize>) {}
fn last(self) -> Option<u8> {}
}
let iter = Iter(vec![1, 2, 4, 8].into_iter());
assert_eq!(iter.count(), 4);
let iter = Iter(vec![1, 2, 4, 8].into_iter());
assert_eq!(iter.last(), Some(8));
let iter = Iter(vec![1, 2, 4, 8].into_iter());
assert_eq!(iter.sum::<u8>(), 15);
struct Foo<T> {
inner: RefCell<Vec<T>>,
}
#[delegate(self.inner.borrow())]
impl<T> Foo<T> {
fn len(&self) -> usize {}
}
#[delegate(self.inner.borrow_mut())]
impl<T> Foo<T> {
fn push(&self, value: T) {}
}
#[delegate(self.inner.into_inner())]
impl<T> Foo<T> {
fn into_boxed_slice(self) -> Box<[T]> {}
}
let foo = Foo { inner: RefCell::new(vec![1]) };
assert_eq!(foo.len(), 1);
foo.push(2);
assert_eq!(foo.len(), 2);
assert_eq!(foo.into_boxed_slice().as_ref(), &[1, 2]);
into
and call
attributestruct Inner;
impl Inner {
pub fn method(&self, num: u32) -> u32 { num }
}
struct Wrapper { inner: Inner }
#[delegate(self.inner)]
impl Wrapper {
// calls method, converts result to u64
#[into]
pub fn method(&self, num: u32) -> u64 {}
// calls method, returns ()
#[call(method)]
pub fn method_noreturn(&self, num: u32) {}
}
struct Foo<T>(Vec<T>);
impl<T> Foo<T> {
#[delegate(self.0)]
fn len(&self) -> usize {}
}
let foo = Foo(vec![1]);
assert_eq!(foo.len(), 1);