diff --git a/CHANGELOG.md b/CHANGELOG.md index dfc66ca1..161c753e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Migrating + +- **Float properties work without a wrapper.** `define_property!` and + `define_derived_property!` now derive `ixa::EqHash`, which implements `PartialEq`, `Eq` and + `Hash` with floats compared by value (`NaN` equals itself, `-0.0` equals `0.0`), so + `define_property!(struct Weight(f64), Person)` compiles and can be indexed. To migrate: + - Remove `impl_eq_hash = ...` arguments, and any hand-written `PartialEq`, `Eq` or `Hash` + impls on macro-declared types, which now conflict. + - On types you declare yourself, replace `#[derive(PartialEq, Eq, Hash)]` with + `#[derive(ixa::EqHash)]` if they hold floats. + - If you used `impl_eq_hash = neither` because a field type is only `PartialEq`, give that type + `Eq` and `Hash` too (`EqHash` if it holds floats). To keep a property `PartialEq`-only, + declare it by hand and use `impl_property!`. + - If your model depends on the sign of a zero: `-0.0` now equals `0.0`, and Ixa does not store + a value that equals the property's default. Setting `Weight(-0.0)` on a property whose + default is `Weight(0.0)` can therefore read back as `Weight(0.0)`. With + `impl_eq_hash = both` the two were different values and `-0.0` was kept. + - A constant of a struct property type can no longer be a `match` pattern, because the type + no longer has the std `PartialEq` derive: write `value if value == ADULT` instead of + `ADULT`. Enums declared with `define_property!` are unaffected. + - The fields of a named-field struct declared with `define_derived_property!` are now always + `pub`, as with `define_property!`; a written visibility was kept before. +- **Removed** `impl_property_eq!`, `impl_property_hash!` and `impl_property_eq_hash!` (each now + fails with an error pointing at `EqHash`), the `ixa::rkyv` re-export and dependency, and + `ixa::hashing::HasherWriter` / `EqualityBufferWriter`. + +### Added + +- `ixa::EqHash` derive: `PartialEq`, `Eq` and `Hash` for a property type, with floats (and + `Option`s, arrays and tuples of them) compared by value. + ## [4.1.0](https://github.com/CDCgov/ixa/compare/ixa-v4.0.0...ixa-v4.1.0) - 2026-11-05 ### Added diff --git a/Cargo.toml b/Cargo.toml index 9be91989..1fe1cd37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,7 +62,6 @@ ouroboros = "^0.18.5" thiserror = "^2.0.11" smallbox = "^0.8.8" smallvec = "^1.15.1" -rkyv = "^0.8.15" [package] name = "ixa" @@ -107,7 +106,6 @@ rustc-hash.workspace = true thiserror.workspace = true smallvec.workspace = true smallbox.workspace = true -rkyv.workspace = true tempfile.workspace = true bincode-next.workspace = true diff --git a/docs/book/src/migration_guide.md b/docs/book/src/migration_guide.md index 504006dd..c11e72fb 100644 --- a/docs/book/src/migration_guide.md +++ b/docs/book/src/migration_guide.md @@ -77,11 +77,9 @@ impl_property!( In the ordinary derive path, `define_property!` tacks on the `derive` traits and `pub` visibility to the type definition and then calls `impl_property!` as -above. For property types that cannot derive `PartialEq` / `Eq` or `Hash`, -`define_property!` can also generate those implementations with -`impl_eq_hash = ...`; manually declared types can use `impl_property_eq!`, -`impl_property_hash!`, or `impl_property_eq_hash!` for the same generated -behavior, or client code can implement these traits itself. +above. Equality and hashing come from the `ixa::EqHash` derive, which compares +floats by value, so a property holding an `f64` needs no wrapper type; a +manually declared type derives `EqHash` itself. The crucial thing to understand is that the value type _is_ the property type. The `impl Property\ for InfectionStatus`, which the macros give you, is @@ -89,8 +87,8 @@ the thing that ties the `InfectionStatus` type to the `Person` entity. For details about defining properties, see the `property_impl` module-level docs and API docs for the macros `define_property!`, `impl_property!`, -`impl_property_eq!`, `impl_property_hash!`, `impl_property_eq_hash!`, -`define_derived_property!`, `impl_derived_property!`, and `define_multi_property!`. +`define_derived_property!`, `impl_derived_property!`, and `define_multi_property!`, +and the `EqHash` derive. The API docs give multiple examples. Multi-property definitions now take the entity first and the component diff --git a/docs/book/src/topics/properties.md b/docs/book/src/topics/properties.md index 44927602..ab98eeee 100644 --- a/docs/book/src/topics/properties.md +++ b/docs/book/src/topics/properties.md @@ -159,17 +159,12 @@ as `struct LastVaccination(Option\)`. define_property!( struct LastVaccination(Option), Person, - impl_eq_hash = neither, default_const = LastVaccination(None) ); ``` -Notice that we provided a default of `LastVaccination(None)`, which stands for "no value set". Because this example -contains an `f64` and does not need to be indexed, we also pass `impl_eq_hash = neither` so `define_property!` does not -try to derive `Eq` and `Hash`. No manual `Eq` or `Hash` implementations are required for unindexed floating-point -properties. -See [Floating Point Types and Implementing `Eq` and `Hash`](#floating-point-types-and-implementing-eq-and-hash) for -the cases where `Eq` and `Hash` are still needed. +Notice that we provided a default of `LastVaccination(None)`, which stands for "no value set". The `f64` inside +needs nothing special: see [Floating Point Properties](#floating-point-properties). This is such a common pattern that Ixa detects the `Option` and provides a custom "display function" for it for writing values to reports and diagnostics; see the section on @@ -268,13 +263,12 @@ define_property!( ``` For these forms, `define_property!` creates the type, makes it public, adds the -standard derives, and then calls `impl_property!` for you. By default, the -standard derives are `Debug`, `PartialEq`, `Eq`, `Hash`, `Clone`, `Copy`, -`serde::Serialize`, and `serde::Deserialize`. The default includes `Eq` and -`Hash` so the property can be indexed or used as a hash-map key without more -boilerplate, but ordinary unindexed properties do not require those two traits. -Use the `impl_eq_hash = ...` argument when the default `Eq`/`Hash` derives are -not possible or not wanted. +standard derives, and then calls `impl_property!` for you. The standard +derives are `Debug`, `Clone`, `Copy`, `serde::Serialize`, `serde::Deserialize`, +and `PartialEq`, `Eq` and `Hash`. For a struct those last three come from +`ixa::EqHash`, which compares floats by value; an enum uses the ordinary +derives. Every property therefore gets `Eq` and `Hash`, so it can be indexed or +used as a hash-map key without more boilerplate. Use `impl_property!` when the type already exists or when the type declaration needs syntax that `define_property!` does not support. The common reasons are: @@ -294,12 +288,9 @@ implement `Eq` and `Hash`. A non-derived property also needs [population persistence](population-persistence.md); declare it with `persist = false` to skip it instead. -If a manually declared property needs `Eq` or `Hash` and those traits cannot be -derived, use `impl_property_eq!`, `impl_property_hash!`, or -`impl_property_eq_hash!` to generate the same byte-based implementations used by -`define_property!(..., impl_eq_hash = ...)`. This most often comes up for -indexed properties containing `f32` or `f64`. The type must derive -`ixa::rkyv::Archive` and `ixa::rkyv::Serialize` for these macros. +If a manually declared property holds an `f32` or `f64`, derive `ixa::EqHash` +in place of `PartialEq`, `Eq` and `Hash`; see +[Floating Point Properties](#floating-point-properties). ### Example: You require different derives @@ -460,211 +451,63 @@ non-derived property. The same trait rule applies to derived properties: all derived properties need `Copy`, `Clone`, `Debug`, and `PartialEq`; derived properties that are indexed -also need `Eq` and `Hash`. The `define_derived_property!` macro includes -`Eq` and `Hash` in its default derives, just like `define_property!`, unless -you pass `impl_eq_hash = ...`. +also need `Eq` and `Hash`. The `define_derived_property!` macro adds the same +derives as `define_property!`. -## Floating Point Types and Implementing `Eq` and `Hash` +## Floating Point Properties -All properties participate in equality for unindexed query scans, so every property needs `PartialEq`. Indexed -properties have the additional requirements of `Eq` and `Hash` because property indexes are hash maps keyed by property -value. +Rust's `f32` and `f64` implement `PartialEq` but not `Eq` or `Hash`, because `NaN` is not equal +to itself. Ixa needs `Eq` and `Hash` on a property to index it or use it as a hash-map key, so an ordinary `#[derive(PartialEq, Eq, Hash)]` on a type holding a float does +not compile. -Plain `f64` and `f32` values implement `PartialEq`, so they can be used in -ordinary unindexed properties. They do not implement `Eq` or `Hash`, so a -floating-point property needs special handling only when: - -- you use the default `define_property!` or `define_derived_property!` form, - which tries to derive `Eq` and `Hash` unless told otherwise; -- you index the property with `context.index_property` or - `context.index_property_counts`; -- you use the property as part of an indexed multi-property; or -- you use the property type as a key in a `HashMap` or `HashSet`. - -> [!INFO] Implementing `PartialEq` and `Eq` in Rust -> -> Indexed properties need to implement `Eq`. In practice, this actually means implementing `PartialEq`. In fact, the `Eq` trait -> is just a marker trait; it has no methods! The `Eq` trait is a guarantee by the author that the implementation of -> `PartialEq` [is reflexive](https://doc.rust-lang.org/std/cmp/trait.Eq.html). Rust also requires that `PartialEq` -> is symmetric and transitive. - -### Unindexed floating-point properties - -If a floating-point property will not be indexed and will not be used as a hash -map key, pass `impl_eq_hash = neither` to `define_property!` or -`define_derived_property!`: +`define_property!` and `define_derived_property!` therefore derive `ixa::EqHash` instead, +which implements `PartialEq`, `Eq` and `Hash` field by field. A float field is compared and +hashed by its value, with `-0.0` equal to `0.0` and every `NaN` equal to every other `NaN`; +any other field goes through its own `Eq` and `Hash`. A float-valued property needs nothing +special: ```rust +define_property!(struct Weight(f64), Person, default_const = Weight(0.0)); define_property!( - struct Weight(f64), + struct Dose { + amount: f64, + count: u8, + }, Person, - impl_eq_hash = neither, - default_const = Weight(0.0) + default_const = Dose { amount: 0.0, count: 0 } ); -``` - -That tells the macro not to derive or generate `Eq` and `Hash`. No manual `Eq` -or `Hash` implementations are required for this unindexed case. - -If you define the type yourself and call `impl_property!` or -`impl_derived_property!`, derive or implement the ordinary property traits: -`Copy`, `Clone`, `Debug`, and `PartialEq`. Do not add `Eq` and `Hash` unless the -property needs to be indexed or used as a key. Derived properties are never -persisted, so they do not need Serde. -### Indexed or hash-keyed floating-point properties - -If a floating-point property is indexed, is part of an indexed multi-property, -or is used as a hash-map key, it must implement `Eq` and `Hash`. There are three -reasonable ways to do that. - -1. [Let Ixa generate equality and hashing for you](#let-ixa-generate-equality-and-hashing). -2. [Implement equality and hashing yourself](#implement-equality-and-hashing-yourself). -3. [Use an alternative floating-point type](#use-an-alternative-floating-point-type). - -### Let Ixa generate equality and hashing - -Ixa can generate byte-based equality and hashing either when it defines the -property type for you or when you declare the type yourself and register it with -`impl_property!` or `impl_derived_property!`. - -#### Types declared with `define_property!` or `define_derived_property!` - -Pass `impl_eq_hash = both` as the first optional argument to -`define_property!` or `define_derived_property!`: - -```rust -define_property!( - struct Weight(f64), - Person, - impl_eq_hash = both, - default_const = Weight(0.0) -); +context.index_property::(); ``` -This is the shortest option when you define the property with a `define_*` -macro, want to keep the property as an `f64`, and are comfortable with Ixa's -generated equality and hashing behavior. It is a good fit for simple measured -quantities where model code still wants direct access to a floating-point value. - -You can also use only `impl_eq_hash = Eq` or only `impl_eq_hash = Hash` when -one trait can still be derived but the other needs Ixa's generated -implementation. Floating-point properties usually need `both`. - -The generated implementations are reasonably efficient, but they are not optimal. -If performance is absolutely critical, use either of the other options. - -#### Manually declared types registered with `impl_*_property!` - -For a type declared manually and registered with `impl_property!` or -`impl_derived_property!`, use the standalone equality and hashing macros instead -of the `impl_eq_hash` parameter. - -| Macro | Purpose | -|:-------------------------|:---------------------------------------------| -| `impl_property_eq!` | Implements `PartialEq` and `Eq` | -| `impl_property_hash!` | Implements `Hash` | -| `impl_property_eq_hash!` | Convenience macro that invokes both macros | +A type you declare yourself derives `EqHash` in place of the three traits: ```rust -#[derive( - Copy, - Clone, - Debug, - serde::Serialize, - serde::Deserialize, - ixa::rkyv::Archive, - ixa::rkyv::Serialize, -)] -#[rkyv(crate = ixa::rkyv)] -struct Weight(f64); - -impl_property_eq_hash!(Weight); +#[derive(Debug, Clone, Copy, ixa::EqHash, serde::Serialize, serde::Deserialize)] +pub struct Weight(pub f64); impl_property!(Weight, Person, default_const = Weight(0.0)); ``` -Use `impl_property_eq!` or `impl_property_hash!` when you only want Ixa to -generate one of the two implementations. These macros are only needed when the -property actually needs the corresponding trait, such as when it will be indexed -or used as a key. Manually declared types using these macros must derive -`ixa::rkyv::Archive` and `ixa::rkyv::Serialize`, as shown above. - -### Implement equality and hashing yourself - -Pass `impl_eq_hash = neither` when you want `define_property!` to create the -type but you want to provide `PartialEq`, `Eq`, and `Hash` yourself: +`EqHash` works on structs and on enums, including enums whose variants carry data, so the +hand-declared form also covers shapes `define_property!` does not accept: ```rust -use std::hash::{Hash, Hasher}; - -define_property!( - struct Weight(f64), - Person, - impl_eq_hash = neither, - default_const = Weight(0.0) -); - -impl PartialEq for Weight { - fn eq(&self, other: &Self) -> bool { - self.0.to_bits() == other.0.to_bits() - } -} - -impl Eq for Weight {} - -impl Hash for Weight { - fn hash(&self, state: &mut H) { - self.0.to_bits().hash(state); - } -} -``` - -Choose this option when you want to use `f32` / `f64` instead of `OrderedFloat` or equivalent alternative float type -and performance is absolutely crucial. It is usually straightforward to implement `PartialEq` and `Hash` for -floating-point types, but you should ensure that your implementations satisfy the property that equal values have the -same hash: - -```rust -if a == b { - assert_eq!(hash(a), hash(b)); +#[derive(Debug, Clone, Copy, ixa::EqHash, serde::Serialize, serde::Deserialize)] +pub enum Treatment { + None, + Antiviral { dose_mg: f64 }, } +impl_property!(Treatment, Person, default_const = Treatment::None); ``` -For sensible equality semantics, equality should also be reflexive, symmetric, and transitive as well. - -### Use an alternative floating-point type +Each field is either a float, an `Option`, array or tuple built only from floats and +primitives, or a type that is itself `Eq + Hash`, such as another property type. A tuple or +array cannot mix the two kinds: write `(Weight, f64)` as two fields, or give the float its own +`EqHash` type. A field type that fits neither kind fails to compile; derive `EqHash` on it +too. A property that must stay `PartialEq`-only, with no `Eq` or `Hash` at all, is declared by hand +and registered with `impl_property!`, which requires only `PartialEq`; it cannot be indexed. -Use a wrapper type from a crate such as -[`decorum`](https://crates.io/crates/decorum) or -[`ordered-float`](https://crates.io/crates/ordered-float) when you want a type -that gives floating-point values a total ordering and implements the traits Ixa -needs: - -```rust -use ordered_float::OrderedFloat; - -// A type alias is always a good idea here. It allows you to swap out the underlying -// type without having to change the rest of your code. -pub type Float = OrderedFloat; - -define_property!( - struct Weight(Float), - Person, - default_const = Weight(OrderedFloat(0.0)) -); -``` - -With these types, `define_property!` can just `derive` the `PartialEq`, `Eq`, -and `Hash` traits that indexed or hash-keyed properties need, and performance -of these derived implementations is usually optimal. This option is especially -attractive when you want to restrict your type only to the real numbers, or only -to the extended real numbers (infinities but not NaNs), giving you a numeric -type with exactly the mathematical semantics you want. - -The trade-off is that model code works with the wrapper type instead of a bare `f64`, and while these libraries do what -they can to alleviate friction, having to convert to and from primitive `f64` values is often unavoidable. This is -really the only downside. The good news is, this conversion is usually only cosmetic: the compiler usually optimizes it -away. +The only visible difference from IEEE comparison is that `NaN` equals itself. ## Multi-Properties @@ -690,40 +533,30 @@ context.index_property::(); For a deeper discussion of when to create multi-property indexes, see [Indexing](indexing.md). Because the components of a multi-property are already required to be properties, multi-properties usually "just work". If a multi-property -will be indexed, each component value must also support `Eq` and `Hash`; this mainly matters for components containing -plain `f32` or `f64`. +will be indexed, each component value must also support `Eq` and `Hash`, which every property declared with +`define_property!` or deriving `ixa::EqHash` does, float-valued ones included. ## Troubleshooting -### `f64` does not implement `Eq` - -If you define a property containing an `f64` with the default macro form: - -```rust -define_property!(struct Weight(f64), Person); -``` +### `f64` does not implement `Eq` or `Hash` -you may see an error like: +A hand-declared property type that derives `PartialEq`, `Eq` and `Hash` directly fails with: ```text error[E0277]: the trait bound `f64: std::cmp::Eq` is not satisfied ``` -or: +Replace those three derives with `ixa::EqHash`, as described in +[Floating Point Properties](#floating-point-properties). `define_property!` does this for you. + +### `probe_key` exists but its trait bounds were not satisfied + +`EqHash` reports a field whose type is neither `Eq + Hash` nor a float, `Option`, array or +tuple of floats with an error like: ```text -the trait `std::cmp::Eq` is not implemented for `f64` +error[E0599]: the method `probe_key` exists for reference `&ixa::value_key::KeyProbe`, but its trait bounds were not satisfied ``` -This happens because `define_property!` normally derives `Eq` and `Hash`, but -Rust floating-point types do not implement those traits. See -[Floating Point Types and Implementing `Eq` and `Hash`](#floating-point-types-and-implementing-eq-and-hash) -for the full discussion. In short: - -- If the property is not indexed and is not used as a hash-map key, pass - `impl_eq_hash = neither`. No manual `Eq` or `Hash` implementations are - required. -- If the property is indexed or used as a key, pass `impl_eq_hash = both` to let - Ixa generate equality and hashing, provide your own implementations with - `impl_eq_hash = neither`, or use a wrapper such as - `ordered_float::OrderedFloat\` or a type from `decorum`. +Derive `EqHash` on that field's type (the compiler's own suggestion to derive `Eq, Hash, +PartialEq` is wrong if `Foo` holds a float). diff --git a/integration-tests/ixa-macro-tests/tests/macros.rs b/integration-tests/ixa-macro-tests/tests/macros.rs index e28e0a50..a3e51b0c 100644 --- a/integration-tests/ixa-macro-tests/tests/macros.rs +++ b/integration-tests/ixa-macro-tests/tests/macros.rs @@ -1,7 +1,6 @@ #[cfg(test)] mod tests { use std::cell::{Cell, RefCell}; - use std::hash::{Hash, Hasher}; use std::rc::Rc; use ixa::prelude::*; @@ -57,144 +56,34 @@ mod tests { default_const = TestPropOpt(None) ); - // Tests of the `impl_eq_hash = ...` mechanism - // Both `PartialEq` / `Eq` and `Hash` are generated by the macro - define_property!(struct TestFloatBoth(f64), Person, impl_eq_hash = both, default_const = TestFloatBoth(0.0)); - // Only `PartialEq` / `Eq` is generated by the macro - define_property!(struct TestFloatEq(f64), Person, impl_eq_hash = Eq, default_const = TestFloatEq(0.0)); - impl Hash for TestFloatEq { - fn hash(&self, state: &mut H) { - state.write_u64(self.0.to_bits()); - } - } - // Only `Hash` is generated by the macro - define_property!(struct TestFloatHash(f64), Person, impl_eq_hash = Hash, default_const = TestFloatHash(0.0)); - impl PartialEq for TestFloatHash { - fn eq(&self, other: &Self) -> bool { - self.0.to_bits() == other.0.to_bits() - } - } - impl Eq for TestFloatHash {} - // Neither `PartialEq` / `Eq` nor `Hash` are generated by the macro - define_property!(struct TestFloatNeither(f64), Person, impl_eq_hash = neither, default_const = TestFloatNeither(0.0)); - impl Hash for TestFloatNeither { - fn hash(&self, state: &mut H) { - state.write_u64(self.0.to_bits()); - } - } - impl PartialEq for TestFloatNeither { - fn eq(&self, other: &Self) -> bool { - self.0.to_bits() == other.0.to_bits() - } - } - impl Eq for TestFloatNeither {} - - // Tests of standalone generated equality / hash macros for manually declared properties. - #[derive( - Debug, Clone, Copy, Serialize, Deserialize, ixa::rkyv::Archive, ixa::rkyv::Serialize, - )] - #[rkyv(crate = ixa::rkyv)] - struct ManualFloatBoth(f64); - impl_property_eq_hash!(ManualFloatBoth); - impl_property!( - ManualFloatBoth, + // Float-valued properties: `define_property!` derives `EqHash`, so these are indexable. + define_property!(struct TestFloat(f64), Person, default_const = TestFloat(0.0)); + define_property!( + struct TestFloatPair { + weight: f64, + dose: u8, + }, Person, - default_const = ManualFloatBoth(0.0) - ); - - #[derive( - Debug, Clone, Copy, Serialize, Deserialize, ixa::rkyv::Archive, ixa::rkyv::Serialize, - )] - #[rkyv(crate = ixa::rkyv)] - struct ManualFloatEq(f64); - impl_property_eq!(ManualFloatEq); - impl Hash for ManualFloatEq { - fn hash(&self, state: &mut H) { - state.write_u64(self.0.to_bits()); - } - } - impl_property!(ManualFloatEq, Person, default_const = ManualFloatEq(0.0)); - - #[derive( - Debug, Clone, Copy, Serialize, Deserialize, ixa::rkyv::Archive, ixa::rkyv::Serialize, - )] - #[rkyv(crate = ixa::rkyv)] - struct ManualFloatHash(f64); - impl PartialEq for ManualFloatHash { - fn eq(&self, other: &Self) -> bool { - self.0.to_bits() == other.0.to_bits() + default_const = TestFloatPair { + weight: 0.0, + dose: 0 } - } - impl Eq for ManualFloatHash {} - impl_property_hash!(ManualFloatHash); - impl_property!( - ManualFloatHash, - Person, - default_const = ManualFloatHash(0.0) ); - // Analogous tests of the `impl_eq_hash = ...` mechanism for `define_derived_property!` - // Both `PartialEq` / `Eq` and `Hash` are generated by the macro - define_derived_property!( - struct DerivedFloatBoth(f64), - Person, - [TestPropU32], - |v| DerivedFloatBoth(v.0 as f64), - impl_eq_hash = both - ); - // Only `PartialEq` / `Eq` is generated by the macro - define_derived_property!( - struct DerivedFloatEq(f64), - Person, - [TestPropU32], - |v| DerivedFloatEq(v.0 as f64), - impl_eq_hash = Eq - ); - impl Hash for DerivedFloatEq { - fn hash(&self, state: &mut H) { - state.write_u64(self.0.to_bits()); - } - } - // Only `Hash` is generated by the macro - define_derived_property!( - struct DerivedFloatHash(f64), - Person, - [TestPropU32], - |v| DerivedFloatHash(v.0 as f64), - impl_eq_hash = Hash - ); - impl PartialEq for DerivedFloatHash { - fn eq(&self, other: &Self) -> bool { - self.0.to_bits() == other.0.to_bits() - } - } - impl Eq for DerivedFloatHash {} - // Neither `PartialEq` / `Eq` nor `Hash` are generated by the macro + // A float-valued type declared by hand derives `EqHash` itself. + #[derive(Debug, Clone, Copy, EqHash, Serialize, Deserialize)] + struct ManualFloat(f64); + impl_property!(ManualFloat, Person, default_const = ManualFloat(0.0)); + define_derived_property!( - struct DerivedFloatNeither(f64), + struct DerivedFloat(f64), Person, [TestPropU32], - |v| DerivedFloatNeither(v.0 as f64), - impl_eq_hash = neither + |v| DerivedFloat(v.0 as f64) ); - impl Hash for DerivedFloatNeither { - fn hash(&self, state: &mut H) { - state.write_u64(self.0.to_bits()); - } - } - impl PartialEq for DerivedFloatNeither { - fn eq(&self, other: &Self) -> bool { - self.0.to_bits() == other.0.to_bits() - } - } - impl Eq for DerivedFloatNeither {} - #[derive( - Debug, Clone, Copy, Serialize, Deserialize, ixa::rkyv::Archive, ixa::rkyv::Serialize, - )] - #[rkyv(crate = ixa::rkyv)] + #[derive(Debug, Clone, Copy, EqHash, Serialize, Deserialize)] struct ManualDerivedFloat(f64); - impl_property_eq_hash!(ManualDerivedFloat); ixa::impl_derived_property!(ManualDerivedFloat, Person, [TestPropU32], |v| { ManualDerivedFloat(v.0 as f64) }); @@ -286,45 +175,35 @@ mod tests { let default_val: TestPropDefault = ctx.get_property(pid); assert_eq!(default_val.0, 7u32); - // Standalone generated equality / hash macros should support manually declared property - // types that are then registered with `impl_property!`. - let mut manual_float_both = HashSet::default(); - manual_float_both.insert(ctx.get_property::<_, ManualFloatBoth>(pid)); - assert!(manual_float_both.contains(&ManualFloatBoth(0.0))); + // Float-valued properties behave as hash keys, whether declared by the macro or by hand. + let mut floats = HashSet::default(); + floats.insert(ctx.get_property::<_, TestFloat>(pid)); + assert!(floats.contains(&TestFloat(0.0))); + assert!(floats.contains(&TestFloat(-0.0))); - let mut manual_float_eq = HashSet::default(); - manual_float_eq.insert(ctx.get_property::<_, ManualFloatEq>(pid)); - assert!(manual_float_eq.contains(&ManualFloatEq(0.0))); + let mut float_pairs = HashSet::default(); + float_pairs.insert(ctx.get_property::<_, TestFloatPair>(pid)); + assert!(float_pairs.contains(&TestFloatPair { + weight: 0.0, + dose: 0 + })); - let mut manual_float_hash = HashSet::default(); - manual_float_hash.insert(ctx.get_property::<_, ManualFloatHash>(pid)); - assert!(manual_float_hash.contains(&ManualFloatHash(0.0))); + let mut manual_float = HashSet::default(); + manual_float.insert(ctx.get_property::<_, ManualFloat>(pid)); + assert!(manual_float.contains(&ManualFloat(0.0))); // Derived property should compute from TestPropU32 let d: DerivedProp = ctx.get_property(pid); assert_eq!(d.0, 11u32); + let mut derived_float = HashSet::default(); + derived_float.insert(ctx.get_property::<_, DerivedFloat>(pid)); + assert!(derived_float.contains(&DerivedFloat(10.0))); + let mut manual_derived_float = HashSet::default(); manual_derived_float.insert(ctx.get_property::<_, ManualDerivedFloat>(pid)); assert!(manual_derived_float.contains(&ManualDerivedFloat(10.0))); - // Derived property `impl_eq_hash = ...` variants should all compile and behave as hashable keys. - let mut derived_float_both = HashSet::default(); - derived_float_both.insert(ctx.get_property::<_, DerivedFloatBoth>(pid)); - assert!(derived_float_both.contains(&DerivedFloatBoth(10.0))); - - let mut derived_float_eq = HashSet::default(); - derived_float_eq.insert(ctx.get_property::<_, DerivedFloatEq>(pid)); - assert!(derived_float_eq.contains(&DerivedFloatEq(10.0))); - - let mut derived_float_hash = HashSet::default(); - derived_float_hash.insert(ctx.get_property::<_, DerivedFloatHash>(pid)); - assert!(derived_float_hash.contains(&DerivedFloatHash(10.0))); - - let mut derived_float_neither = HashSet::default(); - derived_float_neither.insert(ctx.get_property::<_, DerivedFloatNeither>(pid)); - assert!(derived_float_neither.contains(&DerivedFloatNeither(10.0))); - // Multi-property - basic sanity. let multi = (TestPropU32(10u32), TestPropU32b(20u32)); let disp = >::get_display(&multi); diff --git a/integration-tests/ixa-rename-tests/Cargo.toml b/integration-tests/ixa-rename-tests/Cargo.toml new file mode 100644 index 00000000..06bc5b74 --- /dev/null +++ b/integration-tests/ixa-rename-tests/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "ixa-rename-tests" +version = "0.0.1" +description = "Checks that Ixa macros work when the crate is renamed" +publish = false +repository.workspace = true +license.workspace = true +edition.workspace = true +homepage.workspace = true +authors.workspace = true + +[dev-dependencies] +# Deliberately not named `ixa`: generated code must reach the crate through `$crate`. +sim = { package = "ixa", path = "../../" } +serde.workspace = true + +[lints] +workspace = true diff --git a/integration-tests/ixa-rename-tests/src/lib.rs b/integration-tests/ixa-rename-tests/src/lib.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/integration-tests/ixa-rename-tests/src/lib.rs @@ -0,0 +1 @@ + diff --git a/integration-tests/ixa-rename-tests/tests/renamed.rs b/integration-tests/ixa-rename-tests/tests/renamed.rs new file mode 100644 index 00000000..bb01da72 --- /dev/null +++ b/integration-tests/ixa-rename-tests/tests/renamed.rs @@ -0,0 +1,33 @@ +//! Ixa is a dependency under another name here, so `::ixa` does not resolve. + +use sim::prelude::*; + +define_entity!(Person); +define_property!(struct Age(u8), Person, default_const = Age(0)); +define_property!(struct Weight(f64), Person, default_const = Weight(0.0)); +define_derived_property!( + struct HalfWeight(f64), + Person, + [Weight], + |weight| HalfWeight(weight.0 / 2.0) +); + +#[derive(Debug, Clone, Copy, EqHash, serde::Serialize, serde::Deserialize)] +#[eq_hash(crate = sim)] +pub struct Height(f64); +impl_property!(Height, Person, default_const = Height(0.0)); + +#[test] +fn properties_work_under_a_renamed_crate() { + let mut context = Context::new(); + context.index_property::(); + let person = context + .add_entity(with!(Person, Age(3), Weight(-0.0), Height(1.5))) + .unwrap(); + assert_eq!(context.query_entity_count(with!(Person, Weight(0.0))), 1); + assert_eq!( + context.get_property::(person), + HalfWeight(0.0) + ); + assert_eq!(context.get_property::(person), Height(1.5)); +} diff --git a/ixa-bench/criterion/property_semantics.rs b/ixa-bench/criterion/property_semantics.rs index 3f8e0b72..586dbbc9 100644 --- a/ixa-bench/criterion/property_semantics.rs +++ b/ixa-bench/criterion/property_semantics.rs @@ -1,4 +1,3 @@ -use std::hash::{Hash, Hasher}; use std::hint::black_box; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; @@ -17,35 +16,21 @@ define_property!( Person, default_const = HashStruct { bucket: 0, code: 0 } ); -define_property!(struct HashFloat(f64), Person, impl_eq_hash = both, default_const = HashFloat(0.0)); +define_property!(struct HashFloat(f64), Person, default_const = HashFloat(0.0)); define_property!(struct MultiHashByte(u8), Person, default_const = MultiHashByte(0)); -define_property!(struct MultiHashFloat(f64), Person, impl_eq_hash = both, default_const = MultiHashFloat(0.0)); +define_property!(struct MultiHashFloat(f64), Person, default_const = MultiHashFloat(0.0)); define_multi_property!(Person, (MultiHashByte, MultiHashFloat)); -define_property!(struct FloatQueryValue(f64), Person, impl_eq_hash = both, default_const = FloatQueryValue(0.0)); +define_property!(struct FloatQueryValue(f64), Person, default_const = FloatQueryValue(0.0)); #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize)] struct CounterBucket(pub u8); impl_property!(CounterBucket, Person, default_const = CounterBucket(0)); -#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, EqHash, Serialize, Deserialize)] struct FloatCounterValue(pub f64); -impl PartialEq for FloatCounterValue { - fn eq(&self, other: &Self) -> bool { - self.0.to_bits() == other.0.to_bits() - } -} - -impl Eq for FloatCounterValue {} - -impl Hash for FloatCounterValue { - fn hash(&self, state: &mut H) { - self.0.to_bits().hash(state); - } -} - impl_property!( FloatCounterValue, Person, diff --git a/ixa-derive/CHANGELOG.md b/ixa-derive/CHANGELOG.md index 7dc7b0cf..1754e1ae 100644 --- a/ixa-derive/CHANGELOG.md +++ b/ixa-derive/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `EqHash` derive: `PartialEq`, `Eq` and `Hash` for property types with floats compared by value. + `#[eq_hash(crate = path)]` names the ixa crate when it is renamed or re-exported. + ## [2.1.0](https://github.com/CDCgov/ixa/compare/ixa-derive-v2.0.1...ixa-derive-v2.1.0) - 2026-10-26 ### Added diff --git a/ixa-derive/src/eq_hash.rs b/ixa-derive/src/eq_hash.rs new file mode 100644 index 00000000..76b5371f --- /dev/null +++ b/ixa-derive/src/eq_hash.rs @@ -0,0 +1,216 @@ +//! The `EqHash` derive: see `ixa::EqHash`. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::{Attribute, Data, DeriveInput, Fields, Member, Path, Type}; + +pub fn derive_eq_hash(input: &DeriveInput) -> syn::Result { + if !input.generics.params.is_empty() { + return Err(syn::Error::new_spanned( + &input.generics, + "EqHash does not support generic types; implement PartialEq, Eq and Hash by hand", + )); + } + let name = &input.ident; + let ixa = crate_path(&input.attrs)?; + + // A struct is handled as an enum with one variant whose path is `Self`. + let variants: Vec<(TokenStream, &Fields)> = match &input.data { + Data::Struct(data) => vec![(quote! { Self }, &data.fields)], + Data::Enum(data) => { + if data.variants.is_empty() { + return Err(syn::Error::new_spanned( + &data.variants, + "EqHash requires at least one variant", + )); + } + data.variants + .iter() + .map(|variant| { + let variant_name = &variant.ident; + (quote! { Self::#variant_name }, &variant.fields) + }) + .collect() + } + Data::Union(data) => { + return Err(syn::Error::new_spanned( + data.union_token, + "EqHash cannot be derived for unions", + )) + } + }; + + let arms: Vec = variants + .iter() + .map(|(path, fields)| variant_arms(&ixa, path, fields)) + .collect(); + let eq_arms = arms.iter().map(|arms| &arms.eq); + let hash_arms = arms.iter().map(|arms| &arms.hash); + // Only reached with more than one variant, otherwise the pattern would be unreachable. + let different_variants = (variants.len() > 1).then(|| quote! { _ => false, }); + // As in the std derive, the discriminant is hashed only when there is a choice. + let hash_discriminant = (variants.len() > 1).then(|| { + quote! { ::core::hash::Hash::hash(&::core::mem::discriminant(self), state); } + }); + + Ok(impls( + name, + &ixa, + "e! { + match (self, other) { + #(#eq_arms)* + #different_variants + } + }, + "e! { + #hash_discriminant + match self { + #(#hash_arms)* + } + }, + )) +} + +fn impls( + name: &syn::Ident, + ixa: &Path, + eq_body: &TokenStream, + hash_body: &TokenStream, +) -> TokenStream { + quote! { + #[automatically_derived] + impl ::core::cmp::PartialEq for #name { + #[inline] + fn eq(&self, other: &Self) -> bool { + #[allow(unused_imports)] + use #ixa::value_key::{KeyProbeFallback, KeyProbeValue}; + #eq_body + } + } + + #[automatically_derived] + impl ::core::cmp::Eq for #name {} + + #[automatically_derived] + impl ::core::hash::Hash for #name { + #[inline] + fn hash(&self, state: &mut H) { + #[allow(unused_imports)] + use #ixa::value_key::{KeyProbeFallback, KeyProbeValue}; + #hash_body + } + } + } +} + +/// The path of the ixa crate: `#[eq_hash(crate = path)]` if given (the property macros pass +/// `$crate`, so a renamed or re-exported ixa works), otherwise `::ixa`. +fn crate_path(attrs: &[Attribute]) -> syn::Result { + let mut path = None; + for attr in attrs { + if !attr.path().is_ident("eq_hash") { + continue; + } + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("crate") { + path = Some(meta.value()?.parse::()?); + Ok(()) + } else { + Err(meta.error("expected `crate = path`")) + } + })?; + } + Ok(path.unwrap_or_else(|| syn::parse_quote!(::ixa))) +} + +struct VariantArms { + /// `(Path { f: __left_0, .. }, Path { f: __right_0, .. }) => ,` + eq: TokenStream, + /// `Path { f: __left_0, .. } => { }` + hash: TokenStream, +} + +/// The bindings for one variant's fields: `__left_N` and `__right_N` are references to field N of +/// the two values compared, and the keys are what is compared and hashed. +struct FieldBindings { + members: Vec, + left_names: Vec, + right_names: Vec, + left_keys: Vec, + right_keys: Vec, +} + +impl FieldBindings { + fn new(ixa: &Path, fields: &Fields) -> Self { + let mut bindings = FieldBindings { + members: Vec::new(), + left_names: Vec::new(), + right_names: Vec::new(), + left_keys: Vec::new(), + right_keys: Vec::new(), + }; + for (index, field) in fields.iter().enumerate() { + let left_name = format_ident!("__left_{index}"); + let right_name = format_ident!("__right_{index}"); + bindings.members.push(match &field.ident { + Some(ident) => Member::Named(ident.clone()), + None => Member::Unnamed(index.into()), + }); + bindings.left_keys.push(key_of(ixa, &field.ty, &left_name)); + bindings + .right_keys + .push(key_of(ixa, &field.ty, &right_name)); + bindings.left_names.push(left_name); + bindings.right_names.push(right_name); + } + bindings + } + + fn all_equal(&self) -> TokenStream { + let FieldBindings { + left_keys, + right_keys, + .. + } = self; + if left_keys.is_empty() { + quote! { true } + } else { + quote! { #(#left_keys == #right_keys)&&* } + } + } +} + +fn variant_arms(ixa: &Path, path: &TokenStream, fields: &Fields) -> VariantArms { + let bindings = FieldBindings::new(ixa, fields); + let FieldBindings { + members, + left_names, + right_names, + left_keys, + .. + } = &bindings; + let all_equal = bindings.all_equal(); + // The `Path { member: binding }` pattern form covers named, tuple and unit shapes alike. + VariantArms { + eq: quote! { + ( + #path { #(#members: #left_names),* }, + #path { #(#members: #right_names),* }, + ) => #all_equal, + }, + hash: quote! { + #path { #(#members: #left_names),* } => { + #(::core::hash::Hash::hash(&#left_keys, state);)* + } + }, + } +} + +/// The key of a field, resolved at the expansion site: its `ValueKey` when the field type has +/// one (floats by canonical bits), otherwise a reference to the value, compared and hashed +/// through its own `Eq` and `Hash`. +fn key_of(ixa: &Path, field_type: &Type, binding: &syn::Ident) -> TokenStream { + quote! { + (&#ixa::value_key::KeyProbe::<#field_type>::new()).probe_key(#binding) + } +} diff --git a/ixa-derive/src/lib.rs b/ixa-derive/src/lib.rs index c28e68b1..1039a306 100644 --- a/ixa-derive/src/lib.rs +++ b/ixa-derive/src/lib.rs @@ -1,6 +1,7 @@ extern crate proc_macro; mod calendar; +mod eq_hash; use proc_macro::TokenStream; use quote::quote; @@ -12,6 +13,16 @@ pub fn calendar(args: TokenStream, item: TokenStream) -> TokenStream { calendar::calendar(args, item) } +/// Field-by-field `PartialEq`, `Eq` and `Hash` with floats compared by value; documented at +/// `ixa::EqHash`. +#[proc_macro_derive(EqHash, attributes(eq_hash))] +pub fn derive_eq_hash(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + eq_hash::derive_eq_hash(&input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + #[proc_macro_derive(IxaEvent)] pub fn derive_ixa_event(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); diff --git a/src/hashing.rs b/src/hashing.rs index c77cdf91..abb68091 100644 --- a/src/hashing.rs +++ b/src/hashing.rs @@ -28,82 +28,6 @@ pub type HashValueType = u128; pub(crate) type DeterministicHasher = Xxh3Default; -/// A `rkyv` writer that streams serialized bytes directly into a `Hasher`. -pub struct HasherWriter<'a, H> { - hasher: &'a mut H, - pos: usize, -} - -impl<'a, H> HasherWriter<'a, H> { - #[must_use] - pub fn new(hasher: &'a mut H) -> Self { - Self { hasher, pos: 0 } - } -} - -impl rkyv::ser::Positional for HasherWriter<'_, H> { - fn pos(&self) -> usize { - self.pos - } -} - -impl rkyv::ser::Writer for HasherWriter<'_, H> { - fn write(&mut self, bytes: &[u8]) -> Result<(), rkyv::rancor::Error> { - self.hasher.write(bytes); - self.pos += bytes.len(); - Ok(()) - } -} - -/// A fixed-size `rkyv` writer used by macro-generated equality implementations. -#[derive(Debug, Clone, Copy)] -pub struct EqualityBufferWriter { - buf: [u8; N], - pos: usize, -} - -impl EqualityBufferWriter { - #[must_use] - pub fn new() -> Self { - Self { - buf: [0; N], - pos: 0, - } - } - - #[must_use] - pub fn as_written(&self) -> &[u8] { - &self.buf[..self.pos] - } -} - -impl Default for EqualityBufferWriter { - fn default() -> Self { - Self::new() - } -} - -impl rkyv::ser::Positional for EqualityBufferWriter { - fn pos(&self) -> usize { - self.pos - } -} - -impl rkyv::ser::Writer for EqualityBufferWriter { - fn write(&mut self, bytes: &[u8]) -> Result<(), E> { - let end = self.pos + bytes.len(); - assert!( - end <= N, - "Ixa internal error: serialized form exceeded fixed buffer size: {} > {}", - end, - N - ); - self.buf[self.pos..end].copy_from_slice(bytes); - self.pos = end; - Ok(()) - } -} - /// Provides API parity with `std::collections::HashMap`. pub trait HashMapExt { #[must_use] diff --git a/src/lib.rs b/src/lib.rs index 719c8ef7..5a8fc112 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -48,13 +48,41 @@ #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/docs/book/src/cli-usage.md"))] +// Lets code generated by the derive macros name this crate as `::ixa` from inside it too. +extern crate self as ixa; + pub mod context; pub use context::{Context, ContextBase, EventListenerId, ExecutionPhase, IxaEvent}; +/// Derives `PartialEq`, `Eq` and `Hash` for a property type so that it can hold floats and +/// still be indexed. Floats compare by value, with `-0.0` equal to `0.0` and `NaN` equal to +/// itself; other fields use their own `Eq` and `Hash`. +/// +/// ```rust +/// # use ixa::{define_entity, impl_property, EqHash}; +/// # define_entity!(Person); +/// #[derive(Debug, Clone, Copy, EqHash, serde::Serialize, serde::Deserialize)] +/// pub enum Treatment { +/// Untreated, +/// Antiviral { dose_mg: f64 }, +/// } +/// impl_property!(Treatment, Person, default_const = Treatment::Untreated); +/// ``` +/// +/// Limits: +/// - No generic types, unions or `#[repr(packed)]` structs. +/// - A tuple or array field cannot mix floats with non-primitive types: use separate fields. +/// - A value equal to the property's default is not stored, so `-0.0` set against a `0.0` +/// default can read back as `0.0`. +/// - If ixa is renamed or re-exported, add `#[eq_hash(crate = path::to::ixa)]`. +pub use ixa_derive::EqHash; pub use ixa_derive::IxaEvent; pub mod calendar; +#[doc(hidden)] +pub mod value_key; pub use calendar::ContextCalendarExt; pub use ixa_derive::calendar; + /// Re-exports for code generated by ixa macros. #[doc(hidden)] pub mod __private { @@ -112,7 +140,6 @@ pub use csv; pub use ctor; pub use paste; pub use rand; -pub use rkyv; // Deterministic hashing data structures pub use crate::hashing::{HashMap, HashMapExt, HashSet, HashSetExt}; diff --git a/src/macros/property_impl.rs b/src/macros/property_impl.rs index 29e68076..17a02dfb 100644 --- a/src/macros/property_impl.rs +++ b/src/macros/property_impl.rs @@ -30,9 +30,9 @@ The primary advantage of using this macro is that it automatically derives the l [`Property`][crate::entity::property::Property] needs to derive for you. You don't have to remember them. You also get a cute syntax for specifying the default value, but it's not much harder to specify default values using other macros. -If you need the macro to generate `Eq` and/or `Hash` manually instead of deriving them, use the -optional `impl_eq_hash = ...` argument with one of the following values: `Eq`, `Hash`, `both`, or -`neither`. +A generated struct derives [`EqHash`][crate::EqHash] in place of `PartialEq`, `Eq` and +`Hash`, so a field may hold an `f32` or `f64`: floats compare by value, with `NaN` equal to +itself, and the property can be indexed like any other. Notice you need to use the `struct` or `enum` keywords, but you don't need to specify the visibility. A `pub` visibility is added automatically to the struct @@ -49,12 +49,8 @@ required by [`Property`][crate::entity::property::Property] for your type: `Copy `Hash`. To be saved by population persistence, a non-derived property must also implement `serde::Serialize` and `serde::Deserialize`, or be declared with `persist = false` to skip it. -If the type cannot derive `PartialEq` / `Eq` or `Hash`, for example because it contains `f32` or -`f64`, use [`impl_property_eq!`][macro@crate::impl_property_eq], -[`impl_property_hash!`][macro@crate::impl_property_hash], or -[`impl_property_eq_hash!`][macro@crate::impl_property_eq_hash] to generate those implementations -for the manually declared type. These macros require `ixa::rkyv::Archive` and `ixa::rkyv::Serialize` derives -because they compare and hash the type's archived byte representation. +If the type holds an `f32` or `f64`, derive [`EqHash`][crate::EqHash] instead of `PartialEq`, +`Eq` and `Hash`. Some examples: @@ -90,19 +86,9 @@ impl_property!(InfectionStatus, Person, default_const = InfectionStatus::Suscept pub struct Vaccinated(pub bool); impl_property!(Vaccinated, Person, default_const = Vaccinated(false)); -// For manually declared floating-point properties, generate byte-based equality and hashing. -#[derive( - Copy, - Clone, - Debug, - serde::Serialize, - serde::Deserialize, - ixa::rkyv::Archive, - ixa::rkyv::Serialize, -)] -#[rkyv(crate = ixa::rkyv)] +// A floating-point property declared by hand: `EqHash` provides `PartialEq`, `Eq` and `Hash`. +#[derive(Copy, Clone, Debug, ixa::EqHash, serde::Serialize, serde::Deserialize)] struct Weight(pub f64); -impl_property_eq_hash!(Weight); impl_property!(Weight, Person, default_const = Weight(0.0)); ``` @@ -143,7 +129,7 @@ impl_property!( /// ```rust /// # use ixa::{impl_property, define_entity}; /// # define_entity!(Person); -/// #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize, serde::Deserialize)] +/// #[derive(Debug, Clone, Copy, ixa::EqHash, serde::Serialize, serde::Deserialize)] /// pub struct Age(u8); /// impl_property!(Age, Person); /// ``` @@ -163,7 +149,7 @@ impl_property!( /// ```rust /// # use ixa::{impl_property, define_entity}; /// # define_entity!(Person); -/// #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize, serde::Deserialize)] +/// #[derive(Debug, Clone, Copy, ixa::EqHash, serde::Serialize, serde::Deserialize)] /// pub struct Coordinates { x: i32, y: i32 } /// impl_property!(Coordinates, Person); /// ``` @@ -185,7 +171,7 @@ impl_property!( /// ```rust /// # use ixa::{impl_property, define_entity}; /// # define_entity!(Person); -/// #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize, serde::Deserialize)] +/// #[derive(Debug, Clone, Copy, ixa::EqHash, serde::Serialize, serde::Deserialize)] /// pub enum InfectionStatus { /// Susceptible, /// Infectious, @@ -196,128 +182,44 @@ impl_property!( /// /// ### Notes /// -/// - By default, the generated type derives `Debug`, `PartialEq`, `Eq`, `Hash`, `Clone`, `Copy`, and the -/// Serde traits; for a field type without Serde, use [`impl_property!`][macro@crate::impl_property]. +/// - The generated type derives `Debug`, `Clone`, `Copy`, the Serde traits, and `PartialEq`, +/// `Eq` and `Hash`: through [`EqHash`][crate::EqHash] for a struct, so floats compare by +/// value, and through the std derives for an enum. For a field type without Serde, use +/// [`impl_property!`][macro@crate::impl_property]. /// - Use the optional `default_const = ` argument to define a compile-time constant /// default for the property. -/// - Use `impl_eq_hash = Eq`, `Hash`, `both`, or `neither` as the first optional argument to suppress the default -/// `Eq`/`Hash` derives and switch to generated or user-supplied implementations. /// - Remaining optional arguments follow the same ordering as [`impl_property!`][macro@crate::impl_property]. /// - If you need a more complex type definition (e.g., generics, attributes, or non-`Copy` /// fields), define the type manually and then call [`impl_property!`][macro@crate::impl_property] directly. #[macro_export] macro_rules! define_property { - // Implementation Notes - // - // To implement the optional `impl_eq_hash` keyword argument, we have the following choices: - // - // 1. Have a single public match branch per type form with `$(, impl_eq_hash = - // $impl_eq_hash:ident)?`, but explicitly list all the keyword options. This option disallows - // the `$(, $($extra:tt)+)*` pattern for the tail. - // 2. Have two branches per type form, one with the `impl_eq_hash = ...` keyword present and one - // with it absent, and use the `$(, $($extra:tt)+)*` pattern for the tail. This duplicates the - // number of public match arms, but it allows us to keep the keyword arguments defined in - // `impl_property!` instead of repeated throughout the code. - // 3. Use a proc macro or "TT munching", both of which are more heavy weight. - // - // We choose the second option. Unfortunately, this doesn't completely eliminate repetition of - // the list of keyword arguments. We still have them in the - // `impl_derived_property!(@with_option_display_default ...)` and - // `impl_property!(@with_option_display_default ...)` subcommands. - - ( - struct $name:ident ( $visibility:vis Option<$inner_ty:ty> ), - $entity:ident, - impl_eq_hash = $impl_eq_hash:ident - $(, $($extra:tt)*)? - ) => { - $crate::define_property!( - @apply_property_decoration $impl_eq_hash, - pub struct $name(pub Option<$inner_ty>);, - $name - ); - $crate::impl_property!(@with_option_display_default $name, $entity $(, $($extra)*)?); - }; ( struct $name:ident ( $visibility:vis Option<$inner_ty:ty> ), $entity:ident $(, $($extra:tt)*)? ) => { - $crate::define_property!( - @apply_property_decoration , - pub struct $name(pub Option<$inner_ty>);, - $name - ); + $crate::define_property!(@declare pub struct $name(pub Option<$inner_ty>);); $crate::impl_property!(@with_option_display_default $name, $entity $(, $($extra)*)?); }; - ( - struct $name:ident ( $($visibility:vis $field_ty:ty),* $(,)? ), - $entity:ident, - impl_eq_hash = $impl_eq_hash:ident - $(, $($extra:tt)*)? - ) => { - $crate::define_property!( - @apply_property_decoration $impl_eq_hash, - pub struct $name($(pub $field_ty),*);, - $name - ); - $crate::impl_property!($name, $entity $(, $($extra)*)?); - }; ( struct $name:ident ( $($visibility:vis $field_ty:ty),* $(,)? ), $entity:ident $(, $($extra:tt)*)? ) => { - $crate::define_property!( - @apply_property_decoration , - pub struct $name($(pub $field_ty),*);, - $name - ); + $crate::define_property!(@declare pub struct $name($(pub $field_ty),*);); $crate::impl_property!($name, $entity $(, $($extra)*)?); }; - ( - struct $name:ident { $($visibility:vis $field_name:ident : $field_ty:ty),* $(,)? }, - $entity:ident, - impl_eq_hash = $impl_eq_hash:ident - $(, $($extra:tt)*)? - ) => { - $crate::define_property!( - @apply_property_decoration $impl_eq_hash, - pub struct $name { $(pub $field_name : $field_ty),* }, - $name - ); - $crate::impl_property!($name, $entity $(, $($extra)*)?); - }; ( struct $name:ident { $($visibility:vis $field_name:ident : $field_ty:ty),* $(,)? }, $entity:ident $(, $($extra:tt)*)? ) => { - $crate::define_property!( - @apply_property_decoration , - pub struct $name { $(pub $field_name : $field_ty),* }, - $name - ); + $crate::define_property!(@declare pub struct $name { $(pub $field_name : $field_ty),* }); $crate::impl_property!($name, $entity $(, $($extra)*)?); }; - ( - enum $name:ident { - $($variant:ident),* $(,)? - }, - $entity:ident, - impl_eq_hash = $impl_eq_hash:ident - $(, $($extra:tt)*)? - ) => { - $crate::define_property!( - @apply_property_decoration $impl_eq_hash, - pub enum $name { $($variant),* }, - $name - ); - $crate::impl_property!($name, $entity $(, $($extra)*)?); - }; ( enum $name:ident { $($variant:ident),* $(,)? @@ -325,123 +227,54 @@ macro_rules! define_property { $entity:ident $(, $($extra:tt)*)? ) => { - $crate::define_property!( - @apply_property_decoration , - pub enum $name { $($variant),* }, - $name - ); + $crate::define_property!(@declare_enum pub enum $name { $($variant),* }); $crate::impl_property!($name, $entity $(, $($extra)*)?); }; - // Both `define_property!` and `define_derived_property!` need to attach derives to a - // concrete item, so the mode table lives here as a shared internal subcommand. - (@apply_property_decoration , $item:item, $name:ident) => { - #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize, serde::Deserialize)] - $item - }; - (@apply_property_decoration Eq, $item:item, $name:ident) => { - #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, $crate::rkyv::Archive, $crate::rkyv::Serialize)] - #[rkyv(crate = $crate::rkyv)] + // The derives a struct property gets. `EqHash` stands in for `PartialEq`, `Eq` and `Hash` + // so that fields may hold floats. Shared with `define_derived_property!`. + (@declare $item:item) => { + #[derive(Debug, Clone, Copy, $crate::EqHash, serde::Serialize, serde::Deserialize)] + #[eq_hash(crate = $crate)] $item - $crate::impl_property_eq!($name); }; - (@apply_property_decoration Hash, $item:item, $name:ident) => { - #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, $crate::rkyv::Archive, $crate::rkyv::Serialize)] - #[rkyv(crate = $crate::rkyv)] - $item - $crate::impl_property_hash!($name); - }; - (@apply_property_decoration both, $item:item, $name:ident) => { - #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, $crate::rkyv::Archive, $crate::rkyv::Serialize)] - #[rkyv(crate = $crate::rkyv)] - $item - $crate::impl_property_eq_hash!($name); - }; - (@apply_property_decoration neither, $item:item, $name:ident) => { - #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] + // An enum declared here has no fields, so it keeps the std derives and its values stay + // usable as constants in `match` patterns. + (@declare_enum $item:item) => { + #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, serde::Serialize, serde::Deserialize)] $item }; - (@apply_property_decoration $mode:ident, $item:item, $name:ident) => { - compile_error!("`impl_eq_hash` must be one of `Eq`, `Hash`, `both`, or `neither`"); - }; - } -/// Implements [`PartialEq`][core::cmp::PartialEq] and [`Eq`][core::cmp::Eq] for a property type -/// using Ixa's generated byte-based equality behavior. -/// -/// This macro is useful when declaring a property type manually and then using -/// [`impl_property!`][macro@crate::impl_property] or -/// [`impl_derived_property!`][macro@crate::impl_derived_property]. The type must implement -/// [`rkyv::Archive`][crate::rkyv::Archive] and [`rkyv::Serialize`][crate::rkyv::Serialize], because -/// equality is computed by serializing the archived representation of each value. -/// -/// The macro accepts a concrete property type identifier. Generic property types are not supported. +/// Removed in 5.0; derive [`EqHash`][crate::EqHash] instead. Kept for one major release so the +/// error names the replacement. +#[doc(hidden)] #[macro_export] macro_rules! impl_property_eq { - ($name:ident) => { - impl core::cmp::PartialEq for $name { - fn eq(&self, other: &Self) -> bool { - const N: usize = core::mem::size_of::<<$name as $crate::rkyv::Archive>::Archived>(); - - let left = $crate::rkyv::api::high::to_bytes_in::<_, $crate::rkyv::rancor::Error>( - self, - $crate::hashing::EqualityBufferWriter::::new(), - ) - .expect("serializing left value for equality comparison failed"); - - let right = $crate::rkyv::api::high::to_bytes_in::<_, $crate::rkyv::rancor::Error>( - other, - $crate::hashing::EqualityBufferWriter::::new(), - ) - .expect("serializing right value for equality comparison failed"); - - left.as_written() == right.as_written() - } - } - - impl core::cmp::Eq for $name {} + ($($tt:tt)*) => { + compile_error!( + "`impl_property_eq!` was removed: add `#[derive(ixa::EqHash)]` to the type instead." + ); }; } -/// Implements [`Hash`][core::hash::Hash] for a property type using Ixa's generated byte-based -/// hashing behavior. -/// -/// This macro is useful when declaring a property type manually and then using -/// [`impl_property!`][macro@crate::impl_property] or -/// [`impl_derived_property!`][macro@crate::impl_derived_property]. The type must implement -/// [`rkyv::Archive`][crate::rkyv::Archive] and [`rkyv::Serialize`][crate::rkyv::Serialize], because -/// hashing is computed by serializing the archived representation into the supplied hasher. -/// -/// The macro accepts a concrete property type identifier. Generic property types are not supported. +/// Removed in 5.0; derive [`EqHash`][crate::EqHash] instead. +#[doc(hidden)] #[macro_export] macro_rules! impl_property_hash { - ($name:ident) => { - impl core::hash::Hash for $name { - fn hash(&self, state: &mut H) { - $crate::rkyv::api::high::to_bytes_in::<_, $crate::rkyv::rancor::Error>( - self, - $crate::hashing::HasherWriter::new(state), - ) - .expect("serialization failed while hashing"); - } - } + ($($tt:tt)*) => { + compile_error!( + "`impl_property_hash!` was removed: add `#[derive(ixa::EqHash)]` to the type instead." + ); }; } -/// Implements [`PartialEq`][core::cmp::PartialEq], [`Eq`][core::cmp::Eq], and -/// [`Hash`][core::hash::Hash] for a property type using Ixa's generated byte-based equality and -/// hashing behavior. -/// -/// This is a convenience wrapper around [`impl_property_eq!`][macro@crate::impl_property_eq] and -/// [`impl_property_hash!`][macro@crate::impl_property_hash]. -/// -/// The macro accepts a concrete property type identifier. Generic property types are not supported. +/// Removed in 5.0; derive [`EqHash`][crate::EqHash] instead. +#[doc(hidden)] #[macro_export] macro_rules! impl_property_eq_hash { - ($name:ident) => { - $crate::impl_property_eq!($name); - $crate::impl_property_hash!($name); + ($($tt:tt)*) => { + compile_error!("`impl_property_eq_hash!` was removed: add `#[derive(ixa::EqHash)]` to the type instead."); }; } @@ -522,6 +355,23 @@ macro_rules! impl_property_eq_hash { /// Only `false` is accepted. #[macro_export] macro_rules! impl_property { + // The `impl_eq_hash` option was removed in 5.0; these arms give a clear error instead of + // "no rules expected `impl_eq_hash`" and can go in the next major release. + ( + $property:ident, + $entity:ident, + impl_eq_hash = $mode:ident + $(, $($extra:tt)*)? + ) => { + $crate::impl_property!(@removed_impl_eq_hash); + }; + (@removed_impl_eq_hash) => { + compile_error!( + "`impl_eq_hash` was removed: `define_property!` now derives `EqHash`, which handles \ + floats. For a type declared by hand, add `#[derive(ixa::EqHash)]`." + ); + }; + ( $property:ident, $entity:ident @@ -604,6 +454,16 @@ macro_rules! impl_property { ); }; + ( + @with_option_display_default + $property:ident, + $entity:ident, + impl_eq_hash = $mode:ident + $(, $($extra:tt)*)? + ) => { + $crate::impl_property!(@removed_impl_eq_hash); + }; + ( @with_option_display_default $property:ident, @@ -892,59 +752,21 @@ macro_rules! impl_property { /// * `[$($dependency),+]`: A list of person properties the derived property depends on. /// * `[$(global_dependency),*]`: A list of global properties the derived property depends on. Can optionally be omitted if empty. /// * `$calculate`: A closure that takes the values of each dependency and returns the derived value. -/// * Optional parameters: The same optional parameters accepted by [`impl_property!`][macro@crate::impl_property], -/// plus `impl_eq_hash = Eq | Hash | both | neither` to control whether `Eq`/`Hash` are derived or generated -/// for the declared type, mirroring [`define_property!`][macro@crate::define_property]. +/// * Optional parameters: The same optional parameters accepted by [`impl_property!`][macro@crate::impl_property]. +/// +/// The declared type gets the same derives as with [`define_property!`][macro@crate::define_property]. #[macro_export] macro_rules! define_derived_property { - // Implementation Notes - // - // We reuse `define_property!`'s shared decoration helper, then delegate the derived-property - // behavior to `impl_derived_property!`. - // - // See `derive_property!` implementation notes for why each type form is duplicated. - // Struct (tuple) with single Option field - ( - struct $name:ident ( $visibility:vis Option<$inner_ty:ty> ), - $entity:ident, - [$($dependency:ident),*] - $(, [$($global_dependency:ident),*])?, - |$($param:ident),+| $derive_fn:expr, - impl_eq_hash = $impl_eq_hash:ident - $(, $($extra:tt)+)* - ) => { - $crate::define_property!( - @apply_property_decoration - $impl_eq_hash, - pub struct $name(pub Option<$inner_ty>);, - $name - ); - - $crate::impl_derived_property!( - @with_option_display_default - $name, - $entity, - [$($dependency),*], - [$($($global_dependency),*)?], - |$($param),+| $derive_fn - $(, $($extra)+)* - ); - }; ( struct $name:ident ( $visibility:vis Option<$inner_ty:ty> ), $entity:ident, [$($dependency:ident),*] $(, [$($global_dependency:ident),*])?, |$($param:ident),+| $derive_fn:expr - $(, $($extra:tt)+)* + $(, $($extra:tt)+)? ) => { - $crate::define_property!( - @apply_property_decoration - , - pub struct $name(pub Option<$inner_ty>);, - $name - ); + $crate::define_property!(@declare pub struct $name(pub Option<$inner_ty>);); $crate::impl_derived_property!( @with_option_display_default @@ -953,50 +775,20 @@ macro_rules! define_derived_property { [$($dependency),*], [$($($global_dependency),*)?], |$($param),+| $derive_fn - $(, $($extra)+)* + $(, $($extra)+)? ); }; // Struct (tuple) - ( - struct $name:ident ( $($visibility:vis $field_ty:ty),* $(,)? ), - $entity:ident, - [$($dependency:ident),*] - $(, [$($global_dependency:ident),*])?, - |$($param:ident),+| $derive_fn:expr, - impl_eq_hash = $impl_eq_hash:ident - $(, $($extra:tt)+)* - ) => { - $crate::define_property!( - @apply_property_decoration - $impl_eq_hash, - pub struct $name( $(pub $field_ty),* );, - $name - ); - - $crate::impl_derived_property!( - $name, - $entity, - [$($dependency),*], - [$($($global_dependency),*)?], - |$($param),+| $derive_fn - $(, $($extra)+)* - ); - }; ( struct $name:ident ( $($visibility:vis $field_ty:ty),* $(,)? ), $entity:ident, [$($dependency:ident),*] $(, [$($global_dependency:ident),*])?, |$($param:ident),+| $derive_fn:expr - $(, $($extra:tt)+)* + $(, $($extra:tt)+)? ) => { - $crate::define_property!( - @apply_property_decoration - , - pub struct $name( $(pub $field_ty),* );, - $name - ); + $crate::define_property!(@declare pub struct $name( $(pub $field_ty),* );); $crate::impl_derived_property!( $name, @@ -1004,50 +796,20 @@ macro_rules! define_derived_property { [$($dependency),*], [$($($global_dependency),*)?], |$($param),+| $derive_fn - $(, $($extra)+)* + $(, $($extra)+)? ); }; // Struct (named fields) - ( - struct $name:ident { $($visibility:vis $field_name:ident : $field_ty:ty),* $(,)? }, - $entity:ident, - [$($dependency:ident),*] - $(, [$($global_dependency:ident),*])?, - |$($param:ident),+| $derive_fn:expr, - impl_eq_hash = $impl_eq_hash:ident - $(, $($extra:tt)+)* - ) => { - $crate::define_property!( - @apply_property_decoration - $impl_eq_hash, - pub struct $name { $($visibility $field_name : $field_ty),* }, - $name - ); - - $crate::impl_derived_property!( - $name, - $entity, - [$($dependency),*], - [$($($global_dependency),*)?], - |$($param),+| $derive_fn - $(, $($extra)+)* - ); - }; ( struct $name:ident { $($visibility:vis $field_name:ident : $field_ty:ty),* $(,)? }, $entity:ident, [$($dependency:ident),*] $(, [$($global_dependency:ident),*])?, |$($param:ident),+| $derive_fn:expr - $(, $($extra:tt)+)* + $(, $($extra:tt)+)? ) => { - $crate::define_property!( - @apply_property_decoration - , - pub struct $name { $($visibility $field_name : $field_ty),* }, - $name - ); + $crate::define_property!(@declare pub struct $name { $(pub $field_name : $field_ty),* }); $crate::impl_derived_property!( $name, @@ -1055,40 +817,11 @@ macro_rules! define_derived_property { [$($dependency),*], [$($($global_dependency),*)?], |$($param),+| $derive_fn - $(, $($extra)+)* + $(, $($extra)+)? ); }; // Enum - ( - enum $name:ident { - $($variant:ident),* $(,)? - }, - $entity:ident, - [$($dependency:ident),*] - $(, [$($global_dependency:ident),*])?, - |$($param:ident),+| $derive_fn:expr, - impl_eq_hash = $impl_eq_hash:ident - $(, $($extra:tt)+)* - ) => { - $crate::define_property!( - @apply_property_decoration - $impl_eq_hash, - pub enum $name { - $($variant),* - }, - $name - ); - - $crate::impl_derived_property!( - $name, - $entity, - [$($dependency),*], - [$($($global_dependency),*)?], - |$($param),+| $derive_fn - $(, $($extra)+)* - ); - }; ( enum $name:ident { $($variant:ident),* $(,)? @@ -1097,16 +830,9 @@ macro_rules! define_derived_property { [$($dependency:ident),*] $(, [$($global_dependency:ident),*])?, |$($param:ident),+| $derive_fn:expr - $(, $($extra:tt)+)* + $(, $($extra:tt)+)? ) => { - $crate::define_property!( - @apply_property_decoration - , - pub enum $name { - $($variant),* - }, - $name - ); + $crate::define_property!(@declare_enum pub enum $name { $($variant),* }); $crate::impl_derived_property!( $name, @@ -1114,7 +840,7 @@ macro_rules! define_derived_property { [$($dependency),*], [$($($global_dependency),*)?], |$($param),+| $derive_fn - $(, $($extra)+)* + $(, $($extra)+)? ); }; } @@ -1126,13 +852,26 @@ macro_rules! define_derived_property { /// of [`impl_property!`][macro@crate::impl_property]. It calls [`impl_property!`][macro@crate::impl_property] with the appropriate derived property parameters. #[macro_export] macro_rules! impl_derived_property { + ( + $(@with_option_display_default)? + $name:ident, + $entity:ident, + [$($dependency:ident),*] + $(, [$($global_dependency:ident),*])?, + |$($param:ident),+| $derive_fn:expr, + impl_eq_hash = $mode:ident + $(, $($extra:tt)*)? + ) => { + $crate::impl_property!(@removed_impl_eq_hash); + }; + ( $name:ident, $entity:ident, [$($dependency:ident),*] $(, [$($global_dependency:ident),*])?, |$($param:ident),+| $derive_fn:expr - $(, $($extra:tt)+)* + $(, $($extra:tt)+)? ) => { $crate::impl_property!( $name, @@ -1153,7 +892,7 @@ macro_rules! impl_derived_property { } )* } - $(, $($extra)+)* + $(, $($extra)+)? ); }; @@ -1439,7 +1178,6 @@ mod tests { define_property!( struct POFloat(Option), Person, - impl_eq_hash = both, default_const = POFloat(None) ); define_property!( @@ -1463,7 +1201,7 @@ mod tests { default_const = Name::Empty ); define_property!(struct Age(u8), Person, default_const = Age(0)); - define_property!(struct Weight(f64), Person, impl_eq_hash = both, default_const = Weight(0.0)); + define_property!(struct Weight(f64), Person, default_const = Weight(0.0)); // A struct with named fields define_property!( @@ -1472,7 +1210,6 @@ mod tests { dose: u8, }, Person, - impl_eq_hash = both, default_const = Innocculation { time: 0.0, dose: 0 } ); @@ -1526,8 +1263,7 @@ mod tests { struct DerivedMaybeWeight(Option), Person, [Age], - |age| DerivedMaybeWeight((age.0 != 0).then_some(age.0 as f64)), - impl_eq_hash = both + |age| DerivedMaybeWeight((age.0 != 0).then_some(age.0 as f64)) ); define_derived_property!( @@ -1545,8 +1281,7 @@ mod tests { struct DerivedWeight(f64), Person, [Age], - |age| DerivedWeight(age.0 as f64), - impl_eq_hash = both + |age| DerivedWeight(age.0 as f64) ); #[derive(Debug, PartialEq, Clone, Copy, serde::Serialize, serde::Deserialize)] @@ -1933,7 +1668,7 @@ mod tests { } #[test] - fn test_define_derived_property_impl_eq_hash() { + fn test_define_derived_property_float_is_hashable() { let mut values = crate::HashSet::default(); values.insert(DerivedWeight(3.0)); assert!(values.contains(&DerivedWeight(3.0))); diff --git a/src/prelude.rs b/src/prelude.rs index 3b18a369..f3e87887 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -14,6 +14,8 @@ pub use crate::report::ContextReportExt; pub use crate::{ define_data_plugin, define_derived_property, define_entity, define_global_property, define_multi_property, define_network, define_property, define_report, define_rng, impl_entity, - impl_network, impl_property, impl_property_eq, impl_property_eq_hash, impl_property_hash, - output, schedule_relative, track_periodic_value_change_counts, with, PlanId, PluginContext, + impl_network, impl_property, output, schedule_relative, track_periodic_value_change_counts, + with, EqHash, PlanId, PluginContext, }; +// Removed macros, exported so a 4.x model gets an error naming `EqHash`; drop in the next major. +pub use crate::{impl_property_eq, impl_property_eq_hash, impl_property_hash}; diff --git a/src/value_key.rs b/src/value_key.rs new file mode 100644 index 00000000..95c49133 --- /dev/null +++ b/src/value_key.rs @@ -0,0 +1,241 @@ +//! Equality and hashing of property values: support code for `EqHash`, not public API. +//! +//! Property types get `PartialEq`, `Eq` and `Hash` from [`EqHash`](crate::EqHash), which +//! compares and hashes each field by its [`ValueKey`] when the field type has one (that takes +//! precedence over a type's own `Eq` and `Hash`), and by the field's own `Eq` and `Hash` +//! otherwise. Floats have a `ValueKey`: their bit pattern with +//! `-0.0` folded into `0.0` and every `NaN` folded into one, so a float field compares like +//! IEEE equality except that `NaN` equals itself, which an index or hash map needs. + +use std::hash::Hash; +use std::marker::PhantomData; + +/// A value compared and hashed through a key rather than through its own `Eq` and `Hash`. +/// +/// Implemented for `f32` and `f64`, for the integer, `bool`, `char` and `()` types as the +/// identity, and for `Option`s, arrays and tuples of up to eight implementors. +pub trait ValueKey { + type Key: Eq + Hash; + + fn value_key(&self) -> Self::Key; +} + +impl ValueKey for f64 { + type Key = u64; + + #[inline] + fn value_key(&self) -> u64 { + // Adding 0.0 turns -0.0 into 0.0 and changes no other value, without a branch. + let bits = (*self + 0.0).to_bits(); + if self.is_nan() { + f64::NAN.to_bits() + } else { + bits + } + } +} + +impl ValueKey for f32 { + type Key = u32; + + #[inline] + fn value_key(&self) -> u32 { + // Adding 0.0 turns -0.0 into 0.0 and changes no other value, without a branch. + let bits = (*self + 0.0).to_bits(); + if self.is_nan() { + f32::NAN.to_bits() + } else { + bits + } + } +} + +impl ValueKey for Option { + type Key = Option; + + #[inline] + fn value_key(&self) -> Self::Key { + self.as_ref().map(ValueKey::value_key) + } +} + +impl ValueKey for [T; N] { + type Key = [T::Key; N]; + + #[inline] + fn value_key(&self) -> Self::Key { + std::array::from_fn(|index| self[index].value_key()) + } +} + +macro_rules! impl_value_key_identity { + ($($type:ty),*) => { + $( + impl ValueKey for $type { + type Key = $type; + + #[inline] + fn value_key(&self) -> $type { + *self + } + } + )* + }; +} + +impl_value_key_identity!( + (), + bool, + char, + u8, + i8, + u16, + i16, + u32, + i32, + u64, + i64, + u128, + i128, + usize, + isize +); + +macro_rules! impl_value_key_tuple { + ($($name:ident $index:tt),+) => { + impl<$($name: ValueKey),+> ValueKey for ($($name,)+) { + type Key = ($($name::Key,)+); + + #[inline] + fn value_key(&self) -> Self::Key { + ($(self.$index.value_key(),)+) + } + } + }; +} + +impl_value_key_tuple!(A 0); +impl_value_key_tuple!(A 0, B 1); +impl_value_key_tuple!(A 0, B 1, C 2); +impl_value_key_tuple!(A 0, B 1, C 2, D 3); +impl_value_key_tuple!(A 0, B 1, C 2, D 3, E 4); +impl_value_key_tuple!(A 0, B 1, C 2, D 3, E 4, F 5); +impl_value_key_tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6); +impl_value_key_tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7); + +/// Autoref-specialization probe used by `EqHash`: `(&KeyProbe::::new()).probe_key(&value)` +/// resolves to [`ValueKey`] when `T` implements it, and to the reference itself, compared and +/// hashed through `T`'s own `Eq` and `Hash`, otherwise. Both probe traits must be in scope at +/// the call site. +#[doc(hidden)] +pub struct KeyProbe(PhantomData); + +impl KeyProbe { + #[must_use] + pub const fn new() -> Self { + Self(PhantomData) + } +} + +impl Default for KeyProbe { + fn default() -> Self { + Self::new() + } +} + +#[doc(hidden)] +pub trait KeyProbeValue { + type Key: Eq + Hash; + + fn probe_key(&self, value: &T) -> Self::Key; +} + +impl KeyProbeValue for KeyProbe { + type Key = T::Key; + + #[inline] + fn probe_key(&self, value: &T) -> T::Key { + value.value_key() + } +} + +#[doc(hidden)] +pub trait KeyProbeFallback { + fn probe_key<'a>(&self, value: &'a T) -> &'a T; +} + +impl KeyProbeFallback for &KeyProbe { + #[inline] + fn probe_key<'a>(&self, value: &'a T) -> &'a T { + value + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn float_keys_fold_zeros_and_nans() { + assert_eq!(0.0f64.value_key(), (-0.0f64).value_key()); + assert_eq!(f64::NAN.value_key(), (-f64::NAN).value_key()); + assert_eq!( + f64::NAN.value_key(), + f64::from_bits(0x7ff0_0000_0000_0001).value_key() + ); + assert_ne!(1.0f64.value_key(), 2.0f64.value_key()); + assert_ne!(f64::INFINITY.value_key(), f64::NEG_INFINITY.value_key()); + assert_eq!(0.0f32.value_key(), (-0.0f32).value_key()); + assert_eq!(f32::NAN.value_key(), (-f32::NAN).value_key()); + } + + #[test] + fn float_keys_are_the_bits_of_every_other_value() { + assert_eq!((-0.0f64).value_key(), 0); + assert_eq!((-0.0f32).value_key(), 0); + let values = [ + 1.0, + -1.0, + 0.1, + f64::MIN_POSITIVE, + -f64::MIN_POSITIVE, + f64::from_bits(1), + -f64::from_bits(1), + f64::MAX, + f64::MIN, + f64::INFINITY, + f64::NEG_INFINITY, + ]; + for value in values { + assert_eq!(value.value_key(), value.to_bits()); + } + // A coarse sweep of the f32 bit patterns, subnormals and infinities included. + for bits in (0..=u32::MAX).step_by(9973) { + let value = f32::from_bits(bits); + if !value.is_nan() && value != 0.0 { + assert_eq!(value.value_key(), bits); + } + } + } + + #[test] + fn compound_keys_follow_their_elements() { + assert_eq!(Some(-0.0f64).value_key(), Some(0.0f64).value_key()); + assert_ne!(None::.value_key(), Some(0.0f64).value_key()); + assert_eq!( + [0.0f64, f64::NAN].value_key(), + [-0.0f64, f64::NAN].value_key() + ); + assert_eq!((1u8, -0.0f32).value_key(), (1u8, 0.0f32).value_key()); + } + + #[test] + fn probe_prefers_value_key_and_falls_back_to_hash() { + #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] + struct Plain(u8); + + assert_eq!(KeyProbe::::new().probe_key(&-0.0), 0u64); + assert_eq!((&KeyProbe::::new()).probe_key(&Plain(3)), &Plain(3)); + assert_eq!(KeyProbe::::new().probe_key(&7), 7u16); + } +} diff --git a/tests/eq_hash.rs b/tests/eq_hash.rs new file mode 100644 index 00000000..749a78aa --- /dev/null +++ b/tests/eq_hash.rs @@ -0,0 +1,232 @@ +//! The `EqHash` derive: float-valued properties compare by value and can be indexed. + +use ixa::prelude::*; +use ixa::HashMap; + +define_entity!(Person); + +define_property!(struct Weight(f64), Person, default_const = Weight(0.0)); +define_property!(struct MaybeWeight(Option), Person, default_const = MaybeWeight(None)); +define_property!( + struct Dose { + amount: f64, + count: u8, + }, + Person, + default_const = Dose { + amount: 0.0, + count: 0 + } +); +define_property!(struct Position([f64; 2]), Person, default_const = Position([0.0, 0.0])); +define_derived_property!( + struct HalfWeight(f64), + Person, + [Weight], + |weight| HalfWeight(weight.0 / 2.0) +); + +#[derive(Debug, Clone, Copy, EqHash, serde::Serialize, serde::Deserialize)] +pub enum Treatment { + Untreated, + Antiviral { dose_mg: f64 }, + Vaccinated(u8, f32), +} +impl_property!(Treatment, Person, default_const = Treatment::Untreated); + +// A nested property type goes through its own `Eq + Hash`, which `EqHash` provided. +#[derive(Debug, Clone, Copy, EqHash, serde::Serialize, serde::Deserialize)] +pub struct Exposure { + dose: Dose, + weight: Weight, +} +impl_property!( + Exposure, + Person, + default_const = Exposure { + dose: Dose { + amount: 0.0, + count: 0 + }, + weight: Weight(0.0) + } +); + +// The crate path can be given explicitly, as the property macros do with `$crate`. +mod reexport { + pub use ixa as sim; +} +#[derive(Debug, Clone, Copy, EqHash)] +#[eq_hash(crate = reexport::sim)] +pub struct ExplicitCratePath(f64); + +fn hash_of(value: &T) -> u64 { + use std::hash::Hasher; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + value.hash(&mut hasher); + hasher.finish() +} + +#[test] +fn floats_compare_by_value_with_nan_reflexive() { + assert_eq!(Weight(1.5), Weight(1.5)); + assert_ne!(Weight(1.5), Weight(2.5)); + assert_eq!(Weight(0.0), Weight(-0.0)); + assert_eq!(hash_of(&Weight(0.0)), hash_of(&Weight(-0.0))); + assert_eq!(Weight(f64::NAN), Weight(f64::NAN)); + assert_eq!(hash_of(&Weight(f64::NAN)), hash_of(&Weight(-f64::NAN))); + assert_ne!(Weight(f64::INFINITY), Weight(f64::NEG_INFINITY)); + + assert_eq!(MaybeWeight(Some(-0.0)), MaybeWeight(Some(0.0))); + assert_ne!(MaybeWeight(None), MaybeWeight(Some(0.0))); + assert_eq!(Position([0.0, f64::NAN]), Position([-0.0, f64::NAN])); +} + +#[test] +fn mixed_fields_compare_every_field() { + let dose = Dose { + amount: 1.0, + count: 2, + }; + assert_eq!( + dose, + Dose { + amount: 1.0, + count: 2 + } + ); + assert_ne!( + dose, + Dose { + amount: 1.0, + count: 3 + } + ); + assert_ne!( + dose, + Dose { + amount: 2.0, + count: 2 + } + ); + let exposure = Exposure { + dose, + weight: Weight(-0.0), + }; + assert_eq!( + exposure, + Exposure { + dose, + weight: Weight(0.0) + } + ); + assert_eq!( + hash_of(&exposure), + hash_of(&Exposure { + dose, + weight: Weight(0.0) + }) + ); +} + +// A constant named like a plain binding would turn the derive's patterns into const patterns. +mod binding_names { + #[allow(non_upper_case_globals, dead_code)] + const left_0: u8 = 1; + #[allow(non_upper_case_globals, dead_code)] + const right_0: u8 = 1; + + #[derive(Debug, Clone, Copy, ixa::EqHash)] + pub struct Shadowed(pub u8); +} + +#[test] +fn bindings_do_not_collide_with_constants_in_scope() { + assert_eq!(binding_names::Shadowed(2), binding_names::Shadowed(2)); + assert_ne!(binding_names::Shadowed(2), binding_names::Shadowed(3)); +} + +#[test] +fn explicit_crate_path_is_used() { + assert_eq!(ExplicitCratePath(-0.0), ExplicitCratePath(0.0)); +} + +define_property!( + enum Stage { + Early, + Late, + }, + Person, + default_const = Stage::Early +); + +// A `define_property!` enum keeps the std derives, so a constant of it can be a pattern. +#[test] +fn macro_declared_enum_constants_are_patterns() { + const DEFAULT_STAGE: Stage = Stage::Early; + assert!(matches!(Stage::Early, DEFAULT_STAGE)); + assert!(!matches!(Stage::Late, DEFAULT_STAGE)); +} + +#[test] +fn enums_compare_variant_then_fields() { + assert_eq!(Treatment::Untreated, Treatment::Untreated); + assert_ne!(Treatment::Untreated, Treatment::Antiviral { dose_mg: 0.0 }); + assert_eq!( + Treatment::Antiviral { dose_mg: f64::NAN }, + Treatment::Antiviral { dose_mg: f64::NAN } + ); + assert_ne!( + Treatment::Antiviral { dose_mg: 1.0 }, + Treatment::Antiviral { dose_mg: 2.0 } + ); + assert_eq!( + Treatment::Vaccinated(1, 0.0), + Treatment::Vaccinated(1, -0.0) + ); + assert_ne!(Treatment::Vaccinated(1, 0.0), Treatment::Vaccinated(2, 0.0)); + assert_ne!( + hash_of(&Treatment::Vaccinated(1, 0.0)), + hash_of(&Treatment::Vaccinated(2, 0.0)) + ); +} + +#[test] +fn float_properties_index_and_query() { + let mut context = Context::new(); + context.index_property::(); + context.index_property::(); + for weight in [1.0, 2.0, 2.0, -0.0, f64::NAN] { + context + .add_entity(with!( + Person, + Weight(weight), + Treatment::Antiviral { dose_mg: weight } + )) + .unwrap(); + } + + assert_eq!(context.query_entity_count(with!(Person, Weight(2.0))), 2); + assert_eq!(context.query_entity_count(with!(Person, Weight(0.0))), 1); + assert_eq!( + context.query_entity_count(with!(Person, Weight(f64::NAN))), + 1 + ); + assert_eq!(context.query_entity_count(with!(Person, Weight(3.0))), 0); + assert_eq!( + context.query_entity_count(with!(Person, Treatment::Antiviral { dose_mg: 2.0 })), + 2 + ); + assert_eq!( + context.query_entity_count(with!(Person, Treatment::Untreated)), + 0 + ); + + // Derived float properties hash too. + let person = context.add_entity(with!(Person, Weight(5.0))).unwrap(); + let mut halves: HashMap = HashMap::default(); + *halves + .entry(context.get_property::(person)) + .or_default() += 1; + assert_eq!(halves.get(&HalfWeight(2.5)), Some(&1)); +}