Generate mut and non-mut versions of the same function without duplicating code!
mwt provides two mostly identical macros: mwt
and maybe_mut
- mwt
looks for mwt
in identifiers, and looks for types like &Mwt<T>
- maybe_mut
does the same for maybe_mut
and &MaybeMut<T>
both let you put #[if_mut]
and #[not_mut]
before blocks to have conditionally present sections.
both also let you pass an argument ignore_self
e.g. #[mwt::maybe_mut(ignore_self)]
to stop mwt from messing with the &self
(or &mut self
) parameter. stripping mut
from &mut self
is the default because takeing &T<self>
is a parse error, and most of the time this is the desired behavior (at least for my use cases).
mwt lets you write:
```Rust use mwt::mwt;
struct SomeStruct {
a_vector: Vec
impl SomeStruct { #[mwt] fn mymwtaccessor(&mut self) -> &Mwt(SomeStruct) { let mut a = 0; a = a + 1; #[ifmut] { println!("Hello from mymutaccessor()!"); } #[notmut] { println!("Hello from myaccessor()!"); } self.avector.get_mwt(0).unwrap() } } ```
which results in two functions:
```Rust impl SomeStruct { fn myaccessor(&self) -> &SomeStruct { let mut a = 0; a = a + 1; println!("Hello from myaccessor()!"); self.avector.get(0).unwrap() } fn mymutaccessor(&mut self) -> &mut SomeStruct { let mut a = 0; a = a + 1; println!("Hello from mymutaccessor()!"); self.avector.get_mut(0).unwrap() } }
e.g.
```Rust
fn mymwtmethod(&'a mut self, otherparam: i32) -> &Mwt
Basically write the mutable version of your function, but for identifiers, replace mut
with mwt
and for types replace &mut T
with &Mwt<T>
Alternatively you can use mwt::maybe_mut
if you feel that's more readable.
mwt::mwt
basically just replaces the function with two copies (i.e. a non-mut and mut version) and does a few things on those:
&Mwt<T>
with &T
and &mut T
respectivelyto allow for other ways behavior can differ, the mut version strips any occurences of #[not_mut]{...}
and the non-mut version strips any occurrences of #[if_mut]{...}
(the ones that aren't stripped have their braces removed, so be aware of that)
mwt::maybe_mut
is identical just with different strings.
Please file an issue or submit a pull request!