treediff-4.0.2/.cargo_vcs_info.json0000644000000001120000000000100126210ustar { "git": { "sha1": "41c9caf8622f860a1cd782f7a450da1786be78e9" } } treediff-4.0.2/CHANGELOG.md000064400000000000000000000344210072674642500132640ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## v4.0.2 (2021-10-09) * update changelog ### Commit Statistics - 1 commit contributed to the release. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - prepare changelog for next release (716c87e)
## v4.0.1 (2021-10-07) * fix links in documentation (#8) ### Commit Statistics - 12 commits contributed to the release over the course of 613 calendar days. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Release treediff v4.0.1 (ebf1d8b) - Adjusting Changelogs prior to release of treediff v4.0.1 (02db0ae) - cleanup changelog (20e2e0e) - rename changelog to capitalized version. (12ad31b) - Fix broken doc comments. (8f28c92) - Fix serde_yaml tests - for some reason it inserts newlines to key values (6d524b4) - fix most of the clippy warnings (223ef3c) - Remove 'alpha' from next version string (27ec50b) - optimize imports (a52269e) - bye bye travis, it was a good time (c44db69) - Create rust.yml (7bfefb5) - (cargo-release) start next development iteration 4.0.1-alpha.0 (ab3a679)
## v4.0.0 (2020-02-02) ### Commit Statistics - 3 commits contributed to the release. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - fix all lints (0ffb242) - Upgrade serde-yaml to the latest version (3bcb5bb) - (cargo-release) start next development iteration 3.0.3-alpha.0 (ffc085e)
## v3.0.2 (2020-02-02) ### Commit Statistics - 2 commits contributed to the release. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Rust 2018 upgrades (e126c32) - remove clog; smaller package (176cd69)
## v3.0.1 (2018-03-12) ### Commit Statistics - 1 commit contributed to the release. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Make filter_mut() actually return a mutable reference (cbb1b06)
## v3.0.0 (2018-03-11) * **upgrade**: use latest versions of dependencies ### Commit Statistics - 2 commits contributed to the release over the course of 87 calendar days. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Update to latest versions of dependencies (0517e7c) - Apply latest rustfmt (ace2602)
## v2.5.3 (2017-09-24) ### Commit Statistics - 3 commits contributed to the release over the course of 30 calendar days. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - version bump (e0167bd) - Merge pull request #3 from paulrouget/serde_bump (dbac9ec) - serde version bump (fe8f02a)
## v2.5.1 (2017-02-22) ### other - use serde 0.9.8 and Map::Entry * **upgrade:** use serde 0.9.8 and Map::Entry ([60923752](https://github.com/Byron/treediff-rs/commit/6092375279e6fe184c8b457f0e6eb5a9f7f05d3b)) ### Commit Statistics - 2 commits contributed to the release. - 1 commit where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Update changelog (323a20f) - use serde 0.9.8 and Map::Entry (6092375)
## v2.5.0 (2017-02-14) ### other - allow keys to be cloned and displayed * **merger:** allow keys to be cloned and displayed ([75fae1b2](https://github.com/Byron/treediff-rs/commit/75fae1b2c30b9ce42012f1c9d63118e0443b9b6f)) ### Commit Statistics - 2 commits contributed to the release. - 1 commit where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - v2.5.0 (727ed22) - allow keys to be cloned and displayed (75fae1b)
## v2.4.0 (2017-02-14) ### other - method to obtain mutable borrow to filter - method to obtain immutable reference to filter. * **merger:** * method to obtain mutable borrow to filter ([eeb3a2da](https://github.com/Byron/treediff-rs/commit/eeb3a2da52c22d7e820fe3a40c74e55a2431ff9e)) * method to obtain immutable reference to filter. ([fc210ea4](https://github.com/Byron/treediff-rs/commit/fc210ea42354be6e8febcd210bd9630040bd357d)) ### Commit Statistics - 3 commits contributed to the release. - 2 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - v2.4.0 (960d01c) - method to obtain mutable borrow to filter (eeb3a2d) - method to obtain immutable reference to filter. (fc210ea)
## v2.3.0 (2017-02-13) ### other - handle possiblity of underflow - add AsRef implementation * **Merger:** add AsRef implementation ([981c94af](https://github.com/Byron/treediff-rs/commit/981c94afe98cd1da11aed290562ebe4a1e7a60cc)) * **safety:** handle possiblity of underflow ([07eff4f9](https://github.com/Byron/treediff-rs/commit/07eff4f93816bc10d4b0d5d98bcaef03741ee2c0)) ### Commit Statistics - 3 commits contributed to the release. - 2 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Update changelog (49cdef0) - handle possiblity of underflow (07eff4f) - add AsRef implementation (981c94a)
## v2.2.0 (2017-02-13) * `yaml_rust` support, for both `diff` and `merge`. ### Commit Statistics - 2 commits contributed to the release. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Bump to version 2.2 (3c0dc31) - Support for yaml-rust (88b632d)
## v2.1.1 (2017-02-13) ### other - fix links * fix library documentation links ### Commit Statistics - 1 commit contributed to the release. - 1 commit where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - fix links (f061028)
## v2.1.0 (2017-02-13) * `serde_yaml` support, for both `diff` and `merge`. ### Commit Statistics - 3 commits contributed to the release. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Mutator/merge support for serde-yaml (5e44fe9) - prepare merge tests for Yaml (e132c25) - Add diff support for serde-yaml (8e14a85)
## v2.0.1 (2017-02-07) ### other - categories! * **cargo:** categories! ([4dc20325](https://github.com/Byron/treediff-rs/commit/4dc2032561593cee1a41f2371396fade9687906c)) ### Commit Statistics - 3 commits contributed to the release. - 1 commit where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Update changelog (ed7c873) - categories! (4dc2032) - Say goodbye to git-journal, welcome back clog (67797d3)
## v2.0.0 (2017-02-07) Improve `Merger` API considerably, and make it even more powerful. ### Commit Statistics - 3 commits contributed to the release over the course of 1 calendar day. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Bumped version to v2.0 (a579c1c) - Improved merger API (e6512e2) - Added doc link to Readme (d84c44f)
## v1.0.0 (2017-02-05) Initial release. ### Commit Statistics - 74 commits contributed to the release over the course of 23 calendar days. - 0 commits where understood as [conventional](https://www.conventionalcommits.org). - 1 unique issue was worked on ### Commit Details
view details * **Uncategorized** - Changed version to v1.0.0 (958a1f3) - Added all remaining docs (f17d671) - Improved crate structure (5d0c76e) - Added even more docs/structural changes (b463311) - Improved module layout (367aaf4) - Added docs for main traits (2d6a8a8) - Removed unnecessary options in API (a370969) - Added some more docs (ea88d65) - Added support for value removal on conflict (1195299) - Added some crate docs (17fd836) - Improved project structure (5abc89d) - Improved suite definitions (96d3b98) - Added Merge support for serde-json (f932d4a) - Improved API to support arbitrary modifications when merging (038256d) - Improved API by using Cow only when needed (773cd1b) - Added support for deletion handler (a298c50) - Added test to verify conflict resolver. (46f766a) - Improved delegate clarity and capability of resolve() (d4eae6a) - Improved delegate interface consistency (1bcd40a) - Added groundwork for resolving conflicts (5630e87) - Added generalized suite for merge tests (d146dba) - Improved json value tests (fa1bf24) - Added diff support for serde_json Value (cf1934a) - Added json value suite (1070cd4) - Changed structure in preparation for serde (ef34105) - Added remove_key support for json (0b12455) - Changed license to MIT/Apache2 (b734959) - Added handling for merging arrays (3749007) - Improved object setter code (c141b92) - Improved mergeable trait to not degenerate information (d448e7c) - Added key removal and modification for merge (d19b005) - Added added-key tests and impl (52cb2b6) - Added a few tests to assert Mergeable.set() (e1d2c14) - Added merge infrastructure (4347535) - Improved key ownership (627ba19) - Added full key support (843d18b) - Added preliminary key support (70101cc) - Added handling for scalar/object comparisons (434b533) - Added implementation for nested object handling (86fbe0a) - Added key addition and removal (41abd1e) - Fixed tests (e7905a8) - Improved type definition (1694109) - Revert "Added futile attempt to workaround type issue" (420e19c) - Added futile attempt to workaround type issue (01a4b58) - Added attempt to use a recursive type (a7eec83) - Removed std entirely (94b8479) - Changed diff to get closer to finding differences (6528fa5) - Improved travis to not run unnecessary tests (048038d) - Added Value for HashMap (60ef3cf) - Added json array value (b0304d1) - Added tests for all json scalars and the json object (0560d81) - Added first scalar Json value (10b9858) - Added JsonKey to abstract over usize/String (5ac03ce) - Added first version of json Value impl (837f56f) - Added modification of scalar values. (6dee766) - Added utils module (42e7c3c) - Improved Delegate to support references (3e31491) - Improved ChangeType to contain values (9c5904f) - Added first stub of diff function (01d388b) - Removed with-std feature (d14deb4) - Fixed trait type signature to use iterator (ca6ea4e) - Improved trait signature (569c930) - Changed trait to just copy everything (9f8203e) - Revert "Changed trait to support hacky polymorphism" (eb019cc) - Changed trait to support hacky polymorphism (e544f55) - Improved definition of trait implementation (4bb8b7d) - Improved trait lifetime handling (8107a4c) - Added simplified non-working items() method (e618706) - Improved trait by simplifying it (c274604) - Added attempt to create an iterator based items() method (edb547e) - Improved Value trait (26ff8d4) - Added first impl of Value Trait for String (1822a45) - Added git-journal support (15e670a) - Initial commit (83f2154)
treediff-4.0.2/Cargo.toml0000644000000026040000000000100106270ustar # 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 = "2018" name = "treediff" version = "4.0.2" authors = ["Sebastian Thiel "] include = ["src/**/*", "LICENSE-*", "README.md", "CHANGELOG.md"] description = "Find the difference between arbitrary data structures" documentation = "https://docs.rs/treediff" readme = "README.md" keywords = ["diff", "structure", "tree", "arbitrary", "general"] categories = ["algorithms"] license = "MIT/Apache-2.0" repository = "https://github.com/Byron/treediff-rs" [dependencies.rustc-serialize] version = "0.3.24" optional = true [dependencies.serde_json] version = "1.0.45" optional = true [dependencies.serde_yaml] version = "0.8" optional = true [dependencies.yaml-rust] version = "0.4" optional = true [dev-dependencies.serde] version = "1.0" features = ["derive"] [features] with-rustc-serialize = ["rustc-serialize"] with-serde-json = ["serde_json"] with-serde-yaml = ["serde_yaml"] with-yaml-rust = ["yaml-rust"] treediff-4.0.2/Cargo.toml.orig000064400000000000000000000016370072674642500143450ustar 00000000000000[package] authors = ["Sebastian Thiel "] description = "Find the difference between arbitrary data structures" documentation = "https://docs.rs/treediff" keywords = ["diff", "structure", "tree", "arbitrary", "general"] categories = ["algorithms"] license = "MIT/Apache-2.0" name = "treediff" readme = "README.md" repository = "https://github.com/Byron/treediff-rs" edition = "2018" version = "4.0.2" include = ["src/**/*", "LICENSE-*", "README.md", "CHANGELOG.md"] [dependencies] rustc-serialize = {version = "0.3.24", optional = true} serde_json = {version = "1.0.45", optional = true} serde_yaml = {version = "0.8", optional = true} yaml-rust = {version = "0.4", optional = true} [dev-dependencies] serde = { version = "1.0", features = ["derive"] } [features] with-rustc-serialize = ["rustc-serialize"] with-serde-json = ["serde_json"] with-serde-yaml = ["serde_yaml"] with-yaml-rust = ["yaml-rust"] treediff-4.0.2/LICENSE-APACHE000064400000000000000000000251370072674642500134030ustar 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 [yyyy] [name of copyright owner] 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. treediff-4.0.2/LICENSE-MIT000064400000000000000000000020410072674642500131000ustar 00000000000000Copyright (c) 2016 Alex Crichton 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. treediff-4.0.2/README.md000064400000000000000000000006340072674642500127310ustar 00000000000000![Rust](https://github.com/Byron/treediff-rs/workflows/Rust/badge.svg) [![crates.io version](https://img.shields.io/crates/v/treediff.svg)](https://crates.io/crates/treediff) A library to compare arbitrary structured data of the same type, efficiently. Please see the [documentation](https://docs.rs/treediff/*) for more details. # Usage Add this to your Cargo.toml ```toml [dependencies] treediff = "4" ``` treediff-4.0.2/src/diff.rs000064400000000000000000000051640072674642500135220ustar 00000000000000use crate::traitdef::{Delegate, Value}; use std::{cmp::Ordering, collections::BTreeSet}; /// A generic diff algorithm suitable for `Value` types as seen in serialization/deserialization /// libraries. /// /// Such types can represent any tree-like data structure, which will be traversed to find /// *additions*, *removals*, *modifications* and even portions that did not change at all. /// /// # Parameters /// * `l` - the left Value /// * `r` - the right Value /// * `d` - a `Delegate` to receive information about changes between `l` and `r` pub fn diff<'a, V, D>(l: &'a V, r: &'a V, d: &mut D) where V: Value, V::Key: Ord + Clone, D: Delegate<'a, V::Key, V>, { match (l.items(), r.items()) { // two scalars, equal (None, None) if l == r => d.unchanged(l), // two scalars, different (None, None) => d.modified(l, r), // two objects, equal (Some(_), Some(_)) if l == r => d.unchanged(l), // object and scalar (Some(_), None) | (None, Some(_)) => d.modified(l, r), // two objects, different (Some(li), Some(ri)) => { let mut sl: BTreeSet> = BTreeSet::new(); sl.extend(li.map(Into::into)); let mut sr: BTreeSet> = BTreeSet::new(); sr.extend(ri.map(Into::into)); for k in sr.intersection(&sl) { let v1 = sl.get(k).expect("intersection to work"); let v2 = sr.get(k).expect("intersection to work"); d.push(&k.0); diff(v1.1, v2.1, d); d.pop(); } for k in sr.difference(&sl) { d.added(&k.0, sr.get(k).expect("difference to work").1); } for k in sl.difference(&sr) { d.removed(&k.0, sl.get(k).expect("difference to work").1); } } } } struct OrdByKey<'a, K, V: 'a>(pub K, pub &'a V); impl<'a, K, V> From<(K, &'a V)> for OrdByKey<'a, K, V> { fn from(src: (K, &'a V)) -> Self { OrdByKey(src.0, src.1) } } impl<'a, K, V> Eq for OrdByKey<'a, K, V> where K: Eq + PartialOrd {} impl<'a, K, V> PartialEq for OrdByKey<'a, K, V> where K: PartialOrd, { fn eq(&self, other: &OrdByKey<'a, K, V>) -> bool { self.0.eq(&other.0) } } impl<'a, K, V> PartialOrd for OrdByKey<'a, K, V> where K: PartialOrd, { fn partial_cmp(&self, other: &OrdByKey<'a, K, V>) -> Option { self.0.partial_cmp(&other.0) } } impl<'a, K, V> Ord for OrdByKey<'a, K, V> where K: Ord, { fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) } } treediff-4.0.2/src/lib.rs000064400000000000000000000021110072674642500133450ustar 00000000000000//! **See what's different in arbitrary data structures**. //! //! The main [`diff`](`diff::diff`) algorithm. //! we implement here is less than a screen full of lines, yet it enables a vast amount of //! applications. //! It can work with all values implementing the `Value` trait. //! //! On top of it there is a [merge][`tools::Merger`] implementation, which can be used to aggregate changes //! into a target value. It works with `Value`s which implement the `Mutable` trait. //! //! # Usage //! Please have a look at the tests for [diff][diff-tests] and [merge][merge-tests]. //! //! Also note that you will have to choose the features to build the library with in order to //! get trait implementations for `Value` types of common libraries, //! i.e. `cargo build --features=with-serde-json`. //! //! [diff-tests]: https://github.com/Byron/treediff-rs/blob/master/tests/diff.rs //! [merge-tests]: https://github.com/Byron/treediff-rs/blob/master/tests/merge.rs #![deny(missing_docs, unsafe_code)] mod diff; pub mod tools; mod traitdef; pub mod value; pub use diff::*; pub use traitdef::*; treediff-4.0.2/src/tools/merge.rs000064400000000000000000000122410072674642500150430ustar 00000000000000use crate::traitdef::{Delegate, Mutable}; use std::{borrow::BorrowMut, borrow::Cow, fmt::Display, marker::PhantomData}; /// A `Delegate` which applies differences to a target object. /// /// It wraps the target object and applies all calls by the `diff` /// algorithm to it, which changes it in some way. /// /// Custom resolver functions can be provided to arbitrarily alter /// the way the merge is performed. This allows you, for example, to /// keep your own meta-data, or to implement custom conflict resolutions. /// /// # Examples /// Please see the [tests][tests] for usage examples. /// /// [tests]: https://github.com/Byron/treediff-rs/blob/master/tests/merge.rs#L22 pub struct Merger { cursor: Vec, inner: V, filter: BF, _d: PhantomData, } fn appended(keys: &[K], k: Option<&K>) -> Vec where K: Clone, { let mut keys = Vec::from(keys); if let Some(k) = k { keys.push(k.clone()); } keys } /// A filter to manipulate calls to be made to `Value`s implementing the `Mutable` trait in calls /// made by the `Merger` `Delegate`. /// /// This allows you to control the exact way merge operations are performed independently of the /// type implementing the `Value` trait, which usually is not under your control. pub trait MutableFilter { /// Called during `Delegate::modified(...)`, returns `None` to cause the Value at the `keys` to /// be removed, or any Value to be set in its place. /// /// `old` is the previous value at the given `keys` path, and `new` is the one now at its place. /// `_target` provides access to the target of the merge operation. fn resolve_conflict<'a, K: Clone + Display, V: Clone>( &mut self, _keys: &[K], _old: &'a V, new: &'a V, _target: &mut V, ) -> Option> { Some(Cow::Borrowed(new)) } /// Called during `Delegate::removed(...)`, returns `None` to allow the Value at the `keys` path /// to be removed, or any Value to be set in its place instead. /// /// `removed` is the Value which is to be removed. /// `_target` provides access to the target of the merge operation. fn resolve_removal<'a, K: Clone + Display, V: Clone>( &mut self, _keys: &[K], _removed: &'a V, _target: &mut V, ) -> Option> { None } } /// The default implementation used when when creating a new `Merger` from any `Value` type. /// /// If you want to choose your own filter, use `Merger::with_filter(...)` instead. pub struct DefaultMutableFilter; impl MutableFilter for DefaultMutableFilter {} impl<'a, K, V, F, BF> Delegate<'a, K, V> for Merger where V: Mutable + Clone + 'a, K: Clone + Display, F: MutableFilter, BF: BorrowMut, { fn push(&mut self, k: &K) { self.cursor.push(k.clone()); } fn pop(&mut self) { self.cursor.pop(); } fn removed<'b>(&mut self, k: &'b K, v: &'a V) { let keys = appended(&self.cursor, Some(k)); match self .filter .borrow_mut() .resolve_removal(&keys, v, &mut self.inner) { Some(nv) => self.inner.set(&keys, &nv), None => self.inner.remove(&keys), } } fn added<'b>(&mut self, k: &'b K, v: &'a V) { self.inner.set(&appended(&self.cursor, Some(k)), v); } fn unchanged<'b>(&mut self, v: &'a V) { self.inner.set(&self.cursor, v) } fn modified<'b>(&mut self, old: &'a V, new: &'a V) { let keys = appended(&self.cursor, None); match self .filter .borrow_mut() .resolve_conflict(&keys, old, new, &mut self.inner) { Some(v) => self.inner.set(&keys, &v), None => self.inner.remove(&keys), } } } impl Merger { /// Consume the merger and return the contained target Value, which is the result of the /// merge operation. pub fn into_inner(self) -> V { self.inner } /// Returns a mutable borrow to the `MutableFilter` instance pub fn filter_mut(&mut self) -> &mut BF { &mut self.filter } /// Returns a borrow to the `MutableFilter` instance pub fn filter(&self) -> &BF { &self.filter } } impl AsRef for Merger { fn as_ref(&self) -> &V { &self.inner } } impl<'a, V, BF, F> Merger where V: Mutable + 'a + Clone, F: MutableFilter, BF: BorrowMut, { /// Return a new Merger with the given initial value `v` and the filter `f` pub fn with_filter(v: V, f: BF) -> Self { Merger { inner: v, cursor: Vec::new(), filter: f, _d: PhantomData, } } } impl<'a, V> From for Merger where V: Mutable + 'a + Clone, { /// Return a new merger with the given initial value `v`, and the `DefaultMutableFilter`. fn from(v: V) -> Self { Merger { inner: v, cursor: Vec::new(), filter: DefaultMutableFilter, _d: PhantomData, } } } treediff-4.0.2/src/tools/mod.rs000064400000000000000000000002330072674642500145210ustar 00000000000000//! Various tools to help making the `diff` algorithm useful with minimal effort. mod merge; mod record; pub use self::merge::*; pub use self::record::*; treediff-4.0.2/src/tools/record.rs000064400000000000000000000044170072674642500152300ustar 00000000000000use crate::traitdef::Delegate; /// Identifies a type of change at a given Key path, for use with the `Recorder`. /// /// The Key path is followed to know what happened with the Value `V` contained in the variants. #[derive(Debug, PartialEq)] pub enum ChangeType<'a, K, V: 'a> { /// The Value was removed Removed(Vec, &'a V), /// The Value was added Added(Vec, &'a V), /// No change was performed to the Value Unchanged(Vec, &'a V), /// The first Value was modified and became the second Value Modified(Vec, &'a V, &'a V), } /// A `Delegate` to record all calls made to it. /// /// It can be useful if you don't want to implement your own custom delegate, but instead just want /// to quickly see a flat list of all results of the `diff` run. /// /// # Examples /// Please see the [tests][tests] for how to use this type. /// /// [tests]: https://github.com/Byron/treediff-rs/blob/master/tests/diff.rs#L21 #[derive(Debug, PartialEq)] pub struct Recorder<'a, K, V: 'a> { cursor: Vec, /// A list of all calls the `diff` function made on us. pub calls: Vec>, } impl<'a, K, V> Default for Recorder<'a, K, V> { fn default() -> Self { Recorder { cursor: Vec::new(), calls: Vec::new(), } } } fn mk(c: &[K], k: Option<&K>) -> Vec where K: Clone, { let mut c = Vec::from(c); match k { Some(k) => { c.push(k.clone()); c } None => c, } } impl<'a, K, V> Delegate<'a, K, V> for Recorder<'a, K, V> where K: Clone, { fn push(&mut self, k: &K) { self.cursor.push(k.clone()) } fn pop(&mut self) { self.cursor.pop(); } fn removed<'b>(&mut self, k: &'b K, v: &'a V) { self.calls .push(ChangeType::Removed(mk(&self.cursor, Some(k)), v)); } fn added<'b>(&mut self, k: &'b K, v: &'a V) { self.calls .push(ChangeType::Added(mk(&self.cursor, Some(k)), v)); } fn unchanged<'b>(&mut self, v: &'a V) { self.calls .push(ChangeType::Unchanged(self.cursor.clone(), v)); } fn modified<'b>(&mut self, v1: &'a V, v2: &'a V) { self.calls .push(ChangeType::Modified(mk(&self.cursor, None), v1, v2)); } } treediff-4.0.2/src/traitdef.rs000064400000000000000000000047210072674642500144120ustar 00000000000000/// Represents a scalar value or an associative array. pub trait Value: PartialEq { /// The Key type used to find Values in a mapping. type Key; /// The Value type itself. type Item; /// Returns `None` if this is a scalar value, and an iterator yielding (Key, Value) pairs /// otherwise. It is entirely possible for it to yield no values though. #[allow(clippy::type_complexity)] fn items<'a>(&'a self) -> Option + 'a>>; } /// The delegate receiving callbacks by the `diff` algorithm, which compares an old to a new value. /// /// # Type Parameters /// * `K` is the Key's type /// * `V` is the Value's type /// /// Methods will be called if... pub trait Delegate<'a, K, V> { /// ... we recurse into the `Value` at the given `Key`. /// /// Delegates should memoize the current Key path to be able to compute /// the full Key path when needed. fn push(&mut self, _k: &K) {} /// ... we have processed all items and leave the object previously `push`ed. fn pop(&mut self) {} /// ... the Value `v` at the given Key `k` should be removed. /// /// *Note* that the Key is partial, and should be used in conjunction with the recorded Keys /// received via `push(...)` fn removed<'b>(&mut self, _k: &'b K, _v: &'a V) {} /// .. the Value `v` at the given Key `k` should be added. /// /// *Note* that the Key is partial, and should be used in conjunction with the recorded Keys /// received via `push(...)` fn added<'b>(&mut self, _k: &'b K, _v: &'a V) {} /// The Value `v` was not changed. fn unchanged(&mut self, _v: &'a V) {} /// ... the `old` Value was modified, and is now the `new` Value. fn modified(&mut self, _old: &'a V, _new: &'a V) {} } /// A trait to allow changing any `Value`. pub trait Mutable { /// The Key type used to find Values in a mapping. type Key; /// The Value type itself. type Item; /// Set the `new` Value at the path identified by `keys`. /// /// Intermediate container values (like HashMaps, Arrays) must be created until /// the last Key in `keys` can be modified or inserted with `new`. fn set(&mut self, keys: &[Self::Key], new: &Self::Item); /// Remove the value located at the path identified by `keys`. /// /// If the value does not exist, just return. Intermediate container values /// must not be created. fn remove(&mut self, keys: &[Self::Key]); } treediff-4.0.2/src/value/mod.rs000064400000000000000000000005640072674642500145040ustar 00000000000000//! Contains all implementations of the `Value` and `Mutable` traits. //! //! Note that these are behind feature flags. mod shared; pub use self::shared::*; #[cfg(feature = "with-rustc-serialize")] mod rustc_json; #[cfg(feature = "with-serde-json")] mod serde_json; #[cfg(feature = "with-serde-yaml")] mod serde_yaml; #[cfg(feature = "with-yaml-rust")] mod yaml_rust; treediff-4.0.2/src/value/rustc_json.rs000064400000000000000000000152310072674642500161130ustar 00000000000000use super::Key; use crate::traitdef::{Mutable, Value}; use rustc_serialize::json::{Json as RustcJson, Object}; use std::{collections::btree_map::Entry::*, mem}; impl Value for RustcJson { type Key = Key; type Item = RustcJson; fn items<'a>(&'a self) -> Option + 'a>> { match *self { RustcJson::String(_) | RustcJson::U64(_) | RustcJson::I64(_) | RustcJson::F64(_) | RustcJson::Boolean(_) | RustcJson::Null => None, RustcJson::Array(ref inner) => Some(Box::new( inner.iter().enumerate().map(|(i, v)| (Key::Index(i), v)), )), RustcJson::Object(ref inner) => Some(Box::new( inner.iter().map(|(s, v)| (Key::String(s.clone()), v)), )), } } } impl Mutable for RustcJson { type Key = Key; type Item = RustcJson; fn set(&mut self, keys: &[Self::Key], v: &Self::Item) { if keys.is_empty() { *self = v.clone(); } else { let mut c = self; let last_key_index = keys.len() - 1; let object_or_value = |index| { if index == last_key_index { v.clone() } else { RustcJson::Object(Object::new()) } }; fn runup_array_or_value<'a>( array: &'a mut Vec, target_index: usize, key_index: usize, last_key_index: usize, v: &RustcJson, ) -> &'a mut RustcJson { for _ in array.len()..target_index { array.push(RustcJson::Null); } let value = if key_index == last_key_index { v.clone() } else { RustcJson::Null }; if target_index == array.len() { array.push(value); } else { array[target_index] = value; } &mut array[target_index] }; for (i, k) in keys.iter().enumerate() { c = match *k { Key::String(ref k) => match { c } { &mut RustcJson::Object(ref mut obj) => match obj.entry(k.clone()) { Vacant(e) => e.insert(object_or_value(i)), Occupied(e) => { if i == last_key_index { *e.into_mut() = v.clone(); return; } else { e.into_mut() } } }, c @ &mut RustcJson::String(_) | c @ &mut RustcJson::F64(_) | c @ &mut RustcJson::Boolean(_) | c @ &mut RustcJson::Null | c @ &mut RustcJson::U64(_) | c @ &mut RustcJson::Array(_) | c @ &mut RustcJson::I64(_) => { drop(mem::replace( c, RustcJson::Object({ let mut o = Object::new(); o.insert(k.clone(), object_or_value(i)); o }), )); if i == last_key_index { return; } match c { RustcJson::Object(ref mut obj) => { obj.get_mut(k).expect("previous insertion") } _ => unreachable!(), } } }, Key::Index(idx) => match { c } { &mut RustcJson::Array(ref mut a) => { runup_array_or_value(a, idx, i, last_key_index, v) } c @ &mut RustcJson::String(_) | c @ &mut RustcJson::F64(_) | c @ &mut RustcJson::Boolean(_) | c @ &mut RustcJson::Null | c @ &mut RustcJson::U64(_) | c @ &mut RustcJson::Object(_) | c @ &mut RustcJson::I64(_) => { let mut a = Vec::new(); runup_array_or_value(&mut a, idx, i, last_key_index, v); drop(mem::replace(c, RustcJson::Array(a))); if i == last_key_index { return; } match c { RustcJson::Array(ref mut a) => { a.get_mut(idx).expect("previous insertion") } _ => unreachable!(), } } }, } } } } fn remove(&mut self, keys: &[Self::Key]) { let mut c = self; let last_key_index = keys.len().checked_sub(1).expect("at least one key"); for (i, k) in keys.iter().enumerate() { c = match *k { Key::String(ref k) => match { c } { RustcJson::Object(ref mut obj) => { if i == last_key_index { obj.remove(k); return; } else { match obj.get_mut(k) { Some(json) => json, None => return, } } } _ => return, }, Key::Index(idx) => match { c } { RustcJson::Array(ref mut a) => { if i == last_key_index { a.remove(idx); return; } else { match a.get_mut(idx) { Some(json) => json, None => return, } } } _ => return, }, } } } } treediff-4.0.2/src/value/serde_json.rs000064400000000000000000000145460072674642500160650ustar 00000000000000use super::Key; use crate::traitdef::{Mutable, Value}; use serde_json::{map, Map, Value as SerdeJson}; use std::mem; impl Value for SerdeJson { type Key = Key; type Item = SerdeJson; fn items<'a>(&'a self) -> Option + 'a>> { match *self { SerdeJson::String(_) | SerdeJson::Number(_) | SerdeJson::Bool(_) | SerdeJson::Null => { None } SerdeJson::Array(ref inner) => Some(Box::new( inner.iter().enumerate().map(|(i, v)| (Key::Index(i), v)), )), SerdeJson::Object(ref inner) => Some(Box::new( inner.iter().map(|(s, v)| (Key::String(s.clone()), v)), )), } } } impl Mutable for SerdeJson { type Key = Key; type Item = SerdeJson; fn set(&mut self, keys: &[Self::Key], v: &Self::Item) { if keys.is_empty() { *self = v.clone(); } else { let mut c = self; let last_key_index = keys.len() - 1; let object_or_value = |index| { if index == last_key_index { v.clone() } else { SerdeJson::Object(Map::new()) } }; fn runup_array_or_value<'a>( array: &'a mut Vec, target_index: usize, key_index: usize, last_key_index: usize, v: &SerdeJson, ) -> &'a mut SerdeJson { for _ in array.len()..target_index { array.push(SerdeJson::Null); } let value = if key_index == last_key_index { v.clone() } else { SerdeJson::Null }; if target_index == array.len() { array.push(value); } else { array[target_index] = value; } &mut array[target_index] }; for (i, k) in keys.iter().enumerate() { c = match *k { Key::String(ref k) => match { c } { &mut SerdeJson::Object(ref mut obj) => match obj.entry(k.clone()) { map::Entry::Vacant(e) => e.insert(object_or_value(i)), map::Entry::Occupied(e) => { if i == last_key_index { *e.into_mut() = v.clone(); return; } else { e.into_mut() } } }, c @ &mut SerdeJson::String(_) | c @ &mut SerdeJson::Number(_) | c @ &mut SerdeJson::Bool(_) | c @ &mut SerdeJson::Null | c @ &mut SerdeJson::Array(_) => { drop(mem::replace( c, SerdeJson::Object({ let mut o = Map::new(); o.insert(k.clone(), object_or_value(i)); o }), )); if i == last_key_index { return; } match c { SerdeJson::Object(ref mut obj) => { obj.get_mut(k).expect("previous insertion") } _ => unreachable!(), } } }, Key::Index(idx) => match { c } { &mut SerdeJson::Array(ref mut a) => { runup_array_or_value(a, idx, i, last_key_index, v) } c @ &mut SerdeJson::String(_) | c @ &mut SerdeJson::Number(_) | c @ &mut SerdeJson::Bool(_) | c @ &mut SerdeJson::Null | c @ &mut SerdeJson::Object(_) => { let mut a = Vec::new(); runup_array_or_value(&mut a, idx, i, last_key_index, v); drop(mem::replace(c, SerdeJson::Array(a))); if i == last_key_index { return; } match c { SerdeJson::Array(ref mut a) => { a.get_mut(idx).expect("previous insertion") } _ => unreachable!(), } } }, } } } } fn remove(&mut self, keys: &[Self::Key]) { let mut c = self; let last_key_index = keys.len().checked_sub(1).expect("at least one key"); for (i, k) in keys.iter().enumerate() { c = match *k { Key::String(ref k) => match { c } { SerdeJson::Object(ref mut obj) => { if i == last_key_index { obj.remove(k); return; } else { match obj.get_mut(k) { Some(json) => json, None => return, } } } _ => return, }, Key::Index(idx) => match { c } { SerdeJson::Array(ref mut a) => { if i == last_key_index { a.remove(idx); return; } else { match a.get_mut(idx) { Some(json) => json, None => return, } } } _ => return, }, } } } } treediff-4.0.2/src/value/serde_yaml.rs000064400000000000000000000162720072674642500160540ustar 00000000000000use super::Key; use crate::traitdef::{Mutable, Value}; use serde_yaml::{self, to_string, Mapping, Value as SerdeYaml}; use std::mem; fn from_str(s: &str) -> SerdeYaml { serde_yaml::from_str(s).expect("valid yaml document, we created the key via to_string") } impl Value for SerdeYaml { type Key = Key; type Item = SerdeYaml; fn items<'a>(&'a self) -> Option + 'a>> { match *self { SerdeYaml::String(_) | SerdeYaml::Number(_) | SerdeYaml::Bool(_) | SerdeYaml::Null => { None } SerdeYaml::Sequence(ref inner) => Some(Box::new( inner.iter().enumerate().map(|(i, v)| (Key::Index(i), v)), )), SerdeYaml::Mapping(ref inner) => Some(Box::new(inner.iter().map(|(k, v)| { ( Key::String( to_string(k).expect("yaml value to serialize into yaml correctly")[4..] .to_owned(), ), v, ) }))), } } } impl Mutable for SerdeYaml { type Key = Key; type Item = SerdeYaml; fn set(&mut self, keys: &[Self::Key], v: &Self::Item) { if keys.is_empty() { *self = v.clone(); } else { let mut c = self; let last_key_index = keys.len() - 1; let object_or_value = |index| { if index == last_key_index { v.clone() } else { SerdeYaml::Mapping(Mapping::new()) } }; fn runup_array_or_value<'a>( array: &'a mut Vec, target_index: usize, key_index: usize, last_key_index: usize, v: &SerdeYaml, ) -> &'a mut SerdeYaml { for _ in array.len()..target_index { array.push(SerdeYaml::Null); } let value = if key_index == last_key_index { v.clone() } else { SerdeYaml::Null }; if target_index == array.len() { array.push(value); } else { array[target_index] = value; } &mut array[target_index] }; for (i, k) in keys.iter().enumerate() { c = match *k { Key::String(ref k) => { let k = from_str(&k); match { c } { &mut SerdeYaml::Mapping(ref mut obj) => { if obj.contains_key(&k) { let obj = obj.get_mut(&k).expect("map to work"); if i == last_key_index { *obj = v.clone(); return; } obj } else { obj.insert(k.clone(), object_or_value(i)); obj.get_mut(&k).expect("map to work") } } c @ &mut SerdeYaml::String(_) | c @ &mut SerdeYaml::Number(_) | c @ &mut SerdeYaml::Bool(_) | c @ &mut SerdeYaml::Null | c @ &mut SerdeYaml::Sequence(_) => { drop(mem::replace( c, SerdeYaml::Mapping({ let mut o = Mapping::new(); o.insert(k.clone(), object_or_value(i)); o }), )); if i == last_key_index { return; } match c { SerdeYaml::Mapping(ref mut obj) => { obj.get_mut(&k).expect("previous insertion") } _ => unreachable!(), } } } } Key::Index(idx) => match { c } { &mut SerdeYaml::Sequence(ref mut a) => { runup_array_or_value(a, idx, i, last_key_index, v) } c @ &mut SerdeYaml::String(_) | c @ &mut SerdeYaml::Number(_) | c @ &mut SerdeYaml::Bool(_) | c @ &mut SerdeYaml::Null | c @ &mut SerdeYaml::Mapping(_) => { let mut a = Vec::new(); runup_array_or_value(&mut a, idx, i, last_key_index, v); drop(mem::replace(c, SerdeYaml::Sequence(a))); if i == last_key_index { return; } match c { SerdeYaml::Sequence(ref mut a) => { a.get_mut(idx).expect("previous insertion") } _ => unreachable!(), } } }, } } } } fn remove(&mut self, keys: &[Self::Key]) { let mut c = self; let last_key_index = keys.len().checked_sub(1).expect("at least one key"); for (i, k) in keys.iter().enumerate() { c = match *k { Key::String(ref k) => { let k = from_str(&k); match { c } { SerdeYaml::Mapping(ref mut obj) => { if i == last_key_index { obj.remove(&k); return; } else { match obj.get_mut(&k) { Some(json) => json, None => return, } } } _ => return, } } Key::Index(idx) => match { c } { SerdeYaml::Sequence(ref mut a) => { if i == last_key_index { a.remove(idx); return; } else { match a.get_mut(idx) { Some(json) => json, None => return, } } } _ => return, }, } } } } treediff-4.0.2/src/value/shared.rs000064400000000000000000000007270072674642500151740ustar 00000000000000use std::fmt; /// A representation of all key types typical Value types will assume. #[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd)] pub enum Key { /// An array index Index(usize), /// A string index for mappings String(String), } impl fmt::Display for Key { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Key::String(ref v) => v.fmt(f), Key::Index(ref v) => v.fmt(f), } } } treediff-4.0.2/src/value/yaml_rust.rs000064400000000000000000000170230072674642500157420ustar 00000000000000use super::Key; use crate::traitdef::{Mutable, Value}; use std::mem; use yaml_rust::{yaml::Hash, Yaml, YamlEmitter, YamlLoader}; fn from_str(s: &str) -> Yaml { let mut v = YamlLoader::load_from_str(s) .expect("valid yaml value - we serialized it beforehand after all"); assert_eq!( v.len(), 1, "need exactly one document - multi-document keys are just not possible" ); v.pop().unwrap() } fn to_string(v: &Yaml) -> String { let mut buf = String::new(); YamlEmitter::new(&mut buf) .dump(v) .expect("valid yaml value"); buf[4..].to_owned() } impl Value for Yaml { type Key = Key; type Item = Yaml; fn items<'a>(&'a self) -> Option + 'a>> { match *self { Yaml::String(_) | Yaml::Integer(_) | Yaml::Real(_) | Yaml::Boolean(_) | Yaml::Null | Yaml::Alias(_) | Yaml::BadValue => None, Yaml::Array(ref inner) => Some(Box::new( inner.iter().enumerate().map(|(i, v)| (Key::Index(i), v)), )), Yaml::Hash(ref inner) => Some(Box::new( inner.iter().map(|(k, v)| (Key::String(to_string(k)), v)), )), } } } impl Mutable for Yaml { type Key = Key; type Item = Yaml; fn set(&mut self, keys: &[Self::Key], v: &Self::Item) { if keys.is_empty() { *self = v.clone(); } else { let mut c = self; let last_key_index = keys.len() - 1; let object_or_value = |index| { if index == last_key_index { v.clone() } else { Yaml::Hash(Hash::new()) } }; fn runup_array_or_value<'a>( array: &'a mut Vec, target_index: usize, key_index: usize, last_key_index: usize, v: &Yaml, ) -> &'a mut Yaml { for _ in array.len()..target_index { array.push(Yaml::Null); } let value = if key_index == last_key_index { v.clone() } else { Yaml::Null }; if target_index == array.len() { array.push(value); } else { array[target_index] = value; } &mut array[target_index] }; for (i, k) in keys.iter().enumerate() { c = match *k { Key::String(ref k) => { let k = from_str(&k); match { c } { &mut Yaml::Hash(ref mut obj) => { if obj.contains_key(&k) { let obj = obj.get_mut(&k).expect("map to work"); if i == last_key_index { *obj = v.clone(); return; } obj } else { obj.insert(k.clone(), object_or_value(i)); obj.get_mut(&k).expect("map to work") } } c @ &mut Yaml::String(_) | c @ &mut Yaml::Integer(_) | c @ &mut Yaml::Real(_) | c @ &mut Yaml::Boolean(_) | c @ &mut Yaml::Null | c @ &mut Yaml::Alias(_) | c @ &mut Yaml::BadValue | c @ &mut Yaml::Array(_) => { drop(mem::replace( c, Yaml::Hash({ let mut o = Hash::new(); o.insert(k.clone(), object_or_value(i)); o }), )); if i == last_key_index { return; } match c { Yaml::Hash(ref mut obj) => { obj.get_mut(&k).expect("previous insertion") } _ => unreachable!(), } } } } Key::Index(idx) => match { c } { &mut Yaml::Array(ref mut a) => { runup_array_or_value(a, idx, i, last_key_index, v) } c @ &mut Yaml::String(_) | c @ &mut Yaml::Alias(_) | c @ &mut Yaml::BadValue | c @ &mut Yaml::Integer(_) | c @ &mut Yaml::Real(_) | c @ &mut Yaml::Boolean(_) | c @ &mut Yaml::Null | c @ &mut Yaml::Hash(_) => { let mut a = Vec::new(); runup_array_or_value(&mut a, idx, i, last_key_index, v); drop(mem::replace(c, Yaml::Array(a))); if i == last_key_index { return; } match c { Yaml::Array(ref mut a) => { a.get_mut(idx).expect("previous insertion") } _ => unreachable!(), } } }, } } } } fn remove(&mut self, keys: &[Self::Key]) { let mut c = self; let last_key_index = keys.len().checked_sub(1).expect("at least one key"); for (i, k) in keys.iter().enumerate() { c = match *k { Key::String(ref k) => { let k = from_str(&k); match { c } { Yaml::Hash(ref mut obj) => { if i == last_key_index { obj.remove(&k); return; } else { match obj.get_mut(&k) { Some(json) => json, None => return, } } } _ => return, } } Key::Index(idx) => match { c } { Yaml::Array(ref mut a) => { if i == last_key_index { a.remove(idx); return; } else { match a.get_mut(idx) { Some(json) => json, None => return, } } } _ => return, }, } } } }