im-rc-15.0.0/CHANGELOG.md010064400017500001750000000454061365756323600126670ustar0000000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## [15.0.0] - 2020-05-15 ### Changed - Map iterators now return `(&K, &V)` and `(&K, &mut V)` respectively, to be consistent with `std::collections`'s API. `DiffIter` for `OrdMap` has also changed in the same manner. (#121) ### Removed - The `pool` feature flag has been removed from the `im` version of the crate, as `refpool` no longer supports threadsafe pools. - `HashSet::iter_mut()` has been removed, because if you modify the hashed values in a hash set, you break the hash set. ### Added - The `pool` feature flag was missing from the `im-rc` version of the crate, which is the version where it's actually useful. It's been added now. - `DiffIter` now has a `Debug` implementation. - There is now a `Vector::is_inline()` method to determine whether a `Vector` is currently inlined. (#129) ### Fixed - A smarter implementation of the sorting algorithm for `Vector` has improved the performance of `Vector::sort` by approximately 2x. (#126) ## [14.3.0] - 2020-03-03 ### Changed - `proptest` strategies have been moved to `im::proptest`. The previous locations of the strategies (`im::vector::proptest` etc) are still available, but have been deprecated. ### Added - `OrdSet` and `OrdMap` now have `get_prev` and `get_next` methods (with equivalent `get_prev_mut` and `get_next_mut` methods for `OrdMap`) which will return the closest key match to the requested key in the specified direction if the key isn't in the set. (#95) - The `retain` method, inexplicably missing from `HashMap` but not `HashSet`, has been added. (#120) - The `get_mut` method on `OrdMap` was, equally inexplicably, private. It has now been made public. ## [14.2.0] - 2020-01-17 ### Added - Both map types now have the `get_key_value()` method, corresponding to the equivalent [additions](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.get_key_value) to the standard library. - The `ptr_eq` method has been added to all data types, allowing you to test whether two values refer to the same content in memory, by testing for pointer equality. (#117) - `HashMap` had lost its `Arbitrary` implementation for the `quickcheck` feature flag. It's now been restored. (#118) - Implementations for `Arbitrary` from the [`arbitrary`](https://crates.io/crates/arbitrary/) crate have been added behind the `arbitrary` feature flag. ### Fixed - Fixed a bug when reversing a consuming iterator over a `Vector` by replacing the consuming iterator with a much simpler and slightly more efficient version. (#116) ## [14.1.0] - 2019-12-16 ### Added - If you enable the `pool` feature flag, im now supports constructing data types using [`refpool`](https://crates.io/crates/refpool) to speed up chunk allocation. The performance boost will vary between use cases and operating systems, but generally at least a 10% speedup can be expected when constructing a data type from an iterator, and the more complex an operation is, the more likely it is to benefit from being able to quickly reallocate chunks. Note that in order to use this feature, you have to construct your data types using the `with_pool(&pool)` constructor, it's not enough just to enable the feature flag. ## [14.0.0] - 2019-11-19 ### Changed - As `sized-chunks` now requires a slightly more recent version of `rustc` to compile, specifically version 1.36.0, so does `im`. This is a breaking change, but will of course only affect your code if you're using an older `rustc`. ### Fixed - Fixed a quadratic time worst case scenario in the quicksort implementation for `Vector`. (#101) - Fixed an edge case bug when splitting and joining large `Vector`s. (#105, #107) ## [13.0.0] - 2019-05-18 The minimum supported Rust version is now 1.34.0. ### Changed - `im::iter::unfold` now gives you the owned state value rather than an immutable reference to it, which makes it a little more useful. ### Removed - The deprecated `singleton` constructors have been removed. Please use `unit` instead. - The deprecated methods `Vector::chunks` and `Vector::chunks_mut` have been removed in favour of `Vector::leaves` and `Vector::leaves_mut` respectively. (#50) - The deprecated reference to [`sized-chunks`](https://crates.io/crates/sized-chunks) has been removed. If you need it, please use the `sized-chunks` crate directly. - `im::iter::unfold_mut` has been removed, as there's no meaningful difference between it and rust-std 1.34.0's `std::iter::from_fn` with a captured state variable. ### Fixed - `Vector` now uses [`sized_chunks::InlineArray`](https://docs.rs/sized-chunks/0.3.0/sized_chunks/inline_array/struct.InlineArray.html) instead of an `Empty` enum case to avoid allocation at very small sizes, letting you store a handful of elements on the stack before needing to grow into a full chunk. This has a beneficial effect on performance as well, as there's no pointer into the heap to dereference, making it faster than `std::vec::Vec` in this configuration. - Some complexity timings have been added and corrected. (#87) - `OrdSet::is_subset(&self, other)` now returns immediately when `self` is larger than `other` and thus could not possibly be a subset of it. (#87) ## [12.3.4] - 2019-04-08 ### Changed - `Clone` constraints have been further relaxed on maps and sets, so that you can now lookup and iterate over them without requiring a `Clone` constraint (though you do still need `Clone` to actually insert data into them to lookup or iterate over). (#81) ### Fixed - Enforces the latest bugfix release of sized-chunks. (#78) - Another edge case bugfix to `Vector`'s size table handling. (#79) ## [12.3.3] - 2019-03-11 ### Fixed - A number of issues were fixed where `Vector`'s size table would get out of sync with the node structure if exercised too much and cause erroneous behaviour. (#72, #74) - Comprehensive generative tests were added to test all data structures through more unexpected code paths. ## [12.3.2] - 2019-03-05 ### Changed - `Clone` constraints on all data structures, as well as relevant constraints on maps and sets, have been relaxed where possible, so that you can now construct empty instances and call most query methods without requiring values implement `Clone` etc. (#63) ### Fixed - Constructing an empty `Vector` will not allocate any heap memory, instead deferring allocation until you perform an operation that would increase its length. (#65) - Some bugs arising when using `Vector::append` repeatedly were fixed. (#67, #70) ## [12.3.1] - 2019-02-19 ### Changed - Unsafe chunks have been separated out into the `sized-chunks` crate, which is now a dependency of `im`. ## [12.3.0] - 2019-01-15 ### Added - `singleton` methods have been deprecated and renamed to `unit`. - `Vector::chunks` and `Vector::chunks_mut` have been deprecated and renamed to `leaves` and `leaves_mut` to avoid confusion with `Vec::chunks`. (#50) ### Fixed - Fixed an issue where the `HashMap` draining iterator might access uninitialised memory leading to undefined behaviour. (#60) - Fixed multiple issues in `Vector::split_off` and `Vector::append` that would cause lookup errors and unexpectedly unbalanced trees. (#55). ## [12.2.0] - 2018-10-12 ### Added - `OrdMap` and `OrdSet` now have a `range()` method which makes an iterator over a bounded subset of the values. The improved iterator implementation is also considerably more efficient than the previous (about an order of magnitude faster for nontrivial data sets). `iter()` has been updated to take advantage of this, and is now just an alias for `range(..)`. (#27) - `FocusMut` now has an `unmut` method to turn it into an immutable `Focus`, releasing its exclusive hold on the underlying `Vector`. - `Focus` now implements `Clone`. ## [12.1.0] - 2018-09-25 ### Added - Maps and sets now have the `clear` method just like `Vector`. (#46) ### Changed - Single chunk `Vector`s are no longer allocated directly on the stack, meaning that they're now comparable in performance to `std::vec::Vec` rather than slightly faster, but they also won't eat up your stack space quite as quickly, and they'll clone without copying and share structure with clones as you'd expect. ## [12.0.0] - 2018-08-30 Starting with this release, the `arc` flag is gone, in favour of publishing `im` as two separate crates: `im` (using `Arc`) and `im-rc` (using `Rc`). They're identical (and built from the same code), except that `im` is thread safe and `im-rc` is a little bit more performant. This is a major release as a consequence, but there should be no breaking code changes other than the new default choice of reference counter. ### Added - The `Chunk` datatype that's used to build `Vector` and `OrdMap` has been exposed and made generally usable. It's somewhere between a [`GenericArray`](https://crates.io/crates/generic-array) and a ring buffer, offers O(1)\* push in either direction, and is generally hyperoptimised for its purpose of serving as nodes for Bagwell tries, but it's also a powered up version of [`GenericArray`](https://crates.io/crates/generic-array) that might be useful to others, hence the public API. - `Vector` now has `Focus` and `FocusMut` APIs for caching index lookups, yielding huge performance gains when performing multiple adjacent index lookups. `Vector::iter` has been reimplemented using this API, and is now much simpler and about twice as fast as a result, and `Vector::iter_mut` now runs nearly an order of magnitude faster. Likewise, `Vector::sort` and `Vector::retain` are now using `FocusMut` and run considerably faster as a result. - `Focus` and `FocusMut` can also be used as stand ins for subslices through the `narrow` and `split_at` methods. You can also iterate over foci, making this the most efficient way to iterate over a subset of a `Vector`. - `Vector` now implements [Rayon](https://crates.io/crates/rayon)'s parallel iterators behind the `rayon` feature flag. ### Changed - As `std::ops::RangeBounds` is now stabilised in Rust 1.28, the `Vector::slice` method is now unconditionally available on the stable channel. - Union/difference/intersection/is_submap methods on `HashMap` and `OrdMap` that take functions now take `FnMut` instead of `Fn`. This should not affect any existing code. (#34) - `Vector::split_off` can now take an index equal to the length of the vector, yielding an empty vector as the split result. (#33) - `Vector::set` now returns the replaced value. ### Fixed - `Vector` is now represented as a single inline chunk until it grows larger than the chunk size, making it even faster than `Vec` at small sizes, though `clone` could now be slower if the clone is expensive (it's still absurdly fast for `A: Copy`). ## [11.0.1] - 2018-07-23 ### Fixed - Various performance improvements, amounting to a 5-10% speedup for both kinds of map/set. - Fixed an edge case bug in `sort::quicksort`. ## [11.0.0] - 2018-07-10 ### Changed This is a major release with many breaking changes, and is intended to stabilise the API more than to denote that the rewrite is now production ready. You should expect future releases with significant performance improvements as well as additional APIs, but there should be no further major release with breaking changes in the immediate future, barring very serious unforeseen issues. Specifically, you should expect imminent minor releases with performance improvements for `Vector` and `OrdMap`, for which I have a number of known optimisations that remain unimplemented. #### No More `Arc` All data structures have been reworked to take values of `A: Clone` instead of `Arc`, meaning that there's less performance overhead (as well as mental overhead) when using values that clone cheaply. The performance gain when values are `A: Copy` is a factor of two or more. It's expected that users should wrap values in `Arc` themselves when using values which are expensive to clone. Data structures still use reference counters internally to reference nodes, but values are stored directly in the nodes with no further indirection. This is also good for cache locality. Data structures now use `Rc` instead of `Arc` by default to do reference counting. If you need a thread safe version that implements `Send` and `Sync`, you can enable the `arc` feature on the package to compile with `Arc` instead. #### `std::collections` Compatible API The API has been reworked to align more closely with `std::collections`, favouring mutable operations by default, so that operations that were previously suffixed with `_mut` are now the standard operations, and immutable operations which return a modified copy have been given different names altogether. In short, all your code using previous versions of this library will no longer work, and if it was relying heavily on immutable operations, it's recommended that you rewrite it to be mutable by preference, but you should generally be able to make it work again by using the new method names for the immutable operations. Here is a list of the most notable changed method names for maps and sets: | Previous immutable | Current immutable | Previous mutable | Current mutable | | ------------------ | ----------------- | ---------------- | --------------- | | `insert` | `update` | `insert_mut` | `insert` | | `remove` | `without` | `remove_mut` | `remove` | | `pop` | `extract` | `pop_mut` | `remove` | You should expect to be able to rewrite code using `std::collections::HashMap` and `std::collections::BTreeMap` with minimal or no changes using `im::HashMap` and `im::OrdMap` respectively. `Vector` has been completely rewritten and has an API that aligns closely with `std::collections::VecDeque`, with very few immutable equivalents. It's expected that you should use `Vector::clone()` to take a snapshot when you need it rather than cause an implicit clone for each operation. (It's still O(1) and practically instant.) I'm considering adding back some of the immutable operations if I can come up with good names for them, but for now, just `clone` it if you need it. #### RRB Vector `Vector` is now implemented as an [RRB tree](https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf) with [smart head/tail chunking](http://gallium.inria.fr/~rainey/chunked_seq.pdf), obsoleting the previous [Hickey trie](https://hypirion.com/musings/understanding-persistent-vector-pt-1) implementation. RRB trees have generally similar performance characteristics to the Hickey trie, with the added benefit of having O(log n) splitting and concatenation. | Operation | RRB tree | Hickey trie | Vec | VecDeque | | --------------- | -------- | ----------- | ------ | -------- | | Push front | O(1)\* | O(log n) | O(n) | O(1)\* | | Push back | O(1)\* | O(log n) | O(1)\* | O(1)\* | | Pop front | O(1)\* | O(log n) | O(n) | O(1)\* | | Pop back | O(1)\* | O(log n) | O(1) | O(1)\* | | Lookup by index | O(log n) | O(log n) | O(1) | O(1) | | Split | O(log n) | O(log n) | O(n) | O(n) | | Join | O(log n) | O(n) | O(n) | O(n) | (Please note that the timings above are for the `im` version of the Hickey trie, based on the [Immutable.js](https://facebook.github.io/immutable-js/) implementation, which performs better than the original Clojure version on splits and push/pop front, but worse on push/pop back). The RRB tree is the most generally efficient list like data structure currently known, to my knowledge, but obviously it does not and cannot perform as well as a simple `Vec` on certain operations. It makes up for that by having no operations you need to worry about the performance complexity of: nothing you can do to an RRB tree is going to be more expensive than just iterating over it. For larger data sets, being able to concatenate (and, by extension, insert and remove at arbitrary locations) several orders of magnitude faster than `Vec` could also be considered a selling point. #### No More `CatList` And `ConsList` `CatList` has been superseded by `Vector`, and `ConsList` was generally not very useful except in the more peculiar edge cases where memory consumption matters more than performance, and keeping it in line with current API changes wasn't practical. #### No More Funny Words Though it breaks my heart, words like `cons`, `snoc`, `car`, `cdr` and `uncons` are no longer used in the `im` API, to facilitiate closer alignment with `std::collections`. Even the `head`/`tail` pair is gone, though `head` and `last` remain as aliases for `front` and `back`. ## [10.2.0] - 2018-04-15 ### Added - Map/set methods which accept references to keys will now also take any value that's borrowable to the key's type, ie. it will take a reference to a type `Borrowable` where the key implements `Borrow`. This is particularly handy for types such as `String` because you can now pass `&str` to key lookups instead of `&String`. So, instead of the incredibly cumbersome `map.get(&"foo".to_string())` you can just do `map.get("foo")` when looking up a mapping for a string literal. ## [10.1.0] - 2018-04-12 ### Added - `Vector`, `OrdMap` and `HashMap` now implement `Index` and `IndexMut`, allowing for syntax like `map[key] = value`. - Added `cons`, `snoc`, `uncons` and `unsnoc` aliases where they were missing. - Everything now implements `Sum` and `Extend` where possible. ### Changed - Generalised `OrdMap`/`OrdSet`'s internal nodes so `OrdSet` now only needs to store pointers to its values, not pairs of pointers to value and `Unit`. This has caused `OrdMap/Set`'s type constraints to tighten somewhat - in particular, iteration over maps/sets whose keys don't implement `Ord` is no longer possible, but as you would only have been able to create empty instances of these, no sensible code should break because of this. - `HashMap`/`HashSet` now also cannot be iterated over unless they implement `Hash + Eq`, with the same note as above. - Constraints on single operations that take closures on `HashMap` and `OrdMap` have been relaxed from `Fn` to `FnOnce`. (Fixes #7.) ### Fixed - Hashes are now stored in `HashMap`s along with their associated values, removing the need to recompute the hash when a value is reordered inside the tree. ## [10.0.0] - 2018-03-25 ### Added This is the first release to be considered reasonably stable. No changelog has been kept until now. im-rc-15.0.0/CODE_OF_CONDUCT.md010064400017500001750000000062321365756323600136470ustar0000000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at admin@immutable.rs. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org im-rc-15.0.0/Cargo.toml0000644000000042011365756330200102310ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "im-rc" version = "15.0.0" authors = ["Bodil Stokke "] build = "./build.rs" description = "Immutable collection datatypes (the fast but not thread safe version)" homepage = "http://immutable.rs/" documentation = "http://immutable.rs/" readme = "../../README.md" keywords = ["immutable", "persistent", "hamt", "b-tree", "rrb-tree"] categories = ["data-structures"] license = "MPL-2.0+" repository = "https://github.com/bodil/im-rs" [package.metadata.docs.rs] all-features = true [lib] path = "./src/lib.rs" [dependencies.arbitrary] version = "0.4" optional = true [dependencies.bitmaps] version = "2" [dependencies.proptest] version = "0.9" optional = true [dependencies.quickcheck] version = "0.9" optional = true [dependencies.rand_core] version = "0.5.1" [dependencies.rand_xoshiro] version = "0.4" [dependencies.rayon] version = "1" optional = true [dependencies.refpool] version = "0.4" optional = true [dependencies.serde] version = "1" optional = true [dependencies.sized-chunks] version = "0.6" [dependencies.typenum] version = "1.12" [dev-dependencies.metrohash] version = "1" [dev-dependencies.pretty_assertions] version = "0.6" [dev-dependencies.proptest] version = "0.9" [dev-dependencies.proptest-derive] version = "0.1" [dev-dependencies.rand] version = "0.7" features = ["small_rng"] [dev-dependencies.rayon] version = "1" [dev-dependencies.serde] version = "1" [dev-dependencies.serde_json] version = "1" [build-dependencies.version_check] version = "0.9" [features] debug = [] pool = ["refpool", "sized-chunks/refpool"] [badges.travis-ci] repository = "bodil/im-rs" im-rc-15.0.0/Cargo.toml.orig010064400017500001750000000025201365756323600137330ustar0000000000000000[package] name = "im-rc" version = "15.0.0" edition = "2018" authors = ["Bodil Stokke "] license = "MPL-2.0+" description = "Immutable collection datatypes (the fast but not thread safe version)" repository = "https://github.com/bodil/im-rs" documentation = "http://immutable.rs/" homepage = "http://immutable.rs/" readme = "../../README.md" categories = ["data-structures"] keywords = ["immutable", "persistent", "hamt", "b-tree", "rrb-tree"] build = "./build.rs" [package.metadata.docs.rs] all-features = true [lib] path = "./src/lib.rs" [badges] travis-ci = { repository = "bodil/im-rs" } [features] pool = ["refpool", "sized-chunks/refpool"] debug = [] [build-dependencies] version_check = "0.9" [dependencies] typenum = "1.12" bitmaps = "2" sized-chunks = "0.6" rand_core = "0.5.1" rand_xoshiro = "0.4" quickcheck = { version = "0.9", optional = true } proptest = { version = "0.9", optional = true } serde = { version = "1", optional = true } rayon = { version = "1", optional = true } refpool = { version = "0.4", optional = true } arbitrary = { version = "0.4", optional = true } [dev-dependencies] proptest = "0.9" serde = "1" serde_json = "1" rayon = "1" rand = { version = "0.7", features = ["small_rng"] } pretty_assertions = "0.6" metrohash = "1" proptest-derive = "0.1" ["package.metadata.docs.rs"] version_check = "0.9" im-rc-15.0.0/LICENCE.md010064400017500001750000000362761365756323600124470ustar0000000000000000Mozilla Public License Version 2.0 ================================== ### 1. Definitions **1.1. “Contributor”** means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. **1.2. “Contributor Version”** means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. **1.3. “Contribution”** means Covered Software of a particular Contributor. **1.4. “Covered Software”** means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. **1.5. “Incompatible With Secondary Licenses”** means * **(a)** that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or * **(b)** that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. **1.6. “Executable Form”** means any form of the work other than Source Code Form. **1.7. “Larger Work”** means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. **1.8. “License”** means this document. **1.9. “Licensable”** means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. **1.10. “Modifications”** means any of the following: * **(a)** any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or * **(b)** any new file in Source Code Form that contains any Covered Software. **1.11. “Patent Claims” of a Contributor** means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. **1.12. “Secondary License”** means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. **1.13. “Source Code Form”** means the form of the work preferred for making modifications. **1.14. “You” (or “Your”)** means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means **(a)** the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or **(b)** ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. ### 2. License Grants and Conditions #### 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: * **(a)** under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and * **(b)** under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. #### 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. #### 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: * **(a)** for any code that a Contributor has removed from Covered Software; or * **(b)** for infringements caused by: **(i)** Your and any other third party's modifications of Covered Software, or **(ii)** the combination of its Contributions with other software (except as part of its Contributor Version); or * **(c)** under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). #### 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). #### 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. #### 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. #### 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. ### 3. Responsibilities #### 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. #### 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: * **(a)** such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and * **(b)** You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. #### 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). #### 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. #### 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. ### 4. Inability to Comply Due to Statute or Regulation If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: **(a)** comply with the terms of this License to the maximum extent possible; and **(b)** describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. ### 5. Termination **5.1.** The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated **(a)** provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and **(b)** on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. **5.2.** If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. **5.3.** In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ### 6. Disclaimer of Warranty > Covered Software is provided under this License on an “as is” > basis, without warranty of any kind, either expressed, implied, or > statutory, including, without limitation, warranties that the > Covered Software is free of defects, merchantable, fit for a > particular purpose or non-infringing. The entire risk as to the > quality and performance of the Covered Software is with You. > Should any Covered Software prove defective in any respect, You > (not any Contributor) assume the cost of any necessary servicing, > repair, or correction. This disclaimer of warranty constitutes an > essential part of this License. No use of any Covered Software is > authorized under this License except under this disclaimer. ### 7. Limitation of Liability > Under no circumstances and under no legal theory, whether tort > (including negligence), contract, or otherwise, shall any > Contributor, or anyone who distributes Covered Software as > permitted above, be liable to You for any direct, indirect, > special, incidental, or consequential damages of any character > including, without limitation, damages for lost profits, loss of > goodwill, work stoppage, computer failure or malfunction, or any > and all other commercial damages or losses, even if such party > shall have been informed of the possibility of such damages. This > limitation of liability shall not apply to liability for death or > personal injury resulting from such party's negligence to the > extent applicable law prohibits such limitation. Some > jurisdictions do not allow the exclusion or limitation of > incidental or consequential damages, so this exclusion and > limitation may not apply to You. ### 8. Litigation Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. ### 9. Miscellaneous This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. ### 10. Versions of the License #### 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. #### 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. #### 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). #### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. ## Exhibit A - Source Code Form License Notice This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. ## Exhibit B - “Incompatible With Secondary Licenses” Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. im-rc-15.0.0/README.md010064400017500001750000000013351365756323600123260ustar0000000000000000# im-rs Blazing fast immutable collection datatypes for Rust. Comes in two versions: [`im`](https://crates.io/crates/im) (thread safe) and [`im-rc`](https://crates.io/crates/im-rc) (fast but not thread safe). ## Documentation * [API docs](https://docs.rs/im/) ## Licence Copyright 2017 Bodil Stokke This software is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ## Code of Conduct Please note that this project is released with a [Contributor Code of Conduct][coc]. By participating in this project you agree to abide by its terms. [coc]: https://github.com/bodil/im-rs/blob/master/CODE_OF_CONDUCT.md im-rc-15.0.0/build.rs010064400017500001750000000015061365756323600125140ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::env; fn main() { println!("cargo:rerun-if-changed=build.rs"); if let Some(channel) = version_check::Channel::read() { if channel.supports_features() { println!("cargo:rustc-cfg=has_specialisation"); } } let pkgname = env::var("CARGO_PKG_NAME").expect("Cargo didn't set the CARGO_PKG_NAME env var!"); let test_rc = env::var("IM_TEST_RC").is_ok(); match pkgname.as_str() { "im" => { if !test_rc { println!("cargo:rustc-cfg=threadsafe") } } "im-rc" => {} _ => panic!("unexpected package name!"), } } im-rc-15.0.0/proptest-regressions/hash/map.txt010064400017500001750000000060521365756323600175320ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. xs 3591451162 2655640551 804983804 3307909230 # shrinks to ref m = {-13697: 30985, 1338: 29274, -14139: -4092, 673: -19662, -19198: 333, 9155: -4794, -24816: -12851, 14658: -17795, 23662: -25253, -4783: -12972, -31711: -1639, -26495: 16710, -7087: -26434, 18175: -4121, 5045: 8040, -23549: 17012, 6304: -7492, -23305: -28186, 606: 8452, -15872: 2415, 17913: 2306, -20500: 28581} xs 1457767450 3825624317 1539332905 3279740856 # shrinks to ref m = {7136: -9742, -7547: 13954, -15860: 17017, -31620: -15850, 25480: -13526, 9943: -13939, 1142: 22444, 20378: -26706, -10165: -14641} xs 2468731224 2159341902 336190467 4018852179 # shrinks to ref m = {22114: -20101, -30886: -4356, 29938: 40, 6256: -29990, 8450: -21821, 30253: 901, -10781: -24620, 22431: 593} xs 1344206258 166909451 3875523340 3155104601 # shrinks to ref m = {25488: 22186, -4852: 28282, -5097: 4497, 29501: 8087, -29096: -18313, 22286: -17383, 30624: 25063, -2270: -1319, 31014: -28777, 23935: 1507} xs 2403854785 21349881 2962261870 427550728 # shrinks to ref pairs = [(-17914, 0), (16838, 0)] xs 1508395022 1122347352 4113209817 3965614759 # shrinks to ref m = {0: 0, 1: 0} xs 1627474128 2843908894 3937915137 1370561421 # shrinks to ref input = {0: 0}, index_rand = 0 xs 1863744963 3828268266 3976454353 1279901501 # shrinks to ref m = {1033: ",¦⾘f\u{b}C\u{bae94}}$n\"\u{fc28d}\u{feff}\u{b}-", 2568: "\u{8db77}ꖽ\r\u{7af7f}�7\u{a7bf3}\u{393b9}\u{0}G\u{8}\'%5E\u{cd0dc}?\u{ba311}%\u{ee814}Ѩ\\\u{80aa1}", 3527: "\u{41005}\u{41ff0}$`,L&%\u{1b}~\u{36ada}", 3577: "\u{feff}5\u{109dd9}:\u{8}\u{3}𬃹\u{3c2b6}\\\"5𡂏\'\u{feff}%\u{b8c12}?", 4544: "0*8🕴�\u{33669}\r\"\u{92011}𮡱<\u{0}<\u{1}$\u{1},\u{f1234}{G\u{1b}J\u{ceaa4}\\", 4560: "🕴\r\tѨ@\u{edbda}\u{1b}t�\u{b}\u{2}�ò\u{80090}.\'\u{34690}g%Ѩ\u{0}=\u{1}", 7113: "*", 7944: "¨\u{b6d08}$🕴&{H\rUi\u{feff}\u{0}.¥ô{_*\u{d73fc}:Ѩf`2.*\u{c9c6c}", 8738: "%𬊢*:Ä\u{90}\u{b}\u{48d7b}\"\u{4}"} xs 1567907912 1646837549 2298759549 1787615177 # shrinks to ref pairs = [(-28601, 0), (2569, 0), (-3384, 0), (5639, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (-30583, 0), (0, 0), (-154, 0), (-27, 0), (105, 0), (-29, 0), (9, 0), (9, 0), (-508, 0), (-478, 0), (-4095, 0), (-2017, 0), (-130, 0), (27145, 0), (2345, 0), (3241, 0), (458, 0), (-6211, 0), (361, 0), (-4772, 0), (-7717, 0), (4265, 0), (-1144, 0)] xs 2574157460 1821361166 2171243272 102290569 # shrinks to ref pairs = [(0, 0), (7, 0), (7, 0), (2055, 0), (0, 0), (-9530, 0), (0, 0), (6, 0), (6, 0), (0, 0), (6, 0), (0, 0), (0, 0), (0, 0), (0, 0), (-11133, 0), (-161, 0), (-2, 0), (-2051, 0), (-3111, 0), (-2092, 0), (0, 0), (24131, 0), (-5278, 0), (6, 0), (70, 0), (0, 0), (6, 0), (6, 0), (-31, 0), (-3492, 0), (-2373, 0), (8902, 0), (-2438, 0), (3014, 0), (7206, 0), (6854, 0), (15161, 0), (-699, 0)] im-rc-15.0.0/proptest-regressions/hash/set.txt010064400017500001750000000016601365756323600175500ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. xs 4213962225 2884706512 1606470227 2259275645 # shrinks to ref s = {"\\\u{4}\u{b}\u{c7afb}Q$x/\u{1a4f0}\u{1}\u{399ac}$.\u{0}=J>\"\u{2}=\t\t*q乣\'?6\u{ca350}\u{a20b5}", "\u{b50f2}$", "\u{de54f}/¥\u{1b}{*\"¥*:\\\u{e77d2}*s`?\u{3}/\u{9daa7}\t\u{1b}\":\'\u{7cf05}G🕴j", "\u{a2848}\u{bf244}.$=d\u{51d0f}¥\u{98d35}\u{3457c}<`𖡒{\"k�\t.$u\u{0}.", "!`", "\u{4}\u{9c2d9}r\u{d33a9}¥쇛\u{cd875}\u{7f}\\\u{37b37}`\u{b}\ruR\r\t\u{8aaa0}\\&`\u{b}\u{feff}\u{b868c}\u{a976e}\u{0}\\X\u{514dd}&k", "\u{feff}🕴M", "\u{b162a}S\u{6}\"\r\u{4b435}🕴 \\\u{b16df}\'\u{3468e}\\", "÷/\\\u{4dfaf}\u{7f}*\u{47f16}\"�aZ\r(Tj\u{1b}记\t;¥*<\u{1b}E\u{8d037}"} im-rc-15.0.0/proptest-regressions/ord/map010064400017500001750000001546421365756323600165660ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. xs 1087347487 1450735596 3800950698 1648897824 # shrinks to ref m = {29894: -24214, -22768: -29852, -25204: 19090, -22710: 4694, -27608: 14656, -27740: 29393, 7285: -78, -3041: 77, 20980: 467, 13472: 3518, 2845: -9597, 6987: -29072, -30486: 827, -1022: 15821, 22068: -24552, 6293: -21073, -7161: 10155, 3791: -27929, 6361: 15318, 3190: 30164, 31756: 4331, 11824: 30151, -14319: -451, -17781: -5693, -5991: 372, -27192: -2983, 23456: 21711, -19546: 28578, -9753: 30988, 21193: 22302, 432: 24303, -15110: 26679, -11612: -6722, 12373: -31848, -20837: -16031, 25861: -12660, -23775: 32410, -6760: 25269, 21702: -26852, -17649: 27279, -12789: -28758, -26032: 6316, -16837: -16182, 31817: -24478, -3564: -20084, -5315: 23517, 11955: -29343, 9175: -4003, 20615: -19515, -3453: 24768, -28231: 3065, 10336: -24811, -8978: 17861, 23428: 19571, -450: 14904, -5293: -12205, -15735: -13395, 12747: -25893, 29368: 14652, 16863: -31998, 29612: 2394, 3212: 4512, -2804: 16628, -9070: 2599, -8946: -6150, 22872: -15322, -12672: 22236, 8415: -22569, 18541: -20698, 12395: -11080, -3888: -6244, -4893: 21952, -3595: 16707, 11722: -9301, 23547: 8317, -10052: -5551, -8428: -1168, -6805: 1438, 6185: 27026, 9265: 14429, -7016: -19640, 4739: 28713, 27505: -9101, -21379: 11843, 10141: 26568, -27662: -7672, -5384: -15814, -31927: 23347, 28068: -13380, -3075: 11627, -28778: 26949, 821: 22814, 11572: 16591, -10426: 5726, -14986: 6492, -4472: -12187, -22049: -18715, 3822: -26724, -13821: 24964, 14780: 23541, -26068: -17472, 6419: -16387, -21443: -32036, -27285: -11138, -12544: -22185, -25942: -22158, 8799: 22607, 22203: 23175, -29997: 9170, 18341: -19711, -25162: -29851, 29377: -4845, -4337: -3624, -30764: 13318, 2000: 6862, 13510: 4642, 25068: -1590, 16270: -1390, -23439: 16616, -13611: 30094, 10084: -30492, -6677: 12289, 28032: -21767, 10105: 8774, 627: 24722, 27190: 3954, -26665: -7354, 27566: -8037, 15625: -9453, -30151: -25954, -28349: 30379, -6142: 691, -9262: 24633, 27808: -5306, 11490: -10950, 22022: -705, 7283: -7208, 29941: 6208, -4204: -2121, -9279: 17669, -4498: -4582, -4833: 29055, -22069: 27589, 32004: -31982, 4036: 11622, -5971: 6511, 7362: -31402, 2132: 16965, -17605: 3529, 16899: -16958, 20305: -26766, 18755: 21882, 13064: -29474, 1391: -25296, 9071: -8029, -20305: 30895, 167: 21243, 23450: -32278, -22095: 13405, 12963: 18120, 24666: 28046, 14320: 8050, 30437: -12581, 17277: 15852, -19808: -27963, -23409: 24638, 29401: 15328, -21257: -3018, 28299: 29000, 18823: -8987, 15409: 9114, -2476: -12749, 5807: -25088, -17559: 19530, -3994: 32042, -23994: 11576, 17613: -11312, 24203: 30135, 14421: 29461, -8181: 17641, 6171: -20014, 31027: 1105, 20177: 11742, 28023: 10685, -5413: 22256, -29512: -27827, 26068: -31380, 10750: 9166, -19988: 26137, 6165: -12868, -9662: 15887, 12809: -12054, 25972: 23426, -3522: 11010, -13516: 10518, -20198: 8172, -20051: -21390, 17149: 27954, -25908: -3999, 22600: -21800, -15240: -21275, -12894: -31550, 11168: 6165, 1471: -30312, 25562: 31867, -3575: -5407, 16896: -21901, -31594: -2825, 24966: -2987, 31931: 19139, -671: 16835, -13289: 32113, -7420: -21883, -26225: -29508, 14029: -23627, 13600: 7738, 19823: 22879, -7278: -31931, -18518: -15028, -24285: 15271, 30158: -6041, -7778: -10728, 18967: -9084, 12216: 15282, 7667: -29473, -29079: 5065, 28475: 262, 9873: 455, 14700: 2632, -6257: 15024, 2641: -23165, 25766: -21115, 30853: -8411, 24163: -4764, -30666: 17364, -14056: 31344, -16470: -21166, 7863: -28957, 28281: -15377, 4107: -8950, -9388: -32765, 24227: -9133, -10558: 13655, 23295: 9762, -3019: -27437, 11095: 29763, 10609: 12051, -19079: 16494, -638: -5842, 4362: 27932, 2639: -25626, -3030: -14761, 21408: -18773, -21262: -4491, -5008: 1094, -11589: -2784, 15655: 29651, -19013: -9552, 7540: -28066, 18000: 17054, 29752: 18144, 28226: 27155, -12924: 7241, 22083: 13808, -18448: -3080, 29456: 16400, 53: -12710, -1221: 30244, -16504: 24240, 5545: -27714, -20630: -18870, -21090: 28104, 4959: 12418, -15608: 1794, -23432: -22218} xs 2470012874 1108569466 2705233914 2105395150 # shrinks to ref m = {-26536: -10140, -31941: 2328, -23547: -9253, -28157: -17639, -2098: -25615, 9417: -4376, 5027: 16722, 17121: -24663, 8128: -25969, 25933: 18490, -25489: 10837, -13402: 29678, 31055: 14092, -3811: 19345, 3565: -15536, 8160: 25591, 21133: -5677, 31382: -12602, -4552: -6140, 23595: 6118, -5496: 2443, 25445: -32364, 1737: -5168, -9077: -15214, 7942: -27346, 503: 29459, 30229: 31798, -21623: -984, -20767: 1391, -20732: -5138, 179: -2480, -30700: 32256, 23991: -29242, 5811: -2677, 8242: -19246, 14001: 121, 23994: 15968, 16850: 22675, 27403: 20078, 28998: 29713, -18285: -28709, 15265: -345, -2024: -7961, -26394: -16075, -15563: -14632, 3611: -4743, -16600: 8421, 9494: 30533, -26355: -7995, -31604: 15030, -28372: -30678, -1460: 4493, 12812: 6867, 3327: 5994, -27683: -25261, -6712: 14346, 20460: 1089, 10960: 1352, 24869: -29446, -8174: 30195, 24471: -27707, 26252: 15759, -17935: 12699, -19327: 31902, 10672: -17255, -3178: -31772, 14367: 13488, 9093: 13209, -20473: -9178, -31120: 3147, -5795: -3982, -24184: 19687, -8033: 16211, -12944: 8417, -9993: 4190, 2100: 30585, -1397: -27306, 68: -17544, 12442: -4284, 7519: -12190, 22795: -29312, -21157: -16782, -32441: -15527, 3210: -4247, 32108: 9123, 24488: 25516, 11162: -10170, -19251: -2295, -28559: -4773, 31985: 172, -227: 30045, -2104: 26418, -3076: 15669, 14672: 12100, 7576: -13667, -5021: -32276, 21621: 29212, 13537: -19166, -2389: 8930, -4556: -31064, -10630: 3433, 29934: 12298, 6640: -32416, 29552: -6676, 2449: 9495, -20587: -24712, -12359: 29691, -26177: -31729, 4421: -9542, -9965: 7463, 28677: 26334, -27845: -6260, 13285: 11380, 32752: -20965, 15706: -17233, 29886: 13339, 17438: -28315, 26609: 30547, 15151: -15429, -2919: -19952, 16934: -32480, 26615: 24385, 233: -32369, -10268: -10139, 29343: -30102, -15885: 30182, 15822: 25778, -26549: -2360, 2001: -4014, -12019: -1196, 731: 29634, -29995: -22547, -15831: -27743, 1976: -14216, 24671: 21678, -10275: -5156, 28289: 17246, 12893: -32150, -16308: 7767, 5729: 11546, 18882: -31578, -4231: 18279, -25379: -31185, -1139: -16861, -18054: -8385, -31606: -23236, 21235: 7426, -6400: -7360, -8606: -2630, -22484: -11090, 15370: -5085, 5679: -17878, -28308: -24539, 9009: -24480, -16109: -19862, -20544: -20765, -6411: -28066, 11890: 21190, 4579: -7721, -22198: -22517, 338: -4143, 12184: -11969, -15946: -24141, -23654: 2485, 9886: -26974, 11733: 28587, -8243: -20115, 13309: 31556, -14397: -19926, 29872: 19550, -4716: -14669, 16769: 14751, 8353: 18931, -22070: -5371, 24224: -26199, 24823: -30739, 9421: -13020, 19874: -2767, -10193: 2881, 6660: 1643, -31321: -16602, -12356: -8592, 7484: 15900, 4220: 7816, 2781: -7331, 17673: 7955, 21734: -2072, -4406: -26944, -2747: 17863, 4584: -2492, 31654: 15772, -10883: 4363, -3737: 3686, -18179: 30440, 18460: 23217, -3702: 15120, 14407: -18596, 7749: -11497, -27197: 12065, 15409: 18406, 1457: 4533, 24941: 24486, 12520: -29147, 9179: 31948, -14078: -21063, -22741: -21277, 29691: 24484, 13093: 30490, 11422: -28999, 19850: 28538, 58: -1946, 26401: -32289, 16997: -26844, -23467: -28453, 24138: -6868, -14289: 2223, -3164: -12604, -24071: -11711, 6645: -19591, 17685: 9616, -29576: 31095, 15812: -19219, -30119: 20657, -9465: -20600, 5077: 19208, -10326: 3699, 27078: -4075, -7152: 28943, 14558: -22676, -10615: 31120, 29487: 29114, -6096: -1001, 5941: -21634, -30352: 30888, 582: -23140, 16391: 7248, 25557: -14944, 21501: 18193, 11316: 11352, 18183: 17500, -18516: 2584, -2107: -32422, -8402: 12344, -17372: 11869, -15723: 2627, -1765: 19581, 2975: 1, -5867: 23341, 25489: -2444, 9809: 21415, 29497: -18101, -25328: 28247, 9621: -3108, 28275: 8915, 6846: 3451, 28008: 18058, 6195: 10677, 12779: 1341, 13248: 30900, -18786: 27113, -26425: 9293, 16195: 8935, -2461: -16811, -31431: 4635, -9480: 779, -22487: 19715, -15600: -8938, 29782: -1315, 8079: -27635, 3322: 10561, -23910: -4240, -10716: 3872, 12155: -11450, -23322: -27745, 3206: 9309, -23080: 1961, 6761: -31058, 28940: -20745, -29586: -5915, -9310: -8874, 23578: -31849, -24336: 2811, -31640: 13432, 17145: 4078, -10857: 25423, -28879: 7602, 8971: -12084, -19239: 2917, -32289: 12788, 10482: -26779, 7196: 18090, 17174: -28319, -16874: -29949, -10772: 15992, -1774: 239, 5296: -15898, -8433: 14050, -12827: 28010, 29685: -21923, -4742: 18358, -9399: 13522, -3136: 23448, 9803: -30280, 4633: 9138, 22129: -3054, -24759: -3027, 13549: -10895, 770: 13115, -22180: -30951, 26425: 26303, 15351: -14655, -2361: 9031, 21063: -15719, 26334: -23261, 1253: 4242, 21284: -31915, -16220: 4816, 957: -25495, -454: 18872, 8183: 8829, -21137: -20303, -6282: 12896, -23187: 23, -32053: 21416, -924: -16666, -30888: 11634, 31358: 22911, -6028: -984, -28864: 9371, 28554: 18962, 13368: -9926, 25395: 11310, -22859: -15920, 24079: 24924, -20238: -29669, -2746: -24651, -21422: 21027, 30773: 9672, -8756: -14597, -11425: 30250, -8475: 3559, 14902: 23939, 32064: 4283, 15572: 18467, -8531: -31074, 26651: -5381, 27619: -17005, -29712: 2868, 16457: 20436, -11057: -2269, 3024: -15357, 15023: -26768, 14212: -26881, -19185: -18690, -4924: 7128, 23174: -20610, -9472: -16907, 17569: -23072, 20118: -14428, 9805: 26597, 6994: -8522, 2040: -32366, 25162: -31175, -1386: 16672, -22403: 26995, 7584: 27458, -17532: -141, 18644: 3005, 24808: 28562, 9341: -5445, -25768: 32689, 16892: 17059, -30689: -12568, 28747: -19363, -2091: 1259, -11643: -20020} xs 1943497849 4012822781 687301666 4052323690 # shrinks to ref input = {-14552: -9546, -24687: 4553, -5948: -11033, -30216: 31225, -1329: 18654, 25756: 28243, 26320: 32308, 14380: 20303, 30195: -29219, 12769: -13515, 4261: -10098, -15032: 27827, 22373: -30648, -18543: -27064, 20765: -17004, -7193: 29946, 17191: -11212, -9550: 6145, 30413: -3896, 25650: 15492, 6991: -3005, -27117: -18341, -31108: -14720, 2037: -9230, 21209: -17697, -17478: -15083, -7092: -21790, -18620: -19170, 7611: -13546, -10267: -19624, -32677: 26187, 23727: 29533, -3698: -10243, 5300: -3822, 346: -5404, -22233: 16053, 18668: 22996, 2804: 14570, -7140: -914, 29328: 531, 22194: 580, -29271: 32284, -30855: -25589, -24039: 22663, -17584: -7090, 30655: -22419, 6962: 3019, -11388: -29702, 7470: 10191, 12733: -8953, 31781: 29536, -4713: 28624, 29225: 2850, 10639: -17353, 28644: -28651, 27509: 26751, -21653: -3068, -23302: 16505, 23875: -4223, -12294: 8408, 22871: -26300, -11807: -10674, 11617: -20802, -12917: -3942, 12525: 8275, -28360: 25924, -11694: -17660, -8376: -23674, 28022: -11052, 1701: 16466, -10152: 27738, 25396: 3306, 27309: -15176, -24958: 25332, 13257: -9440, 28652: -31476, 28824: -25210, 19544: -26806, -16312: -554, -29314: -25624, -6344: -27482, 12638: 11012, 29993: -5753, -7052: -5445, 6885: -32534, -2710: 15172, 25838: -29888, -4162: 25600, 8274: 3660, 14914: -11250, 18077: 21149, 30865: 29780, 7652: -29810, -27575: -22324, 27190: 13088, -28712: -24931, 32575: 14212, 16100: 2414, 22459: -12558, 12914: 12488, -5756: 26535, -11609: 21588, -23178: 22887, -6623: 10056, 11425: 5119, -24807: 1930, 20747: -2695, 22174: 28280, 26661: -7627, -22429: 26131, 30256: -13483, -23654: -6600, 23857: 20134, -6396: 26307, 27673: -19775, 21325: -20165, 18149: -5624, -16291: 20822, 30797: -19910, -16498: -12698, -28455: -13778, -19937: 16733, 22899: 23440, 20491: -29335, 6724: -14015, 20327: 29236, -13404: 17062, 21857: 21139, -11068: -11817, -24465: -19689, 13258: -20349, -8846: 24655, -14100: -5192, 18797: -4050, 15238: -20885, 21853: -14590, -21265: -5581, 7767: 16287, -29108: -18338, 15365: -10543, -28008: 20715, -27679: 9383, 28946: -32523, -6815: -11660, 25311: -30043, -24259: -32354, -26480: -29813, -4922: -31962, -23235: -14838, -28240: -16289, -20429: -10753, -31466: 4099, 17742: 9919, 22328: -29633, 11484: 5947, -30743: -3454, 27329: -28404, -1440: 16220, -21058: -15381, -7339: 775, 23003: 3428, -29181: -11177, -7918: 18487, 26135: -17235, 31493: -32374, 8674: -29831, 23135: 3319, 22008: 26647, 14087: 926, 9495: 32645, -28424: 4358, -28839: -25000, 12270: 1203, -3843: 24513, 28974: 3537, -11154: 20241, -308: 15509, -1063: 1938, 22352: 16339, 22065: -4794, 25625: 30704, -29994: 25473, -32588: 8066, -19799: -28784, -16369: -7522, 12819: -26116, -10: -12210, 23530: -8239, -8702: 15218, -29559: -6059, 17386: 8272, 9791: 11158, 31268: -23502, 839: -12740, -20953: 30929, -6498: -6179, 18058: 26452, 17715: 21182, -444: 26708, -12166: -10624, -17286: -11707, -5285: 28283, 26686: 28422, -27560: 24488, -9092: -21679, -341: 5249, -1777: -19160, -8798: -18074, 5664: -26770, 8831: 21172, -15630: 10171, 10815: -23739, 10322: -14746, 3683: -28968, -968: -11470, 4300: -21106, 17329: -3943, 919: 15039, 11736: 24420, 18566: 8425, -6499: 17007, 1038: -20933, -1760: 2435, 32364: 17255, -23412: -10508, -20606: -2288, -12261: -24932, 23266: -16759, 29366: -24835, -4536: -26835, 11130: 15321, 9689: -25898, 10497: -8, 8379: -17866, 32503: 1391, -7464: -7476, -10905: 21006, 28934: 27973, -2489: 22253, 18422: -3749, -16897: -26476, 26037: 24177, 25372: -5235, -17793: 5394, -31916: 8290, 2514: 17926, -12681: 10612, -31402: 4216, -21993: 5489, -333: -29732, -7208: 12324, -2259: 7182, -14269: 19700, 7113: -6447, 312: 21681, 16777: -5191, 19799: -22785, -16984: 20498, 13781: -19721, -15005: -27421, -5197: 16418, -26014: 14386, -21116: -29472, 22218: -3249, -12769: 13282, -962: 27871, 323: -26453, -9145: 28365, 20899: 5521, 2983: -28582, 27272: 17304, 14965: 6793, 1119: -8804, 11980: 24389, -27467: 31369, -6059: 22193, 11148: -13064, 28685: 13279, 9266: 23559, 491: 31840, -24358: 20417, -1039: 32656, -8354: 27428, -6823: 13026, 7306: -28986, -29124: -12391, 11358: 19868, 21852: 31747, -354: 17738, -6380: -31076, 6993: -3593, 7749: -26991, -5736: 26845, -23757: -25868, -23018: 21291, -29482: -13037, -28028: -17152, -11500: -2400, 14240: 27368, 8517: -7890, 3318: 26016, 8702: -21694, -15698: -18674, -29992: -16745, 17497: 3921, 17256: 23908, 12994: 16354, -12133: -5976, -9636: -19253, 13662: 26694, -5291: -27961, -19711: -2634, 24676: 200, -21683: -20419, -10755: -20201, 5389: -24265, -18644: 25881, 24013: 26905, -15710: -40, -1078: 24024, 29202: 25073, 7358: 5121, -23181: -31628, 10282: -26184, -20910: -2762, 31789: -11576, -15966: 18578, -14285: 3170, 1448: -13499, -10080: 23097, 9012: -30126, -15463: -12150, 20289: 31453, -23544: -15457, 14694: -5005, 25006: -25213, 20402: -18375, 29679: 20672, -4570: -7111, 22495: -6454, 28869: 31665, 14191: 13852, 16134: 32353, 4529: 8494, 19093: 6864, -794: 18776, 17957: -11241, 25597: -20134, 18037: -1679, 27835: 3288, 22315: -10272, 13032: 9697, -20215: 3797, -12773: -983, 25848: -4873, 19596: 9706, 8030: -28925, 30246: 12946, 7467: -25254, -10731: 6363, 18631: 8976, 1414: -13096, 1779: 15953, -3595: 21321, 339: -8066, -7639: 14039, 20195: 12164, 7156: -11669, 16411: -8927, 13534: -14503, 13577: 17546, -27772: -32545, -6421: -3173, -12316: 16200, -31884: 603, 12395: 3034, 22659: 25898, 30481: -23170, -16623: 20360, -20279: 30762, 3968: -13181, -2313: -4445, -13314: 13183, 17186: -472, -25465: -11926, -12985: 12936, -17260: 21153, 14971: 366, 5035: 29873, 29: 19702, -29547: -10586, -10368: 11518, -13759: -4543, -29208: -4931, 1605: -15282, 22500: 24270, -25324: -150, -24578: -5930, -25949: 21945, -10053: 2314, 19195: 24191, -6760: 32697, -8885: 28695, 12676: -18931, -24963: 5956, -11667: -32632, 3496: -7015, -3422: 24361, 17031: -19643, -21362: 28410, 11868: -24693, 26928: -25916, -8771: -10298, -19434: 29046, 16057: -21815, -28508: -1488, 17240: -23998, 3146: 4003, -8669: 1658, -2885: 3442, 19212: -25066, 8584: -30453, -19749: 25649, 12925: 1864, -7982: -17592, -18312: -6020, 26066: -12698, 10168: 2258, 23411: -27324, 20913: 2058, -17161: -2704, -28674: -8941, 19334: -154, 29314: -18570, -4291: 13987, 27890: -10595, -6139: -19690, -2185: 29099, -19246: -21481, 18345: -7746, 8792: 32374, -12093: -11963, 27898: 28419, -2679: 31973, -6053: -9814, 28750: -1279, 5512: -22468, 24559: 13801, 29152: 10421, -8834: 21875, -11673: 15773, 28602: -9755, -5742: 6786, 13086: 15119, -10716: 23940, -31277: 6551, -12006: 16878, 31399: 15139, -3499: -14162, -7428: -10133, 31533: -4236, -20111: 23374, -13506: -28699, 31291: 27230, -32598: -7092, -5972: 31899, 15397: -8419, 15791: -2952, 24123: 9853, -32197: -7823, 12564: -18593, 16139: 21230, -23524: -28360, 6509: 20623, -8275: 31514, -6607: -5333, 5101: 31408, 23166: 21657, -12672: 8924, 1406: -11027, -24417: -3430, 27934: -17823, -7960: -29901, -20662: 24784, 9478: -22265, -3096: -26803, -5897: 23795, 29566: 26527, -19057: -10328, -22202: 18967, 11290: 32741, 14225: 4804, -31177: 15798, -23514: -7563, 21445: 15844, 14156: 8570, -23968: -24474, 12089: 5498, -14198: -26135, 12664: -23411, 11111: 27354, 15998: 11423, 2891: 21555, -3889: 17061, 32491: -4625, 110: -9137, -20559: -6986, -28721: 3288, 6697: -23898, 8774: -6890, -24838: 20366, 31820: 27280, 14127: 10447, 605: -23336, -28271: -9387, -1486: -28143, 1623: 19882, 30022: -7494, 16398: 31225, -20320: -23582, -23295: -17336, -14291: -775, 3270: 20106, 11662: 16973, 29041: 3377, 7387: -16397, 18767: 32565, 5022: 19191, 16397: -31024, -16106: 13405, -31898: -23690, -25746: 17046, -8847: -29236, 28656: 21644, -11311: -25314, 4515: -19390, -15847: -1245, -5025: 24474, 24302: 28820, -31534: 24028, -14548: -21272, 20722: -27070, -24083: 29927, -27812: 19042, -18194: 5028, -29732: -8181, 20316: 16946, 3176: -32144, -30223: -25654, 202: 22052, -20234: 6669, 18732: 15730, 7127: -27128, -2948: -22493, -21733: 27859, 25166: -31535, -27174: 28732, -14476: 5256, 20346: -27358, 6308: 18033, -10411: 12780, -5469: -28028, 4884: -15738, -12442: -3065, 24311: -21682, 18679: -10632, -13091: 25595, -18882: 31353, 23626: 20687, -17201: 13186, 4270: 16793, -22089: 5358, 4374: -23552, -13011: 5661, -14593: 1052, -10586: -18438, 9093: -3136, -19492: -30355, -5066: 24396, -9852: 13836, 8770: 30757, -18672: -13421, 16224: -10802, 21800: 12639, -213: 28223, 22311: -6756, 7182: 31529, 19224: 16315, 20067: -19940, 10720: -12330, 8384: 14353, 27730: -24075, -18309: 4570, 5808: -32765, 14330: -24746, -19632: -3605, 4228: 25887, 28783: -30008, 16483: -20439, 16655: 26861, -10047: -14259, 30091: 29732, 29182: -13397, -26897: 14659, -17202: 16830, -15265: -16433, 18554: 18464, 3269: -15505, -11054: -20924, -5253: 3749, 14888: -553, 15310: 29010, 3194: 31220, -13770: 21130, 4236: -15365, 13546: -11695, 32688: -16898, 24524: -8344, -2968: 25207, 1449: 26456, 29046: -5209, 12133: -27981, -27130: -21148, -3586: -24606}, index_rand = 6181253659715007859 xs 3094145122 1848048556 41621330 1587738279 # shrinks to ref input = {25109: 17547, 13167: -24835, 32450: -27886, 28704: 27530, -29237: -31051, 17202: -31179, -22358: 15751, -17715: -2518, 82: -27363, -26280: -12489, -10711: 1113, 28197: -29265, -12233: 15499, 1578: 18570, -10956: 7886, 957: -15131, -26652: -19109, -1698: 7038, -3697: -2352, -18762: 4688, 2143: -17488, -30936: -28216, 26547: 20891, 20001: -10566, 20162: 12139, -15042: 4332, 23226: 835, -1720: 26602, -9048: -19721, -29320: -13680, 30000: -7286, -3693: -16312, -30022: -21864, 29541: 16785, 4006: -20908, -29599: 14040, -17690: 24907, -3766: 16608, 22217: -29766, -29552: -3913, -4046: -20703, -26412: 21205, -15898: 17844, -4553: 32030, 30908: 18124, -1065: 27619, 1642: -19186, 31516: 28398, -22847: 5892, -31043: 21198, -20284: 25965, -27740: 4090, -750: 29603, 29546: -7601, 19831: 16923, -27337: 27061, -5052: -22512, 19028: 22656, -6128: -20716, -5324: -2624, 7273: 5987, 26259: 28589, -5682: 24455, 19425: -13458, -8687: 1837, -29081: -5536, -5126: 19859, -23172: -26061, -17454: -9093, -14495: -19415, 124: 27981, -214: -15589, 17580: 24995, -22303: 227, -2043: -17283, 13309: -29027, -22094: -31943, -1826: 12330, -26959: 19945, 22155: 4915, 16: 1005, -6802: -8951, -29879: 4766, 21350: 7196, -4292: -29428, -17591: 7350, -23475: 20767, 23372: 13739, -16316: -30392, 17391: 5141, -10827: 27764, -11304: 7731, -4247: -21446, 8251: -19738, -568: 8414, 14787: 5321, 2403: -17445, -19412: -16874, 16247: -30651, 11946: -29414, -7725: -10389, -2002: -20578, -12689: -21992, 15800: -451, 32435: 1683, 16805: 11493, -8068: 32206, 27386: 26184, -14311: 21859, 7208: 19308, -13115: 24029, 32222: 19098, -3951: 20703, 10184: 5095, -3235: 29199, 7358: 3163, -9539: 23015, 17802: -31374, -12478: 18169, 21253: 2717, -4126: 30376, 31545: 13768, 14466: 10983, 26903: -7058, -8377: 21868, -15947: 21121, 31358: -30749, -22714: 23423, 17855: 9349, 7118: -3573, 20807: 30872, -19809: 19037, 3084: 622, -13442: -19023, -9314: 14811, 19551: 9175, 13945: -24551, -9482: 14832, 4058: -11363, -29175: 3097, 26866: -6501, -19528: 16419, 13884: -10693, -30894: 18387, 2434: -11471, -29588: 8302, 9537: 26353, 11223: -4669, 32503: -8454, -17566: -12769, 2898: 31182, -19042: 2208, 18941: -22060, -22700: -31888, -11067: -21667, -23130: -13776, 29835: 5369, -15197: -21652, -31889: 23653, 19121: -20925, -4888: 11878, -23301: -32625, -12188: 18858, 7983: -19066, 30772: 18792, 18565: -29423, -30448: -28531, -29781: -27670, -23123: 24404, -8686: -5154, 1956: 28781, -7050: -19514, -21874: -15534, 27434: 2933, 11568: 8591, 8645: -32175, -24288: -32065, 23708: -16804, -102: -20155, -21298: -10486, -5606: 25010, -6095: -10305, -19200: -11318, -2702: -31591, 10484: -30488, 12966: 18734, 19351: -29225, -10379: 28706, -13211: 13219, -30684: -30410, 12809: 3245, -9528: -14612, -13917: 30016, 15751: 14348, -16078: -20918, 21568: 22488, 18004: 30534, -19602: 18121, 13959: 22532, -9411: 17916, -13153: -12283, -16441: 24688, -31877: -25633, -10943: 21681, -12241: 25973, 18048: -16131, -32576: 16074, -23799: 30191, -27572: -4842, -9917: 17632, 28907: 26864, 1029: -8790, -15458: 5122, 617: 31966, 5083: 20195, 26118: -27966, -31719: 261, -30897: 26416, -28104: 25353, -25183: 10371, -25051: -9876, -8676: -2203, -25965: -25244, 14552: -27117, -6195: -9440, 6733: -15895, -16548: 22340, 7795: -7156, -5548: -8170, 1975: 11313, 26002: 13579, -1090: 16028, 3119: -22116, -26790: 3213, -12524: -21450, 19788: -30362, -11778: 7254, -24041: 18664, 10038: 10500, 12731: 10291, 19886: 8630, -13579: 4280, -10199: 16578, -10637: 18165, -3835: 6271, 14929: 24076, 27938: -31473, -14770: 5512, 15441: -3706, -17185: 2295, 15932: 20222, 13258: -18255, 24353: -11049, 24897: -6737, 365: -23551, 23329: 30521, -31648: -13380, -1552: -25692, -5206: -1325, -27419: 31094, -51: -28413, 12361: -29699, 5402: 26930, -27529: 7188, -12050: -7233, -7996: 20657, -18903: -31229, 2184: -27864, -22198: 8189, -14333: -3151, -8819: 32208, -25427: -1465, -13361: 23768, 25140: -13818, -18482: 5019, -9847: -31791, -17654: -16678, -18171: -25938, 24839: -22327, -10299: 17415, -517: -9938, 11604: 19413, -20522: 25880, -16853: 12843, -19711: 6243, -2217: 17848, 31544: -23358, 32481: -20104, 916: -13297, 21632: 27432, -20301: -905, -28748: -18375, -18946: -26872, -27139: 23619, -28341: -2690, -14751: 3261, -31340: -5866, 14129: -1873, -17466: -19221, -27794: -25683, -16132: -26856, -6446: 21798, -26329: -20765, -19511: 31669, -25708: -5275, 10217: 797, -9016: -17110, 7696: 13723, 6083: -19072, 31100: 8435, 8017: 10175, -23973: -199, 25418: 21954, -5106: 15703, -29119: -14678, -23448: -14905, -1334: 27615, -25389: 21402, 5764: -14910, -25059: -20274, 32586: -21603, 27022: 24446, 30370: -23901, -31423: 31764, -21135: -21011, -6284: 14914, -20672: -4657, 3691: 9397, 1305: -26046, -29806: 1663, 11409: -9037, -25440: 12737, -16350: -30111, -15664: 4544, 29290: -19087, -10773: -15820, -1299: 31105, -9945: -24879, 25445: -1393, 17568: -11207, 2868: 11240, -14478: -5443, -29749: 22046, 30402: 18906, -14676: 28148, -12434: 19407, -8904: -31377, 32723: 19548, 26961: -12468, -20695: 24529, -11186: -16253, 17983: -16005, -22681: 29406, -32124: -28864, 4551: -32279, 16423: 21410, -29467: 30297, -32316: -11084, 19168: 13447, 31777: -17253, -20788: 30789, 10397: 26717, -16290: 10403, 3436: -20939, 24973: 21047, -23977: 19143, -21115: 16465, -32140: -27035, 29494: 19758, -31925: 16559, 25544: 14705, 16117: 2902, 16076: 1994, 1259: -4130, 11871: -31322, 31923: -12428, 6485: 16367, -15055: 17454, -32536: -23142, 19287: -30036, 19046: -6360, 30467: -20193, -1352: 19442, -24389: -32203, -25508: 28905, 13432: -28476, 15794: -2020, 7907: 12590, 19319: -31856, -10096: -8759, 9365: 24849, -11559: 25438, 23762: 21598, -7248: 22542, -16926: 12934, -24708: 4222, 2179: 3309, 1855: -8693, 10786: 29825, 18783: 25809, -5169: 5570, -8235: -4664, -20234: 26252, 18273: -26922, -4496: 19147, 4458: -20329, -18952: -31435, 22439: -27690, -3304: -7512, -17425: 6385, 2885: -18520, 2478: -17666, -16036: 22920, -8658: -18048, -7204: -25509, 28983: 4786, -9146: 16439, -26893: -27056, -31037: 17541, 643: 17042, 27085: 11808, 26037: 20956, 4234: 1346, -14815: -6582, 25700: -8577, -10298: -23247, 5728: 10020, -25496: 10378, -27275: 28186, 24689: -21421, 32092: -15135, 17254: -370, 13808: 18349, 19084: -163, 16447: -25693, -22306: 26140, -1695: 3490, 32119: -6821, 25084: 21803, 10922: -26376, 27134: 21743, 30570: 8146, -12987: 6435, -20456: -22516, -31704: 12485, -23916: 4096, -26088: 20130, -19159: -28657, -3808: -29934, 21346: 18600, -17642: 22758, -9589: 9627, -12541: -16450, 3120: -31143, -5758: -4025, -14764: 22952, 26792: -16315, 12268: -8062, -31344: 20767, -10729: 652, 32354: 30556, 10533: 27076, 18563: 31611, -15395: -16343, -7271: 28710, 28693: -28840, 19304: -31194, 4838: -28332, -15421: 18530, 24139: -28363, -31872: 15347, 17464: -17470, 30063: -21708, -6516: -17705, 14553: 20142, 29460: -4329, -9381: -14281, 3286: 26530, -25478: 18858, 8614: 12250, 3087: 21051, -32628: 24370, -15651: -18351, 8024: 4382, 15805: -11203, -1077: 8609, 32285: -11583, -27614: 7211, -10535: 22639, -20099: 16870, 21230: 28095, 612: -23352, -5544: -26504, -25887: 2679, 14181: -26845, -31967: -7583, 26010: -15169, -6467: 12825, 24107: 4381, 3800: -2605, 2010: -21114, -1414: 6971, -12659: -21065, 20831: 9711, 20073: -8964, -24951: -3223, -6740: -32200, -8304: -23492, 27109: -8227, -17744: -25257, -28537: 18637, -18411: -15041, -25173: 928, -25903: -13895, -21831: -3009, -25678: 1895, 30480: 17166, -25850: 16586, 12531: -10102, 19095: -6338, -26672: -9944, 11671: 1505, -13311: 12087, 8454: 19381, -12936: -31002, -17139: 19189, 11596: 20259, -25535: 3542, 20951: -18777, -6500: -18332, 30742: -277, 31676: -30490, -27517: -19880, -25374: 32088, 21483: -10823, -16979: -18696, 14561: 13047, -13368: -16548, 4720: -14672, -29316: -19115, 1395: 9605, -10992: -10275, -21747: 8507, -4734: -6057, -30595: 16035, -24700: 22816, -2210: 19173, 7671: 24589, 27460: 5788, -10899: -21848, -26840: -3095, -28802: -2572, -3431: -5783, -21943: -31626, -22611: 26127, 3213: 396, -15957: 17787, -11959: 17422, 1613: 22455, 32292: -9957, -23718: -32341, 2795: 4614, -15162: 2211, 26391: 18246, 885: -15549, -29735: 26493, -17763: -9509, 832: 15026, -23215: 22609, 28230: 20969, -32629: 28951, 10402: -11520, 26729: 11732, 14065: -4855, -12988: 5456, -24309: -15464, -20942: -11584, -18355: 1571, 16650: -13337, -7873: -13362, 11313: -19130, 20194: -6007, -9755: -26600, -25013: 21165, -14900: 26513, 17728: 17821, -28277: -25003, -14757: 5100, 13577: -9806, -22115: 27298, 14668: -23429, -25174: -28161, 2367: 4067, -23795: 27843, -3780: 5571, 30910: -13600, 11355: -21254, -7086: 2278, -13419: 3221, 22732: 21622, 24582: 15497, -4771: -18262, -705: -24363, -6490: 13550, -3098: -31941, -20378: -12040, 25336: -18191, 21299: 822, -30797: -23895, -17162: 18699, 228: -17254, -12250: -21242, 4730: -2067, 8150: -16241, 15707: -29248, 6042: 32137, -26556: 15175, 14154: -28226, 9935: -23158, -29846: -22516, 9461: -29500, 11475: -19325, 31974: 2561, 1330: 8660, -1271: -17382, 3482: -8519, -25956: 15786, 25713: 3023, -394: -27817, 19478: 32434, -12289: 12678, -2608: 9330, -26485: -7465, -27840: 12092, -31666: 3630, 15748: -11979, 30892: 30006, -21505: -30879, 10340: 14885, 11619: 5575, -7216: -30397, -15140: -11637, 16761: -16433, -21925: 12562, 28429: 18057, -12739: -25584, 13377: -24419, -3752: 22641, 21444: -30136, -27669: 23044, 521: 28473, 9286: 5030, 29721: -14329, 10899: 8578, 9145: 15065, -30537: -15209, -21221: -5525, -16581: -17871, 27355: 23268, 56: 17851, -2659: 22647, -1630: 31617, -30759: -18270, -28584: -4801, 1875: 10171, -8604: -27218, -16634: -19036, -17802: -16413, 13379: -6140, 23704: 6880, 8765: -1719, -21255: -6806, -19546: 23388, -22379: -4391, -17126: -18724, -21340: -9110, 18182: -10221, -2471: 2014, 13850: 25597, 18153: -5252, 13325: -21738, -27130: 19737, 8324: -57, 16162: 17766, 30735: -1934, -13008: 18027, -14177: -26344, -3410: -15352, -22373: 13456, 23820: 30037, -16682: -8556, 2771: 32686, 7700: 2288, -15586: 23950, -23520: -30119, 24085: -27227, 28343: -27847, 11661: 11000, -2690: 6058, -30191: 21458, -10655: -20377, -18377: 8672, 15970: 29352, 13854: -28243, -12566: 12732, -11424: -5467, -13021: 19087, 4285: -20833, 4850: 15552, -28485: -26386, 8290: 259, -11749: 19444, 26075: -905, 30605: -1488, 6438: 27983, 9535: 25448, 10668: -26317, 9228: 2787, -9342: 6996, 3077: 2077, 14575: -17406, -13263: -28914, -16497: -8505, 17807: 29989, 17642: 27683, -7320: 22167, -28413: 23955, -29262: 1610, -7611: 20341, 13742: -22167, 1948: -3978, -26335: -18254, 7765: 4432, 22110: -27003, -3021: -16057, 15606: -23087, 8263: -28114, -28389: 28514, -24292: -3802, 593: -22012, -11632: 18700, -8493: -17690, -24000: 29402, -30405: 18870, 2054: -12353, 6302: 13902, 14627: 20456, -20713: -6796, 59: -27945, 15401: 3763, -31282: 2136, -30080: -21448, 596: 31173, -3777: 10969, -27062: -12955, 10983: -10220, 23508: 7525, 18741: -17043, -2752: -3564, 1045: 29156, -23741: -18438, -20412: -20083, 31569: 5108, -19554: 24719, -31716: -26184, 3254: 30063, -23755: -474, -10974: 24808, 32587: 24856, 13274: -13294, -23140: -5331, -1612: -8780, -12950: 16875, -7602: -1367, -8407: 24480, -18043: -18814, 5557: -14426, 23239: -32629, 12839: 10100, -23881: -9397, 9000: 1367, -16739: 24959, 27731: -23120, 1404: 16785, 26722: 2067, 13575: 21126, -4894: 14658, 13344: -7459, -3522: 8125, 10021: -14961, -10653: -5225, -23802: 25545, -6938: -12602, 3949: -14698, 29660: 11675, -2952: -7008, -30398: 12733, 24591: -27470, -8108: -1693, 8378: 6293, 19409: 107, -24293: 13979, -26643: 24382, -8928: 14933, -15145: -3845, -22551: 10211, 425: -15224, 16478: 7707, 2338: 16763, -23791: 31613, -8916: 7382, -5384: -31297, 10300: -1373, -27891: 1916, 2999: -30008, 1165: 24301, -397: -18055, -4201: -8619, -23959: -1718, 16219: -26007, -15100: -24529, -32527: -12160, 19770: -292, -10008: 22619, -26772: 3604, 236: 105, -7879: 31666, 19242: 10567, -6348: 14664, 5832: 13312, 1492: 10163, 8927: 21565, -26318: -18183, -10174: -25158, 9807: -26056, 26076: 17814, -15366: -19761, 2621: 12814, 30193: -31344, 4206: -18921, 7126: 22715, 16128: -10023, 25936: -31820}, index_rand = 5224467844040644997 xs 361304641 2604218693 3136857884 1914902562 # shrinks to ref input = {-19354: 24819, -16292: -12090, -14434: -17000, 7065: 3299, -18458: 22292, 19194: 12574, 1: 18507, 32098: 548, 3309: 3711, 30631: 31499, -9540: -31601, 29472: 15053, 28278: 16574, 10805: -6409, 1937: -29445, -27617: -19598, 14618: -13991, -31216: -14546, -8002: -19976, 24690: -11392, 19023: 6532, -4475: -15383, -3276: 3043, -22021: -831, 7566: 28669, 7414: 7538, 3289: 1498, 32294: 11245, 27957: -24717, 394: -5551, -25550: 7578, -10781: 17801, -15265: 22301, -22600: -27228, 18049: 28811, -5680: -4765, 6393: -26312, -3763: 19239, 12387: -7834, -17270: 15102, -849: -18294, -11185: -8909, 5848: 28816, 4822: -1284, 9283: 17434, 5749: 13204, 11282: 18054, -30054: -1590, -5733: -8222, 27256: -17099, 25828: 27982, -26680: -20087, -31170: -3715, -27215: 20014, -3297: -27491, -4237: -9165, -3803: 6289, -13220: -7922, -31962: 28987, 15542: 18604, -17133: -25302, 13426: -25405, 2685: 15869, 5642: -8384, -8618: -21494, 696: -6333, 30169: 22735, -31498: -2698, -16350: -30346, 23455: -30868, 24880: 8411, 12752: -26951, 807: 5479, -31915: -6948, -6797: 32084, -27450: -5011, 12562: -16186, 16308: 9586, 8802: -8309, 22958: 1367, 5967: -7809, 7342: 9794, -21809: -30257, 22051: -8714, 11489: 27098, 9636: -24412, -22926: 4643, 16522: 3404, -13679: 20161, -20645: -4604, -27194: 2276, -1203: -23043, 15177: -16488, 17368: 19938, 18129: 13518, 29506: 13683, 30487: 29314, 22806: 20773, -1727: -29216, 8206: -19496, 7127: -23074, -2964: 1656, -8043: -15180, 31783: -24797, -14997: -8251, -9625: -985, -3485: -1572, 3259: 1018, 4124: 31363, -6871: 11567, -15128: -13650, -30770: 9112, -2638: 21963, -19057: 16043, 20685: 214, 17778: 6821, 27947: 8329, -13235: -3670, -15954: -21158, 12517: 13054, 23898: 16751, 16216: -18722, 15237: -7624, -31732: 21365, 30822: -28157, -17438: -30023, -26596: 3301, -13414: 5061, 17372: -8376, 30362: 28469, -20309: 143, 24393: 10508, -6411: 32337, -18972: 19110, 30365: 10104, -5140: 19909, 11898: 18406, -14442: -15467, -32552: 22492, -11355: 5350, -8307: -18294, 17475: 7093, 22597: 1992, 20469: 30777, -32614: -6165, 32573: 8339, 1514: 25969, 10701: -20617, -3021: -12256, 6587: 18950, -25402: 12031, -9936: 16285, -29946: 22912, -14064: -10944, 671: 13716, 5073: 7865, 5197: -26128, 19416: 9507, -30681: 8287, -21677: 28198, 3770: -21258, 14103: -8796, 21840: 6932, -14302: -3120, 18835: -21353, -19863: -30682, 30904: -24579, 23767: -2876, 14140: -7923, 23444: -8002, 20015: 24236, -8959: -10261, 19803: 10542, 13739: 29511, -28569: -14754, -3714: -30519, -14450: 8383, -11394: -30165, -32079: -13880, 13248: -30479, 11781: 9474, -10436: -2853, 6759: 27954, 25845: 29391, -31738: -26454, 30132: -23278, -18345: -23422, -25979: 16664, 9607: 29137, 8336: 22464, 20324: -23583, 15078: 31805, -28529: -17128, -12412: 9041, 5972: -27525, 10224: -32042, -6332: 7448, 26995: 20876, -12473: -28199, -23999: -23159, -18299: 21242, -14408: -31328, -29246: -10044, -10164: -28095, -27052: -5400, 10173: -25267, 23822: -17900, -23953: -13219, 28791: -8090, -21909: 21407, 17530: 26269, 29655: 29973, -16374: -16957, 13982: -24366, 11639: -20136, -18021: -4470, -28776: -14271, -19637: 20591, 17096: -6224, 19899: -7035, 10911: -124, 5706: -16549, 2364: -24950, -10944: 31678, 31723: 11433, 6413: 4440, 32675: 19466, 27096: -13819, -10806: 6633, -4937: 28751, -27140: -13550, -12557: 13547, 8629: 3152, 3413: 2565, -25866: 10729, -15566: -15218, -3621: -23194, 7527: -27521, -24127: -29997, 12909: -25868, 31772: 4680, 31014: 29821, 18678: -16508, 30298: 9039, 14505: -3668, 22669: -10595, 26152: -16178, 24944: -8114, 16694: -19338, -14047: 24498, -30270: 26317, -16665: -26461, -30656: 20249, 25517: -20809, -23571: 1882, 23007: 17866, -25659: 8076, -23717: -5810, 6904: 2115, 11784: -31335, 30197: 18033, 12572: -30508, 17268: -18072, 10674: -22655, 29365: 24132, -17185: 10599, 8749: -31736, -3334: 32668, 21915: -2453, 17556: -26978, -9373: 26250, 22616: 30289, 2165: 15435, 10766: 1818, 13715: -20952, 2935: -9271, 25227: 15051, 13045: 23934, 13260: 30812, 10690: -10114, 824: 8266, -14298: -13127, 11000: -14100, -18008: 21650, -8299: 6540, 3128: -12265, -7224: -8911, 19209: 14023, -8038: 24840, -26622: -26079, 14895: 22828, 31625: 20961, -2636: 19675, -17021: -28086, -5946: 15939, -32313: -153, -14012: 30196, 31144: 31395, 7996: 24091, 28923: -29327, -9247: 15709, -26391: -9285, -14883: 27089, -15544: -12422, 1374: 28261, -22870: -12032, 26286: -20763, 4080: 2040, -14599: 9484, 32660: -3226, -22977: 5487, 18067: 3363, -6489: -21852, -10804: -13137, 27933: 20036, 15275: -12004, -13892: -676, 16130: 22039, -24538: 21841, 24641: -3642, 21784: -26054, -20651: -27826, 5295: 32093, -24305: -3414, -18446: 10556, 4517: 526, 24294: 10881, 24194: 26364, -13901: 18395, -12783: -27360, -713: -29957, 8644: 14950, -6324: 9260, 9506: -30362, -29129: 6181, -3784: 18178, -28466: -21361, -18659: 3987, -10595: -19837, 7499: 30194, -12558: 7406, 28463: 12837, 27107: -2298, -6932: 4389, -32374: 25500, 23110: -23112, 8747: -22926, 4097: -2613, 3462: 30698, 3398: 31612, 30467: 23139, -1641: -3740, 3293: -19082, -20228: 31473, 20793: -17194, 17724: -25522, 8074: 32013, 23712: 19733, 31907: 8354, 12744: 28197, -24606: -11268, 23637: 3704, -3436: -24423, -2739: 10852, -4260: 18850, 12969: 6263, -26425: -6431, -28020: 25049, 31644: -1993, -20327: -6272, 22470: 17788, -28205: 31716, -21534: 32498, -4889: 19628, -825: 16644, -30248: -31584, -26932: -3743, -28597: 27796, 10641: 29403, 18736: 11379, 17445: 4741, 15954: -22253, 28955: 3994, -18758: -20179, -16666: -22951, -23409: 7546, 28441: 28286, -6600: 29204, 245: 5060, 21723: -31646, 13693: -28832, 17526: 19157, -3421: -30798, -12920: 25702, -13396: 4699, 25125: -17956, -378: 30900, -29352: 13943, 21551: -27295, -31207: 316, -5104: -20171, 10981: -14599, 13127: 7748, 12536: 20062, 15315: -493, 10111: 24216, 3207: -31216, 18499: -20515, 4815: 26753, 24865: -18658, 28562: -27549, -14256: -3818, 22292: 9007, 9550: -22562, -18174: -5902, 18354: -4282, -14416: 6361, -20722: -24289, 31715: 29227, 29704: 15935, -5533: -8673, 10845: -30941, 14160: 12144, 1992: 1318, -11404: 28138, -5428: 18711, -1624: 3223, -20437: 19171, -13983: -15469, 29721: -11600, -32689: 14340, -12675: 7713, -21501: 21229, -3729: 27686, 13580: -5131, -17708: 16700, 20809: 25221, -28564: -3272, 29509: 26850, -9889: -9564, 938: 25880, -17223: 18566, -20452: -799, -4292: -17811, -19061: -11617, 25764: -11388, -3347: -14170, 29220: -7185, -21149: -4187, -8341: -13996, -9012: -22916, 5303: -18306, 14513: 21706, -4815: 9868, 4316: 3968, 28688: -1524, -19338: 14733, -13386: -14098, 18253: 3130, -1221: -5690, 5093: 24217, -12424: -8733, 25791: 31206, 6697: 29204, 31192: 12158, 31407: 749, 17618: -3504, -3199: -3206, -11293: -20357, -16165: -3563, -27497: -25700, -27297: -3825, -23521: -23715, 4652: -29245, -17313: 10246, 22202: 28783, 12621: 7793, -25616: -9539, -8209: 11244, 2018: -23988, -29161: 7278, -17743: 748, 6678: -15931, -31969: -10178, 11253: -18267, 9135: -23204, -31002: 27729, 22133: 28453, -31372: 16243, 29200: -18504, 27344: -7996}, index_rand = 12865908526723545602 xs 2514330554 4021224636 4249159765 809946243 # shrinks to ref input = {22983: 25567, -21524: 12652, -31419: -14369, 24781: -3215, -6098: -3626, -4344: 6615, 11513: -5995, -32129: -25765, 19648: -32475, 5272: 26666, 6416: 22836, 27222: -3403, -4042: 3636, 13253: -27848, 27331: -4442, 666: -14459, 13044: -27108, 2407: -18269, -11769: -23455, 6186: 23587, 3702: 7914, 29676: -21600, 12424: 12219, 27941: -5207, 15122: -12497, -11158: -27362, -8282: 26473, 3415: 26408, 12831: 17512, 5795: 28896, 21721: -11462, 20429: 9497, -12438: 9683, -3959: -13001, -25293: -23380, 5700: 24227, -21071: 9692, -18808: -24549, -27808: -4112, 14687: -13091, -14445: 10864, 8680: 29230, 28793: 2289, 572: 22804, -12907: -22882, 19549: 29926, -24247: -3077, -96: 16251, 8929: 32524, 18444: -31578, 24622: 19896, -20594: 13891, -22943: 19132, 31425: -2940, -12580: 30389, -526: 2891, -10880: -20465, -20861: -9108, -1990: -1706, -14673: -3333, -12415: 12446, 1711: -3619, 2889: 26166, 5135: -9934, 9761: 7314, -13727: -30121, 23167: -14068, 7972: -16912, 792: -2110, -23816: -11162, -14613: -11944, 2276: 16327, -1710: -513, 14501: 12803, -14424: 12359, 8166: 23242, 7132: -5033, 2661: 18395, -29564: -10169, -24378: -28753, -6535: -12561, 8864: 16922, 5509: 24075, 6948: -31451, 9166: -16562, -15552: -22739, -23577: -11089, -23262: 15724, 7935: -226, -15831: 22789, 19431: 12267, -32692: 13439, 8190: -27259, 5177: 21511, -25935: -29614, -23804: -9779, -5144: -13329, 13090: -1785, -24277: 11514, 23943: -7920, -5978: -7247, -10397: -26707, 25026: -2168, 16104: 8686, 1807: -29851, -24649: -22813, -19629: 11095, 22893: -20902, -23916: 17574, 1476: -25217, -24340: -19076, 28100: 15570, -22175: 22320, -6586: 6492, -18649: 11816, 16251: -21463, 17368: 3798, -20189: 3235, 16961: -6580, -8404: 20372, 16047: -15304, 29490: -3055, -24776: 15119, 27563: 16145, -22311: -2158, -15739: -32392, 2484: 14964, 21250: 7246, -9967: -28930, 31387: 5103, 14859: -2042, 16259: 31622, 29267: 26762, 6688: -2894, -25600: -27724, -22795: -11228, 2779: -25135, 3592: -29746, 2684: 25084, -14032: -6792, 16004: -29800, 10914: 6250, -15582: -26248, 21285: 13207, 22458: 2337, -13517: 14340, -29653: -16328, -9174: 8207, 6822: -22380, -13230: -5805, -24662: -20758, 23527: 6218, 21957: -1144, -29983: -14789, -25776: -10625, 29489: -29112, -634: -1687, 16362: -5095, 24103: 17173, -28568: 4122, -27366: -2615, -3220: 25064, 990: -31755, -14609: 23575, 31478: -24182, -15842: 9193, 7823: -20861, 32558: 23623, 28629: 20621, -27884: 26432, -14903: -17295, -20813: -25646, -14902: -25559, -13309: -1218, -12300: -17285, 31853: -3859, 1399: -7893, -26296: -29878, 19179: 13265, 15479: 17728, -25448: -8456, 13588: 27559, -24783: -7128, -32103: 29322, -1758: -3572, 13728: 31962, -17236: 5243, -21230: 27588, 20742: -27977, -20661: 4578, 9198: -15494, 5045: 25517, 29565: 31629, 20558: -6873, 24626: -30679, -7805: -9759, -3591: -19001, 28566: 18547, -13063: -28236, -19655: -4068, -9420: -16081, 25403: 23876, -17448: 2581, -26642: 1171, -24759: -17468, 20219: 24202, -30341: 13934, 27839: -18353, -545: -28904, 381: 6631, -14539: 19857, -2539: 19520, 31691: -3655, 1385: -507, 30959: -12761, -16041: 8706, 21997: -15520, -11702: 28136, -19969: -15001, -575: -19615, 15183: 2436, 5198: -26540, -18493: 24520, -17505: -5183, -2493: -30253, -25067: -4479, -1283: -3796, 31471: 3428, 25734: 30828, -12627: -6061, 11155: -26067, -26923: 20405, -24052: 21789, -435: -23207, 30135: -13145, -15985: 11367, 16307: 15640, 28752: -18459, 22594: 7750, 22206: -269, 12789: 803, 5691: -26452, 31114: 1532, -15192: -30273, 23101: 3141, 6407: 15910, -1158: -18687, -25606: 29881, 17713: 19127, -1122: -12940, -6489: -9054, 15743: 3691, 21427: -22498, 10898: 19136, -15369: 8230, 30219: 3776, 1353: 27070, 31264: 29339, 31831: -20760, -9233: -18316, 24841: -26176, -12699: 3016, -22370: -9549, -6545: -22728, -8574: -14535, -31864: -12833, 768: 15313, -19955: -22453, -30880: 9396, 29543: 755, -9778: -32702, -22077: -25372, -2605: 16746, -30839: 29080, 32699: 16318, 2417: -12052, -31380: 12651, 24376: -19710, -32686: 761, 5677: 30160, 12035: 12228, 32125: -20315, -20314: 5439, 11493: -17794, -26680: 11610, -28132: -20467, 16900: -25287, 25461: -31865, 24573: -32602, 9200: -1505, 27518: -25693, 12990: -27271, -9397: -803, 14105: 1387, 2651: 8640, 17112: 30678, -969: 19205, 19710: 31993, 1893: 5361, -17816: 24812, 2765: 16979, 1966: -21769, -26954: -1952, 29816: -1928, 26782: -29372, 18567: -22726, -10111: 5989, 14917: 22916, -14570: -2257, 1263: -4715, 18190: 30641, 11528: 12151, 4035: 20675, 20933: 20327, 20055: -30733, -14881: 6272, -26276: -44, 10879: -30096, -9294: -16413, 2817: 13299, 643: 15982, -7677: 4313, -20647: 31903, 3668: 29744, -895: 14661, -17897: -17401, -11844: -19818, -10186: 29763, -32372: 29925, -28816: 10622, 31355: 10910, -17637: -27328, 9535: -27794, 12855: 2934, -3109: 3109, -6427: -16454, -15442: 8398, -23169: 31026, 12834: -25030, 10930: -16079, -12447: 9572, 398: -5332, -11374: 27256, -12183: 32336, -14535: 14519, 12753: -3875, 8795: -11151, -3712: -16993, -26508: 14252, 20375: -14368, -13681: -745, -30307: -5112, 13277: 25773, -7944: -31433, -28425: -12788, 20210: 15294, 17797: -5799, -19999: -7498, 31427: -21005, 11063: 16683, -12187: -11576, 25180: 1372, 12244: -7444, 27900: 20262, 28587: 7083, 18724: 8161, -20180: 25818, 15692: -31648, -28303: 17209, -720: 21874, -16321: 31013, -454: 5366, 31803: 29349, 13754: 24292, 21162: -20849, -23732: -27863, 25477: -6654, -26061: -12152, 20032: -20593, -12006: 28036, 6291: -26468, 14737: 5272, 32728: 5626, -1731: -29345, 24503: 19404, -24868: -21379, -6468: -22831, 22287: 10296, 2631: -26020, 14590: 19330, -9565: 26433, -15283: 5147, 6630: 31769, -17396: -21499, -25553: -10823, 13619: -10207, 23182: -25363, -23069: -32662, 19477: 15524, -1868: 5359, 7929: 27049, -12723: 9380, -16172: -20285, -10286: -10075, -9506: 31490, -25795: 13824, -17148: -32529, -21164: -9272, 20979: 9504, -18600: -2080, 27700: -20006, 9823: 31533, -6997: -19415, 28861: 17091, 26758: -15191, 24983: -24729, -28254: -1130, 25914: -26157, -24819: 405, 20339: 9923, 30368: 1691, -21613: -748, 1453: -19462, 3731: 13394, -32452: 3223, 24913: -6930, -21912: 19356, -24594: 21413, -4422: -29373, -15940: -23075, 27267: 7024, 2732: -24160, -28400: 18241, -24538: 1422, -426: 12283, -10915: -11143, -22114: 31517, 28357: 14424, 19009: 15527, -11167: -4468, 22854: -18910, -23106: 19639, 10382: 23860, 6220: -23926, -26385: -10089, -7503: -5631, 22781: -1889, 16878: -26298, 18982: 21243, 31681: 22201, -7993: 27285, -7299: 25550, 610: 16890, 8167: 21304, -16920: -617, -22339: 30620, 11333: -26987, -26992: -20496, -7985: -22986, 10141: -7469, 372: -21212, 17081: -17544, -11618: -922, 27971: 8305, -28364: -29445, 15932: 3403, 20712: -21072, 14139: 24028, -1589: -1905, 32372: -17183, -21555: 12537, 31409: 17560, 3035: -19927, -5300: 22560, -4845: 21856, 15699: -25855, 7642: 27579, 30284: -15949, -30974: -30226, 15786: 8546, -5179: 30950, 5765: 5052, 1410: -23757, -2705: -31393, 4012: 30468, -1359: -31879, -24808: 31414, 7542: 20843, -26533: -25712, 16975: 8303, -3145: -28727, 30626: -4547, 7331: -22347, -229: -15652, 26743: 8164, -28242: -12747, -13570: 28103, -31635: -32305, 25882: -22303, 392: -21213, -3910: -419, -24637: -4685, 15423: -4564, 16842: -5323, 2530: -6191, -28954: -20857, 12709: -1223, -29605: -31941, -15037: 9147, -2441: -9869, -30549: -24089, -2045: -24975, -6257: 5642, 19458: -26673, -11026: -32379, 11073: -2714, -16340: 29939, 22558: -389, -282: -29137, -8915: 10668, 13276: -26492, -6567: 15209, 18167: 6255, 18833: 9305, 23382: 9685, 22344: -6270, -5200: -17657, -27124: -17742, -19079: -568, 31073: -16882, 28075: 23525, -27683: -6870, -4980: 20988, 15716: -12047, -17167: -27903, 14047: 1751, 18332: 17369, -4584: -13960, -19312: -7004, 24390: -26226, -31358: -20950, 2846: 8574, 23256: -28403, -12965: -970, -10968: 6290, 31485: 3696, -14595: -24510, 8331: -24508, 16660: -6434, -21947: -11573, -13276: 18857, -11196: 13858, 20146: 29787, 26780: 16229, 22109: -21982, 3218: 12243, 20958: -15577, -25637: -8935, -29695: -30458, -27502: -9512, 6608: -10482, 260: -12910, 7060: 3640, 20729: -5920, 9177: 17672, 23669: 9673, -4719: -23531, 12804: -12848, -29031: -3714, 17216: -27527, -23101: 8400, -6250: 26869, -26842: -26986, -21952: 31092, 14811: 3573, -6081: 2717, -10912: -16202, -24595: 20431, -11358: -22184, 21588: -21605, -6061: 3518, 18275: -24618, 24224: 28119, -32273: 6717, -25485: -19967, -21076: -16695, -16947: -17173, 6350: -31349, 21046: 2696, 16207: -13750, -6710: 6770, 24774: -11316, -26121: -7976, 24586: -1831, -28350: -32385, -28591: 6607, 19897: 5582, 10787: -15060, 10497: -6872, -10294: 17802, -8472: 16304, -25702: 1771, 24559: 25237, -22562: 12409, 5848: 32381, 6698: 29851, -29088: -2362, -25758: -7282, 13364: 9287, 9286: -21108, -5875: 7021, 10384: -19100, -14947: -31087, 9224: -30160, 10825: 11627, 15906: 24744, -2491: 14682, 25078: -8675, -1487: 9277, 20301: -16262, -16721: 3749, 12876: 2719, -17183: 4920, -7383: -20989, 587: -29137, 1359: -18302, -31714: 5165, -10671: 13375, -1014: 25286, -5237: 14127, -20162: -15366, -17597: -27172, -16427: 24301, 21080: 29359, -16296: 21156, -27123: 17636, -14475: -17380, 3677: 3071, -13795: -14542, 25583: 2939, -18388: 26695, -30563: -10031, -19535: 16570, 22004: 14784, 4240: 16012, -26396: -7757, 1009: -24215, 10291: 31948, 31730: 31672, -27181: 4692, -7558: 15578, 8628: 18466, 15093: -25146, 15115: -23111, -25498: 19694, -29510: -6893, 10810: -20013, -7953: 24646, 17484: -6921, -22020: 317, 6794: 31084, 3107: 30850, 31725: 21696, -27069: -15468, 20231: -10374, 13074: -27686, -5761: 4056, 6032: 974, -515: -19247, -21834: -21830, 12853: -24945, -12244: 15573, 22762: -30055, 21333: 27246, 17857: -18844, 7569: -30916, 2863: 30220, 24301: -32097, -26608: -8747, -32337: -4850, 27215: 16975, -28845: 5184, 29948: 16776, -8096: -19809, 28922: 1579, -22399: -10320, 23633: 9402, 25594: -10014, -19789: 21539, 7783: -5857, 6413: 28988, 18148: 24286, 16425: -21685, -2117: 24914, 22809: -2465, -4052: 29220, -17437: -20536, 1701: -13236, 3559: -26792, 13260: 28650, 24280: 28935, -31390: 4155, -27444: 448, -15557: -22317, -26261: 14775, 8621: -19065, 854: -24623, -13346: -13154, 28008: 7670, 8308: -26926, -15207: -30554, -4728: -30539, 19116: -14938, -31105: 13428, -17085: 28001, 640: 29984, -30694: -21836, 31336: 29388, -23090: 26134, -22064: -8217, 23023: 25281, 28377: 3055, -826: 32149, -10250: 30089, -21073: -18570, -18476: -26801, -26910: -26764, -23220: -30649, 11262: 14325, 3587: 12688, -20447: -11553, -14604: -1133, 3267: 12700, -30988: -604, 31066: -5487, 4192: 1516, -9863: 26649, -12142: 839, -5180: -23733, 4771: 18192, -30173: 21726, 5816: -6256, -332: -23918, 9971: 21833, 368: 10035, 7709: 315, 18131: 27655, -12214: -2422, 8036: -21700, -12127: 30496, -17331: 23521, -5948: -28752, 9996: -22175, -12256: -9599, 12127: -14043, 8773: 23434, -24251: 31338, -30890: 4170, 796: 22060, -9480: -23318, 30137: -12439, -11200: -14846, -20960: -6630, -11449: -12059, 1710: -25246, 27339: -29509, 23266: -11878, 11424: 13957, -31513: -6604, 29223: 6248, 18427: 26701, -12933: -29661, -22958: 17397, -20885: -7075, -12532: 11832, -11207: -31040, -25413: -32634, -24423: 1136, 27748: -23097, 6865: -20862, 18880: -20717, -10317: -13842, -13186: -15707, 26939: -25776, 28970: 10404, -5636: 14068, -20214: 17872, 24853: 30283, 9956: 8484, 9398: -6284, -16839: 21664, 22800: -14869, 6033: 9989, -4795: -32223, 7279: -20473, 1275: -11857, 22338: 29810, 27015: -1704, -19258: 30646, 29954: 8034, -25853: 14141, 3311: -18597, -23320: -20940, -29480: 24564, 10547: 5534, -242: -13465, 24209: -1327, 10490: -5572, 7640: -20006, -8432: 5032, -11149: -24754, -4663: -23686, -10592: -7167, -25371: 22450, 4522: 7837, 6151: 19181, -18379: -20567, -31877: -18894, 17881: 7374, 24203: -4232, -15566: 16796, 5510: -31735, 15169: -20736, -29601: -27463, 7747: -430, 25280: -6754, -15509: 2251, -3086: -2933, 5884: 27703, -11157: -24312, 14484: -912, -3230: -9668, 16082: -25169, -137: 14744, -2665: -8726, 32412: 31615, -7276: -27566, 6279: 1989, -25300: -15901, 2440: 7619, 31956: 264, -5369: 16171, 14418: 1610, 18599: 4848, 20977: -22077, -6321: -4946, -8343: -22193, 1775: -19058, 26761: -28761, -12920: 27027, 4448: -11253, 25002: 4314, -22369: 23526, -12022: -7474, 32105: -12895, 1455: -4159, 15674: -28876, 11387: 18072, -27516: -8671, -10452: 32061, -29518: 28392, 29722: -20187, 15094: -22775, -31173: 17747, 28936: -12104, -19139: -6836, 10489: -818, -19250: 2431, -24391: 29686, 5886: 4259, 11123: 7634, 14067: 14441}, index_rand = 8788646705830835008 xs 1144700111 3351133221 1701312047 4140849688 # shrinks to ref input = {-995: -18367, -30184: -27030, 4338: -17464, -26495: 18470, -23875: 6714, 11043: 22383, -7998: 11935, 16847: 5368, -9936: 1676, 469: -14105, -25789: -439, 2949: -19822, -13219: -11532, -13024: 24096, 7755: -32141, 5267: 20461, 13213: 5297, -7746: 31930, -24638: 20376, 11502: 161, 28692: -9359, -5352: 788, 17858: 16574, -4832: 26375, 3089: 1666, -27646: -21448, -29415: 27692, 5699: -11459, 9914: -14535, 10779: 11740, -29883: 790, 1921: -17804, -2606: 26661, 355: 10341, -9220: -21783, 10130: 2847, -28778: -8331, -26138: 21104, 19481: -11787, 23407: -22704, -13780: 6006, 7248: 6188, 9583: -27582, -19931: 21871, 7757: 32217, 7030: 24321, 13903: -28335, -6040: -8746, -16956: 3084, -27320: 10074, -11931: 23573, -14684: -2347, 25890: 13771, 770: -22088, 3703: -21750, -20005: -1416, -7260: -3308, -13212: 5663, 11568: -1211, -31546: -12571, 1625: -28634, 29510: -27517, -14067: -32392, -6952: -15279, 32194: -28535, 22530: -9153, 23590: -10792, -24830: 4545, -1413: 4698, 13676: -29216, -22119: 20809, 11493: -23219, 30324: -19957, -19740: 9364, -28332: 23760, 7598: -15700, 5250: 5262, 8892: -11149, 512: 21208, -26713: -22645, 15901: -16244, -11774: 25184, -27782: 31736, 1932: 28625, -19899: -15534, -14500: 28168, -31943: -10376, 5096: -6393, -12529: -28083, 15871: -31782, 24491: 9705, -13197: -2280, 20267: 26985, -2805: -7895, -12439: -25986, -1013: 18461, 1975: 32395, 22412: 8807, 18620: -21921, 18836: -11655, 20099: 15576, -15176: -556, -16690: 10393, -20701: -25137, 16023: 6541, 6323: 30693, 22672: 4962, 6262: -6543, 16070: 8710, 16145: 28518, -1209: -18693, -28389: -24853, 17412: -24261, 3497: 10996, 9187: -19998, -32168: 10884, 3560: 7346, 22807: 23444, -23068: 18732, -26136: -17299, 4558: -4291, 16805: 25070, 23084: 30635, -25411: 22895, -2902: 31559, -7150: -27951, -20232: 1338, 6838: 27765, -31069: -28409, 11606: -29065, -13760: 30312, -2036: -14916, 25218: 18519, -10854: -7745, 27820: 15149, 102: 7496, 804: 9488, 30201: -8547, 32678: 20708, -25202: 31329, -5584: -22884, -5108: 30003, 25093: -865, 27335: 6724, -10328: 15249, 5215: -12859, 25426: -6436, 4131: 8277, -19570: 7708, 20395: 7626, 3155: 12890, 19644: 581, -19031: -9366, -7803: 24805, 6673: -15061, -10892: -20442, -28410: 17433, -18136: 18606, 16432: 31698, -9848: 7414, 10831: 4060, -19606: -19806, -26041: -14198, 7826: 18579, -12900: -19535, -21442: 30662, -9253: -13676, 4185: -25497, -32472: -11113, -20772: -21936, 30731: 247, -17401: -28973, -11698: -26755, -17077: -5017, 22536: -3777, 13939: 16609, -8959: -24782, 29183: 15322, 28738: -31932, 12914: -31447, 27024: 19561, -6230: -2767, -18069: 12291, -3808: -532, 8699: -30308, -13072: 26305, -24174: -1772, 5083: -26578, 32374: -29090, -32055: 12554, 8496: -6213, 3295: 7339, 13897: 31817, -32448: -28910, 16533: 26195, 16795: -8295, 23292: -32385, 15102: 2439, 9462: 19663, 24237: 21643, 5357: 20413, 2361: 5794, 25247: -17229, -4187: 5207, -21262: 19783, -24684: -4240, -24679: -18791, 2368: -8363, 12208: -20319, 23264: 16664, -13617: 1275, -19198: -25513, 5092: 16212, 15124: 28714, 21439: -1196, -4432: 30044, 9557: -4855, -22916: 1046, -26280: 25826, -27674: -20014, -13633: 27408, -10975: -4991, 26520: -9235, -6589: 27583, -31631: -21487, 31832: 8595, -18451: -12811, -10412: -24981, 17602: -10428, -25014: 15888, 21325: 14946, 7746: 2626, -29626: -22668, 29538: -5978, 21901: 5842, 13851: 31830, -11034: 29385, -3586: 7536, -6063: 32614, -11727: 16659, 29320: -1367, -21326: 9220, 3205: -1974, -4787: 12852, 30793: 2568, 25796: 9433, 19016: -13799, -9621: -14129, 20136: 20434, -18060: -13251, -634: 18285, 15435: 22675, 29971: 5174, 31997: -29557, 18450: 7875, 22519: -12860, -10973: -20277, -26809: 31348, 6220: 11504, -178: 22232, 9592: -1419, -13548: 27708, 6172: 20899, 27648: 15593, -12157: 24765, -3131: 27366, -1827: -2958, 18365: 18538, -17861: -8596, -25217: -20668, -4257: -9796, -27958: -17570, -11603: -23589, -17591: -21385, 23905: 22546, -6098: 13776, -26132: 18512, 8204: 14798, 29533: 4545, 62: 22711, -9020: -8280, 11140: -8181, 1781: 10516, -1334: 15284, -7224: 7160, -28987: 22020, -4891: 8434, -4403: 19578, -20394: 14965, 29827: -30255, -560: 29091, -23917: -11862, -13868: -21175, -10219: 16295, 2577: 3128, 9484: -11742, 8668: 21789, -25813: -8178, -21404: 29342, -21751: 13687, 18052: 7524, -19144: -30345, 24903: -25167, 30700: 1834, -28266: 27752, -30375: 954, -11219: -5836, 28011: 8806, 20451: -23577, 10616: -15512, 6848: 4786, -5701: -16618, 10552: -612, 14323: -30855, 25785: -3039, -423: -22087, 20028: 21248, -31919: 15338, -19884: 15952, -22678: -176}, index_rand = 4536586039788573449 # Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. xs 888006417 2608449019 3789353629 478040202 # shrinks to ref m = {0: 0} im-rc-15.0.0/proptest-regressions/ord/map.txt010064400017500001750000000005601365756323600173710ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. xs 888006417 2608449019 3789353629 478040202 # shrinks to ref m = {0: 0} im-rc-15.0.0/proptest-regressions/ord/set.txt010064400017500001750000000006001365756323600174020ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. cc d2977c225bfd8d461dea19c554cae04a48f9155854b53118264fb27b2dab49cb # shrinks to max = 1 im-rc-15.0.0/proptest-regressions/ser.txt010064400017500001750000000025451365756323600166260ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. xs 3983395997 40281418 114824171 2339847213 # shrinks to ref v = {1285771567, -841112960, -2090277076, 1080385872, 900828884, 615148720, -333870035, -1551786909, -1167746969, -1453736382, -1747821313, 367596715, 1982056530, -1495713558} xs 2832291072 3367532499 2480853836 1445020057 # shrinks to ref v = {-1006265241: 1190299023, -874470135: -656918271, -747552887: -119701798, -446035143: 289470610, -38617499: -70412299, -28555422: 742423513, 549345238: -1218765301, 1006459863: 373426025, 1730586809: 1217890615, 1741069766: 1330906833} xs 497222929 1550339526 1868828736 2852494662 # shrinks to ref v = {-33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, 0} xs 3367619631 4093181880 814513877 3641392342 # shrinks to ref v = {-33: 0, -32: 0, -31: 0, -30: 0, -29: 0, -28: 0, -27: 0, -26: 0, -25: 0, -24: 0, -23: 0, -22: 0, -21: 0, -20: 0, -19: 0, -18: 0, -17: 0, -16: 0, -15: 0, -14: 0, -13: 0, -12: 0, -11: 0, -10: 0, -9: 0, -8: 0, -7: 0, -6: 0, -5: 0, -4: 0, -3: 0, -2: 0, 0: 0} im-rc-15.0.0/proptest-regressions/sort.txt010064400017500001750000000041021365756323600170130ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. xs 1397459766 1987461941 1386942626 306293423 # shrinks to ref input = [0, 777418683, 1143505337, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1422499358, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1143505337, 0, -275943289, -1, 0, 0, 0, 777418684, 0, 777418684] im-rc-15.0.0/proptest-regressions/tests/ordset.txt010064400017500001750000000007601365756323600204740ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. cc ad212dea44eb83bbfd86396a2e0f9460ecb93f6b1a2644bc700ffc317638a37a # shrinks to actions = let mut set = OrdSet::new(); set.insert(0); let expected = vec![0]; assert_eq!(OrdSet::from(expected), set); im-rc-15.0.0/proptest-regressions/tests/vector.txt010064400017500001750000000214211365756323600204730ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. cc a81c870198d194d869b85a541fca54b5a3f3ea4e84705bfdede6212ad7451789 # shrinks to actions = [PushFront(0), PushFront(0), PushFront(0), PushFront(0), PushFront(0), PushFront(0), SplitLeft(0), PushFront(0), PushFront(0), PushFront(0), Remove(0), PopFront, PushFront(0), PushFront(0), PushFront(0), PushFront(0), PushFront(0), PushFront(0), SplitLeft(1026178654884686841), PushFront(0), PushFront(0), SplitLeft(2673257349917114567), PushFront(0), PushFront(0), PushFront(0), PushFront(0), JoinLeft([0, 0, 0, 0, 0, 0, 0]), PushFront(0), PushFront(0), SplitRight(6380212717721778205), JoinLeft([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), PopFront, Insert(0, 0), PushFront(0), PushFront(0), SplitRight(12236220624414400388), Insert(0, 0), PushFront(0), JoinLeft([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), SplitLeft(13848748256934322935), JoinLeft([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), JoinLeft([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), JoinLeft([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), JoinRight([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), SplitLeft(13115524110820767241), Insert(0, 0), JoinRight([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), PushFront(0), PopFront, PopFront, Remove(0), Insert(0, 0), PopFront, JoinRight([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), PopFront, PushFront(0), PopFront, PushFront(0), PushFront(0), Remove(0), SplitLeft(9383655485369749481), JoinRight([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), PopBack, PushFront(0), Insert(455053961473158936, 0), SplitRight(676041696221001931), PushBack(0), PopFront, JoinRight([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), JoinRight([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), JoinRight([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), PushFront(0), PushFront(0), PushFront(0), JoinLeft([0])] cc bae4a6aa243531a345cb36883fda4aebc84848fffe12d051df4e24ff22af3689 # shrinks to actions = let mut vec = Vector::new(); let mut vec_new = Vector::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); vec_new.append(vec); vec = vec_new; vec = vec.split_off(6); vec.pop_front(); vec.pop_front(); vec.push_front(0); vec.pop_front(); vec.push_front(0); vec.append(Vector::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); vec.split_off(141); let mut vec_new = Vector::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); vec_new.append(vec); vec = vec_new; vec.insert(41, 0); vec.pop_front(); vec.pop_front(); vec = vec.split_off(5); vec.pop_front(); vec.append(Vector::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); vec.append(Vector::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])); vec.push_front(0); vec.push_front(0); let mut vec_new = Vector::from([0]); vec_new.append(vec); vec = vec_new; cc 2c8368d1e6fe86c9b944a688cc167d961767ffb028ca724bb3c12e2716cbfbf9 # shrinks to actions = let mut vec = Vector::new(); let mut vec_new = Vector::from(vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // size 70 vec_new.append(vec); vec = vec_new; // len = 70 vec.append(Vector::from(vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 59, 108, 189, 95, 24, 92, 116, 211, 64, 195, 2, 58, 198, 130, 44, 163, 180, 50, 176, 78, 24, 2, 180, 91, 132, 176, 205, 155, 65, 228, 182, 175, 100, 204, 222])); // size 61 // len = 131 vec.insert(8, 88); // len = 132 vec.push_back(252); // len = 133 vec.insert(1, 65); // len = 134 let mut vec_new = Vector::from(vec![57, 103, 160, 147, 241, 248, 112, 54, 152, 245, 195, 156, 245, 143, 175, 51, 27, 183, 236, 77, 126, 27, 160, 172, 73, 179]); // size 26 vec_new.append(vec); vec = vec_new; // len = 160 vec.insert(0, 112); // len = 161 let mut vec_new = Vector::from(vec![191, 78, 196, 239, 181, 187, 82, 160]); // size 8 vec_new.append(vec); vec = vec_new; // len = 169 vec.pop_front(); // len = 168 vec.pop_back(); // len = 167 vec.insert(153, 32); // len = 168 vec.split_off(10); // len = 10 vec.insert(6, 131); // len = 11 vec.pop_front(); // len = 10 vec.insert(4, 235); // len = 11 vec.remove(8) // len = 10 vec.insert(6, 48); // len = 11 vec.insert(3, 194); // len = 12 vec.push_back(31); // len = 13 vec.pop_front(); // len = 12 vec.push_front(96); // len = 13 vec.push_back(77); // len = 14 vec.append(Vector::from(vec![70, 240, 146, 141, 164, 160, 150, 102, 163, 137, 14, 197, 249, 2, 249, 52, 9, 203, 50, 161, 148, 209, 86, 161, 34, 32, 189, 39, 208, 106, 47, 100, 194, 160, 147, 69, 4, 249, 250, 77, 73, 181, 49, 228, 141, 195, 210, 102, 73, 75, 167, 106, 233, 141, 182, 243, 42, 102, 166, 184, 248, 127, 120, 88, 246, 204, 127, 214, 30, 201, 205, 115, 28, 204, 26, 17, 67, 228, 44, 158, 15, 79, 141, 86, 101, 148, 76, 44, 216, 65])); // size 90 // len = 104 let mut vec_new = Vector::from(vec![123, 94, 60, 147, 41, 173, 214, 101, 145, 201, 69, 78, 61, 38, 60, 170, 56, 33, 65, 151, 28, 93, 16, 187, 49, 103, 52, 133, 253, 244, 125, 66, 56, 190, 17, 235, 117, 101, 212, 129, 170, 112, 203, 78, 217, 49, 176, 252, 8, 153, 178, 205, 211, 165, 197, 32, 171, 224, 17, 127, 56, 45, 36, 248, 66, 126, 110, 109, 94, 116, 189, 185, 24, 215, 87, 239, 248, 98, 134, 0, 249, 147, 197, 237, 6, 150, 30, 51, 149, 12, 31, 93, 95, 158, 229]); // size 95 vec_new.append(vec); vec = vec_new; // len = 199 vec.append(Vector::from(vec![127, 142, 241, 16, 254, 11, 153, 252, 3, 104, 61, 225, 73, 56, 149, 247, 142, 67, 4, 24, 96, 169, 234, 215, 227, 30, 84, 45, 209])); // size 29 // len = 228 vec.append(Vector::from(vec![194, 101, 202, 247, 108, 248, 86, 224, 255, 187, 50, 123, 93, 110, 63, 83, 122, 101, 48, 38])); // size 20 // len = 248 vec.push_front(80); // len = 249 vec.append(Vector::from(vec![228, 25, 146, 89, 230, 224, 101])); // size 7 // len = 256 let mut vec_new = Vector::from(vec![89, 252, 187, 201, 31, 229, 16, 211, 172, 223, 209, 123, 120, 100, 91, 241, 223, 42, 71, 212, 42, 113, 211, 128, 54, 142]); // size 26 vec_new.append(vec); vec = vec_new; // len = 282 vec = vec.split_off(188); // len = 94 let expected = vec![233, 141, 182, 243, 42, 102, 166, 184, 248, 127, 120, 88, 246, 204, 127, 214, 30, 201, 205, 115, 28, 204, 26, 17, 67, 228, 44, 158, 15, 79, 141, 86, 101, 148, 76, 44, 216, 65, 127, 142, 241, 16, 254, 11, 153, 252, 3, 104, 61, 225, 73, 56, 149, 247, 142, 67, 4, 24, 96, 169, 234, 215, 227, 30, 84, 45, 209, 194, 101, 202, 247, 108, 248, 86, 224, 255, 187, 50, 123, 93, 110, 63, 83, 122, 101, 48, 38, 228, 25, 146, 89, 230, 224, 101]; assert_eq!(Vector::from(expected), vec); im-rc-15.0.0/proptest-regressions/vector/mod.txt010064400017500001750000002731521365756323600201220ustar0000000000000000# Seeds for failure cases proptest has generated in the past. It is # automatically read and these particular cases re-run before any # novel cases are generated. # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. xs 781088174 2402437932 46071810 3445483747 # shrinks to ref vec = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] xs 1236163365 497060525 1875560600 3785939576 xs 2440477773 3871129562 3025797391 1057174199 # shrinks to ref vec1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ref vec2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] xs 3956050500 706730731 3245945489 2502775722 # shrinks to ref vec1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ref vec2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] cc cf2875f6f7c5648d87ffcab4ccac7f8a8f720c93ee377e89f8c86e542cc643bc cc 3f8ab4d20e0696c9811622b868e9e2e11df5e6195ffd427aa305e4c6b36937f0 # shrinks to ref input = [2074036082, -13825946, 1485618086, 938025892, 1634050283, 343602973, -606035941, 2086123502, 756455726, 1967901285, 417064296, 912931675, -48362083, -439614021, -192545534, 353571790, -1804858855, 908622705, 1183010347, -2019732894, 474300008, -1087280630, 1989024406, -1862412421, 1817688323, 1779903690, 645225408, 1290443907, 739077543, 1459983883, -19629421, 921340531, 1254057305, -1854941617, 339275035, 1177377681, -107461978, 1556951107, 1142459430, 418860714, -1711737411, 1787159709, -316274917, 1302348247, 181570291, -2076292901, -1093494155, 1763629984, -1195124258, 490574341, -681065204, 1238632378, 853854507, 42089611, 1831408714, -1041889085, -421564140, -1913933099, 926289166, 279182650, -2127045141, 1738196395, 2053843176, -2017898141, -399808861, 457054821, 1398259288, 560215405, 538259370, -1037968371, -737896076, 341049037, -1211866783, -1843247477, 602815427, -1981792594, -932949201, 1730346408, 173892487, -118710082, -993398654, -852952873, -1368077643, 321394671, 2093514113, 1831301356, 2104751555, -183869811, -1503190860, 1135803650, -25841157, 1218834281, -479227795, -1808365999, -1532913102, -1328086922, 1318622180, -1280127583, -802930281, -508955020, -1574788467, -1982208682, -563261649, -418424840, 2029013774, -1362803987, -638036545, -947262269, 1950557609, 1187410224, -1464584417, 1384726544, 413235774, 1436482752, 1395432848, 1656858203, 147231077, 1946166606, -701896304, 410570040, -1905606977, -1122557347, 2122591018, 567266348, -943154118, -1971951936, 590807013, 1967462062, 255252417, 2073823043, 1541319971, 1453203803, 1421341138, 132882974, -1352759657, 538478979, -140652930, -1307846641, -221794328, 584699783, 51954554, -1851000469, 400639112, -1849914695, -608123546, -1897558717, -938554976, -1021874582, -1619777886, 2098079695, -188166053, -654806278, -1089147663, 1364112441, -2080156329, 485140329, 1867162848, -1435377175, 1281905818, 464841556, 1285796301, 1233354604, 1251770836, 972787149, 194394838, -408637346, 297940676, -764140760, -535189066, -1222082930, 1999659587, -1466965620, -545915560, -33381613, -3391831, -1726247123, 1541843291, 618382071, 1692204756, -556631887, -1010281118, 547567742, 262071110, 1315561258, 1041276450, -200019451, 155953937, -1918010523, -2034646338, 179308692, -1851545907, 518204726, -1644852449, -930708052, -1533983680, 174298704, -1142603020, 400835696, -1032416568, -143748802, 89618872, 1498511740, -1964329731, 1985385121, 1338534044, 63395119, -2024486383, -1608930868, -2132981855, -1724578322, -1192711882, 1794405014, -1875127241, 220328451, -914341018, 1456640965, 1592862117, 1416491276, 457921478, 694438266, 1597638181, -1033179164, 1392568444, 1320710298, -1026116152, -1107223499, 2046373754, -802840884, 167120902, 2132541214, -1939037919, 376672960, -809965082, -629582607, -1849899910, -49034754, 814355126, 1904252470, -1995358474, -1535123866, 1964249876, 1541812798, 1216319781, 1448772690, -1676360707, -593183425, 367191330, -1015415169, -209835596, 973923323, -1379232452, -1678253796, -504812765, -2093303787, 1352940938, 1298454946, 1581876111, -1223031747, 2069730200, -1460608552, -1737622339, 1109644043, 2026556453, 1759367532, 1086741250, -167537825, 1616204085, -326437736, 955819637, 1295445215, 336028006, -1727534730, -968937744, -553518261, 1670053153, -1349953260, -2120024551, 1980134547, -1068452794, 1219491483, -390297250, -1475253674, 415787435, 1873218319, -964316540, 221387283, 1591083275, 1444258216, -1881949415, 776917485, -1456154045, -1552934014, 2084443571, -1120296261, -1579431939, -1519754301, -1709430045, -303381422, 129976350, 254373149, 1407938652, -334266500, 24715971, -1489003805, -344545827, -30707531, -1037864976, -1932107944, -1947334424, -450501819, -717436421, 555717916, 341387118, 369635675, 1599459501, -1778790486, -1104209594, -2118365426, -2054102940, -1118790563, 850092741, 2031700649, -2032648691, 209452659, 1033303173, -2138994429, 747531727, -1564008984, 479576488, -1210763963, -147017823, -78176051, -894576638, -1997663736, 414627089, -460407928, 242360038, -521406219, -1628996761, -744872182, -1441232914, 1846502295, -943262183, -1393886050, -2018639700, 145134549, 187913768, 69737401, -1313998467, 1510329953, -621473150, -982308299, 1043016699, -1651933122, -1244551793, -289264939, 1877434840, -885867921, -1455488637, 1208421381, -195139456, -507382900, -1417009162, -801223255, 913934347, 1483498591, 313323757, 684949109, -2138586829, -2071891390, -812202386, 1737302175, 1076518260, -526641190, -2049254033, 112548900, 323995436, -791419496, -1225118760, 642320913, 383365901, 1380650886, -339607804, 2033605956, 1103328389, -914762689, 1158292416, 1643458103, 139201662, -565020354, -1313785974, -863936467, 897894968, -1312998944, 1790634237, -752758530, 439608095, 1681084131, 233508147, 2013294518, 1823519587, 1660588466, 1812760899, 508524059, 1184818398, 213279538, -1222991812, -1978978464, 971476813, 1841261427, 2132433812, 1958231930, -117862732, 1650837593, 1029355018, 779022208, -1419168200, -340738059, -467041175, 329912954, 2132095988, -1585519098, 1323577018, -810116712, -1865039613, 1617692461, -1807759080, 344751862, 1450322400, -248458668, 237856838, 934330482, -649300467, -1895742412, -68722199, 288157201, -1819800236, 636713948, 1350627276, 86963139, 707515305, 1637864209, -951128924, 1833027683, -660390999, 727450477, -178917142, -1756743187, 153010136, 1146380330, 1149200284, -112449880, -1722382195, -1105256026, -562353456, 735928455, 1980254150, 166745367, 1589677843, 239612358, -1375912249, -232347030, -513829568, -715230968, -951636353, 35308988, 1058861976, -939881777, 389606025, -1455012972, 1789973526, 819109054, 2072323170, -1718042069, 415141655, 91908874, -375749327, 1622668705, 575657694, -1904593276, -67784013, -172853454, -484633603, -93271368, -1345817662, -1137764517, -1270761846, 726587010, 473120028, 178775245, -1701651765, 1526034877, -959144121, -183434587, -1617575041, 638251420, -1667918115, -829628671, 2035538892, 1670451796, 1392586407, -496019207, 903216680, 2100415815, -1980994623, -1052104848, 1457997902, 135859152, -108183568, -1097707977, -1374810787, 1180961208, -1307964614, -655644955, 1068486096, 581472280, 479947778, 136787664, -1476233191, -771095637, -1946363681, -21954842, -1629269370, 398541279, -1381636972, 456435952, 549611143, 1226758538, -665527736, 921771361, 1732495943, 857537416, -1311210307, 259851132, 54363142, -1872821125, -1558611717, -1561079726, -2050987563, 1820207889, 428187339, -1822780242, 676403468, -1654516077, 1731138284, -459002904, -2110845122, -621879519, 957958995, 1265282103, 243944836, -1271620168, 212486812, 1544089397, 1225721531, 1373272554, -1146075901, -31903557, -2122165744, 716785949, 773898185, -1697590745, 1139026087, -1128365692, -625874054, 1620393856, 2049458344, -638108114, 1006443422, 244013891, -959077606, 590687801, 1457741822, -836587639, 1164800185, 715176364, -1990226498, 1876286734, 1104112736, -1019905535, 1546003147, -1944204741, -1441042435, -1003488031, 1193976065, 454296507, 88091747, -1241971921, -372366427, -1131355056, -1993192868, 612679547, -1014555561, -2072304807, -181217339, -1230739815, 144971487, 636393978, -571012714, -1037687907, -1159249903, -656360123, -752128517, -616386904, 1621018842, 2120187290, 840041366, 1046715186, -213798416, 1220245598, -672389981, 963148331, -1445841173, -1758726199, 1919633920, -2120029560, -1217985998, 1161564327, -185318835, -1236360705, -956544035, -2144416202, -613210283, 1670320117, 828779231, 1146210465, 2096904410, -896703053, -1793409666, 484239052, 1374451134, -170334499, -1298101602, -1884559050, 120611217, 561196767, 825646390, -379512545, -1181612672, 1725080453, 894394587, -344082758, 736879648, 674694083, 1619268347, -496023195, -102002782, -842294653, 1841077684, -1510106855, 182713856, -202141272, -1506286097, -745352139, -1623254497, 1993580158, -1458213604, -1063096945, 1838489414, -1507167817, -1800227771, -1597408579, -786176532, 652248741, 369542434, 1568176235, 2131816918, 1675019550, -35228538, -626903300, 925830026, -2112784346, 417584189, -1057780140, 338713052, 825189157, -541098859, 795314319, 834369951, 1813578641, 1853897695, -508754162, 1131302557, 1842805572, -1386265126, -105109281, 1929191619, 365363316, 30848530, 1648738008, -5477858, -128018202, -1616404752, -706096224, -669233949, 1470778925, -818029978, -1123804154, -1801848224, -128380870, 1979870858, -2034279195, 24763756, 146178405, -87107679, -1276578948, -931079626, -19523975, -352157139, -2089700377, 878963733, -933252824, 177118516, 2007822342, 369516438, -223358742, 1555386773, 172477838, 696822368, 1734455136, -1691821089, -1710391517, -852385941, 985649133, -990853305, 2132107158, 1027224135, 1243623279, 1140262391, -680877276, -487308262, -2012563745, -158258209, -776719120, -280474401, -2089800633, 1110970379, 2042227416, 1822232534, 434874365, -1708107889, 564960608, 603651451, 670259206, 496003746, 1781379733, 263720034, 1348487686, -500344248, -47605549, 1083823409, -2112131381, 1360946561, 1032611909, 722713543, 631919140, -2020465896, -1425404176, -1057926350, 2016005948, 1500712949, -572195007, 1705736830, -607815961, -1110944216, 1521417863, -1845376244, 1600750078, 726936858, 1057595290, 621086544, -1389672811, 605472649, 1332661070, -906674643, -1110321279, -1411856682, -1152283803, 1551997284, -1920544851, -923902286, -1158501532, -183191214, -1440914774, 2039809837, 708032355, -783129450, 1757226306, -1934942490, -387201262, 954917910, 2047838574, 1011062626, 2013368665, -785120726, 2110535812, 1784304612, -1463847791, 1144411860, -245946308, -80365437, 1567197443, 1327272314, -140150720, 149507793, 1159202773, 1002514003, -1744390956, -1782985230, 1673971410, -777733567, -129088441, -79017303, 52585550, -334069958, 1154008540, -430846671, 1438426004, 1802651992, -1130101106, -1840626986, 436239024, -1031507775, 1338703766, -1672638532, -185408152, 2138867350, 1455179070, 495841734, 243789940, 119847865, 1584300320, -967618123, 450392156, -333159947, -658236010, 985332812, -828567444, -703879489, 810152232, 1362837274, 538318967, 1493290149, -795241024, -329956784, 1555841105, 1288467661, -712740577, -1555985260, -1096322447, -587003901, -1969396615, 1262483995, -745308685, 1415894777, -927442975, -1119406446, -841365439, 1590961822, -1137095817, -471430773, -1724561514, 1632082470, 1452194693, 1573724207, -1056390572, 1409850492, 1986869003, -1338889943, 1028065063, 852777652, -1970303190, -162211687, 191430130, 73303236, 1248707160, 1147073730, 1963985187, 85123011, 943234918, -589830911, 1615305226, 877377745, 413476354, -1485535096, 292861396, 587319220, -1093011335, -1323555037, -1357193160, 164263022, -972519902, 279224127, 711182294, -1995243735, -1793989650, 1352628071, -866818457, -77298747, 425992637, -1595732809, -700857521, 94834560, -351790881, -1648488658, -450350491, -2086521426, 125456589, 1699220019, 2068296684, -710274617, 646836800, 1804572376, 1258920542, -1787200449, -1903274259, 1206277195, 772958010, 303500230, -15790904, -1612308290, 1658129395, -395132767, -176780729, 701517154, -1141166097, -506094904, 419452540, -447817973, -1944275095, -587149278, 440910705, -1954163668, 284196487, 110272837, 1383525792, -1590873999, -2046627948, 1609135967, 1576362735, 1351579814, 1215558731, -1571835272, 1164889714, -1687222223, -308301954, 548400081, -1603661876, -1492992204, -1069693438, -146086196, 1654865162, -1744673963, -1916511304, 1156765219, 705280294, -1351994050, -1457658843, -1643654416, 1939831051, 592724212, -77904168, -841119817, -1916382996, 332785278, -523144810, -1937360372, -1783779649, -1296361371, -1334714400, -340608540, -557600043, -2121148923, 336729750, 70670973, 1700104880, 1211975311, -2065301796, 1350766899, 1008664094, 914213634, 1451337520, 72519135, 1621122800, -880167527, -1996260667, 1543405835, 19988, -1006109465, 1022821761, 1920504508, 1853584207, -1219874606, 818730373, -389483600, 1126720754, 1200031245, 90176802, 400890505, -632493449, 2126131937, 81577335, -831586672, -1557362007, 1624430684, -97733102, -874664357, 1859678361, -2058068798, 810835444, -797049033, 1588534622, 722602759, 587748230, -306983628, 2112257232, 222045709, 1806043771, -1995279884, 708369281, 1593214010, -594305532, -835696452, -261598470, 1700209807, 2132552449, 1134259195, -557873538, 666199347, -1370860865, -1291669929, -1982793775, -964359611, 1411523767, 874684473, 280843736, -772863939, -1760910534, 1834571177, -113850263, 964555207, 1700093129, -1291386198, -453641221, 1575423428, 1737962346, -1205243353, -1815954346, 69474747, 923104036, 1181772263, -1954223897, 1640227821, -2032732182, 741984480, 695783719, -1075712461, -451815548, 2088922812, -1074740902, 1530562045, 1991403690, 784239790, 840688915, -1065420476, -1783096063, 729574579, -721908166, -806317184, 804801148, 990212065, 166291018, -1286443454, -667451876, -308501055, -194874181, -1871320761, -1358248959, 2057411783, -1382427531, -710083396, 1875533947, -57075992, -1381920306, 511702421, 1053171309, -1989916206, 1155691146, 1768712079, -579366500, -1487994331, 1109105390, -448084072, -1316657967, 23535972, -610752518, 920167859, -685935559, -361038175, 614940771, -1835683232, -1464216722, 1567931048, -1994985293, -1575541261, -250001784, 1659320670, -1129013935, 1227172121, 1021763464, 1360636903, -1009013211, -658125530, -1375782121, 1240924938, 587120020, 251840472, 1919062628, 326163621, -1388285489, 1216631946, 95329632, -1263592868, 1431874243, 475640951, -1885419865, 138624677, -231681197, 1594004410, -114908843, -126965190, -897916266, -646374849, 2140471964, -42192764, -1136579062, -960331802, -1914310317, -161196491, -887650349, 1751087483, 1695100819, 910614545, 2031160212, 1827844249, 1184629796, -143447496, -1098200504, 189279679, 1324510949, -1446474674, 374348185, 814073640, 1059475157, 2106225596, -1353443328, 1489890147, -1710764596, -1784900998, -251447273, 2054477315, 1585596197, -961315036, -826391659, 910636006, 1693044605, 1064368829, 1494075395, 1316546601, -1915811198, -1968971680, 917565630, -911293726, 527747479, 1226513819, -1194618477, -1066559495, 615261865, 109378971, 1985712025, -2121477532, -710315708, 462546122, 244402885, -1169605677, -239741560, -1389817631, -2074550579, 426106154, -1406477206, -1611764701, 1220612586, -169469038, 1633206125, 703871587, 653033018, -1812149862, -143687434, 1563767746, -2029373357, 1133913077, -1365421112, 1830895650, -1241992896, -526096394, -1504042041, 2034202791, -116306895, -105403378, 1320613411, 914735204, -603131075, -1337211362, -709897527, -398529917, 864272188, 745999546, 65547189, 1861061706, 1212542882, 1333816648, -66085575, 746272134, -1975437052, 309057506, 1861395667, -1621979177, 1634029512, 1155954467, -967116681, -1160188235, 2144749944, 612130365, -1694063490, 1188913513, 1817673964, 1581379395, 850453154, -1821257251, 314169881, -586612280, 704538858, -550049394, -209614563, 662701873, -311754096, 1377384853, -2115678459, 838659047, 1425206620, 265309427, -1769712716, 794796500, 1776676236, 180574163, 1731804946, -1245564323, 124720676, 1536773954, -460052747, 1697871505, 1131379069, -230355481, -375495423, 649038466, -2053993612, 1646267153, 1066665731, 66317061, -357886827, -1529226434, -1720347572, 1374808084, -1683348431, -657294744, -1648480561, -142156380, 804824504, -393825521, 808709041, -666437984, -217705813, -2137435184, 1878510110, -1106819282, 801244361, -1643847311, -2000588465, 1420335452, -377832648, -1181104589, 710498099, 1776638075, 823288316, 1610711184, -1652544835, 132984139, -296219092, -114074886, -302097585, 1314050769, 1841154579, -1644619138, 528246600, -1276685666, -245772515, 507798437, -373604894, -1594177389, 53530042, 651204691, -2047265000, -311902066, 880688919, -1613610621, -400217694, 82248699, 642273308, -962271244, 762202930, 1377472172, -55275715, 1724616384, 487093745, -437663694, 168541739, -1812211398, -1672271840, 881873677, 1114714497, -904275714, 980093336, 540542544, 365158655, -916121916, -1187305107, 534011775, 782554968, 1163745042, 2035150524, -1512225129, -651081570, 362911732, -358329340, 1150492243, 182748386, 625114055, 882334292, 1098022965, 661677805, 1546581972, -514109477, 1643063823, -316855599, -442291463, 314094648, 1406436485, 767663595, 332893275, 1988709222, -1693267882, 474960718, -1711721184, 342144578, -1863678194, 2081877579, 2089996190, -471238875, -1097388511, 152530052, -993210765, -1805356187, -937869973, 112616890, -1650110162, -1948553974, 1610043089, -324810425, 1153590211, -2120221729, 1747016685, 1048445071, -200354549, -186862725, -815791749, -1319742901, -1672326416, 154887756, 600989314, 1621636945, -1511044851, -1989762847, 1244663259, -1972206082, -971692935, 159648606, 1886894019, 1256820220, -305051454, -1992313537, -1614655295, 2062970258, -732510151, -327269492, -972065271, 314883827, -804361736, -1802664745, -1393097923, 841119789, 1306073353, -1268939377, -1212140202, -5727530, -1219272851, -1944932538, -1284292025, 1613138533, -1566829015, -2124065514, -890344075, -1725254559, -340276035, 1888494158, 670809273, 490260198, -450901623, 1062109421, 1212084769, -1501158577, -1298993648, 1911739572, 1772401749, 1740321100, -114970408, 1894338453, -485024171, -997653831, -1343152304, -1902325295, 2020326338, -2021698673, -1714917529, -558328846, -1898519224, 1269234258, -1911896692, 1184951814, -724811169, -145504403, -593702511, 1898191072, -1480726052, 953055855, -1821482370, -1887272472, -546961180, -1304957288, -531926924, 823439575, 724449411, -1271201114, 927202475, -1535450500, -2147175631, -1112598415, 866322046, -1564446585, 29633599, -825456558, 150100279, -2101568583, 359203977, -1237656177, -1816457309, 1642157330, 1610350540, 765556957, 1631810071, -233161011, 1845036552, -1946832639, -720202126, 1238716982, -111929575, -61735137, 460862103, -964499783, -1719796295, 1431908922, -2021835794, 534546885, 606442281, 1595336494, 207703461, 1994438784, -896480284, 1985525729, -1708393804, 1394205953, -271754554, -563841883, -819961696, -1646837392, 343169754, -182200579, 1202996831, -1078270387, 1345234359, 393601534, -434470623, -1593472207, 1842910383, -1801179439, -1099448595, -823573945, -356217029, 1217853059, 420981607, 1454030672, 403134304, 867996715, 1600236310, -1419419307, -1419962415, 1305298669, 2020494006, -2109351160, 1650520625, -825913866, 1069743846, -1862232186, 606928841, 1158621547, 2104404684, -485894381, 1851371246, -50298200, -853066598, 985824221, 1004369806, 1102935179, 1510783885, 1656067979, 927075135, 1170380815, 1774084327, -481903018, 47851310, 44620135, 1330599795, 1350266355, -1554545431, 1064732618, 66409816, 65526106, 21165577, 427740885, 483723017, 35454706, -7354557, 1047226914, -945721408, 345991533, 1571094729, -1971201628, -1894897988, 1447332988, -1233870505, 603392934, 1072266402, 514282162, -1642540303, 1762619187, -832224359, 2077531767, -1517254591, -1712552797, -819974299, -1875907532, -1661342398, -990812716, -1240965349, 1607455043, -1377916738, -963550263, -1211027112, -1628311755, 1463570154, -1672122427, 894733706, 544168552, 606117200, -2026249981, -1974738484, -1158307622, -1365243007, -1562950578, 2079141243, -235622301, 614947263, 611227439, 85917271, -1177848821, -664696881, 1488438760, 1177956309, 59705022, 711345438, 923223046, 1203371455, -549647450, -35023964, -1505117893, 710465445, -1296368867, 1630729548, 1557945985, 844231014, 2005708325, -1290199164, 1304486157, -217612581, -1931913813, -970249370, 473025451, -200709418, 184538323, 1213312738, -2013039594, -1639401940, 525613809, 1245902519, 1706341080, 650706587, -1773352619, -1179651170, -575729581, -1730951972, -260659192, 1468639200, 1162190522, 1682825499, -878374032, 771849933, 240576651, 155325731, -960977566, -992840686, 2056114509, 1738055400, 294977645, 1264418031, -958333813, -1380453956, 499832797, 817392330, -1247263376, -777045122, -836124598, 899690640, 1527550217, 1305253225, 1044413882, 1814223024, 931157089, -1723631238, -817502582, -829951866, 2087626889, -1947546236, 971164418, 1939629075, 952567194, 1967395635, 1289866873, -1744342751, -13909708, -1681951265, -73308599, -1335323714, 337521938, 898485675, -961252002, -904441097, -829430518, 1647349729, 859110940, 1009996690, 1175364, -1731015109, -82089215, -1874190134, -1582759345, -595698798, -1796552845, 639185195, -2059403318, -637567169, -635726071, 1506201648, 971714982, -1001821939, 572478864, 186545027, -1574180302, -32768479, -576949254, 2052783601, -151628868, -2036643463, 1778894281, -1197478516, 1753628928, -946610274, 882925391, -1256849931, -222651507, -906735335, 1938435700, 345182693, 1104965399, -1649155143, 435000686, -1909422785, 1216166408, -1692256880, -888695288, -1768507878, -2063241053, 1828957201, -46194893, -489710286, -410395703, -2103572352, 988971566, -2101803910, -1895006133, -1195331642, -1252662530, 1707417472, -967229313, 1792762625, -1102087985, 387508985, 1231080158, 630489021, 880641861, 159427921, -516227521, -1630783764, 1115924174, 1425792795, -566104154, -1150501290, 1969777362, -1230136655, 684335591, -1027332760, 915071942, 838375480, 1507691727, 28096794, -1619278869, 1961812843, 1596475991, 1386509383, -1225479197, 1220206769, -1381497381, 1291039841, -803224587, -895608024, -1364075382, 958971519, 864821661, 243797844, 342931602, -164939684, -411568688, -618750496, -708408003, -1872778333, -1002871277, -584030075, -1666646320, -1808942452, -1981790540, -913956051, -60986585, -1792184994, -1238634575, 570040290, -1753449480, -1592475740, 749966826, -1880520928, -272864035, 1936731130, -773985737, -544732237, -1698904105, 2129148869, -2035046528, 829219482, 905659495, 1582796391, -192820708, -2001536680, 1701433266, 773507903, -766695198, 445972053, 1953498627, 2130699149, 1082788801, -818872630, -346828415, -1325716989, 1744486675, -1565767710, -1835163165, -867656874, 1335135691, 1793823082, -658815696, -689290922, -309120621, -1955820388, 93013624, 1486938108, -284530947, 1524825754, 1733900812, 1457593653, -1355871840, 648014650, 1755325084, -709076667, -764763066, 1739307655, 257954771, 2047109644, -156656991, 558478547, 1258135392, -656024989, 1024959894, -1512664685, -378250925, -1949903037, -139772205, 641075170, -1036173394, 881333798, -82300171, -974627005, 475862077, -1911663845, -1599081849, 23810813, 1957974322, 1503233714, -1722056665, -1378688795, 302037199, 826208596, -141706235, -1206737332, 669753363, 1982305051, -749055015, 1039516909, -498251521, 24230781, -866890024, 1905972132, 2121969063, 1568323848, 1982848987, -1672235500, -63968325, -325701882, 661605179, 1812026469, -399265824, 719541907, 1410608334, 1777006498, -1049031294, -1420572565, 1750207842, -329757753, -1457069586, 1420911533, 2141384494, 574688220, -535474851, 1817098927, 1745079322, -1397130927, 673154800, 1128049219, -9664779, -117030017, 1215158711, 609783724, -964683549, -354644958, 892408159, -1015147858, 1688871110, 786905015, -807927458, -1426313497, 738749954, 432699143, 2034921165, -1200485975, -1413453463, 1937157348, -362092578, 1356874957, -1709834974, 594752720, 946796298, 1854767205, -776650823, 213518265, -37832322, 377817837, -1549358859, 1865874275, -675793518, -853299874, 408852684, -2101382816, 2106904971, 641549702, 872639835, -1625781499, 1578043569, -1869099544, -1520434438, -5792783, -1501624842, 1591670846, -1679808201, 307611723, -1669856920, -1732370715, -1435788919, 1349286702, 1762122722, 444504859, 434118061, 1531872154, -1921635151, 461501365, 171995757, -787029246, 1450608733, -965916943, 2109390499, -968905926, -555935451, 197622877, -1273797603, -1146425472, 1025007550, -2044487715, -1766399309, 1444621382, -1366310202, -1920916880, -1555651494, -1535193099, -644504916, 1008757743, 2114227944, 2146670725, 1615083220, -375991599, 169656183, 347162435, 832769616, -1215247623, 714458165, -444110872, -310018744, 1499610027, 1464902845, -748242684, 863157776, 1156691939, -876228300, 1914798725, -716881422, -34404712, -1073518267, -1842831631, -1827986121, 1149347194, 1108742924, -1812776801, -1347072639, 703653852, -1664322579, -1516110764, 960302225, -2037192203, 152564419, 1172752504, -458652203, -416139558, 1395448680, -1562149933, 846592421, 1478024746, 1382685158, -1212006349, 62959140, -1052743695, 431591648, -1456232854, -144177870, -655319813, -1525278474, -872244779, -721521788, 45166108, 1095986725, -1077614150, -1456137894, 1438074383, -217036601, 958421168, -231776335, 1741860394, 242567606, -20690983, -804748349, -409173917, 22481376, 686480262, 2127592680, 89614444, 1684548825, -984033810, 244142203, -1819765814, -5864415, -1621233543, -1063410560, -986930256, -130908238, 508599121, 1318739213, 896055054, -90612498, -317988103, -264654415, -1329221037, 1470575530, 1164650924, -1071623508, -1437421278, 2135634422, -1240821586, 1076346272, -1266511203, 1250699414, -928392746, -1177069029, 1318782928, 843470750, -248021515, 1187937926, 1443419921, 878529241, -1118633192, 1947534301, 1494772836, 779692278, 253098856, 658362515, 84661694, 400271970, 1523996720, -1712995981, -267561915, 480800796, 1922989838, -460091455, -1832061899, -2047758766, -1864498316, 1124875090, 1574530078, 626652963, -1541103034, 674196527, 1569962865, -1372652113, 1385927992, 340709540, 171708628, 619839443, -348877606, 2027369285, -843916036, 1637078240, -814551079, 164779239, -485665085, -1588076105, 755263840, -115516048, -46400229, 1238897345, -395198949, -1800028195, 1773904467, 870834333, 1729827340, -661543153, 1964144948, -455531520, 1137110697, -281908104, -800939374, 1841735580, -1945155635, -1078994053, -1727806263, -2114522102, -694243633, 121866799, -2019364398, -1776580513, 266209479, 1672380585, -946581043, -815000738, -782944163, 2109990170, 514632370, -1636390124, -1146493658, 1808746770, 271495095, -1730754553, -2031292872, 1782264703, -1085845477, 45845271, -61199851, -1452794038, 766525656, 465624801, 564578530, -1536401328, -1350960158, -822844540, -1675533314, 1463564272, -858456464, 830256249, -1402020590, 1061822244, 2056427231, -818237356, 532810618, -135657641, -495351699, -1523926091, -1264935009, -864112343, -1121277765, -1387523599, 339045071, 696066596, 796576915, -368902456, 687860556, 1598519608, 455454634, -432810106, -1782184913, -1134133295, 1815259154, 248760036, 714170821, -66177395, -1543284772, -781067614, 1488997215, 1189488805, 74603448, 1015125628, -1352920507, -1585448216, -1565182640, 478156282, 1179041562, 1820827756, -1157795129, -1802276672, 209807979, -1309984341, 1129463870, -1886483323, 1281556385, 537249359, -1462568933, 1408903083, 2002922014, -1599364601, -1954412043, 364995218, 2130230766, -45339351, 1809174838, -597555785, -1694863938, 1590113653, -1515483817, -697800002, -856001429, 235165263, 507560979, 2127875549, -851572918, -1675427211, 1750307663, -614113733, -214111301, 1775363940, 1935997873, 821649232, 205051377, 1511250329, 298712720, -462817078, -1611814691, 1585121429, 612069516, -210320298, -925801814, -980440069, -2107723588, 117209888, 983127763, 1317541730, -717236993, -1876759792, -1316138379, -256985663, 1497690548, 1536687898, 266189925, 1992605358, 1062600270, -663324143, -975208133, 389924880, 1274310235, 170158308, -1384484254, -1831200218, 1898972867, -492853557, 61806028, 1273757991, -1160788979, -424235333, 437862120, -1059353567, 1853494041, 72071260, -1109873047, 167168738, 1520669889, 1180353142, -1481132995, -357402117, -369109703, 1291650654, -1600486499, -1082549661, -1749813781, 2105194217, 1032420477, 262986466, 194821755, 951729698, -275962403, 171767054, -674920470, 959584790, -679108067, -536711441, 887066445, -86563567, 1212841687, -421100963, -214630196, -1543529359, 937281409, -74279649, 963974934, -1990658056, 503440542, 2109210720, -232706253, 1009908221, -1854072025, -882006402, 712057373, -2109350230, 913223831, -161622508, -1964288122, 431926902, -401951225, -921597038, 711616884, 443179653, 806599158, -1633467433, -1651928717, -1227985736, -692216005, -2043662074, 1657634295, -279432510, 1688185410, 1329733075, 1925894026, -361652441, -2100044059, 614627571, -1988406558, -1093670315, -225607928, 1040892877, -551764273, 258020151, 1764708688, 1379025933, -1301742585, 193852539, -1049683994, 2096234346, 1441367841, -169123979, 1790047960, 1718395001, 1916251528, -823831239, 2028778371, -1263190013, 1773093197, 1464745833, 1557101023, 1171095454, -1305732503, -57688736, 534714168, 1336831841, 577399491, -1694162936, -688985713, -957445079, 1479776685, 1009735413, -1481884552, -2118003710, -107595726, 453231361, -1278085937, -1371933214, -1326750180, -1509814098, 104964229, -2124793331, -726494051, -1405813182, -569417804, 1350247623, -1893729588, -526892997, -523092364, -119332878, 690575897, 1356673196, 1240271248, 1336359033, -1424078190, 777312073, -698621368, -1265466655, -913875957, 414763056, -2024757661, 150811391, 1985421865, -276870421, -734979648, -1159784487, 1908805935, -1412188802, 3707295, -803678155, 1353282903, 1092966435, -519856726, 688511683, -1315285217, 1754532099, 731675915, 2036642622, -490675351, 702933419, 2054538165, -1605673030, 530137404, 631630234, -396828210, -457910645, 328936322, 1459368517, -626717242, -1493160930, -2024598588, 1185915275, 696036597, -761221335, -1456523719, 1046970154, -138840183, -1141389775, -1082707957, -1190849711, 1056337011, -522959331, 1010405190, -382694875, -1964500446, 1247583659, 1038167337, -1978296836, 1266009218, -1296473165, -1145916624, -899275827, 1193825143, 1413595896, -634764006, -878342348, 1542505892, 875211556, -166409244, 502753504, 1213055506, -603568940, 76615997, -1421135218, -213490441, -1168059769, -231967227, 1978211993, -1960258751, -1930974314, 360249920, -1919900572, -2062200627, -268952584, -1153432068, 627820224, -2130086132, -1868552892, -1909712430, 959778829, 1212057528, 258670222, -840166096, 1943036424, 116014457, -1384564186, 1184824951, 908074466, 1585254178, 98466435, -168240947, -863531830, -1427312059, 1284229190, 507098737, 941402140, -219402260, 1346622990, 1231522110, 507733839, -1610263475, 144940486, -1736219543, -1985784682, -1736477148, 603323115, -1129349621, 1089272848, 992075028, 36696481, -657430524, -1705217716, 327007641, 492791025, -1259407248, -1251063263, -111142734, 1450262749, -1220553021, 477158174, -70417219, -1694169983, -876747649, -523121266, 541922519, 1767514138, -149436036, 742074375, 467226103, -1645352866, 1463142293, -1079931863, -2079781743, 1248229926, 1321418176, 2048066386, -1608973805, 1544685842, -443485137, 690831677, 1640492515, 513242750, -1755983918, -672226322, 1549624163, 816639186, 646205565, -2142323173, -905952197, 703777055, -361653501, 44826984, -1379377990, 820248537, -1473766197, -2072259218, -388366794, -744795441, 873255125, -696641358, 433712478, 207213832, -1560365070, 2127711832, -1451704177, -1565862607, -893138308, 1456692780, 1348910332, -2121013998, 980276993, -1843061248, 604634047, -1232571302, -1165472835, 1156164852, -24630408, 1150613935, -203576330, 1286773721, 1977554936, -2039880063, -896639261, 381035347, -100644266, 219587978, 554988181, -393548497, -127309584, 909855725, -729457340, 1244918128, 337717193, 1722032001, 993989177, -898880404, 592326961, 1243729511, -465647747, -175536179, 777125268, -1471335967, -665574837, 1685142415, 1597001581, 840231777, -882099121, -316303168, 498831327, -662886359, -204322356, -41289200, 1585296337, 686025290, -169769641, 1003321996, -655288081, 1005986195, 814550702, 65769638, 2077078909, -1542497868, -2146482548, 379744626, -1963950020, -1557933593, 360176856, -121386100, -2078743455, 720428054, -119841489, 1154785840, 1515275690, -314559824, 1875610627, -1076311913, -1082989363, -181445483, -935200241, -61787913, 2135864170, 341352098, -159713250, -215695069, -397899140, -512684949, -12334642, -827156706, 740332051, -1763474847, 1204803845, -266555084, 895305683, 41473725, 1628813578, -112444784, -2111837439, -2108547200, -73161153, -702781657, 515297797, 1235614775, 10629611, -530023308, -548143140, 28726025, 449800942, 823846666, -714581681, 148920007, -54038626, -1051920081, -476868902, -1703879247, -938905943, -844892171, -1723049906, -933077256, -405211328, 66095241, -911785435, -1304378355, -1959897308, 952937046, 2123136523, 1205958787, 491498347, -1479208316, -1539225545, 1892839403, 2022346914, -268091380, -1868316126, -1040787542, -980745392, 1331153007, 386141789, 905136649, 1684659822, 162135379, 414483581, 701005460, 1480201692, -1378734756, -26663830, 2123027811, 2137781510, 1787376948, 1402927997, 527423640, 658729620, 1365138809, -18518360, -1230600230, 1013529188, 62224866, -477888403, -1253825556, 446687634, 941525323, 303729260, 1847788660, -1922037783, -477693880, 2017702746, -756743447, -244660715, 614705266, 255273660, -1393183902, 1670522150, -1560879023, 987843854, -166329927, 333448683, 804001381, 2067859291, -1199315134, -2078029009, 153842, 701127658, -1531549608, -1683478668, 1987577619, -1640582263, -2009199526, -412380532, 98749849, -1622982931, -149553096, 1542882428, -115820399, -1850379151, 4360834, -1533034354, -60836772, 655035911, -112587015, -1014416375, -734618575, 228765388, 356365259, -1720978146, 1710607987, -1789263947, 357197964, 410350068, -376736347, -501374844, -452867016, 1282014807, -11985927, 866210915, -1115431305, 1513930489, -1008652725, -551342155, 1941015218, 737178471, 1243940774, -1015983675, -53098971, 1175052126, -706117912, 517538224, -41378405, 1045433289, -1523129539, -1747847230, 638526342, 1915722861, -1698342417, -690431884, -955134729, -931915076, 328490030, -493518972, 984960214, -1886902365, 847353486, 798836730, -1054139840, -225804666, 407385152, -2147014033, -817638518, 1392445506, -961976157, -1421291746, -969326438, 1854942995, -484593744, -178727688, -1445470311, 1053803562, 1738927941, -1664962209, -899079492, 407751969, -1398488508, -973290192, 920431027, 1856922128, 2096160299, 1969255694, 203478216, -1338364749, -1652169167, -1533707229, -50510061, -1523764991, -691586996, -53824577, -737226924, -1426166019, 1281653039, -53358504, -1929518512, -529993360, -651674151, 1498810198, 1031393196, -1652135346, -51111247, 2091523585, 463536701, 1071500444, 540748347, -1795803951, -1915732026, -1661419024, 1029114990, -943529072, 1191387116, -548955746, -1234894541, 597527317, 276199807, 1534347243, -1314792800, 1431327081, 219153107, 972023687, 1901811873, 208388106, -125631310, -349149337, -1584150966, 1886912642, 910816749, -1929990238, -944824810, -1512832057, 763956042, -147358629, -803941828, 2051946990, -1094453475, -1929845707, 1147677932, 1509703282, -2023367159, 433193027, -1576664844, 467784813, 22707195, -1306487477, 1816452998, -1689783528, -1325463290, -1730861539, -1305484409, 921663692, 1095739859, -1693175328, -282877545, -2057324113, 692037929, 1371996733, 1523501989, 122700143, -1091200891, -1829463609, -535515134, -1275135525, 2082791475, -520777512, -1776275494, -720306156, 1033873346, 285927881, -231741121, 1128723274, -956072348, 1439571541, 400465914, -1709917383, 1521453111, 497485965, 1761977252, 957916923, 1519928337, -1868347828, 2058859760, -358080945, -735750927, -373871869, -1397041945, 766223779, 1953031959, -174605878, -550189113, -578254936, 2082017934, 2146629123, 652233524, 1695194840, 514322181, 306067373, 955171379, 1754955550, -648275577, -1536160045, 1152150347, 604002190, 751839298, -1689626970, 929055119, 13379357, -1571319025, -641498014, -215056514, 244571851, -1704294277, -1630617596, 281545329, 274608783, -1734503580, -748864779, 516015612, 1080659711, -2100788843, -1808091194, 1583937858, 999838812, -80396371, 1696942708, 972384977, 813845578, -1619818522, -827535035, 738564182, 1534735370, 1178084327, 1062099304, 649971853, -700047417, -1924569531, -1071445519, -1211292415, -1593959669, -612844096, -1489226422, 507356064, 2053936928, 1017591240, 1266532126, 1431797905, 1587222715, 412743829, -1337081654, -545271364, 145199956, -808302537, -1199919563, -633947214, 167847619, 1807643435, 1346678288, 1355332320, -1666549008, 1632904986, -1427036767, 1670652838, -1479994595, 2089300643, -1047712382, 1391799561, 75631797, 948338528, 1312184720, 1023391218, -1195405238, 1015022648, 235798234, 350656348, 1568644988, 1297496858, -449555341, -515678563, -1864857293, -975601193, -787245172, -1490952641, -1279827921, -1156382894, -646116073, 858316145, -769950195, -39710393, 88536925, -2001591585, 218665428, 917160146, -1814524748, -1137967214, -879059513, -1790020379, 324738303, 1766102514, 1542662684, -924069648, 849207790, -491346181, -536819925, -132727520, 1857712941, 16245144, -866306331, -1419882343, 107014671, 1621166321, -68371792, -2071733847, -1658684180, -440067934, -1950770570, 1094581455, 1213349283, 764120071, -1166648492, 1488933296, -1773499402, -1703199123, 591044452, -1960323109, -33062195, -1165353733, 1213061246, 1415146231, 503178368, -446015207, -1495681265, 1604961090, -293643754, -153737604, -1984907329, 1733363335, -224751819, 796487852, 291842267, -1523522304, -1999692197, 1585224455, -1947336254, 652171247, 2125622736, -1729122005, 1630500369, -1033340691, -1573825480, -1425784021, 643475951, 642365324, -410417441, -1117474800, -909065953, 1194559962, 219654505, 63902071, 1290842847, -152761154, -510349809, -1924129042, 876929856, -1542946447, -475627974, 639979112, -252277489, 1919595738, -1727027988, -927128707, 1089814321, -491152785, 1638330106, -171769176, -1916941547, 1184844161, -1432066173, -1846428288, 220569594, 2140975619, 1452208905, 545709105, 194454757, 1372868620, 976549084, -1111806262, 1888253043, 579383590, -122749484, 168602881, -843792615, 1156474714, 427561130, -491579788, -154084101, 281990897, -2145365970, -1736855559, -438031098, -461649071, -306375756, -1541604875, 457219811, -1582055094, 1071799174, 192394806, -1766023671, 29265591, 2016019049, -611312914, 1318164059, 182883028, 673515689, 183005279, 1973182098, -738598558, 1649146052, -1011477718, -674883198, -1440025384, 1485943453, -1540612093, 1751645316, -2023346810, 1172217580, -1979057075, -736452510, 2134957890, -1701950844, 899095091, 1714720890, -1332274654, 65951221, -810976604, 1157241557, -1165276632, -1542772984, 1812399258, -1829440226, 152305708, 1670513630, 305284046, 696737278, 1933663867, 861576708, 1839383951, -278897829, -79305507, 441656324, -2008503123, 1621004839, -870578638, -1730208427, 1957759346, 1103575856, 292047568, -1604654269, -1510607322, -994649786, 853450133, 763234175, 770708060, 207245487, -1652224543, -490118797, 809015561, 882514568, -389634273, -1607640505, -1569563654, -1682730374, -754592188, 809697056, -1630238741, -1059853554, 280545453, -1176206795, -1620359007, -540935421, 391335261, 2057639650, -498384398, 1717509668, -466886631, 2099709458, -1010958427, 237492257, -873659995, -863100008, -423916400, 889325355, -237567456, -1363946305, -1830059701, 1851239243, 1894589071, 2008064337, 987008987, -219902400, 1323847226, -779715482, -1308702154, -1072433298, -769712548, -2012197226, 353818730, 690469944, 1063129068, -699150855, -752626518, -1173024120, 782754308, -899165002, -2137234434, -891176536, -405501175, 1333656964, -1256821647, -1077501077, 901009235, 378761437, 599284084, 666828278, 55874734, 377787807, 1798946341, 1194014376, 1876826962, 1608228205, -1076408145, 1398475380, 301348623, -2054022313, 432707081, 708175639, 323240415, 60633891, -973452200, -1689748893, -2977077, 1113338446, 1416515366, 1349334298, 1360506403, -838025730, -1952999649, 892626520, 603370344, -1348924970, -1514831615, 1621780120, 1904091156, -376542737, -172218436, 2018768947, -907105355, -1188075675, 1648932414, -899254596, 1109814078, -1793918913, -1548947405, -603102396, 2133289174, 890080233, -2113689655, -1146758468, 1489026587, -743563222, -861689370, 884389758, 449661587, 1077338769, 1897813232, 328663778, -1130090121, 1275118235, 1366341604, -1532401782, -422522473, -349218791, 2140373727, 1873900768, 1876051608, 1766397489, -1767224732, 131722965, 982727640, -752126908, -805647151, 638454515, 1374318748, -1561916119, 561587896, -2064139410, -1281816449, 240506899, -513360137, 1282074327, 1296125714, 625818120, 1199136890, -506723482, 1891863429, -82757734, -1416947287, 1445796244, -413901900, 1937555621, 2107091689, 117504348, 508323586, -1186024288, 1899017606, -1440021746, 521842459, -545367972, -612927121, 1955002522, -1881853770, -552571106, 797659330, 1065526245, -612345780, -41590496, 674019778, -1001718101, -1160268420, -454980785, 854171887, -1245143394, -1791015528, 438117783, 307914154, 337432457, -1090078396, -876162814, -1289713183, 327803597, 1697976843, -558907482, -1321389478, 2044641609, -411540004, 1823501589, 864101340, -1834526660, 1373944591, -1470872387, -226948560, 1372901370, -343459744, -371903978, -1312661143, 2079977874, 742408150, -1499057941, 148641425, 930992199, 544815673, 721621148, -115765913, 973369083, 424415980, -1549216758, -618597574, 1958625024, 1409447570, -603057203, -1527975650, 2104993273, -1785576485, 1908566458, -1018595235, -1710853318, -2085488267, 1281240065, 2113803374, 13943608, -1602197456, 2118886771, 173527948, 1826580684, 1240872132, 1756539355, 2087896242, 922143479, -191504695, -647281978, -171958154, -1255476289, 294425289, 927598937, 21643811, 752692611, -1216529539, -1822079014, 727835201, -577227146, 1165470644, 1786365507, -1813710101, -427640263, -47602469, 53783715, 1730451702, -987636326, -466143974, -1589553810, -1546085501, -1579856642, -899045269, 1505340166, -1164671405, 1072451860, -270630959, 1127407499, -540868162, -619655340, -2126409526, 938216901, -919985099, -1495017247, -1669832294, -151931637, 1839544242, 322354554, 1162744525, 2020189868, -287543513, -483345027, 1446638495, 325228959, -81595817, 1256944124, -1335443082, 1174488134, 364886827, -432665666, -272256721, 400759525, 473083836, -76586090, 244784110, 1188380885, 47224998, -68517340, -237020813, 225843503, 809268006, 41025352, 246789768, 1562386753, 617286531, 1324190717, -1506349386, -816060755, -1047085903, -1256320331, -1689755530, -509368697, -1252406445, -493635213, -2068517664, 899953449, 1581255537, -1617441226, 566665114, -1418703509, -668728976, 1805297953, -1529964729, -834572918, 1689145568, 948831972, 1271117184, -1687381788, 869449980, 1442881835, 197891807, 1621361190, 763601265, 970005330, -816032339, -1241430961, 1117056540, -877805313, 1778383552, -159774267, 1240555093, 933104706, -361664214, -1811290450, 894792515, -1974847711, -1011138336, -572652545, -1707302102, 1140169109, -1335453049, -754708933, -1798188869, -1754444925, 1609153383, 1462870019, -741108495, -1724820016, -1169570857, -1084569577, 166777230, 479334092, 434596987, -1160735569, -1683063484, -1881199759, 1722044665, -1020537872, 1439400109, -370373873, 1753098600, 119497153, 1576101051, -2115202912, 435633137, 1306599882, 2144034428, -943895489, 1197688145, -1690081745, 1966957071, -348851055, -1361463887, -1888382666, -706634846, 972485267, -891440476, -1427508609, 941311775, -204585274, -1584501749, 886272286, 1571755314, 2043848673, 311817685, -408680502, -1862166670, 1635880377, 1527572249, -1278096467, 1377118958, 1262652294, -1091118984, 2086516397, 329263994, 1552769867, -1527200486, -288433628, -563095458, -1584940289, 1334024223, 84739785, -259323643, 1100044557, -1708124818, -1646970400, -1936117242, 2072709245, -1091407826, -1108277230, -373676421, -67633340, 657604325, 1041026038, -1028341463, 1679570632, 1239226158, 1795718869, -1488333441, 670992852, 1251054416, -1773451308, 1508564948, -1108870741, 1848096751, 1893161372, 2042195526, -362483196, -189831198, -285495841, 2043709061, 549374138, -111287294, 478916407, -643916159, 2142122101, 1137203221, 205551013, -1758558588, -1189008453, -451701807, 355995071, 330062930, 310199126, 224784831, 1892658682, -120385839, 1178968057, 1566699717, 798371275, -101779713, -941844963, -564997779, 2069034392, 1798122540, 85386757, -784717221, 788256701, -1179078391, 1135154351, 445136728, 1500872790, 1491120999, -1018865227, 199051662, 1631248559, 1766760035, -1782879050, 308670372, 97810757, 1899550948, -2115836087, -696785835, -1049465052, -1289485631, 444214640, 2073806889, -1021030787, 1894878195, -382280428, -1643933612, 844385613, 1415378315, 821275460, 2102153981, -1064533629, 1944293771, -1998418297, 1242240229, 1699066528, 2040562092, -637924728, -771300786, -169991445, 778433373, 840770087, 1838070208, 1752717773, 1618897921, 1875774154, -373420583, 414868140, -493259749, 494145806, 1231826404, -1989016460, 1203203125, -1135260036, 1977748055, -1283449017, 950247212, 555052392, -488604066, 98995573, 985206533, 607174138, 1924737373, -1737859837, 1869378340, -1977557385, -1858853390, -714707441, -84622775, 802100375, 1434368049, -92901442, 1296808709, 1044407033, -258855319, -1814197593, -1180528805, -1869160359, 2100941288, 812234670, 1274094733, -277835, 228226215, 232912929, -1647043102, 183688632, 1136157093, -268463502, -1739267292, -888602788, -1385421084, -731134281, -1986935102, 459189529, -2015786464, 1342661868, 1240237828, -1293099296, -1094483741, 734711780, -1319809365, 1216592081, 1827537819, -179100428, -329093053, -577009030, -164967258, -1454796743, 1971805902, -323992780, 411470479, -27745064, 1579764247, 770766563, 553750912, 647003888, 1967845144, 1545891632, -595124049, 332495090, 1036458285, 974929185, 784439635, -298652921, 573884910, -349289444, 2064444653, -1621191130, 1255429289, 1369286628, -1433326243, -36551775, -106999787, 451044656, -87845812, -1083898758, -1546608651, 959535292, 1139314193, 276523676, 1541728863, -141361712, 2012223166, 805615487, 1648293994, -1323439451, -186640956, 1373899813, 1796657697, -17274317, 1173436414, -2061081665, -104692029, 552834229, 427672444, -40957158, -598521306, 78868621, -1010455675, -1536817788, -1612736110, 1248796439, -248308003, 1572783690, -670686989, 673543969, 11031149, -1864475537, -1453479741, -1969593833, 273071032, 1189603735, -89223578, 735883119, -1514604429, 1725576379, 1994560422, 1775114857, 896871317, 243717529, 1105336340, -1479198180, 931758820, -1344797382, -777718000, -937648208, -1633310533, -1898865004, -885327079, -694800286, -1859490843, -1212249688, 1240546906, -748514324, -1394103798, 2073669105, -1980277407, -590188717, -1109104871, 1684070352, -2069414525, -1660187001, -2111825961, -201318458, -498248281, -1902567486, 1423117527, -1031737099, -983508297, -823424708, 2069553657, -335142975, -1326063098, 1486359973, -733643559, -786761187, 1697038670, -1091436486, -1928944452, -1695442241, -401154532, 1209432056, 1098530933, 1885489601, 1179541608, 331935293, 176913743, 3081219, -1434190816, -1505383146, 1803905797, -457572185, -1071534803, 11571048, 1131962527, -1771869382, 241183795, 37823486, 1217427161, 1987203666, -568735427, -306617172, 1161643530, 590564904, 1400167229, 1701097954, -952201977, -1129228133, 2095430190, -1000081087, -1923201529, -1761301594, 1927547539, -2123161595, -880460130, -1753228718, -1319847666, -90424752, -1833724758, -1161370626, 1746396178, 1152137535, 1297624921, 693033342, 1235425011, -808117992, -1844322023, 1203230081, 1792834707, -859528231, -1033081524, -572373380, 1990195773, -162570317, 1714745520, -1990949916, 1329926727, -776376214, -2114245141, 2135487702, -1416937561, 286296009, -304241500, 1576212335, 1259961504, -1889004976, -738773038, -1234269522, 1336373882, -382861588, -1933786274, 1993284879, -778592344, 1673217994, 734054451, 1265958727, 470887463, -1136611770, -797826828, -845643334, -464718680, 1264641961, -1214830467, 492726206, 251812049, 746694449, 1899336026, -51762697, -759125365, 1637988900, 673749776, 1473515398, -693266942, -1732826881, 157760323, -23029609, -2113927790, -1190920987, 1646600475, 310793168, -367260854, -1915046107, -1004175641, 1490227158, -1287766122, -1770297209, 2097838891, 1335129038, 408269560, 296936593, -1718727486, -487059993, -662017890, -1309116197, 426018789, 152263385, 719152480, -144526094, -126083625, -1731173609, -468284909, -554786558, 60877782, -1525879147, 1781464866, 151185691, 343636334, 1860584536, 1196616106, -1184296278, 620772008, 1769090949, -1944954026, 1901058524, 738333538, 754721325, -1476349118, 1745185259, 425188529, 1286989520, 402033204, 857854440, 145004339, -737493166, 2043189171, -858248635, 197383432, -358487916, -101346052, 828719427, 1163463215, 513712662, -86911793, -1238467517, 1703799957, -1003879642, -509271454, -1810329514, -2138156127, -950637028, 953540266, -785952983, 517116806, 1146919570, 1884706964, -2043708214, 233153451, 1858488921, 2081122223, 182807755, 1017136123, -1227998082, 569102866, 971760511, -1337926428, -967396970, 714451755, 936890372, 1657304674, 159246135, 1737453408, 889274779, 1093705692, 1902009733, -37633448, -1234081166, -473867125, 1219066117, 829674752, -44923731, -934855099, -878942314, -472397992, -1768482520, 1692918869, 1500983525, -1048871130, 349234751, -1950738688, 44237037, -958358960, -146976346, -2036028016, 1586327603, -167209353, 1899496947, 1738501276, 878188643, -426972254, -864406208, -1551660693, -2088937598, -2061053943, -1931753692, -1583219289, 176444714, 1743454252, -305535081, -1216351997, 1814870305, -237628264, 653602890, -616896896, -778803951, -959013264, -772004972, 1483984089, -793023314, -1254258183, -1070184181, -286779787, 556508486, -1765271586, -1510248020, 892731305, -1095823761, -1145760983, 1279293536, -1258762364, 1174533003, -434460605, -1643499501, -694465319, 1249839444, 1769811645, 469526682, -363913390, 1669258944, 1398157972, 642493446, 239282979, 1756119045, -880464279, 54315273, 862358681, 1151159196, -447772998, -238614009, 1624173119, -49335278, -1898197275, 421288608, 1263513648, -1952853509, -1204312840, 1007760506, -1631468313, 1662367972, -116668764, -537632551, -1094572564, -1262550033, 1104729134, -1779658610, 451398948, -512984257, 1579936149, 1168918838, 1844776551, 1424824056, 119232521, 838131160, 576387104, -1952740534, 2139630082, -1404800115, 440431011, -1020708846, -1476487036, -761323034, -1760043890, -586163271, -1066091016, 1491215679, -2028304454, -744471179, 1823203439, 1858757912, -2102915996, 1398459514, 886637164, 1839257546, -7107191, 1275403245, 1810290977, -542075957, 700835203, 1429066447, 676759135, -834382466, -953039724, -1749087564, 120317812, 17072646, -1942125795, 972240712, 148020674, -1591316233, -910449245, 1426073050, 1147534318, -936550476, -2081241319, -208748296, -960267372, -994110123, -613427933, -201595969, -205196827, 1647051338, 1800255508, -228058846, 70624346, -1842306369, 444655177, 1519873942, 198743973, 2123434816, -522298181, 1694721492, 1747571840, 852083982, 1546848600, -924944917, 356821868, 1709189508, 1668557110, -546818375, -1952199112, 989863762, 877136595, 992412062, 468931108, -463588557, -1022299235, -1046424340, 1420079433, 1548862723, 2137388235, 215317625, -271630187, -615775243, 190807702, -405769929, -1576130825, 1496142733, -1816684069, 135144401, -27072909, -981631974, -111025619, -692242667, -299529448, -1687847043, -392941988, 971233702, 600794222, -1051683690, -1122250514, 2111564991, -1602199506, -1701950254, 823121359, 1547122641, 1467659883, 133498611, 1065266807, 736412120, -1535887524, 449203580, 861102027, 1402576846, 328245414, 1153931228, 679875697, 1131167819, 596755769, 1338750611, -1730948388, -601796230, 670851701, 1563967767, 1992741842, 1659260503, 85445763, -533428286, 360259523, 1891477125, 1855743279, -652463979, 2088965943, 2079231939, -832482670, 1463180761, -801182039, -1160588152, 1630924181, 1733681719, 1859897246, -1218870190, -178910436, 2128076427, -1696546617, -692249829, -1995884661, 2107745556, 1827043533, 2038838233, -1448254580, -538119379, -372960911, -99879391, 1062853129, -1203762349, -1132583315, 623474890, 2118341926, -1549691210, -186827350, -594591207, -679962823, -68245454, -367434618, 426495, 586318770, -591370912, 2092805730, -100148441, 1709716404, 571477958, -185568072, 1046582057, -1047478805, 1831440204, 465849328, -350939875, 210582224, -1729745183, 75244795, -396883531, -243319899, -1969436122, 1314731936, -1918753892, -830896817, 684447648, -1544392575, 619529880, -330622431, -994511347, 2045003157, 1702070421, 490862419, 748577944, 291389637, -935634362, 1872525645, -1919864962, 1972665458, -35727230, -1716530400, 1168047645, -1064624250, 726532814, -1797857541, 394949659, 700463859, -379501333, -307664985, 1315401226, 1326569301, 1803528155, 2101958569, 1601695987, -1287374120, -1092751566, -1039584456, -2038173482, 1218511439, 1087579784, 588280399, 1309035880, -1852388772, -1257814555, -530773262, 1071041812, -1964545898, 1056903014, -1324831597, -859705221, 157302000, 481765849, 878480411, -1742504093, -1335975804, 1523860378, 731675379, 655850775, 1464113121, 1229879349, -251011086, 127432841, 280181141, 100193492, -109082009, 70498174, -1222911310, 779119011, -154051694, 1457747732, 937304362, -1018489071, -109525563, -885944448, -700534214, 929194314, -24302403, 19252334, 1605221340, 110622696, 1145782755, 1532085456, 692870428, -876682148, -1217491345, -1859580331, 1200856996, 156936207, -78999386, -202473350, 1957494031, 1217258624, -840951573, 446690427, -1554112269, -1474023399, 1159667145, -1373856588, -956707787, -300758204, -1079712574, -908623770, -552043928, -2125205393, -17902291, -1576782502, 1861074752, -1735575563, 570152198, 1043235675, 2114020604, 113362085, -675038828, -1701644914, 1294456644, 2002826066, 656766203, -1860683636, 1666227457, 1350539743, -1158617354, -764264913, 1232908095, -1043903274, -355073201, -934926572, 357353202, -1133796212, -118483349, 343744975, 1480665850, -235339094, -890930135, 703181016, 1593901304, -2116499641, -2136025892, 1886250291, -1421351409, 1995789030, 2011021743, -97709252, -529744802, -977079763, 1461719437, -263098075, -1631477150, 1732390911, -1473074318, -1386450233, -1527641596, -556198416, 1554454189, 913242433, -442030097, 750757981, -464848653, -560135963, 1463283303, -575727544, -2101442342, 1111285145, -1802737985, -1647880052, 310516965, 1321872843, 31232586, -1082359948, 1305288621, 101976628, -106800635, 905762446, 1405925544, -975354904, -1911913665, -1262258650, -2096778152, -397839680, 707372112, -2100946576, -1649095945, -1937463837, -1326087674, 780088137, -289955576, -1991644442, -1424190086, 791103730, 696238544, -1200068271, 176051935, -2085488814, -1522879659, -1386910667, -741143752, -1044807339, 1833100441, -1388385218, 243186997, -47865005, -1762318004, 789749490, 1371176934, -1263914852, -369045848, 481876275, 1372926182, -2012472678, -1853824242, -1896567703, -1089943017, -1667761452, -264180301, 228157639, -1916780821, 1985867650, 897451767, 153917328, -905842727, -1220592946, -631629644, -716032020, 2025552307, 1562522355, -1010334971, -927267644, 754628258, 1272622097, 1104384221, -1191154385, 302129978, 1429817251, -960492749, 1644424133, -432607704, 976364174, -1684542904, 1041548268, 606620247, 1864262959, 1486820202, -1829132864, 526926870, 1691389284, -2143249599, -1240381542, -1236473569, -1825200060, -499895390, -1637535245, -902454684, -829107044, 528212553, 107198702, -1012973430, -990199684, -1965130567, -676513468, -1620543935, 470941096, -1654856265, -2048023307, 1204292631, -285460060, -1041645981, 309005246, -838590854, -794658927, 1570231794, -479573069, -154676931, -849990516, 905343764, -499132333, 467057758, 1969418208, -445207676, 2118601161, 718466116, 1324001445, -760912398, -1290246249, 182358651, -1019630363, 129483290, -274190333, -1651993714, -801670429, 43806078, 1935129416, 833913418, 756357517, -1178262913, -806416792, 333729519, 1345590262, -675687454, -1241029615, -971185697, -2033122062, -150126464, 752197541, 1257262996, -1559877980, -1113563444, -1471836203, -2007241830, 1187672164, -986901908, 1445846479, -2114639958, -544630187, 1091212071, -1624183497, -2004556494, -166279234, 798117463, -1670153399, -1432361867, 258628212, -2004477786, -304798408, -1148921742, -1091694152, 1244634716, -1802075338, 399011352, 1776825991, -1819251867, -2122786300, 366608225, 57505644, 1203759938, 1952010824, -1277074148, -875778267, -269726540, -1779917729, -172824242, 1450740065, 571533550, 1018399355, -917165589, -1537685861, -468413845, -112354081, 356053472, 986848556, 1045826577, 531034714, -494638766, 282530995, -648991207, 952087813, -1350575928, -85554593, -1433724313, -1106876537, -92355303, -19732342, 1279456531, -511004989, 2090995347, -194068701, -931731999, -1538206530, -1552383898, 1963519743, -1262967083, 1533354297, 1360187660, -635195693, -1460496431, 39935695, -443925678, -1258451114, 1896558763, -1043378822, -497425755, 1591810520, -135620511, -1635599941, 394692628, -330139562, 1543271410, -1087167487, 1833490804, 2145519002, -1849664784, 1966398456, 245189112, 1504568730, 469359097, -1794286574, 795164740, 154462290, -1132404487, -770876585, 2067624732, 1732871411, -1099848450, -2128319171, 210355300, -566289010, -1875910766, -480568172, 759449271, 637007572, 1220173900, 707230374, -1881577458, -1805267881, -1440820388, -326639744, -498089825, -1219644263, -2114438404, 937098841, -1644360943, 1149071621, 13711491, 645592525, 1857886503, 1276685503, -666910404, -266525754, -1669889761, 264234806, 1942278121, -1720574312, -643229384, 2000722726, -1573775580, 424751713, 1675835969, -1507691437, 1341007072, 1461057880, 89175645, 1284879519, -289397664, 829547553, 810368094, -1499886709, 1527321152, 589356112, -1055023562, -1809562043, 630704973, -1198396920, 1959028384, 51047183, -301144489, 632190403, 2081882212, -724580298, 2960323, 1737756651, -296986722, -71500043, 428711865, 520330322, -913649778, -360470309, -229840389, 17668127, 1836815800, -204069960, 439927126, -1231647731, 1803185177, 979344492, -1811730920, 389991226, -428787354, 648547699, 1604400083, 610540386, -284111845, -409677162, 1827323956, 1066890655, -2036376927, 1625912905, 33644313, -654908008, 711866787, 1166450727, -1854177502, -1672411081, -2136266252, 256114931, -766448457, 1486804296, -687045679, 1141973195, 348013692, 1719141639, 151815235, -515836906, -1973594612, -1336567005, -1786283799, -255995280, -1697254859, -197079406, -355509594, -775387994, 242346369, 1320772486, -355027753, 669325257, -1915807227, -1563840374, 1591832013, -864114483, 1771449603, -1358512000, -1696431172, 396663951, 1980618706, -1797636647, -1318072264, -2100252126, 1676268892, -2041332538, 949691227, -1396800636, -1501010902, -264804697, 605240005, -2018431252, -1823549506, 466310182, -599408057, 2061867463, -1955295038, 167063533, -1117278095, 1046514742, 1317399331, -1487521166, 1708600723, -1532741043, 524638800, 539771184, -1567346127, -1902421047, 1327690622, -399452625, 1978419839, -629061309, 517688324, -437534223, -1848642769, -1139690349, 1678750513, 2079880294, -154610982, -1206647349, 1026064888, -1563666412, -1019699737, -165240022, -1257386366, 16302777, -262978839, -972882478, -1596255938, -1007073849, -1693791556, -1740592051, 1920877952, 571275343, -1913072584, -112346533, 140687899, 142746125, 1539887879, 1124219102, -2042017316, 1159369026, -325843437, -1548040643, 437748400, -945663933, 133028676, -602009872, 1021336736, -233900216, 2145278193, -1685176493, 848377624, 713661621, -1603239815, 1253527041, -785278329, -2086268247, -99491729, 441078542, 2089559025, -1736814327, -2050507416, -1941490914, -512316064, -334217179, 940238206, 1399465411, -181039888, -572169948, 51555859, 675967667, -1980359596, -1723433772, -1886919738, 635420604, -583742593, -1634534623, 1290419560, -171286316, -817731524, 1312434906, -1759898785, -597641420, -544637197, -786446916, 841976872, -1791656634, -1569334239, -398713270, -1059294103, -1867585648, -734953327, -880867153, -837556602, -279074386, -473751100, 425227347, -727733420, 445990327, 635489545, -171288146, 626570935, -811611765, -2129693076, 1815181583, 2125699706, 1040368352, -1500182902, -827534427, -383495021, 1789798837, -2010095577, 2113181078, -1661360834, -1572673619, -156940158, 795771145, 1163588952, -1802413131, 1401931213, 91226831, 2133220100, 935639448, -794624944, -1207195477, -1907460372, 1017424463, -680334818, 537568387, 230845850, -1921146749, -107784639, 1448104587, 175526440, -827678372, -565172898, 892702235, 696460198, -523011714, -336228181, -53616394, 1484216828, 265473548, -811628463, -1426021115, 563112684, -728445080, -2108323126, 1770008742, 598117421, 289095112, -998266551, -991483720, 1012931207, 862005234, 1157773152, -856461279, 718081425, 890695050, -740010500, -1927331273, 732297547, -1060523192, -1610911492, -890318860, -2017287250, -1120743580, -203363363, -1043762290, -22037002, -264942164, -2021176334, -1800389354, -1504514478, -2063684746, 507745979, 811594422, 92249453, -839707683, 507943321, 550798292, -949118789, 932689129, -1483738191, 1759552051, -576389545, 1762152188, 1834491834, -701055718, 883658446, -1901711315, -22631475, 1904271650, -2135132253, 1461801992, -1523997509, 1816037203, 222963140, -463417628, -1086614918, -586342172, -1296250552, 1889492219, -1044343908, -1078371457, 1417179645, 1346055525, -1338333065, 240401292, 898463601, 2028103463, 1377471906, -1836081296, 476069707, 1776633981, -530452195, 968288932, 890819322, -1721041526, 881436101, -716205717, 1255670978, -698960771, 186221364, -1901368678, 13181266, -2021821419, 460530331, -1429362158, 1697726533, 1670115754, -1966795588, -168772316, -1214244161, 1209299080, 1476610933, -1445477393, -1336885137, -1458416740, -710253153, 717281492, -756110181, 1841549480, -1755847037, 1332182527, 955341156, 609214889, -811914714, 1628590942, -93174401, -1388811628, -516356831, -439546673, -1893975994, 1663021042, 1221883868, 239980858, -1466840556, -1619368065, 322640641, -951835123, -1038985615, -683118049, -670282787, -690866931, -449847012, -2061995824, -1388102853, 1516477368, 640253607, -1294087941, 309512468, -1611487107, -1909178758, 1235324156, -1017876933, 1118500709, 1110078562, -1170032855, 2051276038, -2022107000, -723906642, -1101379734, 1864642487, 632483563, -791748618, -986341006, -1908799289, 1305123120, 1726845770, 1850076284, 10511938, -867482539, 306639099, 1716648769, 202374649, -349524953, 1892990254, 1358814887, 1316030237, -577592670, -307946206, 1001830832, -528012684, 5525052, 243506457, -1323434124, 1375456664, -1165563580, -1343647460, 2085752549, 2102600358, -1043876060, 688338850, -667790744, 863013870, 723589796, -2068797193, -192827102, -2091522913, -1125941991, 40717391, -980112913, 1531854866, 1378300095, -865037397, 492844750, -1072377504, -1366962286, -569487310, 442014001, 2007878499, 1922820830, 926929369, 1093596960, 1736700104, -1370953907, -1084090578, 1974542370, -835520428, 515532608, 560437430, -813446277, -832587750, -1658872626, 588658049, 983262531, -1138021283, -915679804, -1808842116, -1732775241, -37732711, -139382643, -198280124, -753073922, -1661346037, 2026396101, 1432382120, -373896278, -1924437090, 730209528, -1593592886, -1259921071, 1366064174, 1343817041, -1974113258, -2104197288, -463028945, -2003101712, -1158200293, -482546759, -1202123214, 1106144636, -1048992621, -1716920381, -1983708276, -872999994, 1658308024, -161843086, -1104434361, -1810553563, 1586629286, 1943507021, 1239585779, 1497381990, 23941066, -1511485983, -1292172121, -525319595, 881872134, -537970334, -1261921096, -1481128204, -181565511, -908995954, 1261259922, -289729113, 908906986, 827560189, -744583768, -1774545524, 1641401552, 1479675189, 2094110052, -1660646617, -467649449, 1176466223, -1971337345, -142127535, 16936052, 92032033, 588921646, 430204899, 1450378766, -1294295346, 953133127, 2109622255, -44060504, -1628122187, -1965740641, -1291543529, -595254331, 751934582, -14179300, 1903705376, -282027011, -626177449, 1787407780, -1606210013, 202969546, -569436844, 1802381428, 1214079296, 1979721392, -474518336, 888014255, 947457302, -1629617301, -750493122, -582516055, -1556977732, -1156580924, -386127641, -1474706510, 1043354379, 779865585, 1492331480, -907328017, 1712098283, -1560289910, 446047665, 1828028329, -829261274, -89699967, 743025664, -1689810597, 1383953176, 155486689, -714590538, 944445991, -757630916, 1258251027, 901437248, -1666374860, -278797100, -1588249212, 60265301, -888566258, -975212770, -1050667488, 1132897368, -568759879, 1778024782, 1265136, 432500843, -395613238, -481388386, -1295348292, -1063206471, 1182932192, 763997125, -1668438736, 1147987730, -1299591081, 1798711578, -1431081630, -995701160, -1937413884, -271552178, -1138524257, -1167464766, -1346163499, 1232997848, 79055216, 731065700, -135452621, 2142188485, -1696629842, 1291212111, -1256697752, 2107450363, -1532556144, 1594302050, -32439309, 671974139, 1184833140, 116018108, 1134849256, 1278619505, -1266026451, 649868591, -1293351797, -869726441, 1154499396, 1306229413, -334065883, -102088072, -1722293900, -397427540, -1264896145, -1265834122, -1158632899, 1727689690, 1394681036, 846314537, 22693533, -1473756825, -1168173184, 1566834549, 205766209, -188916286, 2018032159, 657159513, -1353289563, 950448763, -824578740, -1330551497, 1131370037, 2104825653, -1815931767, 1010327410, -429692101, 1889839321, 1390735967, -805901740, -1812076627, 2117839183, -1332543379, 1488558198, -984084432, -1212941465, 1919241598, -481513581, 495416308, 1678145196, 164935808, 62940067, -445100256, 636973430, -2109503989, -740546976, 1325287205, 269595300, -127163463, -485030574, 1757518990, 1525841992, 786502900, 34685337, -1827246441, -637214929, -2132456108, -2145068466, 482366670, 136455404, -1189251634, 1193571702, 1399591423, -605412824, 456959856, -240983508, 1101790475, 406309509, 1450379739, 1138603224, -1610604815, 1474957962, 737892750, -1863352403, 782239378, -96244599, 1166826194, 1430597679, -1414842655, -67896559, -1714244320, 1876213576, -141594411, 743227148, 1326103887, -2123741245, 1920795101, -1113100821, 1065934167, 1941371950, -1827742881, -1220891549, 384687433, 537505044, -1590238063, 1594202044, -825511470, -1928316518, -668030363, -97323434, -876701055, -1998473144, -1778352483, -1352806925, -1758641284, -553100970, -211681906, 387257811, 1507039009, 1804193901, 1058651819, 1161575196, 674709347, -319546981, -779538207, -1056611535, 251256344, 693404186, 437194922, -1658713950, -1801288432, 1018113721, 1338780308, -1216670331, -177752440, -761877877, -2089265100, -1613587474, -2056412345, 1869809804, -1135095829, 1896739193, -1652210165, -1381792955, 1347460579, 412548609, -1064099555, -222860994, 963497213, 534582273, -2145645948, -1695619591, -1053984336, 949046371, -1798042468, 1382981640, 914975224, 1977758142, -115912768, -927854003, -1888101238, 759311622, -1150381132, -635242601, 1702378448, 656920190, 330170442, -165869015, 786177024, -591730421, 1612998781, -1899126271, 765249873, 2087512946, 619979470, 2052306960, 1949077802, 725654678, 1809778443, -1222211418, 317127039, 1010145479, 2061683757, -28032099, 542650206, 1414017883, -2121220796, 1201370668, -1533701885, 1673507780, 1459625516, 1550957424, 562508126, -1439791928, -1008327214, -112005967, 163783558, -1608877525, 838637880, 1477659230, 830635822, -1080878017, 272070669, 1273867620, 180955359, 1457347688, -1933934457, 345622681, -2050107879, 517258659, 1585272397, 994567680, 1218919543, 673055822, 1771297071, 1827698889, -1982687164, 1076111895, 493057230, -1345851163, -843715648, 1444793790, -1680572085, 626572748, -797425747, 1736137105, 30668615, 615715417, 1386133100, 1844470421, -706966327, 1649859039, -853695528, -1699075962, 705101023, -1927867404, -210990334, 285119545, -63456911, 885527086, 1225888133, -1438597758, 1482202891, 1115394917, -1813462066, -325271838, -917557262, -1485034469, -2071964070, 1967708471, -308957317, 779168177, 680869515, 868021049, 1179897975, 885986630, -1201125406, 1007672284, -1995778044, 1669237647, 1102775073, -479698377, 112012052, 677407472, -2008228544, 1520295092, 1323540059, 1470520212, 247201932, -951322631, 1532334039, 2063700344, 1444835377, -1035289057, 1410714078, -1083505963, -1379420174, 1013396002, 1190436573, -1582951442, -821151101, -1942151161, -1380163371, 330171520, -2130715659, -28583501, -459995767, 973667761, -100453177, 307008783, 1345216289, 1524951312, 406465274, -28206299, 974183900, 536799226, 1630672756, 1129990123, 1353618907, 1089668189, 1904850333, 761952938, -871029652, -1822050367, -688586504, 272640830, 369035972, -1950878186, 1506509752, -998795898, -204219768, -1297629703, -899589825, -670683472, 1787960576, 1644016105, 338201866, 2116326931, -1899970629, 1642768842, -1131482762, -2112417422, 1778001898, -751926370, -459737543, -1847863240, 1624309077, 371959479, -306346411, 57355273, 1848838224, -453576818, -403673626, 157858522, 259945674, -2040696480, -1270438547, 959821219, 1235621123, -1200623479, 1865048288, -1413993835, 2095560907, -756457302, 1513341614, -1894743885, 465802130, 259217706, -1371355875, -825134093, -37760439, 1982607371, 982100976, -251461770, -109420740, -135303870, 1728254082, -1008755595, 1322635974, -1707814277, 1875502416, -606219798, 1414767934, 814026842, 260673651, 1060717532, -284469926, 603652165, -1926380281, -1480763498, -466085677, 1196938735, 1933902021, -1796760197, 1706198895, -366050591, 910643691, 97056506, -1141503023, 1588567766, 1279567070, -2028703996, 942925896, 243771320, -1111380510, -636551777, 1116350337, -858479096, 243543472, 1086819327, 986580791, 2007861973, 1031384023, -1143022022, 1912414163, 2142694296, 1007376573, 1311167569, 213499779, -740458032, -625478066, 1842838241, -593960214, 2128229231, -1955287224, -145847355, -1458464530, 87155307, -1040275014, -158823132, 1513561869, 913385656, 73953344, -1452911678, -777397744, 340137327, -370994148, 1573194720, -1663087073, -1990978380, 795522786, -83650937, -146455910, 483609360, 1585855387, -1943097118, -333323737, -1624074792, 667889848, -856114419, -1697745416, 1003506487, -1243529990, 607591537, -1811621020, -830991550, -1991348671, 1654977098, -1438865202, 1533704444, 1922463110, -1736638706, 1669981662, -345829244, -145942950, -625932037, -483179218, -221123135, -239959610, 282543504, -1599203680, -1742006890, 2012300773, -1105430060, -488277845, 1250922319, 838863466, -602547084, -1270174970, -797094148, -1801674023, -756778832, -941754326, -1189116397, -804409462, 1961039732, 74719705, 1030593184, -525977012, 1976015107, -1909474899, -1438007205, 943751455, 1598647373, -1126223250, 708225303, -1118695985, 536789188, 907843596, -607290504, 1439638712, -1198673677, 1300488445, 954212379, -1287227424, -2038595461, -1700445824, 1660525456, 1542921516, 1081759101, 1019408725, -129931464, 885268106, 1827191247, 329526872, 798939352, 900885749, 2090204093, 473854029, 6695964, -1571885698, -110882082, 1360464789, -1764692592, 624152982, 2090893717, 1282083699, 1890283721, -1713072328, 2101004478, 1907251765, 2068308684, -1149940849, 158125327, -306262136, -878617842, 1189970943, 2021037619, 477519483, 573804935, -93298682, 131138697, -1686110965, 1996378147, 1218292861, -1065325500, 1153402104, 999429539, -825020119, -946863686, -546491620, 792965663, -1478230982, 1434355582, -1694587107, -1249998648, -1855177361, -165161591, 1900361506, 1150385829, -1133265106, -1185711560, -1601032693, 437639327, -762564174, 639983304, -2138540512, -145096692, 1615100466, -467352404, -158476663, 452435267, -450434914, 195998539, -1259992039, 795224178, -661157535, 841030443, -403277952, -1768037422, -1335240071, -550512051, -397812846, 1018278885, -232161122, 1269834741, 634632086, 1926132132, 41228271, 487936248, -1508845369, 917116262, 1281813022, 1704212280, 2111810946, 148202946, -1653513101, 405820496, 812478127, -952723355, -1462311828, 1261885727, 1355900418, 39907862, -1911695180, -1559337887, 1815492105, 1292313827, 1132464543, -1269081408, 1898988954, 1193860859, 874988722, -1821956494, -621347948, 584514376, -1702834466, -465070338, 608773666, 474381651, -1245585111, -895717575, 644848640, -1881777820, 143635668, -1709756281, -1386888345, 1190555952, 714512230, -1973957462, -1499364946, -1511587839, 896202, 1290661604, -402237274, 1428127237, 579764631, 529519317, 979321212, -1892940262, 1779521679, -398148027, 934598603, -749246543, -1100967958, 508803829, -1630055310, 360609136, 158452743, 1211077932, 2103255460, 56670632, -909447983, -1342511656, 1930148350, -435514010, -770012698, 1039873800, 60907859, -718848142, -1506054984, -1686872750, 1908002704, -1955072156, 973271765, -307695281, 271730751, 1954004650, -2089919630, -846140224, -2131570169, -1572407944, 1375770961, 1147452128, 1896431281, -373818574, 235371173, -1779227785, 198950782, -658496693, -1926918750, 1869666309, -699287279, -856560017, 1963282157, 1680103846, -326458250, -1110867595, -1560846156, 535507168, -1129704981, -1297440470, 1215457189, 850033624, -1543009727, 1280572133, -675991366, 109180501, -1797046838, 462655578, -529046673, -1965948407, -90951162, -380177492, -1745766119, 470634811, -1988136729, -1181484889, 2043371297, -201899802, -2051985861, 773608572, 1298870683, 510816179, 2024816508, 1390836454, -1965452238, 1573743511, 2101971164, -557058113, 2047008705, -572878059, -2082464174, 2045885280, -1618586685, 1493452403, 315480741, -67987897, 1223469625, -211714735, 1149868853, -935657783, 1466493203, 2017301009, -363746981, -1409286889, -1604842239, -1721593741, -537192233, -601988941, -1205793450, -1967814592, 1809022425, 1932153337, -1357861460, 1123475538, 1147013933, 1007919760, -699694192, -1621215384, 2066906763, 1593585584, -475179165, 1143779301, -586129542, 581667142, 1492996665, -134971460, -235503615, 1688906035, 1609196744, 804863894, -1108706764, -646274671, -1069027098, 311553694, -1470507906, -1491583483, -844554526, -1171833315, 528747721, -1553568712, -1214535735, 1833189196, 2038088431, 392821632, -763421480, 181827223, 1913070046, -138432946, -304292182, 788965993, 1363804715, 369791559, -790756598, -1515406361, 1410804574, 1418922680, -441340813, -815009575, -1319477066, -728139288, -1449300487, 825291269, -924837484, 1542189515, -270906537, 1400435540, -358233852, -569487515, -99471149, -1444933215, 1522524067, 1446272080, 1487929120, 1943218273, 658282521, 7347755, 961561183, 228439552, 1137293755, 363938864, -930460368, -1262721440, -869797469, 195520033, 1856208903, -1381644842, -592305889, 1757003289, 1106835980, -1025502300, 1224396970, 2030538064, 1003485845, -1144370309, -1414702345, -228124146, -1074354608, 858772232, -2021953086, 1064276939, 1069010619, 1723806992, -1007188432, 1223648261, -32515918, -623447269, -1448072414, 413259913, 1310414793, 1980915107, 493570171, -638293668, -1896394894, 166398873, 1409785101, 1913979640, -1369339660, -144931303, 1398112338, 60412969, -1943421350, -1259699187, 860635849, -703617878, 912943583, -68782392, -1462452538, 1048712056, 2125593372, -1041579446, 1055064102, -262831341, -390597151, -1886237962, -876353887, -1915419926, -739741206, 670877982, -887505070, -736496554, -1482640793, -1289390476, -1860099076, 913978138, 2073436184, -697867410, -892805022, 1207152920, 1501257191, 615876472, -1651410936, 873983899, -902943686, 1156004525, 1832528959, -70970686, 1700299358, -876801647, -1957871498, -1568919510, -1048671770, -1289317034, 134106918, -1505588421, -1849118863, 1199316838, -2035170223, 747626921, 1116667945, 1985054427, -1498370169, -1471611405, -2080774379, -1278151647, -1584771942, 1495636961, -1873481907, 999261603, -883260509, -1723319277, 1082082621, 2112267517, 256910441, 1997830435, 1388706801, -1269559003, -1378663323, 631109243, -1147447055, -498407177, -503070464, -80867569, 587142723, -1530994870, -1895948844, 879602891, -2146732507, 1539449883, 696223252, -774555031, -1632124035, -819276009, -1958336108, -1315318305, 1399945276, -1438713330, 333027049, 785191597, -1133532244, -544335033, -1583465980, 1044996113, -801383905, -1882042242, -1767000104, -81361628, 711688180, -1179435524, -1637699251, 1038689704, 2082705598, -440781644, -880896018, -1880945319, 746337773, -1962866863, 1607533296, 1414422096, -216229277, 1491338910, 1268751922, 868522498, 1949357131, 150085240, -823049178, 519874998, 906136211, 1880165097, -296882572, 240315750, -219188289, -1271262921, 1386352457, 954316131, 1773419711, -1676181866, 1692695249, 1162872812, -796950845, -454589314, 1363666157, -368936427, 1913907725, -2037447971, -1255659661, 487915960, 1125865361, -2072867838, 1895727173, -1926421755, 1909077464, -297156218, 1141419492, 445083635, 1903099022, 1578252925, 1615689799, 9784283, 945365131, 1869253655, 1363070015, 1415617857, -1374773332, -24053714, 1925912383, -1151725608, 1963254455, -115511523, 685088653, 1994257752, -2072935340, -1763247037, 738357279, 1788765089, 599689465, 299419577, -1338585751, -870923977, 1106427347, 1046307483, -1722366216, -1562445700, 1349834553, -1900560798, -1002876056, 1410932156, 206008985, 1932581636, 1120415175, -1107515363, 2122814359, 2115419589, 677032854, -960179552, -1032597134, 1306093785, 250598985, 1399346257, 1263885409, -1359723772, 127748795, -1507208801, -345316697, -319755401, 1817741375, -846437971, -200035232, 2032312812, 1229335204, -1083031187, -608035888, 1709684861, 1758175813, 1578717725, 731742106, 388472928, -1640530790, -424153774, -1226394775, -1185515317, 1467306038, 1804681745, 1774559423, -850048234, 2040572450, -1304240389, -1311073416, -288264857, 894150318, 433611492, 1942311868, -1264482697, 1651399709, 1494322772, 1145757174, -92428104, -180343351, -87504189, 1500850477, 1794815867, 1110876534, -82490581, -46497552, -564501467, 1463635859, 1190109641, -784415639, -2142848349, 350761483, 1814798667, -934644213, 187100501, 1579970904, -586308816, -935549978, 1257543356, 767611618, 99787424, -342521857, -1961608285, 109480681, -1436127526, 322671461, 551301944, 2019301372, 693391259, -569069231, -786187815, 1479195472, 522160502, -376816829, -231805591, -739346990, -1235881491, -132802300, -236315866, -1649160848, 612730780, -100952179, -592361085, 342552280, -1816075130, 673167457, 1317780803, 2063807754, -132379254, -1418234343, 1499984473, -1409360615, -728707861, -1974335171, -1313137885, -1609282390, 1430499621, 1523677325, 124994091, -707775005, 2087940175, 1642400182, 1855929786, 1622443457, -1778512979, -1634604238, 1154697200, -1803419191, 1748161442, -1651637928, 2036482523, 392144337, 1033708636, -1016121353, -1987713610, -754978281, -1628297382, -71273841, -1198093568, 256920147, 1166332723, 142219233, 1523109504, 1627351811, -835890113, -259316639, -122400349, -760823620, -1666156910, 1482428045, -1206379991, -749673126, -312537401, -1540369943, 1355015623, -1833521536, -590564618, 1736424678, -361506754, -511774703, 1447411201, 1232222002, 1918963668, -413877214, 1262435748, -490948743, 1408161504, -233871369, 1936684741, -865381569, -215528641, 970074732, 1621153848, -59102633, -179431796, -720491220, 1719189073, 1498905059, -514838544, -615472888, -1274722182, -1891936203, -1721272720, -363118408, -1044558805, 1242905928, 1436161059, -1600558211, -1692503435, -1061188758, -634857415, -1663890429, 897194027, 1212571456, -673313552, -1225956934, 479241108, -1931596749, 1293948144, -482554295, -869657421, -1514249432, 477405933, 2145290478, -757286371, 277994965, -1261504661, 139991951, 1887011790, -456366895, 1406093317, -886402325, 252494506, 689950503, 1356598053, -1004137644, -1192753277, 670062665, 1083906569, -1329649859, 1488888513, -969685318, 459043016, 1161313952, -1129497754, 1324467055, -1099019764, -203704355, -1069029839, 1278937085, 1073181115, 226875896, -264842983, 1980864560, -656047475, 1323231642, -601401053, -1946802418, -253790903, 119956763, -44364644, -1995613000, 1610683387, -1699262499, -2103180928, -63167324, -1300352141, -1009321940, -1044929750, -1800105049, -1979944148, 14222471, -1432640628, 1688235742, 424114623, 30308972, 1462966850, -359476729, 1488377264, -527220589, 1186931100, 1101973752, -1472579895, 1914931104, 283107098, -1931279151, -1718200491, 1792738082, 1667244170, -114658266, -1224265059, 351047092, -1605815820, 1516659109, 1462102522, 681751559, -807956376, -786865187, -1693372931, -673156580, 1309653081, 446052025, -186550220, -642009792, -2134745073, -449421949, -237043221, 1975064865, -1652125684, 382056507, 1942350801, 1154312036, -1127994577, -1260892858, -70777083, 594868445, -447760497, -1329308630, 1024084550, 766358247, 1827325386, 2144728345, -1298174473, 231860022, -418919919, -2085785440, 2141510387, 1462173083, -661695332, -1156528440, -1959187193, 807454502, -1248709382, 37646812, 1920730334, -661832103, -1190920655, -1881837225, -1201869824, -1208235575, -113727977, -1764793855, -1550797371, -1204731695, 186747613, -1218435074, 1957746366, 454163363, -65971481, -1304482776, 1544857664, 930738730, 1678677373, -1003320057, 1265725736, 1956891693, -417894949, 517277694, 891796487, 1228794427, -176209, 141634552, -439467150, 38106221, -1495901082, 2127996072, -1503461118, 1809040108, 1627496104, -333002288, 2137185931, -1073007113, 1720941082, -1271215886, -1127754397, -1851449345, -1880413021, 353079556, 1459902589, -1921484492, -1510958623, 751470763, -1833747000, -721794635, 2049922754, -291520455, -267044280, 1179388024, 155806298, 1307439864, -709701511, -1081407653, 428855877, -1835958873, -831847952, 2136018861, 1024638104, -1881292992, 936646378, -180466400, 126984382, -1639949024, -444567803, 1091572596, 492144947, -1486723177, 510355722, 33891022, 1803350302, 660921310, 638050765, 874880528, -1986177967, -993906518, 1593021621, -1452112927, -506004895, 437341923, 2119609533, -355668060, -1687323724, -1900041588, 704316977, -1283123831, -709142656, 1680380685, 1343855333, 844516429, -418250255, -656024350, 1228458056, -148191680, -1114556213, 260694258, -441056449, -536921038, -1942265700, -2125229175, -1696362218, -701065156, 560077529, 1036623286, -340511558, 553174342, -737076946, 247187933, -1843075350, -2014538342, -286725762, -830648809, 1006640706, 814528877, -1562137403, -1383810808, 936725162, -1832046635, -595664406, 235633427, 1215009721, -1330003543, 643602705, 9070321, -2122985511, -180874289, -434075224, 1320572600, 448007596, -355760708, -2139522265, 726143704, -558263286, 1711644270, 277293540, -1745861874, -238194849, -1650157982, 891602958, 202684487, -1288519012, 779269420, 716011377, -1529774751, 1115632997, -1246420280, -628585597, 605344052, 1095918929, 1991661933, 83529150, -734389870, 1180932781, -277376191, -872980168, -206171015, -2004269296, -1265516718, -496598906, -1999564102, -1393244179, -1186931866, 915367475, 1194803503, -1462110844, 1340433009, 106022459, 894231254, -494012522, 891382372, -1595168117, -718710097, -868678737, -1876520821, 1350247070, -256081870, -1126707659, 219836420, 607227376, -410259630, -298324977, 141330521, 898675034, 927792137, 1290363279, -595199101, 741850881, -584294764, -836313982, 847360395, 453335563, -1201739726, -286110583, -1890611187, 2950286, 643569779, 1497722778, 1897060465, 677554663, -982550542, -914478017, -992895552, -447444064, 1548929412, -116532649, -578468620, -275364510, -230633369, 1343574242, -1094772458, 84301202, -469969878, 406646030, 2124798447, -1890016752, 758405837, 1651791103, 391191697, -1928726777, -861867533, 4741298, 1816363658, -1473740502, 1922521014, 342230988, -121510671, 1164335844, 256081002, -567311466, 561087273, 1025637901, -613306517, 737542525, 1639112109, 1541340586, -1681025335, 95351556, 1885451465, -1128416918, -1699479660, 198419038, -1666750215, 604793566, 111605059, 683781445, 58947048, 38197788, 1131261318, 964566156, 651980285, -150493665, 1238783127, -1490740101, -73516038, 2066122730, -292995522, -204470899, 349527483, 2059205508, 1492966785, -271090742, 650255319, 178177003, -848926172, -14606861, 912695250, -459254434, 117523430, -545965159, 66550492, 1282668264, -1961586127, 55097911, -360396794, -1918077941, 1377716475, 1988039182, -38646403, -1326950323, 200257735, -1258891143, 375803543, 958470486, 194595748, -1260178113, 1714164163, -1315669042, -492111163, 892128870, 1704553781, 1558430931, -479396028, -728478785, 750924349, 355414235, 478559711, -1434394503, -1008211010, -1717713405, 189750720, -1264975434, 896427939, 978847597, -362686550, -1228966901, 677635207, -1512285449, -1461241351, 1666783574, 824410920, -1417763943, -603173782, -1141448292, -490432104, 1276321843, -12875786, 703613299, -515699362, 1191568619, 1549121985, -2057741765, -1223897867, -1156575124, -1335888653, -1074885462, 435418687, -1577552900, -166211098, -1705461745, 114134930, -1397417735, 2138784264, -1634583703, -2006347946, -909630394, -1965144503, -484300210, 1856096070, -723413990, 1793185962, 1614055343, 810913952, 1662972360, 1182830722, -1471719274, -1546129270, -307483904, 1968956976, -799070156, 1050658604, -1144697434, 89460728, -941428410, -122161052, -1350549960, 1607351415, 1932091470, 1523524394, -1823383970, 960590694, 847249804, -1149243035, -695583853, 686459825, -1343363100, -367498297, 2015530271, 16136716, 1958929914, 1503526383, 296919109, 814553155, 723033123, 580496578, -51354493, 1643839467, -617817823, 1224027864, -1236233218, 765971743, -1224816592, -1208290440, -913761583, -1770804960, -382906420, 1718065547, -429735563, 1912746017, -185128900, -1100384588, 1876289588, -300747725, -1227196825, 1835371648, 1076813716, -2006649175, -673100686, -215048223, -391801397, 123246221, 1158190854, -929001098, -817005448, 1781589109, -274468116, -1995063986, 1742686779, -1201077001, -213531050, 1284583888, -2041131732, -1496569734, -282273172, 183531725, -491997656, -447879478, -1265834145, 1583500155, -1210291916, -878092245, 1607261760, -1666100980, 1120309729, 1002218188, -1531157653, 1393530317, -2008773159, 1415749472, 972906647, -1758198483, -208300303, 1892302216, 494033915, -358341674, 840060403, -1966814599, -1287829260, -1459539048, -772357942, 59900265, -1506353715, -1319659359, -1663555389, 252836352, -656883971, 428100479, 151423145, 1418181703, 1694553898, 1858314111, -1262057723, -545181481, 788235257, 1044460438, 177740558, -1921328030, -322923173, -613090052, -512763215, -669801844, 1722324584, -463603493, 2146427480, 698414532, -1233859098, -1412257772, 120379379, 105339858, -1070572887, 2060852360, -1515083037, 2004731835, 118263430, 1141114334, -413524875, -501302207, -1490521176, 811346316, 884835676, 225107240, 1061444245, -829676748, 426127849, -941093591, 1129629822, -81832228, -1317037345, -1964677234, 275235138, 1502488877, -1554352636, 640613906, -1437798555, 196702482, 1902902971, -472103645, -1670986930, -1688408456, -278506322, -1782195120, -1393346494, -1349310538, 2042497814, 748168186, -444671224, 1338156424, -2145383314, -1514258676, 96996643, -1011442041, -1872055867, 152290864, 322225395, 570061937, -1124117913, -1033305006, -470630024, -81960967, 1464901700, 197750318, -164270934, 1271742859, 463512555, 776858483, 811851213, 1313823641, 1068864647, 905285845, -1067114775, 680811370, -656530561, -1325429453, 2080653677, -1595711403, -567009045, 322923102, 1502953872, 903482515, 1864192536, -757924707, -952190312, -1661511502, -1510483862, -330091202, -652277362, 468740797, -1760350751, -1897316850, -1667560635, 843087663, -2036900525, 1706138183, 1692755666, 409461481, 612918398, -981637914, -478080458, 672151357, 1620269160, -2003279943, 1425552948, -996267201, 71811080, 1689541523, -298179555, -1991497825, 2063037353, 354490008, 1304739678, -684427893, 1314608828, -2074732138, -1318288178, 446712634, -535533431, 1868742830, 1307429836, -1110701257, -752103582, -594250510, -1075350152, -124476854, -1044009920, 684010993, 767483345, -421437497, 2128934646, 1554106672, -1210282217, 1317462638, 1119098170, -489689085, 1242501075, 1474438679, 802577422, -1562705469, -1044966662, 348889038, -1638823850, -1457837203, 1441466964, 1208555157, -711054124, -1231243915, -1150925993, -1220754411, 1307470481, 622936937, -30094442, 1289118, -388114648, 754635617, 856727668, -291283758, 831410314, -1808557882, 87182148, 600411597, 1059398288, -1007267185, -615660547, -1669061323, 1476538285, 2048353399, 468484099, 1420871458, -101588779, -649442911, -97163154, -1613496541, -140285139, -1884559249, -1112984573, -1686654756, 1025522180, 184813412, 2141097723, -1257367414, 553224438, 25301844, -2142562813, 1755485472, 1839193418, -173533633, 371190304, 2018089405, -959463330, -18054443, 102729411, 1838998089, -1269614741, -824599975, -575373865, 1498056256, -678046591, 1553189018, -2018672366, -1793538382, 1462846791, -776054819, -1289769222, -525822720, 2109700966, -1358503882, 1667924983, 1269108284, 1175706598, 1626798475, 2129561451, -887248608, 1513759056, -1931683412, 1952942399, -1889093829, 1913030140, 1106814650, 315507327, -1184354610, -845267304, 86200420, -587958390, 970371571, -495246149, 1087212814, -929663949, -1988622590, -1087217094, -1294581982, -2002943521, -1511705422, -33438, 306070164, -794474068, -607379400, 995075290, -1947574462, 291138661, -1862026425, -284994431, 1981331325, -295095652, -1640664050, -502391647, -298147006, -759845877, -57850817, 62687211, -867523503, -2045788990, -1888838589, -429975345, -1618629335, -61416479, -1120648789, 258517897, -1270073923, 660994092, -1429166385, -840504072, -1435140398, -1341126539, -395745828, -811500847, -1160710657, 940755305, 270032119, -493228936, 796034185, -596653897, -1821200654, 1355130577, 1063640085, -462968182, 2128283302, -1913776328, 359717262, -1152333962, -998979542, 1975954391, -557806346, -463622556, 1216253080, -635822680, 718622920, 2013281180, -2004887289, 1829369658, 666403036, -349103516, 1527813962, -1135439226, -1161633003, -443906754, -1923472597, 1815774854, 1568116969, 2136400151, -827712414, 119489899, -2091704143, 1578039823, -204310972, 1639073175, 1973581756, -1405492023, 464695482, -574900055, 986315757, 1743760258, -132155111, 950211624, -570553748, -1038810430, 778193004, -1468229997, 234884206, -372299627, -751441573, 1425166080, 317414273, 1358862764, 1949216581, 1862852961, 1400729205, 416699274, -2023791725, -556950324, -1276507218, 1367038669, 810158340, -1253834255, 1547203648, 1712426469, -2040438668, -942745551, 1914533793, -1937965113, 1800509634, 2029585463, 1384292693, 1181618494, -413404740, 1561115879, 297314112, 229917094, -1978493305, 1214251529, -837122023, -833015636, 1954960522, 1006169068, -1531846893, 333842166, -1012672929, -469850904, 637048029, -395312868, -1380943487, -1892576823, 442180993, -1646482639, 1446446226, -1682016398, -1007453652, 888411462, 331116203, -629682089, -1718482518, 265043760, -1019221259, 1869846781, 936747089, -1517311213, 372562696, 906859232, -1425676017, 48975252, -1341854859, -2089180612, -1068076055, 1874892782, 1652169965, 1157943384, -773225543, -323996276, -818862632, 156005302, 2000519514, 1427820008, -1021442831, 1804302941, -1609750249, 1228352825, -1290885767, -1899483953, -1272003119, -1035472828, 2001303805, 1279880126, -1972758673, -860699977, -895677, 1553908866, -256889456, -54349105, 1935563167, 1959654550, 1342306927, -463860350, 2018212448, -1976136873, -1321789709, 519290351, -878196271, 1416391706, 1997808027, -741508841, -647346054, 646400542, -1106467688, 1468263050, -1425279304, 1170563435, -1841378329, 1184969864, 1914824652, -1325456412, 988552147, 884565065, 415800418, -453574918, 275834609, 48207744, 2135467314, 702477650, 102965566, -763968440, 471224482, -1279720951, 739300156, 2136013176, -2115946465, 823955913, -1847689566, -859494013, -1717723340, 421442946, -775469653, -1602093703, 628061442, -1156466954, 2146056167, 1163863080, 613966968, -268941904, 1130830948, -1580207712, -1766534996, 385727357, 320405604, -2144049214, 1276259991, 1344448621, 489194245, -1847841712, 756151600, -151969326, 164358178, 697709449, -370308967, 2093670590, -665704333, -134953266, 759941983, 672239619, 279015781, 1395133283, -842458038, -1524105337, 182288246, 1431853343, 78700095, 1433355670, -24593159, 527405240, 1406613517, -764183089, 686495640, 2053356436, 1543473442, 1665227150, -16894973, 1892440712, 1791400383, -1510847956, -1214782850, 916872379, -1086841580, -1084208313, 416347580, -268161060, -594948841, -1010051534, -54545220, 22879806, 22079373, 260808346, 1499853288, 752706288, -1446555783, -1508906906, -142572826, 2085624580, -1694570799, 1322533584, -1634778380, 1720243426, -446724573, -966715585, -1060769188, -303942680, 101162157, -478783329, -2024114681, -254341969, 979137120, -303649029, 808347593, 321882488, 1493080090, 1691499643, -418789643, -1064499066, -1102944414, 879990377, 1588432383, 1150856295, -1680509849, 1970957530, -797026769, -73327919, 748785685, 1215011973, 585217952, -886677309, 1766904120, 365332543, -1482001054, -326119897, -1445345695, 1456094038, 1027199429, 1010128020, -1080582474, 2023702212, 1350470435, 390289859, -165678955, 1391872715, -2036012256, 583114991, -1027988504, -872534637, -980212881, -1929975011, -327092927, 734121734, 1585555479, 550659297, 1974120794, -923753061, 2043915994, 1159226886, -1806512234, -1828935780, -1530965616, 873171067, -1789687415, -1872307293, -417901750, 1741334968, -360712375, -1022301158, 1865882568, 1200151331, 2145666141, -2027655890, 687151700, 1410594918, 974900322, -1519354448, -156678080, -226110093, -1047772447, -1719525872] cc e62da794bbaf569bec601c6ce85d8ca80d85b726d10347a487524807c76e9e9a # shrinks to ref input = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] cc 6bb8dfa5f2a1b8c2e7cbd18e81b31724ea1e121e84061ee6fa6a8ad7ed62fbe2 # shrinks to ref input = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] cc a2ce9c3a2234cbda6bcf2e0d84a3c3e607d730def32a5dfff59b9c680a18b5af # shrinks to ref mut input_src = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] cc bc29377410935c0e4cd1d3a56cb6e5ccc8bb23ca1fc7e11dae15e57066482739 # shrinks to ref input = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] im-rc-15.0.0/src/arbitrary.rs010064400017500001750000000117531365756323600142100ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::hash::{BuildHasher, Hash}; use std::iter; use ::arbitrary::{size_hint, Arbitrary, Result, Unstructured}; use crate::{HashMap, HashSet, OrdMap, OrdSet, Vector}; fn empty() -> Box> { Box::new(iter::empty()) } fn shrink_collection( entries: impl Iterator, f: impl Fn(&T) -> Box>, ) -> Box>> { let entries: Vec<_> = entries.collect(); if entries.is_empty() { return empty(); } let mut shrinkers: Vec> = vec![]; let mut i = entries.len(); loop { shrinkers.push(entries.iter().take(i).map(&f).collect()); i /= 2; if i == 0 { break; } } Box::new(iter::once(Vec::new()).chain(iter::from_fn(move || loop { let mut shrinker = shrinkers.pop()?; let x: Option> = shrinker.iter_mut().map(|s| s.next()).collect(); if x.is_none() { continue; } shrinkers.push(shrinker); return x; }))) } impl Arbitrary for Vector { fn arbitrary(u: &mut Unstructured<'_>) -> Result { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result { u.arbitrary_take_rest_iter()?.collect() } fn size_hint(depth: usize) -> (usize, Option) { size_hint::recursion_guard(depth, |depth| { size_hint::and(::size_hint(depth), (0, None)) }) } fn shrink(&self) -> Box> { let collections = shrink_collection(self.iter(), |x| x.shrink()); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl Arbitrary for OrdMap { fn arbitrary(u: &mut Unstructured<'_>) -> Result { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result { u.arbitrary_take_rest_iter()?.collect() } fn size_hint(depth: usize) -> (usize, Option) { size_hint::recursion_guard(depth, |depth| { size_hint::and(::size_hint(depth), (0, None)) }) } fn shrink(&self) -> Box> { let collections = shrink_collection(self.iter(), |(k, v)| Box::new(k.shrink().zip(v.shrink()))); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl Arbitrary for OrdSet { fn arbitrary(u: &mut Unstructured<'_>) -> Result { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result { u.arbitrary_take_rest_iter()?.collect() } fn size_hint(depth: usize) -> (usize, Option) { size_hint::recursion_guard(depth, |depth| { size_hint::and(::size_hint(depth), (0, None)) }) } fn shrink(&self) -> Box> { let collections = shrink_collection(self.iter(), |v| v.shrink()); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl Arbitrary for HashMap where K: Arbitrary + Hash + Eq + Clone, V: Arbitrary + Clone, S: BuildHasher + Default + 'static, { fn arbitrary(u: &mut Unstructured<'_>) -> Result { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result { u.arbitrary_take_rest_iter()?.collect() } fn size_hint(depth: usize) -> (usize, Option) { size_hint::recursion_guard(depth, |depth| { size_hint::and(::size_hint(depth), (0, None)) }) } fn shrink(&self) -> Box> { let collections = shrink_collection(self.iter(), |(k, v)| Box::new(k.shrink().zip(v.shrink()))); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl Arbitrary for HashSet where A: Arbitrary + Hash + Eq + Clone, S: BuildHasher + Default + 'static, { fn arbitrary(u: &mut Unstructured<'_>) -> Result { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result { u.arbitrary_take_rest_iter()?.collect() } fn size_hint(depth: usize) -> (usize, Option) { size_hint::recursion_guard(depth, |depth| { size_hint::and(::size_hint(depth), (0, None)) }) } fn shrink(&self) -> Box> { let collections = shrink_collection(self.iter(), |v| v.shrink()); Box::new(collections.map(|entries| entries.into_iter().collect())) } } im-rc-15.0.0/src/config.rs010064400017500001750000000014251365756323600134510ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use typenum::*; /// The branching factor of RRB-trees pub(crate) type VectorChunkSize = U64; /// The branching factor of B-trees pub(crate) type OrdChunkSize = U64; // Must be an even number! /// The level size of HAMTs, in bits /// Branching factor is 2 ^ HashLevelSize. pub(crate) type HashLevelSize = U5; /// The size of per-instance memory pools if the `pool` feature is enabled. /// This is set to 0, meaning you have to opt in to using a pool by constructing /// with eg. `Vector::with_pool(pool)` even if the `pool` feature is enabled. pub(crate) const POOL_SIZE: usize = 0; im-rc-15.0.0/src/fakepool.rs010064400017500001750000000100641365756323600140030ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #![allow(dead_code)] use std::marker::PhantomData; use std::ops::Deref; use std::rc::Rc as RRc; use std::sync::Arc as RArc; use crate::nodes::chunk::Chunk; pub(crate) trait PoolDefault: Default {} pub(crate) trait PoolClone: Clone {} impl PoolDefault for Chunk {} impl PoolClone for Chunk where A: Clone {} pub(crate) struct Pool(PhantomData); impl Pool { pub(crate) fn new(_size: usize) -> Self { Pool(PhantomData) } pub(crate) fn get_pool_size(&self) -> usize { 0 } pub(crate) fn fill(&self) {} } impl Clone for Pool { fn clone(&self) -> Self { Self::new(0) } } // Rc #[derive(Default)] pub(crate) struct Rc(RRc); impl Rc { #[inline(always)] pub(crate) fn default(_pool: &Pool) -> Self where A: PoolDefault, { Self(Default::default()) } #[inline(always)] pub(crate) fn new(_pool: &Pool, value: A) -> Self { Rc(RRc::new(value)) } #[inline(always)] pub(crate) fn clone_from(_pool: &Pool, value: &A) -> Self where A: PoolClone, { Rc(RRc::new(value.clone())) } #[inline(always)] pub(crate) fn make_mut<'a>(_pool: &Pool, this: &'a mut Self) -> &'a mut A where A: PoolClone, { RRc::make_mut(&mut this.0) } #[inline(always)] pub(crate) fn ptr_eq(left: &Self, right: &Self) -> bool { RRc::ptr_eq(&left.0, &right.0) } pub(crate) fn unwrap_or_clone(this: Self) -> A where A: PoolClone, { RRc::try_unwrap(this.0).unwrap_or_else(|r| (*r).clone()) } } impl Clone for Rc { #[inline(always)] fn clone(&self) -> Self { Rc(self.0.clone()) } } impl Deref for Rc { type Target = A; #[inline(always)] fn deref(&self) -> &Self::Target { self.0.deref() } } impl PartialEq for Rc where A: PartialEq, { #[inline(always)] fn eq(&self, other: &Self) -> bool { **self == **other } } impl Eq for Rc where A: Eq {} impl std::fmt::Debug for Rc where A: std::fmt::Debug, { #[inline(always)] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { self.0.fmt(f) } } // Arc #[derive(Default)] pub(crate) struct Arc(RArc); impl Arc { #[inline(always)] pub(crate) fn default(_pool: &Pool) -> Self where A: PoolDefault, { Self(Default::default()) } #[inline(always)] pub(crate) fn new(_pool: &Pool, value: A) -> Self { Self(RArc::new(value)) } #[inline(always)] pub(crate) fn clone_from(_pool: &Pool, value: &A) -> Self where A: PoolClone, { Self(RArc::new(value.clone())) } #[inline(always)] pub(crate) fn make_mut<'a>(_pool: &Pool, this: &'a mut Self) -> &'a mut A where A: PoolClone, { RArc::make_mut(&mut this.0) } #[inline(always)] pub(crate) fn ptr_eq(left: &Self, right: &Self) -> bool { RArc::ptr_eq(&left.0, &right.0) } pub(crate) fn unwrap_or_clone(this: Self) -> A where A: PoolClone, { RArc::try_unwrap(this.0).unwrap_or_else(|r| (*r).clone()) } } impl Clone for Arc { #[inline(always)] fn clone(&self) -> Self { Self(self.0.clone()) } } impl Deref for Arc { type Target = A; #[inline(always)] fn deref(&self) -> &Self::Target { self.0.deref() } } impl PartialEq for Arc where A: PartialEq, { #[inline(always)] fn eq(&self, other: &Self) -> bool { **self == **other } } impl Eq for Arc where A: Eq {} impl std::fmt::Debug for Arc where A: std::fmt::Debug, { #[inline(always)] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { self.0.fmt(f) } } im-rc-15.0.0/src/hash/map.rs010064400017500001750000002046301365756323600137070ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! An unordered map. //! //! An immutable hash map using [hash array mapped tries][1]. //! //! Most operations on this map are O(logx n) for a //! suitably high *x* that it should be nearly O(1) for most maps. //! Because of this, it's a great choice for a generic map as long as //! you don't mind that keys will need to implement //! [`Hash`][std::hash::Hash] and [`Eq`][std::cmp::Eq]. //! //! Map entries will have a predictable order based on the hasher //! being used. Unless otherwise specified, this will be the standard //! [`RandomState`][std::collections::hash_map::RandomState] hasher. //! //! [1]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie //! [std::cmp::Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html //! [std::hash::Hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html //! [std::collections::hash_map::RandomState]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html use std::borrow::Borrow; use std::cmp::Ordering; use std::collections; use std::collections::hash_map::RandomState; use std::fmt::{Debug, Error, Formatter}; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter::{FromIterator, FusedIterator, Sum}; use std::mem; use std::ops::{Add, Index, IndexMut}; use crate::nodes::hamt::{ hash_key, Drain as NodeDrain, HashBits, HashValue, Iter as NodeIter, IterMut as NodeIterMut, Node, }; use crate::util::{Pool, PoolRef, Ref}; /// Construct a hash map from a sequence of key/value pairs. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// # fn main() { /// assert_eq!( /// hashmap!{ /// 1 => 11, /// 2 => 22, /// 3 => 33 /// }, /// HashMap::from(vec![(1, 11), (2, 22), (3, 33)]) /// ); /// # } /// ``` #[macro_export] macro_rules! hashmap { () => { $crate::hashmap::HashMap::new() }; ( $( $key:expr => $value:expr ),* ) => {{ let mut map = $crate::hashmap::HashMap::new(); $({ map.insert($key, $value); })*; map }}; ( $( $key:expr => $value:expr ,)* ) => {{ let mut map = $crate::hashmap::HashMap::new(); $({ map.insert($key, $value); })*; map }}; } def_pool!(HashMapPool, Node<(K,V)>); /// An unordered map. /// /// An immutable hash map using [hash array mapped tries] [1]. /// /// Most operations on this map are O(logx n) for a /// suitably high *x* that it should be nearly O(1) for most maps. /// Because of this, it's a great choice for a generic map as long as /// you don't mind that keys will need to implement /// [`Hash`][std::hash::Hash] and [`Eq`][std::cmp::Eq]. /// /// Map entries will have a predictable order based on the hasher /// being used. Unless otherwise specified, this will be the standard /// [`RandomState`][std::collections::hash_map::RandomState] hasher. /// /// [1]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie /// [std::cmp::Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html /// [std::hash::Hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html /// [std::collections::hash_map::RandomState]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html pub struct HashMap { size: usize, pool: HashMapPool, root: PoolRef>, hasher: Ref, } impl HashValue for (K, V) where K: Eq, { type Key = K; fn extract_key(&self) -> &Self::Key { &self.0 } fn ptr_eq(&self, _other: &Self) -> bool { false } } impl HashMap { /// Construct an empty hash map. #[inline] #[must_use] pub fn new() -> Self { Self::default() } /// Construct an empty hash map using a specific memory pool. #[cfg(feature = "pool")] #[must_use] pub fn with_pool(pool: &HashMapPool) -> Self { let root = PoolRef::default(&pool.0); Self { size: 0, hasher: Default::default(), pool: pool.clone(), root, } } } impl HashMap where K: Hash + Eq + Clone, V: Clone, { /// Construct a hash map with a single mapping. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map = HashMap::unit(123, "onetwothree"); /// assert_eq!( /// map.get(&123), /// Some(&"onetwothree") /// ); /// ``` #[inline] #[must_use] pub fn unit(k: K, v: V) -> HashMap { HashMap::new().update(k, v) } } impl HashMap { /// Test whether a hash map is empty. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// assert!( /// !hashmap!{1 => 2}.is_empty() /// ); /// assert!( /// HashMap::::new().is_empty() /// ); /// ``` #[inline] #[must_use] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Get the size of a hash map. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// assert_eq!(3, hashmap!{ /// 1 => 11, /// 2 => 22, /// 3 => 33 /// }.len()); /// ``` #[inline] #[must_use] pub fn len(&self) -> usize { self.size } /// Test whether two maps refer to the same content in memory. /// /// This is true if the two sides are references to the same map, /// or if the two maps refer to the same root node. /// /// This would return true if you're comparing a map to itself, or /// if you're comparing a map to a fresh clone of itself. /// /// Time: O(1) pub fn ptr_eq(&self, other: &Self) -> bool { std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root) } /// Get a reference to the memory pool used by this map. /// /// Note that if you didn't specifically construct it with a pool, you'll /// get back a reference to a pool of size 0. #[cfg(feature = "pool")] pub fn pool(&self) -> &HashMapPool { &self.pool } /// Construct an empty hash map using the provided hasher. #[inline] #[must_use] pub fn with_hasher(hasher: RS) -> Self where Ref: From, { let pool = HashMapPool::default(); let root = PoolRef::default(&pool.0); HashMap { size: 0, hasher: hasher.into(), pool, root, } } /// Construct an empty hash map using a specific memory pool and hasher. #[cfg(feature = "pool")] #[must_use] pub fn with_pool_hasher(pool: &HashMapPool, hasher: RS) -> Self where Ref: From, { let root = PoolRef::default(&pool.0); Self { size: 0, hasher: hasher.into(), pool: pool.clone(), root, } } /// Get a reference to the map's [`BuildHasher`][BuildHasher]. /// /// [BuildHasher]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html #[must_use] pub fn hasher(&self) -> &Ref { &self.hasher } /// Construct an empty hash map using the same hasher as the /// current hash map. #[inline] #[must_use] pub fn new_from(&self) -> HashMap where K1: Hash + Eq + Clone, V1: Clone, { let pool = HashMapPool::default(); let root = PoolRef::default(&pool.0); HashMap { size: 0, pool, root, hasher: self.hasher.clone(), } } /// Get an iterator over the key/value pairs of a hash map. /// /// Please note that the order is consistent between maps using /// the same hasher, but no other ordering guarantee is offered. /// Items will not come out in insertion order or sort order. /// They will, however, come out in the same order every time for /// the same map. #[inline] #[must_use] pub fn iter(&self) -> Iter<'_, K, V> { Iter { it: NodeIter::new(&self.root, self.size), } } /// Get an iterator over a hash map's keys. /// /// Please note that the order is consistent between maps using /// the same hasher, but no other ordering guarantee is offered. /// Items will not come out in insertion order or sort order. /// They will, however, come out in the same order every time for /// the same map. #[inline] #[must_use] pub fn keys(&self) -> Keys<'_, K, V> { Keys { it: NodeIter::new(&self.root, self.size), } } /// Get an iterator over a hash map's values. /// /// Please note that the order is consistent between maps using /// the same hasher, but no other ordering guarantee is offered. /// Items will not come out in insertion order or sort order. /// They will, however, come out in the same order every time for /// the same map. #[inline] #[must_use] pub fn values(&self) -> Values<'_, K, V> { Values { it: NodeIter::new(&self.root, self.size), } } /// Discard all elements from the map. /// /// This leaves you with an empty map, and all elements that /// were previously inside it are dropped. /// /// Time: O(n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::HashMap; /// let mut map = hashmap![1=>1, 2=>2, 3=>3]; /// map.clear(); /// assert!(map.is_empty()); /// ``` pub fn clear(&mut self) { if !self.is_empty() { self.root = PoolRef::default(&self.pool.0); self.size = 0; } } } impl HashMap where K: Hash + Eq, S: BuildHasher, { fn test_eq(&self, other: &Self) -> bool where K: Hash + Eq, V: PartialEq, { if self.len() != other.len() { return false; } let mut seen = collections::HashSet::new(); for (key, value) in self.iter() { if Some(value) != other.get(&key) { return false; } seen.insert(key); } for key in other.keys() { if !seen.contains(&key) { return false; } } true } /// Get the value for a key from a hash map. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map = hashmap!{123 => "lol"}; /// assert_eq!( /// map.get(&123), /// Some(&"lol") /// ); /// ``` #[must_use] pub fn get(&self, key: &BK) -> Option<&V> where BK: Hash + Eq + ?Sized, K: Borrow, { self.root .get(hash_key(&*self.hasher, key), 0, key) .map(|&(_, ref v)| v) } /// Get the key/value pair for a key from a hash map. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map = hashmap!{123 => "lol"}; /// assert_eq!( /// map.get_key_value(&123), /// Some((&123, &"lol")) /// ); /// ``` #[must_use] pub fn get_key_value(&self, key: &BK) -> Option<(&K, &V)> where BK: Hash + Eq + ?Sized, K: Borrow, { self.root .get(hash_key(&*self.hasher, key), 0, key) .map(|&(ref k, ref v)| (k, v)) } /// Test for the presence of a key in a hash map. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map = hashmap!{123 => "lol"}; /// assert!( /// map.contains_key(&123) /// ); /// assert!( /// !map.contains_key(&321) /// ); /// ``` #[inline] #[must_use] pub fn contains_key(&self, k: &BK) -> bool where BK: Hash + Eq + ?Sized, K: Borrow, { self.get(k).is_some() } /// Test whether a map is a submap of another map, meaning that /// all keys in our map must also be in the other map, with the /// same values. /// /// Use the provided function to decide whether values are equal. /// /// Time: O(n log n) #[must_use] pub fn is_submap_by(&self, other: RM, mut cmp: F) -> bool where F: FnMut(&V, &B) -> bool, RM: Borrow>, { self.iter() .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false)) } /// Test whether a map is a proper submap of another map, meaning /// that all keys in our map must also be in the other map, with /// the same values. To be a proper submap, ours must also contain /// fewer keys than the other map. /// /// Use the provided function to decide whether values are equal. /// /// Time: O(n log n) #[must_use] pub fn is_proper_submap_by(&self, other: RM, cmp: F) -> bool where F: FnMut(&V, &B) -> bool, RM: Borrow>, { self.len() != other.borrow().len() && self.is_submap_by(other, cmp) } /// Test whether a map is a submap of another map, meaning that /// all keys in our map must also be in the other map, with the /// same values. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 2 => 2}; /// let map2 = hashmap!{1 => 1, 2 => 2, 3 => 3}; /// assert!(map1.is_submap(map2)); /// ``` #[inline] #[must_use] pub fn is_submap(&self, other: RM) -> bool where V: PartialEq, RM: Borrow, { self.is_submap_by(other.borrow(), PartialEq::eq) } /// Test whether a map is a proper submap of another map, meaning /// that all keys in our map must also be in the other map, with /// the same values. To be a proper submap, ours must also contain /// fewer keys than the other map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 2 => 2}; /// let map2 = hashmap!{1 => 1, 2 => 2, 3 => 3}; /// assert!(map1.is_proper_submap(map2)); /// /// let map3 = hashmap!{1 => 1, 2 => 2}; /// let map4 = hashmap!{1 => 1, 2 => 2}; /// assert!(!map3.is_proper_submap(map4)); /// ``` #[inline] #[must_use] pub fn is_proper_submap(&self, other: RM) -> bool where V: PartialEq, RM: Borrow, { self.is_proper_submap_by(other.borrow(), PartialEq::eq) } } impl HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher, { /// Get a mutable iterator over the values of a hash map. /// /// Please note that the order is consistent between maps using /// the same hasher, but no other ordering guarantee is offered. /// Items will not come out in insertion order or sort order. /// They will, however, come out in the same order every time for /// the same map. #[inline] #[must_use] pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); IterMut { it: NodeIterMut::new(&self.pool.0, root, self.size), } } /// Get a mutable reference to the value for a key from a hash /// map. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let mut map = hashmap!{123 => "lol"}; /// if let Some(value) = map.get_mut(&123) { /// *value = "omg"; /// } /// assert_eq!( /// map.get(&123), /// Some(&"omg") /// ); /// ``` #[must_use] pub fn get_mut(&mut self, key: &BK) -> Option<&mut V> where BK: Hash + Eq + ?Sized, K: Borrow, { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); match root.get_mut(&self.pool.0, hash_key(&*self.hasher, key), 0, key) { None => None, Some(&mut (_, ref mut value)) => Some(value), } } /// Insert a key/value mapping into a map. /// /// If the map already has a mapping for the given key, the /// previous value is overwritten. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let mut map = hashmap!{}; /// map.insert(123, "123"); /// map.insert(456, "456"); /// assert_eq!( /// map, /// hashmap!{123 => "123", 456 => "456"} /// ); /// ``` #[inline] pub fn insert(&mut self, k: K, v: V) -> Option { let hash = hash_key(&*self.hasher, &k); let root = PoolRef::make_mut(&self.pool.0, &mut self.root); let result = root.insert(&self.pool.0, hash, 0, (k, v)); if result.is_none() { self.size += 1; } result.map(|(_, v)| v) } /// Remove a key/value pair from a map, if it exists, and return /// the removed value. /// /// This is a copy-on-write operation, so that the parts of the /// set's structure which are shared with other sets will be /// safely copied before mutating. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let mut map = hashmap!{123 => "123", 456 => "456"}; /// assert_eq!(Some("123"), map.remove(&123)); /// assert_eq!(Some("456"), map.remove(&456)); /// assert_eq!(None, map.remove(&789)); /// assert!(map.is_empty()); /// ``` pub fn remove(&mut self, k: &BK) -> Option where BK: Hash + Eq + ?Sized, K: Borrow, { self.remove_with_key(k).map(|(_, v)| v) } /// Remove a key/value pair from a map, if it exists, and return /// the removed key and value. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let mut map = hashmap!{123 => "123", 456 => "456"}; /// assert_eq!(Some((123, "123")), map.remove_with_key(&123)); /// assert_eq!(Some((456, "456")), map.remove_with_key(&456)); /// assert_eq!(None, map.remove_with_key(&789)); /// assert!(map.is_empty()); /// ``` pub fn remove_with_key(&mut self, k: &BK) -> Option<(K, V)> where BK: Hash + Eq + ?Sized, K: Borrow, { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); let result = root.remove(&self.pool.0, hash_key(&*self.hasher, k), 0, k); if result.is_some() { self.size -= 1; } result } /// Get the [`Entry`][Entry] for a key in the map for in-place manipulation. /// /// Time: O(log n) /// /// [Entry]: enum.Entry.html #[must_use] pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S> { let hash = hash_key(&*self.hasher, &key); if self.root.get(hash, 0, &key).is_some() { Entry::Occupied(OccupiedEntry { map: self, hash, key, }) } else { Entry::Vacant(VacantEntry { map: self, hash, key, }) } } /// Construct a new hash map by inserting a key/value mapping into a map. /// /// If the map already has a mapping for the given key, the previous value /// is overwritten. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map = hashmap!{}; /// assert_eq!( /// map.update(123, "123"), /// hashmap!{123 => "123"} /// ); /// ``` #[inline] #[must_use] pub fn update(&self, k: K, v: V) -> Self { let mut out = self.clone(); out.insert(k, v); out } /// Construct a new hash map by inserting a key/value mapping into /// a map. /// /// If the map already has a mapping for the given key, we call /// the provided function with the old value and the new value, /// and insert the result as the new value. /// /// Time: O(log n) #[must_use] pub fn update_with(&self, k: K, v: V, f: F) -> Self where F: FnOnce(V, V) -> V, { match self.extract_with_key(&k) { None => self.update(k, v), Some((_, v2, m)) => m.update(k, f(v2, v)), } } /// Construct a new map by inserting a key/value mapping into a /// map. /// /// If the map already has a mapping for the given key, we call /// the provided function with the key, the old value and the new /// value, and insert the result as the new value. /// /// Time: O(log n) #[must_use] pub fn update_with_key(&self, k: K, v: V, f: F) -> Self where F: FnOnce(&K, V, V) -> V, { match self.extract_with_key(&k) { None => self.update(k, v), Some((_, v2, m)) => { let out_v = f(&k, v2, v); m.update(k, out_v) } } } /// Construct a new map by inserting a key/value mapping into a /// map, returning the old value for the key as well as the new /// map. /// /// If the map already has a mapping for the given key, we call /// the provided function with the key, the old value and the new /// value, and insert the result as the new value. /// /// Time: O(log n) #[must_use] pub fn update_lookup_with_key(&self, k: K, v: V, f: F) -> (Option, Self) where F: FnOnce(&K, &V, V) -> V, { match self.extract_with_key(&k) { None => (None, self.update(k, v)), Some((_, v2, m)) => { let out_v = f(&k, &v2, v); (Some(v2), m.update(k, out_v)) } } } /// Update the value for a given key by calling a function with /// the current value and overwriting it with the function's /// return value. /// /// The function gets an [`Option`][std::option::Option] and /// returns the same, so that it can decide to delete a mapping /// instead of updating the value, and decide what to do if the /// key isn't in the map. /// /// Time: O(log n) /// /// [std::option::Option]: https://doc.rust-lang.org/std/option/enum.Option.html #[must_use] pub fn alter(&self, f: F, k: K) -> Self where F: FnOnce(Option) -> Option, { let pop = self.extract_with_key(&k); match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) { (None, None) => self.clone(), (Some(v), None) => self.update(k, v), (None, Some((_, _, m))) => m, (Some(v), Some((_, _, m))) => m.update(k, v), } } /// Construct a new map without the given key. /// /// Construct a map that's a copy of the current map, absent the /// mapping for `key` if it's present. /// /// Time: O(log n) #[must_use] pub fn without(&self, k: &BK) -> Self where BK: Hash + Eq + ?Sized, K: Borrow, { match self.extract_with_key(k) { None => self.clone(), Some((_, _, map)) => map, } } /// Filter out values from a map which don't satisfy a predicate. /// /// This is slightly more efficient than filtering using an /// iterator, in that it doesn't need to rehash the retained /// values, but it still needs to reconstruct the entire tree /// structure of the map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::HashMap; /// let mut map = hashmap!{1 => 1, 2 => 2, 3 => 3}; /// map.retain(|k, v| *k > 1); /// let expected = hashmap!{2 => 2, 3 => 3}; /// assert_eq!(expected, map); /// ``` pub fn retain(&mut self, mut f: F) where F: FnMut(&K, &V) -> bool, { let old_root = self.root.clone(); let root = PoolRef::make_mut(&self.pool.0, &mut self.root); for ((key, value), hash) in NodeIter::new(&old_root, self.size) { if !f(key, value) && root.remove(&self.pool.0, hash, 0, key).is_some() { self.size -= 1; } } } /// Remove a key/value pair from a map, if it exists, and return /// the removed value as well as the updated map. /// /// Time: O(log n) #[must_use] pub fn extract(&self, k: &BK) -> Option<(V, Self)> where BK: Hash + Eq + ?Sized, K: Borrow, { self.extract_with_key(k).map(|(_, v, m)| (v, m)) } /// Remove a key/value pair from a map, if it exists, and return /// the removed key and value as well as the updated list. /// /// Time: O(log n) #[must_use] pub fn extract_with_key(&self, k: &BK) -> Option<(K, V, Self)> where BK: Hash + Eq + ?Sized, K: Borrow, { let mut out = self.clone(); out.remove_with_key(k).map(|(k, v)| (k, v, out)) } /// Construct the union of two maps, keeping the values in the /// current map when keys exist in both maps. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 3 => 3}; /// let map2 = hashmap!{2 => 2, 3 => 4}; /// let expected = hashmap!{1 => 1, 2 => 2, 3 => 3}; /// assert_eq!(expected, map1.union(map2)); /// ``` #[must_use] pub fn union(mut self, other: Self) -> Self { for (k, v) in other { self.entry(k).or_insert(v); } self } /// Construct the union of two maps, using a function to decide /// what to do with the value when a key is in both maps. /// /// The function is called when a value exists in both maps, and /// receives the value from the current map as its first argument, /// and the value from the other map as the second. It should /// return the value to be inserted in the resulting map. /// /// Time: O(n log n) #[inline] #[must_use] pub fn union_with(self, other: Self, mut f: F) -> Self where F: FnMut(V, V) -> V, { self.union_with_key(other, |_, v1, v2| f(v1, v2)) } /// Construct the union of two maps, using a function to decide /// what to do with the value when a key is in both maps. /// /// The function is called when a value exists in both maps, and /// receives a reference to the key as its first argument, the /// value from the current map as the second argument, and the /// value from the other map as the third argument. It should /// return the value to be inserted in the resulting map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 3 => 4}; /// let map2 = hashmap!{2 => 2, 3 => 5}; /// let expected = hashmap!{1 => 1, 2 => 2, 3 => 9}; /// assert_eq!(expected, map1.union_with_key( /// map2, /// |key, left, right| left + right /// )); /// ``` #[must_use] pub fn union_with_key(mut self, other: Self, mut f: F) -> Self where F: FnMut(&K, V, V) -> V, { for (key, right_value) in other { match self.remove(&key) { None => { self.insert(key, right_value); } Some(left_value) => { let final_value = f(&key, left_value, right_value); self.insert(key, final_value); } } } self } /// Construct the union of a sequence of maps, selecting the value /// of the leftmost when a key appears in more than one map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 3 => 3}; /// let map2 = hashmap!{2 => 2}; /// let expected = hashmap!{1 => 1, 2 => 2, 3 => 3}; /// assert_eq!(expected, HashMap::unions(vec![map1, map2])); /// ``` #[must_use] pub fn unions(i: I) -> Self where S: Default, I: IntoIterator, { i.into_iter().fold(Self::default(), Self::union) } /// Construct the union of a sequence of maps, using a function to /// decide what to do with the value when a key is in more than /// one map. /// /// The function is called when a value exists in multiple maps, /// and receives the value from the current map as its first /// argument, and the value from the next map as the second. It /// should return the value to be inserted in the resulting map. /// /// Time: O(n log n) #[must_use] pub fn unions_with(i: I, f: F) -> Self where S: Default, I: IntoIterator, F: Fn(V, V) -> V, { i.into_iter() .fold(Self::default(), |a, b| a.union_with(b, &f)) } /// Construct the union of a sequence of maps, using a function to /// decide what to do with the value when a key is in more than /// one map. /// /// The function is called when a value exists in multiple maps, /// and receives a reference to the key as its first argument, the /// value from the current map as the second argument, and the /// value from the next map as the third argument. It should /// return the value to be inserted in the resulting map. /// /// Time: O(n log n) #[must_use] pub fn unions_with_key(i: I, f: F) -> Self where S: Default, I: IntoIterator, F: Fn(&K, V, V) -> V, { i.into_iter() .fold(Self::default(), |a, b| a.union_with_key(b, &f)) } /// Construct the symmetric difference between two maps by discarding keys /// which occur in both maps. /// /// This is an alias for the /// [`symmetric_difference`][symmetric_difference] method. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 3 => 4}; /// let map2 = hashmap!{2 => 2, 3 => 5}; /// let expected = hashmap!{1 => 1, 2 => 2}; /// assert_eq!(expected, map1.difference(map2)); /// ``` /// /// [symmetric_difference]: #method.symmetric_difference #[inline] #[must_use] pub fn difference(self, other: Self) -> Self { self.symmetric_difference(other) } /// Construct the symmetric difference between two maps by discarding keys /// which occur in both maps. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 3 => 4}; /// let map2 = hashmap!{2 => 2, 3 => 5}; /// let expected = hashmap!{1 => 1, 2 => 2}; /// assert_eq!(expected, map1.symmetric_difference(map2)); /// ``` #[inline] #[must_use] pub fn symmetric_difference(self, other: Self) -> Self { self.symmetric_difference_with_key(other, |_, _, _| None) } /// Construct the symmetric difference between two maps by using a function /// to decide what to do if a key occurs in both. /// /// This is an alias for the /// [`symmetric_difference_with`][symmetric_difference_with] method. /// /// Time: O(n log n) /// /// [symmetric_difference_with]: #method.symmetric_difference_with #[inline] #[must_use] pub fn difference_with(self, other: Self, f: F) -> Self where F: FnMut(V, V) -> Option, { self.symmetric_difference_with(other, f) } /// Construct the symmetric difference between two maps by using a function /// to decide what to do if a key occurs in both. /// /// Time: O(n log n) #[inline] #[must_use] pub fn symmetric_difference_with(self, other: Self, mut f: F) -> Self where F: FnMut(V, V) -> Option, { self.symmetric_difference_with_key(other, |_, a, b| f(a, b)) } /// Construct the symmetric difference between two maps by using a function /// to decide what to do if a key occurs in both. The function /// receives the key as well as both values. /// /// This is an alias for the /// [`symmetric_difference_with`_key][symmetric_difference_with_key] /// method. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 3 => 4}; /// let map2 = hashmap!{2 => 2, 3 => 5}; /// let expected = hashmap!{1 => 1, 2 => 2, 3 => 9}; /// assert_eq!(expected, map1.difference_with_key( /// map2, /// |key, left, right| Some(left + right) /// )); /// ``` /// /// [symmetric_difference_with_key]: #method.symmetric_difference_with_key #[must_use] pub fn difference_with_key(self, other: Self, f: F) -> Self where F: FnMut(&K, V, V) -> Option, { self.symmetric_difference_with_key(other, f) } /// Construct the symmetric difference between two maps by using a function /// to decide what to do if a key occurs in both. The function /// receives the key as well as both values. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 3 => 4}; /// let map2 = hashmap!{2 => 2, 3 => 5}; /// let expected = hashmap!{1 => 1, 2 => 2, 3 => 9}; /// assert_eq!(expected, map1.symmetric_difference_with_key( /// map2, /// |key, left, right| Some(left + right) /// )); /// ``` #[must_use] pub fn symmetric_difference_with_key(mut self, other: Self, mut f: F) -> Self where F: FnMut(&K, V, V) -> Option, { let mut out = self.new_from(); for (key, right_value) in other { match self.remove(&key) { None => { out.insert(key, right_value); } Some(left_value) => { if let Some(final_value) = f(&key, left_value, right_value) { out.insert(key, final_value); } } } } out.union(self) } /// Construct the relative complement between two maps by discarding keys /// which occur in `other`. /// /// Time: O(m log n) where m is the size of the other map /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 4}; /// let map2 = ordmap!{2 => 2, 3 => 5}; /// let expected = ordmap!{1 => 1}; /// assert_eq!(expected, map1.relative_complement(map2)); /// ``` #[inline] #[must_use] pub fn relative_complement(mut self, other: Self) -> Self { for (key, _) in other { let _ = self.remove(&key); } self } /// Construct the intersection of two maps, keeping the values /// from the current map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 2 => 2}; /// let map2 = hashmap!{2 => 3, 3 => 4}; /// let expected = hashmap!{2 => 2}; /// assert_eq!(expected, map1.intersection(map2)); /// ``` #[inline] #[must_use] pub fn intersection(self, other: Self) -> Self { self.intersection_with_key(other, |_, v, _| v) } /// Construct the intersection of two maps, calling a function /// with both values for each key and using the result as the /// value for the key. /// /// Time: O(n log n) #[inline] #[must_use] pub fn intersection_with(self, other: HashMap, mut f: F) -> HashMap where B: Clone, C: Clone, F: FnMut(V, B) -> C, { self.intersection_with_key(other, |_, v1, v2| f(v1, v2)) } /// Construct the intersection of two maps, calling a function /// with the key and both values for each key and using the result /// as the value for the key. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashmap::HashMap; /// let map1 = hashmap!{1 => 1, 2 => 2}; /// let map2 = hashmap!{2 => 3, 3 => 4}; /// let expected = hashmap!{2 => 5}; /// assert_eq!(expected, map1.intersection_with_key( /// map2, /// |key, left, right| left + right /// )); /// ``` #[must_use] pub fn intersection_with_key( mut self, other: HashMap, mut f: F, ) -> HashMap where B: Clone, C: Clone, F: FnMut(&K, V, B) -> C, { let mut out = self.new_from(); for (key, right_value) in other { match self.remove(&key) { None => (), Some(left_value) => { let result = f(&key, left_value, right_value); out.insert(key, result); } } } out } } // Entries /// A handle for a key and its associated value. /// /// ## Performance Note /// /// When using an `Entry`, the key is only ever hashed once, when you /// create the `Entry`. Operations on an `Entry` will never trigger a /// rehash, where eg. a `contains_key(key)` followed by an /// `insert(key, default_value)` (the equivalent of /// `Entry::or_insert()`) would need to hash the key once for the /// `contains_key` and again for the `insert`. The operations /// generally perform similarly otherwise. pub enum Entry<'a, K, V, S> where K: Hash + Eq + Clone, V: Clone, S: BuildHasher, { /// An entry which exists in the map. Occupied(OccupiedEntry<'a, K, V, S>), /// An entry which doesn't exist in the map. Vacant(VacantEntry<'a, K, V, S>), } impl<'a, K, V, S> Entry<'a, K, V, S> where K: 'a + Hash + Eq + Clone, V: 'a + Clone, S: 'a + BuildHasher, { /// Insert the default value provided if there was no value /// already, and return a mutable reference to the value. pub fn or_insert(self, default: V) -> &'a mut V { self.or_insert_with(|| default) } /// Insert the default value from the provided function if there /// was no value already, and return a mutable reference to the /// value. pub fn or_insert_with(self, default: F) -> &'a mut V where F: FnOnce() -> V, { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default()), } } /// Insert a default value if there was no value already, and /// return a mutable reference to the value. pub fn or_default(self) -> &'a mut V where V: Default, { self.or_insert_with(Default::default) } /// Get the key for this entry. #[must_use] pub fn key(&self) -> &K { match self { Entry::Occupied(entry) => entry.key(), Entry::Vacant(entry) => entry.key(), } } /// Call the provided function to modify the value if the value /// exists. pub fn and_modify(mut self, f: F) -> Self where F: FnOnce(&mut V), { match &mut self { Entry::Occupied(ref mut entry) => f(entry.get_mut()), Entry::Vacant(_) => (), } self } } /// An entry for a mapping that already exists in the map. pub struct OccupiedEntry<'a, K, V, S> where K: Hash + Eq + Clone, V: Clone, S: BuildHasher, { map: &'a mut HashMap, hash: HashBits, key: K, } impl<'a, K, V, S> OccupiedEntry<'a, K, V, S> where K: 'a + Hash + Eq + Clone, V: 'a + Clone, S: 'a + BuildHasher, { /// Get the key for this entry. #[must_use] pub fn key(&self) -> &K { &self.key } /// Remove this entry from the map and return the removed mapping. pub fn remove_entry(self) -> (K, V) { let root = PoolRef::make_mut(&self.map.pool.0, &mut self.map.root); let result = root.remove(&self.map.pool.0, self.hash, 0, &self.key); self.map.size -= 1; result.unwrap() } /// Get the current value. #[must_use] pub fn get(&self) -> &V { &self.map.root.get(self.hash, 0, &self.key).unwrap().1 } /// Get a mutable reference to the current value. #[must_use] pub fn get_mut(&mut self) -> &mut V { let root = PoolRef::make_mut(&self.map.pool.0, &mut self.map.root); &mut root .get_mut(&self.map.pool.0, self.hash, 0, &self.key) .unwrap() .1 } /// Convert this entry into a mutable reference. #[must_use] pub fn into_mut(self) -> &'a mut V { let root = PoolRef::make_mut(&self.map.pool.0, &mut self.map.root); &mut root .get_mut(&self.map.pool.0, self.hash, 0, &self.key) .unwrap() .1 } /// Overwrite the current value. pub fn insert(&mut self, value: V) -> V { mem::replace(self.get_mut(), value) } /// Remove this entry from the map and return the removed value. pub fn remove(self) -> V { self.remove_entry().1 } } /// An entry for a mapping that does not already exist in the map. pub struct VacantEntry<'a, K, V, S> where K: Hash + Eq + Clone, V: Clone, S: BuildHasher, { map: &'a mut HashMap, hash: HashBits, key: K, } impl<'a, K, V, S> VacantEntry<'a, K, V, S> where K: 'a + Hash + Eq + Clone, V: 'a + Clone, S: 'a + BuildHasher, { /// Get the key for this entry. #[must_use] pub fn key(&self) -> &K { &self.key } /// Convert this entry into its key. #[must_use] pub fn into_key(self) -> K { self.key } /// Insert a value into this entry. pub fn insert(self, value: V) -> &'a mut V { let root = PoolRef::make_mut(&self.map.pool.0, &mut self.map.root); if root .insert(&self.map.pool.0, self.hash, 0, (self.key.clone(), value)) .is_none() { self.map.size += 1; } // TODO it's unfortunate that we need to look up the key again // here to get the mut ref. &mut root .get_mut(&self.map.pool.0, self.hash, 0, &self.key) .unwrap() .1 } } // Core traits impl Clone for HashMap where K: Clone, V: Clone, { /// Clone a map. /// /// Time: O(1) #[inline] fn clone(&self) -> Self { HashMap { root: self.root.clone(), pool: self.pool.clone(), size: self.size, hasher: self.hasher.clone(), } } } #[cfg(not(has_specialisation))] impl PartialEq for HashMap where K: Hash + Eq, V: PartialEq, S: BuildHasher, { fn eq(&self, other: &Self) -> bool { self.test_eq(other) } } #[cfg(has_specialisation)] impl PartialEq for HashMap where K: Hash + Eq, V: PartialEq, S: BuildHasher, { default fn eq(&self, other: &Self) -> bool { self.test_eq(other) } } #[cfg(has_specialisation)] impl PartialEq for HashMap where K: Hash + Eq, V: Eq, S: BuildHasher, { fn eq(&self, other: &Self) -> bool { if PoolRef::ptr_eq(&self.root, &other.root) { return true; } self.test_eq(other) } } impl Eq for HashMap where K: Hash + Eq, V: Eq, S: BuildHasher, { } impl PartialOrd for HashMap where K: Hash + Eq + Clone + PartialOrd, V: PartialOrd + Clone, S: BuildHasher, { fn partial_cmp(&self, other: &Self) -> Option { if Ref::ptr_eq(&self.hasher, &other.hasher) { return self.iter().partial_cmp(other.iter()); } self.iter().partial_cmp(other.iter()) } } impl Ord for HashMap where K: Hash + Eq + Ord + Clone, V: Ord + Clone, S: BuildHasher, { fn cmp(&self, other: &Self) -> Ordering { if Ref::ptr_eq(&self.hasher, &other.hasher) { return self.iter().cmp(other.iter()); } self.iter().cmp(other.iter()) } } impl Hash for HashMap where K: Hash + Eq, V: Hash, S: BuildHasher, { fn hash(&self, state: &mut H) where H: Hasher, { for i in self.iter() { i.hash(state); } } } impl Default for HashMap where S: BuildHasher + Default, { #[inline] fn default() -> Self { let pool = HashMapPool::default(); let root = PoolRef::default(&pool.0); HashMap { size: 0, pool, root, hasher: Ref::::default(), } } } impl Add for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher, { type Output = HashMap; fn add(self, other: Self) -> Self::Output { self.union(other) } } impl<'a, K, V, S> Add for &'a HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher, { type Output = HashMap; fn add(self, other: Self) -> Self::Output { self.clone().union(other.clone()) } } impl Sum for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn sum(it: I) -> Self where I: Iterator, { it.fold(Self::default(), |a, b| a + b) } } impl Extend<(RK, RV)> for HashMap where K: Hash + Eq + Clone + From, V: Clone + From, S: BuildHasher, { fn extend(&mut self, iter: I) where I: IntoIterator, { for (key, value) in iter { self.insert(From::from(key), From::from(value)); } } } impl<'a, BK, K, V, S> Index<&'a BK> for HashMap where BK: Hash + Eq + ?Sized, K: Hash + Eq + Borrow, S: BuildHasher, { type Output = V; fn index(&self, key: &BK) -> &Self::Output { match self.root.get(hash_key(&*self.hasher, key), 0, key) { None => panic!("HashMap::index: invalid key"), Some(&(_, ref value)) => value, } } } impl<'a, BK, K, V, S> IndexMut<&'a BK> for HashMap where BK: Hash + Eq + ?Sized, K: Hash + Eq + Clone + Borrow, V: Clone, S: BuildHasher, { fn index_mut(&mut self, key: &BK) -> &mut Self::Output { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); match root.get_mut(&self.pool.0, hash_key(&*self.hasher, key), 0, key) { None => panic!("HashMap::index_mut: invalid key"), Some(&mut (_, ref mut value)) => value, } } } #[cfg(not(has_specialisation))] impl Debug for HashMap where K: Hash + Eq + Debug, V: Debug, S: BuildHasher, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let mut d = f.debug_map(); for (k, v) in self { d.entry(k, v); } d.finish() } } #[cfg(has_specialisation)] impl Debug for HashMap where K: Hash + Eq + Debug, V: Debug, S: BuildHasher, { default fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let mut d = f.debug_map(); for (k, v) in self { d.entry(k, v); } d.finish() } } #[cfg(has_specialisation)] impl Debug for HashMap where K: Hash + Eq + Ord + Debug, V: Debug, S: BuildHasher, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let mut keys = collections::BTreeSet::new(); keys.extend(self.keys()); let mut d = f.debug_map(); for key in keys { d.entry(key, &self[key]); } d.finish() } } // // Iterators /// An iterator over the elements of a map. pub struct Iter<'a, K, V> { it: NodeIter<'a, (K, V)>, } impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item = (&'a K, &'a V); fn next(&mut self) -> Option { self.it.next().map(|((k, v), _)| (k, v)) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {} impl<'a, K, V> FusedIterator for Iter<'a, K, V> {} /// A mutable iterator over the elements of a map. pub struct IterMut<'a, K, V> where K: Clone, V: Clone, { it: NodeIterMut<'a, (K, V)>, } impl<'a, K, V> Iterator for IterMut<'a, K, V> where K: Clone, V: Clone, { type Item = (&'a K, &'a mut V); fn next(&mut self) -> Option { self.it.next().map(|((k, v), _)| (&*k, v)) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> where K: Clone, V: Clone, { } impl<'a, K, V> FusedIterator for IterMut<'a, K, V> where K: Clone, V: Clone, { } /// A consuming iterator over the elements of a map. pub struct ConsumingIter { it: NodeDrain, } impl Iterator for ConsumingIter where A: HashValue + Clone, { type Item = A; fn next(&mut self) -> Option { self.it.next().map(|(p, _)| p) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl ExactSizeIterator for ConsumingIter where A: HashValue + Clone {} impl FusedIterator for ConsumingIter where A: HashValue + Clone {} /// An iterator over the keys of a map. pub struct Keys<'a, K, V> { it: NodeIter<'a, (K, V)>, } impl<'a, K, V> Iterator for Keys<'a, K, V> { type Item = &'a K; fn next(&mut self) -> Option { self.it.next().map(|((k, _), _)| k) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {} impl<'a, K, V> FusedIterator for Keys<'a, K, V> {} /// An iterator over the values of a map. pub struct Values<'a, K, V> { it: NodeIter<'a, (K, V)>, } impl<'a, K, V> Iterator for Values<'a, K, V> { type Item = &'a V; fn next(&mut self) -> Option { self.it.next().map(|((_, v), _)| v) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {} impl<'a, K, V> FusedIterator for Values<'a, K, V> {} impl<'a, K, V, S> IntoIterator for &'a HashMap where K: Hash + Eq, S: BuildHasher, { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V>; #[inline] fn into_iter(self) -> Self::IntoIter { self.iter() } } impl IntoIterator for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher, { type Item = (K, V); type IntoIter = ConsumingIter<(K, V)>; #[inline] fn into_iter(self) -> Self::IntoIter { ConsumingIter { it: NodeDrain::new(&self.pool.0, self.root, self.size), } } } // Conversions impl FromIterator<(K, V)> for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn from_iter(i: T) -> Self where T: IntoIterator, { let mut map = Self::default(); for (k, v) in i { map.insert(k, v); } map } } impl AsRef> for HashMap { #[inline] fn as_ref(&self) -> &Self { self } } impl<'m, 'k, 'v, K, V, OK, OV, SA, SB> From<&'m HashMap<&'k K, &'v V, SA>> for HashMap where K: Hash + Eq + ToOwned + ?Sized, V: ToOwned + ?Sized, OK: Hash + Eq + Clone + Borrow, OV: Borrow + Clone, SA: BuildHasher, SB: BuildHasher + Default, { fn from(m: &HashMap<&K, &V, SA>) -> Self { m.iter() .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) .collect() } } impl<'a, K, V, S> From<&'a [(K, V)]> for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn from(m: &'a [(K, V)]) -> Self { m.iter().cloned().collect() } } impl From> for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn from(m: Vec<(K, V)>) -> Self { m.into_iter().collect() } } impl<'a, K, V, S> From<&'a Vec<(K, V)>> for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn from(m: &'a Vec<(K, V)>) -> Self { m.iter().cloned().collect() } } impl From> for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn from(m: collections::HashMap) -> Self { m.into_iter().collect() } } impl<'a, K, V, S> From<&'a collections::HashMap> for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn from(m: &'a collections::HashMap) -> Self { m.iter().map(|(k, v)| (k.clone(), v.clone())).collect() } } impl From> for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn from(m: collections::BTreeMap) -> Self { m.into_iter().collect() } } impl<'a, K, V, S> From<&'a collections::BTreeMap> for HashMap where K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Default, { fn from(m: &'a collections::BTreeMap) -> Self { m.iter().map(|(k, v)| (k.clone(), v.clone())).collect() } } // impl From> for HashMap // where // S: BuildHasher + Default, // { // fn from(m: OrdMap) -> Self { // m.into_iter().collect() // } // } // impl<'a, K: Ord + Hash + Eq, V, S> From<&'a OrdMap> for HashMap // where // S: BuildHasher + Default, // { // fn from(m: &'a OrdMap) -> Self { // m.into_iter().collect() // } // } // Proptest #[cfg(any(test, feature = "proptest"))] #[doc(hidden)] pub mod proptest { #[deprecated( since = "14.3.0", note = "proptest strategies have moved to im::proptest" )] pub use crate::proptest::hash_map; } // Tests #[cfg(test)] mod test { use super::*; use crate::test::LolHasher; use ::proptest::num::{i16, usize}; use ::proptest::{collection, proptest}; use std::hash::BuildHasherDefault; #[test] fn safe_mutation() { let v1: HashMap = HashMap::from_iter((0..131_072).map(|i| (i, i))); let mut v2 = v1.clone(); v2.insert(131_000, 23); assert_eq!(Some(&23), v2.get(&131_000)); assert_eq!(Some(&131_000), v1.get(&131_000)); } #[test] fn index_operator() { let mut map = hashmap![1 => 2, 3 => 4, 5 => 6]; assert_eq!(4, map[&3]); map[&3] = 8; assert_eq!(hashmap![1 => 2, 3 => 8, 5 => 6], map); } #[test] fn proper_formatting() { let map = hashmap![1 => 2]; assert_eq!("{1: 2}", format!("{:?}", map)); assert_eq!("{}", format!("{:?}", HashMap::<(), ()>::new())); } #[test] fn remove_failing() { let pairs = [(1469, 0), (-67, 0)]; let mut m: collections::HashMap = collections::HashMap::with_hasher(BuildHasherDefault::::default()); for &(ref k, ref v) in &pairs { m.insert(*k, *v); } let mut map: HashMap = HashMap::with_hasher(BuildHasherDefault::::default()); for (k, v) in &m { map = map.update(*k, *v); } for k in m.keys() { let l = map.len(); assert_eq!(m.get(k).cloned(), map.get(k).cloned()); map = map.without(k); assert_eq!(None, map.get(k)); assert_eq!(l - 1, map.len()); } } #[test] fn match_string_keys_with_string_slices() { let mut map: HashMap = From::from(&hashmap! { "foo" => &1, "bar" => &2, "baz" => &3 }); assert_eq!(Some(&1), map.get("foo")); map = map.without("foo"); assert_eq!(Some(3), map.remove("baz")); map["bar"] = 8; assert_eq!(8, map["bar"]); } #[test] fn macro_allows_trailing_comma() { let map1 = hashmap! {"x" => 1, "y" => 2}; let map2 = hashmap! { "x" => 1, "y" => 2, }; assert_eq!(map1, map2); } #[test] fn remove_top_level_collisions() { let pairs = vec![9, 2569, 27145]; let mut map: HashMap> = Default::default(); for k in pairs.clone() { map.insert(k, k); } assert_eq!(pairs.len(), map.len()); let keys: Vec<_> = map.keys().cloned().collect(); for k in keys { let l = map.len(); assert_eq!(Some(&k), map.get(&k)); map.remove(&k); assert_eq!(None, map.get(&k)); assert_eq!(l - 1, map.len()); } } #[test] fn entry_api() { let mut map = hashmap! {"bar" => 5}; map.entry(&"foo").and_modify(|v| *v += 5).or_insert(1); assert_eq!(1, map[&"foo"]); map.entry(&"foo").and_modify(|v| *v += 5).or_insert(1); assert_eq!(6, map[&"foo"]); map.entry(&"bar").and_modify(|v| *v += 5).or_insert(1); assert_eq!(10, map[&"bar"]); assert_eq!( 10, match map.entry(&"bar") { Entry::Occupied(entry) => entry.remove(), _ => panic!(), } ); assert!(!map.contains_key(&"bar")); } #[test] fn refpool_crash() { let _map = HashMap::::new(); } #[test] fn large_map() { let mut map = HashMap::new(); let size = 32769; for i in 0..size { map.insert(i, i); } assert_eq!(size, map.len()); for i in 0..size { assert_eq!(Some(&i), map.get(&i)); } } proptest! { #[test] fn update_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) { let mut map: HashMap> = Default::default(); for (index, (k, v)) in m.iter().enumerate() { map = map.update(*k, *v); assert_eq!(Some(v), map.get(k)); assert_eq!(index + 1, map.len()); } } #[test] fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) { let map: HashMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); assert_eq!(m.len(), map.len()); } #[test] fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) { let map: HashMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); assert_eq!(m.len(), map.iter().count()); } #[test] fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) { let map1: HashMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); let map2: HashMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); assert_eq!(map1, map2); } #[test] fn lookup(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) { let map: HashMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); for (k, v) in m { assert_eq!(Some(*v), map.get(k).cloned()); } } #[test] fn without(ref pairs in collection::vec((i16::ANY, i16::ANY), 0..100)) { let mut m: collections::HashMap = collections::HashMap::with_hasher(BuildHasherDefault::::default()); for &(ref k, ref v) in pairs { m.insert(*k, *v); } let mut map: HashMap = HashMap::with_hasher(BuildHasherDefault::::default()); for (k, v) in &m { map = map.update(*k, *v); } for k in m.keys() { let l = map.len(); assert_eq!(m.get(k).cloned(), map.get(k).cloned()); map = map.without(k); assert_eq!(None, map.get(k)); assert_eq!(l - 1, map.len()); } } #[test] fn insert(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..100)) { let mut mut_map: HashMap> = Default::default(); let mut map: HashMap> = Default::default(); for (count, (k, v)) in m.iter().enumerate() { map = map.update(*k, *v); mut_map.insert(*k, *v); assert_eq!(count + 1, map.len()); assert_eq!(count + 1, mut_map.len()); } assert_eq!(map, mut_map); } #[test] fn remove(ref pairs in collection::vec((i16::ANY, i16::ANY), 0..100)) { let mut m: collections::HashMap = collections::HashMap::with_hasher(BuildHasherDefault::::default()); for &(ref k, ref v) in pairs { m.insert(*k, *v); } let mut map: HashMap = HashMap::with_hasher(BuildHasherDefault::::default()); for (k, v) in &m { map.insert(*k, *v); } for k in m.keys() { let l = map.len(); assert_eq!(m.get(k).cloned(), map.get(k).cloned()); map.remove(k); assert_eq!(None, map.get(k)); assert_eq!(l - 1, map.len()); } } #[test] fn delete_and_reinsert( ref input in collection::hash_map(i16::ANY, i16::ANY, 1..100), index_rand in usize::ANY ) { let index = *input.keys().nth(index_rand % input.len()).unwrap(); let map1: HashMap<_, _> = HashMap::from_iter(input.clone()); let (val, map2) = map1.extract(&index).unwrap(); let map3 = map2.update(index, val); for key in map2.keys() { assert!(*key != index); } assert_eq!(map1.len(), map2.len() + 1); assert_eq!(map1, map3); } #[test] fn proptest_works(ref m in proptest::hash_map(0..9999, ".*", 10..100)) { assert!(m.len() < 100); assert!(m.len() >= 10); } #[test] fn exact_size_iterator(ref m in proptest::hash_map(i16::ANY, i16::ANY, 0..100)) { let mut should_be = m.len(); let mut it = m.iter(); loop { assert_eq!(should_be, it.len()); match it.next() { None => break, Some(_) => should_be -= 1, } } assert_eq!(0, it.len()); } } } im-rc-15.0.0/src/hash/mod.rs010064400017500001750000000003771365756323600137130ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #[macro_use] pub mod map; #[macro_use] pub mod set; im-rc-15.0.0/src/hash/set.rs010064400017500001750000000652241365756323600137310ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! An unordered set. //! //! An immutable hash set using [hash array mapped tries] [1]. //! //! Most operations on this set are O(logx n) for a //! suitably high *x* that it should be nearly O(1) for most sets. //! Because of this, it's a great choice for a generic set as long as //! you don't mind that values will need to implement //! [`Hash`][std::hash::Hash] and [`Eq`][std::cmp::Eq]. //! //! Values will have a predictable order based on the hasher //! being used. Unless otherwise specified, this will be the standard //! [`RandomState`][std::collections::hash_map::RandomState] hasher. //! //! [1]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie //! [std::cmp::Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html //! [std::hash::Hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html //! [std::collections::hash_map::RandomState]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::hash_map::RandomState; use std::collections::{self, BTreeSet}; use std::fmt::{Debug, Error, Formatter}; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter::FusedIterator; use std::iter::{FromIterator, IntoIterator, Sum}; use std::ops::{Add, Deref, Mul}; use crate::nodes::hamt::{hash_key, Drain as NodeDrain, HashValue, Iter as NodeIter, Node}; use crate::ordset::OrdSet; use crate::util::{Pool, PoolRef, Ref}; /// Construct a set from a sequence of values. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// # fn main() { /// assert_eq!( /// hashset![1, 2, 3], /// HashSet::from(vec![1, 2, 3]) /// ); /// # } /// ``` #[macro_export] macro_rules! hashset { () => { $crate::hashset::HashSet::new() }; ( $($x:expr),* ) => {{ let mut l = $crate::hashset::HashSet::new(); $( l.insert($x); )* l }}; ( $($x:expr ,)* ) => {{ let mut l = $crate::hashset::HashSet::new(); $( l.insert($x); )* l }}; } def_pool!(HashSetPool, Node>); /// An unordered set. /// /// An immutable hash set using [hash array mapped tries] [1]. /// /// Most operations on this set are O(logx n) for a /// suitably high *x* that it should be nearly O(1) for most sets. /// Because of this, it's a great choice for a generic set as long as /// you don't mind that values will need to implement /// [`Hash`][std::hash::Hash] and [`Eq`][std::cmp::Eq]. /// /// Values will have a predictable order based on the hasher /// being used. Unless otherwise specified, this will be the standard /// [`RandomState`][std::collections::hash_map::RandomState] hasher. /// /// [1]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie /// [std::cmp::Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html /// [std::hash::Hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html /// [std::collections::hash_map::RandomState]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html pub struct HashSet { hasher: Ref, pool: HashSetPool, root: PoolRef>>, size: usize, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] struct Value(A); impl Deref for Value { type Target = A; fn deref(&self) -> &Self::Target { &self.0 } } // FIXME lacking specialisation, we can't simply implement `HashValue` // for `A`, we have to use the `Value` indirection. impl HashValue for Value where A: Hash + Eq, { type Key = A; fn extract_key(&self) -> &Self::Key { &self.0 } fn ptr_eq(&self, _other: &Self) -> bool { false } } impl HashSet { /// Construct an empty set. #[must_use] pub fn new() -> Self { Self::default() } /// Construct an empty set using a specific memory pool. #[cfg(feature = "pool")] #[must_use] pub fn with_pool(pool: &HashSetPool) -> Self { Self { pool: pool.clone(), hasher: Default::default(), size: 0, root: PoolRef::default(&pool.0), } } } impl HashSet where A: Hash + Eq + Clone, { /// Construct a set with a single value. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// # use std::sync::Arc; /// let set = HashSet::unit(123); /// assert!(set.contains(&123)); /// ``` #[inline] #[must_use] pub fn unit(a: A) -> Self { HashSet::new().update(a) } } impl HashSet { /// Test whether a set is empty. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// assert!( /// !hashset![1, 2, 3].is_empty() /// ); /// assert!( /// HashSet::::new().is_empty() /// ); /// ``` #[inline] #[must_use] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Get the size of a set. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// assert_eq!(3, hashset![1, 2, 3].len()); /// ``` #[inline] #[must_use] pub fn len(&self) -> usize { self.size } /// Test whether two sets refer to the same content in memory. /// /// This is true if the two sides are references to the same set, /// or if the two sets refer to the same root node. /// /// This would return true if you're comparing a set to itself, or /// if you're comparing a set to a fresh clone of itself. /// /// Time: O(1) pub fn ptr_eq(&self, other: &Self) -> bool { std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root) } /// Get a reference to the memory pool used by this set. /// /// Note that if you didn't specifically construct it with a pool, you'll /// get back a reference to a pool of size 0. #[cfg(feature = "pool")] pub fn pool(&self) -> &HashSetPool { &self.pool } /// Construct an empty hash set using the provided hasher. #[inline] #[must_use] pub fn with_hasher(hasher: RS) -> Self where Ref: From, { let pool = HashSetPool::default(); let root = PoolRef::default(&pool.0); HashSet { size: 0, pool, root, hasher: From::from(hasher), } } /// Construct an empty hash set using the provided memory pool and hasher. #[cfg(feature = "pool")] #[inline] #[must_use] pub fn with_pool_hasher(pool: &HashSetPool, hasher: RS) -> Self where Ref: From, { let root = PoolRef::default(&pool.0); HashSet { size: 0, pool: pool.clone(), root, hasher: From::from(hasher), } } /// Get a reference to the set's [`BuildHasher`][BuildHasher]. /// /// [BuildHasher]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html #[must_use] pub fn hasher(&self) -> &Ref { &self.hasher } /// Construct an empty hash set using the same hasher as the current hash set. #[inline] #[must_use] pub fn new_from(&self) -> HashSet where A1: Hash + Eq + Clone, { let pool = HashSetPool::default(); let root = PoolRef::default(&pool.0); HashSet { size: 0, pool, root, hasher: self.hasher.clone(), } } /// Discard all elements from the set. /// /// This leaves you with an empty set, and all elements that /// were previously inside it are dropped. /// /// Time: O(n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::HashSet; /// let mut set = hashset![1, 2, 3]; /// set.clear(); /// assert!(set.is_empty()); /// ``` pub fn clear(&mut self) { if !self.is_empty() { self.root = PoolRef::default(&self.pool.0); self.size = 0; } } /// Get an iterator over the values in a hash set. /// /// Please note that the order is consistent between sets using /// the same hasher, but no other ordering guarantee is offered. /// Items will not come out in insertion order or sort order. /// They will, however, come out in the same order every time for /// the same set. #[must_use] pub fn iter(&self) -> Iter<'_, A> { Iter { it: NodeIter::new(&self.root, self.size), } } } impl HashSet where A: Hash + Eq, S: BuildHasher, { fn test_eq(&self, other: &Self) -> bool { if self.len() != other.len() { return false; } let mut seen = collections::HashSet::new(); for value in self.iter() { if !other.contains(&value) { return false; } seen.insert(value); } for value in other.iter() { if !seen.contains(&value) { return false; } } true } /// Test if a value is part of a set. /// /// Time: O(log n) #[must_use] pub fn contains(&self, a: &BA) -> bool where BA: Hash + Eq + ?Sized, A: Borrow, { self.root.get(hash_key(&*self.hasher, a), 0, a).is_some() } /// Test whether a set is a subset of another set, meaning that /// all values in our set must also be in the other set. /// /// Time: O(n log n) #[must_use] pub fn is_subset(&self, other: RS) -> bool where RS: Borrow, { let o = other.borrow(); self.iter().all(|a| o.contains(&a)) } /// Test whether a set is a proper subset of another set, meaning /// that all values in our set must also be in the other set. A /// proper subset must also be smaller than the other set. /// /// Time: O(n log n) #[must_use] pub fn is_proper_subset(&self, other: RS) -> bool where RS: Borrow, { self.len() != other.borrow().len() && self.is_subset(other) } } impl HashSet where A: Hash + Eq + Clone, S: BuildHasher, { /// Insert a value into a set. /// /// Time: O(log n) #[inline] pub fn insert(&mut self, a: A) -> Option { let hash = hash_key(&*self.hasher, &a); let root = PoolRef::make_mut(&self.pool.0, &mut self.root); match root.insert(&self.pool.0, hash, 0, Value(a)) { None => { self.size += 1; None } Some(Value(old_value)) => Some(old_value), } } /// Remove a value from a set if it exists. /// /// Time: O(log n) pub fn remove(&mut self, a: &BA) -> Option where BA: Hash + Eq + ?Sized, A: Borrow, { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); let result = root.remove(&self.pool.0, hash_key(&*self.hasher, a), 0, a); if result.is_some() { self.size -= 1; } result.map(|v| v.0) } /// Construct a new set from the current set with the given value /// added. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// # use std::sync::Arc; /// let set = hashset![123]; /// assert_eq!( /// set.update(456), /// hashset![123, 456] /// ); /// ``` #[must_use] pub fn update(&self, a: A) -> Self { let mut out = self.clone(); out.insert(a); out } /// Construct a new set with the given value removed if it's in /// the set. /// /// Time: O(log n) #[must_use] pub fn without(&self, a: &BA) -> Self where BA: Hash + Eq + ?Sized, A: Borrow, { let mut out = self.clone(); out.remove(a); out } /// Filter out values from a set which don't satisfy a predicate. /// /// This is slightly more efficient than filtering using an /// iterator, in that it doesn't need to rehash the retained /// values, but it still needs to reconstruct the entire tree /// structure of the set. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::HashSet; /// let mut set = hashset![1, 2, 3]; /// set.retain(|v| *v > 1); /// let expected = hashset![2, 3]; /// assert_eq!(expected, set); /// ``` pub fn retain(&mut self, mut f: F) where F: FnMut(&A) -> bool, { let old_root = self.root.clone(); let root = PoolRef::make_mut(&self.pool.0, &mut self.root); for (value, hash) in NodeIter::new(&old_root, self.size) { if !f(value) && root.remove(&self.pool.0, hash, 0, value).is_some() { self.size -= 1; } } } /// Construct the union of two sets. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// let set1 = hashset!{1, 2}; /// let set2 = hashset!{2, 3}; /// let expected = hashset!{1, 2, 3}; /// assert_eq!(expected, set1.union(set2)); /// ``` #[must_use] pub fn union(mut self, other: Self) -> Self { for value in other { self.insert(value); } self } /// Construct the union of multiple sets. /// /// Time: O(n log n) #[must_use] pub fn unions(i: I) -> Self where I: IntoIterator, S: Default, { i.into_iter().fold(Self::default(), Self::union) } /// Construct the symmetric difference between two sets. /// /// This is an alias for the /// [`symmetric_difference`][symmetric_difference] method. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// let set1 = hashset!{1, 2}; /// let set2 = hashset!{2, 3}; /// let expected = hashset!{1, 3}; /// assert_eq!(expected, set1.difference(set2)); /// ``` /// /// [symmetric_difference]: #method.symmetric_difference #[must_use] pub fn difference(self, other: Self) -> Self { self.symmetric_difference(other) } /// Construct the symmetric difference between two sets. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// let set1 = hashset!{1, 2}; /// let set2 = hashset!{2, 3}; /// let expected = hashset!{1, 3}; /// assert_eq!(expected, set1.symmetric_difference(set2)); /// ``` #[must_use] pub fn symmetric_difference(mut self, other: Self) -> Self { for value in other { if self.remove(&value).is_none() { self.insert(value); } } self } /// Construct the relative complement between two sets, that is the set /// of values in `self` that do not occur in `other`. /// /// Time: O(m log n) where m is the size of the other set /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let set1 = ordset!{1, 2}; /// let set2 = ordset!{2, 3}; /// let expected = ordset!{1}; /// assert_eq!(expected, set1.relative_complement(set2)); /// ``` #[must_use] pub fn relative_complement(mut self, other: Self) -> Self { for value in other { let _ = self.remove(&value); } self } /// Construct the intersection of two sets. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::hashset::HashSet; /// let set1 = hashset!{1, 2}; /// let set2 = hashset!{2, 3}; /// let expected = hashset!{2}; /// assert_eq!(expected, set1.intersection(set2)); /// ``` #[must_use] pub fn intersection(self, other: Self) -> Self { let mut out = self.new_from(); for value in other { if self.contains(&value) { out.insert(value); } } out } } // Core traits impl Clone for HashSet where A: Clone, { /// Clone a set. /// /// Time: O(1) #[inline] fn clone(&self) -> Self { HashSet { hasher: self.hasher.clone(), pool: self.pool.clone(), root: self.root.clone(), size: self.size, } } } impl PartialEq for HashSet where A: Hash + Eq, S: BuildHasher + Default, { fn eq(&self, other: &Self) -> bool { self.test_eq(other) } } impl Eq for HashSet where A: Hash + Eq, S: BuildHasher + Default, { } impl PartialOrd for HashSet where A: Hash + Eq + Clone + PartialOrd, S: BuildHasher + Default, { fn partial_cmp(&self, other: &Self) -> Option { if Ref::ptr_eq(&self.hasher, &other.hasher) { return self.iter().partial_cmp(other.iter()); } self.iter().partial_cmp(other.iter()) } } impl Ord for HashSet where A: Hash + Eq + Clone + Ord, S: BuildHasher + Default, { fn cmp(&self, other: &Self) -> Ordering { if Ref::ptr_eq(&self.hasher, &other.hasher) { return self.iter().cmp(other.iter()); } self.iter().cmp(other.iter()) } } impl Hash for HashSet where A: Hash + Eq, S: BuildHasher + Default, { fn hash(&self, state: &mut H) where H: Hasher, { for i in self.iter() { i.hash(state); } } } impl Default for HashSet where S: BuildHasher + Default, { fn default() -> Self { let pool = HashSetPool::default(); let root = PoolRef::default(&pool.0); HashSet { hasher: Ref::::default(), pool, root, size: 0, } } } impl Add for HashSet where A: Hash + Eq + Clone, S: BuildHasher, { type Output = HashSet; fn add(self, other: Self) -> Self::Output { self.union(other) } } impl Mul for HashSet where A: Hash + Eq + Clone, S: BuildHasher, { type Output = HashSet; fn mul(self, other: Self) -> Self::Output { self.intersection(other) } } impl<'a, A, S> Add for &'a HashSet where A: Hash + Eq + Clone, S: BuildHasher, { type Output = HashSet; fn add(self, other: Self) -> Self::Output { self.clone().union(other.clone()) } } impl<'a, A, S> Mul for &'a HashSet where A: Hash + Eq + Clone, S: BuildHasher, { type Output = HashSet; fn mul(self, other: Self) -> Self::Output { self.clone().intersection(other.clone()) } } impl Sum for HashSet where A: Hash + Eq + Clone, S: BuildHasher + Default, { fn sum(it: I) -> Self where I: Iterator, { it.fold(Self::default(), |a, b| a + b) } } impl Extend for HashSet where A: Hash + Eq + Clone + From, S: BuildHasher, { fn extend(&mut self, iter: I) where I: IntoIterator, { for value in iter { self.insert(From::from(value)); } } } #[cfg(not(has_specialisation))] impl Debug for HashSet where A: Hash + Eq + Debug, S: BuildHasher, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.debug_set().entries(self.iter()).finish() } } #[cfg(has_specialisation)] impl Debug for HashSet where A: Hash + Eq + Debug, S: BuildHasher, { default fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.debug_set().entries(self.iter()).finish() } } #[cfg(has_specialisation)] impl Debug for HashSet where A: Hash + Eq + Debug + Ord, S: BuildHasher, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.debug_set().entries(self.iter()).finish() } } // Iterators /// An iterator over the elements of a set. pub struct Iter<'a, A> { it: NodeIter<'a, Value>, } impl<'a, A> Iterator for Iter<'a, A> where A: 'a, { type Item = &'a A; fn next(&mut self) -> Option { self.it.next().map(|(v, _)| &v.0) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl<'a, A> ExactSizeIterator for Iter<'a, A> {} impl<'a, A> FusedIterator for Iter<'a, A> {} /// A consuming iterator over the elements of a set. pub struct ConsumingIter where A: Hash + Eq + Clone, { it: NodeDrain>, } impl Iterator for ConsumingIter where A: Hash + Eq + Clone, { type Item = A; fn next(&mut self) -> Option { self.it.next().map(|(v, _)| v.0) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl ExactSizeIterator for ConsumingIter where A: Hash + Eq + Clone {} impl FusedIterator for ConsumingIter where A: Hash + Eq + Clone {} // Iterator conversions impl FromIterator for HashSet where A: Hash + Eq + Clone + From, S: BuildHasher + Default, { fn from_iter(i: T) -> Self where T: IntoIterator, { let mut set = Self::default(); for value in i { set.insert(From::from(value)); } set } } impl<'a, A, S> IntoIterator for &'a HashSet where A: Hash + Eq, S: BuildHasher, { type Item = &'a A; type IntoIter = Iter<'a, A>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl IntoIterator for HashSet where A: Hash + Eq + Clone, S: BuildHasher, { type Item = A; type IntoIter = ConsumingIter; fn into_iter(self) -> Self::IntoIter { ConsumingIter { it: NodeDrain::new(&self.pool.0, self.root, self.size), } } } // Conversions impl<'s, 'a, A, OA, SA, SB> From<&'s HashSet<&'a A, SA>> for HashSet where A: ToOwned + Hash + Eq + ?Sized, OA: Borrow + Hash + Eq + Clone, SA: BuildHasher, SB: BuildHasher + Default, { fn from(set: &HashSet<&A, SA>) -> Self { set.iter().map(|a| (*a).to_owned()).collect() } } impl<'a, A, S> From<&'a [A]> for HashSet where A: Hash + Eq + Clone, S: BuildHasher + Default, { fn from(slice: &'a [A]) -> Self { slice.iter().cloned().collect() } } impl From> for HashSet where A: Hash + Eq + Clone, S: BuildHasher + Default, { fn from(vec: Vec) -> Self { vec.into_iter().collect() } } impl<'a, A, S> From<&'a Vec> for HashSet where A: Hash + Eq + Clone, S: BuildHasher + Default, { fn from(vec: &Vec) -> Self { vec.iter().cloned().collect() } } impl From> for HashSet where A: Eq + Hash + Clone, S: BuildHasher + Default, { fn from(hash_set: collections::HashSet) -> Self { hash_set.into_iter().collect() } } impl<'a, A, S> From<&'a collections::HashSet> for HashSet where A: Eq + Hash + Clone, S: BuildHasher + Default, { fn from(hash_set: &collections::HashSet) -> Self { hash_set.iter().cloned().collect() } } impl<'a, A, S> From<&'a BTreeSet> for HashSet where A: Hash + Eq + Clone, S: BuildHasher + Default, { fn from(btree_set: &BTreeSet) -> Self { btree_set.iter().cloned().collect() } } impl From> for HashSet where A: Ord + Hash + Eq + Clone, S: BuildHasher + Default, { fn from(ordset: OrdSet) -> Self { ordset.into_iter().collect() } } impl<'a, A, S> From<&'a OrdSet> for HashSet where A: Ord + Hash + Eq + Clone, S: BuildHasher + Default, { fn from(ordset: &OrdSet) -> Self { ordset.into_iter().cloned().collect() } } // Proptest #[cfg(any(test, feature = "proptest"))] #[doc(hidden)] pub mod proptest { #[deprecated( since = "14.3.0", note = "proptest strategies have moved to im::proptest" )] pub use crate::proptest::hash_set; } #[cfg(test)] mod test { use super::proptest::*; use super::*; use crate::test::LolHasher; use ::proptest::num::i16; use ::proptest::proptest; use std::hash::BuildHasherDefault; #[test] fn insert_failing() { let mut set: HashSet> = Default::default(); set.insert(14658); assert_eq!(1, set.len()); set.insert(-19198); assert_eq!(2, set.len()); } #[test] fn match_strings_with_string_slices() { let mut set: HashSet = From::from(&hashset!["foo", "bar"]); set = set.without("bar"); assert!(!set.contains("bar")); set.remove("foo"); assert!(!set.contains("foo")); } #[test] fn macro_allows_trailing_comma() { let set1 = hashset! {"foo", "bar"}; let set2 = hashset! { "foo", "bar", }; assert_eq!(set1, set2); } #[test] fn issue_60_drain_iterator_memory_corruption() { use crate::test::MetroHashBuilder; for i in 0..1000 { let mut lhs = vec![0, 1, 2]; lhs.sort(); let hasher = Ref::from(MetroHashBuilder::new(i)); let mut iset: HashSet<_, MetroHashBuilder> = HashSet::with_hasher(hasher.clone()); for &i in &lhs { iset.insert(i); } let mut rhs: Vec<_> = iset.clone().into_iter().collect(); rhs.sort(); if lhs != rhs { println!("iteration: {}", i); println!("seed: {}", hasher.seed()); println!("lhs: {}: {:?}", lhs.len(), &lhs); println!("rhs: {}: {:?}", rhs.len(), &rhs); panic!(); } } } proptest! { #[test] fn proptest_a_set(ref s in hash_set(".*", 10..100)) { assert!(s.len() < 100); assert!(s.len() >= 10); } } } im-rc-15.0.0/src/iter.rs010064400017500001750000000030021365756323600131400ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! Iterators over immutable data. /// Create an iterator of values using a function to update an owned state /// value. /// /// The function is called with the current state as its argument, and should /// return an [`Option`][std::option::Option] of a tuple of the next value to /// yield from the iterator and the updated state. If the function returns /// [`None`][std::option::Option::None], the iterator ends. /// /// # Examples /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::iter::unfold; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// // Create an infinite stream of numbers, starting at 0. /// let mut it = unfold(0, |i| Some((i, i + 1))); /// /// // Make a list out of its first five elements. /// let numbers = Vector::from_iter(it.take(5)); /// assert_eq!(numbers, vector![0, 1, 2, 3, 4]); /// ``` /// /// [std::option::Option]: https://doc.rust-lang.org/std/option/enum.Option.html /// [std::option::Option::None]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None pub fn unfold(value: S, f: F) -> impl Iterator where F: Fn(S) -> Option<(A, S)>, { let mut value = Some(value); std::iter::from_fn(move || { f(value.take().unwrap()).map(|(next, state)| { value = Some(state); next }) }) } im-rc-15.0.0/src/lib.rs010064400017500001750000000572061365756323600127620ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! # Immutable Data Structures for Rust //! //! This library implements several of the more commonly useful immutable data //! structures for Rust. //! //! ## What are immutable data structures? //! //! Immutable data structures are data structures which can be copied and //! modified efficiently without altering the original. The most uncomplicated //! example of this is the venerable [cons list][cons-list]. This crate offers a //! selection of more modern and flexible data structures with similar //! properties, tuned for the needs of Rust developers. //! //! Briefly, the following data structures are provided: //! //! * [Vectors][vector::Vector] based on [RRB trees][rrb-tree] //! * [Hash maps][hashmap::HashMap]/[sets][hashset::HashSet] based on [hash //! array mapped tries][hamt] //! * [Ordered maps][ordmap::OrdMap]/[sets][ordset::OrdSet] based on //! [B-trees][b-tree] //! //! ## Why Would I Want This? //! //! While immutable data structures can be a game changer for other //! programming languages, the most obvious benefit - avoiding the //! accidental mutation of data - is already handled so well by Rust's //! type system that it's just not something a Rust programmer needs //! to worry about even when using data structures that would send a //! conscientious Clojure programmer into a panic. //! //! Immutable data structures offer other benefits, though, some of //! which are useful even in a language like Rust. The most prominent //! is *structural sharing*, which means that if two data structures //! are mostly copies of each other, most of the memory they take up //! will be shared between them. This implies that making copies of an //! immutable data structure is cheap: it's really only a matter of //! copying a pointer and increasing a reference counter, where in the //! case of [`Vec`][std::vec::Vec] you have to allocate the same //! amount of memory all over again and make a copy of every element //! it contains. For immutable data structures, extra memory isn't //! allocated until you modify either the copy or the original, and //! then only the memory needed to record the difference. //! //! Another goal of this library has been the idea that you shouldn't //! even have to think about what data structure to use in any given //! situation, until the point where you need to start worrying about //! optimisation - which, in practice, often never comes. Beyond the //! shape of your data (ie. whether to use a list or a map), it should //! be fine not to think too carefully about data structures - you can //! just pick the one that has the right shape and it should have //! acceptable performance characteristics for every operation you //! might need. Specialised data structures will always be faster at //! what they've been specialised for, but `im` aims to provide the //! data structures which deliver the least chance of accidentally //! using them for the wrong thing. //! //! For instance, [`Vec`][std::vec::Vec] beats everything at memory //! usage, indexing and operations that happen at the back of the //! list, but is terrible at insertion and removal, and gets worse the //! closer to the front of the list you get. //! [`VecDeque`][std::collections::VecDeque] adds a little bit of //! complexity in order to make operations at the front as efficient //! as operations at the back, but is still bad at insertion and //! especially concatenation. [`Vector`][vector::Vector] adds another //! bit of complexity, and could never match [`Vec`][std::vec::Vec] at //! what it's best at, but in return every operation you can throw at //! it can be completed in a reasonable amount of time - even normally //! expensive operations like copying and especially concatenation are //! reasonably cheap when using a [`Vector`][vector::Vector]. //! //! It should be noted, however, that because of its simplicity, //! [`Vec`][std::vec::Vec] actually beats [`Vector`][vector::Vector] even at its //! strongest operations at small sizes, just because modern CPUs are //! hyperoptimised for things like copying small chunks of contiguous memory - //! you actually need to go past a certain size (usually in the vicinity of //! several hundred elements) before you get to the point where //! [`Vec`][std::vec::Vec] isn't always going to be the fastest choice. //! [`Vector`][vector::Vector] attempts to overcome this by actually just being //! an array at very small sizes, and being able to switch efficiently to the //! full data structure when it grows large enough. Thus, //! [`Vector`][vector::Vector] will actually be equivalent to //! [Vec][std::vec::Vec] until it grows past the size of a single chunk. //! //! The maps - [`HashMap`][hashmap::HashMap] and //! [`OrdMap`][ordmap::OrdMap] - generally perform similarly to their //! equivalents in the standard library, but tend to run a bit slower //! on the basic operations ([`HashMap`][hashmap::HashMap] is almost //! neck and neck with its counterpart, while //! [`OrdMap`][ordmap::OrdMap] currently tends to run 2-3x slower). On //! the other hand, they offer the cheap copy and structural sharing //! between copies that you'd expect from immutable data structures. //! //! In conclusion, the aim of this library is to provide a safe //! default choice for the most common kinds of data structures, //! allowing you to defer careful thinking about the right data //! structure for the job until you need to start looking for //! optimisations - and you may find, especially for larger data sets, //! that immutable data structures are still the right choice. //! //! ## Values //! //! Because we need to make copies of shared nodes in these data structures //! before updating them, the values you store in them must implement //! [`Clone`][std::clone::Clone]. For primitive values that implement //! [`Copy`][std::marker::Copy], such as numbers, everything is fine: this is //! the case for which the data structures are optimised, and performance is //! going to be great. //! //! On the other hand, if you want to store values for which cloning is //! expensive, or values that don't implement [`Clone`][std::clone::Clone], you //! need to wrap them in [`Rc`][std::rc::Rc] or [`Arc`][std::sync::Arc]. Thus, //! if you have a complex structure `BigBlobOfData` and you want to store a list //! of them as a `Vector`, you should instead use a //! `Vector>`, which is going to save you not only the time //! spent cloning the big blobs of data, but also the memory spent keeping //! multiple copies of it around, as [`Rc`][std::rc::Rc] keeps a single //! reference counted copy around instead. //! //! If you're storing smaller values that aren't //! [`Copy`][std::marker::Copy]able, you'll need to exercise judgement: if your //! values are going to be very cheap to clone, as would be the case for short //! [`String`][std::string::String]s or small [`Vec`][std::vec::Vec]s, you're //! probably better off storing them directly without wrapping them in an //! [`Rc`][std::rc::Rc], because, like the [`Rc`][std::rc::Rc], they're just //! pointers to some data on the heap, and that data isn't expensive to clone - //! you might actually lose more performance from the extra redirection of //! wrapping them in an [`Rc`][std::rc::Rc] than you would from occasionally //! cloning them. //! //! ### When does cloning happen? //! //! So when will your values actually be cloned? The easy answer is only if you //! [`clone`][std::clone::Clone::clone] the data structure itself, and then only //! lazily as you change it. Values are stored in tree nodes inside the data //! structure, each node of which contains up to 64 values. When you //! [`clone`][std::clone::Clone::clone] a data structure, nothing is actually //! copied - it's just the reference count on the root node that's incremented, //! to indicate that it's shared between two data structures. It's only when you //! actually modify one of the shared data structures that nodes are cloned: //! when you make a change somewhere in the tree, the node containing the change //! needs to be cloned, and then its parent nodes need to be updated to contain //! the new child node instead of the old version, and so they're cloned as //! well. //! //! We can call this "lazy" cloning - if you make two copies of a data structure //! and you never change either of them, there's never any need to clone the //! data they contain. It's only when you start making changes that cloning //! starts to happen, and then only on the specific tree nodes that are part of //! the change. Note that the implications of lazily cloning the data structure //! extend to memory usage as well as the CPU workload of copying the data //! around - cloning an immutable data structure means both copies share the //! same allocated memory, until you start making changes. //! //! Most crucially, if you never clone the data structure, the data inside it is //! also never cloned, and in this case it acts just like a mutable data //! structure, with minimal performance differences (but still non-zero, as we //! still have to check for shared nodes). //! //! ## Data Structures //! //! We'll attempt to provide a comprehensive guide to the available //! data structures below. //! //! ### Performance Notes //! //! "Big O notation" is the standard way of talking about the time //! complexity of data structure operations. If you're not familiar //! with big O notation, here's a quick cheat sheet: //! //! *O(1)* means an operation runs in constant time: it will take the //! same time to complete regardless of the size of the data //! structure. //! //! *O(n)* means an operation runs in linear time: if you double the //! size of your data structure, the operation will take twice as long //! to complete; if you quadruple the size, it will take four times as //! long, etc. //! //! *O(log n)* means an operation runs in logarithmic time: for //! *log2*, if you double the size of your data structure, //! the operation will take one step longer to complete; if you //! quadruple the size, it will need two steps more; and so on. //! However, the data structures in this library generally run in //! *log64* time, meaning you have to make your data //! structure 64 times bigger to need one extra step, and 4096 times //! bigger to need two steps. This means that, while they still count //! as O(log n), operations on all but really large data sets will run //! at near enough to O(1) that you won't usually notice. //! //! *O(n log n)* is the most expensive operation you'll see in this //! library: it means that for every one of the *n* elements in your //! data structure, you have to perform *log n* operations. In our //! case, as noted above, this is often close enough to O(n) that it's //! not usually as bad as it sounds, but even O(n) isn't cheap and the //! cost still increases logarithmically, if slowly, as the size of //! your data increases. O(n log n) basically means "are you sure you //! need to do this?" //! //! *O(1)** means 'amortised O(1),' which means that an operation //! usually runs in constant time but will occasionally be more //! expensive: for instance, //! [`Vector::push_back`][vector::Vector::push_back], if called in //! sequence, will be O(1) most of the time but every 64th time it //! will be O(log n), as it fills up its tail chunk and needs to //! insert it into the tree. Please note that the O(1) with the //! asterisk attached is not a common notation; it's just a convention //! I've used in these docs to save myself from having to type //! 'amortised' everywhere. //! //! ### Lists //! //! Lists are sequences of single elements which maintain the order in //! which you inserted them. The only list in this library is //! [`Vector`][vector::Vector], which offers the best all round //! performance characteristics: it's pretty good at everything, even //! if there's always another kind of list that's better at something. //! //! | Type | Algorithm | Constraints | Order | Push | Pop | Split | Append | Lookup | //! | --- | --- | --- | --- | --- | --- | --- | --- | --- | //! | [`Vector`][vector::Vector] | [RRB tree][rrb-tree] | [`Clone`][std::clone::Clone] | insertion | O(1)\* | O(1)\* | O(log n) | O(log n) | O(log n) | //! //! ### Maps //! //! Maps are mappings of keys to values, where the most common read //! operation is to find the value associated with a given key. Maps //! may or may not have a defined order. Any given key can only occur //! once inside a map, and setting a key to a different value will //! overwrite the previous value. //! //! | Type | Algorithm | Key Constraints | Order | Insert | Remove | Lookup | //! | --- | --- | --- | --- | --- | --- | --- | //! | [`HashMap`][hashmap::HashMap] | [HAMT][hamt] | [`Clone`][std::clone::Clone] + [`Hash`][std::hash::Hash] + [`Eq`][std::cmp::Eq] | undefined | O(log n) | O(log n) | O(log n) | //! | [`OrdMap`][ordmap::OrdMap] | [B-tree][b-tree] | [`Clone`][std::clone::Clone] + [`Ord`][std::cmp::Ord] | sorted | O(log n) | O(log n) | O(log n) | //! //! ### Sets //! //! Sets are collections of unique values, and may or may not have a //! defined order. Their crucial property is that any given value can //! only exist once in a given set. //! //! | Type | Algorithm | Constraints | Order | Insert | Remove | Lookup | //! | --- | --- | --- | --- | --- | --- | --- | //! | [`HashSet`][hashset::HashSet] | [HAMT][hamt] | [`Clone`][std::clone::Clone] + [`Hash`][std::hash::Hash] + [`Eq`][std::cmp::Eq] | undefined | O(log n) | O(log n) | O(log n) | //! | [`OrdSet`][ordset::OrdSet] | [B-tree][b-tree] | [`Clone`][std::clone::Clone] + [`Ord`][std::cmp::Ord] | sorted | O(log n) | O(log n) | O(log n) | //! //! ## In-place Mutation //! //! All of these data structures support in-place copy-on-write //! mutation, which means that if you're the sole user of a data //! structure, you can update it in place without taking the //! performance hit of making a copy of the data structure before //! modifying it (this is about an order of magnitude faster than //! immutable operations, almost as fast as //! [`std::collections`][std::collections]'s mutable data structures). //! //! Thanks to [`Rc`][std::rc::Rc]'s reference counting, we are able to //! determine whether a node in a data structure is being shared with //! other data structures, or whether it's safe to mutate it in place. //! When it's shared, we'll automatically make a copy of the node //! before modifying it. The consequence of this is that cloning a //! data structure becomes a lazy operation: the initial clone is //! instant, and as you modify the cloned data structure it will clone //! chunks only where you change them, so that if you change the //! entire thing you will eventually have performed a full clone. //! //! This also gives us a couple of other optimisations for free: //! implementations of immutable data structures in other languages //! often have the idea of local mutation, like Clojure's transients //! or Haskell's `ST` monad - a managed scope where you can treat an //! immutable data structure like a mutable one, gaining a //! considerable amount of performance because you no longer need to //! copy your changed nodes for every operation, just the first time //! you hit a node that's sharing structure. In Rust, we don't need to //! think about this kind of managed scope, it's all taken care of //! behind the scenes because of our low level access to the garbage //! collector (which, in our case, is just a simple //! [`Rc`][std::rc::Rc]). //! //! ## Thread Safety //! //! The data structures in the `im` crate are thread safe, through //! [`Arc`][std::sync::Arc]. This comes with a slight performance impact, so //! that if you prioritise speed over thread safety, you may want to use the //! `im-rc` crate instead, which is identical to `im` except that it uses //! [`Rc`][std::rc::Rc] instead of [`Arc`][std::sync::Arc], implying that the //! data structures in `im-rc` do not implement [`Send`][std::marker::Send] and //! [`Sync`][std::marker::Sync]. This yields approximately a 20-25% increase in //! general performance. //! //! ## Feature Flags //! //! `im` comes with optional support for the following crates through Cargo //! feature flags. You can enable them in your `Cargo.toml` file like this: //! //! ```no_compile //! [dependencies] //! im = { version = "*", features = ["proptest", "serde"] } //! ``` //! //! | Feature | Description | //! | ------- | ----------- | //! | [`pool`](https://crates.io/crates/refpool) | Constructors and pool types for [`refpool`](https://crates.io/crates/refpool) memory pools (only available in `im-rc`) | //! | [`proptest`](https://crates.io/crates/proptest) | Strategies for all `im` datatypes under a `proptest` namespace, eg. `im::vector::proptest::vector()` | //! | [`quickcheck`](https://crates.io/crates/quickcheck) | [`quickcheck::Arbitrary`](https://docs.rs/quickcheck/latest/quickcheck/trait.Arbitrary.html) implementations for all `im` datatypes (not available in `im-rc`) | //! | [`rayon`](https://crates.io/crates/rayon) | parallel iterator implementations for [`Vector`][vector::Vector] (not available in `im-rc`) | //! | [`serde`](https://crates.io/crates/serde) | [`Serialize`](https://docs.rs/serde/latest/serde/trait.Serialize.html) and [`Deserialize`](https://docs.rs/serde/latest/serde/trait.Deserialize.html) implementations for all `im` datatypes | //! | [`arbitrary`](https://crates.io/crates/arbitrary/) | [`arbitrary::Arbitrary`](https://docs.rs/arbitrary/latest/arbitrary/trait.Arbitrary.html) implementations for all `im` datatypes | //! //! [std::collections]: https://doc.rust-lang.org/std/collections/index.html //! [std::collections::VecDeque]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html //! [std::vec::Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html //! [std::string::String]: https://doc.rust-lang.org/std/string/struct.String.html //! [std::rc::Rc]: https://doc.rust-lang.org/std/rc/struct.Rc.html //! [std::sync::Arc]: https://doc.rust-lang.org/std/sync/struct.Arc.html //! [std::cmp::Eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html //! [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html //! [std::clone::Clone]: https://doc.rust-lang.org/std/clone/trait.Clone.html //! [std::clone::Clone::clone]: https://doc.rust-lang.org/std/clone/trait.Clone.html#tymethod.clone //! [std::marker::Copy]: https://doc.rust-lang.org/std/marker/trait.Copy.html //! [std::hash::Hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html //! [std::marker::Send]: https://doc.rust-lang.org/std/marker/trait.Send.html //! [std::marker::Sync]: https://doc.rust-lang.org/std/marker/trait.Sync.html //! [hashmap::HashMap]: ./struct.HashMap.html //! [hashset::HashSet]: ./struct.HashSet.html //! [ordmap::OrdMap]: ./struct.OrdMap.html //! [ordset::OrdSet]: ./struct.OrdSet.html //! [vector::Vector]: ./struct.Vector.html //! [vector::Vector::push_back]: ./vector/enum.Vector.html#method.push_back //! [rrb-tree]: https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf //! [hamt]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie //! [b-tree]: https://en.wikipedia.org/wiki/B-tree //! [cons-list]: https://en.wikipedia.org/wiki/Cons#Lists #![forbid(rust_2018_idioms)] #![deny(unsafe_code, nonstandard_style)] #![warn(unreachable_pub, missing_docs)] #![cfg_attr(has_specialisation, feature(specialization))] #[cfg(test)] #[macro_use] extern crate pretty_assertions; mod config; mod nodes; mod sort; mod sync; #[macro_use] mod util; #[macro_use] mod ord; pub use crate::ord::map as ordmap; pub use crate::ord::set as ordset; #[macro_use] mod hash; pub use crate::hash::map as hashmap; pub use crate::hash::set as hashset; #[macro_use] pub mod vector; pub mod iter; #[cfg(any(test, feature = "proptest"))] pub mod proptest; #[cfg(any(test, feature = "serde"))] #[doc(hidden)] pub mod ser; #[cfg(feature = "arbitrary")] #[doc(hidden)] pub mod arbitrary; #[cfg(all(threadsafe, feature = "quickcheck"))] #[doc(hidden)] pub mod quickcheck; #[cfg(any(threadsafe, not(feature = "pool")))] mod fakepool; #[cfg(all(threadsafe, feature = "pool"))] compile_error!( "The `pool` feature is not threadsafe but you've enabled it on a threadsafe version of `im`." ); pub use crate::hashmap::HashMap; pub use crate::hashset::HashSet; pub use crate::ordmap::OrdMap; pub use crate::ordset::OrdSet; #[doc(inline)] pub use crate::vector::Vector; #[cfg(test)] mod test; #[cfg(test)] mod tests; /// Update a value inside multiple levels of data structures. /// /// This macro takes a [`Vector`][Vector], [`OrdMap`][OrdMap] or [`HashMap`][HashMap], /// a key or a series of keys, and a value, and returns the data structure with the /// new value at the location described by the keys. /// /// If one of the keys in the path doesn't exist, the macro will panic. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use std::sync::Arc; /// # fn main() { /// let vec_inside_vec = vector![vector![1, 2, 3], vector![4, 5, 6]]; /// /// let expected = vector![vector![1, 2, 3], vector![4, 5, 1337]]; /// /// assert_eq!(expected, update_in![vec_inside_vec, 1 => 2, 1337]); /// # } /// ``` /// /// [Vector]: ../vector/enum.Vector.html /// [HashMap]: ../hashmap/struct.HashMap.html /// [OrdMap]: ../ordmap/struct.OrdMap.html #[macro_export] macro_rules! update_in { ($target:expr, $path:expr => $($tail:tt) => *, $value:expr ) => {{ let inner = $target.get($path).expect("update_in! macro: key not found in target"); $target.update($path, update_in!(inner, $($tail) => *, $value)) }}; ($target:expr, $path:expr, $value:expr) => { $target.update($path, $value) }; } /// Get a value inside multiple levels of data structures. /// /// This macro takes a [`Vector`][Vector], [`OrdMap`][OrdMap] or [`HashMap`][HashMap], /// along with a key or a series of keys, and returns the value at the location inside /// the data structure described by the key sequence, or `None` if any of the keys didn't /// exist. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use std::sync::Arc; /// # fn main() { /// let vec_inside_vec = vector![vector![1, 2, 3], vector![4, 5, 6]]; /// /// assert_eq!(Some(&6), get_in![vec_inside_vec, 1 => 2]); /// # } /// ``` /// /// [Vector]: ../vector/enum.Vector.html /// [HashMap]: ../hashmap/struct.HashMap.html /// [OrdMap]: ../ordmap/struct.OrdMap.html #[macro_export] macro_rules! get_in { ($target:expr, $path:expr => $($tail:tt) => * ) => {{ $target.get($path).and_then(|v| get_in!(v, $($tail) => *)) }}; ($target:expr, $path:expr) => { $target.get($path) }; } #[cfg(test)] mod lib_test { #[test] fn update_in() { let vector = vector![1, 2, 3, 4, 5]; assert_eq!(vector![1, 2, 23, 4, 5], update_in!(vector, 2, 23)); let hashmap = hashmap![1 => 1, 2 => 2, 3 => 3]; assert_eq!( hashmap![1 => 1, 2 => 23, 3 => 3], update_in!(hashmap, 2, 23) ); let ordmap = ordmap![1 => 1, 2 => 2, 3 => 3]; assert_eq!(ordmap![1 => 1, 2 => 23, 3 => 3], update_in!(ordmap, 2, 23)); let vecs = vector![vector![1, 2, 3], vector![4, 5, 6], vector![7, 8, 9]]; let vecs_target = vector![vector![1, 2, 3], vector![4, 5, 23], vector![7, 8, 9]]; assert_eq!(vecs_target, update_in!(vecs, 1 => 2, 23)); } #[test] fn get_in() { let vector = vector![1, 2, 3, 4, 5]; assert_eq!(Some(&3), get_in!(vector, 2)); let hashmap = hashmap![1 => 1, 2 => 2, 3 => 3]; assert_eq!(Some(&2), get_in!(hashmap, &2)); let ordmap = ordmap![1 => 1, 2 => 2, 3 => 3]; assert_eq!(Some(&2), get_in!(ordmap, &2)); let vecs = vector![vector![1, 2, 3], vector![4, 5, 6], vector![7, 8, 9]]; assert_eq!(Some(&6), get_in!(vecs, 1 => 2)); } } im-rc-15.0.0/src/nodes/btree.rs010064400017500001750000001345561365756323600144310ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::borrow::Borrow; use std::cmp::Ordering; use std::mem; use std::ops::{Bound, RangeBounds}; use sized_chunks::Chunk; use typenum::{Add1, Unsigned}; use crate::config::OrdChunkSize as NodeSize; use crate::util::{Pool, PoolClone, PoolDefault, PoolRef}; use self::Insert::*; use self::InsertAction::*; const NODE_SIZE: usize = NodeSize::USIZE; const MEDIAN: usize = (NODE_SIZE + 1) >> 1; pub trait BTreeValue { type Key; fn ptr_eq(&self, other: &Self) -> bool; fn search_key(slice: &[Self], key: &BK) -> Result where BK: Ord + ?Sized, Self: Sized, Self::Key: Borrow; fn search_value(slice: &[Self], value: &Self) -> Result where Self: Sized; fn cmp_keys(&self, other: &BK) -> Ordering where BK: Ord + ?Sized, Self::Key: Borrow; fn cmp_values(&self, other: &Self) -> Ordering; } pub(crate) struct Node { keys: Chunk, children: Chunk>>, Add1>, } #[cfg(feature = "pool")] #[allow(unsafe_code)] unsafe fn cast_uninit(target: &mut A) -> &mut mem::MaybeUninit { &mut *(target as *mut A as *mut mem::MaybeUninit) } #[allow(unsafe_code)] impl PoolDefault for Node { #[cfg(feature = "pool")] unsafe fn default_uninit(target: &mut mem::MaybeUninit) { let ptr: *mut Self = target.as_mut_ptr(); Chunk::default_uninit(cast_uninit(&mut (*ptr).keys)); Chunk::default_uninit(cast_uninit(&mut (*ptr).children)); (*ptr).children.push_back(None); } } #[allow(unsafe_code)] impl PoolClone for Node where A: Clone, { #[cfg(feature = "pool")] unsafe fn clone_uninit(&self, target: &mut mem::MaybeUninit) { self.keys .clone_uninit(cast_uninit(&mut (*target.as_mut_ptr()).keys)); self.children .clone_uninit(cast_uninit(&mut (*target.as_mut_ptr()).children)); } } pub(crate) enum Insert { Added, Replaced(A), Split(Node, A, Node), } enum InsertAction { AddedAction, ReplacedAction(A), InsertAt, InsertSplit(Node, A, Node), } pub(crate) enum Remove { NoChange, Removed(A), Update(A, Node), } enum RemoveAction { DeleteAt(usize), PullUp(usize, usize, usize), Merge(usize), StealFromLeft(usize), StealFromRight(usize), MergeFirst(usize), ContinueDown(usize), } impl Clone for Node where A: Clone, { fn clone(&self) -> Self { Node { keys: self.keys.clone(), children: self.children.clone(), } } } impl Default for Node { fn default() -> Self { Node { keys: Chunk::new(), children: Chunk::unit(None), } } } impl Node { #[inline] fn has_room(&self) -> bool { self.keys.len() < NODE_SIZE } #[inline] fn too_small(&self) -> bool { self.keys.len() < MEDIAN } #[inline] fn is_leaf(&self) -> bool { self.children[0].is_none() } #[inline] pub(crate) fn unit(value: A) -> Self { Node { keys: Chunk::unit(value), children: Chunk::pair(None, None), } } #[inline] pub(crate) fn new_from_split( pool: &Pool>, left: Node, median: A, right: Node, ) -> Self { Node { keys: Chunk::unit(median), children: Chunk::pair( Some(PoolRef::new(pool, left)), Some(PoolRef::new(pool, right)), ), } } pub(crate) fn min(&self) -> Option<&A> { match self.children.first().unwrap() { None => self.keys.first(), Some(ref child) => child.min(), } } pub(crate) fn max(&self) -> Option<&A> { match self.children.last().unwrap() { None => self.keys.last(), Some(ref child) => child.max(), } } } impl Node { fn child_contains(&self, index: usize, key: &BK) -> bool where BK: Ord + ?Sized, A::Key: Borrow, { if let Some(Some(ref child)) = self.children.get(index) { child.lookup(key).is_some() } else { false } } pub(crate) fn lookup(&self, key: &BK) -> Option<&A> where BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return None; } // Perform a binary search, resulting in either a match or // the index of the first higher key, meaning we search the // child to the left of it. match A::search_key(&self.keys, key) { Ok(index) => Some(&self.keys[index]), Err(index) => match self.children[index] { None => None, Some(ref node) => node.lookup(key), }, } } pub(crate) fn lookup_mut(&mut self, pool: &Pool>, key: &BK) -> Option<&mut A> where A: Clone, BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return None; } // Perform a binary search, resulting in either a match or // the index of the first higher key, meaning we search the // child to the left of it. match A::search_key(&self.keys, key) { Ok(index) => Some(&mut self.keys[index]), Err(index) => match self.children[index] { None => None, Some(ref mut child_ref) => { let child = PoolRef::make_mut(pool, child_ref); child.lookup_mut(pool, key) } }, } } pub(crate) fn lookup_prev<'a, BK>(&'a self, key: &BK) -> Option<&A> where BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return None; } match A::search_key(&self.keys, key) { Ok(index) => Some(&self.keys[index]), Err(index) => match self.children[index] { None if index == 0 => None, None => match self.keys.get(index - 1) { Some(_) => Some(&self.keys[index - 1]), None => None, }, Some(ref node) => node.lookup_prev(key), }, } } pub(crate) fn lookup_next<'a, BK>(&'a self, key: &BK) -> Option<&A> where BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return None; } match A::search_key(&self.keys, key) { Ok(index) => Some(&self.keys[index]), Err(index) => match self.children[index] { None => match self.keys.get(index) { Some(_) => Some(&self.keys[index]), None => None, }, Some(ref node) => node.lookup_next(key), }, } } pub(crate) fn lookup_prev_mut<'a, BK>( &'a mut self, pool: &Pool>, key: &BK, ) -> Option<&mut A> where A: Clone, BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return None; } match A::search_key(&self.keys, key) { Ok(index) => Some(&mut self.keys[index]), Err(index) => match self.children[index] { None if index == 0 => None, None => match self.keys.get(index - 1) { Some(_) => Some(&mut self.keys[index - 1]), None => None, }, Some(ref mut node) => PoolRef::make_mut(pool, node).lookup_prev_mut(pool, key), }, } } pub(crate) fn lookup_next_mut<'a, BK>( &'a mut self, pool: &Pool>, key: &BK, ) -> Option<&mut A> where A: Clone, BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return None; } match A::search_key(&self.keys, key) { Ok(index) => Some(&mut self.keys[index]), Err(index) => match self.children[index] { None => match self.keys.get(index) { Some(_) => Some(&mut self.keys[index]), None => None, }, Some(ref mut node) => PoolRef::make_mut(pool, node).lookup_next_mut(pool, key), }, } } pub(crate) fn path_first<'a, BK>( &'a self, mut path: Vec<(&'a Node, usize)>, ) -> Vec<(&'a Node, usize)> where A: 'a, BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return Vec::new(); } match self.children[0] { None => { path.push((self, 0)); path } Some(ref node) => { path.push((self, 0)); node.path_first(path) } } } pub(crate) fn path_last<'a, BK>( &'a self, mut path: Vec<(&'a Node, usize)>, ) -> Vec<(&'a Node, usize)> where A: 'a, BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return Vec::new(); } let end = self.children.len() - 1; match self.children[end] { None => { path.push((self, end - 1)); path } Some(ref node) => { path.push((self, end)); node.path_last(path) } } } pub(crate) fn path_next<'a, BK>( &'a self, key: &BK, mut path: Vec<(&'a Node, usize)>, ) -> Vec<(&'a Node, usize)> where A: 'a, BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return Vec::new(); } match A::search_key(&self.keys, key) { Ok(index) => { path.push((self, index)); path } Err(index) => match self.children[index] { None => match self.keys.get(index) { Some(_) => { path.push((self, index)); path } None => Vec::new(), }, Some(ref node) => { path.push((self, index)); node.path_next(key, path) } }, } } pub(crate) fn path_prev<'a, BK>( &'a self, key: &BK, mut path: Vec<(&'a Node, usize)>, ) -> Vec<(&'a Node, usize)> where A: 'a, BK: Ord + ?Sized, A::Key: Borrow, { if self.keys.is_empty() { return Vec::new(); } match A::search_key(&self.keys, key) { Ok(index) => { path.push((self, index)); path } Err(index) => match self.children[index] { None if index == 0 => Vec::new(), None => match self.keys.get(index - 1) { Some(_) => { path.push((self, index)); path } None => Vec::new(), }, Some(ref node) => { path.push((self, index)); node.path_prev(key, path) } }, } } fn split( &mut self, pool: &Pool>, value: A, ins_left: Option>, ins_right: Option>, ) -> Insert { let left_child = ins_left.map(|node| PoolRef::new(pool, node)); let right_child = ins_right.map(|node| PoolRef::new(pool, node)); let index = A::search_value(&self.keys, &value).unwrap_err(); let mut left_keys; let mut left_children; let mut right_keys; let mut right_children; let median; match index.cmp(&MEDIAN) { Ordering::Less => { self.children[index] = left_child; left_keys = Chunk::from_front(&mut self.keys, index); left_keys.push_back(value); left_keys.drain_from_front(&mut self.keys, MEDIAN - index - 1); left_children = Chunk::from_front(&mut self.children, index + 1); left_children.push_back(right_child); left_children.drain_from_front(&mut self.children, MEDIAN - index - 1); median = self.keys.pop_front(); right_keys = Chunk::drain_from(&mut self.keys); right_children = Chunk::drain_from(&mut self.children); } Ordering::Greater => { self.children[index] = left_child; left_keys = Chunk::from_front(&mut self.keys, MEDIAN); left_children = Chunk::from_front(&mut self.children, MEDIAN + 1); median = self.keys.pop_front(); right_keys = Chunk::from_front(&mut self.keys, index - MEDIAN - 1); right_keys.push_back(value); right_keys.append(&mut self.keys); right_children = Chunk::from_front(&mut self.children, index - MEDIAN); right_children.push_back(right_child); right_children.append(&mut self.children); } Ordering::Equal => { left_keys = Chunk::from_front(&mut self.keys, MEDIAN); left_children = Chunk::from_front(&mut self.children, MEDIAN); left_children.push_back(left_child); median = value; right_keys = Chunk::drain_from(&mut self.keys); right_children = Chunk::drain_from(&mut self.children); right_children[0] = right_child; } } debug_assert!(left_keys.len() == MEDIAN); debug_assert!(left_children.len() == MEDIAN + 1); debug_assert!(right_keys.len() == MEDIAN); debug_assert!(right_children.len() == MEDIAN + 1); Split( Node { keys: left_keys, children: left_children, }, median, Node { keys: right_keys, children: right_children, }, ) } fn merge(middle: A, left: Node, mut right: Node) -> Node { let mut keys = left.keys; keys.push_back(middle); keys.append(&mut right.keys); let mut children = left.children; children.append(&mut right.children); Node { keys, children } } fn pop_min(&mut self) -> (A, Option>>) { let value = self.keys.pop_front(); let child = self.children.pop_front(); (value, child) } fn pop_max(&mut self) -> (A, Option>>) { let value = self.keys.pop_back(); let child = self.children.pop_back(); (value, child) } fn push_min(&mut self, child: Option>>, value: A) { self.keys.push_front(value); self.children.push_front(child); } fn push_max(&mut self, child: Option>>, value: A) { self.keys.push_back(value); self.children.push_back(child); } pub(crate) fn insert(&mut self, pool: &Pool>, value: A) -> Insert where A: Clone, { if self.keys.is_empty() { self.keys.push_back(value); self.children.push_back(None); return Insert::Added; } let (median, left, right) = match A::search_value(&self.keys, &value) { // Key exists in node Ok(index) => { return Insert::Replaced(mem::replace(&mut self.keys[index], value)); } // Key is adjacent to some key in node Err(index) => { let has_room = self.has_room(); let action = match self.children[index] { // No child at location, this is the target node. None => InsertAt, // Child at location, pass it on. Some(ref mut child_ref) => { let child = PoolRef::make_mut(pool, child_ref); match child.insert(pool, value.clone()) { Insert::Added => AddedAction, Insert::Replaced(value) => ReplacedAction(value), Insert::Split(left, median, right) => InsertSplit(left, median, right), } } }; match action { ReplacedAction(value) => return Insert::Replaced(value), AddedAction => { return Insert::Added; } InsertAt => { if has_room { self.keys.insert(index, value); self.children.insert(index + 1, None); return Insert::Added; } else { (value, None, None) } } InsertSplit(left, median, right) => { if has_room { self.children[index] = Some(PoolRef::new(pool, left)); self.keys.insert(index, median); self.children .insert(index + 1, Some(PoolRef::new(pool, right))); return Insert::Added; } else { (median, Some(left), Some(right)) } } } } }; self.split(pool, median, left, right) } pub(crate) fn remove(&mut self, pool: &Pool>, key: &BK) -> Remove where A: Clone, BK: Ord + ?Sized, A::Key: Borrow, { let index = A::search_key(&self.keys, key); self.remove_index(pool, index, key) } fn remove_index( &mut self, pool: &Pool>, index: Result, key: &BK, ) -> Remove where A: Clone, BK: Ord + ?Sized, A::Key: Borrow, { let action = match index { // Key exists in node, remove it. Ok(index) => { match (&self.children[index], &self.children[index + 1]) { // If we're a leaf, just delete the entry. (&None, &None) => RemoveAction::DeleteAt(index), // If the left hand child has capacity, pull the predecessor up. (&Some(ref left), _) if !left.too_small() => { if left.is_leaf() { RemoveAction::PullUp(left.keys.len() - 1, index, index) } else { RemoveAction::StealFromLeft(index + 1) } } // If the right hand child has capacity, pull the successor up. (_, &Some(ref right)) if !right.too_small() => { if right.is_leaf() { RemoveAction::PullUp(0, index, index + 1) } else { RemoveAction::StealFromRight(index) } } // If neither child has capacity, we'll have to merge them. (&Some(_), &Some(_)) => RemoveAction::Merge(index), // If one child exists and the other doesn't, we're in a bad state. _ => unreachable!(), } } // Key is adjacent to some key in node Err(index) => match self.children[index] { // No child at location means key isn't in map. None => return Remove::NoChange, // Child at location, but it's at minimum capacity. Some(ref child) if child.too_small() => { let left = if index > 0 { self.children.get(index - 1) } else { None }; // index is usize and can't be negative, best make sure it never is. match (left, self.children.get(index + 1)) { // If it has a left sibling with capacity, steal a key from it. (Some(&Some(ref old_left)), _) if !old_left.too_small() => { RemoveAction::StealFromLeft(index) } // If it has a right sibling with capacity, same as above. (_, Some(&Some(ref old_right))) if !old_right.too_small() => { RemoveAction::StealFromRight(index) } // If it has neither, we'll have to merge it with a sibling. // If we have a right sibling, we'll merge with that. (_, Some(&Some(_))) => RemoveAction::MergeFirst(index), // If we have a left sibling, we'll merge with that. (Some(&Some(_)), _) => RemoveAction::MergeFirst(index - 1), // If none of the above, we're in a bad state. _ => unreachable!(), } } // Child at location, and it's big enough, we can recurse down. Some(_) => RemoveAction::ContinueDown(index), }, }; match action { RemoveAction::DeleteAt(index) => { let pair = self.keys.remove(index); self.children.remove(index); Remove::Removed(pair) } RemoveAction::PullUp(target_index, pull_to, child_index) => { let children = &mut self.children; let mut update = None; let value; if let Some(&mut Some(ref mut child_ref)) = children.get_mut(child_index) { let child = PoolRef::make_mut(pool, child_ref); match child.remove_index(pool, Ok(target_index), key) { Remove::NoChange => unreachable!(), Remove::Removed(pulled_value) => { value = self.keys.set(pull_to, pulled_value); } Remove::Update(pulled_value, new_child) => { value = self.keys.set(pull_to, pulled_value); update = Some(new_child); } } } else { unreachable!() } if let Some(new_child) = update { children[child_index] = Some(PoolRef::new(pool, new_child)); } Remove::Removed(value) } RemoveAction::Merge(index) => { let left = self.children.remove(index).unwrap(); let right = mem::replace(&mut self.children[index], None).unwrap(); let value = self.keys.remove(index); let mut merged_child = Node::merge( value, PoolRef::unwrap_or_clone(left), PoolRef::unwrap_or_clone(right), ); let (removed, new_child) = match merged_child.remove(pool, key) { Remove::NoChange => unreachable!(), Remove::Removed(removed) => (removed, merged_child), Remove::Update(removed, updated_child) => (removed, updated_child), }; if self.keys.is_empty() { // If we've depleted the root node, the merged child becomes the root. Remove::Update(removed, new_child) } else { self.children[index] = Some(PoolRef::new(pool, new_child)); Remove::Removed(removed) } } RemoveAction::StealFromLeft(index) => { let mut update = None; let out_value; { let mut children = self.children.as_mut_slice()[index - 1..=index] .iter_mut() .map(|n| { if let Some(ref mut o) = *n { o } else { unreachable!() } }); let left = PoolRef::make_mut(pool, children.next().unwrap()); let child = PoolRef::make_mut(pool, children.next().unwrap()); // Prepare the rebalanced node. child.push_min( left.children.last().unwrap().clone(), self.keys[index - 1].clone(), ); match child.remove(pool, key) { Remove::NoChange => { // Key wasn't there, we need to revert the steal. child.pop_min(); return Remove::NoChange; } Remove::Removed(value) => { // If we did remove something, we complete the rebalancing. let (left_value, _) = left.pop_max(); self.keys[index - 1] = left_value; out_value = value; } Remove::Update(value, new_child) => { // If we did remove something, we complete the rebalancing. let (left_value, _) = left.pop_max(); self.keys[index - 1] = left_value; update = Some(new_child); out_value = value; } } } if let Some(new_child) = update { self.children[index] = Some(PoolRef::new(pool, new_child)); } Remove::Removed(out_value) } RemoveAction::StealFromRight(index) => { let mut update = None; let out_value; { let mut children = self.children.as_mut_slice()[index..index + 2] .iter_mut() .map(|n| { if let Some(ref mut o) = *n { o } else { unreachable!() } }); let child = PoolRef::make_mut(pool, children.next().unwrap()); let right = PoolRef::make_mut(pool, children.next().unwrap()); // Prepare the rebalanced node. child.push_max(right.children[0].clone(), self.keys[index].clone()); match child.remove(pool, key) { Remove::NoChange => { // Key wasn't there, we need to revert the steal. child.pop_max(); return Remove::NoChange; } Remove::Removed(value) => { // If we did remove something, we complete the rebalancing. let (right_value, _) = right.pop_min(); self.keys[index] = right_value; out_value = value; } Remove::Update(value, new_child) => { // If we did remove something, we complete the rebalancing. let (right_value, _) = right.pop_min(); self.keys[index] = right_value; update = Some(new_child); out_value = value; } } } if let Some(new_child) = update { self.children[index] = Some(PoolRef::new(pool, new_child)); } Remove::Removed(out_value) } RemoveAction::MergeFirst(index) => { if self.keys[index].cmp_keys(key) != Ordering::Equal && !self.child_contains(index, key) && !self.child_contains(index + 1, key) { return Remove::NoChange; } let left = self.children.remove(index).unwrap(); let right = mem::replace(&mut self.children[index], None).unwrap(); let middle = self.keys.remove(index); let mut merged = Node::merge( middle, PoolRef::unwrap_or_clone(left), PoolRef::unwrap_or_clone(right), ); let update; let out_value; match merged.remove(pool, key) { Remove::NoChange => { panic!("nodes::btree::Node::remove: caught an absent key too late while merging"); } Remove::Removed(value) => { if self.keys.is_empty() { return Remove::Update(value, merged); } update = merged; out_value = value; } Remove::Update(value, new_child) => { if self.keys.is_empty() { return Remove::Update(value, new_child); } update = new_child; out_value = value; } } self.children[index] = Some(PoolRef::new(pool, update)); Remove::Removed(out_value) } RemoveAction::ContinueDown(index) => { let mut update = None; let out_value; if let Some(&mut Some(ref mut child_ref)) = self.children.get_mut(index) { let child = PoolRef::make_mut(pool, child_ref); match child.remove(pool, key) { Remove::NoChange => return Remove::NoChange, Remove::Removed(value) => { out_value = value; } Remove::Update(value, new_child) => { update = Some(new_child); out_value = value; } } } else { unreachable!() } if let Some(new_child) = update { self.children[index] = Some(PoolRef::new(pool, new_child)); } Remove::Removed(out_value) } } } } // Iterator /// An iterator over an ordered set. pub struct Iter<'a, A> { fwd_path: Vec<(&'a Node, usize)>, back_path: Vec<(&'a Node, usize)>, pub(crate) remaining: usize, } impl<'a, A: BTreeValue> Iter<'a, A> { pub(crate) fn new(root: &'a Node, size: usize, range: R) -> Self where R: RangeBounds, A::Key: Borrow, BK: Ord + ?Sized, { let fwd_path = match range.start_bound() { Bound::Included(key) => root.path_next(key, Vec::new()), Bound::Excluded(key) => { let mut path = root.path_next(key, Vec::new()); if let Some(value) = Self::get(&path) { if value.cmp_keys(key) == Ordering::Equal { Self::step_forward(&mut path); } } path } Bound::Unbounded => root.path_first(Vec::new()), }; let back_path = match range.end_bound() { Bound::Included(key) => root.path_prev(key, Vec::new()), Bound::Excluded(key) => { let mut path = root.path_prev(key, Vec::new()); if let Some(value) = Self::get(&path) { if value.cmp_keys(key) == Ordering::Equal { Self::step_back(&mut path); } } path } Bound::Unbounded => root.path_last(Vec::new()), }; Iter { fwd_path, back_path, remaining: size, } } fn get(path: &[(&'a Node, usize)]) -> Option<&'a A> { match path.last() { Some((node, index)) => Some(&node.keys[*index]), None => None, } } fn step_forward(path: &mut Vec<(&'a Node, usize)>) -> Option<&'a A> { match path.pop() { Some((node, index)) => { let index = index + 1; match node.children[index] { // Child between current and next key -> step down Some(ref child) => { path.push((node, index)); path.push((child, 0)); let mut node = child; while let Some(ref left_child) = node.children[0] { path.push((left_child, 0)); node = left_child; } Some(&node.keys[0]) } None => match node.keys.get(index) { // Yield next key value @ Some(_) => { path.push((node, index)); value } // No more keys -> exhausted level, step up and yield None => loop { match path.pop() { None => { return None; } Some((node, index)) => { if let value @ Some(_) = node.keys.get(index) { path.push((node, index)); return value; } } } }, }, } } None => None, } } fn step_back(path: &mut Vec<(&'a Node, usize)>) -> Option<&'a A> { match path.pop() { Some((node, index)) => match node.children[index] { Some(ref child) => { path.push((node, index)); let mut end = child.keys.len() - 1; path.push((child, end)); let mut node = child; while let Some(ref right_child) = node.children[end + 1] { end = right_child.keys.len() - 1; path.push((right_child, end)); node = right_child; } Some(&node.keys[end]) } None => { if index == 0 { loop { match path.pop() { None => { return None; } Some((node, index)) => { if index > 0 { let index = index - 1; path.push((node, index)); return Some(&node.keys[index]); } } } } } else { let index = index - 1; path.push((node, index)); Some(&node.keys[index]) } } }, None => None, } } } impl<'a, A: 'a + BTreeValue> Iterator for Iter<'a, A> { type Item = &'a A; fn next(&mut self) -> Option { match Iter::get(&self.fwd_path) { None => None, Some(value) => match Iter::get(&self.back_path) { Some(last_value) if value.cmp_values(last_value) == Ordering::Greater => None, None => None, Some(_) => { Iter::step_forward(&mut self.fwd_path); self.remaining -= 1; Some(value) } }, } } fn size_hint(&self) -> (usize, Option) { // (0, Some(self.remaining)) (0, None) } } impl<'a, A: 'a + BTreeValue> DoubleEndedIterator for Iter<'a, A> { fn next_back(&mut self) -> Option { match Iter::get(&self.back_path) { None => None, Some(value) => match Iter::get(&self.fwd_path) { Some(last_value) if value.cmp_values(last_value) == Ordering::Less => None, None => None, Some(_) => { Iter::step_back(&mut self.back_path); self.remaining -= 1; Some(value) } }, } } } // Consuming iterator enum ConsumingIterItem { Consider(Node), Yield(A), } /// A consuming iterator over an ordered set. pub struct ConsumingIter { fwd_last: Option, fwd_stack: Vec>, back_last: Option, back_stack: Vec>, remaining: usize, } impl ConsumingIter { pub(crate) fn new(root: &Node, total: usize) -> Self { ConsumingIter { fwd_last: None, fwd_stack: vec![ConsumingIterItem::Consider(root.clone())], back_last: None, back_stack: vec![ConsumingIterItem::Consider(root.clone())], remaining: total, } } fn push_node(stack: &mut Vec>, maybe_node: Option>>) { if let Some(node) = maybe_node { stack.push(ConsumingIterItem::Consider(PoolRef::unwrap_or_clone(node))) } } fn push(stack: &mut Vec>, mut node: Node) { for _n in 0..node.keys.len() { ConsumingIter::push_node(stack, node.children.pop_back()); stack.push(ConsumingIterItem::Yield(node.keys.pop_back())); } ConsumingIter::push_node(stack, node.children.pop_back()); } fn push_fwd(&mut self, node: Node) { ConsumingIter::push(&mut self.fwd_stack, node) } fn push_node_back(&mut self, maybe_node: Option>>) { if let Some(node) = maybe_node { self.back_stack .push(ConsumingIterItem::Consider(PoolRef::unwrap_or_clone(node))) } } fn push_back(&mut self, mut node: Node) { for _i in 0..node.keys.len() { self.push_node_back(node.children.pop_front()); self.back_stack .push(ConsumingIterItem::Yield(node.keys.pop_front())); } self.push_node_back(node.children.pop_back()); } } impl Iterator for ConsumingIter where A: BTreeValue + Clone, { type Item = A; fn next(&mut self) -> Option { loop { match self.fwd_stack.pop() { None => { self.remaining = 0; return None; } Some(ConsumingIterItem::Consider(node)) => self.push_fwd(node), Some(ConsumingIterItem::Yield(value)) => { if let Some(ref last) = self.back_last { if value.cmp_values(last) != Ordering::Less { self.fwd_stack.clear(); self.back_stack.clear(); self.remaining = 0; return None; } } self.remaining -= 1; self.fwd_last = Some(value.clone()); return Some(value); } } } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } impl DoubleEndedIterator for ConsumingIter where A: BTreeValue + Clone, { fn next_back(&mut self) -> Option { loop { match self.back_stack.pop() { None => { self.remaining = 0; return None; } Some(ConsumingIterItem::Consider(node)) => self.push_back(node), Some(ConsumingIterItem::Yield(value)) => { if let Some(ref last) = self.fwd_last { if value.cmp_values(last) != Ordering::Greater { self.fwd_stack.clear(); self.back_stack.clear(); self.remaining = 0; return None; } } self.remaining -= 1; self.back_last = Some(value.clone()); return Some(value); } } } } } impl ExactSizeIterator for ConsumingIter {} // DiffIter /// An iterator over the differences between two ordered sets. pub struct DiffIter<'a, A> { old_stack: Vec>, new_stack: Vec>, } /// A description of a difference between two ordered sets. #[derive(PartialEq, Eq, Debug)] pub enum DiffItem<'a, A> { /// This value has been added to the new set. Add(&'a A), /// This value has been changed between the two sets. Update { /// The old value. old: &'a A, /// The new value. new: &'a A, }, /// This value has been removed from the new set. Remove(&'a A), } enum IterItem<'a, A> { Consider(&'a Node), Yield(&'a A), } impl<'a, A: 'a> DiffIter<'a, A> { pub(crate) fn new(old: &'a Node, new: &'a Node) -> Self { DiffIter { old_stack: if old.keys.is_empty() { Vec::new() } else { vec![IterItem::Consider(old)] }, new_stack: if new.keys.is_empty() { Vec::new() } else { vec![IterItem::Consider(new)] }, } } fn push_node(stack: &mut Vec>, maybe_node: &'a Option>>) { if let Some(ref node) = *maybe_node { stack.push(IterItem::Consider(&node)) } } fn push(stack: &mut Vec>, node: &'a Node) { for n in 0..node.keys.len() { let i = node.keys.len() - n; Self::push_node(stack, &node.children[i]); stack.push(IterItem::Yield(&node.keys[i - 1])); } Self::push_node(stack, &node.children[0]); } } impl<'a, A> Iterator for DiffIter<'a, A> where A: 'a + BTreeValue + PartialEq, { type Item = DiffItem<'a, A>; fn next(&mut self) -> Option { loop { match (self.old_stack.pop(), self.new_stack.pop()) { (None, None) => return None, (None, Some(new)) => match new { IterItem::Consider(new) => Self::push(&mut self.new_stack, &new), IterItem::Yield(new) => return Some(DiffItem::Add(new)), }, (Some(old), None) => match old { IterItem::Consider(old) => Self::push(&mut self.old_stack, &old), IterItem::Yield(old) => return Some(DiffItem::Remove(old)), }, (Some(old), Some(new)) => match (old, new) { (IterItem::Consider(old), IterItem::Consider(new)) => { if !std::ptr::eq(old, new) { match old.keys[0].cmp_values(&new.keys[0]) { Ordering::Less => { Self::push(&mut self.old_stack, &old); self.new_stack.push(IterItem::Consider(new)); } Ordering::Greater => { self.old_stack.push(IterItem::Consider(old)); Self::push(&mut self.new_stack, &new); } Ordering::Equal => { Self::push(&mut self.old_stack, &old); Self::push(&mut self.new_stack, &new); } } } } (IterItem::Consider(old), IterItem::Yield(new)) => { Self::push(&mut self.old_stack, &old); self.new_stack.push(IterItem::Yield(new)); } (IterItem::Yield(old), IterItem::Consider(new)) => { self.old_stack.push(IterItem::Yield(old)); Self::push(&mut self.new_stack, &new); } (IterItem::Yield(old), IterItem::Yield(new)) => match old.cmp_values(&new) { Ordering::Less => { self.new_stack.push(IterItem::Yield(new)); return Some(DiffItem::Remove(old)); } Ordering::Equal => { if old != new { return Some(DiffItem::Update { old, new }); } } Ordering::Greater => { self.old_stack.push(IterItem::Yield(old)); return Some(DiffItem::Add(new)); } }, }, } } } } im-rc-15.0.0/src/nodes/hamt.rs010064400017500001750000000520511365756323600142460ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::borrow::Borrow; use std::fmt; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter::FusedIterator; use std::slice::{Iter as SliceIter, IterMut as SliceIterMut}; use std::{mem, ptr}; use bitmaps::Bits; use sized_chunks::sparse_chunk::{Iter as ChunkIter, IterMut as ChunkIterMut, SparseChunk}; use typenum::{Pow, Unsigned, U2}; use crate::config::HashLevelSize; use crate::util::{clone_ref, Pool, PoolClone, PoolDefault, PoolRef, Ref}; pub(crate) type HashWidth = >::Output; pub(crate) type HashBits = ::Store; // a uint of HASH_SIZE bits pub(crate) const HASH_SHIFT: usize = HashLevelSize::USIZE; pub(crate) const HASH_WIDTH: usize = HashWidth::USIZE; pub(crate) const HASH_MASK: HashBits = (HASH_WIDTH - 1) as HashBits; pub(crate) fn hash_key(bh: &S, key: &K) -> HashBits { let mut hasher = bh.build_hasher(); key.hash(&mut hasher); hasher.finish() as HashBits } #[inline] fn mask(hash: HashBits, shift: usize) -> HashBits { hash >> shift & HASH_MASK } pub trait HashValue { type Key: Eq; fn extract_key(&self) -> &Self::Key; fn ptr_eq(&self, other: &Self) -> bool; } #[derive(Clone)] pub(crate) struct Node { data: SparseChunk, HashWidth>, } #[allow(unsafe_code)] impl PoolDefault for Node { #[cfg(feature = "pool")] unsafe fn default_uninit(target: &mut mem::MaybeUninit) { SparseChunk::default_uninit( target .as_mut_ptr() .cast::, HashWidth>>>() .as_mut() .unwrap(), ) } } #[allow(unsafe_code)] impl PoolClone for Node where A: Clone, { #[cfg(feature = "pool")] unsafe fn clone_uninit(&self, target: &mut mem::MaybeUninit) { self.data.clone_uninit( target .as_mut_ptr() .cast::, HashWidth>>>() .as_mut() .unwrap(), ) } } #[derive(Clone)] pub(crate) struct CollisionNode { hash: HashBits, data: Vec, } pub(crate) enum Entry { Value(A, HashBits), Collision(Ref>), Node(PoolRef>), } impl Clone for Entry { fn clone(&self) -> Self { match self { Entry::Value(value, hash) => Entry::Value(value.clone(), *hash), Entry::Collision(coll) => Entry::Collision(coll.clone()), Entry::Node(node) => Entry::Node(node.clone()), } } } impl Entry { fn is_value(&self) -> bool { match self { Entry::Value(_, _) => true, _ => false, } } fn unwrap_value(self) -> A { match self { Entry::Value(a, _) => a, _ => panic!("nodes::hamt::Entry::unwrap_value: unwrapped a non-value"), } } fn from_node(pool: &Pool>, node: Node) -> Self { Entry::Node(PoolRef::new(pool, node)) } } impl From> for Entry { fn from(node: CollisionNode) -> Self { Entry::Collision(Ref::new(node)) } } impl Default for Node { fn default() -> Self { Self::new() } } impl Node { #[inline] pub(crate) fn new() -> Self { Node { data: SparseChunk::new(), } } #[inline] fn len(&self) -> usize { self.data.len() } #[inline] pub(crate) fn unit(index: usize, value: Entry) -> Self { Node { data: SparseChunk::unit(index, value), } } #[inline] pub(crate) fn pair(index1: usize, value1: Entry, index2: usize, value2: Entry) -> Self { Node { data: SparseChunk::pair(index1, value1, index2, value2), } } #[inline] pub(crate) fn single_child(pool: &Pool>, index: usize, node: Self) -> Self { Node { data: SparseChunk::unit(index, Entry::from_node(pool, node)), } } fn pop(&mut self) -> Entry { self.data.pop().unwrap() } } impl Node { fn merge_values( pool: &Pool>, value1: A, hash1: HashBits, value2: A, hash2: HashBits, shift: usize, ) -> Self { let index1 = mask(hash1, shift) as usize; let index2 = mask(hash2, shift) as usize; if index1 != index2 { // Both values fit on the same level. Node::pair( index1, Entry::Value(value1, hash1), index2, Entry::Value(value2, hash2), ) } else if shift + HASH_SHIFT >= HASH_WIDTH { // If we're at the bottom, we've got a collision. Node::unit( index1, Entry::from(CollisionNode::new(hash1, value1, value2)), ) } else { // Pass the values down a level. let node = Node::merge_values(pool, value1, hash1, value2, hash2, shift + HASH_SHIFT); Node::single_child(pool, index1, node) } } pub(crate) fn get(&self, hash: HashBits, shift: usize, key: &BK) -> Option<&A> where BK: Eq + ?Sized, A::Key: Borrow, { let index = mask(hash, shift) as usize; if let Some(entry) = self.data.get(index) { match entry { Entry::Value(ref value, _) => { if key == value.extract_key().borrow() { Some(value) } else { None } } Entry::Collision(ref coll) => coll.get(key), Entry::Node(ref child) => child.get(hash, shift + HASH_SHIFT, key), } } else { None } } pub(crate) fn get_mut( &mut self, pool: &Pool>, hash: HashBits, shift: usize, key: &BK, ) -> Option<&mut A> where A: Clone, BK: Eq + ?Sized, A::Key: Borrow, { let index = mask(hash, shift) as usize; if let Some(entry) = self.data.get_mut(index) { match entry { Entry::Value(ref mut value, _) => { if key == value.extract_key().borrow() { Some(value) } else { None } } Entry::Collision(ref mut coll_ref) => { let coll = Ref::make_mut(coll_ref); coll.get_mut(key) } Entry::Node(ref mut child_ref) => { let child = PoolRef::make_mut(pool, child_ref); child.get_mut(pool, hash, shift + HASH_SHIFT, key) } } } else { None } } pub(crate) fn insert( &mut self, pool: &Pool>, hash: HashBits, shift: usize, value: A, ) -> Option where A: Clone, { let index = mask(hash, shift) as usize; if let Some(entry) = self.data.get_mut(index) { let mut fallthrough = false; // Value is here match entry { // Update value or create a subtree Entry::Value(ref current, _) => { if current.extract_key() == value.extract_key() { // If we have a key match, fall through to the outer // level where we replace the current value. If we // don't, fall through to the inner level where we merge // some nodes. fallthrough = true; } } // There's already a collision here. Entry::Collision(ref mut collision) => { let coll = Ref::make_mut(collision); return coll.insert(value); } Entry::Node(ref mut child_ref) => { // Child node let child = PoolRef::make_mut(pool, child_ref); return child.insert(pool, hash, shift + HASH_SHIFT, value); } } if !fallthrough { // If we get here, we're looking at a value entry that needs a merge. // We're going to be unsafe and pry it out of the reference, trusting // that we overwrite it with the merged node. #[allow(unsafe_code)] let old_entry = unsafe { ptr::read(entry) }; if shift + HASH_SHIFT >= HASH_WIDTH { // We're at the lowest level, need to set up a collision node. let coll = CollisionNode::new(hash, old_entry.unwrap_value(), value); #[allow(unsafe_code)] unsafe { ptr::write(entry, Entry::from(coll)) }; } else if let Entry::Value(old_value, old_hash) = old_entry { let node = Node::merge_values( pool, old_value, old_hash, value, hash, shift + HASH_SHIFT, ); #[allow(unsafe_code)] unsafe { ptr::write(entry, Entry::from_node(pool, node)) }; } else { unreachable!() } return None; } } // If we get here, either we found nothing at this index, in which case // we insert a new entry, or we hit a value entry with the same key, in // which case we replace it. self.data .insert(index, Entry::Value(value, hash)) .map(Entry::unwrap_value) } pub(crate) fn remove( &mut self, pool: &Pool>, hash: HashBits, shift: usize, key: &BK, ) -> Option where A: Clone, BK: Eq + ?Sized, A::Key: Borrow, { let index = mask(hash, shift) as usize; let mut new_node = None; let mut removed = None; if let Some(entry) = self.data.get_mut(index) { match entry { Entry::Value(ref value, _) => { if key != value.extract_key().borrow() { // Key wasn't in the map. return None; } // Otherwise, fall through to the removal. } Entry::Collision(ref mut coll_ref) => { let coll = Ref::make_mut(coll_ref); removed = coll.remove(key); if coll.len() == 1 { new_node = Some(coll.pop()); } else { return removed; } } Entry::Node(ref mut child_ref) => { let child = PoolRef::make_mut(pool, child_ref); match child.remove(pool, hash, shift + HASH_SHIFT, key) { None => { return None; } Some(value) => { if child.len() == 1 && child.data[child.data.first_index().unwrap()].is_value() { // If the child now contains only a single value node, // pull it up one level and discard the child. removed = Some(value); new_node = Some(child.pop()); } else { return Some(value); } } } } } } if let Some(node) = new_node { self.data.insert(index, node); return removed; } self.data.remove(index).map(Entry::unwrap_value) } } impl CollisionNode { fn new(hash: HashBits, value1: A, value2: A) -> Self { CollisionNode { hash, data: vec![value1, value2], } } #[inline] fn len(&self) -> usize { self.data.len() } fn get(&self, key: &BK) -> Option<&A> where BK: Eq + ?Sized, A::Key: Borrow, { for entry in &self.data { if key == entry.extract_key().borrow() { return Some(entry); } } None } fn get_mut(&mut self, key: &BK) -> Option<&mut A> where BK: Eq + ?Sized, A::Key: Borrow, { for entry in &mut self.data { if key == entry.extract_key().borrow() { return Some(entry); } } None } fn insert(&mut self, value: A) -> Option { for item in &mut self.data { if value.extract_key() == item.extract_key() { return Some(mem::replace(item, value)); } } self.data.push(value); None } fn remove(&mut self, key: &BK) -> Option where BK: Eq + ?Sized, A::Key: Borrow, { let mut loc = None; for (index, item) in self.data.iter().enumerate() { if key == item.extract_key().borrow() { loc = Some(index); } } if let Some(index) = loc { Some(self.data.remove(index)) } else { None } } fn pop(&mut self) -> Entry { Entry::Value(self.data.pop().unwrap(), self.hash) } } // Ref iterator pub(crate) struct Iter<'a, A> { count: usize, stack: Vec, HashWidth>>, current: ChunkIter<'a, Entry, HashWidth>, collision: Option<(HashBits, SliceIter<'a, A>)>, } impl<'a, A> Iter<'a, A> where A: 'a, { pub(crate) fn new(root: &'a Node, size: usize) -> Self { Iter { count: size, stack: Vec::with_capacity((HASH_WIDTH / HASH_SHIFT) + 1), current: root.data.iter(), collision: None, } } } impl<'a, A> Iterator for Iter<'a, A> where A: 'a, { type Item = (&'a A, HashBits); fn next(&mut self) -> Option { if self.count == 0 { return None; } if self.collision.is_some() { if let Some((hash, ref mut coll)) = self.collision { match coll.next() { None => {} Some(value) => { self.count -= 1; return Some((value, hash)); } } } self.collision = None; return self.next(); } match self.current.next() { Some(Entry::Value(value, hash)) => { self.count -= 1; Some((value, *hash)) } Some(Entry::Node(child)) => { let current = mem::replace(&mut self.current, child.data.iter()); self.stack.push(current); self.next() } Some(Entry::Collision(coll)) => { self.collision = Some((coll.hash, coll.data.iter())); self.next() } None => match self.stack.pop() { None => None, Some(iter) => { self.current = iter; self.next() } }, } } fn size_hint(&self) -> (usize, Option) { (self.count, Some(self.count)) } } impl<'a, A> ExactSizeIterator for Iter<'a, A> where A: 'a {} impl<'a, A> FusedIterator for Iter<'a, A> where A: 'a {} // Mut ref iterator pub(crate) struct IterMut<'a, A> { count: usize, pool: Pool>, stack: Vec, HashWidth>>, current: ChunkIterMut<'a, Entry, HashWidth>, collision: Option<(HashBits, SliceIterMut<'a, A>)>, } impl<'a, A> IterMut<'a, A> where A: 'a, { pub(crate) fn new(pool: &Pool>, root: &'a mut Node, size: usize) -> Self { IterMut { count: size, pool: pool.clone(), stack: Vec::with_capacity((HASH_WIDTH / HASH_SHIFT) + 1), current: root.data.iter_mut(), collision: None, } } } impl<'a, A> Iterator for IterMut<'a, A> where A: Clone + 'a, { type Item = (&'a mut A, HashBits); fn next(&mut self) -> Option { if self.count == 0 { return None; } if self.collision.is_some() { if let Some((hash, ref mut coll)) = self.collision { match coll.next() { None => {} Some(value) => { self.count -= 1; return Some((value, hash)); } } } self.collision = None; return self.next(); } match self.current.next() { Some(Entry::Value(value, hash)) => { self.count -= 1; Some((value, *hash)) } Some(Entry::Node(child_ref)) => { let child = PoolRef::make_mut(&self.pool, child_ref); let current = mem::replace(&mut self.current, child.data.iter_mut()); self.stack.push(current); self.next() } Some(Entry::Collision(coll_ref)) => { let coll = Ref::make_mut(coll_ref); self.collision = Some((coll.hash, coll.data.iter_mut())); self.next() } None => match self.stack.pop() { None => None, Some(iter) => { self.current = iter; self.next() } }, } } fn size_hint(&self) -> (usize, Option) { (self.count, Some(self.count)) } } impl<'a, A> ExactSizeIterator for IterMut<'a, A> where A: Clone + 'a {} impl<'a, A> FusedIterator for IterMut<'a, A> where A: Clone + 'a {} // Consuming iterator pub(crate) struct Drain where A: HashValue, { count: usize, pool: Pool>, stack: Vec>>, current: PoolRef>, collision: Option>, } impl Drain where A: HashValue, { pub(crate) fn new(pool: &Pool>, root: PoolRef>, size: usize) -> Self { Drain { count: size, pool: pool.clone(), stack: vec![], current: root, collision: None, } } } impl Iterator for Drain where A: HashValue + Clone, { type Item = (A, HashBits); fn next(&mut self) -> Option { if self.count == 0 { return None; } if self.collision.is_some() { if let Some(ref mut coll) = self.collision { if let Some(value) = coll.data.pop() { self.count -= 1; return Some((value, coll.hash)); } } self.collision = None; return self.next(); } match PoolRef::make_mut(&self.pool, &mut self.current).data.pop() { Some(Entry::Value(value, hash)) => { self.count -= 1; Some((value, hash)) } Some(Entry::Collision(coll_ref)) => { self.collision = Some(clone_ref(coll_ref)); self.next() } Some(Entry::Node(child)) => { let parent = mem::replace(&mut self.current, child); self.stack.push(parent); self.next() } None => match self.stack.pop() { None => None, Some(parent) => { self.current = parent; self.next() } }, } } fn size_hint(&self) -> (usize, Option) { (self.count, Some(self.count)) } } impl ExactSizeIterator for Drain where A: Clone {} impl FusedIterator for Drain where A: Clone {} impl fmt::Debug for Node { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "Node[ ")?; for i in self.data.indices() { write!(f, "{}: ", i)?; match &self.data[i] { Entry::Value(v, h) => write!(f, "{:?} :: {}, ", v, h)?, Entry::Collision(c) => write!(f, "Coll{:?} :: {}", c.data, c.hash)?, Entry::Node(n) => write!(f, "{:?}, ", n)?, } } write!(f, " ]") } } im-rc-15.0.0/src/nodes/mod.rs010064400017500001750000000010201365756323600140620ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. pub(crate) mod btree; pub(crate) mod hamt; pub(crate) mod rrb; pub(crate) mod chunk { use crate::config::VectorChunkSize; use sized_chunks as sc; use typenum::Unsigned; pub(crate) type Chunk = sc::sized_chunk::Chunk; pub(crate) const CHUNK_SIZE: usize = VectorChunkSize::USIZE; } im-rc-15.0.0/src/nodes/rrb.rs010064400017500001750000001176341365756323600141130ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::mem::replace; use std::ops::Range; use crate::nodes::chunk::{Chunk, CHUNK_SIZE}; use crate::util::{ Pool, PoolRef, Side::{self, Left, Right}, }; use crate::vector::RRBPool; use self::Entry::*; pub(crate) const NODE_SIZE: usize = CHUNK_SIZE; #[derive(Debug)] enum Size { Size(usize), Table(PoolRef>), } impl Clone for Size { fn clone(&self) -> Self { match *self { Size::Size(size) => Size::Size(size), Size::Table(ref table) => Size::Table(table.clone()), } } } impl Size { fn size(&self) -> usize { match self { Size::Size(s) => *s, Size::Table(sizes) => *sizes.last().unwrap_or(&0), } } fn is_size(&self) -> bool { match self { Size::Size(_) => true, Size::Table(_) => false, } } fn table_from_size(pool: &Pool>, level: usize, size: usize) -> Self { let mut chunk = Chunk::new(); let mut remaining = size; if let Some(child_size) = NODE_SIZE.checked_pow(level as u32) { while remaining > child_size { let next_value = chunk.last().unwrap_or(&0) + child_size; chunk.push_back(next_value); remaining -= child_size; } } if remaining > 0 { let next_value = chunk.last().unwrap_or(&0) + remaining; chunk.push_back(next_value); } Size::Table(PoolRef::new(pool, chunk)) } fn push(&mut self, pool: &Pool>, side: Side, level: usize, value: usize) { let size = match self { Size::Size(ref mut size) => match side { Left => *size, Right => { *size += value; return; } }, Size::Table(ref mut size_ref) => { let size_table = PoolRef::make_mut(pool, size_ref); debug_assert!(size_table.len() < NODE_SIZE); match side { Left => { for entry in size_table.iter_mut() { *entry += value; } size_table.push_front(value); } Right => { let prev = *(size_table.last().unwrap_or(&0)); size_table.push_back(value + prev); } } return; } }; *self = Size::table_from_size(pool, level, size); self.push(pool, side, level, value); } fn pop(&mut self, pool: &Pool>, side: Side, level: usize, value: usize) { let size = match self { Size::Size(ref mut size) => match side { Left => *size, Right => { *size -= value; return; } }, Size::Table(ref mut size_ref) => { let size_table = PoolRef::make_mut(pool, size_ref); match side { Left => { let first = size_table.pop_front(); debug_assert_eq!(value, first); for entry in size_table.iter_mut() { *entry -= value; } } Right => { let pop = size_table.pop_back(); let last = size_table.last().unwrap_or(&0); debug_assert_eq!(value, pop - last); } } return; } }; *self = Size::table_from_size(pool, level, size); self.pop(pool, side, level, value); } fn update(&mut self, pool: &Pool>, index: usize, level: usize, value: isize) { let size = match self { Size::Size(ref size) => *size, Size::Table(ref mut size_ref) => { let size_table = PoolRef::make_mut(pool, size_ref); for entry in size_table.iter_mut().skip(index) { *entry = (*entry as isize + value) as usize; } return; } }; *self = Size::table_from_size(pool, level, size); self.update(pool, index, level, value); } } pub(crate) enum PushResult { Full(A, usize), Done, } pub(crate) enum PopResult { Done(A), Drained(A), Empty, } pub(crate) enum SplitResult { Dropped(usize), OutOfBounds, } // Invariants: Nodes only at level > 0, Values/Empty only at level = 0 enum Entry { Nodes(Size, PoolRef>>), Values(PoolRef>), Empty, } impl Clone for Entry { fn clone(&self) -> Self { match *self { Nodes(ref size, ref nodes) => Nodes(size.clone(), nodes.clone()), Values(ref values) => Values(values.clone()), Empty => Empty, } } } impl Entry { fn len(&self) -> usize { match self { Nodes(_, ref nodes) => nodes.len(), Values(ref values) => values.len(), Empty => 0, } } fn is_full(&self) -> bool { match self { Nodes(_, ref nodes) => nodes.is_full(), Values(ref values) => values.is_full(), Empty => false, } } fn unwrap_values(&self) -> &Chunk { match self { Values(ref values) => values, _ => panic!("rrb::Entry::unwrap_values: expected values, found nodes"), } } fn unwrap_nodes(&self) -> &Chunk> { match self { Nodes(_, ref nodes) => nodes, _ => panic!("rrb::Entry::unwrap_nodes: expected nodes, found values"), } } fn unwrap_values_mut(&mut self, pool: &RRBPool) -> &mut Chunk { match self { Values(ref mut values) => PoolRef::make_mut(&pool.value_pool, values), _ => panic!("rrb::Entry::unwrap_values_mut: expected values, found nodes"), } } fn unwrap_nodes_mut(&mut self, pool: &RRBPool) -> &mut Chunk> { match self { Nodes(_, ref mut nodes) => PoolRef::make_mut(&pool.node_pool, nodes), _ => panic!("rrb::Entry::unwrap_nodes_mut: expected nodes, found values"), } } fn values(self) -> Chunk { match self { Values(values) => PoolRef::unwrap_or_clone(values), _ => panic!("rrb::Entry::values: expected values, found nodes"), } } fn nodes(self) -> Chunk> { match self { Nodes(_, nodes) => PoolRef::unwrap_or_clone(nodes), _ => panic!("rrb::Entry::nodes: expected nodes, found values"), } } fn is_empty_node(&self) -> bool { match self { Empty => true, _ => false, } } } // Node pub(crate) struct Node { children: Entry, } impl Clone for Node { fn clone(&self) -> Self { Node { children: self.children.clone(), } } } impl Default for Node { fn default() -> Self { Self::new() } } impl Node { pub(crate) fn new() -> Self { Node { children: Empty } } pub(crate) fn parent(pool: &RRBPool, level: usize, children: Chunk) -> Self { let size = { let mut size = Size::Size(0); let mut it = children.iter().peekable(); loop { match it.next() { None => break, Some(child) => { if size.is_size() && !child.is_completely_dense(level - 1) && it.peek().is_some() { size = Size::table_from_size(&pool.size_pool, level, size.size()); } size.push(&pool.size_pool, Right, level, child.len()) } } } size }; Node { children: Nodes(size, PoolRef::new(&pool.node_pool, children)), } } pub(crate) fn clear_node(&mut self) { self.children = Empty; } pub(crate) fn from_chunk(pool: &RRBPool, level: usize, chunk: PoolRef>) -> Self { let node = Node { children: Values(chunk), }; node.elevate(pool, level) } pub(crate) fn single_parent(pool: &RRBPool, node: Self) -> Self { let size = if node.is_dense() { Size::Size(node.len()) } else { let size_table = Chunk::unit(node.len()); Size::Table(PoolRef::new(&pool.size_pool, size_table)) }; let children = PoolRef::new(&pool.node_pool, Chunk::unit(node)); Node { children: Nodes(size, children), } } pub(crate) fn join_dense(pool: &RRBPool, left: Self, right: Self) -> Self { let left_len = left.len(); let right_len = right.len(); Node { children: { let children = PoolRef::new(&pool.node_pool, Chunk::pair(left, right)); Nodes(Size::Size(left_len + right_len), children) }, } } pub(crate) fn elevate(self, pool: &RRBPool, level_increment: usize) -> Self { if level_increment > 0 { Self::single_parent(pool, self.elevate(pool, level_increment - 1)) } else { self } } pub(crate) fn join_branches(self, pool: &RRBPool, right: Self, level: usize) -> Self { let left_len = self.len(); let right_len = right.len(); let size = if self.is_completely_dense(level) && right.is_dense() { Size::Size(left_len + right_len) } else { let size_table = Chunk::pair(left_len, left_len + right_len); Size::Table(PoolRef::new(&pool.size_pool, size_table)) }; Node { children: { let children = Chunk::pair(self, right); Nodes(size, PoolRef::new(&pool.node_pool, children)) }, } } pub(crate) fn len(&self) -> usize { match self.children { Entry::Nodes(Size::Size(size), _) => size, Entry::Nodes(Size::Table(ref size_table), _) => *(size_table.last().unwrap_or(&0)), Entry::Values(ref values) => values.len(), Entry::Empty => 0, } } pub(crate) fn is_empty(&self) -> bool { self.len() == 0 } pub(crate) fn is_single(&self) -> bool { self.children.len() == 1 } pub(crate) fn is_full(&self) -> bool { self.children.is_full() } #[allow(dead_code)] // this is only used by tests pub(crate) fn number_of_children(&self) -> usize { self.children.len() } pub(crate) fn first_child(&self) -> &Self { self.children.unwrap_nodes().first().unwrap() } /// True if the node is dense and so doesn't have a size table fn is_dense(&self) -> bool { match self.children { Entry::Nodes(Size::Table(_), _) => false, _ => true, } } /// True if the node and its children are dense and at capacity // TODO can use this technique to quickly test if a Size::Table // should be converted back to a Size::Size fn is_completely_dense(&self, level: usize) -> bool { // Size of a full node is NODE_SIZE at level 0, NODE_SIZE² at // level 1, etc. if let Some(expected_size) = NODE_SIZE.checked_pow(level as u32 + 1) { self.size() == expected_size } else { // We overflowed a usize, there's no way we can be completely dense as we know the size // fits in a usize. false } } #[inline] fn size(&self) -> usize { match self.children { Entry::Nodes(ref size, _) => size.size(), Entry::Values(ref values) => values.len(), Entry::Empty => 0, } } #[inline] fn push_size(&mut self, pool: &RRBPool, side: Side, level: usize, value: usize) { if let Entry::Nodes(ref mut size, _) = self.children { size.push(&pool.size_pool, side, level, value) } } #[inline] fn pop_size(&mut self, pool: &RRBPool, side: Side, level: usize, value: usize) { if let Entry::Nodes(ref mut size, _) = self.children { size.pop(&pool.size_pool, side, level, value) } } #[inline] fn update_size(&mut self, pool: &RRBPool, index: usize, level: usize, value: isize) { if let Entry::Nodes(ref mut size, _) = self.children { size.update(&pool.size_pool, index, level, value) } } fn size_up_to(&self, level: usize, index: usize) -> usize { if let Entry::Nodes(ref size, _) = self.children { if index == 0 { 0 } else { match size { Size::Table(ref size_table) => size_table[index - 1], Size::Size(_) => index * NODE_SIZE.pow(level as u32), } } } else { index } } fn index_in(&self, level: usize, index: usize) -> Option { let mut target_idx = if let Some(child_size) = NODE_SIZE.checked_pow(level as u32) { index / child_size } else { 0 }; if target_idx >= self.children.len() { return None; } if let Entry::Nodes(Size::Table(ref size_table), _) = self.children { while size_table[target_idx] <= index { target_idx += 1; if target_idx >= size_table.len() { return None; } } } Some(target_idx) } pub(crate) fn index(&self, level: usize, index: usize) -> &A { if level == 0 { &self.children.unwrap_values()[index] } else { let target_idx = self.index_in(level, index).unwrap(); self.children.unwrap_nodes()[target_idx] .index(level - 1, index - self.size_up_to(level, target_idx)) } } pub(crate) fn index_mut(&mut self, pool: &RRBPool, level: usize, index: usize) -> &mut A { if level == 0 { &mut self.children.unwrap_values_mut(pool)[index] } else { let target_idx = self.index_in(level, index).unwrap(); let offset = index - self.size_up_to(level, target_idx); let child = &mut self.children.unwrap_nodes_mut(pool)[target_idx]; child.index_mut(pool, level - 1, offset) } } pub(crate) fn lookup_chunk( &self, level: usize, base: usize, index: usize, ) -> (Range, *const Chunk) { if level == 0 { ( base..(base + self.children.len()), self.children.unwrap_values() as *const Chunk, ) } else { let target_idx = self.index_in(level, index).unwrap(); let offset = self.size_up_to(level, target_idx); let child_base = base + offset; let children = self.children.unwrap_nodes(); let child = &children[target_idx]; child.lookup_chunk(level - 1, child_base, index - offset) } } pub(crate) fn lookup_chunk_mut( &mut self, pool: &RRBPool, level: usize, base: usize, index: usize, ) -> (Range, *mut Chunk) { if level == 0 { ( base..(base + self.children.len()), self.children.unwrap_values_mut(pool) as *mut Chunk, ) } else { let target_idx = self.index_in(level, index).unwrap(); let offset = self.size_up_to(level, target_idx); let child_base = base + offset; let children = self.children.unwrap_nodes_mut(pool); let child = &mut children[target_idx]; child.lookup_chunk_mut(pool, level - 1, child_base, index - offset) } } fn push_child_node(&mut self, pool: &RRBPool, side: Side, child: Node) { let children = self.children.unwrap_nodes_mut(pool); match side { Left => children.push_front(child), Right => children.push_back(child), } } fn pop_child_node(&mut self, pool: &RRBPool, side: Side) -> Node { let children = self.children.unwrap_nodes_mut(pool); match side { Left => children.pop_front(), Right => children.pop_back(), } } pub(crate) fn push_chunk( &mut self, pool: &RRBPool, level: usize, side: Side, mut chunk: PoolRef>, ) -> PushResult>> { if chunk.is_empty() { return PushResult::Done; } let is_full = self.is_full(); if level == 0 { if self.children.is_empty_node() { self.push_size(pool, side, level, chunk.len()); self.children = Values(chunk); PushResult::Done } else { let values = self.children.unwrap_values_mut(pool); if values.len() + chunk.len() <= NODE_SIZE { let chunk = PoolRef::make_mut(&pool.value_pool, &mut chunk); match side { Side::Left => { chunk.append(values); values.append(chunk); } Side::Right => values.append(chunk), } PushResult::Done } else { PushResult::Full(chunk, 0) } } } else if level == 1 { // If rightmost existing node has any room, merge as much as // possible over from the new node. let num_drained = match side { Side::Right => { if let Entry::Nodes(ref mut size, ref mut children) = self.children { let rightmost = PoolRef::make_mut(&pool.node_pool, children) .last_mut() .unwrap(); let old_size = rightmost.len(); let chunk = PoolRef::make_mut(&pool.value_pool, &mut chunk); let values = rightmost.children.unwrap_values_mut(pool); let to_drain = chunk.len().min(NODE_SIZE - values.len()); values.drain_from_front(chunk, to_drain); size.pop(&pool.size_pool, Side::Right, level, old_size); size.push(&pool.size_pool, Side::Right, level, values.len()); to_drain } else { 0 } } Side::Left => { if let Entry::Nodes(ref mut size, ref mut children) = self.children { let leftmost = PoolRef::make_mut(&pool.node_pool, children) .first_mut() .unwrap(); let old_size = leftmost.len(); let chunk = PoolRef::make_mut(&pool.value_pool, &mut chunk); let values = leftmost.children.unwrap_values_mut(pool); let to_drain = chunk.len().min(NODE_SIZE - values.len()); values.drain_from_back(chunk, to_drain); size.pop(&pool.size_pool, Side::Left, level, old_size); size.push(&pool.size_pool, Side::Left, level, values.len()); to_drain } else { 0 } } }; if is_full { PushResult::Full(chunk, num_drained) } else { // If the chunk is empty after being drained, there might be // more space in existing chunks. To keep the middle dense, we // do not add it here. if !chunk.is_empty() { if side == Left && chunk.len() < NODE_SIZE { if let Entry::Nodes(ref mut size, _) = self.children { if let Size::Size(value) = *size { *size = Size::table_from_size(&pool.size_pool, level, value); } } } self.push_size(pool, side, level, chunk.len()); self.push_child_node(pool, side, Node::from_chunk(pool, 0, chunk)); } PushResult::Done } } else { let chunk_size = chunk.len(); let index = match side { Right => self.children.len() - 1, Left => 0, }; let new_child = { let children = self.children.unwrap_nodes_mut(pool); let child = &mut children[index]; match child.push_chunk(pool, level - 1, side, chunk) { PushResult::Done => None, PushResult::Full(chunk, num_drained) => { // Our chunk was too large for `child`, so it could not // be pushed there. However, exactly `num_drained` // elements were added to the child. We need to reflect // that change in the size field of the node. match side { Right => match self.children { Entry::Nodes(Size::Table(ref mut sizes), _) => { let sizes = PoolRef::make_mut(&pool.size_pool, sizes); sizes[index] += num_drained; } Entry::Nodes(Size::Size(ref mut size), _) => { *size += num_drained; } Entry::Values(_) | Entry::Empty => (), }, Left => { self.update_size(pool, 0, level, num_drained as isize); } } if is_full { return PushResult::Full(chunk, 0); } else { Some(Node::from_chunk(pool, level - 1, chunk)) } } } }; match new_child { None => { self.update_size(pool, index, level, chunk_size as isize); PushResult::Done } Some(child) => { if side == Left && chunk_size < NODE_SIZE { if let Entry::Nodes(ref mut size, _) = self.children { if let Size::Size(value) = *size { *size = Size::table_from_size(&pool.size_pool, level, value); } } } self.push_size(pool, side, level, child.len()); self.push_child_node(pool, side, child); PushResult::Done } } } } pub(crate) fn pop_chunk( &mut self, pool: &RRBPool, level: usize, side: Side, ) -> PopResult>> { if self.is_empty() { return PopResult::Empty; } if level == 0 { // should only get here if the tree is just one leaf node match replace(&mut self.children, Empty) { Values(chunk) => PopResult::Drained(chunk), Empty => panic!("rrb::Node::pop_chunk: non-empty tree with Empty leaf"), Nodes(_, _) => panic!("rrb::Node::pop_chunk: branch node at leaf"), } } else if level == 1 { let child_node = self.pop_child_node(pool, side); self.pop_size(pool, side, level, child_node.len()); let chunk = match child_node.children { Values(ref chunk) => chunk.clone(), Empty => panic!("rrb::Node::pop_chunk: non-empty tree with Empty leaf"), Nodes(_, _) => panic!("rrb::Node::pop_chunk: branch node at leaf"), }; if self.is_empty() { PopResult::Drained(chunk) } else { PopResult::Done(chunk) } } else { let index = match side { Right => self.children.len() - 1, Left => 0, }; let mut drained = false; let chunk = { let children = self.children.unwrap_nodes_mut(pool); let child = &mut children[index]; match child.pop_chunk(pool, level - 1, side) { PopResult::Empty => return PopResult::Empty, PopResult::Done(chunk) => chunk, PopResult::Drained(chunk) => { drained = true; chunk } } }; if drained { self.pop_size(pool, side, level, chunk.len()); self.pop_child_node(pool, side); if self.is_empty() { PopResult::Drained(chunk) } else { PopResult::Done(chunk) } } else { self.update_size(pool, index, level, -(chunk.len() as isize)); PopResult::Done(chunk) } } } pub(crate) fn split( &mut self, pool: &RRBPool, level: usize, drop_side: Side, index: usize, ) -> SplitResult { if index == 0 && drop_side == Side::Left { // Dropped nothing return SplitResult::Dropped(0); } if level > 0 && index == 0 && drop_side == Side::Right { // Dropped everything let dropped = if let Entry::Nodes(ref size, _) = self.children { size.size() } else { panic!("leaf node at non-leaf level!"); }; self.children = Entry::Empty; return SplitResult::Dropped(dropped); } let mut dropped; if level == 0 { let len = self.children.len(); if index >= len { return SplitResult::OutOfBounds; } let children = self.children.unwrap_values_mut(pool); match drop_side { Side::Left => children.drop_left(index), Side::Right => children.drop_right(index), } SplitResult::Dropped(match drop_side { Left => index, Right => len - index, }) } else if let Some(target_idx) = self.index_in(level, index) { let size_up_to = self.size_up_to(level, target_idx); let (size, children) = if let Entry::Nodes(ref mut size, ref mut children) = self.children { (size, PoolRef::make_mut(&pool.node_pool, children)) } else { unreachable!() }; let child_gone = 0 == { let child_node = &mut children[target_idx]; match child_node.split(pool, level - 1, drop_side, index - size_up_to) { SplitResult::OutOfBounds => return SplitResult::OutOfBounds, SplitResult::Dropped(amount) => dropped = amount, } child_node.len() }; match drop_side { Left => { let mut drop_from = target_idx; if child_gone { drop_from += 1; } children.drop_left(drop_from); if let Size::Size(value) = *size { *size = Size::table_from_size(&pool.size_pool, level, value); } let size_table = if let Size::Table(ref mut size_ref) = size { PoolRef::make_mut(&pool.size_pool, size_ref) } else { unreachable!() }; let dropped_size = if target_idx > 0 { size_table[target_idx - 1] } else { 0 }; dropped += dropped_size; size_table.drop_left(drop_from); for i in size_table.iter_mut() { *i -= dropped; } } Right => { let at_last = target_idx == children.len() - 1; let mut drop_from = target_idx + 1; if child_gone { drop_from -= 1; } if drop_from < children.len() { children.drop_right(drop_from); } match size { Size::Size(ref mut size) if at_last => { *size -= dropped; } Size::Size(ref mut size) => { let size_per_child = NODE_SIZE.pow(level as u32); let remainder = (target_idx + 1) * size_per_child; let new_size = remainder - dropped; if new_size < *size { dropped = *size - new_size; *size = new_size; } else { unreachable!( "this means node is empty, should be caught at start of method" ); } } Size::Table(ref mut size_ref) => { let size_table = PoolRef::make_mut(&pool.size_pool, size_ref); let dropped_size = size_table[size_table.len() - 1] - size_table[target_idx]; if drop_from < size_table.len() { size_table.drop_right(drop_from); } if !child_gone { size_table[target_idx] -= dropped; } dropped += dropped_size; } } } } SplitResult::Dropped(dropped) } else { SplitResult::OutOfBounds } } fn merge_leaves(pool: &RRBPool, mut left: Self, mut right: Self) -> Self { if left.children.is_empty_node() { // Left is empty, just use right Self::single_parent(pool, right) } else if right.children.is_empty_node() { // Right is empty, just use left Self::single_parent(pool, left) } else { { let left_vals = left.children.unwrap_values_mut(pool); let left_len = left_vals.len(); let right_vals = right.children.unwrap_values_mut(pool); let right_len = right_vals.len(); if left_len + right_len <= NODE_SIZE { left_vals.append(right_vals); } else { let count = right_len.min(NODE_SIZE - left_len); left_vals.drain_from_front(right_vals, count); } } if right.is_empty() { Self::single_parent(pool, left) } else { Self::join_dense(pool, left, right) } } } fn merge_rebalance( pool: &RRBPool, level: usize, left: Self, middle: Self, right: Self, ) -> Self { let left_nodes = left.children.nodes().into_iter(); let middle_nodes = middle.children.nodes().into_iter(); let right_nodes = right.children.nodes().into_iter(); let mut subtree_still_balanced = true; let mut next_leaf = Chunk::new(); let mut next_node = Chunk::new(); let mut next_subtree = Chunk::new(); let mut root = Chunk::new(); for subtree in left_nodes.chain(middle_nodes).chain(right_nodes) { if subtree.is_empty() { continue; } if subtree.is_completely_dense(level) && subtree_still_balanced { root.push_back(subtree); continue; } subtree_still_balanced = false; if level == 1 { for value in subtree.children.values() { next_leaf.push_back(value); if next_leaf.is_full() { let new_node = Node::from_chunk(pool, 0, PoolRef::new(&pool.value_pool, next_leaf)); next_subtree.push_back(new_node); next_leaf = Chunk::new(); if next_subtree.is_full() { let new_subtree = Node::parent(pool, level, next_subtree); root.push_back(new_subtree); next_subtree = Chunk::new(); } } } } else { for node in subtree.children.nodes() { next_node.push_back(node); if next_node.is_full() { let new_node = Node::parent(pool, level - 1, next_node); next_subtree.push_back(new_node); next_node = Chunk::new(); if next_subtree.is_full() { let new_subtree = Node::parent(pool, level, next_subtree); root.push_back(new_subtree); next_subtree = Chunk::new(); } } } } } if !next_leaf.is_empty() { let new_node = Node::from_chunk(pool, 0, PoolRef::new(&pool.value_pool, next_leaf)); next_subtree.push_back(new_node); } if !next_node.is_empty() { let new_node = Node::parent(pool, level - 1, next_node); next_subtree.push_back(new_node); } if !next_subtree.is_empty() { let new_subtree = Node::parent(pool, level, next_subtree); root.push_back(new_subtree); } Node::parent(pool, level + 1, root) } pub(crate) fn merge(pool: &RRBPool, mut left: Self, mut right: Self, level: usize) -> Self { if level == 0 { Self::merge_leaves(pool, left, right) } else { let merged = { if level == 1 { // We're going to rebalance all the leaves anyway, there's // no need for a middle at level 1 Node::parent(pool, 0, Chunk::new()) } else { let left_last = if let Entry::Nodes(ref mut size, ref mut children) = left.children { let node = PoolRef::make_mut(&pool.node_pool, children).pop_back(); if !node.is_empty() { size.pop(&pool.size_pool, Side::Right, level, node.len()); } node } else { panic!("expected nodes, found entries or empty"); }; let right_first = if let Entry::Nodes(ref mut size, ref mut children) = right.children { let node = PoolRef::make_mut(&pool.node_pool, children).pop_front(); if !node.is_empty() { size.pop(&pool.size_pool, Side::Left, level, node.len()); } node } else { panic!("expected nodes, found entries or empty"); }; Self::merge(pool, left_last, right_first, level - 1) } }; Self::merge_rebalance(pool, level, left, merged, right) } } #[cfg(any(test, feature = "debug"))] pub(crate) fn assert_invariants(&self, level: usize) -> usize { // Verifies that the size table matches reality. match self.children { Entry::Empty => 0, Entry::Values(ref values) => { // An empty value node is pointless and should never occur. assert_ne!(0, values.len()); // Value nodes should only occur at level 0. assert_eq!(0, level); values.len() } Entry::Nodes(ref size, ref children) => { // A parent node with no children should never occur. assert_ne!(0, children.len()); // Parent nodes should never occur at level 0. assert_ne!(0, level); let mut lengths = Vec::new(); let should_be_dense = if let Size::Size(_) = size { true } else { false }; for (index, child) in children.iter().enumerate() { let len = child.assert_invariants(level - 1); if should_be_dense && index < children.len() - 1 { // Assert that non-end nodes without size tables are full. assert_eq!(len, NODE_SIZE.pow(level as u32)); } lengths.push(len); } match size { Size::Size(size) => { let total: usize = lengths.iter().sum(); assert_eq!(*size, total); } Size::Table(ref table) => { assert_eq!(table.iter().len(), children.len()); for (index, current) in table.iter().enumerate() { let expected: usize = lengths.iter().take(index + 1).sum(); assert_eq!(expected, *current); } } } lengths.iter().sum() } } } // pub fn print(&self, f: &mut W, indent: usize, level: usize) -> Result<(), fmt::Error> // where // W: fmt::Write, // A: fmt::Debug, // { // print_indent(f, indent)?; // if level == 0 { // if self.children.is_empty_node() { // writeln!(f, "Leaf: EMPTY") // } else { // writeln!(f, "Leaf: {:?}", self.children.unwrap_values()) // } // } else { // match &self.children { // Entry::Nodes(size, children) => { // writeln!(f, "Node level {} size_table {:?}", level, size)?; // for child in children.iter() { // child.print(f, indent + 4, level - 1)?; // } // Ok(()) // } // _ => unreachable!(), // } // } // } } // fn print_indent(f: &mut W, indent: usize) -> Result<(), fmt::Error> // where // W: fmt::Write, // { // for _i in 0..indent { // write!(f, " ")?; // } // Ok(()) // } im-rc-15.0.0/src/ord/map.rs010064400017500001750000002205751365756323600135560ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! An ordered map. //! //! An immutable ordered map implemented as a [B-tree] [1]. //! //! Most operations on this type of map are O(log n). A //! [`HashMap`][hashmap::HashMap] is usually a better choice for //! performance, but the `OrdMap` has the advantage of only requiring //! an [`Ord`][std::cmp::Ord] constraint on the key, and of being //! ordered, so that keys always come out from lowest to highest, //! where a [`HashMap`][hashmap::HashMap] has no guaranteed ordering. //! //! [1]: https://en.wikipedia.org/wiki/B-tree //! [hashmap::HashMap]: ../hashmap/struct.HashMap.html //! [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html use std::borrow::Borrow; use std::cmp::Ordering; use std::collections; use std::fmt::{Debug, Error, Formatter}; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter::{FromIterator, Iterator, Sum}; use std::mem; use std::ops::{Add, Index, IndexMut, RangeBounds}; use crate::hashmap::HashMap; use crate::nodes::btree::{BTreeValue, Insert, Node, Remove}; #[cfg(has_specialisation)] use crate::util::linear_search_by; use crate::util::{Pool, PoolRef}; pub use crate::nodes::btree::{ ConsumingIter, DiffItem as NodeDiffItem, DiffIter as NodeDiffIter, Iter as RangedIter, }; /// Construct a map from a sequence of key/value pairs. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// # fn main() { /// assert_eq!( /// ordmap!{ /// 1 => 11, /// 2 => 22, /// 3 => 33 /// }, /// OrdMap::from(vec![(1, 11), (2, 22), (3, 33)]) /// ); /// # } /// ``` #[macro_export] macro_rules! ordmap { () => { $crate::ordmap::OrdMap::new() }; ( $( $key:expr => $value:expr ),* ) => {{ let mut map = $crate::ordmap::OrdMap::new(); $({ map.insert($key, $value); })*; map }}; } #[cfg(not(has_specialisation))] impl BTreeValue for (K, V) { type Key = K; fn ptr_eq(&self, _other: &Self) -> bool { false } fn search_key(slice: &[Self], key: &BK) -> Result where BK: Ord + ?Sized, Self::Key: Borrow, { slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key)) } fn search_value(slice: &[Self], key: &Self) -> Result { slice.binary_search_by(|value| value.0.cmp(&key.0)) } fn cmp_keys(&self, other: &BK) -> Ordering where BK: Ord + ?Sized, Self::Key: Borrow, { Self::Key::borrow(&self.0).cmp(other) } fn cmp_values(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) } } #[cfg(has_specialisation)] impl BTreeValue for (K, V) { type Key = K; fn ptr_eq(&self, _other: &Self) -> bool { false } default fn search_key(slice: &[Self], key: &BK) -> Result where BK: Ord + ?Sized, Self::Key: Borrow, { slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key)) } default fn search_value(slice: &[Self], key: &Self) -> Result { slice.binary_search_by(|value| value.0.cmp(&key.0)) } fn cmp_keys(&self, other: &BK) -> Ordering where BK: Ord + ?Sized, Self::Key: Borrow, { Self::Key::borrow(&self.0).cmp(other) } fn cmp_values(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) } } #[cfg(has_specialisation)] impl BTreeValue for (K, V) { fn search_key(slice: &[Self], key: &BK) -> Result where BK: Ord + ?Sized, Self::Key: Borrow, { linear_search_by(slice, |value| Self::Key::borrow(&value.0).cmp(key)) } fn search_value(slice: &[Self], key: &Self) -> Result { linear_search_by(slice, |value| value.0.cmp(&key.0)) } } def_pool!(OrdMapPool, Node<(K, V)>); /// An ordered map. /// /// An immutable ordered map implemented as a B-tree. /// /// Most operations on this type of map are O(log n). A /// [`HashMap`][hashmap::HashMap] is usually a better choice for /// performance, but the `OrdMap` has the advantage of only requiring /// an [`Ord`][std::cmp::Ord] constraint on the key, and of being /// ordered, so that keys always come out from lowest to highest, /// where a [`HashMap`][hashmap::HashMap] has no guaranteed ordering. /// /// [hashmap::HashMap]: ../hashmap/struct.HashMap.html /// [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html pub struct OrdMap { size: usize, pool: OrdMapPool, root: PoolRef>, } impl OrdMap { /// Construct an empty map. #[must_use] pub fn new() -> Self { let pool = OrdMapPool::default(); let root = PoolRef::default(&pool.0); OrdMap { size: 0, pool, root, } } /// Construct an empty map using a specific memory pool. #[cfg(feature = "pool")] #[must_use] pub fn with_pool(pool: &OrdMapPool) -> Self { let root = PoolRef::default(&pool.0); OrdMap { size: 0, pool: pool.clone(), root, } } /// Construct a map with a single mapping. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map = OrdMap::unit(123, "onetwothree"); /// assert_eq!( /// map.get(&123), /// Some(&"onetwothree") /// ); /// ``` #[inline] #[must_use] pub fn unit(key: K, value: V) -> Self { let pool = OrdMapPool::default(); let root = PoolRef::new(&pool.0, Node::unit((key, value))); OrdMap { size: 1, pool, root, } } /// Test whether a map is empty. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// assert!( /// !ordmap!{1 => 2}.is_empty() /// ); /// assert!( /// OrdMap::::new().is_empty() /// ); /// ``` #[inline] #[must_use] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Test whether two maps refer to the same content in memory. /// /// This is true if the two sides are references to the same map, /// or if the two maps refer to the same root node. /// /// This would return true if you're comparing a map to itself, or /// if you're comparing a map to a fresh clone of itself. /// /// Time: O(1) pub fn ptr_eq(&self, other: &Self) -> bool { std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root) } /// Get the size of a map. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// assert_eq!(3, ordmap!{ /// 1 => 11, /// 2 => 22, /// 3 => 33 /// }.len()); /// ``` #[inline] #[must_use] pub fn len(&self) -> usize { self.size } /// Get a reference to the memory pool used by this map. /// /// Note that if you didn't specifically construct it with a pool, you'll /// get back a reference to a pool of size 0. #[cfg(feature = "pool")] pub fn pool(&self) -> &OrdMapPool { &self.pool } /// Discard all elements from the map. /// /// This leaves you with an empty map, and all elements that /// were previously inside it are dropped. /// /// Time: O(n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::OrdMap; /// let mut map = ordmap![1=>1, 2=>2, 3=>3]; /// map.clear(); /// assert!(map.is_empty()); /// ``` pub fn clear(&mut self) { if !self.is_empty() { self.root = PoolRef::default(&self.pool.0); self.size = 0; } } } impl OrdMap where K: Ord, { /// Get the largest key in a map, along with its value. If the map /// is empty, return `None`. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// assert_eq!(Some(&(3, 33)), ordmap!{ /// 1 => 11, /// 2 => 22, /// 3 => 33 /// }.get_max()); /// ``` #[must_use] pub fn get_max(&self) -> Option<&(K, V)> { self.root.max() } /// Get the smallest key in a map, along with its value. If the /// map is empty, return `None`. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// assert_eq!(Some(&(1, 11)), ordmap!{ /// 1 => 11, /// 2 => 22, /// 3 => 33 /// }.get_min()); /// ``` #[must_use] pub fn get_min(&self) -> Option<&(K, V)> { self.root.min() } /// Get an iterator over the key/value pairs of a map. #[must_use] pub fn iter(&self) -> Iter<'_, K, V> { Iter { it: RangedIter::new(&self.root, self.size, ..), } } /// Create an iterator over a range of key/value pairs. #[must_use] pub fn range(&self, range: R) -> Iter<'_, K, V> where R: RangeBounds, K: Borrow, BK: Ord + ?Sized, { Iter { it: RangedIter::new(&self.root, self.size, range), } } /// Get an iterator over a map's keys. #[must_use] pub fn keys(&self) -> Keys<'_, K, V> { Keys { it: self.iter() } } /// Get an iterator over a map's values. #[must_use] pub fn values(&self) -> Values<'_, K, V> { Values { it: self.iter() } } /// Get an iterator over the differences between this map and /// another, i.e. the set of entries to add, update, or remove to /// this map in order to make it equal to the other map. /// /// This function will avoid visiting nodes which are shared /// between the two maps, meaning that even very large maps can be /// compared quickly if most of their structure is shared. /// /// Time: O(n) (where n is the number of unique elements across /// the two maps, minus the number of elements belonging to nodes /// shared between them) #[must_use] pub fn diff<'a>(&'a self, other: &'a Self) -> DiffIter<'a, K, V> { DiffIter { it: NodeDiffIter::new(&self.root, &other.root), } } /// Get the value for a key from a map. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map = ordmap!{123 => "lol"}; /// assert_eq!( /// map.get(&123), /// Some(&"lol") /// ); /// ``` #[must_use] pub fn get(&self, key: &BK) -> Option<&V> where BK: Ord + ?Sized, K: Borrow, { self.root.lookup(key).map(|(_, v)| v) } /// Get the key/value pair for a key from a map. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map = ordmap!{123 => "lol"}; /// assert_eq!( /// map.get_key_value(&123), /// Some((&123, &"lol")) /// ); /// ``` #[must_use] pub fn get_key_value(&self, key: &BK) -> Option<(&K, &V)> where BK: Ord + ?Sized, K: Borrow, { self.root.lookup(key).map(|&(ref k, ref v)| (k, v)) } /// Get the closest smaller entry in a map to a given key /// as a mutable reference. /// /// If the map contains the given key, this is returned. /// Otherwise, the closest key in the map smaller than the /// given value is returned. If the smallest key in the map /// is larger than the given key, `None` is returned. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::OrdMap; /// let map = ordmap![1 => 1, 3 => 3, 5 => 5]; /// assert_eq!(Some((&3, &3)), map.get_prev(&4)); /// ``` #[must_use] pub fn get_prev(&self, key: &BK) -> Option<(&K, &V)> where BK: Ord + ?Sized, K: Borrow, { self.root.lookup_prev(key).map(|(k, v)| (k, v)) } /// Get the closest larger entry in a map to a given key /// as a mutable reference. /// /// If the set contains the given value, this is returned. /// Otherwise, the closest value in the set larger than the /// given value is returned. If the largest value in the set /// is smaller than the given value, `None` is returned. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::OrdMap; /// let map = ordmap![1 => 1, 3 => 3, 5 => 5]; /// assert_eq!(Some((&5, &5)), map.get_next(&4)); /// ``` #[must_use] pub fn get_next(&self, key: &BK) -> Option<(&K, &V)> where BK: Ord + ?Sized, K: Borrow, { self.root.lookup_next(key).map(|(k, v)| (k, v)) } /// Test for the presence of a key in a map. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map = ordmap!{123 => "lol"}; /// assert!( /// map.contains_key(&123) /// ); /// assert!( /// !map.contains_key(&321) /// ); /// ``` #[must_use] pub fn contains_key(&self, k: &BK) -> bool where BK: Ord + ?Sized, K: Borrow, { self.get(k).is_some() } /// Test whether a map is a submap of another map, meaning that /// all keys in our map must also be in the other map, with the /// same values. /// /// Use the provided function to decide whether values are equal. /// /// Time: O(n log n) #[must_use] pub fn is_submap_by(&self, other: RM, mut cmp: F) -> bool where F: FnMut(&V, &B) -> bool, RM: Borrow>, { self.iter() .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false)) } /// Test whether a map is a proper submap of another map, meaning /// that all keys in our map must also be in the other map, with /// the same values. To be a proper submap, ours must also contain /// fewer keys than the other map. /// /// Use the provided function to decide whether values are equal. /// /// Time: O(n log n) #[must_use] pub fn is_proper_submap_by(&self, other: RM, cmp: F) -> bool where F: FnMut(&V, &B) -> bool, RM: Borrow>, { self.len() != other.borrow().len() && self.is_submap_by(other, cmp) } /// Test whether a map is a submap of another map, meaning that /// all keys in our map must also be in the other map, with the /// same values. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 2 => 2}; /// let map2 = ordmap!{1 => 1, 2 => 2, 3 => 3}; /// assert!(map1.is_submap(map2)); /// ``` #[must_use] pub fn is_submap(&self, other: RM) -> bool where V: PartialEq, RM: Borrow, { self.is_submap_by(other.borrow(), PartialEq::eq) } /// Test whether a map is a proper submap of another map, meaning /// that all keys in our map must also be in the other map, with /// the same values. To be a proper submap, ours must also contain /// fewer keys than the other map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 2 => 2}; /// let map2 = ordmap!{1 => 1, 2 => 2, 3 => 3}; /// assert!(map1.is_proper_submap(map2)); /// /// let map3 = ordmap!{1 => 1, 2 => 2}; /// let map4 = ordmap!{1 => 1, 2 => 2}; /// assert!(!map3.is_proper_submap(map4)); /// ``` #[must_use] pub fn is_proper_submap(&self, other: RM) -> bool where V: PartialEq, RM: Borrow, { self.is_proper_submap_by(other.borrow(), PartialEq::eq) } } impl OrdMap where K: Ord + Clone, V: Clone, { /// Get a mutable reference to the value for a key from a map. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let mut map = ordmap!{123 => "lol"}; /// if let Some(value) = map.get_mut(&123) { /// *value = "omg"; /// } /// assert_eq!( /// map.get(&123), /// Some(&"omg") /// ); /// ``` #[must_use] pub fn get_mut(&mut self, key: &BK) -> Option<&mut V> where BK: Ord + ?Sized, K: Borrow, { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); root.lookup_mut(&self.pool.0, key).map(|(_, v)| v) } /// Get the closest smaller entry in a map to a given key /// as a mutable reference. /// /// If the map contains the given key, this is returned. /// Otherwise, the closest key in the map smaller than the /// given value is returned. If the smallest key in the map /// is larger than the given key, `None` is returned. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::OrdMap; /// let mut map = ordmap![1 => 1, 3 => 3, 5 => 5]; /// if let Some((key, value)) = map.get_prev_mut(&4) { /// *value = 4; /// } /// assert_eq!(ordmap![1 => 1, 3 => 4, 5 => 5], map); /// ``` #[must_use] pub fn get_prev_mut(&mut self, key: &BK) -> Option<(&K, &mut V)> where BK: Ord + ?Sized, K: Borrow, { let pool = &self.pool.0; PoolRef::make_mut(pool, &mut self.root) .lookup_prev_mut(pool, key) .map(|(ref k, ref mut v)| (k, v)) } /// Get the closest larger entry in a map to a given key /// as a mutable reference. /// /// If the set contains the given value, this is returned. /// Otherwise, the closest value in the set larger than the /// given value is returned. If the largest value in the set /// is smaller than the given value, `None` is returned. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::OrdMap; /// let mut map = ordmap![1 => 1, 3 => 3, 5 => 5]; /// if let Some((key, value)) = map.get_next_mut(&4) { /// *value = 4; /// } /// assert_eq!(ordmap![1 => 1, 3 => 3, 5 => 4], map); /// ``` #[must_use] pub fn get_next_mut(&mut self, key: &BK) -> Option<(&K, &mut V)> where BK: Ord + ?Sized, K: Borrow, { let pool = &self.pool.0; PoolRef::make_mut(pool, &mut self.root) .lookup_next_mut(pool, key) .map(|(ref k, ref mut v)| (k, v)) } /// Insert a key/value mapping into a map. /// /// This is a copy-on-write operation, so that the parts of the /// map's structure which are shared with other maps will be /// safely copied before mutating. /// /// If the map already has a mapping for the given key, the /// previous value is overwritten. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let mut map = ordmap!{}; /// map.insert(123, "123"); /// map.insert(456, "456"); /// assert_eq!( /// map, /// ordmap!{123 => "123", 456 => "456"} /// ); /// ``` /// /// [insert]: #method.insert #[inline] pub fn insert(&mut self, key: K, value: V) -> Option { let new_root = { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); match root.insert(&self.pool.0, (key, value)) { Insert::Replaced((_, old_value)) => return Some(old_value), Insert::Added => { self.size += 1; return None; } Insert::Split(left, median, right) => PoolRef::new( &self.pool.0, Node::new_from_split(&self.pool.0, left, median, right), ), } }; self.size += 1; self.root = new_root; None } /// Remove a key/value mapping from a map if it exists. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let mut map = ordmap!{123 => "123", 456 => "456"}; /// map.remove(&123); /// map.remove(&456); /// assert!(map.is_empty()); /// ``` /// /// [remove]: #method.remove #[inline] pub fn remove(&mut self, k: &BK) -> Option where BK: Ord + ?Sized, K: Borrow, { self.remove_with_key(k).map(|(_, v)| v) } /// Remove a key/value pair from a map, if it exists, and return /// the removed key and value. /// /// Time: O(log n) pub fn remove_with_key(&mut self, k: &BK) -> Option<(K, V)> where BK: Ord + ?Sized, K: Borrow, { let (new_root, removed_value) = { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); match root.remove(&self.pool.0, k) { Remove::NoChange => return None, Remove::Removed(pair) => { self.size -= 1; return Some(pair); } Remove::Update(pair, root) => (PoolRef::new(&self.pool.0, root), Some(pair)), } }; self.size -= 1; self.root = new_root; removed_value } /// Construct a new map by inserting a key/value mapping into a /// map. /// /// If the map already has a mapping for the given key, the /// previous value is overwritten. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map = ordmap!{}; /// assert_eq!( /// map.update(123, "123"), /// ordmap!{123 => "123"} /// ); /// ``` #[must_use] pub fn update(&self, key: K, value: V) -> Self { let mut out = self.clone(); out.insert(key, value); out } /// Construct a new map by inserting a key/value mapping into a /// map. /// /// If the map already has a mapping for the given key, we call /// the provided function with the old value and the new value, /// and insert the result as the new value. /// /// Time: O(log n) #[must_use] pub fn update_with(self, k: K, v: V, f: F) -> Self where F: FnOnce(V, V) -> V, { self.update_with_key(k, v, |_, v1, v2| f(v1, v2)) } /// Construct a new map by inserting a key/value mapping into a /// map. /// /// If the map already has a mapping for the given key, we call /// the provided function with the key, the old value and the new /// value, and insert the result as the new value. /// /// Time: O(log n) #[must_use] pub fn update_with_key(self, k: K, v: V, f: F) -> Self where F: FnOnce(&K, V, V) -> V, { match self.extract_with_key(&k) { None => self.update(k, v), Some((_, v2, m)) => { let out_v = f(&k, v2, v); m.update(k, out_v) } } } /// Construct a new map by inserting a key/value mapping into a /// map, returning the old value for the key as well as the new /// map. /// /// If the map already has a mapping for the given key, we call /// the provided function with the key, the old value and the new /// value, and insert the result as the new value. /// /// Time: O(log n) #[must_use] pub fn update_lookup_with_key(self, k: K, v: V, f: F) -> (Option, Self) where F: FnOnce(&K, &V, V) -> V, { match self.extract_with_key(&k) { None => (None, self.update(k, v)), Some((_, v2, m)) => { let out_v = f(&k, &v2, v); (Some(v2), m.update(k, out_v)) } } } /// Update the value for a given key by calling a function with /// the current value and overwriting it with the function's /// return value. /// /// The function gets an [`Option`][std::option::Option] and /// returns the same, so that it can decide to delete a mapping /// instead of updating the value, and decide what to do if the /// key isn't in the map. /// /// Time: O(log n) /// /// [std::option::Option]: https://doc.rust-lang.org/std/option/enum.Option.html #[must_use] pub fn alter(&self, f: F, k: K) -> Self where F: FnOnce(Option) -> Option, { let pop = self.extract_with_key(&k); match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) { (None, None) => self.clone(), (Some(v), None) => self.update(k, v), (None, Some((_, _, m))) => m, (Some(v), Some((_, _, m))) => m.update(k, v), } } /// Remove a key/value pair from a map, if it exists. /// /// Time: O(log n) #[must_use] pub fn without(&self, k: &BK) -> Self where BK: Ord + ?Sized, K: Borrow, { self.extract(k) .map(|(_, m)| m) .unwrap_or_else(|| self.clone()) } /// Remove a key/value pair from a map, if it exists, and return /// the removed value as well as the updated list. /// /// Time: O(log n) #[must_use] pub fn extract(&self, k: &BK) -> Option<(V, Self)> where BK: Ord + ?Sized, K: Borrow, { self.extract_with_key(k).map(|(_, v, m)| (v, m)) } /// Remove a key/value pair from a map, if it exists, and return /// the removed key and value as well as the updated list. /// /// Time: O(log n) #[must_use] pub fn extract_with_key(&self, k: &BK) -> Option<(K, V, Self)> where BK: Ord + ?Sized, K: Borrow, { let mut out = self.clone(); let result = out.remove_with_key(k); result.map(|(k, v)| (k, v, out)) } /// Construct the union of two maps, keeping the values in the /// current map when keys exist in both maps. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 3}; /// let map2 = ordmap!{2 => 2, 3 => 4}; /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 3}; /// assert_eq!(expected, map1.union(map2)); /// ``` #[inline] #[must_use] pub fn union(mut self, other: Self) -> Self { for (k, v) in other { self.entry(k).or_insert(v); } self } /// Construct the union of two maps, using a function to decide /// what to do with the value when a key is in both maps. /// /// The function is called when a value exists in both maps, and /// receives the value from the current map as its first argument, /// and the value from the other map as the second. It should /// return the value to be inserted in the resulting map. /// /// Time: O(n log n) #[inline] #[must_use] pub fn union_with(self, other: Self, mut f: F) -> Self where F: FnMut(V, V) -> V, { self.union_with_key(other, |_, v1, v2| f(v1, v2)) } /// Construct the union of two maps, using a function to decide /// what to do with the value when a key is in both maps. /// /// The function is called when a value exists in both maps, and /// receives a reference to the key as its first argument, the /// value from the current map as the second argument, and the /// value from the other map as the third argument. It should /// return the value to be inserted in the resulting map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 4}; /// let map2 = ordmap!{2 => 2, 3 => 5}; /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 9}; /// assert_eq!(expected, map1.union_with_key( /// map2, /// |key, left, right| left + right /// )); /// ``` #[must_use] pub fn union_with_key(mut self, other: Self, mut f: F) -> Self where F: FnMut(&K, V, V) -> V, { for (key, right_value) in other { match self.remove(&key) { None => { self.insert(key, right_value); } Some(left_value) => { let final_value = f(&key, left_value, right_value); self.insert(key, final_value); } } } self } /// Construct the union of a sequence of maps, selecting the value /// of the leftmost when a key appears in more than one map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 3}; /// let map2 = ordmap!{2 => 2}; /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 3}; /// assert_eq!(expected, OrdMap::unions(vec![map1, map2])); /// ``` #[must_use] pub fn unions(i: I) -> Self where I: IntoIterator, { i.into_iter().fold(Self::default(), Self::union) } /// Construct the union of a sequence of maps, using a function to /// decide what to do with the value when a key is in more than /// one map. /// /// The function is called when a value exists in multiple maps, /// and receives the value from the current map as its first /// argument, and the value from the next map as the second. It /// should return the value to be inserted in the resulting map. /// /// Time: O(n log n) #[must_use] pub fn unions_with(i: I, f: F) -> Self where I: IntoIterator, F: Fn(V, V) -> V, { i.into_iter() .fold(Self::default(), |a, b| a.union_with(b, &f)) } /// Construct the union of a sequence of maps, using a function to /// decide what to do with the value when a key is in more than /// one map. /// /// The function is called when a value exists in multiple maps, /// and receives a reference to the key as its first argument, the /// value from the current map as the second argument, and the /// value from the next map as the third argument. It should /// return the value to be inserted in the resulting map. /// /// Time: O(n log n) #[must_use] pub fn unions_with_key(i: I, f: F) -> Self where I: IntoIterator, F: Fn(&K, V, V) -> V, { i.into_iter() .fold(Self::default(), |a, b| a.union_with_key(b, &f)) } /// Construct the symmetric difference between two maps by discarding keys /// which occur in both maps. /// /// This is an alias for the /// [`symmetric_difference`][symmetric_difference] method. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 4}; /// let map2 = ordmap!{2 => 2, 3 => 5}; /// let expected = ordmap!{1 => 1, 2 => 2}; /// assert_eq!(expected, map1.difference(map2)); /// ``` /// /// [symmetric_difference]: #method.symmetric_difference #[inline] #[must_use] pub fn difference(self, other: Self) -> Self { self.symmetric_difference(other) } /// Construct the symmetric difference between two maps by discarding keys /// which occur in both maps. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 4}; /// let map2 = ordmap!{2 => 2, 3 => 5}; /// let expected = ordmap!{1 => 1, 2 => 2}; /// assert_eq!(expected, map1.symmetric_difference(map2)); /// ``` #[inline] #[must_use] pub fn symmetric_difference(self, other: Self) -> Self { self.symmetric_difference_with_key(other, |_, _, _| None) } /// Construct the symmetric difference between two maps by using a function /// to decide what to do if a key occurs in both. /// /// This is an alias for the /// [`symmetric_difference_with`][symmetric_difference_with] method. /// /// Time: O(n log n) /// /// [symmetric_difference_with]: #method.symmetric_difference_with #[inline] #[must_use] pub fn difference_with(self, other: Self, f: F) -> Self where F: FnMut(V, V) -> Option, { self.symmetric_difference_with(other, f) } /// Construct the symmetric difference between two maps by using a function /// to decide what to do if a key occurs in both. /// /// Time: O(n log n) #[inline] #[must_use] pub fn symmetric_difference_with(self, other: Self, mut f: F) -> Self where F: FnMut(V, V) -> Option, { self.symmetric_difference_with_key(other, |_, a, b| f(a, b)) } /// Construct the symmetric difference between two maps by using a function /// to decide what to do if a key occurs in both. The function /// receives the key as well as both values. /// /// This is an alias for the /// [`symmetric_difference_with_key`][symmetric_difference_with_key] /// method. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 4}; /// let map2 = ordmap!{2 => 2, 3 => 5}; /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 9}; /// assert_eq!(expected, map1.difference_with_key( /// map2, /// |key, left, right| Some(left + right) /// )); /// ``` /// [symmetric_difference_with_key]: #method.symmetric_difference_with_key #[must_use] pub fn difference_with_key(self, other: Self, f: F) -> Self where F: FnMut(&K, V, V) -> Option, { self.symmetric_difference_with_key(other, f) } /// Construct the symmetric difference between two maps by using a function /// to decide what to do if a key occurs in both. The function /// receives the key as well as both values. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 4}; /// let map2 = ordmap!{2 => 2, 3 => 5}; /// let expected = ordmap!{1 => 1, 2 => 2, 3 => 9}; /// assert_eq!(expected, map1.symmetric_difference_with_key( /// map2, /// |key, left, right| Some(left + right) /// )); /// ``` #[must_use] pub fn symmetric_difference_with_key(mut self, other: Self, mut f: F) -> Self where F: FnMut(&K, V, V) -> Option, { let mut out = Self::default(); for (key, right_value) in other { match self.remove(&key) { None => { out.insert(key, right_value); } Some(left_value) => { if let Some(final_value) = f(&key, left_value, right_value) { out.insert(key, final_value); } } } } out.union(self) } /// Construct the relative complement between two maps by discarding keys /// which occur in `other`. /// /// Time: O(m log n) where m is the size of the other map /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 3 => 4}; /// let map2 = ordmap!{2 => 2, 3 => 5}; /// let expected = ordmap!{1 => 1}; /// assert_eq!(expected, map1.relative_complement(map2)); /// ``` #[inline] #[must_use] pub fn relative_complement(mut self, other: Self) -> Self { for (key, _) in other { let _ = self.remove(&key); } self } /// Construct the intersection of two maps, keeping the values /// from the current map. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 2 => 2}; /// let map2 = ordmap!{2 => 3, 3 => 4}; /// let expected = ordmap!{2 => 2}; /// assert_eq!(expected, map1.intersection(map2)); /// ``` #[inline] #[must_use] pub fn intersection(self, other: Self) -> Self { self.intersection_with_key(other, |_, v, _| v) } /// Construct the intersection of two maps, calling a function /// with both values for each key and using the result as the /// value for the key. /// /// Time: O(n log n) #[inline] #[must_use] pub fn intersection_with(self, other: OrdMap, mut f: F) -> OrdMap where B: Clone, C: Clone, F: FnMut(V, B) -> C, { self.intersection_with_key(other, |_, v1, v2| f(v1, v2)) } /// Construct the intersection of two maps, calling a function /// with the key and both values for each key and using the result /// as the value for the key. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordmap::OrdMap; /// let map1 = ordmap!{1 => 1, 2 => 2}; /// let map2 = ordmap!{2 => 3, 3 => 4}; /// let expected = ordmap!{2 => 5}; /// assert_eq!(expected, map1.intersection_with_key( /// map2, /// |key, left, right| left + right /// )); /// ``` #[must_use] pub fn intersection_with_key(mut self, other: OrdMap, mut f: F) -> OrdMap where B: Clone, C: Clone, F: FnMut(&K, V, B) -> C, { let mut out = OrdMap::::default(); for (key, right_value) in other { match self.remove(&key) { None => (), Some(left_value) => { let result = f(&key, left_value, right_value); out.insert(key, result); } } } out } /// Split a map into two, with the left hand map containing keys /// which are smaller than `split`, and the right hand map /// containing keys which are larger than `split`. /// /// The `split` mapping is discarded. #[must_use] pub fn split(&self, split: &BK) -> (Self, Self) where BK: Ord + ?Sized, K: Borrow, { let (l, _, r) = self.split_lookup(split); (l, r) } /// Split a map into two, with the left hand map containing keys /// which are smaller than `split`, and the right hand map /// containing keys which are larger than `split`. /// /// Returns both the two maps and the value of `split`. #[must_use] pub fn split_lookup(&self, split: &BK) -> (Self, Option, Self) where BK: Ord + ?Sized, K: Borrow, { // TODO this is atrociously slow, got to be a better way self.iter() .fold((ordmap![], None, ordmap![]), |(l, m, r), (k, v)| { match k.borrow().cmp(split) { Ordering::Less => (l.update(k.clone(), v.clone()), m, r), Ordering::Equal => (l, Some(v.clone()), r), Ordering::Greater => (l, m, r.update(k.clone(), v.clone())), } }) } /// Construct a map with only the `n` smallest keys from a given /// map. #[must_use] pub fn take(&self, n: usize) -> Self { self.iter() .take(n) .map(|(k, v)| (k.clone(), v.clone())) .collect() } /// Construct a map with the `n` smallest keys removed from a /// given map. #[must_use] pub fn skip(&self, n: usize) -> Self { self.iter() .skip(n) .map(|(k, v)| (k.clone(), v.clone())) .collect() } /// Remove the smallest key from a map, and return its value as /// well as the updated map. #[must_use] pub fn without_min(&self) -> (Option, Self) { let (pop, next) = self.without_min_with_key(); (pop.map(|(_, v)| v), next) } /// Remove the smallest key from a map, and return that key, its /// value as well as the updated map. #[must_use] pub fn without_min_with_key(&self) -> (Option<(K, V)>, Self) { match self.get_min() { None => (None, self.clone()), Some((k, _)) => { let (key, value, next) = self.extract_with_key(k).unwrap(); (Some((key, value)), next) } } } /// Remove the largest key from a map, and return its value as /// well as the updated map. #[must_use] pub fn without_max(&self) -> (Option, Self) { let (pop, next) = self.without_max_with_key(); (pop.map(|(_, v)| v), next) } /// Remove the largest key from a map, and return that key, its /// value as well as the updated map. #[must_use] pub fn without_max_with_key(&self) -> (Option<(K, V)>, Self) { match self.get_max() { None => (None, self.clone()), Some((k, _)) => { let (key, value, next) = self.extract_with_key(k).unwrap(); (Some((key, value)), next) } } } /// Get the [`Entry`][Entry] for a key in the map for in-place manipulation. /// /// Time: O(log n) /// /// [Entry]: enum.Entry.html #[must_use] pub fn entry(&mut self, key: K) -> Entry<'_, K, V> { if self.contains_key(&key) { Entry::Occupied(OccupiedEntry { map: self, key }) } else { Entry::Vacant(VacantEntry { map: self, key }) } } } // Entries /// A handle for a key and its associated value. pub enum Entry<'a, K, V> where K: Ord + Clone, V: Clone, { /// An entry which exists in the map. Occupied(OccupiedEntry<'a, K, V>), /// An entry which doesn't exist in the map. Vacant(VacantEntry<'a, K, V>), } impl<'a, K, V> Entry<'a, K, V> where K: Ord + Clone, V: Clone, { /// Insert the default value provided if there was no value /// already, and return a mutable reference to the value. pub fn or_insert(self, default: V) -> &'a mut V { self.or_insert_with(|| default) } /// Insert the default value from the provided function if there /// was no value already, and return a mutable reference to the /// value. pub fn or_insert_with(self, default: F) -> &'a mut V where F: FnOnce() -> V, { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default()), } } /// Insert a default value if there was no value already, and /// return a mutable reference to the value. pub fn or_default(self) -> &'a mut V where V: Default, { self.or_insert_with(Default::default) } /// Get the key for this entry. #[must_use] pub fn key(&self) -> &K { match self { Entry::Occupied(entry) => entry.key(), Entry::Vacant(entry) => entry.key(), } } /// Call the provided function to modify the value if the value /// exists. pub fn and_modify(mut self, f: F) -> Self where F: FnOnce(&mut V), { match &mut self { Entry::Occupied(ref mut entry) => f(entry.get_mut()), Entry::Vacant(_) => (), } self } } /// An entry for a mapping that already exists in the map. pub struct OccupiedEntry<'a, K, V> where K: Ord + Clone, V: Clone, { map: &'a mut OrdMap, key: K, } impl<'a, K, V> OccupiedEntry<'a, K, V> where K: 'a + Ord + Clone, V: 'a + Clone, { /// Get the key for this entry. #[must_use] pub fn key(&self) -> &K { &self.key } /// Remove this entry from the map and return the removed mapping. pub fn remove_entry(self) -> (K, V) { self.map .remove_with_key(&self.key) .expect("ordmap::OccupiedEntry::remove_entry: key has vanished!") } /// Get the current value. #[must_use] pub fn get(&self) -> &V { self.map.get(&self.key).unwrap() } /// Get a mutable reference to the current value. #[must_use] pub fn get_mut(&mut self) -> &mut V { self.map.get_mut(&self.key).unwrap() } /// Convert this entry into a mutable reference. #[must_use] pub fn into_mut(self) -> &'a mut V { self.map.get_mut(&self.key).unwrap() } /// Overwrite the current value. pub fn insert(&mut self, value: V) -> V { mem::replace(self.get_mut(), value) } /// Remove this entry from the map and return the removed value. pub fn remove(self) -> V { self.remove_entry().1 } } /// An entry for a mapping that does not already exist in the map. pub struct VacantEntry<'a, K, V> where K: Ord + Clone, V: Clone, { map: &'a mut OrdMap, key: K, } impl<'a, K, V> VacantEntry<'a, K, V> where K: 'a + Ord + Clone, V: 'a + Clone, { /// Get the key for this entry. #[must_use] pub fn key(&self) -> &K { &self.key } /// Convert this entry into its key. #[must_use] pub fn into_key(self) -> K { self.key } /// Insert a value into this entry. pub fn insert(self, value: V) -> &'a mut V { self.map.insert(self.key.clone(), value); // TODO insert_mut ought to return this reference self.map.get_mut(&self.key).unwrap() } } // Core traits impl Clone for OrdMap { /// Clone a map. /// /// Time: O(1) #[inline] fn clone(&self) -> Self { OrdMap { size: self.size, pool: self.pool.clone(), root: self.root.clone(), } } } #[cfg(not(has_specialisation))] impl PartialEq for OrdMap where K: Ord + PartialEq, V: PartialEq, { fn eq(&self, other: &Self) -> bool { self.len() == other.len() && self.diff(other).next().is_none() } } #[cfg(has_specialisation)] impl PartialEq for OrdMap where K: Ord + PartialEq, V: PartialEq, { default fn eq(&self, other: &Self) -> bool { self.len() == other.len() && self.diff(other).next().is_none() } } #[cfg(has_specialisation)] impl PartialEq for OrdMap where K: Ord + Eq, V: Eq, { fn eq(&self, other: &Self) -> bool { PoolRef::ptr_eq(&self.root, &other.root) || (self.len() == other.len() && self.diff(other).next().is_none()) } } impl Eq for OrdMap {} impl PartialOrd for OrdMap where K: Ord, V: PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option { self.iter().partial_cmp(other.iter()) } } impl Ord for OrdMap where K: Ord, V: Ord, { fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other.iter()) } } impl Hash for OrdMap where K: Ord + Hash, V: Hash, { fn hash(&self, state: &mut H) where H: Hasher, { for i in self.iter() { i.hash(state); } } } impl Default for OrdMap { fn default() -> Self { Self::new() } } impl<'a, K, V> Add for &'a OrdMap where K: Ord + Clone, V: Clone, { type Output = OrdMap; fn add(self, other: Self) -> Self::Output { self.clone().union(other.clone()) } } impl Add for OrdMap where K: Ord + Clone, V: Clone, { type Output = OrdMap; fn add(self, other: Self) -> Self::Output { self.union(other) } } impl Sum for OrdMap where K: Ord + Clone, V: Clone, { fn sum(it: I) -> Self where I: Iterator, { it.fold(Self::default(), |a, b| a + b) } } impl Extend<(RK, RV)> for OrdMap where K: Ord + Clone + From, V: Clone + From, { fn extend(&mut self, iter: I) where I: IntoIterator, { for (key, value) in iter { self.insert(From::from(key), From::from(value)); } } } impl<'a, BK, K, V> Index<&'a BK> for OrdMap where BK: Ord + ?Sized, K: Ord + Borrow, { type Output = V; fn index(&self, key: &BK) -> &Self::Output { match self.root.lookup(key) { None => panic!("OrdMap::index: invalid key"), Some(&(_, ref value)) => value, } } } impl<'a, BK, K, V> IndexMut<&'a BK> for OrdMap where BK: Ord + ?Sized, K: Ord + Clone + Borrow, V: Clone, { fn index_mut(&mut self, key: &BK) -> &mut Self::Output { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); match root.lookup_mut(&self.pool.0, key) { None => panic!("OrdMap::index: invalid key"), Some(&mut (_, ref mut value)) => value, } } } impl Debug for OrdMap where K: Ord + Debug, V: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let mut d = f.debug_map(); for (k, v) in self.iter() { d.entry(k, v); } d.finish() } } // Iterators /// An iterator over the key/value pairs of a map. pub struct Iter<'a, K, V> { it: RangedIter<'a, (K, V)>, } impl<'a, K, V> Iterator for Iter<'a, K, V> where (K, V): 'a + BTreeValue, { type Item = (&'a K, &'a V); fn next(&mut self) -> Option { self.it.next().map(|(k, v)| (k, v)) } fn size_hint(&self) -> (usize, Option) { (self.it.remaining, Some(self.it.remaining)) } } impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> where (K, V): 'a + BTreeValue, { fn next_back(&mut self) -> Option { self.it.next_back().map(|(k, v)| (k, v)) } } impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> where (K, V): 'a + BTreeValue {} /// An iterator over the differences between two maps. pub struct DiffIter<'a, K, V> { it: NodeDiffIter<'a, (K, V)>, } /// A description of a difference between two ordered maps. #[derive(PartialEq, Eq, Debug)] pub enum DiffItem<'a, K, V> { /// This value has been added to the new map. Add(&'a K, &'a V), /// This value has been changed between the two maps. Update { /// The old value. old: (&'a K, &'a V), /// The new value. new: (&'a K, &'a V), }, /// This value has been removed from the new map. Remove(&'a K, &'a V), } impl<'a, K, V> Iterator for DiffIter<'a, K, V> where (K, V): 'a + BTreeValue + PartialEq, { type Item = DiffItem<'a, K, V>; fn next(&mut self) -> Option { self.it.next().map(|item| match item { NodeDiffItem::Add((k, v)) => DiffItem::Add(k, v), NodeDiffItem::Update { old: (oldk, oldv), new: (newk, newv), } => DiffItem::Update { old: (oldk, oldv), new: (newk, newv), }, NodeDiffItem::Remove((k, v)) => DiffItem::Remove(k, v), }) } } /// An iterator ove the keys of a map. pub struct Keys<'a, K, V> { it: Iter<'a, K, V>, } impl<'a, K, V> Iterator for Keys<'a, K, V> where K: 'a + Ord, V: 'a, { type Item = &'a K; fn next(&mut self) -> Option { self.it.next().map(|(k, _)| k) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> where K: 'a + Ord, V: 'a, { fn next_back(&mut self) -> Option { match self.it.next_back() { None => None, Some((k, _)) => Some(k), } } } impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> where K: 'a + Ord, V: 'a, { } /// An iterator over the values of a map. pub struct Values<'a, K, V> { it: Iter<'a, K, V>, } impl<'a, K, V> Iterator for Values<'a, K, V> where K: 'a + Ord, V: 'a, { type Item = &'a V; fn next(&mut self) -> Option { self.it.next().map(|(_, v)| v) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> where K: 'a + Ord, V: 'a, { fn next_back(&mut self) -> Option { match self.it.next_back() { None => None, Some((_, v)) => Some(v), } } } impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> where K: 'a + Ord, V: 'a, { } impl FromIterator<(RK, RV)> for OrdMap where K: Ord + Clone + From, V: Clone + From, { fn from_iter(i: T) -> Self where T: IntoIterator, { let mut m = OrdMap::default(); for (k, v) in i { m.insert(From::from(k), From::from(v)); } m } } impl<'a, K, V> IntoIterator for &'a OrdMap where K: Ord, { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl IntoIterator for OrdMap where K: Ord + Clone, V: Clone, { type Item = (K, V); type IntoIter = ConsumingIter<(K, V)>; fn into_iter(self) -> Self::IntoIter { ConsumingIter::new(&self.root, self.size) } } // Conversions impl AsRef> for OrdMap { fn as_ref(&self) -> &Self { self } } impl<'m, 'k, 'v, K, V, OK, OV> From<&'m OrdMap<&'k K, &'v V>> for OrdMap where K: Ord + ToOwned + ?Sized, V: ToOwned + ?Sized, OK: Ord + Clone + Borrow, OV: Clone + Borrow, { fn from(m: &OrdMap<&K, &V>) -> Self { m.iter() .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) .collect() } } impl<'a, K, V, RK, RV, OK, OV> From<&'a [(RK, RV)]> for OrdMap where K: Ord + Clone + From, V: Clone + From, OK: Borrow, OV: Borrow, RK: ToOwned, RV: ToOwned, { fn from(m: &'a [(RK, RV)]) -> OrdMap { m.iter() .map(|&(ref k, ref v)| (k.to_owned(), v.to_owned())) .collect() } } impl From> for OrdMap where K: Ord + Clone + From, V: Clone + From, { fn from(m: Vec<(RK, RV)>) -> OrdMap { m.into_iter().collect() } } impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a Vec<(RK, RV)>> for OrdMap where K: Ord + Clone + From, V: Clone + From, OK: Borrow, OV: Borrow, RK: ToOwned, RV: ToOwned, { fn from(m: &'a Vec<(RK, RV)>) -> OrdMap { m.iter() .map(|&(ref k, ref v)| (k.to_owned(), v.to_owned())) .collect() } } impl From> for OrdMap where K: Ord + Clone + From, V: Clone + From, { fn from(m: collections::HashMap) -> OrdMap { m.into_iter().collect() } } impl<'a, K, V, OK, OV, RK, RV> From<&'a collections::HashMap> for OrdMap where K: Ord + Clone + From, V: Clone + From, OK: Borrow, OV: Borrow, RK: Hash + Eq + ToOwned, RV: ToOwned, { fn from(m: &'a collections::HashMap) -> OrdMap { m.iter() .map(|(k, v)| (k.to_owned(), v.to_owned())) .collect() } } impl From> for OrdMap where K: Ord + Clone + From, V: Clone + From, { fn from(m: collections::BTreeMap) -> OrdMap { m.into_iter().collect() } } impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a collections::BTreeMap> for OrdMap where K: Ord + Clone + From, V: Clone + From, OK: Borrow, OV: Borrow, RK: Ord + ToOwned, RV: ToOwned, { fn from(m: &'a collections::BTreeMap) -> OrdMap { m.iter() .map(|(k, v)| (k.to_owned(), v.to_owned())) .collect() } } impl From> for OrdMap { fn from(m: HashMap) -> Self { m.into_iter().collect() } } impl<'a, K: Ord + Hash + Eq + Clone, V: Clone, S: BuildHasher> From<&'a HashMap> for OrdMap { fn from(m: &'a HashMap) -> Self { m.iter().map(|(k, v)| (k.clone(), v.clone())).collect() } } // Proptest #[cfg(any(test, feature = "proptest"))] #[doc(hidden)] pub mod proptest { #[deprecated( since = "14.3.0", note = "proptest strategies have moved to im::proptest" )] pub use crate::proptest::ord_map; } // Tests #[cfg(test)] mod test { use super::*; use crate::proptest::*; use crate::test::is_sorted; use ::proptest::num::{i16, usize}; use ::proptest::{bool, collection, proptest}; #[test] fn iterates_in_order() { let map = ordmap! { 2 => 22, 1 => 11, 3 => 33, 8 => 88, 9 => 99, 4 => 44, 5 => 55, 7 => 77, 6 => 66 }; let mut it = map.iter(); assert_eq!(it.next(), Some((&1, &11))); assert_eq!(it.next(), Some((&2, &22))); assert_eq!(it.next(), Some((&3, &33))); assert_eq!(it.next(), Some((&4, &44))); assert_eq!(it.next(), Some((&5, &55))); assert_eq!(it.next(), Some((&6, &66))); assert_eq!(it.next(), Some((&7, &77))); assert_eq!(it.next(), Some((&8, &88))); assert_eq!(it.next(), Some((&9, &99))); assert_eq!(it.next(), None); } #[test] fn into_iter() { let map = ordmap! { 2 => 22, 1 => 11, 3 => 33, 8 => 88, 9 => 99, 4 => 44, 5 => 55, 7 => 77, 6 => 66 }; let mut vec = vec![]; for (k, v) in map { assert_eq!(k * 11, v); vec.push(k) } assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]); } #[test] fn deletes_correctly() { let map = ordmap! { 2 => 22, 1 => 11, 3 => 33, 8 => 88, 9 => 99, 4 => 44, 5 => 55, 7 => 77, 6 => 66 }; assert_eq!(map.extract(&11), None); let (popped, less) = map.extract(&5).unwrap(); assert_eq!(popped, 55); let mut it = less.iter(); assert_eq!(it.next(), Some((&1, &11))); assert_eq!(it.next(), Some((&2, &22))); assert_eq!(it.next(), Some((&3, &33))); assert_eq!(it.next(), Some((&4, &44))); assert_eq!(it.next(), Some((&6, &66))); assert_eq!(it.next(), Some((&7, &77))); assert_eq!(it.next(), Some((&8, &88))); assert_eq!(it.next(), Some((&9, &99))); assert_eq!(it.next(), None); } #[test] fn debug_output() { assert_eq!( format!("{:?}", ordmap! { 3 => 4, 5 => 6, 1 => 2 }), "{1: 2, 3: 4, 5: 6}" ); } #[test] fn equality2() { let v1 = "1".to_string(); let v2 = "1".to_string(); assert_eq!(v1, v2); let p1 = Vec::::new(); let p2 = Vec::::new(); assert_eq!(p1, p2); let c1 = OrdMap::unit(v1, p1); let c2 = OrdMap::unit(v2, p2); assert_eq!(c1, c2); } #[test] fn insert_remove_single_mut() { let mut m = OrdMap::new(); m.insert(0, 0); assert_eq!(OrdMap::unit(0, 0), m); m.remove(&0); assert_eq!(OrdMap::new(), m); } #[test] fn double_ended_iterator_1() { let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4}; let mut it = m.iter(); assert_eq!(Some((&1, &1)), it.next()); assert_eq!(Some((&4, &4)), it.next_back()); assert_eq!(Some((&2, &2)), it.next()); assert_eq!(Some((&3, &3)), it.next_back()); assert_eq!(None, it.next()); } #[test] fn double_ended_iterator_2() { let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4}; let mut it = m.iter(); assert_eq!(Some((&1, &1)), it.next()); assert_eq!(Some((&4, &4)), it.next_back()); assert_eq!(Some((&2, &2)), it.next()); assert_eq!(Some((&3, &3)), it.next_back()); assert_eq!(None, it.next_back()); } #[test] fn safe_mutation() { let v1 = OrdMap::from_iter((0..131_072).map(|i| (i, i))); let mut v2 = v1.clone(); v2.insert(131_000, 23); assert_eq!(Some(&23), v2.get(&131_000)); assert_eq!(Some(&131_000), v1.get(&131_000)); } #[test] fn index_operator() { let mut map = ordmap! {1 => 2, 3 => 4, 5 => 6}; assert_eq!(4, map[&3]); map[&3] = 8; assert_eq!(ordmap! {1 => 2, 3 => 8, 5 => 6}, map); } #[test] fn entry_api() { let mut map = ordmap! {"bar" => 5}; map.entry(&"foo").and_modify(|v| *v += 5).or_insert(1); assert_eq!(1, map[&"foo"]); map.entry(&"foo").and_modify(|v| *v += 5).or_insert(1); assert_eq!(6, map[&"foo"]); map.entry(&"bar").and_modify(|v| *v += 5).or_insert(1); assert_eq!(10, map[&"bar"]); assert_eq!( 10, match map.entry(&"bar") { Entry::Occupied(entry) => entry.remove(), _ => panic!(), } ); assert!(!map.contains_key(&"bar")); } #[test] fn match_string_keys_with_string_slices() { let mut map: OrdMap = From::from(ºap! { "foo" => &1, "bar" => &2, "baz" => &3 }); assert_eq!(Some(&1), map.get("foo")); map = map.without("foo"); assert_eq!(Some(3), map.remove("baz")); map["bar"] = 8; assert_eq!(8, map["bar"]); } #[test] fn ranged_iter() { let map: OrdMap = ordmap![1=>2, 2=>3, 3=>4, 4=>5, 5=>6]; let range: Vec<(i32, i32)> = map.range(..).map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range); let range: Vec<(i32, i32)> = map.range(..).rev().map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range); let range: Vec<(i32, i32)> = map.range(2..5).map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range); let range: Vec<(i32, i32)> = map.range(2..5).rev().map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range); let range: Vec<(i32, i32)> = map.range(3..).map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(3, 4), (4, 5), (5, 6)], range); let range: Vec<(i32, i32)> = map.range(3..).rev().map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(5, 6), (4, 5), (3, 4)], range); let range: Vec<(i32, i32)> = map.range(..4).map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range); let range: Vec<(i32, i32)> = map.range(..4).rev().map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range); let range: Vec<(i32, i32)> = map.range(..=3).map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range); let range: Vec<(i32, i32)> = map.range(..=3).rev().map(|(k, v)| (*k, *v)).collect(); assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range); } proptest! { #[test] fn length(ref input in collection::btree_map(i16::ANY, i16::ANY, 0..1000)) { let map: OrdMap = OrdMap::from(input.clone()); input.len() == map.len() } #[test] fn order(ref input in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) { let map: OrdMap = OrdMap::from(input.clone()); is_sorted(map.keys()) } #[test] fn overwrite_values(ref vec in collection::vec((i16::ANY, i16::ANY), 1..1000), index_rand in usize::ANY, new_val in i16::ANY) { let index = vec[index_rand % vec.len()].0; let map1 = OrdMap::from_iter(vec.clone()); let map2 = map1.update(index, new_val); for (k, v) in map2 { if k == index { assert_eq!(v, new_val); } else { match map1.get(&k) { None => panic!("map1 didn't have key {:?}", k), Some(other_v) => { assert_eq!(v, *other_v); } } } } } #[test] fn delete_values(ref vec in collection::vec((usize::ANY, usize::ANY), 1..1000), index_rand in usize::ANY) { let index = vec[index_rand % vec.len()].0; let map1: OrdMap = OrdMap::from_iter(vec.clone()); let map2 = map1.without(&index); assert_eq!(map1.len(), map2.len() + 1); for k in map2.keys() { assert_ne!(*k, index); } } #[test] fn insert_and_delete_values( ref input in ord_map(0usize..64, 0usize..64, 1..1000), ref ops in collection::vec((bool::ANY, usize::ANY, usize::ANY), 1..1000) ) { let mut map = input.clone(); let mut tree: collections::BTreeMap = input.iter().map(|(k, v)| (*k, *v)).collect(); for (ins, key, val) in ops { if *ins { tree.insert(*key, *val); map = map.update(*key, *val) } else { tree.remove(key); map = map.without(key) } } assert!(map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v)))); } #[test] fn proptest_works(ref m in ord_map(0..9999, ".*", 10..100)) { assert!(m.len() < 100); assert!(m.len() >= 10); } #[test] fn insert_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) { let mut map: OrdMap = OrdMap::new(); for (k, v) in m.iter() { map = map.update(*k, *v) } assert_eq!(m.len(), map.len()); } #[test] fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) { let map: OrdMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); assert_eq!(m.len(), map.len()); } #[test] fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) { let map: OrdMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); assert_eq!(m.len(), map.iter().count()); } #[test] fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) { let map1: OrdMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); let map2: OrdMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); assert_eq!(map1, map2); } #[test] fn lookup(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) { let map: OrdMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); for (k, v) in m.iter() { assert_eq!(Some(*v), map.get(k).cloned()); } } #[test] fn remove(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) { let mut map: OrdMap = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v))); for k in m.keys() { let l = map.len(); assert_eq!(m.get(k).cloned(), map.get(k).cloned()); map = map.without(k); assert_eq!(None, map.get(k)); assert_eq!(l - 1, map.len()); } } #[test] fn insert_mut(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) { let mut mut_map = OrdMap::new(); let mut map = OrdMap::new(); for (k, v) in m.iter() { map = map.update(*k, *v); mut_map.insert(*k, *v); } assert_eq!(map, mut_map); } #[test] fn remove_mut(ref orig in ord_map(i16::ANY, i16::ANY, 0..1000)) { let mut map = orig.clone(); for key in orig.keys() { let len = map.len(); assert_eq!(orig.get(key), map.get(key)); assert_eq!(orig.get(key).cloned(), map.remove(key)); assert_eq!(None, map.get(key)); assert_eq!(len - 1, map.len()); } } #[test] fn remove_alien(ref orig in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) { let mut map = OrdMap::::from(orig.clone()); for key in orig.keys() { let len = map.len(); assert_eq!(orig.get(key), map.get(key)); assert_eq!(orig.get(key).cloned(), map.remove(key)); assert_eq!(None, map.get(key)); assert_eq!(len - 1, map.len()); } } #[test] fn delete_and_reinsert( ref input in collection::hash_map(i16::ANY, i16::ANY, 1..1000), index_rand in usize::ANY ) { let index = *input.keys().nth(index_rand % input.len()).unwrap(); let map1 = OrdMap::from_iter(input.clone()); let (val, map2): (i16, _) = map1.extract(&index).unwrap(); let map3 = map2.update(index, val); for key in map2.keys() { assert!(*key != index); } assert_eq!(map1.len(), map2.len() + 1); assert_eq!(map1, map3); } #[test] fn exact_size_iterator(ref m in ord_map(i16::ANY, i16::ANY, 1..1000)) { let mut should_be = m.len(); let mut it = m.iter(); loop { assert_eq!(should_be, it.len()); match it.next() { None => break, Some(_) => should_be -= 1, } } assert_eq!(0, it.len()); } #[test] fn diff_all_values(a in collection::vec((usize::ANY, usize::ANY), 1..1000), b in collection::vec((usize::ANY, usize::ANY), 1..1000)) { let a: OrdMap = OrdMap::from(a); let b: OrdMap = OrdMap::from(b); let diff: Vec<_> = a.diff(&b).collect(); let union = b.clone().union(a.clone()); let expected: Vec<_> = union.iter().filter_map(|(k, v)| { if a.contains_key(&k) { if b.contains_key(&k) { let old = a.get(&k).unwrap(); if old != v { Some(DiffItem::Update { old: (k, old), new: (k, v), }) } else { None } } else { Some(DiffItem::Remove(k, v)) } } else { Some(DiffItem::Add(k, v)) } }).collect(); assert_eq!(expected, diff); } } } im-rc-15.0.0/src/ord/mod.rs010064400017500001750000000003771365756323600135540ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #[macro_use] pub mod map; #[macro_use] pub mod set; im-rc-15.0.0/src/ord/set.rs010064400017500001750000000777041365756323600136000ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! An ordered set. //! //! An immutable ordered set implemented as a [B-tree] [1]. //! //! Most operations on this type of set are O(log n). A //! [`HashSet`][hashset::HashSet] is usually a better choice for //! performance, but the `OrdSet` has the advantage of only requiring //! an [`Ord`][std::cmp::Ord] constraint on its values, and of being //! ordered, so values always come out from lowest to highest, where a //! [`HashSet`][hashset::HashSet] has no guaranteed ordering. //! //! [1]: https://en.wikipedia.org/wiki/B-tree //! [hashset::HashSet]: ../hashset/struct.HashSet.html //! [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html use std::borrow::Borrow; use std::cmp::Ordering; use std::collections; use std::fmt::{Debug, Error, Formatter}; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter::{FromIterator, IntoIterator, Sum}; use std::ops::{Add, Deref, Mul, RangeBounds}; use crate::hashset::HashSet; use crate::nodes::btree::{ BTreeValue, ConsumingIter as ConsumingNodeIter, DiffIter as NodeDiffIter, Insert, Iter as NodeIter, Node, Remove, }; #[cfg(has_specialisation)] use crate::util::linear_search_by; use crate::util::{Pool, PoolRef}; pub use crate::nodes::btree::DiffItem; /// Construct a set from a sequence of values. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// # fn main() { /// assert_eq!( /// ordset![1, 2, 3], /// OrdSet::from(vec![1, 2, 3]) /// ); /// # } /// ``` #[macro_export] macro_rules! ordset { () => { $crate::ordset::OrdSet::new() }; ( $($x:expr),* ) => {{ let mut l = $crate::ordset::OrdSet::new(); $( l.insert($x); )* l }}; } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] struct Value(A); impl Deref for Value { type Target = A; fn deref(&self) -> &Self::Target { &self.0 } } // FIXME lacking specialisation, we can't simply implement `BTreeValue` // for `A`, we have to use the `Value` indirection. #[cfg(not(has_specialisation))] impl BTreeValue for Value { type Key = A; fn ptr_eq(&self, _other: &Self) -> bool { false } fn search_key(slice: &[Self], key: &BK) -> Result where BK: Ord + ?Sized, Self::Key: Borrow, { slice.binary_search_by(|value| Self::Key::borrow(value).cmp(key)) } fn search_value(slice: &[Self], key: &Self) -> Result { slice.binary_search_by(|value| value.cmp(key)) } fn cmp_keys(&self, other: &BK) -> Ordering where BK: Ord + ?Sized, Self::Key: Borrow, { Self::Key::borrow(self).cmp(other) } fn cmp_values(&self, other: &Self) -> Ordering { self.cmp(other) } } #[cfg(has_specialisation)] impl BTreeValue for Value { type Key = A; fn ptr_eq(&self, _other: &Self) -> bool { false } default fn search_key(slice: &[Self], key: &BK) -> Result where BK: Ord + ?Sized, Self::Key: Borrow, { slice.binary_search_by(|value| Self::Key::borrow(value).cmp(key)) } default fn search_value(slice: &[Self], key: &Self) -> Result { slice.binary_search_by(|value| value.cmp(key)) } fn cmp_keys(&self, other: &BK) -> Ordering where BK: Ord + ?Sized, Self::Key: Borrow, { Self::Key::borrow(self).cmp(other) } fn cmp_values(&self, other: &Self) -> Ordering { self.cmp(other) } } #[cfg(has_specialisation)] impl BTreeValue for Value { fn search_key(slice: &[Self], key: &BK) -> Result where BK: Ord + ?Sized, Self::Key: Borrow, { linear_search_by(slice, |value| Self::Key::borrow(value).cmp(key)) } fn search_value(slice: &[Self], key: &Self) -> Result { linear_search_by(slice, |value| value.cmp(key)) } } def_pool!(OrdSetPool, Node>); /// An ordered set. /// /// An immutable ordered set implemented as a [B-tree] [1]. /// /// Most operations on this type of set are O(log n). A /// [`HashSet`][hashset::HashSet] is usually a better choice for /// performance, but the `OrdSet` has the advantage of only requiring /// an [`Ord`][std::cmp::Ord] constraint on its values, and of being /// ordered, so values always come out from lowest to highest, where a /// [`HashSet`][hashset::HashSet] has no guaranteed ordering. /// /// [1]: https://en.wikipedia.org/wiki/B-tree /// [hashset::HashSet]: ../hashset/struct.HashSet.html /// [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html pub struct OrdSet { size: usize, pool: OrdSetPool, root: PoolRef>>, } impl OrdSet { /// Construct an empty set. #[must_use] pub fn new() -> Self { let pool = OrdSetPool::default(); let root = PoolRef::default(&pool.0); OrdSet { size: 0, pool, root, } } /// Construct an empty set using a specific memory pool. #[cfg(feature = "pool")] #[must_use] pub fn with_pool(pool: &OrdSetPool) -> Self { let root = PoolRef::default(&pool.0); OrdSet { size: 0, pool: pool.clone(), root, } } /// Construct a set with a single value. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let set = OrdSet::unit(123); /// assert!(set.contains(&123)); /// ``` #[inline] #[must_use] pub fn unit(a: A) -> Self { let pool = OrdSetPool::default(); let root = PoolRef::new(&pool.0, Node::unit(Value(a))); OrdSet { size: 1, pool, root, } } /// Test whether a set is empty. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// assert!( /// !ordset![1, 2, 3].is_empty() /// ); /// assert!( /// OrdSet::::new().is_empty() /// ); /// ``` #[inline] #[must_use] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Get the size of a set. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// assert_eq!(3, ordset![1, 2, 3].len()); /// ``` #[inline] #[must_use] pub fn len(&self) -> usize { self.size } /// Test whether two sets refer to the same content in memory. /// /// This is true if the two sides are references to the same set, /// or if the two sets refer to the same root node. /// /// This would return true if you're comparing a set to itself, or /// if you're comparing a set to a fresh clone of itself. /// /// Time: O(1) pub fn ptr_eq(&self, other: &Self) -> bool { std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root) } /// Get a reference to the memory pool used by this set. /// /// Note that if you didn't specifically construct it with a pool, you'll /// get back a reference to a pool of size 0. #[cfg(feature = "pool")] pub fn pool(&self) -> &OrdSetPool { &self.pool } /// Discard all elements from the set. /// /// This leaves you with an empty set, and all elements that /// were previously inside it are dropped. /// /// Time: O(n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::OrdSet; /// let mut set = ordset![1, 2, 3]; /// set.clear(); /// assert!(set.is_empty()); /// ``` pub fn clear(&mut self) { if !self.is_empty() { self.root = PoolRef::default(&self.pool.0); self.size = 0; } } } impl OrdSet where A: Ord, { /// Get the smallest value in a set. /// /// If the set is empty, returns `None`. /// /// Time: O(log n) #[must_use] pub fn get_min(&self) -> Option<&A> { self.root.min().map(Deref::deref) } /// Get the largest value in a set. /// /// If the set is empty, returns `None`. /// /// Time: O(log n) #[must_use] pub fn get_max(&self) -> Option<&A> { self.root.max().map(Deref::deref) } /// Create an iterator over the contents of the set. #[must_use] pub fn iter(&self) -> Iter<'_, A> { Iter { it: NodeIter::new(&self.root, self.size, ..), } } /// Create an iterator over a range inside the set. #[must_use] pub fn range(&self, range: R) -> RangedIter<'_, A> where R: RangeBounds, A: Borrow, BA: Ord + ?Sized, { RangedIter { it: NodeIter::new(&self.root, self.size, range), } } /// Get an iterator over the differences between this set and /// another, i.e. the set of entries to add or remove to this set /// in order to make it equal to the other set. /// /// This function will avoid visiting nodes which are shared /// between the two sets, meaning that even very large sets can be /// compared quickly if most of their structure is shared. /// /// Time: O(n) (where n is the number of unique elements across /// the two sets, minus the number of elements belonging to nodes /// shared between them) #[must_use] pub fn diff<'a>(&'a self, other: &'a Self) -> DiffIter<'_, A> { DiffIter { it: NodeDiffIter::new(&self.root, &other.root), } } /// Test if a value is part of a set. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let mut set = ordset!{1, 2, 3}; /// assert!(set.contains(&1)); /// assert!(!set.contains(&4)); /// ``` #[inline] #[must_use] pub fn contains(&self, a: &BA) -> bool where BA: Ord + ?Sized, A: Borrow, { self.root.lookup(a).is_some() } /// Get the closest smaller value in a set to a given value. /// /// If the set contains the given value, this is returned. /// Otherwise, the closest value in the set smaller than the /// given value is returned. If the smallest value in the set /// is larger than the given value, `None` is returned. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::OrdSet; /// let set = ordset![1, 3, 5, 7, 9]; /// assert_eq!(Some(&5), set.get_prev(&6)); /// ``` #[must_use] pub fn get_prev(&self, key: &A) -> Option<&A> { self.root.lookup_prev(key).map(|v| &v.0) } /// Get the closest larger value in a set to a given value. /// /// If the set contains the given value, this is returned. /// Otherwise, the closest value in the set larger than the /// given value is returned. If the largest value in the set /// is smaller than the given value, `None` is returned. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::OrdSet; /// let set = ordset![1, 3, 5, 7, 9]; /// assert_eq!(Some(&5), set.get_next(&4)); /// ``` #[must_use] pub fn get_next(&self, key: &A) -> Option<&A> { self.root.lookup_next(key).map(|v| &v.0) } /// Test whether a set is a subset of another set, meaning that /// all values in our set must also be in the other set. /// /// Time: O(n log m) where m is the size of the other set #[must_use] pub fn is_subset(&self, other: RS) -> bool where RS: Borrow, { let other = other.borrow(); if other.len() < self.len() { return false; } self.iter().all(|a| other.contains(&a)) } /// Test whether a set is a proper subset of another set, meaning /// that all values in our set must also be in the other set. A /// proper subset must also be smaller than the other set. /// /// Time: O(n log m) where m is the size of the other set #[must_use] pub fn is_proper_subset(&self, other: RS) -> bool where RS: Borrow, { self.len() != other.borrow().len() && self.is_subset(other) } } impl OrdSet where A: Ord + Clone, { /// Insert a value into a set. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let mut set = ordset!{}; /// set.insert(123); /// set.insert(456); /// assert_eq!( /// set, /// ordset![123, 456] /// ); /// ``` #[inline] pub fn insert(&mut self, a: A) -> Option { let new_root = { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); match root.insert(&self.pool.0, Value(a)) { Insert::Replaced(Value(old_value)) => return Some(old_value), Insert::Added => { self.size += 1; return None; } Insert::Split(left, median, right) => PoolRef::new( &self.pool.0, Node::new_from_split(&self.pool.0, left, median, right), ), } }; self.size += 1; self.root = new_root; None } /// Remove a value from a set. /// /// Time: O(log n) #[inline] pub fn remove(&mut self, a: &BA) -> Option where BA: Ord + ?Sized, A: Borrow, { let (new_root, removed_value) = { let root = PoolRef::make_mut(&self.pool.0, &mut self.root); match root.remove(&self.pool.0, a) { Remove::Update(value, root) => (PoolRef::new(&self.pool.0, root), Some(value.0)), Remove::Removed(value) => { self.size -= 1; return Some(value.0); } Remove::NoChange => return None, } }; self.size -= 1; self.root = new_root; removed_value } /// Remove the smallest value from a set. /// /// Time: O(log n) pub fn remove_min(&mut self) -> Option { // FIXME implement this at the node level for better efficiency let key = match self.get_min() { None => return None, Some(v) => v, } .clone(); self.remove(&key) } /// Remove the largest value from a set. /// /// Time: O(log n) pub fn remove_max(&mut self) -> Option { // FIXME implement this at the node level for better efficiency let key = match self.get_max() { None => return None, Some(v) => v, } .clone(); self.remove(&key) } /// Construct a new set from the current set with the given value /// added. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let set = ordset![456]; /// assert_eq!( /// set.update(123), /// ordset![123, 456] /// ); /// ``` #[must_use] pub fn update(&self, a: A) -> Self { let mut out = self.clone(); out.insert(a); out } /// Construct a new set with the given value removed if it's in /// the set. /// /// Time: O(log n) #[must_use] pub fn without(&self, a: &BA) -> Self where BA: Ord + ?Sized, A: Borrow, { let mut out = self.clone(); out.remove(a); out } /// Remove the smallest value from a set, and return that value as /// well as the updated set. /// /// Time: O(log n) #[must_use] pub fn without_min(&self) -> (Option, Self) { match self.get_min() { Some(v) => (Some(v.clone()), self.without(&v)), None => (None, self.clone()), } } /// Remove the largest value from a set, and return that value as /// well as the updated set. /// /// Time: O(log n) #[must_use] pub fn without_max(&self) -> (Option, Self) { match self.get_max() { Some(v) => (Some(v.clone()), self.without(&v)), None => (None, self.clone()), } } /// Construct the union of two sets. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let set1 = ordset!{1, 2}; /// let set2 = ordset!{2, 3}; /// let expected = ordset!{1, 2, 3}; /// assert_eq!(expected, set1.union(set2)); /// ``` #[must_use] pub fn union(mut self, other: Self) -> Self { for value in other { self.insert(value); } self } /// Construct the union of multiple sets. /// /// Time: O(n log n) #[must_use] pub fn unions(i: I) -> Self where I: IntoIterator, { i.into_iter().fold(Self::default(), Self::union) } /// Construct the symmetric difference between two sets. /// /// This is an alias for the /// [`symmetric_difference`][symmetric_difference] method. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let set1 = ordset!{1, 2}; /// let set2 = ordset!{2, 3}; /// let expected = ordset!{1, 3}; /// assert_eq!(expected, set1.difference(set2)); /// ``` /// /// [symmetric_difference]: #method.symmetric_difference #[must_use] pub fn difference(self, other: Self) -> Self { self.symmetric_difference(other) } /// Construct the symmetric difference between two sets. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let set1 = ordset!{1, 2}; /// let set2 = ordset!{2, 3}; /// let expected = ordset!{1, 3}; /// assert_eq!(expected, set1.symmetric_difference(set2)); /// ``` #[must_use] pub fn symmetric_difference(mut self, other: Self) -> Self { for value in other { if self.remove(&value).is_none() { self.insert(value); } } self } /// Construct the relative complement between two sets, that is the set /// of values in `self` that do not occur in `other`. /// /// Time: O(m log n) where m is the size of the other set /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let set1 = ordset!{1, 2}; /// let set2 = ordset!{2, 3}; /// let expected = ordset!{1}; /// assert_eq!(expected, set1.relative_complement(set2)); /// ``` #[must_use] pub fn relative_complement(mut self, other: Self) -> Self { for value in other { let _ = self.remove(&value); } self } /// Construct the intersection of two sets. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::ordset::OrdSet; /// let set1 = ordset!{1, 2}; /// let set2 = ordset!{2, 3}; /// let expected = ordset!{2}; /// assert_eq!(expected, set1.intersection(set2)); /// ``` #[must_use] pub fn intersection(self, other: Self) -> Self { let mut out = Self::default(); for value in other { if self.contains(&value) { out.insert(value); } } out } /// Split a set into two, with the left hand set containing values /// which are smaller than `split`, and the right hand set /// containing values which are larger than `split`. /// /// The `split` value itself is discarded. /// /// Time: O(n) #[must_use] pub fn split(self, split: &BA) -> (Self, Self) where BA: Ord + ?Sized, A: Borrow, { let (left, _, right) = self.split_member(split); (left, right) } /// Split a set into two, with the left hand set containing values /// which are smaller than `split`, and the right hand set /// containing values which are larger than `split`. /// /// Returns a tuple of the two sets and a boolean which is true if /// the `split` value existed in the original set, and false /// otherwise. /// /// Time: O(n) #[must_use] pub fn split_member(self, split: &BA) -> (Self, bool, Self) where BA: Ord + ?Sized, A: Borrow, { let mut left = Self::default(); let mut right = Self::default(); let mut present = false; for value in self { match value.borrow().cmp(split) { Ordering::Less => { left.insert(value); } Ordering::Equal => { present = true; } Ordering::Greater => { right.insert(value); } } } (left, present, right) } /// Construct a set with only the `n` smallest values from a given /// set. /// /// Time: O(n) #[must_use] pub fn take(&self, n: usize) -> Self { self.iter().take(n).cloned().collect() } /// Construct a set with the `n` smallest values removed from a /// given set. /// /// Time: O(n) #[must_use] pub fn skip(&self, n: usize) -> Self { self.iter().skip(n).cloned().collect() } } // Core traits impl Clone for OrdSet { /// Clone a set. /// /// Time: O(1) #[inline] fn clone(&self) -> Self { OrdSet { size: self.size, pool: self.pool.clone(), root: self.root.clone(), } } } impl PartialEq for OrdSet { fn eq(&self, other: &Self) -> bool { PoolRef::ptr_eq(&self.root, &other.root) || (self.len() == other.len() && self.diff(other).next().is_none()) } } impl Eq for OrdSet {} impl PartialOrd for OrdSet { fn partial_cmp(&self, other: &Self) -> Option { self.iter().partial_cmp(other.iter()) } } impl Ord for OrdSet { fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other.iter()) } } impl Hash for OrdSet { fn hash(&self, state: &mut H) where H: Hasher, { for i in self.iter() { i.hash(state); } } } impl Default for OrdSet { fn default() -> Self { OrdSet::new() } } impl Add for OrdSet { type Output = OrdSet; fn add(self, other: Self) -> Self::Output { self.union(other) } } impl<'a, A: Ord + Clone> Add for &'a OrdSet { type Output = OrdSet; fn add(self, other: Self) -> Self::Output { self.clone().union(other.clone()) } } impl Mul for OrdSet { type Output = OrdSet; fn mul(self, other: Self) -> Self::Output { self.intersection(other) } } impl<'a, A: Ord + Clone> Mul for &'a OrdSet { type Output = OrdSet; fn mul(self, other: Self) -> Self::Output { self.clone().intersection(other.clone()) } } impl Sum for OrdSet { fn sum(it: I) -> Self where I: Iterator, { it.fold(Self::new(), |a, b| a + b) } } impl Extend for OrdSet where A: Ord + Clone + From, { fn extend(&mut self, iter: I) where I: IntoIterator, { for value in iter { self.insert(From::from(value)); } } } impl Debug for OrdSet { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.debug_set().entries(self.iter()).finish() } } // Iterators /// An iterator over the elements of a set. pub struct Iter<'a, A> { it: NodeIter<'a, Value>, } impl<'a, A> Iterator for Iter<'a, A> where A: 'a + Ord, { type Item = &'a A; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { self.it.next().map(Deref::deref) } fn size_hint(&self) -> (usize, Option) { (self.it.remaining, Some(self.it.remaining)) } } impl<'a, A> DoubleEndedIterator for Iter<'a, A> where A: 'a + Ord, { fn next_back(&mut self) -> Option { self.it.next_back().map(Deref::deref) } } impl<'a, A> ExactSizeIterator for Iter<'a, A> where A: 'a + Ord {} /// A ranged iterator over the elements of a set. /// /// The only difference from `Iter` is that this one doesn't implement /// `ExactSizeIterator` because we can't know the size of the range without first /// iterating over it to count. pub struct RangedIter<'a, A> { it: NodeIter<'a, Value>, } impl<'a, A> Iterator for RangedIter<'a, A> where A: 'a + Ord, { type Item = &'a A; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { self.it.next().map(Deref::deref) } fn size_hint(&self) -> (usize, Option) { self.it.size_hint() } } impl<'a, A> DoubleEndedIterator for RangedIter<'a, A> where A: 'a + Ord, { fn next_back(&mut self) -> Option { self.it.next_back().map(Deref::deref) } } /// A consuming iterator over the elements of a set. pub struct ConsumingIter { it: ConsumingNodeIter>, } impl Iterator for ConsumingIter where A: Ord + Clone, { type Item = A; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { self.it.next().map(|v| v.0) } } /// An iterator over the difference between two sets. pub struct DiffIter<'a, A> { it: NodeDiffIter<'a, Value>, } impl<'a, A> Iterator for DiffIter<'a, A> where A: Ord + PartialEq, { type Item = DiffItem<'a, A>; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { self.it.next().map(|item| match item { DiffItem::Add(v) => DiffItem::Add(v.deref()), DiffItem::Update { old, new } => DiffItem::Update { old: old.deref(), new: new.deref(), }, DiffItem::Remove(v) => DiffItem::Remove(v.deref()), }) } } impl FromIterator for OrdSet where A: Ord + Clone + From, { fn from_iter(i: T) -> Self where T: IntoIterator, { let mut out = Self::new(); for item in i { out.insert(From::from(item)); } out } } impl<'a, A> IntoIterator for &'a OrdSet where A: 'a + Ord, { type Item = &'a A; type IntoIter = Iter<'a, A>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl IntoIterator for OrdSet where A: Ord + Clone, { type Item = A; type IntoIter = ConsumingIter; fn into_iter(self) -> Self::IntoIter { ConsumingIter { it: ConsumingNodeIter::new(&self.root, self.size), } } } // Conversions impl<'s, 'a, A, OA> From<&'s OrdSet<&'a A>> for OrdSet where A: ToOwned + Ord + ?Sized, OA: Borrow + Ord + Clone, { fn from(set: &OrdSet<&A>) -> Self { set.iter().map(|a| (*a).to_owned()).collect() } } impl<'a, A> From<&'a [A]> for OrdSet where A: Ord + Clone, { fn from(slice: &'a [A]) -> Self { slice.iter().cloned().collect() } } impl From> for OrdSet { fn from(vec: Vec) -> Self { vec.into_iter().collect() } } impl<'a, A: Ord + Clone> From<&'a Vec> for OrdSet { fn from(vec: &Vec) -> Self { vec.iter().cloned().collect() } } impl From> for OrdSet { fn from(hash_set: collections::HashSet) -> Self { hash_set.into_iter().collect() } } impl<'a, A: Eq + Hash + Ord + Clone> From<&'a collections::HashSet> for OrdSet { fn from(hash_set: &collections::HashSet) -> Self { hash_set.iter().cloned().collect() } } impl From> for OrdSet { fn from(btree_set: collections::BTreeSet) -> Self { btree_set.into_iter().collect() } } impl<'a, A: Ord + Clone> From<&'a collections::BTreeSet> for OrdSet { fn from(btree_set: &collections::BTreeSet) -> Self { btree_set.iter().cloned().collect() } } impl From> for OrdSet { fn from(hashset: HashSet) -> Self { hashset.into_iter().collect() } } impl<'a, A: Hash + Eq + Ord + Clone, S: BuildHasher> From<&'a HashSet> for OrdSet { fn from(hashset: &HashSet) -> Self { hashset.into_iter().cloned().collect() } } // Proptest #[cfg(any(test, feature = "proptest"))] #[doc(hidden)] pub mod proptest { #[deprecated( since = "14.3.0", note = "proptest strategies have moved to im::proptest" )] pub use crate::proptest::ord_set; } #[cfg(test)] mod test { use super::*; use crate::proptest::*; use ::proptest::proptest; #[test] fn match_strings_with_string_slices() { let mut set: OrdSet = From::from(&ordset!["foo", "bar"]); set = set.without("bar"); assert!(!set.contains("bar")); set.remove("foo"); assert!(!set.contains("foo")); } #[test] fn ranged_iter() { let set: OrdSet = ordset![1, 2, 3, 4, 5]; let range: Vec = set.range(..).cloned().collect(); assert_eq!(vec![1, 2, 3, 4, 5], range); let range: Vec = set.range(..).rev().cloned().collect(); assert_eq!(vec![5, 4, 3, 2, 1], range); let range: Vec = set.range(2..5).cloned().collect(); assert_eq!(vec![2, 3, 4], range); let range: Vec = set.range(2..5).rev().cloned().collect(); assert_eq!(vec![4, 3, 2], range); let range: Vec = set.range(3..).cloned().collect(); assert_eq!(vec![3, 4, 5], range); let range: Vec = set.range(3..).rev().cloned().collect(); assert_eq!(vec![5, 4, 3], range); let range: Vec = set.range(..4).cloned().collect(); assert_eq!(vec![1, 2, 3], range); let range: Vec = set.range(..4).rev().cloned().collect(); assert_eq!(vec![3, 2, 1], range); let range: Vec = set.range(..=3).cloned().collect(); assert_eq!(vec![1, 2, 3], range); let range: Vec = set.range(..=3).rev().cloned().collect(); assert_eq!(vec![3, 2, 1], range); } proptest! { #[test] fn proptest_a_set(ref s in ord_set(".*", 10..100)) { assert!(s.len() < 100); assert!(s.len() >= 10); } #[test] fn long_ranged_iter(max in 1..1000) { let range = 0..max; let expected: Vec = range.clone().collect(); let set: OrdSet = OrdSet::from_iter(range.clone()); let result: Vec = set.range(..).cloned().collect(); assert_eq!(expected, result); let expected: Vec = range.clone().rev().collect(); let set: OrdSet = OrdSet::from_iter(range); let result: Vec = set.range(..).rev().cloned().collect(); assert_eq!(expected, result); } } } im-rc-15.0.0/src/proptest.rs010064400017500001750000000103111365756323600140560ustar0000000000000000//! Proptest strategies. //! //! These are only available when using the `proptest` feature flag. use crate::{HashMap, HashSet, OrdMap, OrdSet, Vector}; use ::proptest::collection::vec; use ::proptest::strategy::{BoxedStrategy, Strategy, ValueTree}; use std::hash::Hash; use std::iter::FromIterator; use std::ops::Range; /// A strategy for generating a [`Vector`][Vector] of a certain size. /// /// # Examples /// /// ```rust,no_run /// # use ::proptest::proptest; /// proptest! { /// #[test] /// fn proptest_a_vector(ref l in vector(".*", 10..100)) { /// assert!(l.len() < 100); /// assert!(l.len() >= 10); /// } /// } /// ``` /// /// [Vector]: ../struct.Vector.html pub fn vector( element: A, size: Range, ) -> BoxedStrategy::Value>> where ::Value: Clone, { vec(element, size).prop_map(Vector::from_iter).boxed() } /// A strategy for an [`OrdMap`][OrdMap] of a given size. /// /// # Examples /// /// ```rust,no_run /// # use ::proptest::proptest; /// proptest! { /// #[test] /// fn proptest_works(ref m in ord_map(0..9999, ".*", 10..100)) { /// assert!(m.len() < 100); /// assert!(m.len() >= 10); /// } /// } /// ``` /// /// [OrdMap]: ../struct.OrdMap.html pub fn ord_map( key: K, value: V, size: Range, ) -> BoxedStrategy::Value, ::Value>> where ::Value: Ord + Clone, ::Value: Clone, { ::proptest::collection::vec((key, value), size.clone()) .prop_map(OrdMap::from) .prop_filter("OrdMap minimum size".to_owned(), move |m| { m.len() >= size.start }) .boxed() } /// A strategy for an [`OrdSet`][OrdSet] of a given size. /// /// # Examples /// /// ```rust,no_run /// # use ::proptest::proptest; /// proptest! { /// #[test] /// fn proptest_a_set(ref s in ord_set(".*", 10..100)) { /// assert!(s.len() < 100); /// assert!(s.len() >= 10); /// } /// } /// ``` /// /// [OrdSet]: ../struct.OrdSet.html pub fn ord_set( element: A, size: Range, ) -> BoxedStrategy::Value>> where ::Value: Ord + Clone, { ::proptest::collection::vec(element, size.clone()) .prop_map(OrdSet::from) .prop_filter("OrdSet minimum size".to_owned(), move |s| { s.len() >= size.start }) .boxed() } /// A strategy for a [`HashMap`][HashMap] of a given size. /// /// # Examples /// /// ```rust,no_run /// # use ::proptest::proptest; /// proptest! { /// #[test] /// fn proptest_works(ref m in hash_map(0..9999, ".*", 10..100)) { /// assert!(m.len() < 100); /// assert!(m.len() >= 10); /// } /// } /// ``` /// /// [HashMap]: ../struct.HashMap.html pub fn hash_map( key: K, value: V, size: Range, ) -> BoxedStrategy::Value, ::Value>> where ::Value: Hash + Eq + Clone, ::Value: Clone, { ::proptest::collection::vec((key, value), size.clone()) .prop_map(HashMap::from) .prop_filter("Map minimum size".to_owned(), move |m| { m.len() >= size.start }) .boxed() } /// A strategy for a [`HashSet`][HashSet] of a given size. /// /// # Examples /// /// ```rust,no_run /// # use ::proptest::proptest; /// proptest! { /// #[test] /// fn proptest_a_set(ref s in hash_set(".*", 10..100)) { /// assert!(s.len() < 100); /// assert!(s.len() >= 10); /// } /// } /// ``` /// /// [HashSet]: ../struct.HashSet.html pub fn hash_set( element: A, size: Range, ) -> BoxedStrategy::Value>> where ::Value: Hash + Eq + Clone, { ::proptest::collection::vec(element, size.clone()) .prop_map(HashSet::from) .prop_filter("HashSet minimum size".to_owned(), move |s| { s.len() >= size.start }) .boxed() } im-rc-15.0.0/src/quickcheck.rs010064400017500001750000000023031365756323600143120ustar0000000000000000use crate::{HashMap, HashSet, OrdMap, OrdSet, Vector}; use ::quickcheck::{Arbitrary, Gen}; use std::hash::{BuildHasher, Hash}; use std::iter::FromIterator; impl Arbitrary for Vector { fn arbitrary(g: &mut G) -> Self { Vector::from_iter(Vec::::arbitrary(g)) } } impl Arbitrary for OrdMap { fn arbitrary(g: &mut G) -> Self { OrdMap::from_iter(Vec::<(K, V)>::arbitrary(g)) } } impl Arbitrary for OrdSet { fn arbitrary(g: &mut G) -> Self { OrdSet::from_iter(Vec::::arbitrary(g)) } } impl Arbitrary for HashSet where A: Hash + Eq + Arbitrary + Sync, S: BuildHasher + Default + Send + Sync + 'static, { fn arbitrary(g: &mut G) -> Self { HashSet::from_iter(Vec::::arbitrary(g)) } } impl Arbitrary for HashMap where K: Hash + Eq + Arbitrary + Sync, V: Arbitrary + Sync, S: BuildHasher + Default + Send + Sync + 'static, { fn arbitrary(g: &mut G) -> Self { HashMap::from(Vec::<(K, V)>::arbitrary(g)) } } im-rc-15.0.0/src/ser.rs010064400017500001750000000165511365756323600130030ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::marker::PhantomData; use std::ops::Deref; use crate::hashmap::HashMap; use crate::hashset::HashSet; use crate::ordmap::OrdMap; use crate::ordset::OrdSet; use crate::vector::Vector; struct SeqVisitor<'de, S, A> where S: From>, A: Deserialize<'de>, { phantom_s: PhantomData, phantom_a: PhantomData, phantom_lifetime: PhantomData<&'de ()>, } impl<'de, S, A> SeqVisitor<'de, S, A> where S: From>, A: Deserialize<'de>, { pub(crate) fn new() -> SeqVisitor<'de, S, A> { SeqVisitor { phantom_s: PhantomData, phantom_a: PhantomData, phantom_lifetime: PhantomData, } } } impl<'de, S, A> Visitor<'de> for SeqVisitor<'de, S, A> where S: From>, A: Deserialize<'de>, { type Value = S; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a sequence") } fn visit_seq(self, mut access: Access) -> Result where Access: SeqAccess<'de>, { let mut v: Vec = match access.size_hint() { None => Vec::new(), Some(l) => Vec::with_capacity(l), }; while let Some(i) = access.next_element()? { v.push(i) } Ok(From::from(v)) } } struct MapVisitor<'de, S, K, V> where S: From>, K: Deserialize<'de>, V: Deserialize<'de>, { phantom_s: PhantomData, phantom_k: PhantomData, phantom_v: PhantomData, phantom_lifetime: PhantomData<&'de ()>, } impl<'de, S, K, V> MapVisitor<'de, S, K, V> where S: From>, K: Deserialize<'de>, V: Deserialize<'de>, { pub(crate) fn new() -> MapVisitor<'de, S, K, V> { MapVisitor { phantom_s: PhantomData, phantom_k: PhantomData, phantom_v: PhantomData, phantom_lifetime: PhantomData, } } } impl<'de, S, K, V> Visitor<'de> for MapVisitor<'de, S, K, V> where S: From>, K: Deserialize<'de>, V: Deserialize<'de>, { type Value = S; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a sequence") } fn visit_map(self, mut access: Access) -> Result where Access: MapAccess<'de>, { let mut v: Vec<(K, V)> = match access.size_hint() { None => Vec::new(), Some(l) => Vec::with_capacity(l), }; while let Some(i) = access.next_entry()? { v.push(i) } Ok(From::from(v)) } } // Set impl<'de, A: Deserialize<'de> + Ord + Clone> Deserialize<'de> for OrdSet { fn deserialize(des: D) -> Result where D: Deserializer<'de>, { des.deserialize_seq(SeqVisitor::new()) } } impl Serialize for OrdSet { fn serialize(&self, ser: S) -> Result where S: Serializer, { let mut s = ser.serialize_seq(Some(self.len()))?; for i in self.iter() { s.serialize_element(i.deref())?; } s.end() } } // Map impl<'de, K: Deserialize<'de> + Ord + Clone, V: Deserialize<'de> + Clone> Deserialize<'de> for OrdMap { fn deserialize(des: D) -> Result where D: Deserializer<'de>, { des.deserialize_map(MapVisitor::<'de, OrdMap, K, V>::new()) } } impl Serialize for OrdMap { fn serialize(&self, ser: S) -> Result where S: Serializer, { let mut s = ser.serialize_map(Some(self.len()))?; for (k, v) in self.iter() { s.serialize_entry(k.deref(), v.deref())?; } s.end() } } // HashMap impl<'de, K, V, S> Deserialize<'de> for HashMap where K: Deserialize<'de> + Hash + Eq + Clone, V: Deserialize<'de> + Clone, S: BuildHasher + Default, { fn deserialize(des: D) -> Result where D: Deserializer<'de>, { des.deserialize_map(MapVisitor::<'de, HashMap, K, V>::new()) } } impl Serialize for HashMap where K: Serialize + Hash + Eq + Clone, V: Serialize + Clone, S: BuildHasher + Default, { fn serialize(&self, ser: Ser) -> Result where Ser: Serializer, { let mut s = ser.serialize_map(Some(self.len()))?; for (k, v) in self.iter() { s.serialize_entry(k.deref(), v.deref())?; } s.end() } } // HashSet impl<'de, A: Deserialize<'de> + Hash + Eq + Clone, S: BuildHasher + Default> Deserialize<'de> for HashSet { fn deserialize(des: D) -> Result where D: Deserializer<'de>, { des.deserialize_seq(SeqVisitor::new()) } } impl Serialize for HashSet { fn serialize(&self, ser: Ser) -> Result where Ser: Serializer, { let mut s = ser.serialize_seq(Some(self.len()))?; for i in self.iter() { s.serialize_element(i.deref())?; } s.end() } } // Vector impl<'de, A: Clone + Deserialize<'de>> Deserialize<'de> for Vector { fn deserialize(des: D) -> Result where D: Deserializer<'de>, { des.deserialize_seq(SeqVisitor::<'de, Vector, A>::new()) } } impl Serialize for Vector { fn serialize(&self, ser: S) -> Result where S: Serializer, { let mut s = ser.serialize_seq(Some(self.len()))?; for i in self.iter() { s.serialize_element(i.deref())?; } s.end() } } // Tests #[cfg(test)] mod test { use super::*; use crate::proptest::{hash_map, hash_set, ord_map, ord_set, vector}; use ::proptest::num::i32; use ::proptest::proptest; use serde_json::{from_str, to_string}; proptest! { #[test] fn ser_ordset(ref v in ord_set(i32::ANY, 0..100)) { assert_eq!(v, &from_str::>(&to_string(&v).unwrap()).unwrap()); } #[test] fn ser_ordmap(ref v in ord_map(i32::ANY, i32::ANY, 0..100)) { assert_eq!(v, &from_str::>(&to_string(&v).unwrap()).unwrap()); } #[test] fn ser_hashmap(ref v in hash_map(i32::ANY, i32::ANY, 0..100)) { assert_eq!(v, &from_str::>(&to_string(&v).unwrap()).unwrap()); } #[test] fn ser_hashset(ref v in hash_set(i32::ANY, 0..100)) { assert_eq!(v, &from_str::>(&to_string(&v).unwrap()).unwrap()); } #[test] fn ser_vector(ref v in vector(i32::ANY, 0..100)) { assert_eq!(v, &from_str::>(&to_string(&v).unwrap()).unwrap()); } } } im-rc-15.0.0/src/sort.rs010064400017500001750000000163331365756323600131770ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use crate::vector::FocusMut; use rand_core::{RngCore, SeedableRng}; use std::cmp::Ordering; use std::mem; fn gen_range(rng: &mut R, min: usize, max: usize) -> usize { let range = max - min; min + (rng.next_u64() as usize % range) } // Ported from the Java version at: // http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf // There are a couple of modifications made here to make it more performant on the tree structure of // the Vector. Instead of moving of handling equal and nonequal items in a single pass we make two // additional passes to find the exact partition places. This allows us to split the focus into // three correctly sized parts for less than, equal to and greater than items. As a bonus this // doesn't need to reorder the equal items to the center of the vector. fn do_quicksort(vector: FocusMut<'_, A>, cmp: &F, rng: &mut R) where A: Clone, F: Fn(&A, &A) -> Ordering, R: RngCore, { if vector.len() <= 1 { return; } // We know there are at least 2 elements here let pivot_index = gen_range(rng, 0, vector.len()); let (mut first, mut rest) = vector.split_at(1); if pivot_index > 0 { mem::swap(rest.index_mut(pivot_index - 1), first.index_mut(0)); } // Pivot is now always in the first slice let pivot_item = first.index(0); // Find the exact place to put the pivot or pivot-equal items let mut less_count = 0; let mut equal_count = 0; for index in 0..rest.len() { let item = rest.index(index); let comp = cmp(item, pivot_item); match comp { Ordering::Less => less_count += 1, Ordering::Equal => equal_count += 1, Ordering::Greater => {} } } // If by accident we picked the minimum element as a pivot, we just call sort again with the // rest of the vector. if less_count == 0 { do_quicksort(rest, cmp, rng); return; } // We know here that there is at least one item before the pivot, so we move the minimum to the // beginning part of the vector. First, however we swap the pivot to the start of the equal // zone. less_count -= 1; equal_count += 1; let first_item = first.index_mut(0); mem::swap(first_item, rest.index_mut(less_count)); for index in 0..rest.len() { if index == less_count { // This is the position we swapped the pivot to. We can't move it from its position, and // we know its not the minimum. continue; } let rest_item = rest.index_mut(index); if cmp(rest_item, first_item) == Ordering::Less { mem::swap(first_item, rest_item); } } // Split the vector up into less_than, equal to and greater than parts. let (remaining, mut greater_focus) = rest.split_at(less_count + equal_count); let (mut less_focus, mut equal_focus) = remaining.split_at(less_count); let mut less_position = 0; let mut equal_position = 0; let mut greater_position = 0; while less_position != less_focus.len() || greater_position != greater_focus.len() { // At start of this loop, equal_position always points to an equal item let mut equal_swap_side = None; let equal_item = equal_focus.index(equal_position); // Advance the less_position until we find an out of place item while less_position != less_focus.len() { let less_item = less_focus.index(less_position); match cmp(less_item, equal_item) { Ordering::Equal => { equal_swap_side = Some(Ordering::Less); break; } Ordering::Greater => { break; } _ => {} } less_position += 1; } // Advance the greater until we find an out of place item while greater_position != greater_focus.len() { let greater_item = greater_focus.index(greater_position); match cmp(greater_item, equal_item) { Ordering::Less => break, Ordering::Equal => { equal_swap_side = Some(Ordering::Greater); break; } _ => {} } greater_position += 1; } if let Some(swap_side) = equal_swap_side { // One of the sides is equal to the pivot, advance the pivot let item = if swap_side == Ordering::Less { less_focus.index_mut(less_position) } else { greater_focus.index_mut(greater_position) }; // We are guaranteed not to hit the end of the equal focus while cmp(item, equal_focus.index(equal_position)) == Ordering::Equal { equal_position += 1; } // Swap the equal position and the desired side, it's important to note that only the // equals focus is guaranteed to have made progress so we don't advance the side's index mem::swap(item, equal_focus.index_mut(equal_position)); } else if less_position != less_focus.len() && greater_position != greater_focus.len() { // Both sides are out of place and not equal to the pivot, this can only happen if there // is a greater item in the lesser zone and a lesser item in the greater zone. The // solution is to swap both sides and advance both side's indices. debug_assert_ne!( cmp( less_focus.index(less_position), equal_focus.index(equal_position) ), Ordering::Equal ); debug_assert_ne!( cmp( greater_focus.index(greater_position), equal_focus.index(equal_position) ), Ordering::Equal ); mem::swap( less_focus.index_mut(less_position), greater_focus.index_mut(greater_position), ); less_position += 1; greater_position += 1; } } // Now we have partitioned both sides correctly, we just have to recurse now do_quicksort(less_focus, cmp, rng); if !greater_focus.is_empty() { do_quicksort(greater_focus, cmp, rng); } } pub(crate) fn quicksort(vector: FocusMut<'_, A>, cmp: &F) where A: Clone, F: Fn(&A, &A) -> Ordering, { let mut rng = rand_xoshiro::Xoshiro256Plus::seed_from_u64(0); do_quicksort(vector, cmp, &mut rng); } #[cfg(test)] mod test { use super::*; use crate::test::is_sorted; use crate::vector::proptest::vector; use ::proptest::num::i32; use ::proptest::proptest; proptest! { #[test] fn test_quicksort(ref input in vector(i32::ANY, 0..10000)) { let mut vec = input.clone(); let len = vec.len(); if len > 1 { quicksort(vec.focus_mut(), &Ord::cmp); } assert!(is_sorted(vec)); } } } im-rc-15.0.0/src/sync.rs010064400017500001750000000032031365756323600131540ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. pub(crate) use self::lock::Lock; #[cfg(threadsafe)] mod lock { use std::sync::{Arc, Mutex, MutexGuard}; /// Thread safe lock: just wraps a `Mutex`. pub(crate) struct Lock { lock: Arc>, } impl Lock { pub(crate) fn new(value: A) -> Self { Lock { lock: Arc::new(Mutex::new(value)), } } #[inline] pub(crate) fn lock(&mut self) -> Option> { self.lock.lock().ok() } } impl Clone for Lock { fn clone(&self) -> Self { Lock { lock: self.lock.clone(), } } } } #[cfg(not(threadsafe))] mod lock { use std::cell::{RefCell, RefMut}; use std::rc::Rc; /// Single threaded lock: a `RefCell` so we should safely panic if somehow /// trying to access the stored data twice from the same thread. pub(crate) struct Lock { lock: Rc>, } impl Lock { pub(crate) fn new(value: A) -> Self { Lock { lock: Rc::new(RefCell::new(value)), } } #[inline] pub(crate) fn lock(&mut self) -> Option> { self.lock.try_borrow_mut().ok() } } impl Clone for Lock { fn clone(&self) -> Self { Lock { lock: self.lock.clone(), } } } } im-rc-15.0.0/src/test.rs010064400017500001750000000035551365756323600131710ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use metrohash::MetroHash64; use std::hash::{BuildHasher, Hasher}; use std::marker::PhantomData; use typenum::{Unsigned, U64}; pub(crate) fn is_sorted(l: I) -> bool where I: IntoIterator, A: Ord, { let mut it = l.into_iter().peekable(); loop { match (it.next(), it.peek()) { (_, None) => return true, (Some(ref a), Some(b)) if a > b => return false, _ => (), } } } pub(crate) struct LolHasher { state: u64, shift: usize, size: PhantomData, } impl LolHasher { fn feed_me(&mut self, byte: u8) { self.state ^= u64::from(byte) << self.shift; self.shift += 8; if self.shift >= 64 { self.shift = 0; } } } impl Hasher for LolHasher { fn write(&mut self, bytes: &[u8]) { for byte in bytes { self.feed_me(*byte) } } fn finish(&self) -> u64 { if N::USIZE == 64 { self.state } else { self.state & ((1 << N::USIZE) - 1) } } } impl Default for LolHasher { fn default() -> Self { LolHasher { state: 0, shift: 0, size: PhantomData, } } } pub(crate) struct MetroHashBuilder { seed: u64, } impl MetroHashBuilder { pub(crate) fn new(seed: u64) -> Self { MetroHashBuilder { seed } } pub(crate) fn seed(&self) -> u64 { self.seed } } impl BuildHasher for MetroHashBuilder { type Hasher = MetroHash64; fn build_hasher(&self) -> Self::Hasher { MetroHash64::with_seed(self.seed) } } im-rc-15.0.0/src/tests/hashset.rs010064400017500001750000000045611365756323600150110ustar0000000000000000#![allow(clippy::unit_arg)] use std::collections::HashSet as NatSet; use std::fmt::{Debug, Error, Formatter, Write}; use std::hash::Hash; use crate::HashSet; use proptest::proptest; use proptest_derive::Arbitrary; #[derive(Arbitrary, Debug)] enum Action { Insert(A), Remove(A), } #[derive(Arbitrary)] struct Actions(Vec>) where A: Hash + Eq + Clone; impl Debug for Actions where A: Hash + Eq + Debug + Clone, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let mut out = String::new(); let mut expected = NatSet::new(); writeln!(out, "let mut set = HashSet::new();")?; for action in &self.0 { match action { Action::Insert(ref value) => { expected.insert(value.clone()); writeln!(out, "set.insert({:?});", value)?; } Action::Remove(ref value) => { expected.remove(value); writeln!(out, "set.remove({:?});", value)?; } } } writeln!( out, "let expected = vec!{:?};", expected.into_iter().collect::>() )?; writeln!(out, "assert_eq!(HashSet::from(expected), set);")?; write!(f, "{}", super::code_fmt(&out)) } } proptest! { #[test] fn comprehensive(actions: Actions) { let mut set = HashSet::new(); let mut nat = NatSet::new(); for action in actions.0 { match action { Action::Insert(value) => { let len = nat.len() + if nat.contains(&value) { 0 } else { 1 }; nat.insert(value); set.insert(value); assert_eq!(len, set.len()); } Action::Remove(value) => { let len = nat.len() - if nat.contains(&value) { 1 } else { 0 }; nat.remove(&value); set.remove(&value); assert_eq!(len, set.len()); } } assert_eq!(nat.len(), set.len()); assert_eq!(HashSet::from(nat.clone()), set); } } } im-rc-15.0.0/src/tests/mod.rs010064400017500001750000000015401365756323600141230ustar0000000000000000mod hashset; mod ordset; mod vector; fn code_fmt(code: &str) -> String { // use syntect::easy::HighlightLines; // use syntect::highlighting::{Style, ThemeSet}; // use syntect::parsing::SyntaxSet; // use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings}; // // let ps = SyntaxSet::load_defaults_newlines(); // let ts = ThemeSet::load_defaults(); // let syntax = ps.find_syntax_by_extension("rs").unwrap(); // let mut h = HighlightLines::new(syntax, &ts.themes["base16-ocean.dark"]); // let mut out = String::from("\n\n"); // for line in LinesWithEndings::from(&code) { // let ranges: Vec<(Style, &str)> = h.highlight(line, &ps); // let escaped = as_24_bit_terminal_escaped(&ranges[..], false); // out += &escaped; // } // out += "\n\x1b[0m"; // out code.to_string() } im-rc-15.0.0/src/tests/ordset.rs010064400017500001750000000045661365756323600146570ustar0000000000000000#![allow(clippy::unit_arg)] use std::collections::BTreeSet; use std::fmt::{Debug, Error, Formatter, Write}; use crate::OrdSet; use proptest::proptest; use proptest_derive::Arbitrary; #[derive(Arbitrary, Debug)] enum Action { Insert(A), Remove(A), } #[derive(Arbitrary)] struct Actions(Vec>) where A: Ord + Clone; impl Debug for Actions where A: Ord + Debug + Clone, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let mut out = String::new(); let mut expected = BTreeSet::new(); writeln!(out, "let mut set = OrdSet::new();")?; for action in &self.0 { match action { Action::Insert(ref value) => { expected.insert(value.clone()); writeln!(out, "set.insert({:?});", value)?; } Action::Remove(ref value) => { expected.remove(value); writeln!(out, "set.remove({:?});", value)?; } } } writeln!( out, "let expected = vec!{:?};", expected.into_iter().collect::>() )?; writeln!(out, "assert_eq!(OrdSet::from(expected), set);")?; write!(f, "{}", super::code_fmt(&out)) } } proptest! { #[test] fn comprehensive(actions: Actions) { let mut set = OrdSet::new(); let mut nat = BTreeSet::new(); for action in actions.0 { match action { Action::Insert(value) => { let len = nat.len() + if nat.contains(&value) { 0 } else { 1 }; nat.insert(value); set.insert(value); assert_eq!(len, set.len()); } Action::Remove(value) => { let len = nat.len() - if nat.contains(&value) { 1 } else { 0 }; nat.remove(&value); set.remove(&value); assert_eq!(len, set.len()); } } assert_eq!(nat.len(), set.len()); assert_eq!(OrdSet::from(nat.clone()), set); assert!(nat.iter().eq(set.iter())); } } } im-rc-15.0.0/src/tests/vector.rs010064400017500001750000000205401365756323600146470ustar0000000000000000#![allow(clippy::unit_arg)] use std::fmt::{Debug, Error, Formatter, Write}; use std::iter::FromIterator; use crate::Vector; use proptest::proptest; use proptest_derive::Arbitrary; #[derive(Arbitrary, Debug)] enum Action { PushFront(A), PushBack(A), PopFront, PopBack, Insert(usize, A), Remove(usize), JoinLeft(Vec), JoinRight(Vec), SplitLeft(usize), SplitRight(usize), } #[derive(Arbitrary)] struct Actions(Vec>) where A: Clone; impl Debug for Actions where A: Debug + Clone, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let mut out = String::new(); let mut expected = vec![]; writeln!(out, "let mut vec = Vector::new();")?; for action in &self.0 { match action { Action::PushFront(ref value) => { expected.insert(0, value.clone()); writeln!(out, "vec.push_front({:?});", value)? } Action::PushBack(ref value) => { expected.push(value.clone()); writeln!(out, "vec.push_back({:?});", value)? } Action::PopFront => { if !expected.is_empty() { expected.remove(0); } writeln!(out, "vec.pop_front();")? } Action::PopBack => { expected.pop(); writeln!(out, "vec.pop_back();")? } Action::Insert(ref index, ref value) => { let index = cap_index(expected.len(), *index); expected.insert(index, value.clone()); writeln!(out, "vec.insert({:?}, {:?});", index, value)? } Action::Remove(ref index) => { if !expected.is_empty() { let index = cap_index(expected.len(), *index); expected.remove(index); writeln!(out, "vec.remove({:?})", index)? } else { continue; } } Action::JoinLeft(ref vec) => { let mut vec_new = vec.clone(); vec_new.append(&mut expected); expected = vec_new; writeln!( out, "let mut vec_new = Vector::from(vec!{:?}); // size {:?}", vec, vec.len() )?; writeln!(out, "vec_new.append(vec);")?; writeln!(out, "vec = vec_new;")? } Action::JoinRight(ref vec) => { expected.append(&mut vec.clone()); writeln!( out, "vec.append(Vector::from(vec!{:?})); // size {:?}", vec, vec.len() )? } Action::SplitLeft(ref index) => { let index = cap_index(expected.len(), *index); expected.truncate(index); writeln!(out, "vec.split_off({:?});", index)? } Action::SplitRight(ref index) => { let index = cap_index(expected.len(), *index); expected = expected.split_off(index); writeln!(out, "vec = vec.split_off({:?});", index)? } } writeln!(out, "// len = {:?}", expected.len())?; } writeln!(out, "let expected = vec!{:?};", expected)?; writeln!(out, "assert_eq!(Vector::from(expected), vec);")?; write!(f, "{}", super::code_fmt(&out)) } } fn cap_index(len: usize, index: usize) -> usize { if len == 0 { 0 } else { index % len } } proptest! { #[test] fn comprehensive(actions: Actions) { let mut vec = Vector::new(); let mut nat = Vec::new(); vec.assert_invariants(); for action in actions.0 { match action { Action::PushFront(value) => { let len = vec.len(); nat.insert(0, value); vec.push_front(value); assert_eq!(len + 1, vec.len()); } Action::PushBack(value) => { let len = vec.len(); nat.push(value); vec.push_back(value); assert_eq!(len + 1, vec.len()); } Action::PopFront => { if vec.is_empty() { assert_eq!(None, vec.pop_front()); } else { let len = vec.len(); assert_eq!(nat.remove(0), vec.pop_front().unwrap()); assert_eq!(len - 1, vec.len()); } } Action::PopBack => { if vec.is_empty() { assert_eq!(None, vec.pop_back()); } else { let len = vec.len(); assert_eq!(nat.pop(), vec.pop_back()); assert_eq!(len - 1, vec.len()); } } Action::Insert(index, value) => { let index = cap_index(vec.len(), index); let len = vec.len(); nat.insert(index, value); vec.insert(index, value); assert_eq!(len + 1, vec.len()); } Action::Remove(index) => { if vec.is_empty() { continue; } let index = cap_index(vec.len(), index); let len = vec.len(); assert_eq!(nat.remove(index), vec.remove(index)); assert_eq!(len - 1, vec.len()); } Action::JoinLeft(mut new_nat) => { let mut new_vec = Vector::from_iter(new_nat.iter().cloned()); let add_len = new_nat.len(); let len = vec.len(); new_vec.append(vec); vec = new_vec; new_nat.append(&mut nat); nat = new_nat; assert_eq!(len + add_len, vec.len()); } Action::JoinRight(mut new_nat) => { let new_vec = Vector::from_iter(new_nat.iter().cloned()); let add_len = new_nat.len(); let len = vec.len(); vec.append(new_vec); nat.append(&mut new_nat); assert_eq!(len + add_len, vec.len()); } Action::SplitLeft(index) => { let index = cap_index(vec.len(), index); let len = vec.len(); let vec_right = vec.split_off(index); let nat_right = nat.split_off(index); assert_eq!(index, vec.len()); assert_eq!(len - index, vec_right.len()); assert_eq!(Vector::from_iter(nat_right.iter().cloned()), vec_right); } Action::SplitRight(index) => { let index = cap_index(vec.len(), index); let len = vec.len(); let vec_right = vec.split_off(index); let nat_right = nat.split_off(index); assert_eq!(index, vec.len()); assert_eq!(len - index, vec_right.len()); assert_eq!(Vector::from_iter(nat.iter().cloned()), vec); vec = vec_right; nat = nat_right; } } vec.assert_invariants(); assert_eq!(nat.len(),vec.len()); assert_eq!(Vector::from_iter(nat.iter().cloned()), vec); } } } #[test] fn test_inserts() { const N: usize = 2000; let mut v = Vector::new(); for i in 0..N { v.insert(v.len() / 2, i); } let mut rv: Vec = Vec::new(); rv.extend((0..N).skip(1).step_by(2)); rv.extend((0..N).step_by(2).rev()); assert_eq!(Vector::from_iter(rv.iter().cloned()), v); } im-rc-15.0.0/src/util.rs010064400017500001750000000074131365756323600131640ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Every codebase needs a `util` module. use std::cmp::Ordering; use std::ops::{Bound, IndexMut, Range, RangeBounds}; use std::ptr; #[cfg(feature = "pool")] pub(crate) use refpool::{PoolClone, PoolDefault}; // The `Ref` type is an alias for either `Rc` or `Arc`, user's choice. // `Arc` without refpool #[cfg(all(threadsafe))] pub(crate) use crate::fakepool::{Arc as PoolRef, Pool, PoolClone, PoolDefault}; // `Ref` == `Arc` when threadsafe #[cfg(threadsafe)] pub(crate) type Ref = std::sync::Arc; // `Rc` without refpool #[cfg(all(not(threadsafe), not(feature = "pool")))] pub(crate) use crate::fakepool::{Pool, PoolClone, PoolDefault, Rc as PoolRef}; // `Rc` with refpool #[cfg(all(not(threadsafe), feature = "pool"))] pub(crate) type PoolRef = refpool::PoolRef; #[cfg(all(not(threadsafe), feature = "pool"))] pub(crate) type Pool = refpool::Pool; // `Ref` == `Rc` when not threadsafe #[cfg(not(threadsafe))] pub(crate) type Ref = std::rc::Rc; pub(crate) fn clone_ref(r: Ref) -> A where A: Clone, { Ref::try_unwrap(r).unwrap_or_else(|r| (*r).clone()) } #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Side { Left, Right, } /// Swap two values of anything implementing `IndexMut`. /// /// Like `slice::swap`, but more generic. #[allow(unsafe_code)] pub(crate) fn swap_indices(vector: &mut V, a: usize, b: usize) where V: IndexMut, V::Output: Sized, { if a == b { return; } // so sorry, but there's no implementation for this in std that's // sufficiently generic let pa: *mut V::Output = &mut vector[a]; let pb: *mut V::Output = &mut vector[b]; unsafe { ptr::swap(pa, pb); } } #[allow(dead_code)] pub(crate) fn linear_search_by<'a, A, I, F>(iterable: I, mut cmp: F) -> Result where A: 'a, I: IntoIterator, F: FnMut(&A) -> Ordering, { let mut pos = 0; for value in iterable { match cmp(value) { Ordering::Equal => return Ok(pos), Ordering::Greater => return Err(pos), Ordering::Less => {} } pos += 1; } Err(pos) } pub(crate) fn to_range(range: &R, right_unbounded: usize) -> Range where R: RangeBounds, { let start_index = match range.start_bound() { Bound::Included(i) => *i, Bound::Excluded(i) => *i + 1, Bound::Unbounded => 0, }; let end_index = match range.end_bound() { Bound::Included(i) => *i + 1, Bound::Excluded(i) => *i, Bound::Unbounded => right_unbounded, }; start_index..end_index } macro_rules! def_pool { ($name:ident<$($arg:tt),*>, $pooltype:ty) => { /// A memory pool for the appropriate node type. pub struct $name<$($arg,)*>(Pool<$pooltype>); impl<$($arg,)*> $name<$($arg,)*> { /// Create a new pool with the given size. pub fn new(size: usize) -> Self { Self(Pool::new(size)) } /// Fill the pool with preallocated chunks. pub fn fill(&self) { self.0.fill(); } ///Get the current size of the pool. pub fn pool_size(&self) -> usize { self.0.get_pool_size() } } impl<$($arg,)*> Default for $name<$($arg,)*> { fn default() -> Self { Self::new($crate::config::POOL_SIZE) } } impl<$($arg,)*> Clone for $name<$($arg,)*> { fn clone(&self) -> Self { Self(self.0.clone()) } } }; } im-rc-15.0.0/src/vector/focus.rs010064400017500001750000000737771365756323600146500ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::mem::{replace, swap}; use std::ops::{Range, RangeBounds}; use std::ptr::null; use std::sync::atomic::{AtomicPtr, Ordering}; use crate::nodes::chunk::Chunk; use crate::sync::Lock; use crate::util::{to_range, PoolRef, Ref}; use crate::vector::{ Iter, IterMut, RRBPool, Vector, VectorInner::{Full, Inline, Single}, RRB, }; /// Focused indexing over a [`Vector`][Vector]. /// /// By remembering the last tree node accessed through an index lookup and the /// path we took to get there, we can speed up lookups for adjacent indices /// tremendously. Lookups on indices in the same node are instantaneous, and /// lookups on sibling nodes are also very fast. /// /// A `Focus` can also be used as a restricted view into a vector, using the /// [`narrow`][narrow] and [`split_at`][split_at] methods. /// /// # When should I use a `Focus` for better performance? /// /// `Focus` is useful when you need to perform a large number of index lookups /// that are more likely than not to be close to each other. It's usually worth /// using a `Focus` in any situation where you're batching a lot of index /// lookups together, even if they're not obviously adjacent - there's likely /// to be some performance gain for even completely random access. /// /// If you're just iterating forwards or backwards over the [`Vector`][Vector] /// in order, you're better off with a regular iterator, which, in fact, is /// implemented using a `Focus`, but provides a simpler interface. /// /// If you're just doing a very small number of index lookups, the setup cost /// for the `Focus` is probably not worth it. /// /// A `Focus` is never faster than an index lookup on a small [`Vector`][Vector] /// with a length below the internal RRB tree's branching factor of 64. /// /// # Examples /// /// This example is contrived, as the better way to iterate forwards or /// backwards over a vector is with an actual iterator. Even so, the version /// using a `Focus` should run nearly an order of magnitude faster than the /// version using index lookups at a length of 1000. It should also be noted /// that [`vector::Iter`][Iter] is actually implemented using a `Focus` behind /// the scenes, so the performance of the two should be identical. /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let mut vec: Vector = Vector::from_iter(0..1000); /// /// // Summing a vector, the slow way: /// let mut sum = 0; /// for i in 0..1000 { /// sum += *vec.get(i).unwrap(); /// } /// assert_eq!(499500, sum); /// /// // Summing a vector faster using a Focus: /// let mut sum = 0; /// let mut focus = vec.focus(); /// for i in 0..1000 { /// sum += *focus.get(i).unwrap(); /// } /// assert_eq!(499500, sum); /// /// // And the easy way, for completeness: /// let sum: i64 = vec.iter().sum(); /// assert_eq!(499500, sum); /// ``` /// /// [Vector]: enum.Vector.html /// [Iter]: struct.Iter.html /// [narrow]: #method.narrow /// [split_at]: #method.split_at pub enum Focus<'a, A> { #[doc(hidden)] Single(&'a [A]), #[doc(hidden)] Full(TreeFocus), } impl<'a, A> Focus<'a, A> where A: Clone + 'a, { /// Construct a `Focus` for a [`Vector`][Vector]. /// /// [Vector]: enum.Vector.html pub fn new(vector: &'a Vector) -> Self { match &vector.vector { Inline(_, chunk) => Focus::Single(chunk), Single(_, chunk) => Focus::Single(chunk), Full(_, tree) => Focus::Full(TreeFocus::new(tree)), } } /// Get the length of the focused [`Vector`][Vector]. /// /// [Vector]: enum.Vector.html pub fn len(&self) -> usize { match self { Focus::Single(chunk) => chunk.len(), Focus::Full(tree) => tree.len(), } } /// Test if the focused [`Vector`][Vector] is empty. /// /// [Vector]: enum.Vector.html pub fn is_empty(&self) -> bool { self.len() == 0 } /// Get a reference to the value at a given index. pub fn get(&mut self, index: usize) -> Option<&A> { match self { Focus::Single(chunk) => chunk.get(index), Focus::Full(tree) => tree.get(index), } } /// Get a reference to the value at a given index. /// /// Panics if the index is out of bounds. pub fn index(&mut self, index: usize) -> &A { self.get(index).expect("index out of bounds") } /// Get the chunk for the given index. /// /// This gives you a reference to the leaf node that contains the index, /// along with its start and end indices. pub fn chunk_at(&mut self, index: usize) -> (Range, &[A]) { let len = self.len(); if index >= len { panic!("vector::Focus::chunk_at: index out of bounds"); } match self { Focus::Single(chunk) => (0..len, chunk), Focus::Full(tree) => tree.get_chunk(index), } } /// Narrow the focus onto a subslice of the vector. /// /// `Focus::narrow(range)` has the same effect as `&slice[range]`, without /// actually modifying the underlying vector. /// /// Panics if the range isn't fully inside the current focus. /// /// ## Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let vec = Vector::from_iter(0..1000); /// let narrowed = vec.focus().narrow(100..200); /// let narrowed_vec = narrowed.into_iter().cloned().collect(); /// assert_eq!(Vector::from_iter(100..200), narrowed_vec); /// ``` /// /// [slice::split_at]: https://doc.rust-lang.org/std/primitive.slice.html#method.split_at /// [Vector::split_at]: enum.Vector.html#method.split_at pub fn narrow(self, range: R) -> Self where R: RangeBounds, { let r = to_range(&range, self.len()); if r.start >= r.end || r.start >= self.len() { panic!("vector::Focus::narrow: range out of bounds"); } match self { Focus::Single(chunk) => Focus::Single(&chunk[r]), Focus::Full(tree) => Focus::Full(tree.narrow(r)), } } /// Split the focus into two. /// /// Given an index `index`, consume the focus and produce two new foci, the /// left onto indices `0..index`, and the right onto indices `index..N` /// where `N` is the length of the current focus. /// /// Panics if the index is out of bounds. /// /// This is the moral equivalent of [`slice::split_at`][slice::split_at], in /// that it leaves the underlying data structure unchanged, unlike /// [`Vector::split_at`][Vector::split_at]. /// /// ## Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let vec = Vector::from_iter(0..1000); /// let (left, right) = vec.focus().split_at(500); /// let left_vec = left.into_iter().cloned().collect(); /// let right_vec = right.into_iter().cloned().collect(); /// assert_eq!(Vector::from_iter(0..500), left_vec); /// assert_eq!(Vector::from_iter(500..1000), right_vec); /// ``` /// /// [slice::split_at]: https://doc.rust-lang.org/std/primitive.slice.html#method.split_at /// [Vector::split_at]: enum.Vector.html#method.split_at pub fn split_at(self, index: usize) -> (Self, Self) { if index >= self.len() { panic!("vector::Focus::split_at: index out of bounds"); } match self { Focus::Single(chunk) => { let (left, right) = chunk.split_at(index); (Focus::Single(left), Focus::Single(right)) } Focus::Full(tree) => { let (left, right) = tree.split_at(index); (Focus::Full(left), Focus::Full(right)) } } } } impl<'a, A> IntoIterator for Focus<'a, A> where A: Clone + 'a, { type Item = &'a A; type IntoIter = Iter<'a, A>; fn into_iter(self) -> Self::IntoIter { Iter::from_focus(self) } } impl<'a, A> Clone for Focus<'a, A> where A: Clone + 'a, { fn clone(&self) -> Self { match self { Focus::Single(chunk) => Focus::Single(chunk), Focus::Full(tree) => Focus::Full(tree.clone()), } } } pub struct TreeFocus { tree: RRB, view: Range, middle_range: Range, target_range: Range, target_ptr: *const Chunk, } impl Clone for TreeFocus { fn clone(&self) -> Self { let tree = self.tree.clone(); TreeFocus { view: self.view.clone(), middle_range: self.middle_range.clone(), target_range: 0..0, target_ptr: null(), tree, } } } #[allow(unsafe_code)] #[cfg(threadsafe)] unsafe impl Send for TreeFocus {} #[allow(unsafe_code)] #[cfg(threadsafe)] unsafe impl Sync for TreeFocus {} #[inline] fn contains(range: &Range, index: &A) -> bool { *index >= range.start && *index < range.end } impl TreeFocus where A: Clone, { fn new(tree: &RRB) -> Self { let middle_start = tree.outer_f.len() + tree.inner_f.len(); let middle_end = middle_start + tree.middle.len(); TreeFocus { tree: tree.clone(), view: 0..tree.length, middle_range: middle_start..middle_end, target_range: 0..0, target_ptr: null(), } } fn len(&self) -> usize { self.view.end - self.view.start } fn narrow(self, mut view: Range) -> Self { view.start += self.view.start; view.end += self.view.start; TreeFocus { view, middle_range: self.middle_range.clone(), target_range: 0..0, target_ptr: null(), tree: self.tree, } } fn split_at(self, index: usize) -> (Self, Self) { let len = self.len(); let left = self.clone().narrow(0..index); let right = self.narrow(index..len); (left, right) } fn physical_index(&self, index: usize) -> usize { debug_assert!(index < self.view.end); self.view.start + index } fn logical_range(&self, range: &Range) -> Range { (range.start - self.view.start)..(range.end - self.view.start) } fn set_focus(&mut self, index: usize) { if index < self.middle_range.start { let outer_len = self.tree.outer_f.len(); if index < outer_len { self.target_range = 0..outer_len; self.target_ptr = &*self.tree.outer_f; } else { self.target_range = outer_len..self.middle_range.start; self.target_ptr = &*self.tree.inner_f; } } else if index >= self.middle_range.end { let outer_start = self.middle_range.end + self.tree.inner_b.len(); if index < outer_start { self.target_range = self.middle_range.end..outer_start; self.target_ptr = &*self.tree.inner_b; } else { self.target_range = outer_start..self.tree.length; self.target_ptr = &*self.tree.outer_b; } } else { let tree_index = index - self.middle_range.start; let (range, ptr) = self .tree .middle .lookup_chunk(self.tree.middle_level, 0, tree_index); self.target_range = (range.start + self.middle_range.start)..(range.end + self.middle_range.start); self.target_ptr = ptr; } } #[allow(unsafe_code)] fn get_focus(&self) -> &Chunk { unsafe { &*self.target_ptr } } pub fn get(&mut self, index: usize) -> Option<&A> { if index >= self.len() { return None; } let phys_index = self.physical_index(index); if !contains(&self.target_range, &phys_index) { self.set_focus(phys_index); } let target_phys_index = phys_index - self.target_range.start; Some(&self.get_focus()[target_phys_index]) } pub fn get_chunk(&mut self, index: usize) -> (Range, &[A]) { let phys_index = self.physical_index(index); if !contains(&self.target_range, &phys_index) { self.set_focus(phys_index); } let mut slice: &[A] = self.get_focus(); let mut left = 0; let mut right = 0; if self.target_range.start < self.view.start { left = self.view.start - self.target_range.start; } if self.target_range.end > self.view.end { right = self.target_range.end - self.view.end; } slice = &slice[left..(slice.len() - right)]; let phys_range = (self.target_range.start + left)..(self.target_range.end - right); (self.logical_range(&phys_range), slice) } } /// A mutable version of [`Focus`][Focus]. /// /// See [`Focus`][Focus] for more details. /// /// You can only build one `FocusMut` at a time for a vector, effectively /// keeping a lock on the vector until you're done with the focus, which relies /// on the structure of the vector not changing while it exists. /// /// ```rust,compile_fail /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let mut vec = Vector::from_iter(0..1000); /// let focus1 = vec.focus_mut(); /// // Fails here in 2015 edition because you're creating /// // two mutable references to the same thing. /// let focus2 = vec.focus_mut(); /// // Fails here in 2018 edition because creating focus2 /// // made focus1's lifetime go out of scope. /// assert_eq!(Some(&0), focus1.get(0)); /// ``` /// /// On the other hand, you can split that one focus into multiple sub-focuses, /// which is safe because they can't overlap: /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let mut vec = Vector::from_iter(0..1000); /// let focus = vec.focus_mut(); /// let (mut left, mut right) = focus.split_at(500); /// assert_eq!(Some(&0), left.get(0)); /// assert_eq!(Some(&500), right.get(0)); /// ``` /// /// These sub-foci also work as a lock on the vector, even if the focus they /// were created from goes out of scope. /// /// ```rust,compile_fail /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let mut vec = Vector::from_iter(0..1000); /// let (left, right) = { /// let focus = vec.focus_mut(); /// focus.split_at(500) /// }; /// // `left` and `right` are still in scope even if `focus` isn't, so we can't /// // create another focus: /// let focus2 = vec.focus_mut(); /// assert_eq!(Some(&0), left.get(0)); /// ``` /// /// [Focus]: enum.Focus.html pub enum FocusMut<'a, A> { #[doc(hidden)] Single(RRBPool, &'a mut [A]), #[doc(hidden)] Full(RRBPool, TreeFocusMut<'a, A>), } impl<'a, A> FocusMut<'a, A> where A: Clone + 'a, { /// Construct a `FocusMut` for a `Vector`. pub fn new(vector: &'a mut Vector) -> Self { match &mut vector.vector { Inline(pool, chunk) => FocusMut::Single(pool.clone(), chunk), Single(pool, chunk) => FocusMut::Single( pool.clone(), PoolRef::make_mut(&pool.value_pool, chunk).as_mut_slice(), ), Full(pool, tree) => FocusMut::Full(pool.clone(), TreeFocusMut::new(tree)), } } /// Get the length of the focused `Vector`. pub fn len(&self) -> usize { match self { FocusMut::Single(_, chunk) => chunk.len(), FocusMut::Full(_, tree) => tree.len(), } } /// Test if the focused `Vector` is empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Get a reference to the value at a given index. pub fn get(&mut self, index: usize) -> Option<&A> { self.get_mut(index).map(|r| &*r) } /// Get a mutable reference to the value at a given index. pub fn get_mut(&mut self, index: usize) -> Option<&mut A> { match self { FocusMut::Single(_, chunk) => chunk.get_mut(index), FocusMut::Full(pool, tree) => tree.get(pool, index), } } /// Get a reference to the value at a given index. /// /// Panics if the index is out of bounds. pub fn index(&mut self, index: usize) -> &A { &*self.index_mut(index) } /// Get a mutable reference to the value at a given index. /// /// Panics if the index is out of bounds. #[allow(clippy::should_implement_trait)] // would if I could pub fn index_mut(&mut self, index: usize) -> &mut A { self.get_mut(index).expect("index out of bounds") } /// Update the value at a given index. /// /// Returns `None` if the index is out of bounds, or the replaced value /// otherwise. pub fn set(&mut self, index: usize, value: A) -> Option { match self.get_mut(index) { Some(ref mut pos) => Some(replace(pos, value)), None => None, } } /// Swap the values at two given indices. /// /// Panics if either index is out of bounds. /// /// If the indices are equal, this function returns without doing anything. pub fn swap(&mut self, a: usize, b: usize) { if a == b { return; } self.pair(a, b, |left, right| swap(left, right)); } /// Lookup two indices simultaneously and run a function over them. /// /// Useful because the borrow checker won't let you have more than one /// mutable reference into the same data structure at any given time. /// /// Panics if either index is out of bounds, or if they are the same index. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let mut vec = vector![1, 2, 3, 4, 5]; /// vec.focus_mut().pair(1, 3, |a, b| *a += *b); /// assert_eq!(vector![1, 6, 3, 4, 5], vec); /// ``` #[allow(unsafe_code)] pub fn pair(&mut self, a: usize, b: usize, mut f: F) -> B where F: FnMut(&mut A, &mut A) -> B, { if a == b { panic!("vector::FocusMut::pair: indices cannot be equal!"); } let pa: *mut A = self.index_mut(a); let pb: *mut A = self.index_mut(b); unsafe { f(&mut *pa, &mut *pb) } } /// Lookup three indices simultaneously and run a function over them. /// /// Useful because the borrow checker won't let you have more than one /// mutable reference into the same data structure at any given time. /// /// Panics if any index is out of bounds, or if any indices are equal. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let mut vec = vector![1, 2, 3, 4, 5]; /// vec.focus_mut().triplet(0, 2, 4, |a, b, c| *a += *b + *c); /// assert_eq!(vector![9, 2, 3, 4, 5], vec); /// ``` #[allow(unsafe_code)] pub fn triplet(&mut self, a: usize, b: usize, c: usize, mut f: F) -> B where F: FnMut(&mut A, &mut A, &mut A) -> B, { if a == b || b == c || a == c { panic!("vector::FocusMut::triplet: indices cannot be equal!"); } let pa: *mut A = self.index_mut(a); let pb: *mut A = self.index_mut(b); let pc: *mut A = self.index_mut(c); unsafe { f(&mut *pa, &mut *pb, &mut *pc) } } /// Get the chunk for the given index. /// /// This gives you a reference to the leaf node that contains the index, /// along with its start and end indices. pub fn chunk_at(&mut self, index: usize) -> (Range, &mut [A]) { let len = self.len(); if index >= len { panic!("vector::FocusMut::chunk_at: index out of bounds"); } match self { FocusMut::Single(_, chunk) => (0..len, chunk), FocusMut::Full(pool, tree) => { let (range, chunk) = tree.get_chunk(pool, index); (range, chunk) } } } /// Narrow the focus onto a subslice of the vector. /// /// `FocusMut::narrow(range)` has the same effect as `&slice[range]`, without /// actually modifying the underlying vector. /// /// Panics if the range isn't fully inside the current focus. /// /// ## Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let mut vec = Vector::from_iter(0..1000); /// let narrowed = vec.focus_mut().narrow(100..200); /// let narrowed_vec = narrowed.unmut().into_iter().cloned().collect(); /// assert_eq!(Vector::from_iter(100..200), narrowed_vec); /// ``` /// /// [slice::split_at]: https://doc.rust-lang.org/std/primitive.slice.html#method.split_at /// [Vector::split_at]: enum.Vector.html#method.split_at pub fn narrow(self, range: R) -> Self where R: RangeBounds, { let r = to_range(&range, self.len()); if r.start > r.end || r.start > self.len() { panic!("vector::FocusMut::narrow: range out of bounds"); } match self { FocusMut::Single(pool, chunk) => FocusMut::Single(pool, &mut chunk[r]), FocusMut::Full(pool, tree) => FocusMut::Full(pool, tree.narrow(r)), } } /// Split the focus into two. /// /// Given an index `index`, consume the focus and produce two new foci, the /// left onto indices `0..index`, and the right onto indices `index..N` /// where `N` is the length of the current focus. /// /// Panics if the index is out of bounds. /// /// This is the moral equivalent of [`slice::split_at`][slice::split_at], in /// that it leaves the underlying data structure unchanged, unlike /// [`Vector::split_at`][Vector::split_at]. /// /// ## Examples /// /// ```rust /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # use std::iter::FromIterator; /// let mut vec = Vector::from_iter(0..1000); /// { /// let (left, right) = vec.focus_mut().split_at(500); /// for ptr in left { /// *ptr += 100; /// } /// for ptr in right { /// *ptr -= 100; /// } /// } /// let expected = Vector::from_iter(100..600) /// + Vector::from_iter(400..900); /// assert_eq!(expected, vec); /// ``` /// /// [slice::split_at]: https://doc.rust-lang.org/std/primitive.slice.html#method.split_at /// [Vector::split_at]: enum.Vector.html#method.split_at #[allow(clippy::redundant_clone)] pub fn split_at(self, index: usize) -> (Self, Self) { if index > self.len() { panic!("vector::FocusMut::split_at: index out of bounds"); } match self { FocusMut::Single(pool, chunk) => { let (left, right) = chunk.split_at_mut(index); ( FocusMut::Single(pool.clone(), left), FocusMut::Single(pool, right), ) } FocusMut::Full(pool, tree) => { let (left, right) = tree.split_at(index); ( FocusMut::Full(pool.clone(), left), FocusMut::Full(pool, right), ) } } } /// Convert a `FocusMut` into a `Focus`. pub fn unmut(self) -> Focus<'a, A> { match self { FocusMut::Single(_, chunk) => Focus::Single(chunk), FocusMut::Full(_, mut tree) => Focus::Full(TreeFocus { tree: { let t = tree.tree.lock().unwrap(); (*t).clone() }, view: tree.view.clone(), middle_range: tree.middle_range.clone(), target_range: 0..0, target_ptr: null(), }), } } } impl<'a, A> IntoIterator for FocusMut<'a, A> where A: Clone + 'a, { type Item = &'a mut A; type IntoIter = IterMut<'a, A>; fn into_iter(self) -> Self::IntoIter { IterMut::from_focus(self) } } impl<'a, A> Into> for FocusMut<'a, A> where A: Clone + 'a, { fn into(self) -> Focus<'a, A> { self.unmut() } } pub struct TreeFocusMut<'a, A> { tree: Lock<&'a mut RRB>, view: Range, middle_range: Range, target_range: Range, target_ptr: AtomicPtr>, } impl<'a, A> TreeFocusMut<'a, A> where A: Clone + 'a, { fn new(tree: &'a mut RRB) -> Self { let middle_start = tree.outer_f.len() + tree.inner_f.len(); let middle_end = middle_start + tree.middle.len(); TreeFocusMut { view: 0..tree.length, tree: Lock::new(tree), middle_range: middle_start..middle_end, target_range: 0..0, target_ptr: AtomicPtr::default(), } } fn len(&self) -> usize { self.view.end - self.view.start } fn narrow(self, mut view: Range) -> Self { view.start += self.view.start; view.end += self.view.start; TreeFocusMut { view, middle_range: self.middle_range.clone(), target_range: 0..0, target_ptr: AtomicPtr::default(), tree: self.tree, } } fn split_at(self, index: usize) -> (Self, Self) { let len = self.len(); debug_assert!(index <= len); #[allow(unsafe_code)] let left = TreeFocusMut { view: self.view.start..(self.view.start + index), middle_range: self.middle_range.clone(), target_range: 0..0, target_ptr: AtomicPtr::default(), tree: self.tree.clone(), }; let right = TreeFocusMut { view: (self.view.start + index)..(self.view.start + len), middle_range: self.middle_range.clone(), target_range: 0..0, target_ptr: AtomicPtr::default(), tree: self.tree, }; (left, right) } fn physical_index(&self, index: usize) -> usize { debug_assert!(index < self.view.end); self.view.start + index } fn logical_range(&self, range: &Range) -> Range { (range.start - self.view.start)..(range.end - self.view.start) } fn set_focus(&mut self, pool: &RRBPool, index: usize) { let mut tree = self .tree .lock() .expect("im::vector::Focus::set_focus: unable to acquire exclusive lock on Vector"); if index < self.middle_range.start { let outer_len = tree.outer_f.len(); if index < outer_len { self.target_range = 0..outer_len; self.target_ptr.store( PoolRef::make_mut(&pool.value_pool, &mut tree.outer_f), Ordering::Relaxed, ); } else { self.target_range = outer_len..self.middle_range.start; self.target_ptr.store( PoolRef::make_mut(&pool.value_pool, &mut tree.inner_f), Ordering::Relaxed, ); } } else if index >= self.middle_range.end { let outer_start = self.middle_range.end + tree.inner_b.len(); if index < outer_start { self.target_range = self.middle_range.end..outer_start; self.target_ptr.store( PoolRef::make_mut(&pool.value_pool, &mut tree.inner_b), Ordering::Relaxed, ); } else { self.target_range = outer_start..tree.length; self.target_ptr.store( PoolRef::make_mut(&pool.value_pool, &mut tree.outer_b), Ordering::Relaxed, ); } } else { let tree_index = index - self.middle_range.start; let level = tree.middle_level; let middle = Ref::make_mut(&mut tree.middle); let (range, ptr) = middle.lookup_chunk_mut(pool, level, 0, tree_index); self.target_range = (range.start + self.middle_range.start)..(range.end + self.middle_range.start); self.target_ptr.store(ptr, Ordering::Relaxed); } } #[allow(unsafe_code)] fn get_focus(&mut self) -> &mut Chunk { unsafe { &mut *self.target_ptr.load(Ordering::Relaxed) } } pub fn get(&mut self, pool: &RRBPool, index: usize) -> Option<&mut A> { if index >= self.len() { return None; } let phys_index = self.physical_index(index); if !contains(&self.target_range, &phys_index) { self.set_focus(pool, phys_index); } let target_phys_index = phys_index - self.target_range.start; Some(&mut self.get_focus()[target_phys_index]) } pub fn get_chunk(&mut self, pool: &RRBPool, index: usize) -> (Range, &mut [A]) { let phys_index = self.physical_index(index); if !contains(&self.target_range, &phys_index) { self.set_focus(pool, phys_index); } let mut left = 0; let mut right = 0; if self.target_range.start < self.view.start { left = self.view.start - self.target_range.start; } if self.target_range.end > self.view.end { right = self.target_range.end - self.view.end; } let phys_range = (self.target_range.start + left)..(self.target_range.end - right); let log_range = self.logical_range(&phys_range); let slice_len = self.get_focus().len(); let slice = &mut (self.get_focus().as_mut_slice())[left..(slice_len - right)]; (log_range, slice) } } im-rc-15.0.0/src/vector/mod.rs010064400017500001750000002542021365756323600142700ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! A persistent vector. //! //! This is a sequence of elements in insertion order - if you need a //! list of things, any kind of list of things, this is what you're //! looking for. //! //! It's implemented as an [RRB vector][rrbpaper] with [smart //! head/tail chunking][chunkedseq]. In performance terms, this means //! that practically every operation is O(log n), except push/pop on //! both sides, which will be O(1) amortised, and O(log n) in the //! worst case. In practice, the push/pop operations will be //! blindingly fast, nearly on par with the native //! [`VecDeque`][VecDeque], and other operations will have decent, if //! not high, performance, but they all have more or less the same //! O(log n) complexity, so you don't need to keep their performance //! characteristics in mind - everything, even splitting and merging, //! is safe to use and never too slow. //! //! ## Performance Notes //! //! Because of the head/tail chunking technique, until you push a //! number of items above double the tree's branching factor (that's //! `self.len()` = 2 × *k* (where *k* = 64) = 128) on either side, the //! data structure is still just a handful of arrays, not yet an RRB //! tree, so you'll see performance and memory characteristics fairly //! close to [`Vec`][Vec] or [`VecDeque`][VecDeque]. //! //! This means that the structure always preallocates four chunks of //! size *k* (*k* being the tree's branching factor), equivalent to a //! [`Vec`][Vec] with an initial capacity of 256. Beyond that, it will //! allocate tree nodes of capacity *k* as needed. //! //! In addition, vectors start out as single chunks, and only expand into the //! full data structure once you go past the chunk size. This makes them //! perform identically to [`Vec`][Vec] at small sizes. //! //! [rrbpaper]: https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf //! [chunkedseq]: http://deepsea.inria.fr/pasl/chunkedseq.pdf //! [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html //! [VecDeque]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html use std::borrow::Borrow; use std::cmp::Ordering; use std::fmt::{Debug, Error, Formatter}; use std::hash::{Hash, Hasher}; use std::iter::Sum; use std::iter::{FromIterator, FusedIterator}; use std::mem::{replace, swap}; use std::ops::{Add, Index, IndexMut, RangeBounds}; use sized_chunks::InlineArray; use crate::nodes::chunk::{Chunk, CHUNK_SIZE}; use crate::nodes::rrb::{Node, PopResult, PushResult, SplitResult}; use crate::sort; use crate::util::{clone_ref, swap_indices, to_range, Pool, PoolDefault, PoolRef, Ref, Side}; use self::VectorInner::{Full, Inline, Single}; mod focus; pub use self::focus::{Focus, FocusMut}; mod pool; pub use self::pool::RRBPool; #[cfg(all(threadsafe, any(test, feature = "rayon")))] pub mod rayon; /// Construct a vector from a sequence of elements. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// # fn main() { /// assert_eq!( /// vector![1, 2, 3], /// Vector::from(vec![1, 2, 3]) /// ); /// # } /// ``` #[macro_export] macro_rules! vector { () => { $crate::vector::Vector::new() }; ( $($x:expr),* ) => {{ let mut l = $crate::vector::Vector::new(); $( l.push_back($x); )* l }}; ( $($x:expr ,)* ) => {{ let mut l = $crate::vector::Vector::new(); $( l.push_back($x); )* l }}; } /// A persistent vector. /// /// This is a sequence of elements in insertion order - if you need a list of /// things, any kind of list of things, this is what you're looking for. /// /// It's implemented as an [RRB vector][rrbpaper] with [smart head/tail /// chunking][chunkedseq]. In performance terms, this means that practically /// every operation is O(log n), except push/pop on both sides, which will be /// O(1) amortised, and O(log n) in the worst case. In practice, the push/pop /// operations will be blindingly fast, nearly on par with the native /// [`VecDeque`][VecDeque], and other operations will have decent, if not high, /// performance, but they all have more or less the same O(log n) complexity, so /// you don't need to keep their performance characteristics in mind - /// everything, even splitting and merging, is safe to use and never too slow. /// /// ## Performance Notes /// /// Because of the head/tail chunking technique, until you push a number of /// items above double the tree's branching factor (that's `self.len()` = 2 × /// *k* (where *k* = 64) = 128) on either side, the data structure is still just /// a handful of arrays, not yet an RRB tree, so you'll see performance and /// memory characteristics similar to [`Vec`][Vec] or [`VecDeque`][VecDeque]. /// /// This means that the structure always preallocates four chunks of size *k* /// (*k* being the tree's branching factor), equivalent to a [`Vec`][Vec] with /// an initial capacity of 256. Beyond that, it will allocate tree nodes of /// capacity *k* as needed. /// /// In addition, vectors start out as single chunks, and only expand into the /// full data structure once you go past the chunk size. This makes them /// perform identically to [`Vec`][Vec] at small sizes. /// /// [rrbpaper]: https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf /// [chunkedseq]: http://deepsea.inria.fr/pasl/chunkedseq.pdf /// [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html /// [VecDeque]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html pub struct Vector { vector: VectorInner, } enum VectorInner { Inline(RRBPool, InlineArray>), Single(RRBPool, PoolRef>), Full(RRBPool, RRB), } #[doc(hidden)] pub struct RRB { length: usize, middle_level: usize, outer_f: PoolRef>, inner_f: PoolRef>, middle: Ref>, inner_b: PoolRef>, outer_b: PoolRef>, } impl Clone for RRB { fn clone(&self) -> Self { RRB { length: self.length, middle_level: self.middle_level, outer_f: self.outer_f.clone(), inner_f: self.inner_f.clone(), middle: self.middle.clone(), inner_b: self.inner_b.clone(), outer_b: self.outer_b.clone(), } } } impl Vector { /// Get a reference to the memory pool this `Vector` is using. /// /// Note that if you didn't specifically construct it with a pool, you'll /// get back a reference to a pool of size 0. #[cfg_attr(not(feature = "pool"), doc = "hidden")] pub fn pool(&self) -> &RRBPool { match self.vector { Inline(ref pool, _) => pool, Single(ref pool, _) => pool, Full(ref pool, _) => pool, } } /// True if a vector is a full inline or single chunk, ie. must be promoted /// to grow further. fn needs_promotion(&self) -> bool { match &self.vector { Inline(_, chunk) if chunk.is_full() => true, Single(_, chunk) if chunk.is_full() => true, _ => false, } } /// Promote an inline to a single. fn promote_inline(&mut self) { if let Inline(pool, chunk) = &mut self.vector { self.vector = Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into())); } } /// Promote a single to a full, with the single chunk becoming inner_f, or /// promote an inline to a single. fn promote_front(&mut self) { self.vector = match &mut self.vector { Inline(pool, chunk) => { Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into())) } Single(pool, chunk) => { let chunk = chunk.clone(); Full( pool.clone(), RRB { length: chunk.len(), middle_level: 0, outer_f: PoolRef::default(&pool.value_pool), inner_f: chunk, middle: Ref::new(Node::new()), inner_b: PoolRef::default(&pool.value_pool), outer_b: PoolRef::default(&pool.value_pool), }, ) } Full(_, _) => return, } } /// Promote a single to a full, with the single chunk becoming inner_b, or /// promote an inline to a single. fn promote_back(&mut self) { self.vector = match &mut self.vector { Inline(pool, chunk) => { Single(pool.clone(), PoolRef::new(&pool.value_pool, chunk.into())) } Single(pool, chunk) => { let chunk = chunk.clone(); Full( pool.clone(), RRB { length: chunk.len(), middle_level: 0, outer_f: PoolRef::default(&pool.value_pool), inner_f: PoolRef::default(&pool.value_pool), middle: Ref::new(Node::new()), inner_b: chunk, outer_b: PoolRef::default(&pool.value_pool), }, ) } Full(_, _) => return, } } /// Construct an empty vector. #[must_use] pub fn new() -> Self { Self { vector: Inline(RRBPool::default(), InlineArray::new()), } } /// Construct an empty vector using a specific memory pool. #[cfg(feature = "pool")] #[must_use] pub fn with_pool(pool: &RRBPool) -> Self { Self { vector: Inline(pool.clone(), InlineArray::new()), } } /// Get the length of a vector. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// assert_eq!(5, vector![1, 2, 3, 4, 5].len()); /// ``` #[inline] #[must_use] pub fn len(&self) -> usize { match &self.vector { Inline(_, chunk) => chunk.len(), Single(_, chunk) => chunk.len(), Full(_, tree) => tree.length, } } /// Test whether a vector is empty. /// /// Time: O(1) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let vec = vector!["Joe", "Mike", "Robert"]; /// assert_eq!(false, vec.is_empty()); /// assert_eq!(true, Vector::::new().is_empty()); /// ``` #[inline] #[must_use] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Test whether a vector is currently inlined. /// /// Vectors small enough that their contents could be stored entirely inside /// the space of `std::mem::size_of::>()` bytes are stored inline on /// the stack instead of allocating any chunks. This method returns `true` if /// this vector is currently inlined, or `false` if it currently has chunks allocated /// on the heap. /// /// This may be useful in conjunction with [`ptr_eq()`][ptr_eq], which checks if /// two vectors' heap allocations are the same, and thus will never return `true` /// for inlined vectors. /// /// Time: O(1) /// /// [ptr_eq]: #method.ptr_eq #[inline] #[must_use] pub fn is_inline(&self) -> bool { if let Inline(_, _) = &self.vector { true } else { false } } /// Test whether two vectors refer to the same content in memory. /// /// This uses the following rules to determine equality: /// * If the two sides are references to the same vector, return true. /// * If the two sides are single chunk vectors pointing to the same chunk, return true. /// * If the two sides are full trees pointing to the same chunks, return true. /// /// This would return true if you're comparing a vector to itself, or /// if you're comparing a vector to a fresh clone of itself. The exception to this is /// if you've cloned an inline array (ie. an array with so few elements they can fit /// inside the space a `Vector` allocates for its pointers, so there are no heap allocations /// to compare). /// /// Time: O(1), or O(n) for inline vectors #[must_use] pub fn ptr_eq(&self, other: &Self) -> bool { fn cmp_chunk(left: &PoolRef>, right: &PoolRef>) -> bool { (left.is_empty() && right.is_empty()) || PoolRef::ptr_eq(left, right) } if std::ptr::eq(self, other) { return true; } match (&self.vector, &other.vector) { (Single(_, left), Single(_, right)) => cmp_chunk(left, right), (Full(_, left), Full(_, right)) => { cmp_chunk(&left.outer_f, &right.outer_f) && cmp_chunk(&left.inner_f, &right.inner_f) && cmp_chunk(&left.inner_b, &right.inner_b) && cmp_chunk(&left.outer_b, &right.outer_b) && ((left.middle.is_empty() && right.middle.is_empty()) || Ref::ptr_eq(&left.middle, &right.middle)) } _ => false, } } /// Get an iterator over a vector. /// /// Time: O(1) #[inline] #[must_use] pub fn iter(&self) -> Iter<'_, A> { Iter::new(self) } /// Get a mutable iterator over a vector. /// /// Time: O(1) #[inline] #[must_use] pub fn iter_mut(&mut self) -> IterMut<'_, A> { IterMut::new(self) } /// Get an iterator over the leaf nodes of a vector. /// /// This returns an iterator over the [`Chunk`s][Chunk] at the leaves of the /// RRB tree. These are useful for efficient parallelisation of work on /// the vector, but should not be used for basic iteration. /// /// Time: O(1) /// /// [Chunk]: ../chunk/struct.Chunk.html #[inline] #[must_use] pub fn leaves(&self) -> Chunks<'_, A> { Chunks::new(self) } /// Get a mutable iterator over the leaf nodes of a vector. // /// This returns an iterator over the [`Chunk`s][Chunk] at the leaves of the /// RRB tree. These are useful for efficient parallelisation of work on /// the vector, but should not be used for basic iteration. /// /// Time: O(1) /// /// [Chunk]: ../chunk/struct.Chunk.html #[inline] #[must_use] pub fn leaves_mut(&mut self) -> ChunksMut<'_, A> { ChunksMut::new(self) } /// Construct a [`Focus`][Focus] for a vector. /// /// Time: O(1) /// /// [Focus]: enum.Focus.html #[inline] #[must_use] pub fn focus(&self) -> Focus<'_, A> { Focus::new(self) } /// Construct a [`FocusMut`][FocusMut] for a vector. /// /// Time: O(1) /// /// [FocusMut]: enum.FocusMut.html #[inline] #[must_use] pub fn focus_mut(&mut self) -> FocusMut<'_, A> { FocusMut::new(self) } /// Get a reference to the value at index `index` in a vector. /// /// Returns `None` if the index is out of bounds. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let vec = vector!["Joe", "Mike", "Robert"]; /// assert_eq!(Some(&"Robert"), vec.get(2)); /// assert_eq!(None, vec.get(5)); /// ``` #[must_use] pub fn get(&self, index: usize) -> Option<&A> { if index >= self.len() { return None; } match &self.vector { Inline(_, chunk) => chunk.get(index), Single(_, chunk) => chunk.get(index), Full(_, tree) => { let mut local_index = index; if local_index < tree.outer_f.len() { return Some(&tree.outer_f[local_index]); } local_index -= tree.outer_f.len(); if local_index < tree.inner_f.len() { return Some(&tree.inner_f[local_index]); } local_index -= tree.inner_f.len(); if local_index < tree.middle.len() { return Some(tree.middle.index(tree.middle_level, local_index)); } local_index -= tree.middle.len(); if local_index < tree.inner_b.len() { return Some(&tree.inner_b[local_index]); } local_index -= tree.inner_b.len(); Some(&tree.outer_b[local_index]) } } } /// Get a mutable reference to the value at index `index` in a /// vector. /// /// Returns `None` if the index is out of bounds. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let mut vec = vector!["Joe", "Mike", "Robert"]; /// { /// let robert = vec.get_mut(2).unwrap(); /// assert_eq!(&mut "Robert", robert); /// *robert = "Bjarne"; /// } /// assert_eq!(vector!["Joe", "Mike", "Bjarne"], vec); /// ``` #[must_use] pub fn get_mut(&mut self, index: usize) -> Option<&mut A> { if index >= self.len() { return None; } match &mut self.vector { Inline(_, chunk) => chunk.get_mut(index), Single(pool, chunk) => PoolRef::make_mut(&pool.value_pool, chunk).get_mut(index), Full(pool, tree) => { let mut local_index = index; if local_index < tree.outer_f.len() { let outer_f = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_f); return Some(&mut outer_f[local_index]); } local_index -= tree.outer_f.len(); if local_index < tree.inner_f.len() { let inner_f = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_f); return Some(&mut inner_f[local_index]); } local_index -= tree.inner_f.len(); if local_index < tree.middle.len() { let middle = Ref::make_mut(&mut tree.middle); return Some(middle.index_mut(pool, tree.middle_level, local_index)); } local_index -= tree.middle.len(); if local_index < tree.inner_b.len() { let inner_b = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_b); return Some(&mut inner_b[local_index]); } local_index -= tree.inner_b.len(); let outer_b = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_b); Some(&mut outer_b[local_index]) } } } /// Get the first element of a vector. /// /// If the vector is empty, `None` is returned. /// /// Time: O(log n) #[inline] #[must_use] pub fn front(&self) -> Option<&A> { self.get(0) } /// Get a mutable reference to the first element of a vector. /// /// If the vector is empty, `None` is returned. /// /// Time: O(log n) #[inline] #[must_use] pub fn front_mut(&mut self) -> Option<&mut A> { self.get_mut(0) } /// Get the first element of a vector. /// /// If the vector is empty, `None` is returned. /// /// This is an alias for the [`front`][front] method. /// /// Time: O(log n) /// /// [front]: #method.front #[inline] #[must_use] pub fn head(&self) -> Option<&A> { self.get(0) } /// Get the last element of a vector. /// /// If the vector is empty, `None` is returned. /// /// Time: O(log n) #[must_use] pub fn back(&self) -> Option<&A> { if self.is_empty() { None } else { self.get(self.len() - 1) } } /// Get a mutable reference to the last element of a vector. /// /// If the vector is empty, `None` is returned. /// /// Time: O(log n) #[must_use] pub fn back_mut(&mut self) -> Option<&mut A> { if self.is_empty() { None } else { let len = self.len(); self.get_mut(len - 1) } } /// Get the last element of a vector. /// /// If the vector is empty, `None` is returned. /// /// This is an alias for the [`back`][back] method. /// /// Time: O(log n) /// /// [back]: #method.back #[inline] #[must_use] pub fn last(&self) -> Option<&A> { self.back() } /// Get the index of a given element in the vector. /// /// Searches the vector for the first occurrence of a given value, /// and returns the index of the value if it's there. Otherwise, /// it returns `None`. /// /// Time: O(n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let mut vec = vector![1, 2, 3, 4, 5]; /// assert_eq!(Some(2), vec.index_of(&3)); /// assert_eq!(None, vec.index_of(&31337)); /// ``` #[must_use] pub fn index_of(&self, value: &A) -> Option where A: PartialEq, { for (index, item) in self.iter().enumerate() { if value == item { return Some(index); } } None } /// Test if a given element is in the vector. /// /// Searches the vector for the first occurrence of a given value, /// and returns `true if it's there. If it's nowhere to be found /// in the vector, it returns `false`. /// /// Time: O(n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let mut vec = vector![1, 2, 3, 4, 5]; /// assert_eq!(true, vec.contains(&3)); /// assert_eq!(false, vec.contains(&31337)); /// ``` #[inline] #[must_use] pub fn contains(&self, value: &A) -> bool where A: PartialEq, { self.index_of(value).is_some() } /// Discard all elements from the vector. /// /// This leaves you with an empty vector, and all elements that /// were previously inside it are dropped. /// /// Time: O(n) pub fn clear(&mut self) { if !self.is_empty() { self.vector = Inline(self.pool().clone(), InlineArray::new()); } } /// Binary search a sorted vector for a given element using a comparator /// function. /// /// Assumes the vector has already been sorted using the same comparator /// function, eg. by using [`sort_by`][sort_by]. /// /// If the value is found, it returns `Ok(index)` where `index` is the index /// of the element. If the value isn't found, it returns `Err(index)` where /// `index` is the index at which the element would need to be inserted to /// maintain sorted order. /// /// Time: O(log n) /// /// [sort_by]: #method.sort_by pub fn binary_search_by(&self, mut f: F) -> Result where F: FnMut(&A) -> Ordering, { let mut size = self.len(); if size == 0 { return Err(0); } let mut base = 0; while size > 1 { let half = size / 2; let mid = base + half; base = match f(&self[mid]) { Ordering::Greater => base, _ => mid, }; size -= half; } match f(&self[base]) { Ordering::Equal => Ok(base), Ordering::Greater => Err(base), Ordering::Less => Err(base + 1), } } /// Binary search a sorted vector for a given element. /// /// If the value is found, it returns `Ok(index)` where `index` is the index /// of the element. If the value isn't found, it returns `Err(index)` where /// `index` is the index at which the element would need to be inserted to /// maintain sorted order. /// /// Time: O(log n) pub fn binary_search(&self, value: &A) -> Result where A: Ord, { self.binary_search_by(|e| e.cmp(value)) } /// Binary search a sorted vector for a given element with a key extract /// function. /// /// Assumes the vector has already been sorted using the same key extract /// function, eg. by using [`sort_by_key`][sort_by_key]. /// /// If the value is found, it returns `Ok(index)` where `index` is the index /// of the element. If the value isn't found, it returns `Err(index)` where /// `index` is the index at which the element would need to be inserted to /// maintain sorted order. /// /// Time: O(log n) /// /// [sort_by_key]: #method.sort_by_key pub fn binary_search_by_key(&self, b: &B, mut f: F) -> Result where F: FnMut(&A) -> B, B: Ord, { self.binary_search_by(|k| f(k).cmp(b)) } } impl Vector { /// Construct a vector with a single value. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// let vec = Vector::unit(1337); /// assert_eq!(1, vec.len()); /// assert_eq!( /// vec.get(0), /// Some(&1337) /// ); /// ``` #[inline] #[must_use] pub fn unit(a: A) -> Self { let pool = RRBPool::default(); if InlineArray::>::CAPACITY > 0 { let mut array = InlineArray::new(); array.push(a); Self { vector: Inline(pool, array), } } else { let chunk = PoolRef::new(&pool.value_pool, Chunk::unit(a)); Self { vector: Single(pool, chunk), } } } /// Create a new vector with the value at index `index` updated. /// /// Panics if the index is out of bounds. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let mut vec = vector![1, 2, 3]; /// assert_eq!(vector![1, 5, 3], vec.update(1, 5)); /// ``` #[must_use] pub fn update(&self, index: usize, value: A) -> Self { let mut out = self.clone(); out[index] = value; out } /// Update the value at index `index` in a vector. /// /// Returns the previous value at the index. /// /// Panics if the index is out of bounds. /// /// Time: O(log n) #[inline] pub fn set(&mut self, index: usize, value: A) -> A { replace(&mut self[index], value) } /// Swap the elements at indices `i` and `j`. /// /// Time: O(log n) pub fn swap(&mut self, i: usize, j: usize) { swap_indices(self, i, j) } /// Push a value to the front of a vector. /// /// Time: O(1)* /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let mut vec = vector![5, 6, 7]; /// vec.push_front(4); /// assert_eq!(vector![4, 5, 6, 7], vec); /// ``` pub fn push_front(&mut self, value: A) { if self.needs_promotion() { self.promote_back(); } match &mut self.vector { Inline(_, chunk) => { chunk.insert(0, value); } Single(pool, chunk) => PoolRef::make_mut(&pool.value_pool, chunk).push_front(value), Full(pool, tree) => tree.push_front(pool, value), } } /// Push a value to the back of a vector. /// /// Time: O(1)* /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let mut vec = vector![1, 2, 3]; /// vec.push_back(4); /// assert_eq!(vector![1, 2, 3, 4], vec); /// ``` pub fn push_back(&mut self, value: A) { if self.needs_promotion() { self.promote_front(); } match &mut self.vector { Inline(_, chunk) => { chunk.push(value); } Single(pool, chunk) => PoolRef::make_mut(&pool.value_pool, chunk).push_back(value), Full(pool, tree) => tree.push_back(pool, value), } } /// Remove the first element from a vector and return it. /// /// Time: O(1)* /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let mut vec = vector![1, 2, 3]; /// assert_eq!(Some(1), vec.pop_front()); /// assert_eq!(vector![2, 3], vec); /// ``` pub fn pop_front(&mut self) -> Option { if self.is_empty() { None } else { match &mut self.vector { Inline(_, chunk) => chunk.remove(0), Single(pool, chunk) => Some(PoolRef::make_mut(&pool.value_pool, chunk).pop_front()), Full(pool, tree) => tree.pop_front(pool), } } } /// Remove the last element from a vector and return it. /// /// Time: O(1)* /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::Vector; /// let mut vec = vector![1, 2, 3]; /// assert_eq!(Some(3), vec.pop_back()); /// assert_eq!(vector![1, 2], vec); /// ``` pub fn pop_back(&mut self) -> Option { if self.is_empty() { None } else { match &mut self.vector { Inline(_, chunk) => chunk.pop(), Single(pool, chunk) => Some(PoolRef::make_mut(&pool.value_pool, chunk).pop_back()), Full(pool, tree) => tree.pop_back(pool), } } } /// Append the vector `other` to the end of the current vector. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// let mut vec = vector![1, 2, 3]; /// vec.append(vector![7, 8, 9]); /// assert_eq!(vector![1, 2, 3, 7, 8, 9], vec); /// ``` pub fn append(&mut self, mut other: Self) { if other.is_empty() { return; } if self.is_empty() { replace(self, other); return; } self.promote_inline(); other.promote_inline(); let total_length = self .len() .checked_add(other.len()) .expect("Vector length overflow"); match &mut self.vector { Inline(_, _) => unreachable!("inline vecs should have been promoted"), Single(pool, left) => { match &mut other.vector { Inline(_, _) => unreachable!("inline vecs should have been promoted"), // If both are single chunks and left has room for right: directly // memcpy right into left Single(_, ref mut right) if total_length <= CHUNK_SIZE => { PoolRef::make_mut(&pool.value_pool, left) .append(PoolRef::make_mut(&pool.value_pool, right)); return; } // If only left is a single chunk and has room for right: push // right's elements into left _ if total_length <= CHUNK_SIZE => { while let Some(value) = other.pop_front() { PoolRef::make_mut(&pool.value_pool, left).push_back(value); } return; } _ => {} } } Full(pool, left) => { if let Full(_, mut right) = other.vector { // If left and right are trees with empty middles, left has no back // buffers, and right has no front buffers: copy right's back // buffers over to left if left.middle.is_empty() && right.middle.is_empty() && left.outer_b.is_empty() && left.inner_b.is_empty() && right.outer_f.is_empty() && right.inner_f.is_empty() { left.inner_b = right.inner_b; left.outer_b = right.outer_b; left.length = total_length; return; } // If left and right are trees with empty middles and left's buffers // can fit right's buffers: push right's elements onto left if left.middle.is_empty() && right.middle.is_empty() && total_length <= CHUNK_SIZE * 4 { while let Some(value) = right.pop_front(pool) { left.push_back(pool, value); } return; } // Both are full and big: do the full RRB join let inner_b1 = left.inner_b.clone(); left.push_middle(pool, Side::Right, inner_b1); let outer_b1 = left.outer_b.clone(); left.push_middle(pool, Side::Right, outer_b1); let inner_f2 = right.inner_f.clone(); right.push_middle(pool, Side::Left, inner_f2); let outer_f2 = right.outer_f.clone(); right.push_middle(pool, Side::Left, outer_f2); let mut middle1 = clone_ref(replace(&mut left.middle, Ref::from(Node::new()))); let mut middle2 = clone_ref(right.middle); let normalised_middle = match left.middle_level.cmp(&right.middle_level) { Ordering::Greater => { middle2 = middle2.elevate(pool, left.middle_level - right.middle_level); left.middle_level } Ordering::Less => { middle1 = middle1.elevate(pool, right.middle_level - left.middle_level); right.middle_level } Ordering::Equal => left.middle_level, }; left.middle = Ref::new(Node::merge(pool, middle1, middle2, normalised_middle)); left.middle_level = normalised_middle + 1; left.inner_b = right.inner_b; left.outer_b = right.outer_b; left.length = total_length; left.prune(); return; } } } // No optimisations available, and either left, right or both are // single: promote both to full and retry self.promote_front(); other.promote_back(); self.append(other) } /// Retain only the elements specified by the predicate. /// /// Remove all elements for which the provided function `f` /// returns false from the vector. /// /// Time: O(n) pub fn retain(&mut self, mut f: F) where F: FnMut(&A) -> bool, { let len = self.len(); let mut del = 0; { let mut focus = self.focus_mut(); for i in 0..len { if !f(focus.index(i)) { del += 1; } else if del > 0 { focus.swap(i - del, i); } } } if del > 0 { self.split_off(len - del); } } /// Split a vector at a given index. /// /// Split a vector at a given index, consuming the vector and /// returning a pair of the left hand side and the right hand side /// of the split. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// let mut vec = vector![1, 2, 3, 7, 8, 9]; /// let (left, right) = vec.split_at(3); /// assert_eq!(vector![1, 2, 3], left); /// assert_eq!(vector![7, 8, 9], right); /// ``` pub fn split_at(mut self, index: usize) -> (Self, Self) { let right = self.split_off(index); (self, right) } /// Split a vector at a given index. /// /// Split a vector at a given index, leaving the left hand side in /// the current vector and returning a new vector containing the /// right hand side. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// let mut left = vector![1, 2, 3, 7, 8, 9]; /// let right = left.split_off(3); /// assert_eq!(vector![1, 2, 3], left); /// assert_eq!(vector![7, 8, 9], right); /// ``` pub fn split_off(&mut self, index: usize) -> Self { assert!(index <= self.len()); match &mut self.vector { Inline(pool, chunk) => Self { vector: Inline(pool.clone(), chunk.split_off(index)), }, Single(pool, chunk) => Self { vector: Single( pool.clone(), PoolRef::new( &pool.value_pool, PoolRef::make_mut(&pool.value_pool, chunk).split_off(index), ), ), }, Full(pool, tree) => { let mut local_index = index; if local_index < tree.outer_f.len() { let of2 = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_f) .split_off(local_index); let right = RRB { length: tree.length - index, middle_level: tree.middle_level, outer_f: PoolRef::new(&pool.value_pool, of2), inner_f: replace_pool_def(&pool.value_pool, &mut tree.inner_f), middle: std::mem::take(&mut tree.middle), inner_b: replace_pool_def(&pool.value_pool, &mut tree.inner_b), outer_b: replace_pool_def(&pool.value_pool, &mut tree.outer_b), }; tree.length = index; tree.middle_level = 0; return Self { vector: Full(pool.clone(), right), }; } local_index -= tree.outer_f.len(); if local_index < tree.inner_f.len() { let if2 = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_f) .split_off(local_index); let right = RRB { length: tree.length - index, middle_level: tree.middle_level, outer_f: PoolRef::new(&pool.value_pool, if2), inner_f: PoolRef::>::default(&pool.value_pool), middle: std::mem::take(&mut tree.middle), inner_b: replace_pool_def(&pool.value_pool, &mut tree.inner_b), outer_b: replace_pool_def(&pool.value_pool, &mut tree.outer_b), }; tree.length = index; tree.middle_level = 0; swap(&mut tree.outer_b, &mut tree.inner_f); return Self { vector: Full(pool.clone(), right), }; } local_index -= tree.inner_f.len(); if local_index < tree.middle.len() { let mut right_middle = tree.middle.clone(); let (c1, c2) = { let m1 = Ref::make_mut(&mut tree.middle); let m2 = Ref::make_mut(&mut right_middle); match m1.split(pool, tree.middle_level, Side::Right, local_index) { SplitResult::Dropped(_) => (), SplitResult::OutOfBounds => unreachable!(), }; match m2.split(pool, tree.middle_level, Side::Left, local_index) { SplitResult::Dropped(_) => (), SplitResult::OutOfBounds => unreachable!(), }; let c1 = match m1.pop_chunk(pool, tree.middle_level, Side::Right) { PopResult::Empty => PoolRef::default(&pool.value_pool), PopResult::Done(chunk) => chunk, PopResult::Drained(chunk) => { m1.clear_node(); chunk } }; let c2 = match m2.pop_chunk(pool, tree.middle_level, Side::Left) { PopResult::Empty => PoolRef::default(&pool.value_pool), PopResult::Done(chunk) => chunk, PopResult::Drained(chunk) => { m2.clear_node(); chunk } }; (c1, c2) }; let mut right = RRB { length: tree.length - index, middle_level: tree.middle_level, outer_f: c2, inner_f: PoolRef::>::default(&pool.value_pool), middle: right_middle, inner_b: replace_pool_def(&pool.value_pool, &mut tree.inner_b), outer_b: replace(&mut tree.outer_b, c1), }; tree.length = index; tree.prune(); right.prune(); return Self { vector: Full(pool.clone(), right), }; } local_index -= tree.middle.len(); if local_index < tree.inner_b.len() { let ib2 = PoolRef::make_mut(&pool.value_pool, &mut tree.inner_b) .split_off(local_index); let right = RRB { length: tree.length - index, outer_b: replace_pool_def(&pool.value_pool, &mut tree.outer_b), outer_f: PoolRef::new(&pool.value_pool, ib2), ..RRB::new(pool) }; tree.length = index; swap(&mut tree.outer_b, &mut tree.inner_b); return Self { vector: Full(pool.clone(), right), }; } local_index -= tree.inner_b.len(); let ob2 = PoolRef::make_mut(&pool.value_pool, &mut tree.outer_b).split_off(local_index); tree.length = index; Self { vector: Single(pool.clone(), PoolRef::new(&pool.value_pool, ob2)), } } } } /// Construct a vector with `count` elements removed from the /// start of the current vector. /// /// Time: O(log n) #[must_use] pub fn skip(&self, count: usize) -> Self { // FIXME can be made more efficient by dropping the unwanted side without constructing it self.clone().split_off(count) } /// Construct a vector of the first `count` elements from the /// current vector. /// /// Time: O(log n) #[must_use] pub fn take(&self, count: usize) -> Self { // FIXME can be made more efficient by dropping the unwanted side without constructing it let mut left = self.clone(); left.split_off(count); left } /// Truncate a vector to the given size. /// /// Discards all elements in the vector beyond the given length. /// /// Panics if the new length is greater than the current length. /// /// Time: O(log n) pub fn truncate(&mut self, len: usize) { // FIXME can be made more efficient by dropping the unwanted side without constructing it self.split_off(len); } /// Extract a slice from a vector. /// /// Remove the elements from `start_index` until `end_index` in /// the current vector and return the removed slice as a new /// vector. /// /// Time: O(log n) pub fn slice(&mut self, range: R) -> Self where R: RangeBounds, { let r = to_range(&range, self.len()); if r.start >= r.end || r.start >= self.len() { return Vector::new(); } let mut middle = self.split_off(r.start); let right = middle.split_off(r.end - r.start); self.append(right); middle } /// Insert an element into a vector. /// /// Insert an element at position `index`, shifting all elements /// after it to the right. /// /// ## Performance Note /// /// While `push_front` and `push_back` are heavily optimised /// operations, `insert` in the middle of a vector requires a /// split, a push, and an append. Thus, if you want to insert /// many elements at the same location, instead of `insert`ing /// them one by one, you should rather create a new vector /// containing the elements to insert, split the vector at the /// insertion point, and append the left hand, the new vector and /// the right hand in order. /// /// Time: O(log n) pub fn insert(&mut self, index: usize, value: A) { if index == 0 { return self.push_front(value); } if index == self.len() { return self.push_back(value); } assert!(index < self.len()); if if let Inline(_, chunk) = &self.vector { chunk.is_full() } else { false } { self.promote_inline(); } match &mut self.vector { Inline(_, chunk) => { chunk.insert(index, value); } Single(pool, chunk) if chunk.len() < CHUNK_SIZE => { PoolRef::make_mut(&pool.value_pool, chunk).insert(index, value) } // TODO a lot of optimisations still possible here _ => { let right = self.split_off(index); self.push_back(value); self.append(right); } } } /// Remove an element from a vector. /// /// Remove the element from position 'index', shifting all /// elements after it to the left, and return the removec element. /// /// ## Performance Note /// /// While `pop_front` and `pop_back` are heavily optimised /// operations, `remove` in the middle of a vector requires a /// split, a pop, and an append. Thus, if you want to remove many /// elements from the same location, instead of `remove`ing them /// one by one, it is much better to use [`slice`][slice]. /// /// Time: O(log n) /// /// [slice]: #method.slice pub fn remove(&mut self, index: usize) -> A { assert!(index < self.len()); match &mut self.vector { Inline(_, chunk) => chunk.remove(index).unwrap(), Single(pool, chunk) => PoolRef::make_mut(&pool.value_pool, chunk).remove(index), _ => { if index == 0 { return self.pop_front().unwrap(); } if index == self.len() - 1 { return self.pop_back().unwrap(); } // TODO a lot of optimisations still possible here let mut right = self.split_off(index); let value = right.pop_front().unwrap(); self.append(right); value } } } /// Insert an element into a sorted vector. /// /// Insert an element into a vector in sorted order, assuming the vector is /// already in sorted order. /// /// Time: O(log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// let mut vec = vector![1, 2, 3, 7, 8, 9]; /// vec.insert_ord(5); /// assert_eq!(vector![1, 2, 3, 5, 7, 8, 9], vec); /// ``` pub fn insert_ord(&mut self, item: A) where A: Ord, { match self.binary_search(&item) { Ok(index) => self.insert(index, item), Err(index) => self.insert(index, item), } } /// Sort a vector. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// let mut vec = vector![3, 2, 5, 4, 1]; /// vec.sort(); /// assert_eq!(vector![1, 2, 3, 4, 5], vec); /// ``` pub fn sort(&mut self) where A: Ord, { self.sort_by(Ord::cmp) } /// Sort a vector using a comparator function. /// /// Time: O(n log n) /// /// # Examples /// /// ``` /// # #[macro_use] extern crate im_rc as im; /// # use im::vector::Vector; /// let mut vec = vector![3, 2, 5, 4, 1]; /// vec.sort_by(|left, right| left.cmp(right)); /// assert_eq!(vector![1, 2, 3, 4, 5], vec); /// ``` pub fn sort_by(&mut self, cmp: F) where F: Fn(&A, &A) -> Ordering, { let len = self.len(); if len > 1 { sort::quicksort(self.focus_mut(), &cmp); } } /// Verify the internal consistency of a vector. /// /// This method walks the RRB tree making up the current `Vector` /// (if it has one) and verifies that all the invariants hold. /// If something is wrong, it will panic. /// /// This method requires the `debug` feature flag. #[cfg(any(test, feature = "debug"))] pub fn assert_invariants(&self) { if let Full(_, ref tree) = self.vector { tree.assert_invariants(); } } } // Implementation details impl RRB { fn new(pool: &RRBPool) -> Self { RRB { length: 0, middle_level: 0, outer_f: PoolRef::default(&pool.value_pool), inner_f: PoolRef::default(&pool.value_pool), middle: Ref::new(Node::new()), inner_b: PoolRef::default(&pool.value_pool), outer_b: PoolRef::default(&pool.value_pool), } } #[cfg(any(test, feature = "debug"))] fn assert_invariants(&self) { let ml = self.middle.assert_invariants(self.middle_level); assert_eq!( self.length, self.outer_f.len() + self.inner_f.len() + ml + self.inner_b.len() + self.outer_b.len() ); } fn prune(&mut self) { if self.middle.is_empty() { self.middle = Ref::new(Node::new()); self.middle_level = 0; } else { while self.middle_level > 0 && self.middle.is_single() { // FIXME could be optimised, cloning the node is expensive self.middle = Ref::new(self.middle.first_child().clone()); self.middle_level -= 1; } } } fn pop_front(&mut self, pool: &RRBPool) -> Option { if self.length == 0 { return None; } if self.outer_f.is_empty() { if self.inner_f.is_empty() { if self.middle.is_empty() { if self.inner_b.is_empty() { swap(&mut self.outer_f, &mut self.outer_b); } else { swap(&mut self.outer_f, &mut self.inner_b); } } else { self.outer_f = self.pop_middle(pool, Side::Left).unwrap(); } } else { swap(&mut self.outer_f, &mut self.inner_f); } } self.length -= 1; let outer_f = PoolRef::make_mut(&pool.value_pool, &mut self.outer_f); Some(outer_f.pop_front()) } fn pop_back(&mut self, pool: &RRBPool) -> Option { if self.length == 0 { return None; } if self.outer_b.is_empty() { if self.inner_b.is_empty() { if self.middle.is_empty() { if self.inner_f.is_empty() { swap(&mut self.outer_b, &mut self.outer_f); } else { swap(&mut self.outer_b, &mut self.inner_f); } } else { self.outer_b = self.pop_middle(pool, Side::Right).unwrap(); } } else { swap(&mut self.outer_b, &mut self.inner_b); } } self.length -= 1; let outer_b = PoolRef::make_mut(&pool.value_pool, &mut self.outer_b); Some(outer_b.pop_back()) } fn push_front(&mut self, pool: &RRBPool, value: A) { if self.outer_f.is_full() { swap(&mut self.outer_f, &mut self.inner_f); if !self.outer_f.is_empty() { let mut chunk = PoolRef::new(&pool.value_pool, Chunk::new()); swap(&mut chunk, &mut self.outer_f); self.push_middle(pool, Side::Left, chunk); } } self.length = self.length.checked_add(1).expect("Vector length overflow"); let outer_f = PoolRef::make_mut(&pool.value_pool, &mut self.outer_f); outer_f.push_front(value) } fn push_back(&mut self, pool: &RRBPool, value: A) { if self.outer_b.is_full() { swap(&mut self.outer_b, &mut self.inner_b); if !self.outer_b.is_empty() { let mut chunk = PoolRef::new(&pool.value_pool, Chunk::new()); swap(&mut chunk, &mut self.outer_b); self.push_middle(pool, Side::Right, chunk); } } self.length = self.length.checked_add(1).expect("Vector length overflow"); let outer_b = PoolRef::make_mut(&pool.value_pool, &mut self.outer_b); outer_b.push_back(value) } fn push_middle(&mut self, pool: &RRBPool, side: Side, chunk: PoolRef>) { if chunk.is_empty() { return; } let new_middle = { let middle = Ref::make_mut(&mut self.middle); match middle.push_chunk(pool, self.middle_level, side, chunk) { PushResult::Done => return, PushResult::Full(chunk, _num_drained) => Ref::from({ match side { Side::Left => Node::from_chunk(pool, self.middle_level, chunk) .join_branches(pool, middle.clone(), self.middle_level), Side::Right => middle.clone().join_branches( pool, Node::from_chunk(pool, self.middle_level, chunk), self.middle_level, ), } }), } }; self.middle_level += 1; self.middle = new_middle; } fn pop_middle(&mut self, pool: &RRBPool, side: Side) -> Option>> { let chunk = { let middle = Ref::make_mut(&mut self.middle); match middle.pop_chunk(pool, self.middle_level, side) { PopResult::Empty => return None, PopResult::Done(chunk) => chunk, PopResult::Drained(chunk) => { middle.clear_node(); self.middle_level = 0; chunk } } }; Some(chunk) } } #[inline] fn replace_pool_def(pool: &Pool, dest: &mut PoolRef) -> PoolRef { replace(dest, PoolRef::default(pool)) } // Core traits impl Default for Vector { fn default() -> Self { Self::new() } } impl Clone for Vector { /// Clone a vector. /// /// Time: O(1), or O(n) with a very small, bounded *n* for an inline vector. fn clone(&self) -> Self { Self { vector: match &self.vector { Inline(pool, chunk) => Inline(pool.clone(), chunk.clone()), Single(pool, chunk) => Single(pool.clone(), chunk.clone()), Full(pool, tree) => Full(pool.clone(), tree.clone()), }, } } } impl Debug for Vector { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.debug_list().entries(self.iter()).finish() // match self { // Full(rrb) => { // writeln!(f, "Head: {:?} {:?}", rrb.outer_f, rrb.inner_f)?; // rrb.middle.print(f, 0, rrb.middle_level)?; // writeln!(f, "Tail: {:?} {:?}", rrb.inner_b, rrb.outer_b) // } // Single(_) => write!(f, "nowt"), // } } } #[cfg(not(has_specialisation))] impl PartialEq for Vector { fn eq(&self, other: &Self) -> bool { self.len() == other.len() && self.iter().eq(other.iter()) } } #[cfg(has_specialisation)] impl PartialEq for Vector { default fn eq(&self, other: &Self) -> bool { self.len() == other.len() && self.iter().eq(other.iter()) } } #[cfg(has_specialisation)] impl PartialEq for Vector { fn eq(&self, other: &Self) -> bool { fn cmp_chunk(left: &PoolRef>, right: &PoolRef>) -> bool { (left.is_empty() && right.is_empty()) || PoolRef::ptr_eq(left, right) } if std::ptr::eq(self, other) { return true; } match (&self.vector, &other.vector) { (Single(_, left), Single(_, right)) => { if cmp_chunk(left, right) { return true; } self.iter().eq(other.iter()) } (Full(_, left), Full(_, right)) => { if left.length != right.length { return false; } if cmp_chunk(&left.outer_f, &right.outer_f) && cmp_chunk(&left.inner_f, &right.inner_f) && cmp_chunk(&left.inner_b, &right.inner_b) && cmp_chunk(&left.outer_b, &right.outer_b) && ((left.middle.is_empty() && right.middle.is_empty()) || Ref::ptr_eq(&left.middle, &right.middle)) { return true; } self.iter().eq(other.iter()) } _ => self.len() == other.len() && self.iter().eq(other.iter()), } } } impl Eq for Vector {} impl PartialOrd for Vector { fn partial_cmp(&self, other: &Self) -> Option { self.iter().partial_cmp(other.iter()) } } impl Ord for Vector { fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other.iter()) } } impl Hash for Vector { fn hash(&self, state: &mut H) { for i in self { i.hash(state) } } } impl Sum for Vector { fn sum(it: I) -> Self where I: Iterator, { it.fold(Self::new(), |a, b| a + b) } } impl Add for Vector { type Output = Vector; /// Concatenate two vectors. /// /// Time: O(log n) fn add(mut self, other: Self) -> Self::Output { self.append(other); self } } impl<'a, A: Clone> Add for &'a Vector { type Output = Vector; /// Concatenate two vectors. /// /// Time: O(log n) fn add(self, other: Self) -> Self::Output { let mut out = self.clone(); out.append(other.clone()); out } } impl Extend for Vector { /// Add values to the end of a vector by consuming an iterator. /// /// Time: O(n) fn extend(&mut self, iter: I) where I: IntoIterator, { for item in iter { self.push_back(item) } } } impl Index for Vector { type Output = A; /// Get a reference to the value at index `index` in the vector. /// /// Time: O(log n) fn index(&self, index: usize) -> &Self::Output { match self.get(index) { Some(value) => value, None => panic!( "Vector::index: index out of bounds: {} < {}", index, self.len() ), } } } impl IndexMut for Vector { /// Get a mutable reference to the value at index `index` in the /// vector. /// /// Time: O(log n) fn index_mut(&mut self, index: usize) -> &mut Self::Output { match self.get_mut(index) { Some(value) => value, None => panic!("Vector::index_mut: index out of bounds"), } } } // Conversions impl<'a, A: Clone> IntoIterator for &'a Vector { type Item = &'a A; type IntoIter = Iter<'a, A>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl IntoIterator for Vector { type Item = A; type IntoIter = ConsumingIter; fn into_iter(self) -> Self::IntoIter { ConsumingIter::new(self) } } impl FromIterator for Vector { /// Create a vector from an iterator. /// /// Time: O(n) fn from_iter(iter: I) -> Self where I: IntoIterator, { let mut seq = Self::new(); for item in iter { seq.push_back(item) } seq } } impl<'s, 'a, A, OA> From<&'s Vector<&'a A>> for Vector where A: ToOwned, OA: Borrow + Clone, { fn from(vec: &Vector<&A>) -> Self { vec.iter().map(|a| (*a).to_owned()).collect() } } impl<'a, A: Clone> From<&'a [A]> for Vector { fn from(slice: &[A]) -> Self { slice.iter().cloned().collect() } } impl From> for Vector { /// Create a vector from a [`std::vec::Vec`][vec]. /// /// Time: O(n) /// /// [vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html fn from(vec: Vec) -> Self { vec.into_iter().collect() } } impl<'a, A: Clone> From<&'a Vec> for Vector { /// Create a vector from a [`std::vec::Vec`][vec]. /// /// Time: O(n) /// /// [vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html fn from(vec: &Vec) -> Self { vec.iter().cloned().collect() } } // Iterators /// An iterator over vectors with values of type `A`. /// /// To obtain one, use [`Vector::iter()`][iter]. /// /// [iter]: enum.Vector.html#method.iter pub struct Iter<'a, A> { focus: Focus<'a, A>, front_index: usize, back_index: usize, } impl<'a, A: Clone> Iter<'a, A> { fn new(seq: &'a Vector) -> Self { Iter { focus: seq.focus(), front_index: 0, back_index: seq.len(), } } fn from_focus(focus: Focus<'a, A>) -> Self { Iter { front_index: 0, back_index: focus.len(), focus, } } } impl<'a, A: Clone> Iterator for Iter<'a, A> { type Item = &'a A; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { if self.front_index >= self.back_index { return None; } #[allow(unsafe_code)] let focus: &'a mut Focus<'a, A> = unsafe { &mut *(&mut self.focus as *mut _) }; let value = focus.get(self.front_index); self.front_index += 1; value } fn size_hint(&self) -> (usize, Option) { let remaining = self.back_index - self.front_index; (remaining, Some(remaining)) } } impl<'a, A: Clone> DoubleEndedIterator for Iter<'a, A> { /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next_back(&mut self) -> Option { if self.front_index >= self.back_index { return None; } self.back_index -= 1; #[allow(unsafe_code)] let focus: &'a mut Focus<'a, A> = unsafe { &mut *(&mut self.focus as *mut _) }; focus.get(self.back_index) } } impl<'a, A: Clone> ExactSizeIterator for Iter<'a, A> {} impl<'a, A: Clone> FusedIterator for Iter<'a, A> {} /// A mutable iterator over vectors with values of type `A`. /// /// To obtain one, use [`Vector::iter_mut()`][iter_mut]. /// /// [iter_mut]: enum.Vector.html#method.iter_mut pub struct IterMut<'a, A> { focus: FocusMut<'a, A>, front_index: usize, back_index: usize, } impl<'a, A> IterMut<'a, A> where A: Clone, { fn new(seq: &'a mut Vector) -> Self { let focus = seq.focus_mut(); let len = focus.len(); IterMut { focus, front_index: 0, back_index: len, } } fn from_focus(focus: FocusMut<'a, A>) -> Self { IterMut { front_index: 0, back_index: focus.len(), focus, } } } impl<'a, A> Iterator for IterMut<'a, A> where A: 'a + Clone, { type Item = &'a mut A; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { if self.front_index >= self.back_index { return None; } #[allow(unsafe_code)] let focus: &'a mut FocusMut<'a, A> = unsafe { &mut *(&mut self.focus as *mut _) }; let value = focus.get_mut(self.front_index); self.front_index += 1; value } fn size_hint(&self) -> (usize, Option) { let remaining = self.back_index - self.front_index; (remaining, Some(remaining)) } } impl<'a, A> DoubleEndedIterator for IterMut<'a, A> where A: 'a + Clone, { /// Remove and return an element from the back of the iterator. /// /// Time: O(1)* fn next_back(&mut self) -> Option { if self.front_index >= self.back_index { return None; } self.back_index -= 1; #[allow(unsafe_code)] let focus: &'a mut FocusMut<'a, A> = unsafe { &mut *(&mut self.focus as *mut _) }; focus.get_mut(self.back_index) } } impl<'a, A: Clone> ExactSizeIterator for IterMut<'a, A> {} impl<'a, A: Clone> FusedIterator for IterMut<'a, A> {} /// A consuming iterator over vectors with values of type `A`. pub struct ConsumingIter { vector: Vector, } impl ConsumingIter { fn new(vector: Vector) -> Self { Self { vector } } } impl Iterator for ConsumingIter { type Item = A; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { self.vector.pop_front() } fn size_hint(&self) -> (usize, Option) { let len = self.vector.len(); (len, Some(len)) } } impl DoubleEndedIterator for ConsumingIter { /// Remove and return an element from the back of the iterator. /// /// Time: O(1)* fn next_back(&mut self) -> Option { self.vector.pop_back() } } impl ExactSizeIterator for ConsumingIter {} impl FusedIterator for ConsumingIter {} /// An iterator over the leaf nodes of a vector. /// /// To obtain one, use [`Vector::chunks()`][chunks]. /// /// [chunks]: enum.Vector.html#method.chunks pub struct Chunks<'a, A> { focus: Focus<'a, A>, front_index: usize, back_index: usize, } impl<'a, A: Clone> Chunks<'a, A> { fn new(seq: &'a Vector) -> Self { Chunks { focus: seq.focus(), front_index: 0, back_index: seq.len(), } } } impl<'a, A: Clone> Iterator for Chunks<'a, A> { type Item = &'a [A]; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { if self.front_index >= self.back_index { return None; } #[allow(unsafe_code)] let focus: &'a mut Focus<'a, A> = unsafe { &mut *(&mut self.focus as *mut _) }; let (range, value) = focus.chunk_at(self.front_index); self.front_index = range.end; Some(value) } } impl<'a, A: Clone> DoubleEndedIterator for Chunks<'a, A> { /// Remove and return an element from the back of the iterator. /// /// Time: O(1)* fn next_back(&mut self) -> Option { if self.front_index >= self.back_index { return None; } self.back_index -= 1; #[allow(unsafe_code)] let focus: &'a mut Focus<'a, A> = unsafe { &mut *(&mut self.focus as *mut _) }; let (range, value) = focus.chunk_at(self.back_index); self.back_index = range.start; Some(value) } } impl<'a, A: Clone> FusedIterator for Chunks<'a, A> {} /// A mutable iterator over the leaf nodes of a vector. /// /// To obtain one, use [`Vector::chunks_mut()`][chunks_mut]. /// /// [chunks_mut]: enum.Vector.html#method.chunks_mut pub struct ChunksMut<'a, A> { focus: FocusMut<'a, A>, front_index: usize, back_index: usize, } impl<'a, A: Clone> ChunksMut<'a, A> { fn new(seq: &'a mut Vector) -> Self { let len = seq.len(); ChunksMut { focus: seq.focus_mut(), front_index: 0, back_index: len, } } } impl<'a, A: Clone> Iterator for ChunksMut<'a, A> { type Item = &'a mut [A]; /// Advance the iterator and return the next value. /// /// Time: O(1)* fn next(&mut self) -> Option { if self.front_index >= self.back_index { return None; } #[allow(unsafe_code)] let focus: &'a mut FocusMut<'a, A> = unsafe { &mut *(&mut self.focus as *mut _) }; let (range, value) = focus.chunk_at(self.front_index); self.front_index = range.end; Some(value) } } impl<'a, A: Clone> DoubleEndedIterator for ChunksMut<'a, A> { /// Remove and return an element from the back of the iterator. /// /// Time: O(1)* fn next_back(&mut self) -> Option { if self.front_index >= self.back_index { return None; } self.back_index -= 1; #[allow(unsafe_code)] let focus: &'a mut FocusMut<'a, A> = unsafe { &mut *(&mut self.focus as *mut _) }; let (range, value) = focus.chunk_at(self.back_index); self.back_index = range.start; Some(value) } } impl<'a, A: Clone> FusedIterator for ChunksMut<'a, A> {} // Proptest #[cfg(any(test, feature = "proptest"))] #[doc(hidden)] pub mod proptest { #[deprecated( since = "14.3.0", note = "proptest strategies have moved to im::proptest" )] pub use crate::proptest::vector; } // Tests #[cfg(test)] mod test { use super::*; use crate::proptest::vector; use ::proptest::collection::vec; use ::proptest::num::{i32, usize}; use ::proptest::proptest; #[test] fn macro_allows_trailing_comma() { let vec1 = vector![1, 2, 3]; let vec2 = vector![1, 2, 3,]; assert_eq!(vec1, vec2); } #[test] fn indexing() { let mut vec = vector![0, 1, 2, 3, 4, 5]; vec.push_front(0); assert_eq!(0, *vec.get(0).unwrap()); assert_eq!(0, vec[0]); } #[test] fn large_vector_focus() { let input = Vector::from_iter(0..100_000); let vec = input.clone(); let mut sum: i64 = 0; let mut focus = vec.focus(); for i in 0..input.len() { sum += *focus.index(i); } let expected: i64 = (0..100_000).sum(); assert_eq!(expected, sum); } #[test] fn large_vector_focus_mut() { let input = Vector::from_iter(0..100_000); let mut vec = input.clone(); { let mut focus = vec.focus_mut(); for i in 0..input.len() { let p = focus.index_mut(i); *p += 1; } } let expected: Vector = input.into_iter().map(|i| i + 1).collect(); assert_eq!(expected, vec); } #[test] fn issue_55_fwd() { let mut l = Vector::new(); for i in 0..4098 { l.append(Vector::unit(i)); } l.append(Vector::unit(4098)); assert_eq!(Some(&4097), l.get(4097)); assert_eq!(Some(&4096), l.get(4096)); } #[test] fn issue_55_back() { let mut l = Vector::unit(0); for i in 0..4099 { let mut tmp = Vector::unit(i + 1); tmp.append(l); l = tmp; } assert_eq!(Some(&4098), l.get(1)); assert_eq!(Some(&4097), l.get(2)); let len = l.len(); l.slice(2..len); } #[test] fn issue_55_append() { let mut vec1 = Vector::from_iter(0..92); let vec2 = Vector::from_iter(0..165); vec1.append(vec2); } #[test] fn issue_70() { let mut x = Vector::new(); for _ in 0..262 { x.push_back(0); } for _ in 0..97 { x.pop_front(); } for &offset in &[160, 163, 160] { x.remove(offset); } for _ in 0..64 { x.push_back(0); } // At this point middle contains three chunks of size 64, 64 and 1 // respectively. Previously the next `push_back()` would append another // zero-sized chunk to middle even though there is enough space left. match x.vector { VectorInner::Full(_, ref tree) => { assert_eq!(129, tree.middle.len()); assert_eq!(3, tree.middle.number_of_children()); } _ => unreachable!(), } x.push_back(0); match x.vector { VectorInner::Full(_, ref tree) => { assert_eq!(131, tree.middle.len()); assert_eq!(3, tree.middle.number_of_children()) } _ => unreachable!(), } for _ in 0..64 { x.push_back(0); } for _ in x.iter() {} } #[test] fn issue_67() { let mut l = Vector::unit(4100); for i in (0..4099).rev() { let mut tmp = Vector::unit(i); tmp.append(l); l = tmp; } assert_eq!(4100, l.len()); let len = l.len(); let tail = l.slice(1..len); assert_eq!(1, l.len()); assert_eq!(4099, tail.len()); assert_eq!(Some(&0), l.get(0)); assert_eq!(Some(&1), tail.get(0)); } #[test] fn issue_74_simple_size() { use crate::nodes::rrb::NODE_SIZE; let mut x = Vector::new(); for _ in 0..(CHUNK_SIZE * ( 1 // inner_f + (2 * NODE_SIZE) // middle: two full Entry::Nodes (4096 elements each) + 1 // inner_b + 1 // outer_b )) { x.push_back(0u32); } let middle_first_node_start = CHUNK_SIZE; let middle_second_node_start = middle_first_node_start + NODE_SIZE * CHUNK_SIZE; // This reduces the size of the second node to 4095. x.remove(middle_second_node_start); // As outer_b is full, this will cause inner_b (length 64) to be pushed // to middle. The first element will be merged into the second node, the // remaining 63 elements will end up in a new node. x.push_back(0u32); match x.vector { VectorInner::Full(_, tree) => { assert_eq!(3, tree.middle.number_of_children()); assert_eq!( 2 * NODE_SIZE * CHUNK_SIZE + CHUNK_SIZE - 1, tree.middle.len() ); } _ => unreachable!(), } } #[test] fn issue_77() { let mut x = Vector::new(); for _ in 0..44 { x.push_back(0); } for _ in 0..20 { x.insert(0, 0); } x.insert(1, 0); for _ in 0..441 { x.push_back(0); } for _ in 0..58 { x.insert(0, 0); } x.insert(514, 0); for _ in 0..73 { x.push_back(0); } for _ in 0..10 { x.insert(0, 0); } x.insert(514, 0); } #[test] fn issue_105() { let mut v = Vector::new(); for i in 0..270_000 { v.push_front(i); } while !v.is_empty() { v = v.take(v.len() - 1); } } #[test] fn issue_107_split_off_causes_overflow() { let mut vec = Vector::from_iter(0..4289); let mut control = Vec::from_iter(0..4289); let chunk = 64; while vec.len() >= chunk { vec = vec.split_off(chunk); control = control.split_off(chunk); assert_eq!(vec.len(), control.len()); assert_eq!(control, vec.iter().cloned().collect::>()); } } #[test] fn collect_crash() { let _vector: Vector = (0..5953).collect(); // let _vector: Vector = (0..16384).collect(); } #[test] fn issue_116() { let vec = Vector::from_iter(0..300); let rev_vec: Vector = vec.clone().into_iter().rev().collect(); assert_eq!(vec.len(), rev_vec.len()); } #[test] fn issue_131() { let smol = std::iter::repeat(42).take(64).collect::>(); let mut smol2 = smol.clone(); assert!(smol.ptr_eq(&smol2)); smol2.set(63, 420); assert!(!smol.ptr_eq(&smol2)); let huge = std::iter::repeat(42).take(65).collect::>(); let mut huge2 = huge.clone(); assert!(huge.ptr_eq(&huge2)); huge2.set(63, 420); assert!(!huge.ptr_eq(&huge2)); } #[test] fn ptr_eq() { for len in 32..256 { let input = std::iter::repeat(42).take(len).collect::>(); let mut inp2 = input.clone(); assert!(input.ptr_eq(&inp2)); inp2.set(len - 1, 98); assert_ne!(inp2.get(len - 1), input.get(len - 1)); assert!(!input.ptr_eq(&inp2), len); } } proptest! { #[test] fn iter(ref vec in vec(i32::ANY, 0..1000)) { let seq: Vector = Vector::from_iter(vec.iter().cloned()); for (index, item) in seq.iter().enumerate() { assert_eq!(&vec[index], item); } assert_eq!(vec.len(), seq.len()); } #[test] fn push_front_mut(ref input in vec(i32::ANY, 0..1000)) { let mut vector = Vector::new(); for (count, value) in input.iter().cloned().enumerate() { assert_eq!(count, vector.len()); vector.push_front(value); assert_eq!(count + 1, vector.len()); } let input2 = Vec::from_iter(input.iter().rev().cloned()); assert_eq!(input2, Vec::from_iter(vector.iter().cloned())); } #[test] fn push_back_mut(ref input in vec(i32::ANY, 0..1000)) { let mut vector = Vector::new(); for (count, value) in input.iter().cloned().enumerate() { assert_eq!(count, vector.len()); vector.push_back(value); assert_eq!(count + 1, vector.len()); } assert_eq!(input, &Vec::from_iter(vector.iter().cloned())); } #[test] fn pop_back_mut(ref input in vec(i32::ANY, 0..1000)) { let mut vector = Vector::from_iter(input.iter().cloned()); assert_eq!(input.len(), vector.len()); for (index, value) in input.iter().cloned().enumerate().rev() { match vector.pop_back() { None => panic!("vector emptied unexpectedly"), Some(item) => { assert_eq!(index, vector.len()); assert_eq!(value, item); } } } assert_eq!(0, vector.len()); } #[test] fn pop_front_mut(ref input in vec(i32::ANY, 0..1000)) { let mut vector = Vector::from_iter(input.iter().cloned()); assert_eq!(input.len(), vector.len()); for (index, value) in input.iter().cloned().rev().enumerate().rev() { match vector.pop_front() { None => panic!("vector emptied unexpectedly"), Some(item) => { assert_eq!(index, vector.len()); assert_eq!(value, item); } } } assert_eq!(0, vector.len()); } // #[test] // fn push_and_pop(ref input in vec(i32::ANY, 0..1000)) { // let mut vector = Vector::new(); // for (count, value) in input.iter().cloned().enumerate() { // assert_eq!(count, vector.len()); // vector.push_back(value); // assert_eq!(count + 1, vector.len()); // } // for (index, value) in input.iter().cloned().rev().enumerate().rev() { // match vector.pop_front() { // None => panic!("vector emptied unexpectedly"), // Some(item) => { // assert_eq!(index, vector.len()); // assert_eq!(value, item); // } // } // } // assert_eq!(true, vector.is_empty()); // } #[test] fn split(ref vec in vec(i32::ANY, 1..2000), split_pos in usize::ANY) { let split_index = split_pos % (vec.len() + 1); let mut left = Vector::from_iter(vec.iter().cloned()); let right = left.split_off(split_index); assert_eq!(left.len(), split_index); assert_eq!(right.len(), vec.len() - split_index); for (index, item) in left.iter().enumerate() { assert_eq!(& vec[index], item); } for (index, item) in right.iter().enumerate() { assert_eq!(&vec[split_index + index], item); } } #[test] fn append(ref vec1 in vec(i32::ANY, 0..1000), ref vec2 in vec(i32::ANY, 0..1000)) { let mut seq1 = Vector::from_iter(vec1.iter().cloned()); let seq2 = Vector::from_iter(vec2.iter().cloned()); assert_eq!(seq1.len(), vec1.len()); assert_eq!(seq2.len(), vec2.len()); seq1.append(seq2); let mut vec = vec1.clone(); vec.extend(vec2); assert_eq!(seq1.len(), vec.len()); for (index, item) in seq1.into_iter().enumerate() { assert_eq!(vec[index], item); } } #[test] fn iter_mut(ref input in vector(i32::ANY, 0..10000)) { let mut vec = input.clone(); { for p in vec.iter_mut() { *p = p.overflowing_add(1).0; } } let expected: Vector = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect(); assert_eq!(expected, vec); } #[test] fn focus(ref input in vector(i32::ANY, 0..10000)) { let mut vec = input.clone(); { let mut focus = vec.focus_mut(); for i in 0..input.len() { let p = focus.index_mut(i); *p = p.overflowing_add(1).0; } } let expected: Vector = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect(); assert_eq!(expected, vec); } #[test] fn focus_mut_split(ref input in vector(i32::ANY, 0..10000)) { let mut vec = input.clone(); fn split_down(focus: FocusMut<'_, i32>) { let len = focus.len(); if len < 8 { for p in focus { *p = p.overflowing_add(1).0; } } else { let (left, right) = focus.split_at(len / 2); split_down(left); split_down(right); } } split_down(vec.focus_mut()); let expected: Vector = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect(); assert_eq!(expected, vec); } #[test] fn chunks(ref input in vector(i32::ANY, 0..10000)) { let output: Vector<_> = input.leaves().flatten().cloned().collect(); assert_eq!(input, &output); let rev_in: Vector<_> = input.iter().rev().cloned().collect(); let rev_out: Vector<_> = input.leaves().rev().map(|c| c.iter().rev()).flatten().cloned().collect(); assert_eq!(rev_in, rev_out); } #[test] fn chunks_mut(ref mut input_src in vector(i32::ANY, 0..10000)) { let mut input = input_src.clone(); #[allow(clippy::map_clone)] let output: Vector<_> = input.leaves_mut().flatten().map(|v| *v).collect(); assert_eq!(input, output); let rev_in: Vector<_> = input.iter().rev().cloned().collect(); let rev_out: Vector<_> = input.leaves_mut().rev().map(|c| c.iter().rev()).flatten().cloned().collect(); assert_eq!(rev_in, rev_out); } // The following two tests are very slow and there are unit tests above // which test for regression of issue #55. It would still be good to // run them occasionally. // #[test] // fn issue55_back(count in 0..10000, slice_at in usize::ANY) { // let count = count as usize; // let slice_at = slice_at % count; // let mut l = Vector::unit(0); // for _ in 0..count { // let mut tmp = Vector::unit(0); // tmp.append(l); // l = tmp; // } // let len = l.len(); // l.slice(slice_at..len); // } // #[test] // fn issue55_fwd(count in 0..10000, slice_at in usize::ANY) { // let count = count as usize; // let slice_at = slice_at % count; // let mut l = Vector::new(); // for i in 0..count { // l.append(Vector::unit(i)); // } // assert_eq!(Some(&slice_at), l.get(slice_at)); // } } } im-rc-15.0.0/src/vector/pool.rs010064400017500001750000000040261365756323600144570ustar0000000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use crate::config::POOL_SIZE; use crate::nodes::chunk::Chunk; use crate::nodes::rrb::Node; use crate::util::Pool; /// A memory pool for `Vector`. pub struct RRBPool { pub(crate) node_pool: Pool>>, pub(crate) value_pool: Pool>, pub(crate) size_pool: Pool>, } impl RRBPool { /// Create a new memory pool with the given size. pub fn new(size: usize) -> Self { Self::with_sizes(size, size, size) } /// Create a new memory pool with the given sizes for each subpool. pub fn with_sizes( node_pool_size: usize, leaf_pool_size: usize, size_table_pool_size: usize, ) -> Self { Self { node_pool: Pool::new(node_pool_size), value_pool: Pool::new(leaf_pool_size), size_pool: Pool::new(size_table_pool_size), } } /// Fill the memory pool with preallocated chunks. pub fn fill(&self) { self.node_pool.fill(); self.value_pool.fill(); self.size_pool.fill(); } /// Get the size of the node subpool. pub fn node_pool_size(&self) -> usize { self.node_pool.get_pool_size() } /// Get the size of the leaf node subpool. pub fn leaf_pool_size(&self) -> usize { self.value_pool.get_pool_size() } /// Get the size of the size table subpool. pub fn size_table_pool_size(&self) -> usize { self.size_pool.get_pool_size() } } impl Default for RRBPool { /// Construct a pool with a reasonable default pool size. fn default() -> Self { Self::new(POOL_SIZE) } } impl Clone for RRBPool { fn clone(&self) -> Self { Self { node_pool: self.node_pool.clone(), value_pool: self.value_pool.clone(), size_pool: self.size_pool.clone(), } } } im-rc-15.0.0/src/vector/rayon.rs010064400017500001750000000110721365756323600146350ustar0000000000000000//! Parallel iterators. //! //! These are only available when using the `rayon` feature flag. use super::*; use ::rayon::iter::plumbing::{bridge, Consumer, Producer, ProducerCallback, UnindexedConsumer}; use ::rayon::iter::{ IndexedParallelIterator, IntoParallelRefIterator, IntoParallelRefMutIterator, ParallelIterator, }; impl<'a, A> IntoParallelRefIterator<'a> for Vector where A: Clone + Send + Sync + 'a, { type Item = &'a A; type Iter = ParIter<'a, A>; fn par_iter(&'a self) -> Self::Iter { ParIter { focus: self.focus(), } } } impl<'a, A> IntoParallelRefMutIterator<'a> for Vector where A: Clone + Send + Sync + 'a, { type Item = &'a mut A; type Iter = ParIterMut<'a, A>; fn par_iter_mut(&'a mut self) -> Self::Iter { ParIterMut { focus: self.focus_mut(), } } } /// A parallel iterator for [`Vector`][Vector]. /// /// [Vector]: ../struct.Vector.html pub struct ParIter<'a, A> where A: Clone + Send + Sync, { focus: Focus<'a, A>, } impl<'a, A> ParallelIterator for ParIter<'a, A> where A: Clone + Send + Sync + 'a, { type Item = &'a A; fn drive_unindexed(self, consumer: C) -> C::Result where C: UnindexedConsumer, { bridge(self, consumer) } } impl<'a, A> IndexedParallelIterator for ParIter<'a, A> where A: Clone + Send + Sync + 'a, { fn drive(self, consumer: C) -> C::Result where C: Consumer, { bridge(self, consumer) } fn len(&self) -> usize { self.focus.len() } fn with_producer(self, callback: CB) -> CB::Output where CB: ProducerCallback, { callback.callback(VectorProducer { focus: self.focus }) } } /// A mutable parallel iterator for [`Vector`][Vector]. /// /// [Vector]: ../struct.Vector.html pub struct ParIterMut<'a, A> where A: Clone + Send + Sync, { focus: FocusMut<'a, A>, } impl<'a, A> ParallelIterator for ParIterMut<'a, A> where A: Clone + Send + Sync + 'a, { type Item = &'a mut A; fn drive_unindexed(self, consumer: C) -> C::Result where C: UnindexedConsumer, { bridge(self, consumer) } } impl<'a, A> IndexedParallelIterator for ParIterMut<'a, A> where A: Clone + Send + Sync + 'a, { fn drive(self, consumer: C) -> C::Result where C: Consumer, { bridge(self, consumer) } fn len(&self) -> usize { self.focus.len() } fn with_producer(self, callback: CB) -> CB::Output where CB: ProducerCallback, { callback.callback(VectorMutProducer { focus: self.focus }) } } struct VectorProducer<'a, A> where A: Clone + Send + Sync, { focus: Focus<'a, A>, } impl<'a, A> Producer for VectorProducer<'a, A> where A: Clone + Send + Sync + 'a, { type Item = &'a A; type IntoIter = Iter<'a, A>; fn into_iter(self) -> Self::IntoIter { self.focus.into_iter() } fn split_at(self, index: usize) -> (Self, Self) { let (left, right) = self.focus.split_at(index); ( VectorProducer { focus: left }, VectorProducer { focus: right }, ) } } struct VectorMutProducer<'a, A> where A: Clone + Send + Sync, { focus: FocusMut<'a, A>, } impl<'a, A> Producer for VectorMutProducer<'a, A> where A: Clone + Send + Sync + 'a, { type Item = &'a mut A; type IntoIter = IterMut<'a, A>; fn into_iter(self) -> Self::IntoIter { self.focus.into_iter() } fn split_at(self, index: usize) -> (Self, Self) { let (left, right) = self.focus.split_at(index); ( VectorMutProducer { focus: left }, VectorMutProducer { focus: right }, ) } } #[cfg(test)] mod test { use super::super::*; use super::proptest::vector; use ::proptest::num::i32; use ::proptest::proptest; use ::rayon::iter::{IntoParallelRefIterator, IntoParallelRefMutIterator, ParallelIterator}; proptest! { #[test] fn par_iter(ref mut input in vector(i32::ANY, 0..10000)) { assert_eq!(input.iter().max(), input.par_iter().max()) } #[test] fn par_mut_iter(ref mut input in vector(i32::ANY, 0..10000)) { let mut vec = input.clone(); vec.par_iter_mut().for_each(|i| *i = i.overflowing_add(1).0); let expected: Vector = input.clone().into_iter().map(|i| i.overflowing_add(1).0).collect(); assert_eq!(expected, vec); } } }