3 unstable releases

0.2.1 Feb 9, 2020
0.2.0 Feb 8, 2020
0.1.0 Feb 8, 2020

#2127 in Rust patterns

33 downloads per month

MIT/Apache

10KB
294 lines

is-same

Crates.io License: MIT/Apache-2.0 build Coverage Status

This crate provides the IsSame trait, which is specifically for diffing immutable data that has been transformed. The trait differs from PartialEq in some important ways:

  • Floating point values are compared by their bit patterns, preventing NaN values from making a data structure permanently compare as not equal to itself. This also lets you detect a value changing from -0.0 to 0.0.
  • Referential equality is used to make comparisons more efficient. The library assumes that the contents of Rc<T> and Arc<T> are immutable and can't change, so they only need to be compared by their pointers.

This trait is implemented out of the box for a lot of standard library types, but if any are missing feel free to file an issue or contribute a PR. Issues relating to error messages or other usability issues (including with the proc macro) are also welcome!

The trait is explicitly not implemented for interior mutability types (Cell, RefCell, AtomicUSize, Mutex, etc.), as this would make the assumptions based on referential equality unsound. This could be changed in the future if it presents a problem.

Install

Add to your Cargo.toml:

is-same = "0.1"
is-same-derive = "0.1"

Usage

use is_same::IsSame;
use is_same_derive::IsSame;

#[derive(IsSame)]
struct MyStruct {
    text: String,
    foo: usize,
    bar: char,
}

fn diff(left: &MyStruct, right: &MyStruct) {
    println!("is_same? {}", left.is_same(right));
}

lib.rs:

This crate provides the IsSame trait, which is specifically for diffing immutable data that has been transformed. The trait differs from PartialEq in some important ways:

  • Floating point values are compared by their bit patterns, preventing NaN values from making a data structure permanently compare as not equal to itself. This also lets you detect a value changing from -0.0 to 0.0.
  • Referential equality is used to make comparisons more efficient. The library assumes that the contents of Rc<T> and Arc<T> are immutable and can't change, so they only need to be compared by their pointers.

There is also a is-same-derive crate which can automatically derive an IsSame implementation for your structs:

use is_same_derive::IsSame;

#[derive(IsSame)]
struct MyStruct {
    count: usize,
    ch: char,
    text: String,
}

No runtime deps