https://github.com/upsuper/delegate-attr
Attribute proc-macro to delegate method to a field
https://github.com/upsuper/delegate-attr
Last synced: 3 months ago
JSON representation
Attribute proc-macro to delegate method to a field
- Host: GitHub
- URL: https://github.com/upsuper/delegate-attr
- Owner: upsuper
- License: mit
- Created: 2020-05-19T12:05:13.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2023-09-17T08:35:13.000Z (almost 2 years ago)
- Last Synced: 2024-05-01T23:06:48.333Z (about 1 year ago)
- Language: Rust
- Size: 37.1 KB
- Stars: 26
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# delegate-attr
[](https://github.com/upsuper/delegate-attr/actions)
[](https://crates.io/crates/delegate-attr)Attribute proc-macro to delegate method to a field.
## Examples
### Delegate `impl` block
```rust
use delegate_attr::delegate;struct Foo(String);
#[delegate(self.0)]
impl Foo {
fn as_str(&self) -> &str {}
fn into_bytes(self) -> Vec {}
}let foo = Foo("hello".to_owned());
assert_eq!(foo.as_str(), "hello");
assert_eq!(foo.into_bytes(), b"hello");
```### Delegate trait `impl`
```rust
struct Iter(std::vec::IntoIter);
#[delegate(self.0)]
impl Iterator for Iter {
type Item = u8;
fn next(&mut self) -> Option {}
fn count(self) -> usize {}
fn size_hint(&self) -> (usize, Option) {}
fn last(self) -> Option {}
}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::(), 15);
```### With more complicated target
```rust
struct Foo {
inner: RefCell>,
}#[delegate(self.inner.borrow())]
impl Foo {
fn len(&self) -> usize {}
}#[delegate(self.inner.borrow_mut())]
impl Foo {
fn push(&self, value: T) {}
}#[delegate(self.inner.into_inner())]
impl Foo {
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` attribute
```rust
struct 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) {}
}
```### Delegate single method
```rust
struct Foo(Vec);impl Foo {
#[delegate(self.0)]
fn len(&self) -> usize {}
}let foo = Foo(vec![1]);
assert_eq!(foo.len(), 1);
```