daft-0.1.5/.cargo_vcs_info.json0000644000000001420000000000100117520ustar { "git": { "sha1": "5dc889ee3f1ec59b196b298cd30646da62c5914b" }, "path_in_vcs": "daft" }daft-0.1.5/CHANGELOG.md000064400000000000000000000036161046102023000123640ustar 00000000000000# Changelog ## [0.1.5] - 2025-09-29 ### Fixed Replaced obsolete `doc_auto_cfg` with `doc_cfg`, to fix Rust nightly builds with the `doc_cfg` flag enabled. ## [0.1.4] - 2025-06-29 ### Added - Implement `Diffable` for `NonZero` types. Thanks [itsjunetime](https://github.com/itsjunetime) for your first contribution! ## [0.1.3] - 2025-04-01 ### Fixed The `Diffable` derive macro now produces both code and errors when the only errors are duplicate struct and field attribute errors. Thanks to [schneems](https://github.com/schneems) for your first contribution; be sure to read [his blog post](https://www.schneems.com/2025/03/26/a-daft-procmacro-trick-how-to-emit-partialcode-errors/) about Daft's error handling! ## [0.1.2] - 2025-03-10 ### Fixed - Semantic errors (e.g. a field not implementing `Diffable`) are better annotated. - The `Diffable` derive macro now produces references to `core` rather than to `std`, meaning that the code it generates is no-std compatible. ## [0.1.1] - 2025-02-10 ### Added - Add `Leaf::is_unchanged` and `Leaf::is_modified` when the stored type is `Eq`. - Add `BTreeMapDiff::is_unchanged`, `BTreeMapDiff::is_modified`, `BTreeMapDiff::get_unchanged`, `BTreeMapDiff::get_modified`, and similar methods for `HashMapDiff` when map values are `Eq`. ## [0.1.0] - 2025-02-10 Initial release with support for: - Diffing maps, sets, and structs recursively - Eager and lazy diffing - No-std support - The `Diffable` derive macro - Implementations for `oxnet`, `uuid`, and `newtype-uuid` [0.1.5]: https://github.com/oxidecomputer/daft/releases/daft-0.1.5 [0.1.4]: https://github.com/oxidecomputer/daft/releases/daft-0.1.4 [0.1.3]: https://github.com/oxidecomputer/daft/releases/daft-0.1.3 [0.1.2]: https://github.com/oxidecomputer/daft/releases/daft-0.1.2 [0.1.1]: https://github.com/oxidecomputer/daft/releases/daft-0.1.1 [0.1.0]: https://github.com/oxidecomputer/daft/releases/daft-0.1.0 daft-0.1.5/Cargo.lock0000644000000127530000000000100077400ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "daft" version = "0.1.5" dependencies = [ "daft-derive", "newtype-uuid", "oxnet", "paste", "uuid", ] [[package]] name = "daft-derive" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27c6a4a4003df965e441d13b2a7044efa44334b567c984701f8a2773f815c5e2" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "dyn-clone" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" [[package]] name = "getrandom" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "ipnetwork" version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf370abdafd54d13e54a620e8c3e1145f28e46cc9d704bc6d94414559df41763" [[package]] name = "itoa" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" [[package]] name = "libc" version = "0.2.169" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "newtype-uuid" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee3224f0e8be7c2a1ebc77ef9c3eecb90f55c6594399ee825de964526b3c9056" dependencies = [ "uuid", ] [[package]] name = "oxnet" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff7aba867c36df803039621068faf1630d3039eb999c2f6c3950d1064d4fbbdf" dependencies = [ "ipnetwork", "schemars", "serde", "serde_json", ] [[package]] name = "paste" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" [[package]] name = "proc-macro2" version = "1.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] [[package]] name = "ryu" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "schemars" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09c024468a378b7e36765cd36702b7a90cc3cba11654f6685c8f233408e89e92" dependencies = [ "dyn-clone", "schemars_derive", "serde", "serde_json", ] [[package]] name = "schemars_derive" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1eee588578aff73f856ab961cd2f79e36bc45d7ded33a7562adba4667aecc0e" dependencies = [ "proc-macro2", "quote", "serde_derive_internals", "syn", ] [[package]] name = "serde" version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_derive_internals" version = "0.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.137" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "930cfb6e6abf99298aaad7d29abbef7a9999a9a8806a40088f55f0dcec03146b" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "syn" version = "2.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11cd88e12b17c6494200a9c1b683a04fcac9573ed74cd1b62aeb2727c5592243" [[package]] name = "uuid" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3758f5e68192bb96cc8f9b7e2c2cfdabb435499a28499a42f8f984092adad4b" dependencies = [ "getrandom", ] [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" daft-0.1.5/Cargo.toml0000644000000033420000000000100077550ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.81.0" name = "daft" version = "0.1.5" build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Structural diffs of Rust data structures" readme = "README.md" keywords = [ "diff", "difference", "semantic-diff", "structural-diff", ] categories = [ "development-tools", "no-std::no-alloc", ] license = "MIT OR Apache-2.0" repository = "https://github.com/oxidecomputer/daft" [package.metadata.cargo-sync-rdme.badge.badges] crates-io = true docs-rs = true license = true rust-version = true [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg=doc_cfg"] [features] alloc = [] default = ["std"] derive = ["dep:daft-derive"] newtype-uuid1 = ["dep:newtype-uuid"] oxnet01 = ["dep:oxnet"] std = ["alloc"] uuid1 = ["dep:uuid"] [lib] name = "daft" path = "src/lib.rs" [dependencies.daft-derive] version = "=0.1.5" optional = true [dependencies.newtype-uuid] version = "1.2.1" optional = true [dependencies.oxnet] version = "0.1.0" optional = true [dependencies.paste] version = "1.0.15" [dependencies.uuid] version = "1.12.0" features = ["v4"] optional = true [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = ["cfg(doc_cfg)"] daft-0.1.5/Cargo.toml.orig000064400000000000000000000016721046102023000134420ustar 00000000000000[package] name = "daft" version = "0.1.5" description = "Structural diffs of Rust data structures" readme = "README.md" categories = ["development-tools", "no-std::no-alloc"] keywords.workspace = true edition.workspace = true repository.workspace = true rust-version.workspace = true license.workspace = true [lints] workspace = true [dependencies] daft-derive = { workspace = true, optional = true } newtype-uuid = { workspace = true, optional = true } oxnet = { workspace = true, optional = true } paste.workspace = true uuid = { workspace = true, optional = true, features = ["v4"] } [features] default = ["std"] std = ["alloc"] alloc = [] derive = ["dep:daft-derive"] newtype-uuid1 = ["dep:newtype-uuid"] oxnet01 = ["dep:oxnet"] uuid1 = ["dep:uuid"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg=doc_cfg"] [package.metadata.cargo-sync-rdme.badge.badges] license = true crates-io = true docs-rs = true rust-version = true daft-0.1.5/LICENSE-APACHE000064400000000000000000000251721046102023000125000ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright (c) 2016 Alex Crichton Copyright (c) 2017 The Tokio Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. daft-0.1.5/LICENSE-MIT000064400000000000000000000020521046102023000122000ustar 00000000000000Copyright (c) 2025 Oxide Computer Company Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. daft-0.1.5/README.md000064400000000000000000000371011046102023000120260ustar 00000000000000 # daft ![License: MIT OR Apache-2.0](https://img.shields.io/crates/l/daft.svg?) [![crates.io](https://img.shields.io/crates/v/daft.svg?logo=rust)](https://crates.io/crates/daft) [![docs.rs](https://img.shields.io/docsrs/daft.svg?logo=docs.rs)](https://docs.rs/daft) [![Rust: ^1.81.0](https://img.shields.io/badge/rust-^1.81.0-93450a.svg?logo=rust)](https://doc.rust-lang.org/cargo/reference/manifest.html#the-rust-version-field) Daft is a library to perform semantic diffs of Rust data structures. Daft consists of a trait called [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html), along with [a derive macro](https://docs.rs/daft-derive/0.1.5/daft_derive/derive.Diffable.html) by the same name. This trait represents the notion of a type for which two members can be simultaneously compared. ## Features * **Recursive diffing** of structs, sets, and maps * **Derive macro** for automatically generating diff types * Choose between **eager** and **lazy** diffing * **No-std compatible**, both with and without `alloc` ## Usage ````rust use daft::{Diffable, Leaf}; // Annotate your struct with `#[derive(Diffable)]`: #[derive(Diffable)] struct MyStruct { a: i32, b: String, } // This generates a type called MyStructDiff, which looks like: #[automatically_derived] struct MyStructDiff<'daft> { a: Leaf<&'daft i32>, b: Leaf<&'daft str>, } // Then, with two instances of MyStruct: let before = MyStruct { a: 1, b: "hello".to_owned() }; let after = MyStruct { a: 2, b: "world".to_owned() }; // You can diff them like so: let diff = before.diff(&after); // And compare the results: assert_eq!(*diff.a.before, 1); assert_eq!(*diff.a.after, 2); assert_eq!(diff.b.before, "hello"); assert_eq!(diff.b.after, "world"); ```` This crate assigns one side the name *before*, and the other side *after*. These labels are arbitrary: if *before* and *after* are swapped, the diff is reversed. ### Diff types Currently, daft comes with a few kinds of diff types: #### [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) instances A [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) represents a logical *leaf node* or *base case* in a diff, i.e. a point at which diffing stops. [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) instances are used for: * *Scalar* or *primitive types* like `i32`, `String`, `bool`, etc. * *Enums*, since diffing across variants is usually not meaningful. * Vector and slice types, since there are several reasonable ways to diff vectors (e.g. set-like, ordered, etc.) and we don’t want to make assumptions. * As an opt-in mechanism for struct fields: see [*Recursive diffs*](#recursive-diffs) below for more. ##### Example A contrived example for integers: ````rust use daft::{Diffable, Leaf}; let diff: Leaf<&i32> = 1_i32.diff(&2); assert_eq!(*diff.before, 1); assert_eq!(*diff.after, 2); ```` Enums also use `Leaf`: ````rust use daft::{Diffable, Leaf}; // Option uses Leaf: let diff: Leaf> = Some(1_i32).diff(&Some(2)); assert_eq!(diff.before, Some(&1)); assert_eq!(diff.after, Some(&2)); // Automatically derived enums also use Leaf: #[derive(Debug, PartialEq, Eq, Diffable)] enum MyEnum { A(i32), B(String), } let before = MyEnum::A(1); let after = MyEnum::B("hello".to_string()); let diff: Leaf<&MyEnum> = before.diff(&after); assert_eq!(diff.before, &before); assert_eq!(diff.after, &after); ```` Vectors use `Leaf` as well: ````rust use daft::{Diffable, Leaf}; let before = vec![1, 2, 3]; let after = vec![4, 5, 6]; let diff: Leaf<&[i32]> = before.diff(&after); assert_eq!(diff.before, &before); assert_eq!(diff.after, &after); ```` #### Map diffs For [`BTreeMap`] and [`HashMap`], daft has corresponding [`BTreeMapDiff`](https://docs.rs/daft/0.1.5/daft/alloc_impls/struct.BTreeMapDiff.html) and [`HashMapDiff`](https://docs.rs/daft/0.1.5/daft/std_impls/struct.HashMapDiff.html) types. These types have fields for *common*, *added*, and *removed* entries. Map diffs are performed eagerly for keys, but values are stored as leaf nodes. ##### Example ````rust use daft::{Diffable, Leaf, BTreeMapDiff}; use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, "one"); a.insert(2, "two"); a.insert(3, "three"); let mut b = BTreeMap::new(); b.insert(2, "two"); b.insert(3, "THREE"); b.insert(4, "four"); let diff: BTreeMapDiff<'_, i32, &str> = a.diff(&b); // Added and removed entries are stored as maps: assert_eq!(diff.added, [(&4, &"four")].into_iter().collect()); assert_eq!(diff.removed, [(&1, &"one")].into_iter().collect()); // Common entries are stored as leaf nodes. assert_eq!( diff.common, [ (&2, Leaf { before: &"two", after: &"two" }), (&3, Leaf { before: &"three", after: &"THREE" }) ] .into_iter().collect(), ); // If `V` implements `Eq`, unchanged and modified iterators become // available. `unchanged` and `modified` return key-value pairs; // `unchanged_keys` and `modified_keys` return keys; and // `unchanged_values` and `modified_values` return values. // // Here's `unchanged_keys` to get the keys of unchanged entries: assert_eq!(diff.unchanged_keys().collect::>(), [&2]); // `modified_values` returns leaf nodes for modified entries. assert_eq!( diff.modified_values().collect::>(), [Leaf { before: &"three", after: &"THREE" }], ); ```` #### Set diffs For [`BTreeSet`] and [`HashSet`], daft has corresponding [`BTreeSetDiff`](https://docs.rs/daft/0.1.5/daft/alloc_impls/struct.BTreeSetDiff.html) and [`HashSetDiff`](https://docs.rs/daft/0.1.5/daft/std_impls/struct.HashSetDiff.html) types. These types have fields for *common*, *added*, and *removed* entries. Set diffs are performed eagerly. ##### Example ````rust use daft::{Diffable, Leaf, BTreeSetDiff}; use std::collections::BTreeSet; let a: BTreeSet = [0, 1, 2, 3, 4, 5].into_iter().collect(); let b: BTreeSet = [3, 4, 5, 6, 7, 8].into_iter().collect(); let diff: BTreeSetDiff<'_, i32> = a.diff(&b); assert_eq!(diff.common, [&3, &4, &5].into_iter().collect()); assert_eq!(diff.added, [&6, &7, &8].into_iter().collect()); assert_eq!(diff.removed, [&0, &1, &2].into_iter().collect()); ```` #### Tuple diffs For a tuple like `(A, B, C)`, the [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) implementation is recursive: the diff resolves to `(A::Diff, B::Diff, C::Diff)`. ##### Example ````rust use daft::{BTreeSetDiff, Diffable, Leaf}; use std::collections::BTreeSet; let before: (usize, String, BTreeSet) = (1, "hello".to_owned(), [1, 2, 3].into_iter().collect()); let after = (2, "world".to_owned(), [2, 3, 4].into_iter().collect()); let diff = before.diff(&after); assert_eq!( diff, ( Leaf { before: &1, after: &2 }, Leaf { before: "hello", after: "world" }, BTreeSetDiff { common: [&2, &3].into_iter().collect(), added: [&4].into_iter().collect(), removed: [&1].into_iter().collect(), } ), ); ```` #### Struct diffs For structs, the [`Diffable`](https://docs.rs/daft-derive/0.1.5/daft_derive/derive.Diffable.html) derive macro generates a diff type with a field corresponding to each field type. Each field must implement [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html). A struct `Foo` gets a corresponding `FooDiff` struct, which has fields corresponding to each field in `Foo`. ##### Struct options * `#[daft(leaf)]`: if a **struct** is annotated with this, the [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) implementation for the struct will be a [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) instead of a recursive diff. ##### Field options * `#[daft(leaf)]`: if a **struct field** is annotated with this, the generated struct’s corresponding field will be a [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html), regardless of the field’s `Diff` type (or even whether it implements [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) at all). * `#[daft(ignore)]`: the generated struct’s corresponding field is not included in the diff. ##### Example For an example of structs with named fields, see [*Usage*](#usage) above. Tuple-like structs produce tuple-like diff structs: ````rust use daft::Diffable; use std::collections::BTreeMap; #[derive(Diffable)] struct MyTuple(BTreeMap, i32); let before = MyTuple(BTreeMap::new(), 1); let after = MyTuple([(1, "hello")].into_iter().collect(), 2); let diff = before.diff(&after); // The generated type is MyTupleDiff(BTreeMapDiff, Leaf). assert_eq!(**diff.0.added.get(&1).unwrap(), "hello"); assert_eq!(*diff.1.before, 1); assert_eq!(*diff.1.after, 2); ```` An example with `#[daft(leaf)]` on **structs**: ````rust use daft::{Diffable, Leaf}; #[derive(Diffable)] #[daft(leaf)] struct MyStruct { a: i32, } let before = MyStruct { a: 1 }; let after = MyStruct { a: 2 }; let diff: Leaf<&MyStruct> = before.diff(&after); assert_eq!(diff.before.a, 1); assert_eq!(diff.after.a, 2); ```` An example with `#[daft(leaf)]` on **struct fields**: ````rust use daft::{Diffable, Leaf}; // A simple struct that implements Diffable. #[derive(Debug, PartialEq, Eq, Diffable)] struct InnerStruct { text: &'static str, } // A struct that does not implement Diffable. #[derive(Debug, PartialEq, Eq)] struct PlainStruct(usize); #[derive(Diffable)] struct OuterStruct { // Ordinarily, InnerStruct would be diffed recursively, but // with #[daft(leaf)], it is treated as a leaf node. #[daft(leaf)] inner: InnerStruct, // PlainStruct does not implement Diffable, but using // daft(leaf) allows it to be diffed anyway. #[daft(leaf)] plain: PlainStruct, } let before = OuterStruct { inner: InnerStruct { text: "hello" }, plain: PlainStruct(1) }; let after = OuterStruct { inner: InnerStruct { text: "world" }, plain: PlainStruct(2) }; let diff = before.diff(&after); // `OuterStructDiff` does *not* recursively diff `InnerStruct`, but instead // returns a leaf node. assert_eq!( diff.inner, Leaf { before: &InnerStruct { text: "hello" }, after: &InnerStruct { text: "world" } }, ); // But you can continue the recursion anyway, since `InnerStruct` implements // `Diffable`: let inner_diff = diff.inner.diff_pair(); assert_eq!( inner_diff, InnerStructDiff { text: Leaf { before: "hello", after: "world" } }, ); // `PlainStruct` can also be compared even though it doesn't implement `Diffable`. assert_eq!(diff.plain, Leaf { before: &PlainStruct(1), after: &PlainStruct(2) }); ```` #### Custom diff types The [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) trait can also be implemented manually for custom behavior. In general, most custom implementations will likely use one of the built-in diff types directly. #### Example Some structs like identifiers should be treated as leaf nodes. This can be implemented via `#[daft(leaf)]`, but also manually: ````rust use daft::{Diffable, Leaf}; struct Identifier(String); impl Diffable for Identifier { type Diff<'daft> = Leaf<&'daft Self>; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { Leaf { before: self, after: other, } } } ```` ### Type and lifetime parameters If a type parameter is specified, the [`Diffable`](https://docs.rs/daft-derive/0.1.5/daft_derive/derive.Diffable.html) derive macro for structs normally requires that the type parameter implement `Diffable`. This is not required if the field is annotated with `#[daft(leaf)]`. Daft fully supports types with arbitrary lifetimes. Automatically generated diff structs will have an additional `'daft` lifetime parameter at the beginning, with the requirement that all other lifetime and type parameters outlive it. #### Example ````rust use daft::Diffable; #[derive(Diffable)] struct BorrowedData<'a, 'b, T: Diffable + ?Sized> { a: &'a str, b: &'b T, // TODO: example with daft(leaf) } // This generates a struct that looks like: #[automatically_derived] struct BorrowedDataDiff<'daft, 'a: 'daft, 'b: 'daft, T: ?Sized + 'daft> { a: Leaf<'daft, &'a str>, b: T::Diff<'daft>, } ```` ## Optional features * `derive`: Enable the `Diffable` derive macro: **disabled** by default. Implementations for standard library types, all **enabled** by default: * `alloc`: Enable diffing for types from the [`alloc`](https://doc.rust-lang.org/nightly/alloc/index.html) crate. * `std`: Enable diffing for types from the [`std`](https://doc.rust-lang.org/nightly/std/index.html) crate. (With `default-features = false`, daft is no-std compatible.) Implementations for third-party types, all **disabled** by default: * `uuid1`: Enable diffing for [`uuid::Uuid`](https://docs.rs/uuid/1.12.1/uuid/struct.Uuid.html). * `oxnet01`: Enable diffing for network types from the [`oxnet`](https://docs.rs/oxnet/0.1.0/oxnet/index.html) crate. * `newtype-uuid1`: Enable diffing for [`newtype_uuid::TypedUuid`](https://docs.rs/newtype-uuid/1.2.1/newtype_uuid/struct.TypedUuid.html). ## Minimum supported Rust version (MSRV) The minimum supported Rust version is **1.81.0**. At any time, at least the last three stable versions of Rust are supported. While this crate is a pre-release (0.x.x) it may have its MSRV bumped in a patch release. Once this crate has reached 1.x, any MSRV bump will be accompanied with a new minor version. ## Related work [Diffus](https://crates.io/crates/diffus) is the original inspiration for this crate and a great alternative. Daft diverges from diffus in a few ways: * Daft’s derive macro does not attempt to diff enums with different variants. In practice, we’ve found that diffing enums across different variants is less useful than it first appears. * Daft has the notion of a [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html) type, which represents an atomic unit. (For example, the [`Diffable`](https://docs.rs/daft/0.1.5/daft/diffable/trait.Diffable.html) implementation for `i32` is a [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html).) [`Leaf`](https://docs.rs/daft/0.1.5/daft/leaf/struct.Leaf.html)s are also used for enums, as well as in any other place where lazy diffing is desired. * Diffus has a `Same` trait, which is like `Eq` except it’s also implemented for floats. Daft doesn’t have the `Same` trait, and its core functionality forgoes the need for `Eq` entirely. For a primitive scalar like `f64`, you’ll get a `Leaf` struct which you can compare with whatever notion of equality you want. * Daft uses a [generic associated type (GAT)][GAT] so that the `Diffable` trait no longer needs a lifetime parameter. This leads to simpler usage. (Diffus was written before GATs were available in stable Rust.) * Daft uses fewer types in general. For example, diffus wraps its return values in an outer `Edit` type, but daft does not. * Daft is no-std-compatible, while diffus requires std. [`BTreeMap`]: https://doc.rust-lang.org/nightly/alloc/collections/btree/map/struct.BTreeMap.html [`HashMap`]: https://doc.rust-lang.org/nightly/std/collections/hash/map/struct.HashMap.html [`BTreeSet`]: https://doc.rust-lang.org/nightly/alloc/collections/btree/set/struct.BTreeSet.html [`HashSet`]: https://doc.rust-lang.org/nightly/std/collections/hash/set/struct.HashSet.html [GAT]: https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html ## License This project is available under the terms of either the [Apache 2.0 license](LICENSE-APACHE) or the [MIT license](LICENSE-MIT). daft-0.1.5/src/alloc_impls.rs000064400000000000000000000152621046102023000142060ustar 00000000000000//! Implementations for types from the `alloc` crate. use crate::{Diffable, Leaf}; use alloc::{ borrow::{Cow, ToOwned}, boxed::Box, collections::{BTreeMap, BTreeSet}, rc::Rc, string::String, sync::Arc, vec::Vec, }; leaf_deref! { String => str } impl Diffable for Box { type Diff<'daft> = ::Diff<'daft> where T: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { (**self).diff(other) } } impl Diffable for Cow<'_, T> { type Diff<'daft> = ::Diff<'daft> where Self: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { self.as_ref().diff(other.as_ref()) } } impl Diffable for Arc { type Diff<'daft> = ::Diff<'daft> where T: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { (**self).diff(other) } } impl Diffable for Rc { type Diff<'daft> = ::Diff<'daft> where T: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { (**self).diff(other) } } map_diff!( /// A diff of two [`BTreeMap`] instances. /// /// The diff contains three elements: /// /// - `common`: Entries that are present in both maps, with their values /// stored as a [`Leaf`]. /// - `added`: Entries present in `after`, but not in `before`. /// - `removed`: Entries present in `before`, but not in `after`. /// /// If `V` implements `Eq`, `common` can be split into /// [`unchanged`][Self::unchanged] and [`modified`][Self::modified] entries. /// Additionally, if `V` implements [`Diffable`], /// [`modified_diff`][Self::modified_diff] can be used to recursively diff /// modified entries. /// /// # Example /// /// ``` /// # #[cfg(feature = "std")] { /// use daft::{BTreeMapDiff, Diffable, Leaf}; /// use std::collections::BTreeMap; /// /// let a: BTreeMap = /// [(0, "lorem"), (1, "ipsum"), (2, "dolor")].into_iter().collect(); /// let b: BTreeMap = /// [(1, "ipsum"), (2, "sit"), (3, "amet")].into_iter().collect(); /// /// let changes = a.diff(&b); /// let expected = BTreeMapDiff { /// // Keys are stored by reference and matched by equality. /// common: [ /// (&1, Leaf { before: &"ipsum", after: &"ipsum" }), /// (&2, Leaf { before: &"dolor", after: &"sit" }), /// ].into_iter().collect(), /// added: [(&3, &"amet")].into_iter().collect(), /// removed: [(&0, &"lorem")].into_iter().collect(), /// }; /// /// assert_eq!(changes, expected); /// /// // If the values are `Eq`, it's also possible to get lists of /// // modified and unchanged entries. /// assert!(changes.is_unchanged(&1)); /// assert!(changes.is_modified(&2)); /// let unchanged = changes.unchanged().collect::>(); /// let modified = changes.modified().collect::>(); /// /// assert_eq!(unchanged, [(&1, &"ipsum")]); /// assert_eq!(modified, [(&2, Leaf { before: &"dolor", after: &"sit" })]); /// # } /// ``` BTreeMap, Ord ); set_diff!( /// A diff of two [`BTreeSet`] instances. /// /// The diff contains three elements: /// /// - `common`: Entries that are present in both sets. /// - `added`: Entries present in `after`, but not in `before`. /// - `removed`: Entries present in `before`, but not in `after`. /// /// # Example /// /// ``` /// # #[cfg(feature = "std")] { /// use daft::{BTreeSetDiff, Diffable}; /// use std::collections::BTreeSet; /// /// let a: BTreeSet = [0, 1].into_iter().collect(); /// let b: BTreeSet = [1, 2].into_iter().collect(); /// /// let changes = a.diff(&b); /// let expected = BTreeSetDiff { /// // Entries are stored by reference and matched by equality. /// common: [&1].into_iter().collect(), /// added: [&2].into_iter().collect(), /// removed: [&0].into_iter().collect(), /// }; /// /// assert_eq!(changes, expected); /// # } /// ``` BTreeSet, Ord ); /// Treat Vecs as Leafs // // We plan to add opt in diff functionality: set-like, reordered, etc... impl Diffable for Vec { type Diff<'daft> = Leaf<&'daft [T]> where T: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { Leaf { before: self, after: other } } } #[cfg(test)] mod tests { use super::*; #[test] fn btree_set_diff() { let a: BTreeSet<_> = [0, 1, 2, 3, 4, 5].into_iter().collect(); let b: BTreeSet<_> = [3, 4, 5, 6, 7, 8].into_iter().collect(); let changes = a.diff(&b); let expected = BTreeSetDiff { added: [&6, &7, &8].into_iter().collect(), removed: [&0, &1, &2].into_iter().collect(), common: [&3, &4, &5].into_iter().collect(), }; assert_eq!(expected, changes); } #[test] fn btree_map_diff() { let a: BTreeMap<_, _> = [(0, 1), (1, 1), (2, 1)].into_iter().collect(); let b: BTreeMap<_, _> = [(0, 2), (2, 1), (3, 1)].into_iter().collect(); let changes = a.diff(&b); let expected = BTreeMapDiff { common: [ (&0, Leaf { before: &1, after: &2 }), (&2, Leaf { before: &1, after: &1 }), ] .into_iter() .collect(), added: [(&3, &1)].into_iter().collect(), removed: [(&1, &1)].into_iter().collect(), }; assert_eq!(changes, expected); // Ensure that keys don't need to be Diffable, and values don't need to // be Eq or Diffable. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct K(i32); #[derive(Debug)] #[expect(dead_code)] struct V(f64); let floats_a: BTreeMap = [(K(0), V(1.0)), (K(1), V(1.0)), (K(2), V(1.0))] .into_iter() .collect(); let floats_b: BTreeMap = [(K(0), V(2.0)), (K(2), V(1.0)), (K(3), V(1.0))] .into_iter() .collect(); let diff = floats_a.diff(&floats_b); assert_eq!(diff.added.keys().copied().collect::>(), [&K(3)]); assert_eq!(diff.removed.keys().copied().collect::>(), [&K(1)]); assert_eq!( diff.common.keys().copied().collect::>(), [&K(0), &K(2)] ); } } daft-0.1.5/src/core_impls.rs000064400000000000000000000107271046102023000140450ustar 00000000000000//! Implementations for core types. use crate::{Diffable, Leaf}; use core::{ cell::RefCell, marker::PhantomData, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}, num::{ NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, }, }; leaf! { i64, i32, i16, i8, u64, u32, u16, u8, char, bool, isize, usize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroUsize, () } leaf! { IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6 } leaf! { str } impl Diffable for Option { type Diff<'daft> = Leaf> where T: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { Leaf { before: self.as_ref(), after: other.as_ref() } } } impl Diffable for Result { type Diff<'daft> = Leaf> where T: 'daft, U: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { Leaf { before: self.as_ref(), after: other.as_ref() } } } impl<'a, T: Diffable + ?Sized> Diffable for &'a T { // It would be nice to extend the lifetime of the diff to `'a` (e.g. diffing // &'static str`s results in a Leaf<&'static str>), and it does actually // work for that simpler case, but rustc (1.84.1) complains about cases with // multiple references like &'a &'b T (see complex-lifetimes.rs for an // example). This is probably a bug in rustc: see // https://gist.github.com/sunshowers/25fcc2f590f1c6b19daa99e11e927dc7 for // the error with Rust 1.84.1. type Diff<'daft> = ::Diff<'daft> where 'a: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { (**self).diff(other) } } // Can't express lifetimes due to `RefCell`'s limited borrows, so we must return // a leaf node that can be recursively diffed. impl Diffable for RefCell { type Diff<'daft> = Leaf<&'daft Self> where T: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { Leaf { before: self, after: other } } } impl Diffable for PhantomData { type Diff<'daft> = Leaf<&'daft PhantomData> where Self: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { Leaf { before: self, after: other } } } /// Treat slices as leaf nodes. impl Diffable for [T] { type Diff<'daft> = Leaf<&'daft [T]> where T: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { Leaf { before: self, after: other } } } macro_rules! tuple_diffable { ($(($($name:ident $ix:tt),+)),+) => { $( impl<$($name: Diffable),+> Diffable for ($($name,)+) { type Diff<'daft> = ($($name::Diff<'daft>,)+) where $($name: 'daft,)+; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { ($(self.$ix.diff(&other.$ix),)+) } } )+ } } tuple_diffable! { (A 0), (A 0, B 1), (A 0, B 1, C 2), (A 0, B 1, C 2, D 3), (A 0, B 1, C 2, D 3, E 4), (A 0, B 1, C 2, D 3, E 4, F 5), (A 0, B 1, C 2, D 3, E 4, F 5, G 6), (A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7), (A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7, I 8), (A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7, I 8, J 9) } #[cfg(test)] mod tests { use super::*; #[test] fn reference_diffable() { // Test that a reference to a diffable type can be diffed. let before = &&&&&&"hello"; let after = &&&&&&"world"; // This should automatically dereference the references. let diff: Leaf<&str> = before.diff(after); assert_eq!(diff.before, ******before); assert_eq!(diff.after, ******after); } #[test] fn tuple_diffable() { let before = (1usize, 2usize, 3usize); let after = (4, 5, 6); let diff = before.diff(&after); assert_eq!( diff, ( Leaf { before: &1, after: &4 }, Leaf { before: &2, after: &5 }, Leaf { before: &3, after: &6 }, ) ); } } daft-0.1.5/src/diffable.rs000064400000000000000000000012211046102023000134320ustar 00000000000000/// Represents a type which can be diffed. /// /// For more information, see the [crate-level documentation](crate). pub trait Diffable { /// The type of the diff. /// /// This is a [generic associated type][GAT], also known as a GAT. The /// `'daft` lifetime is used in the `diff` method to ensure that the /// returned diff is valid for the lifetime of the input values. /// /// [GAT]: https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html type Diff<'daft> where Self: 'daft; /// Compute the diff between two values. fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft>; } daft-0.1.5/src/leaf.rs000064400000000000000000000136631046102023000126220ustar 00000000000000use crate::Diffable; use core::ops::{Deref, DerefMut}; /// A primitive or atomic change. /// /// `T` is normally a reference of some kind, but it can be any type. /// /// For more information, see the [crate-level documentation](crate). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Leaf { /// The value on the before side. pub before: T, /// The value on the after side. pub after: T, } impl Leaf { /// Convert from `&Leaf` to `Leaf<&T>`. #[inline] pub fn as_ref(&self) -> Leaf<&T> { Leaf { before: &self.before, after: &self.after } } /// Convert from `&mut Leaf` to `Leaf<&mut T>`. #[inline] pub fn as_mut(&mut self) -> Leaf<&mut T> { Leaf { before: &mut self.before, after: &mut self.after } } /// Convert from `Leaf` or `&Leaf` to `Leaf<&T::Target>`. /// /// # Example /// /// ``` /// # #[cfg(feature = "std")] { /// use daft::Leaf; /// /// let x: Leaf = Leaf { before: "hello".to_owned(), after: "world".to_owned() }; /// assert_eq!(x.as_deref(), Leaf { before: "hello", after: "world" }); /// # } /// ``` #[inline] pub fn as_deref(&self) -> Leaf<&T::Target> where T: Deref, { Leaf { before: &*self.before, after: &*self.after } } /// Convert from `Leaf` or `&mut Leaf` to `Leaf<&mut T::Target>`. /// /// # Example /// /// ``` /// # #[cfg(feature = "std")] { /// use daft::Leaf; /// /// let mut x: Leaf = Leaf { before: "hello".to_owned(), after: "world".to_owned() }; /// assert_eq!( /// x.as_deref_mut().map(|x| { /// x.make_ascii_uppercase(); /// x /// }), /// Leaf { before: "HELLO".to_owned().as_mut_str(), after: "WORLD".to_owned().as_mut_str() }, /// ); /// # } /// ``` #[inline] pub fn as_deref_mut(&mut self) -> Leaf<&mut T::Target> where T: DerefMut, { Leaf { before: &mut *self.before, after: &mut *self.after } } /// Map a `Leaf` to a `Leaf` by applying a function to the `before` /// and `after` values. /// /// `f` will be called twice: first with `before`, then with `after`. /// /// # Example /// /// A `Leaf<&str>` can be converted to a `Leaf` by calling `map` /// with `String::from`: /// /// ``` /// # #[cfg(feature = "std")] { /// use daft::{Diffable, Leaf}; /// /// let before = "hello"; /// let after = "world"; /// /// let leaf: Leaf<&str> = Leaf { before, after }; /// let leaf: Leaf = leaf.map(String::from); /// # } /// ``` #[inline] pub fn map(self, mut f: F) -> Leaf where F: FnMut(T) -> U, { Leaf { before: f(self.before), after: f(self.after) } } /// Return true if before is the same as after. /// /// This is the same as `self.before == self.after`, but is easier to use in /// a chained series of method calls. /// /// # Example /// /// ``` /// use daft::{Diffable, Leaf}; /// /// let before = "hello"; /// let after = "hello"; /// /// let leaf: Leaf<&str> = Leaf { before, after }; /// assert!(leaf.is_unchanged()); /// /// let before = "hello"; /// let after = "world"; /// /// let leaf: Leaf<&str> = Leaf { before, after }; /// assert!(!leaf.is_unchanged()); /// ``` #[inline] pub fn is_unchanged(&self) -> bool where T: Eq, { self.before == self.after } /// Return true if before is different from after. /// /// This is the same as `self.before != self.after`, but is easier to use in /// a chained series of method calls. /// /// # Example /// /// ``` /// use daft::{Diffable, Leaf}; /// /// let before = "hello"; /// let after = "hello"; /// /// let leaf: Leaf<&str> = Leaf { before, after }; /// assert!(!leaf.is_modified()); /// /// let before = "hello"; /// let after = "world"; /// /// let leaf: Leaf<&str> = Leaf { before, after }; /// assert!(leaf.is_modified()); /// ``` #[inline] pub fn is_modified(&self) -> bool where T: Eq, { self.before != self.after } } impl<'daft, T: ?Sized + Diffable> Leaf<&'daft T> { /// Perform a diff on [`before`][Self::before] and [`after`][Self::after], /// returning `T::Diff`. /// /// This is useful when `T::Diff` is not a leaf node. #[inline] pub fn diff_pair(self) -> T::Diff<'daft> { self.before.diff(self.after) } } impl Leaf<&T> { /// Create a clone of the leaf with owned values. /// /// # Example /// /// ``` /// # #[cfg(feature = "std")] { /// use daft::{Diffable, Leaf}; /// /// let before = String::from("hello"); /// let after = String::from("world"); /// /// let leaf: Leaf<&String> = Leaf { before: &before, after: &after }; /// // cloned turns a Leaf<&String> into a Leaf. /// let leaf: Leaf = leaf.cloned(); /// assert_eq!(leaf.before, "hello"); /// assert_eq!(leaf.after, "world"); /// # } /// ``` #[inline] pub fn cloned(self) -> Leaf where T: Clone, { Leaf { before: self.before.clone(), after: self.after.clone() } } /// Create a copy of the leaf with owned values. /// /// # Example /// /// ``` /// use daft::{Diffable, Leaf}; /// /// let before = "hello"; /// let after = "world"; /// /// let leaf: Leaf<&&str> = Leaf { before: &before, after: &after }; /// // copied turns a Leaf<&&str> into a Leaf<&str>. /// let leaf: Leaf<&str> = leaf.copied(); /// assert_eq!(leaf.before, "hello"); /// assert_eq!(leaf.after, "world"); /// ``` #[inline] pub fn copied(self) -> Leaf where T: Copy, { Leaf { before: *self.before, after: *self.after } } } daft-0.1.5/src/lib.rs000064400000000000000000000402771046102023000124620ustar 00000000000000#![cfg_attr(doc_cfg, feature(doc_cfg))] #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] //! Daft is a library to perform semantic diffs of Rust data structures. //! //! Daft consists of a trait called [`Diffable`], along with [a derive //! macro][macro@Diffable] by the same name. This trait represents the //! notion of a type for which two members can be simultaneously compared. //! //! # Features //! //! - **Recursive diffing** of structs, sets, and maps //! - **Derive macro** for automatically generating diff types //! - Choose between **eager** and **lazy** diffing //! - **No-std compatible**, both with and without `alloc` //! //! # Usage //! //! ```rust //! # #[cfg(all(feature = "std", feature = "derive"))] { //! use daft::{Diffable, Leaf}; //! //! // Annotate your struct with `#[derive(Diffable)]`: //! #[derive(Diffable)] //! struct MyStruct { //! a: i32, //! b: String, //! } //! //! // This generates a type called MyStructDiff, which looks like: //! # /* //! #[automatically_derived] //! struct MyStructDiff<'daft> { //! a: Leaf<&'daft i32>, //! b: Leaf<&'daft str>, //! } //! # */ //! //! // Then, with two instances of MyStruct: //! let before = MyStruct { a: 1, b: "hello".to_owned() }; //! let after = MyStruct { a: 2, b: "world".to_owned() }; //! //! // You can diff them like so: //! let diff = before.diff(&after); //! //! // And compare the results: //! assert_eq!(*diff.a.before, 1); //! assert_eq!(*diff.a.after, 2); //! assert_eq!(diff.b.before, "hello"); //! assert_eq!(diff.b.after, "world"); //! # } //! ``` //! //! This crate assigns one side the name *before*, and the other side *after*. //! These labels are arbitrary: if *before* and *after* are swapped, the diff is //! reversed. //! //! ## Diff types //! //! Currently, daft comes with a few kinds of diff types: //! //! ### [`Leaf`] instances //! //! A [`Leaf`] represents a logical *leaf node* or *base case* in a diff, i.e. a //! point at which diffing stops. [`Leaf`] instances are used for: //! //! * *Scalar* or *primitive types* like `i32`, `String`, `bool`, etc. //! * *Enums*, since diffing across variants is usually not meaningful. //! * Vector and slice types, since there are several reasonable ways to diff //! vectors (e.g. set-like, ordered, etc.) and we don't want to make assumptions. //! * As an opt-in mechanism for struct fields: see //! [*Recursive diffs*](#recursive-diffs) below for more. //! //! #### Example //! //! A contrived example for integers: //! //! ```rust //! use daft::{Diffable, Leaf}; //! //! let diff: Leaf<&i32> = 1_i32.diff(&2); //! assert_eq!(*diff.before, 1); //! assert_eq!(*diff.after, 2); //! ``` //! //! Enums also use `Leaf`: //! //! ```rust //! use daft::{Diffable, Leaf}; //! //! // Option uses Leaf: //! let diff: Leaf> = Some(1_i32).diff(&Some(2)); //! assert_eq!(diff.before, Some(&1)); //! assert_eq!(diff.after, Some(&2)); //! //! # #[cfg(feature = "derive")] { //! // Automatically derived enums also use Leaf: //! #[derive(Debug, PartialEq, Eq, Diffable)] //! enum MyEnum { //! A(i32), //! B(String), //! } //! //! let before = MyEnum::A(1); //! let after = MyEnum::B("hello".to_string()); //! //! let diff: Leaf<&MyEnum> = before.diff(&after); //! assert_eq!(diff.before, &before); //! assert_eq!(diff.after, &after); //! # } //! ``` //! //! Vectors use `Leaf` as well: //! //! ```rust //! # #[cfg(feature = "std")] { //! use daft::{Diffable, Leaf}; //! //! let before = vec![1, 2, 3]; //! let after = vec![4, 5, 6]; //! let diff: Leaf<&[i32]> = before.diff(&after); //! assert_eq!(diff.before, &before); //! assert_eq!(diff.after, &after); //! # } //! ``` //! //! ### Map diffs //! //! For [`BTreeMap`] and [`HashMap`], daft has corresponding [`BTreeMapDiff`] //! and [`HashMapDiff`] types. These types have fields for *common*, *added*, //! and *removed* entries. //! //! Map diffs are performed eagerly for keys, but values are stored as leaf //! nodes. //! //! #### Example //! //! ```rust //! # #[cfg(feature = "std")] { //! use daft::{Diffable, Leaf, BTreeMapDiff}; //! use std::collections::BTreeMap; //! //! let mut a = BTreeMap::new(); //! a.insert(1, "one"); //! a.insert(2, "two"); //! a.insert(3, "three"); //! //! let mut b = BTreeMap::new(); //! b.insert(2, "two"); //! b.insert(3, "THREE"); //! b.insert(4, "four"); //! //! let diff: BTreeMapDiff<'_, i32, &str> = a.diff(&b); //! //! // Added and removed entries are stored as maps: //! assert_eq!(diff.added, [(&4, &"four")].into_iter().collect()); //! assert_eq!(diff.removed, [(&1, &"one")].into_iter().collect()); //! //! // Common entries are stored as leaf nodes. //! assert_eq!( //! diff.common, //! [ //! (&2, Leaf { before: &"two", after: &"two" }), //! (&3, Leaf { before: &"three", after: &"THREE" }) //! ] //! .into_iter().collect(), //! ); //! //! // If `V` implements `Eq`, unchanged and modified iterators become //! // available. `unchanged` and `modified` return key-value pairs; //! // `unchanged_keys` and `modified_keys` return keys; and //! // `unchanged_values` and `modified_values` return values. //! // //! // Here's `unchanged_keys` to get the keys of unchanged entries: //! assert_eq!(diff.unchanged_keys().collect::>(), [&2]); //! //! // `modified_values` returns leaf nodes for modified entries. //! assert_eq!( //! diff.modified_values().collect::>(), //! [Leaf { before: &"three", after: &"THREE" }], //! ); //! # } //! ``` //! //! ### Set diffs //! //! For [`BTreeSet`] and [`HashSet`], daft has corresponding [`BTreeSetDiff`] //! and [`HashSetDiff`] types. These types have fields for *common*, *added*, //! and *removed* entries. //! //! Set diffs are performed eagerly. //! //! #### Example //! //! ```rust //! # #[cfg(feature = "std")] { //! use daft::{Diffable, Leaf, BTreeSetDiff}; //! use std::collections::BTreeSet; //! //! let a: BTreeSet = [0, 1, 2, 3, 4, 5].into_iter().collect(); //! let b: BTreeSet = [3, 4, 5, 6, 7, 8].into_iter().collect(); //! let diff: BTreeSetDiff<'_, i32> = a.diff(&b); //! //! assert_eq!(diff.common, [&3, &4, &5].into_iter().collect()); //! assert_eq!(diff.added, [&6, &7, &8].into_iter().collect()); //! assert_eq!(diff.removed, [&0, &1, &2].into_iter().collect()); //! # } //! ``` //! //! ### Tuple diffs //! //! For a tuple like `(A, B, C)`, the [`Diffable`] implementation is recursive: //! the diff resolves to `(A::Diff, B::Diff, C::Diff)`. //! //! #### Example //! //! ```rust //! # #[cfg(feature = "std")] { //! use daft::{BTreeSetDiff, Diffable, Leaf}; //! use std::collections::BTreeSet; //! //! let before: (usize, String, BTreeSet) = (1, "hello".to_owned(), [1, 2, 3].into_iter().collect()); //! let after = (2, "world".to_owned(), [2, 3, 4].into_iter().collect()); //! //! let diff = before.diff(&after); //! assert_eq!( //! diff, //! ( //! Leaf { before: &1, after: &2 }, //! Leaf { before: "hello", after: "world" }, //! BTreeSetDiff { //! common: [&2, &3].into_iter().collect(), //! added: [&4].into_iter().collect(), //! removed: [&1].into_iter().collect(), //! } //! ), //! ); //! # } //! ``` //! //! ### Struct diffs //! //! For structs, the [`Diffable`][macro@Diffable] derive macro generates //! a diff type with a field corresponding to each field type. Each field must //! implement [`Diffable`]. //! //! A struct `Foo` gets a corresponding `FooDiff` struct, which has fields //! corresponding to each field in `Foo`. //! //! #### Struct options //! //! * `#[daft(leaf)]`: if a **struct** is annotated with this, the [`Diffable`] //! implementation for the struct will be a [`Leaf`] instead of a recursive //! diff. //! //! #### Field options //! //! * `#[daft(leaf)]`: if a **struct field** is annotated with this, the generated //! struct's corresponding field will be a [`Leaf`], regardless of the field's //! `Diff` type (or even whether it implements [`Diffable`] at all). //! * `#[daft(ignore)]`: the generated struct's corresponding field is not included //! in the diff. //! //! #### Example //! //! For an example of structs with named fields, see [*Usage*](#usage) above. //! //! Tuple-like structs produce tuple-like diff structs: //! //! ```rust //! # #[cfg(all(feature = "std", feature = "derive"))] { //! use daft::Diffable; //! use std::collections::BTreeMap; //! //! #[derive(Diffable)] //! struct MyTuple(BTreeMap, i32); //! //! let before = MyTuple(BTreeMap::new(), 1); //! let after = MyTuple([(1, "hello")].into_iter().collect(), 2); //! let diff = before.diff(&after); //! //! // The generated type is MyTupleDiff(BTreeMapDiff, Leaf). //! assert_eq!(**diff.0.added.get(&1).unwrap(), "hello"); //! assert_eq!(*diff.1.before, 1); //! assert_eq!(*diff.1.after, 2); //! # } //! ``` //! //! An example with `#[daft(leaf)]` on **structs**: //! //! ```rust //! # #[cfg(feature = "derive")] { //! use daft::{Diffable, Leaf}; //! //! #[derive(Diffable)] //! #[daft(leaf)] //! struct MyStruct { //! a: i32, //! } //! //! let before = MyStruct { a: 1 }; //! let after = MyStruct { a: 2 }; //! let diff: Leaf<&MyStruct> = before.diff(&after); //! //! assert_eq!(diff.before.a, 1); //! assert_eq!(diff.after.a, 2); //! # } //! ``` //! //! An example with `#[daft(leaf)]` on **struct fields**: //! //! ```rust //! # #[cfg(feature = "derive")] { //! use daft::{Diffable, Leaf}; //! //! // A simple struct that implements Diffable. //! #[derive(Debug, PartialEq, Eq, Diffable)] //! struct InnerStruct { //! text: &'static str, //! } //! //! // A struct that does not implement Diffable. //! #[derive(Debug, PartialEq, Eq)] //! struct PlainStruct(usize); //! //! #[derive(Diffable)] //! struct OuterStruct { //! // Ordinarily, InnerStruct would be diffed recursively, but //! // with #[daft(leaf)], it is treated as a leaf node. //! #[daft(leaf)] //! inner: InnerStruct, //! //! // PlainStruct does not implement Diffable, but using //! // daft(leaf) allows it to be diffed anyway. //! #[daft(leaf)] //! plain: PlainStruct, //! } //! //! let before = OuterStruct { inner: InnerStruct { text: "hello" }, plain: PlainStruct(1) }; //! let after = OuterStruct { inner: InnerStruct { text: "world" }, plain: PlainStruct(2) }; //! let diff = before.diff(&after); //! //! // `OuterStructDiff` does *not* recursively diff `InnerStruct`, but instead //! // returns a leaf node. //! assert_eq!( //! diff.inner, //! Leaf { before: &InnerStruct { text: "hello" }, after: &InnerStruct { text: "world" } }, //! ); //! //! // But you can continue the recursion anyway, since `InnerStruct` implements //! // `Diffable`: //! let inner_diff = diff.inner.diff_pair(); //! assert_eq!( //! inner_diff, //! InnerStructDiff { text: Leaf { before: "hello", after: "world" } }, //! ); //! //! // `PlainStruct` can also be compared even though it doesn't implement `Diffable`. //! assert_eq!(diff.plain, Leaf { before: &PlainStruct(1), after: &PlainStruct(2) }); //! # } //! ``` //! //! ### Custom diff types //! //! The [`Diffable`] trait can also be implemented manually for custom behavior. //! //! In general, most custom implementations will likely use one of the built-in //! diff types directly. //! //! ### Example //! //! Some structs like identifiers should be treated as leaf nodes. This can be //! implemented via `#[daft(leaf)]`, but also manually: //! //! ```rust //! # #[cfg(feature = "std")] { //! use daft::{Diffable, Leaf}; //! //! struct Identifier(String); //! //! impl Diffable for Identifier { //! type Diff<'daft> = Leaf<&'daft Self>; //! //! fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { //! Leaf { //! before: self, //! after: other, //! } //! } //! } //! # } //! ``` //! //! ## Type and lifetime parameters //! //! If a type parameter is specified, the [`Diffable`][macro@Diffable] derive //! macro for structs normally requires that the type parameter implement //! `Diffable`. This is not required if the field is annotated with //! `#[daft(leaf)]`. //! //! Daft fully supports types with arbitrary lifetimes. Automatically generated //! diff structs will have an additional `'daft` lifetime parameter at the //! beginning, with the requirement that all other lifetime and type parameters //! outlive it. //! //! ### Example //! //! ```rust //! # #[cfg(feature = "derive")] { //! use daft::Diffable; //! //! #[derive(Diffable)] //! struct BorrowedData<'a, 'b, T: Diffable + ?Sized> { //! a: &'a str, //! b: &'b T, //! // TODO: example with daft(leaf) //! } //! //! // This generates a struct that looks like: //! # /* //! #[automatically_derived] //! struct BorrowedDataDiff<'daft, 'a: 'daft, 'b: 'daft, T: ?Sized + 'daft> { //! a: Leaf<'daft, &'a str>, //! b: T::Diff<'daft>, //! } //! # */ //! # } //! ``` //! //! # Optional features //! //! * `derive`: Enable the `Diffable` derive macro: **disabled** by default. //! //! Implementations for standard library types, all **enabled** by default: //! //! * `alloc`: Enable diffing for types from the [`alloc`] crate. //! * `std`: Enable diffing for types from the [`std`] crate. //! //! (With `default-features = false`, daft is no-std compatible.) //! //! Implementations for third-party types, all **disabled** by default: //! //! * `uuid1`: Enable diffing for [`uuid::Uuid`]. //! * `oxnet01`: Enable diffing for network types from the [`oxnet`] crate. //! * `newtype-uuid1`: Enable diffing for [`newtype_uuid::TypedUuid`]. //! //! # Minimum supported Rust version (MSRV) //! //! The minimum supported Rust version is **1.81.0**. At any time, at least the //! last three stable versions of Rust are supported. //! //! While this crate is a pre-release (0.x.x) it may have its MSRV bumped in a //! patch release. Once this crate has reached 1.x, any MSRV bump will be //! accompanied with a new minor version. //! //! # Related work //! //! [Diffus](https://crates.io/crates/diffus) is the original inspiration for //! this crate and a great alternative. Daft diverges from diffus in a few ways: //! //! * Daft's derive macro does not attempt to diff enums with different variants. //! In practice, we've found that diffing enums across different variants is less //! useful than it first appears. //! //! * Daft has the notion of a [`Leaf`] type, which represents an atomic unit. //! (For example, the [`Diffable`] implementation for `i32` is a [`Leaf`].) //! [`Leaf`]s are also used for enums, as well as in any other place where lazy //! diffing is desired. //! //! * Diffus has a `Same` trait, which is like `Eq` except it's also implemented //! for floats. Daft doesn't have the `Same` trait, and its core //! functionality forgoes the need for `Eq` entirely. //! //! For a primitive scalar like `f64`, you'll get a `Leaf` struct which you can //! compare with whatever notion of equality you want. //! //! * Daft uses a [generic associated type (GAT)][GAT] so that the `Diffable` //! trait no longer needs a lifetime parameter. This leads to simpler usage. //! (Diffus was written before GATs were available in stable Rust.) //! //! * Daft uses fewer types in general. For example, diffus wraps its return values //! in an outer `Edit` type, but daft does not. //! //! * Daft is no-std-compatible, while diffus requires std. //! //! [GAT]: https://blog.rust-lang.org/2021/08/03/GATs-stabilization-push.html //! [`BTreeMap`]: std::collections::BTreeMap //! [`BTreeSet`]: std::collections::BTreeSet //! [`HashMap`]: std::collections::HashMap //! [`HashSet`]: std::collections::HashSet #[cfg(feature = "alloc")] extern crate alloc; #[macro_use] mod macros; #[cfg(feature = "alloc")] mod alloc_impls; mod core_impls; mod diffable; mod leaf; #[cfg(feature = "std")] mod std_impls; mod third_party; #[cfg(feature = "alloc")] pub use alloc_impls::*; /// Derive macro for the [`Diffable`] trait. /// /// The behavior of this macro varies by type: /// /// - For **structs**, this macro generates a corresponding recursive (eager) /// diff type by default. A non-recursive (lazy) diff can be generated by /// annotating the struct overall with `#[daft(leaf)]`. /// - For **enums** and **unions**, this macro generates a non-recursive (lazy) /// diff. /// /// For more information, see the [crate-level documentation](crate). #[cfg(feature = "derive")] pub use daft_derive::Diffable; pub use diffable::*; pub use leaf::*; #[cfg(feature = "std")] pub use std_impls::*; daft-0.1.5/src/macros.rs000064400000000000000000000236641046102023000132010ustar 00000000000000//! Macros for internal implementations. macro_rules! leaf { ($($typ:ty),*) => { $( impl $crate::Diffable for $typ { type Diff<'daft> = $crate::Leaf<&'daft Self>; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { $crate::Leaf { before: self, after: other } } } )* } } #[cfg(feature = "alloc")] macro_rules! leaf_deref { ($($typ:ty => $target:ty),*) => { $( impl $crate::Diffable for $typ { type Diff<'daft> = $crate::Leaf<&'daft $target>; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { $crate::Leaf { before: &**self, after: &**other } } } )* }; } /// Create a type `Diff` and `impl Diffable` on it. /// /// This is supported for `BTreeMap` and `HashMap` #[cfg(feature = "alloc")] macro_rules! map_diff { ($(#[$doc:meta])* $typ:ident, $key_constraint:ident) => { paste::paste! { $(#[$doc])* #[derive(Debug, PartialEq, Eq)] pub struct [<$typ Diff>]<'daft, K: $key_constraint + Eq, V> { /// Entries common to both maps. /// /// Values are stored as `Leaf`s to references. pub common: $typ<&'daft K, $crate::Leaf<&'daft V>>, /// Entries present in the `after` map, but not in `before`. pub added: $typ<&'daft K, &'daft V>, /// Entries present in the `before` map, but not in `after`. pub removed: $typ<&'daft K, &'daft V>, } impl<'daft, K: $key_constraint + Eq, V> [<$typ Diff>]<'daft, K, V> { #[doc = "Create a new, empty `" $typ "Diff` instance."] pub fn new() -> Self { Self { common: $typ::new(), added: $typ::new(), removed: $typ::new(), } } } impl<'daft, K: $key_constraint + Eq, V: Eq> [<$typ Diff>]<'daft, K, V> { /// Return an iterator over unchanged keys and values. pub fn unchanged(&self) -> impl Iterator + '_ { self.common.iter().filter_map(|(k, leaf)| { leaf.is_unchanged().then_some((*k, leaf.before)) }) } /// Return true if the value corresponding to the key is /// unchanged. pub fn is_unchanged(&self, key: &K) -> bool { self.common.get(key).is_some_and(|leaf| leaf.is_unchanged()) } /// Return the value associated with the key if it is unchanged, /// otherwise `None`. pub fn get_unchanged(&self, key: &K) -> Option<&'daft V> { self.common.get(key).and_then(|leaf| { leaf.is_unchanged().then_some(leaf.before) }) } /// Return an iterator over unchanged keys. pub fn unchanged_keys(&self) -> impl Iterator + '_ { self.common.iter().filter_map(|(k, leaf)| { leaf.is_unchanged().then_some(*k) }) } /// Return an iterator over unchanged values. pub fn unchanged_values(&self) -> impl Iterator + '_ { self.common.iter().filter_map(|(_, leaf)| { leaf.is_unchanged().then_some(leaf.before) }) } /// Return an iterator over modified keys and values. pub fn modified(&self) -> impl Iterator)> + '_ { self.common.iter().filter_map(|(k, leaf)| { leaf.is_modified().then_some((*k, *leaf)) }) } /// Return true if the value corresponding to the key is /// modified. pub fn is_modified(&self, key: &K) -> bool { self.common.get(key).is_some_and(|leaf| leaf.is_modified()) } /// Return the `Leaf` associated with the key if it is modified, /// otherwise `None`. pub fn get_modified(&self, key: &K) -> Option<$crate::Leaf<&'daft V>> { self.common.get(key).and_then(|leaf| { leaf.is_modified().then_some(*leaf) }) } /// Return an iterator over modified keys. pub fn modified_keys(&self) -> impl Iterator + '_ { self.common.iter().filter_map(|(k, leaf)| { leaf.is_modified().then_some(*k) }) } /// Return an iterator over modified values. pub fn modified_values(&self) -> impl Iterator> + '_ { self.common.iter().filter_map(|(_, leaf)| { leaf.is_modified().then_some(*leaf) }) } /// Return an iterator over modified keys and values, performing /// a diff on the values. /// /// This is useful when `V::Diff` is a complex type, not just a /// [`Leaf`](crate::Leaf). #[allow(rustdoc::redundant_explicit_links)] // some macro use sites have Leaf available, some don't pub fn modified_diff(&self) -> impl Iterator)> + '_ where V: Diffable, { self.modified().map(|(k, leaf)| (k, leaf.before.diff(&leaf.after))) } /// Return an iterator over modified values, performing a diff on /// them. /// /// This is useful when `V::Diff` is a complex type, not just a /// [`Leaf`](crate::Leaf). #[allow(rustdoc::redundant_explicit_links)] // some macro use sites have Leaf available, some don't pub fn modified_values_diff(&self) -> impl Iterator> + '_ where V: Diffable, { self.modified_values().map(|leaf| leaf.before.diff(&leaf.after)) } } // Note: not deriving Default here because we don't want to require // K or V to be Default. impl<'daft, K: $key_constraint + Eq, V> Default for [<$typ Diff>]<'daft, K, V> { fn default() -> Self { Self::new() } } impl $crate::Diffable for $typ { type Diff<'daft> = [<$typ Diff>]<'daft, K, V> where K: 'daft, V: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { let mut diff = [<$typ Diff>]::new(); for (k, v) in self { if let Some(other_v) = other.get(k) { diff.common.insert(k, $crate::Leaf { before: v, after: other_v }); } else { diff.removed.insert(k, v); } } for (k, v) in other { if !self.contains_key(k) { diff.added.insert(k, v); } } diff } } } } } /// Create a type `Diff` and `impl Diffable` on it. /// /// This is supported for `BTreeSet` and `HashSet`. #[cfg(feature = "alloc")] macro_rules! set_diff { ($(#[$doc:meta])* $typ:ident, $key_constraint:ident) => { paste::paste! { $(#[$doc])* #[derive(Debug, PartialEq, Eq)] pub struct [<$typ Diff>]<'daft, K: $key_constraint + Eq> { /// Entries common to both sets. pub common: $typ<&'daft K>, /// Entries present in the `after` set, but not in `before`. pub added: $typ<&'daft K>, /// Entries present in the `before` set, but not in `after`. pub removed: $typ<&'daft K>, } impl<'daft, K: $key_constraint + Eq> [<$typ Diff>]<'daft, K> { #[doc = "Create a new, empty `" $typ "Diff` instance."] pub fn new() -> Self { Self { common: $typ::new(), added: $typ::new(), removed: $typ::new(), } } } // Note: not deriving Default here because we don't want to require // K to be Default. impl<'daft, K: $key_constraint + Eq> Default for [<$typ Diff>]<'daft, K> { fn default() -> Self { Self::new() } } impl $crate::Diffable for $typ { type Diff<'daft> = [<$typ Diff>]<'daft, K> where K: 'daft; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { let mut diff = [<$typ Diff>]::new(); diff.removed = self.difference(other).collect(); diff.added = other.difference(self).collect(); diff.common = self.intersection(other).collect(); diff } } } } } daft-0.1.5/src/std_impls.rs000064400000000000000000000130551046102023000137040ustar 00000000000000//! Implementations for types in std. use crate::Diffable; use std::{ collections::{HashMap, HashSet}, ffi::{OsStr, OsString}, hash::Hash, path::{Path, PathBuf}, }; leaf! { Path, OsStr } leaf_deref! { PathBuf => Path, OsString => OsStr } map_diff!( /// A diff of two [`HashMap`] instances. /// /// The diff contains three elements: /// /// - `common`: Entries that are present in both maps, with their values /// stored as a [`Leaf`][crate::Leaf]. /// - `added`: Entries present in `after`, but not in `before`. /// - `removed`: Entries present in `before`, but not in `after`. /// /// If `V` implements `Eq`, `common` can be split into /// [`unchanged`][Self::unchanged] and [`modified`][Self::modified] entries. /// Additionally, if `V` implements [`Diffable`], /// [`modified_diff`][Self::modified_diff] can be used to recursively diff /// modified entries. /// /// # Example /// /// ``` /// # #[cfg(feature = "std")] { /// use daft::{Diffable, HashMapDiff, Leaf}; /// use std::collections::HashMap; /// /// let a: HashMap = /// [(0, "lorem"), (1, "ipsum"), (2, "dolor")].into_iter().collect(); /// let b: HashMap = /// [(1, "ipsum"), (2, "sit"), (3, "amet")].into_iter().collect(); /// /// let changes = a.diff(&b); /// let expected = HashMapDiff { /// // Keys are stored by reference and matched by equality. /// common: [ /// (&1, Leaf { before: &"ipsum", after: &"ipsum" }), /// (&2, Leaf { before: &"dolor", after: &"sit" }), /// ].into_iter().collect(), /// added: [(&3, &"amet")].into_iter().collect(), /// removed: [(&0, &"lorem")].into_iter().collect(), /// }; /// /// assert_eq!(changes, expected); /// /// // If the values are `Eq`, it's also possible to get lists of /// // modified and unchanged entries. /// assert!(changes.is_unchanged(&1)); /// assert!(changes.is_modified(&2)); /// let mut unchanged = changes.unchanged().collect::>(); /// unchanged.sort_by_key(|(k, _)| *k); /// let mut modified = changes.modified().collect::>(); /// modified.sort_by_key(|(k, _)| *k); /// /// assert_eq!(unchanged, [(&1, &"ipsum")]); /// assert_eq!(modified, [(&2, Leaf { before: &"dolor", after: &"sit" })]); /// # } /// ``` HashMap, Hash ); set_diff!( /// A diff of two [`HashSet`] instances. /// /// The diff contains three elements: /// /// - `common`: Entries that are present in both sets. /// - `added`: Entries present in `after`, but not in `before`. /// - `removed`: Entries present in `before`, but not in `after`. /// /// # Example /// /// ``` /// # #[cfg(feature = "std")] { /// use daft::{Diffable, HashSetDiff}; /// use std::collections::HashSet; /// /// let a: HashSet = [0, 1].into_iter().collect(); /// let b: HashSet = [1, 2].into_iter().collect(); /// /// let changes = a.diff(&b); /// let expected = HashSetDiff { /// // Entries are stored by reference and matched by equality. /// common: [&1].into_iter().collect(), /// added: [&2].into_iter().collect(), /// removed: [&0].into_iter().collect(), /// }; /// /// assert_eq!(changes, expected); /// # } /// ``` HashSet, Hash ); #[cfg(test)] mod tests { use super::*; use crate::Leaf; #[test] fn hash_set_diff() { let a: HashSet<_> = [0, 1, 2, 3, 4, 5].into_iter().collect(); let b: HashSet<_> = [3, 4, 5, 6, 7, 8].into_iter().collect(); let changes = a.diff(&b); let expected = HashSetDiff { added: [&6, &7, &8].into_iter().collect(), removed: [&0, &1, &2].into_iter().collect(), common: [&3, &4, &5].into_iter().collect(), }; assert_eq!(expected, changes); } #[test] fn hash_map_diff() { let a: HashMap<_, _> = [(0, 1), (1, 1), (2, 1)].into_iter().collect(); let b: HashMap<_, _> = [(0, 2), (2, 1), (3, 1)].into_iter().collect(); let changes = a.diff(&b); let expected = HashMapDiff { common: [ (&0, Leaf { before: &1, after: &2 }), (&2, Leaf { before: &1, after: &1 }), ] .into_iter() .collect(), added: [(&3, &1)].into_iter().collect(), removed: [(&1, &1)].into_iter().collect(), }; assert_eq!(changes, expected); // Ensure that keys don't need to be Diffable, and values don't need to // be Eq or Diffable. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] struct K(i32); #[derive(Debug)] #[expect(dead_code)] struct V(f64); let floats_a: HashMap = [(K(0), V(1.0)), (K(1), V(1.0)), (K(2), V(1.0))] .into_iter() .collect(); let floats_b: HashMap = [(K(0), V(2.0)), (K(2), V(1.0)), (K(3), V(1.0))] .into_iter() .collect(); let diff = floats_a.diff(&floats_b); assert_eq!(diff.added.keys().copied().collect::>(), [&K(3)]); assert_eq!(diff.removed.keys().copied().collect::>(), [&K(1)]); // HashMaps have non-deterministic order, so they should be sorted // before comparison. let mut common = diff.common.keys().copied().collect::>(); common.sort(); assert_eq!(common, [&K(0), &K(2)]); } } daft-0.1.5/src/third_party/mod.rs000064400000000000000000000003011046102023000150040ustar 00000000000000//! Implementations for third-party libraries. #[cfg(feature = "newtype-uuid1")] mod newtype_uuid_impls; #[cfg(feature = "oxnet01")] mod oxnet_impls; #[cfg(feature = "uuid1")] mod uuid_impls; daft-0.1.5/src/third_party/newtype_uuid_impls.rs000064400000000000000000000005111046102023000201550ustar 00000000000000use crate::{Diffable, Leaf}; use newtype_uuid::{TypedUuid, TypedUuidKind}; impl Diffable for TypedUuid where T: TypedUuidKind + Diffable, { type Diff<'daft> = Leaf<&'daft TypedUuid>; fn diff<'daft>(&'daft self, other: &'daft Self) -> Self::Diff<'daft> { Leaf { before: self, after: other } } } daft-0.1.5/src/third_party/oxnet_impls.rs000064400000000000000000000001031046102023000165660ustar 00000000000000leaf! { oxnet::IpNet, oxnet::Ipv4Net, oxnet::Ipv6Net } daft-0.1.5/src/third_party/uuid_impls.rs000064400000000000000000000033541046102023000164120ustar 00000000000000leaf! { uuid::Uuid } #[cfg(test)] #[cfg(feature = "alloc")] mod tests { use crate::{BTreeMapDiff, Diffable, Leaf}; use alloc::{collections::BTreeMap, vec}; #[test] fn example_struct() { use uuid::Uuid; #[derive(Debug, Clone, PartialEq, Eq)] enum SledState { Active, Decommissioned, } leaf!(SledState); #[derive(Debug, Clone)] struct TestStruct { id: Uuid, sled_state: BTreeMap, } // This is what daft-derive should generate // for `TestStruct` #[derive(Debug)] struct TestStructDiff<'daft> { id: Leaf<&'daft Uuid>, sled_state: BTreeMapDiff<'daft, Uuid, SledState>, } let sled_states = vec![ (Uuid::new_v4(), SledState::Active), (Uuid::new_v4(), SledState::Active), (Uuid::new_v4(), SledState::Decommissioned), ]; let a = TestStruct { id: Uuid::new_v4(), sled_state: sled_states.clone().into_iter().collect(), }; let mut b = a.clone(); b.id = Uuid::new_v4(); *(b.sled_state.get_mut(&sled_states[0].0).unwrap()) = SledState::Decommissioned; b.sled_state.insert(Uuid::new_v4(), SledState::Active); let diff = TestStructDiff { id: a.id.diff(&b.id), sled_state: a.sled_state.diff(&b.sled_state), }; assert_ne!(diff.id.before, diff.id.after); assert_eq!(diff.sled_state.unchanged().count(), 2); assert_eq!(diff.sled_state.added.len(), 1); assert_eq!(diff.sled_state.removed.len(), 0); assert_eq!(diff.sled_state.modified().count(), 1); } }