2 unstable releases

0.3.0 Feb 9, 2021
0.1.0 Dec 10, 2019

#342 in Rust patterns

Download history 11897/week @ 2024-07-04 12984/week @ 2024-07-11 12274/week @ 2024-07-18 12293/week @ 2024-07-25 10876/week @ 2024-08-01 11331/week @ 2024-08-08 11691/week @ 2024-08-15 11453/week @ 2024-08-22 10951/week @ 2024-08-29 13805/week @ 2024-09-05 13470/week @ 2024-09-12 12815/week @ 2024-09-19 12461/week @ 2024-09-26 13074/week @ 2024-10-03 14171/week @ 2024-10-10 16657/week @ 2024-10-17

59,192 downloads per month
Used in 37 crates (19 directly)

MIT license

29KB
275 lines

auto_ops Build Status Latest Version

Macros for easy operator overloading.

Documentation

This library is forked from the original impl_ops by brianwp3000.

This library makes writing multiple impl std::ops::<op> blocks much faster, especially when you want operators defined for both owned and borrowed variants of the inputs.

To use, import the macros with use auto_ops::*;. Remember that you can only overload operators between one or more types defined in the current crate (respecting Rust orphan rules).

Examples

use auto_ops::*;

#[derive(Clone, Debug, PartialEq)]
struct DonkeyKong {
    pub bananas: i32,
}
impl DonkeyKong {
    pub fn new(bananas: i32) -> DonkeyKong {
        DonkeyKong { bananas: bananas }
    }
}

impl_op_ex!(+ |a: &DonkeyKong, b: &DonkeyKong| -> DonkeyKong { DonkeyKong::new(a.bananas + b.bananas) });
impl_op_ex!(+= |a: &mut DonkeyKong, b: &DonkeyKong| { a.bananas += b.bananas });

fn main() {
    assert_eq!(DonkeyKong::new(5), DonkeyKong::new(4) + DonkeyKong::new(1));
    assert_eq!(DonkeyKong::new(5), DonkeyKong::new(4) + &DonkeyKong::new(1));
    assert_eq!(DonkeyKong::new(5), &DonkeyKong::new(4) + DonkeyKong::new(1));
    assert_eq!(DonkeyKong::new(5), &DonkeyKong::new(4) + &DonkeyKong::new(1));

    let mut dk = DonkeyKong::new(4);
    dk += DonkeyKong::new(1);
    dk += &DonkeyKong::new(1);
    assert_eq!(DonkeyKong::new(6), dk);
}

Roadmap

With Rust lifetime inference changes, implementations for generic (over types and lifetimes) impls are being worked on.

No runtime deps