| 1 | # Method delegation with less boilerplate |
| 2 | |
| 3 | [](https://github.com/kobzol/rust-delegate/actions) |
| 4 | [](https://crates.io/crates/delegate) |
| 5 | |
| 6 | This crate removes some boilerplate for structs that simply delegate some of |
| 7 | their methods to one or more of their fields. |
| 8 | |
| 9 | It gives you the `delegate!` macro, which delegates method calls to selected |
| 10 | expressions (usually inner fields). |
| 11 | |
| 12 | ## Example: |
| 13 | |
| 14 | A Stack data structure implemented using an inner Vec via delegation. |
| 15 | |
| 16 | ```rust |
| 17 | use delegate::delegate; |
| 18 | |
| 19 | #[derive(Clone, Debug)] |
| 20 | struct Stack<T> { |
| 21 | inner: Vec<T>, |
| 22 | } |
| 23 | impl<T> Stack<T> { |
| 24 | pub fn new() -> Self <T> { |
| 25 | Self { inner: vec![] } |
| 26 | } |
| 27 | |
| 28 | delegate! { |
| 29 | to self.inner { |
| 30 | pub fn is_empty(&self) -> bool; |
| 31 | pub fn push(&mut self, value: T); |
| 32 | pub fn pop(&mut self) -> Option<T>; |
| 33 | pub fn clear(&mut self); |
| 34 | |
| 35 | #[call(len)] |
| 36 | pub fn size(&self) -> usize; |
| 37 | |
| 38 | #[call(last)] |
| 39 | pub fn peek(&self) -> Option<&T>; |
| 40 | |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | ``` |
| 45 | |
| 46 | ## Features |
| 47 | |
| 48 | ### Delegate to a method with a different name |
| 49 | ```rust |
| 50 | struct Stack { |
| 51 | inner: Vec<u32> |
| 52 | } |
| 53 | impl Stack { |
| 54 | delegate! { |
| 55 | to self.inner { |
| 56 | #[call(push)] |
| 57 | pub fn add(&mut self, value: u32); |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | ``` |
| 62 | |
| 63 | ### Use an arbitrary inner field expression |
| 64 | ```rust |
| 65 | struct Wrapper { |
| 66 | inner: Rc<RefCell<Vec<u32>>> |
| 67 | } |
| 68 | impl Wrapper { |
| 69 | delegate! { |
| 70 | to self.inner.deref().borrow_mut() { |
| 71 | pub fn push(&mut self, val: u32); |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | ``` |
| 76 | |
| 77 | ### Delegate to enum variants |
| 78 | ```rust |
| 79 | use delegate::delegate; |
| 80 | |
| 81 | enum Enum { |
| 82 | A(A), |
| 83 | B(B), |
| 84 | C { v: C }, |
| 85 | } |
| 86 | |
| 87 | struct A { |
| 88 | val: usize, |
| 89 | } |
| 90 | |
| 91 | impl A { |
| 92 | fn dbg_inner(&self) -> usize { |
| 93 | dbg!(self.val); |
| 94 | 1 |
| 95 | } |
| 96 | } |
| 97 | struct B { |
| 98 | val_a: String, |
| 99 | } |
| 100 | |
| 101 | impl B { |
| 102 | fn dbg_inner(&self) -> usize { |
| 103 | dbg!(self.val_a.clone()); |
| 104 | 2 |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | struct C { |
| 109 | val_c: f64, |
| 110 | } |
| 111 | |
| 112 | impl C { |
| 113 | fn dbg_inner(&self) -> usize { |
| 114 | dbg!(self.val_c); |
| 115 | 3 |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | impl Enum { |
| 120 | delegate! { |
| 121 | // transformed to |
| 122 | // |
| 123 | // ```rust |
| 124 | // match self { |
| 125 | // Enum::A(a) => a.dbg_inner(), |
| 126 | // Enum::B(b) => { println!("i am b"); b }.dbg_inner(), |
| 127 | // Enum::C { v: c } => { c }.dbg_inner(), |
| 128 | // } |
| 129 | // ``` |
| 130 | to match self { |
| 131 | Enum::A(a) => a, |
| 132 | Enum::B(b) => { println!("i am b"); b }, |
| 133 | Enum::C { v: c } => { c }, |
| 134 | } { |
| 135 | fn dbg_inner(&self) -> usize; |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | ``` |
| 140 | |
| 141 | ### Use modifiers that alter the generated method body |
| 142 | ```rust |
| 143 | use delegate::delegate; |
| 144 | struct Inner; |
| 145 | impl Inner { |
| 146 | pub fn method(&self, num: u32) -> u32 { num } |
| 147 | pub fn method_res(&self, num: u32) -> Result<u32, ()> { Ok(num) } |
| 148 | } |
| 149 | struct Wrapper { |
| 150 | inner: Inner |
| 151 | } |
| 152 | impl Wrapper { |
| 153 | delegate! { |
| 154 | to self.inner { |
| 155 | // calls method, converts result to u64 using `From` |
| 156 | #[into] |
| 157 | pub fn method(&self, num: u32) -> u64; |
| 158 | |
| 159 | // calls method, returns () |
| 160 | #[call(method)] |
| 161 | pub fn method_noreturn(&self, num: u32); |
| 162 | |
| 163 | // calls method, converts result to i6 using `TryFrom` |
| 164 | #[try_into] |
| 165 | #[call(method)] |
| 166 | pub fn method2(&self, num: u32) -> Result<u16, std::num::TryFromIntError>; |
| 167 | |
| 168 | // calls method_res, unwraps the result |
| 169 | #[unwrap] |
| 170 | pub fn method_res(&self, num: u32) -> u32; |
| 171 | |
| 172 | // calls method_res, unwraps the result, then calls into |
| 173 | #[unwrap] |
| 174 | #[into] |
| 175 | #[call(method_res)] |
| 176 | pub fn method_res_into(&self, num: u32) -> u64; |
| 177 | |
| 178 | // specify explicit type for into |
| 179 | #[into(u64)] |
| 180 | #[call(method)] |
| 181 | pub fn method_into_explicit(&self, num: u32) -> u64; |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | ``` |
| 186 | |
| 187 | ### Custom called expression |
| 188 | |
| 189 | The `#[expr()]` attribute can be used to modify the delegated call. You can use the `$` sigil as a placeholder for what delegate would normally expand to, and wrap that expression with custom code. |
| 190 | |
| 191 | _Note:_ the `$` placeholder isn't required and can be present multiple times if you want. |
| 192 | |
| 193 | ```rust |
| 194 | struct A(Vec<u8>); |
| 195 | |
| 196 | impl A { |
| 197 | delegate! { |
| 198 | to self.0 { |
| 199 | #[expr(*$.unwrap())] |
| 200 | /// Here `$` == `self.0.get(idx)` |
| 201 | /// Will expand to `*self.0.get(idx).unwrap()` |
| 202 | fn get(&self, idx: usize) -> u8; |
| 203 | |
| 204 | #[call(get)] |
| 205 | #[expr($?.checked_pow(2))] |
| 206 | /// Here `$` == `self.0.get(idx)` |
| 207 | /// Will expand to `self.0.get(idx)?.checked_pow(2)` |
| 208 | fn get_checked_pow_2(&self, idx: usize) -> Option<u8>; |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | ``` |
| 213 | |
| 214 | ### Add additional arguments to method |
| 215 | ```rust |
| 216 | struct Inner(u32); |
| 217 | impl Inner { |
| 218 | pub fn new(m: u32) -> Self { |
| 219 | // some "very complex" constructing work |
| 220 | Self(m) |
| 221 | } |
| 222 | pub fn method(&self, n: u32) -> u32 { |
| 223 | self.0 + n |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | struct Wrapper { |
| 228 | inner: OnceCell<Inner>, |
| 229 | } |
| 230 | |
| 231 | impl Wrapper { |
| 232 | pub fn new() -> Self { |
| 233 | Self { |
| 234 | inner: OnceCell::new(), |
| 235 | } |
| 236 | } |
| 237 | fn content(&self, val: u32) -> &Inner { |
| 238 | self.inner.get_or_init(|| Inner(val)) |
| 239 | } |
| 240 | delegate! { |
| 241 | to |k: u32| self.content(k) { |
| 242 | // `wrapper.method(k, num)` will call `self.content(k).method(num)` |
| 243 | pub fn method(&self, num: u32) -> u32; |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | ``` |
| 248 | |
| 249 | ### Call `await` on async functions |
| 250 | ```rust |
| 251 | struct Inner; |
| 252 | impl Inner { |
| 253 | pub async fn method(&self, num: u32) -> u32 { num } |
| 254 | } |
| 255 | struct Wrapper { |
| 256 | inner: Inner |
| 257 | } |
| 258 | impl Wrapper { |
| 259 | delegate! { |
| 260 | to self.inner { |
| 261 | // calls method(num).await, returns impl Future<Output = u32> |
| 262 | pub async fn method(&self, num: u32) -> u32; |
| 263 | // calls method(num).await.into(), returns impl Future<Output = u64> |
| 264 | #[into] |
| 265 | #[call(method)] |
| 266 | pub async fn method_into(&self, num: u32) -> u64; |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | ``` |
| 271 | |
| 272 | You can use the `#[await(true/false)]` attribute on delegated methods to specify |
| 273 | if `.await` should be generated after the delegated expression. It will be |
| 274 | generated by default if the delegated method is `async`. |
| 275 | |
| 276 | ### Delegate to multiple fields |
| 277 | ```rust |
| 278 | struct MultiStack { |
| 279 | left: Vec<u32>, |
| 280 | right: Vec<u32>, |
| 281 | } |
| 282 | impl MultiStack { |
| 283 | delegate! { |
| 284 | to self.left { |
| 285 | /// Push an item to the top of the left stack |
| 286 | #[call(push)] |
| 287 | pub fn push_left(&mut self, value: u32); |
| 288 | } |
| 289 | to self.right { |
| 290 | /// Push an item to the top of the right stack |
| 291 | #[call(push)] |
| 292 | pub fn push_right(&mut self, value: u32); |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | ``` |
| 297 | |
| 298 | ### Inline attributes |
| 299 | `rust-delegate` inserts `#[inline(always)]` automatically. You can override that decision by specifying `#[inline]` |
| 300 | manually on the delegated method. |
| 301 | |
| 302 | ### Segment attributes |
| 303 | You can use an attribute on a whole delegation segment to automatically apply it to all methods in that segment: |
| 304 | |
| 305 | ```rust |
| 306 | struct Wrapper { |
| 307 | inner: Inner |
| 308 | } |
| 309 | |
| 310 | impl Wrapper { |
| 311 | delegate! { |
| 312 | #[unwrap] |
| 313 | to self.inner { |
| 314 | fn foo(&self) -> u32; // calls self.inner.foo().unwrap() |
| 315 | fn bar(&self) -> u32; // calls self.inner.bar().unwrap() |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | ``` |
| 320 | |
| 321 | ### Adding additional arguments |
| 322 | You can specify expressions in the signature that will be used as delegated arguments: |
| 323 | |
| 324 | ```rust |
| 325 | use delegate::delegate; |
| 326 | |
| 327 | struct Inner; |
| 328 | impl Inner { |
| 329 | pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 { |
| 330 | a + x * x + b * y + c |
| 331 | } |
| 332 | } |
| 333 | struct Wrapper { |
| 334 | inner: Inner, |
| 335 | a: i32, |
| 336 | b: i32, |
| 337 | c: i32 |
| 338 | } |
| 339 | impl Wrapper { |
| 340 | delegate! { |
| 341 | to self.inner { |
| 342 | // Calls `polynomial` on `inner` with `self.a`, `self.b` and |
| 343 | // `self.c` passed as arguments `a`, `b`, and `c`, effectively |
| 344 | // calling `polynomial(self.a, x, self.b, y, self.c)`. |
| 345 | pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ; |
| 346 | // Calls `polynomial` on `inner` with `0`s passed for arguments |
| 347 | // `a` and `x`, and `self.b` and `self.c` for `b` and `c`, |
| 348 | // effectively calling `polynomial(0, 0, self.b, y, self.c)`. |
| 349 | #[call(polynomial)] |
| 350 | pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ; |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | ``` |
| 355 | |
| 356 | ### Parameter modifiers |
| 357 | You can modify how will an input parameter be passed to the delegated method with parameter attribute modifiers. Currently, the following modifiers are supported: |
| 358 | - `#[into]`: Calls `.into()` on the parameter passed to the delegated method. |
| 359 | - `#[as_ref]`: Calls `.as_ref()` on the parameter passed to the delegated method. |
| 360 | - `#[newtype]`: Accesses the first tuple element (`.0`) of the parameter passed to the delegated method. |
| 361 | |
| 362 | > Note that these modifiers might be removed in the future, try to use the more general `#[expr]` mechanism to achieve this functionality. |
| 363 | |
| 364 | ```rust |
| 365 | use delegate::delegate; |
| 366 | |
| 367 | struct InnerType {} |
| 368 | impl InnerType { |
| 369 | fn foo(&self, other: Self) {} |
| 370 | } |
| 371 | |
| 372 | impl From<Wrapper> for InnerType { |
| 373 | fn from(wrapper: Wrapper) -> Self { |
| 374 | wrapper.0 |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | struct Wrapper(InnerType); |
| 379 | impl Wrapper { |
| 380 | delegate! { |
| 381 | to self.0 { |
| 382 | // Calls `self.0.foo(other.into());` |
| 383 | pub fn foo(&self, #[into] other: Self); |
| 384 | // Calls `self.0.bar(other.0);` |
| 385 | pub fn bar(&self, #[newtype] other: Self); |
| 386 | } |
| 387 | } |
| 388 | } |
| 389 | ``` |
| 390 | |
| 391 | ### Delegate associated functions |
| 392 | ```rust |
| 393 | use delegate::delegate; |
| 394 | |
| 395 | struct A {} |
| 396 | impl A { |
| 397 | fn foo(a: u32) -> u32 { |
| 398 | a + 1 |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | struct B; |
| 403 | |
| 404 | impl B { |
| 405 | delegate! { |
| 406 | to A { |
| 407 | fn foo(a: u32) -> u32; |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | assert_eq!(B::foo(1), 2); |
| 413 | ``` |
| 414 | |
| 415 | ### Delegate associated constants |
| 416 | ```rust |
| 417 | use delegate::delegate; |
| 418 | |
| 419 | trait WithConst { |
| 420 | const TOTO: u8; |
| 421 | } |
| 422 | |
| 423 | struct A; |
| 424 | impl WithConst for A { |
| 425 | const TOTO: u8 = 1; |
| 426 | } |
| 427 | |
| 428 | struct B; |
| 429 | impl WithConst for B { |
| 430 | const TOTO: u8 = 2; |
| 431 | } |
| 432 | struct C; |
| 433 | impl WithConst for C { |
| 434 | const TOTO: u8 = 2; |
| 435 | } |
| 436 | |
| 437 | enum Enum { |
| 438 | A(A), |
| 439 | B(B), |
| 440 | C(C), |
| 441 | } |
| 442 | |
| 443 | impl Enum { |
| 444 | delegate! { |
| 445 | to match self { |
| 446 | Self::A(a) => a, |
| 447 | Self::B(b) => b, |
| 448 | Self::C(c) => { println!("hello from c"); c }, |
| 449 | } { |
| 450 | #[const(WithConst::TOTO)] |
| 451 | fn get_toto(&self) -> u8; |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | assert_eq!(Enum::A(A).get_toto(), <A as WithConst>::TOTO); |
| 457 | ``` |
| 458 | |
| 459 | ### Delegate to fields |
| 460 | ```rust |
| 461 | use delegate::delegate; |
| 462 | |
| 463 | struct Datum { |
| 464 | value: u32, |
| 465 | error: u32, |
| 466 | } |
| 467 | |
| 468 | struct DatumWrapper(Datum); |
| 469 | |
| 470 | impl DatumWrapper { |
| 471 | delegate! { |
| 472 | to self.0 { |
| 473 | /// Get the value of a nested field with the same name |
| 474 | #[field] |
| 475 | fn value(&self) -> u32; |
| 476 | |
| 477 | /// Get the value of a nested field with a different name |
| 478 | #[field(value)] |
| 479 | fn renamed_value(&self) -> u32; |
| 480 | |
| 481 | /// Get shared reference to a nested field |
| 482 | #[field(&value)] |
| 483 | fn value_ref(&self) -> &u32; |
| 484 | |
| 485 | /// Get mutable reference to a nested field |
| 486 | #[field(&mut value)] |
| 487 | fn value_ref_mut(&mut self) -> &mut u32; |
| 488 | |
| 489 | /// Get mutable reference to a nested field with the same name |
| 490 | #[field(&)] |
| 491 | fn error(&self) -> &u32; |
| 492 | } |
| 493 | } |
| 494 | } |
| 495 | ``` |
| 496 | |
| 497 | ## Development |
| 498 | |
| 499 | This project uses a standard test suite for quality control, as well as a set of |
| 500 | "expansion" tests that utilize the `macrotest` crate to ensure the macro expands |
| 501 | as expected. PRs implementing new features should add both standard and expansion |
| 502 | tests where appropriate. |
| 503 | |
| 504 | To add an expansion test, place a Rust source file in the `tests/expand/` directory |
| 505 | with methods demonstrating the new feature. Next, run `cargo test` to run the test |
| 506 | suite and generate a `*.expanded.rs` file in the same directory. Next, carefully |
| 507 | inspect the contents of the generated file to confirm that all methods expanded as |
| 508 | expected. Finally, commit both files to the git repository. Future test suite runs |
| 509 | will now include expanding the source file and comparing it to the expanded file. |
| 510 | |
| 511 | ## License |
| 512 | |
| 513 | Licensed under either of |
| 514 | |
| 515 | - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or |
| 516 | http://www.apache.org/licenses/LICENSE-2.0) |
| 517 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) |
| 518 | |
| 519 | at your option. |
| 520 | |
| 521 | ## Contribution |
| 522 | |
| 523 | Unless you explicitly state otherwise, any contribution intentionally submitted |
| 524 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be |
| 525 | dual licensed as above, without any additional terms or conditions. |
| 526 | |
| 527 | ## Conduct |
| 528 | |
| 529 | Please follow the [Rust Code of Conduct]. For escalation or moderation issues |
| 530 | please contact the crate author(s) listed in [`Cargo.toml`](./Cargo.toml). |
| 531 | |
| 532 | [Rust Code of Conduct]: https://www.rust-lang.org/conduct.html |