bimap-0.6.3/.cargo_vcs_info.json0000644000000001360000000000100121320ustar { "git": { "sha1": "8e5a4e224b95857da8a28a7dd4a1a9eec241ef7d" }, "path_in_vcs": "" }bimap-0.6.3/.github/workflows/ci.yml000064400000000000000000000023021046102023000154320ustar 00000000000000name: Test suite on: push: branches: - main pull_request: jobs: style: name: Enforce style runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal # use nightly rustfmt for unstable options toolchain: nightly override: true components: rustfmt - uses: actions-rs/cargo@v1 with: command: fmt args: -- --check test: name: Run tests needs: style strategy: matrix: os: - ubuntu-latest - macos-latest - windows-latest rust: - stable - nightly runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.rust }} override: true - uses: actions-rs/cargo@v1 with: command: test - uses: actions-rs/cargo@v1 with: command: test args: --all-features - uses: actions-rs/cargo@v1 with: command: test args: --no-default-features bimap-0.6.3/.gitignore000064400000000000000000000003721046102023000127140ustar 00000000000000# This is a slight modification of the default .gitignore generated by cargo # for library projects. I prefer `/**/target` over `/target` to ignore build # artifacts in nested directories (for instance, when using workspaces). /**/target Cargo.lock bimap-0.6.3/CHANGELOG.md000064400000000000000000000044161046102023000125400ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.6.3] ### Added - `Debug` and `Clone` on iterators (#37). ## [0.6.2] ### Added - `BiBTreeMap::retain` (#30). - `BiHashMap::reserve`, `BiHashMap::shrink_to`, and `BiHashMap::shrink_to_fit` (#32). ## [0.6.1] ### Added - `serde` trait implementations for `BiHashMap` are now generic over the left and right hashers (#27, #28). Before, they were only implemented for the default hasher. ## [0.6.0] ### Changed - Generalize query interfaces using `std::borrow::Borrow` for `BiMap` methods like `get`, `contains`, and `remove`. This more closely aligns to the API provided by the Rust standard library. ## [0.5.3] ### Added - Implement `Hash` for `BiBTreeMap` (#23). ### Changed - Minor edits to the README. ### Removed - Unnecessary trait bounds on the `fmt::Debug` impl for `BiMap` (#22). ## [0.5.2] ### Added - Documentation link to docs.rs in Cargo.toml. ## [0.5.1] ### Fixed - Outdated docs.rs link in README. ## [0.5.0] ### Added - This changelog. - `Extend` implementations. - Pretty `Debug` formatting. - `left_range` and `right_range` methods for `BiBTreeMap`. ### Changed - Documentation and useful public documents were created and/or updated. ### Fixed - Tests for `BiBTreeMap` run correctly with `no_std`. ## [0.4.0] [Unreleased]: https://github.com/billyrieger/bimap-rs/compare/v0.6.3...HEAD [0.6.3]: https://github.com/billyrieger/bimap-rs/compare/v0.6.2...v0.6.3 [0.6.2]: https://github.com/billyrieger/bimap-rs/compare/v0.6.1...v0.6.2 [0.6.1]: https://github.com/billyrieger/bimap-rs/compare/v0.6.0...v0.6.1 [0.6.0]: https://github.com/billyrieger/bimap-rs/compare/v0.5.3...v0.6.0 [0.5.3]: https://github.com/billyrieger/bimap-rs/compare/v0.5.2...v0.5.3 [0.5.2]: https://github.com/billyrieger/bimap-rs/compare/v0.5.1...v0.5.2 [0.5.1]: https://github.com/billyrieger/bimap-rs/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/billyrieger/bimap-rs/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/billyrieger/bimap-rs/releases/tag/v0.4.0 bimap-0.6.3/CODE_OF_CONDUCT.md000064400000000000000000000121521046102023000135220ustar 00000000000000 # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders 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, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at wrieger@protonmail.com. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. bimap-0.6.3/CONTRIBUTING.md000064400000000000000000000033031046102023000131520ustar 00000000000000# Contributing Thank you for your interest in improving `bimap-rs`! 1. [How to contribute](#how-to-contribute) 1. [Bug reports](#bug-reports) 1. [Feature requests](#feature-requests) 1. [Direct pull requests](#direct-pull-requests) 1. [Local development](#local-development) ## How to contribute ### Bug reports `bimap-rs` tries to be well tested but mistakes can still slip through. If something isn't working as expected, please open an issue to let me know! It helps to include the following information: - `bimap-rs` version and enabled/disabled features - Rust version (`rustc --version`) - Environment (other dependencies, operating system, etc) - Minimal example that illustrates the issue ### Feature requests If there's a feature you'd like to see in `bimap-rs`, open an issue describing the feature in as much detail as you can. ### Direct pull requests For small and/or uncontroversial features and bug fixes, feel free to skip the issue process and just submit a pull request. ## Local development Building `bimap-rs` locally is as simple as cloning the repository. ```shell $ # clone the repository $ git clone https://github.com/billyrieger/bimap-rs.git $ cd bimap-rs $ # build the library $ cargo build ``` The full test suite runs the library tests and documentation tests with different combinations of feature flags. ```shell $ # run the test suite $ cargo test $ cargo test --all-features $ cargo test --no-default-features ``` Don't forget to format your code! You'll need the nightly version of `rustfmt`. ```shell $ # install nightly rustfmt $ rustup toolchain install nightly $ rustup component add --toolchain nightly rustfmt $ # format the repository $ cargo +nightly fmt ```bimap-0.6.3/Cargo.toml0000644000000022560000000000100101350ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "bimap" version = "0.6.3" authors = ["Billy Rieger "] description = "Bijective maps" documentation = "https://docs.rs/bimap/" readme = "README.md" keywords = [ "bijection", "bidirectional", "map", "container", "two-way", ] categories = [ "data-structures", "algorithms", "no-std", ] license = "Apache-2.0/MIT" repository = "https://github.com/billyrieger/bimap-rs/" [package.metadata.docs.rs] all-features = true [dependencies.serde] version = "1.0" optional = true [dev-dependencies.fnv] version = "1.0" [dev-dependencies.hashbrown] version = "0.11" [dev-dependencies.serde_json] version = "1.0" [features] default = ["std"] std = [] bimap-0.6.3/Cargo.toml.orig000064400000000000000000000013031046102023000136060ustar 00000000000000[package] name = "bimap" version = "0.6.3" authors = ["Billy Rieger "] description = "Bijective maps" repository = "https://github.com/billyrieger/bimap-rs/" documentation = "https://docs.rs/bimap/" readme = "README.md" keywords = ["bijection", "bidirectional", "map", "container", "two-way"] categories = ["data-structures", "algorithms", "no-std"] license = "Apache-2.0/MIT" edition = "2018" [features] default = ["std"] std = [] [dependencies] serde = { version = "1.0", optional = true } [dev-dependencies] serde_json = "1.0" fnv = "1.0" hashbrown = "0.11" # This ensures that documentation for optional features is on docs.rs. [package.metadata.docs.rs] all-features = true bimap-0.6.3/LICENSE_APACHE000064400000000000000000000251371046102023000127400ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. bimap-0.6.3/LICENSE_MIT000064400000000000000000000017771046102023000124540ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bimap-0.6.3/README.md000064400000000000000000000071261046102023000122070ustar 00000000000000# `bimap-rs` [![version][version badge]][lib.rs] [![documentation][documentation badge]][docs.rs] [![license][license badge]](#license) `bimap-rs` is a pure Rust library for dealing with bijective maps, aiming to feel like an extension of the standard library's data structures whenever possible. There are no external dependencies by default but [Serde] and [`no_std`] compatibility are available through feature flags. 1. [Quick start](#quick-start) 1. [Feature flags](#feature-flags) 1. [Documentation](#documentation) 1. [Contributing](#contributing) 1. [Semantic versioning](#semantic-versioning) 1. [Minimum supported Rust version](#minimum-supported-rust-version) 1. [License](#license) ## Quick start To use the latest version of `bimap-rs` with the default features, add this to your project's `Cargo.toml` file: ```toml [dependencies] bimap = "0.6.3" ``` You can now run the `bimap-rs` Hello World! ```rust fn main() { // A bijective map between letters of the English alphabet and their positions. let mut alphabet = bimap::BiMap::::new(); alphabet.insert('A', 1); // ... alphabet.insert('Z', 26); println!("A is at position {}", alphabet.get_by_left(&'A').unwrap()); println!("{} is at position 26", alphabet.get_by_right(&26).unwrap()); } ``` ## Feature flags | Flag name | Description | Enabled by default? | | --- | --- | --- | | `std` | Standard library usage (`HashMap`) | yes | | `serde` | (De)serialization using [Serde] | no | This `Cargo.toml` shows how these features can be enabled and disabled. ```toml [dependencies] # I just want to use `bimap-rs`. bimap = "0.6.3" # I want to use `bimap-rs` without the Rust standard library. bimap = { version = "0.6.3", default-features = false } # I want to use `bimap-rs` with Serde support. bimap = { version = "0.6.3", features = ["serde"] } ``` ## Documentation Documentation for the latest version of `bimap-rs` is available on [docs.rs]. ## Contributing Thank you for your interest in improving `bimap-rs`! Please read the [code of conduct] and the [contributing guidelines] before submitting an issue or opening a pull request. ## Semantic versioning `bimap-rs` adheres to the de-facto Rust variety of Semantic Versioning. ## Minimum supported Rust version | `bimap` | MSRV | | --- | --- | | v0.6.3 | 1.56.1 | | v0.6.2 | 1.56.1 | | v0.6.1 | 1.42.0 | | v0.6.0 | 1.38.0 | | v0.5.3 | 1.38.0 | | v0.5.2 | 1.38.0 | | v0.5.1 | 1.38.0 | | v0.5.0 | 1.38.0 | | v0.4.0 | 1.38.0 | ## License `bimap-rs` is dual-licensed under the [Apache License] and the [MIT License]. As a library user, this means that you are free to choose either license when using `bimap-rs`. As a library contributor, this means that any work you contribute to `bimap-rs` will be similarly dual-licensed. [docs.rs]: https://docs.rs/bimap/ [lib.rs]: https://lib.rs/crates/bimap [`no_std`]: https://rust-embedded.github.io/book/intro/no-std.html [Serde]: https://serde.rs/ [Apache License]: LICENSE_APACHE [code of conduct]: CODE_OF_CONDUCT.md [contributing guidelines]: CONTRIBUTING.md [MIT License]: LICENSE_MIT [documentation badge]: https://img.shields.io/static/v1?label=documentation&message=docs.rs&color=blueviolet [license badge]: https://img.shields.io/static/v1?label=license&message=Apache-2.0/MIT&color=blueviolet [version badge]: https://img.shields.io/static/v1?label=latest%20version&message=lib.rs&color=blueviolet bimap-0.6.3/rustfmt.toml000064400000000000000000000001061046102023000133200ustar 00000000000000imports_granularity = "Crate" wrap_comments = true comment_width = 80 bimap-0.6.3/src/btree.rs000064400000000000000000001062431046102023000131660ustar 00000000000000//! A bimap backed by two `BTreeMap`s. use crate::{ mem::{Ref, Wrapper}, Overwritten, }; use alloc::{ collections::{btree_map, BTreeMap}, rc::Rc, }; use core::{ borrow::Borrow, cmp::Ordering, fmt, hash::{Hash, Hasher}, iter::{Extend, FromIterator, FusedIterator}, ops::RangeBounds, }; /// A bimap backed by two `BTreeMap`s. /// /// See the [module-level documentation] for more details and examples. /// /// [module-level documentation]: crate pub struct BiBTreeMap { left2right: BTreeMap, Ref>, right2left: BTreeMap, Ref>, } impl BiBTreeMap where L: Ord, R: Ord, { /// Creates an empty `BiBTreeMap`. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let bimap = BiBTreeMap::::new(); /// ``` pub fn new() -> Self { Self { left2right: BTreeMap::new(), right2left: BTreeMap::new(), } } /// Returns the number of left-right pairs in the bimap. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// assert_eq!(bimap.len(), 3); /// ``` pub fn len(&self) -> usize { self.left2right.len() } /// Returns `true` if the bimap contains no left-right pairs, and `false` /// otherwise. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// assert!(bimap.is_empty()); /// bimap.insert('a', 1); /// assert!(!bimap.is_empty()); /// bimap.remove_by_right(&1); /// assert!(bimap.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.left2right.is_empty() } /// Removes all left-right pairs from the bimap. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// bimap.clear(); /// assert!(bimap.len() == 0); /// ``` pub fn clear(&mut self) { self.left2right.clear(); self.right2left.clear(); } /// Creates an iterator over the left-right pairs in the bimap in ascending /// order by left value. /// /// The iterator element type is `(&L, &R)`. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// for (left, right) in bimap.iter() { /// println!("({}, {})", left, right); /// } /// ``` pub fn iter(&self) -> Iter<'_, L, R> { Iter { inner: self.left2right.iter(), } } /// Creates an iterator over the left values in the bimap in ascending /// order. /// /// The iterator element type is `&L`. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// for char_value in bimap.left_values() { /// println!("{}", char_value); /// } /// ``` pub fn left_values(&self) -> LeftValues<'_, L, R> { LeftValues { inner: self.left2right.iter(), } } /// Creates an iterator over the right values in the bimap in ascending /// order. /// /// The iterator element type is `&R`. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// for int_value in bimap.right_values() { /// println!("{}", int_value); /// } /// ``` pub fn right_values(&self) -> RightValues<'_, L, R> { RightValues { inner: self.right2left.iter(), } } /// Returns a reference to the right value corresponding to the given left /// value. /// /// The input may be any borrowed form of the bimap's left type, but the /// ordering on the borrowed form *must* match the ordering on the left /// type. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// assert_eq!(bimap.get_by_left(&'a'), Some(&1)); /// assert_eq!(bimap.get_by_left(&'z'), None); /// ``` pub fn get_by_left(&self, left: &Q) -> Option<&R> where L: Borrow, Q: Ord + ?Sized, { self.left2right.get(Wrapper::wrap(left)).map(|l| &*l.0) } /// Returns a reference to the left value corresponding to the given right /// value. /// /// The input may be any borrowed form of the bimap's right type, but the /// ordering on the borrowed form *must* match the ordering on the right /// type. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// assert_eq!(bimap.get_by_right(&1), Some(&'a')); /// assert_eq!(bimap.get_by_right(&2), None); /// ``` pub fn get_by_right(&self, right: &Q) -> Option<&L> where R: Borrow, Q: Ord + ?Sized, { self.right2left.get(Wrapper::wrap(right)).map(|r| &*r.0) } /// Returns `true` if the bimap contains the given left value and `false` /// otherwise. /// /// The input may be any borrowed form of the bimap's left type, but the /// ordering on the borrowed form *must* match the ordering on the left /// type. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// assert!(bimap.contains_left(&'a')); /// assert!(!bimap.contains_left(&'b')); /// ``` pub fn contains_left(&self, left: &Q) -> bool where L: Borrow, Q: Ord + ?Sized, { self.left2right.contains_key(Wrapper::wrap(left)) } /// Returns `true` if the map contains the given right value and `false` /// otherwise. /// /// The input may be any borrowed form of the bimap's right type, but the /// ordering on the borrowed form *must* match the ordering on the right /// type. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// assert!(bimap.contains_right(&1)); /// assert!(!bimap.contains_right(&2)); /// ``` pub fn contains_right(&self, right: &Q) -> bool where R: Borrow, Q: Ord + ?Sized, { self.right2left.contains_key(Wrapper::wrap(right)) } /// Removes the left-right pair corresponding to the given left value. /// /// Returns the previous left-right pair if the map contained the left value /// and `None` otherwise. /// /// The input may be any borrowed form of the bimap's left type, but the /// ordering on the borrowed form *must* match the ordering on the left /// type. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// assert_eq!(bimap.remove_by_left(&'b'), Some(('b', 2))); /// assert_eq!(bimap.remove_by_left(&'b'), None); /// ``` pub fn remove_by_left(&mut self, left: &Q) -> Option<(L, R)> where L: Borrow, Q: Ord + ?Sized, { self.left2right.remove(Wrapper::wrap(left)).map(|right_rc| { // unwrap is safe because we know right2left contains the key (it's a bimap) let left_rc = self.right2left.remove(&right_rc).unwrap(); // at this point we can safely unwrap because the other pointers are gone ( Rc::try_unwrap(left_rc.0).ok().unwrap(), Rc::try_unwrap(right_rc.0).ok().unwrap(), ) }) } /// Removes the left-right pair corresponding to the given right value. /// /// Returns the previous left-right pair if the map contained the right /// value and `None` otherwise. /// /// The input may be any borrowed form of the bimap's right type, but the /// ordering on the borrowed form *must* match the ordering on the right /// type. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// assert_eq!(bimap.remove_by_right(&2), Some(('b', 2))); /// assert_eq!(bimap.remove_by_right(&2), None); /// ``` pub fn remove_by_right(&mut self, right: &Q) -> Option<(L, R)> where R: Borrow, Q: Ord + ?Sized, { self.right2left.remove(Wrapper::wrap(right)).map(|left_rc| { // unwrap is safe because we know left2right contains the key (it's a bimap) let right_rc = self.left2right.remove(&left_rc).unwrap(); // at this point we can safely unwrap because the other pointers are gone ( Rc::try_unwrap(left_rc.0).ok().unwrap(), Rc::try_unwrap(right_rc.0).ok().unwrap(), ) }) } /// Retains only elements specified by a predicate /// /// In other words, remove all left-right pairs `(l, r)` such that `f(&l, /// &r)` returns `false`. /// /// # Example /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// bimap.retain(|&l, _| l != 'b'); /// assert_eq!(bimap.len(), 2); /// assert_eq!(bimap.get_by_right(&1), Some(&'a')); /// assert_eq!(bimap.get_by_right(&2), None); /// assert_eq!(bimap.get_by_right(&3), Some(&'c')); /// ``` pub fn retain(&mut self, f: F) where F: FnMut(&L, &R) -> bool, { let mut f = f; let right2left = &mut self.right2left; self.left2right.retain(|l, r| { let to_retain = f(&l.0, &r.0); if !to_retain { right2left.remove(r); } to_retain }) } /// Inserts the given left-right pair into the bimap. /// /// Returns an enum `Overwritten` representing any left-right pairs that /// were overwritten by the call to `insert`. The example below details /// all possible enum variants that can be returned. /// /// # Warnings /// /// Somewhat paradoxically, calling `insert()` can actually reduce the size /// of the bimap! This is because of the invariant that each left value /// maps to exactly one right value and vice versa. /// /// # Examples /// /// ``` /// use bimap::{BiBTreeMap, Overwritten}; /// /// let mut bimap = BiBTreeMap::new(); /// assert_eq!(bimap.len(), 0); // {} /// /// // no values are overwritten. /// assert_eq!(bimap.insert('a', 1), Overwritten::Neither); /// assert_eq!(bimap.len(), 1); // {'a' <> 1} /// /// // no values are overwritten. /// assert_eq!(bimap.insert('b', 2), Overwritten::Neither); /// assert_eq!(bimap.len(), 2); // {'a' <> 1, 'b' <> 2} /// /// // ('a', 1) already exists, so inserting ('a', 4) overwrites 'a', the left value. /// // the previous left-right pair ('a', 1) is returned. /// assert_eq!(bimap.insert('a', 4), Overwritten::Left('a', 1)); /// assert_eq!(bimap.len(), 2); // {'a' <> 4, 'b' <> 2} /// /// // ('b', 2) already exists, so inserting ('c', 2) overwrites 2, the right value. /// // the previous left-right pair ('b', 2) is returned. /// assert_eq!(bimap.insert('c', 2), Overwritten::Right('b', 2)); /// assert_eq!(bimap.len(), 2); // {'a' <> 1, 'c' <> 2} /// /// // both ('a', 4) and ('c', 2) already exist, so inserting ('a', 2) overwrites both. /// // ('a', 4) has the overwritten left value ('a'), so it's the first tuple returned. /// // ('c', 2) has the overwritten right value (2), so it's the second tuple returned. /// assert_eq!(bimap.insert('a', 2), Overwritten::Both(('a', 4), ('c', 2))); /// assert_eq!(bimap.len(), 1); // {'a' <> 2} // bimap is smaller than before! /// /// // ('a', 2) already exists, so inserting ('a', 2) overwrites the pair. /// // the previous left-right pair ('a', 2) is returned. /// assert_eq!(bimap.insert('a', 2), Overwritten::Pair('a', 2)); /// assert_eq!(bimap.len(), 1); // {'a' <> 2} /// ``` pub fn insert(&mut self, left: L, right: R) -> Overwritten { let retval = match (self.remove_by_left(&left), self.remove_by_right(&right)) { (None, None) => Overwritten::Neither, (None, Some(r_pair)) => Overwritten::Right(r_pair.0, r_pair.1), (Some(l_pair), None) => { // since remove_by_left() was called first, it's possible the right value was // removed if a duplicate pair is being inserted if l_pair.1 == right { Overwritten::Pair(l_pair.0, l_pair.1) } else { Overwritten::Left(l_pair.0, l_pair.1) } } (Some(l_pair), Some(r_pair)) => Overwritten::Both(l_pair, r_pair), }; self.insert_unchecked(left, right); retval } /// Inserts the given left-right pair into the bimap without overwriting any /// existing values. /// /// Returns `Ok(())` if the pair was successfully inserted into the bimap. /// If either value exists in the map, `Err((left, right)` is returned /// with the attempted left-right pair and the map is unchanged. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// assert_eq!(bimap.insert_no_overwrite('a', 1), Ok(())); /// assert_eq!(bimap.insert_no_overwrite('b', 2), Ok(())); /// assert_eq!(bimap.insert_no_overwrite('a', 3), Err(('a', 3))); /// assert_eq!(bimap.insert_no_overwrite('c', 2), Err(('c', 2))); /// ``` pub fn insert_no_overwrite(&mut self, left: L, right: R) -> Result<(), (L, R)> { if self.contains_left(&left) || self.contains_right(&right) { Err((left, right)) } else { self.insert_unchecked(left, right); Ok(()) } } /// Inserts the given left-right pair into the bimap without checking if the /// pair already exists. fn insert_unchecked(&mut self, left: L, right: R) { let left = Ref(Rc::new(left)); let right_rc = Ref(Rc::new(right)); self.left2right.insert(left.clone(), right_rc.clone()); self.right2left.insert(right_rc, left); } /// Creates an iterator over the left-right pairs lying within a range of /// left values in the bimap in ascending order by left. /// /// The iterator element type is `(&L, &R)`. /// /// The range bounds may be any borrowed form of the bimap's left type, but /// the ordering on the borrowed form *must* match the ordering on the left /// type. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// bimap.insert('d', 4); /// /// for (left, right) in bimap.left_range('b'..'d') { /// println!("({}, {})", left, right); /// } /// ``` pub fn left_range(&self, range: A) -> LeftRange<'_, L, R> where L: Borrow, A: RangeBounds, T: Ord + ?Sized, { let start = Wrapper::wrap_bound(range.start_bound()); let end = Wrapper::wrap_bound(range.end_bound()); LeftRange { inner: self.left2right.range::, _>((start, end)), } } /// Creates an iterator over the left-right pairs lying within a range of /// right values in the bimap in ascending order by right. /// /// The iterator element type is `(&L, &R)`. /// /// The range bounds may be any borrowed form of the bimap's right type, but /// the ordering on the borrowed form *must* match the ordering on the right /// type. /// /// # Examples /// /// ``` /// use bimap::BiBTreeMap; /// /// let mut bimap = BiBTreeMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// bimap.insert('d', 4); /// /// for (left, right) in bimap.right_range(2..4) { /// println!("({}, {})", left, right); /// } /// ``` pub fn right_range(&self, range: A) -> RightRange<'_, L, R> where R: Borrow, A: RangeBounds, T: Ord + ?Sized, { let start = Wrapper::wrap_bound(range.start_bound()); let end = Wrapper::wrap_bound(range.end_bound()); RightRange { inner: self.right2left.range::, _>((start, end)), } } } impl Clone for BiBTreeMap where L: Clone + Ord, R: Clone + Ord, { fn clone(&self) -> BiBTreeMap { self.iter().map(|(l, r)| (l.clone(), r.clone())).collect() } } impl fmt::Debug for BiBTreeMap where L: fmt::Debug + Ord, R: fmt::Debug + Ord, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{{")?; for (i, (left, right)) in self.left2right.iter().enumerate() { let comma = if i == 0 { "" } else { ", " }; write!(f, "{}{:?} <> {:?}", comma, left, right)?; } write!(f, "}}")?; Ok(()) } } impl Default for BiBTreeMap where L: Ord, R: Ord, { fn default() -> BiBTreeMap { BiBTreeMap { left2right: BTreeMap::default(), right2left: BTreeMap::default(), } } } impl Eq for BiBTreeMap where L: Ord, R: Ord, { } impl FromIterator<(L, R)> for BiBTreeMap where L: Ord, R: Ord, { fn from_iter(iter: I) -> BiBTreeMap where I: IntoIterator, { let mut bimap = BiBTreeMap::new(); for (left, right) in iter { bimap.insert(left, right); } bimap } } impl<'a, L, R> IntoIterator for &'a BiBTreeMap where L: Ord, R: Ord, { type Item = (&'a L, &'a R); type IntoIter = Iter<'a, L, R>; fn into_iter(self) -> Iter<'a, L, R> { self.iter() } } impl IntoIterator for BiBTreeMap where L: Ord, R: Ord, { type Item = (L, R); type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { IntoIter { inner: self.left2right.into_iter(), } } } impl Extend<(L, R)> for BiBTreeMap where L: Ord, R: Ord, { fn extend>(&mut self, iter: T) { iter.into_iter().for_each(move |(l, r)| { self.insert(l, r); }); } } impl Ord for BiBTreeMap where L: Ord, R: Ord, { fn cmp(&self, other: &Self) -> Ordering { self.left2right.cmp(&other.left2right) } } impl PartialEq for BiBTreeMap where L: Ord, R: Ord, { fn eq(&self, other: &Self) -> bool { self.left2right == other.left2right } } impl PartialOrd for BiBTreeMap where L: Ord, R: Ord, { fn partial_cmp(&self, other: &Self) -> Option { self.left2right.partial_cmp(&other.left2right) } } impl Hash for BiBTreeMap where L: Hash, R: Hash, { fn hash(&self, state: &mut H) { self.left2right.hash(state); } } /// An owning iterator over the left-right pairs in a `BiBTreeMap`. pub struct IntoIter { inner: btree_map::IntoIter, Ref>, } impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option { // unwraps are safe because right2left is gone self.inner.next_back().map(|(l, r)| { ( Rc::try_unwrap(l.0).ok().unwrap(), Rc::try_unwrap(r.0).ok().unwrap(), ) }) } } impl ExactSizeIterator for IntoIter {} impl FusedIterator for IntoIter {} impl Iterator for IntoIter { type Item = (L, R); fn next(&mut self) -> Option { // unwraps are safe because right2left is gone self.inner.next().map(|(l, r)| { ( Rc::try_unwrap(l.0).ok().unwrap(), Rc::try_unwrap(r.0).ok().unwrap(), ) }) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } /// An iterator over the left-right pairs in a `BiBTreeMap`. /// /// This struct is created by the [`iter`] method of `BiBTreeMap`. /// /// [`iter`]: BiBTreeMap::iter #[derive(Debug, Clone)] pub struct Iter<'a, L, R> { inner: btree_map::Iter<'a, Ref, Ref>, } impl<'a, L, R> DoubleEndedIterator for Iter<'a, L, R> { fn next_back(&mut self) -> Option { self.inner.next_back().map(|(l, r)| (&*l.0, &*r.0)) } } impl<'a, L, R> ExactSizeIterator for Iter<'a, L, R> {} impl<'a, L, R> FusedIterator for Iter<'a, L, R> {} impl<'a, L, R> Iterator for Iter<'a, L, R> { type Item = (&'a L, &'a R); fn next(&mut self) -> Option { self.inner.next().map(|(l, r)| (&*l.0, &*r.0)) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } /// An iterator over the left values in a `BiBTreeMap`. /// /// This struct is created by the [`left_values`] method of `BiBTreeMap`. /// /// [`left_values`]: BiBTreeMap::left_values #[derive(Debug, Clone)] pub struct LeftValues<'a, L, R> { inner: btree_map::Iter<'a, Ref, Ref>, } impl<'a, L, R> DoubleEndedIterator for LeftValues<'a, L, R> { fn next_back(&mut self) -> Option { self.inner.next_back().map(|(l, _)| &*l.0) } } impl<'a, L, R> ExactSizeIterator for LeftValues<'a, L, R> {} impl<'a, L, R> FusedIterator for LeftValues<'a, L, R> {} impl<'a, L, R> Iterator for LeftValues<'a, L, R> { type Item = &'a L; fn next(&mut self) -> Option { self.inner.next().map(|(l, _)| &*l.0) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } /// An iterator over the right values in a `BiBTreeMap`. /// /// This struct is created by the [`right_values`] method of `BiBTreeMap`. /// /// [`right_values`]: BiBTreeMap::right_values #[derive(Debug, Clone)] pub struct RightValues<'a, L, R> { inner: btree_map::Iter<'a, Ref, Ref>, } impl<'a, L, R> DoubleEndedIterator for RightValues<'a, L, R> { fn next_back(&mut self) -> Option { self.inner.next_back().map(|(r, _)| &*r.0) } } impl<'a, L, R> ExactSizeIterator for RightValues<'a, L, R> {} impl<'a, L, R> FusedIterator for RightValues<'a, L, R> {} impl<'a, L, R> Iterator for RightValues<'a, L, R> { type Item = &'a R; fn next(&mut self) -> Option { self.inner.next().map(|(r, _)| &*r.0) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } /// An iterator over a range of left-right pairs in a `BiBTreeMap`. /// /// This struct is created by the [`left_range`] method of `BiBTreeMap`. /// /// [`left_range`]: BiBTreeMap::left_range #[derive(Debug, Clone)] pub struct LeftRange<'a, L, R> { inner: btree_map::Range<'a, Ref, Ref>, } impl<'a, L, R> DoubleEndedIterator for LeftRange<'a, L, R> { fn next_back(&mut self) -> Option { self.inner.next_back().map(|(l, r)| (&*l.0, &*r.0)) } } impl<'a, L, R> ExactSizeIterator for LeftRange<'a, L, R> {} impl<'a, L, R> FusedIterator for LeftRange<'a, L, R> {} impl<'a, L, R> Iterator for LeftRange<'a, L, R> { type Item = (&'a L, &'a R); fn next(&mut self) -> Option { self.inner.next().map(|(l, r)| (&*l.0, &*r.0)) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } /// An iterator over a range of left-right pairs in a `BiBTreeMap`. /// /// This struct is created by the [`right_range`] method of `BiBTreeMap`. /// /// [`right_range`]: BiBTreeMap::right_range #[derive(Debug, Clone)] pub struct RightRange<'a, L, R> { inner: btree_map::Range<'a, Ref, Ref>, } impl<'a, L, R> DoubleEndedIterator for RightRange<'a, L, R> { fn next_back(&mut self) -> Option { self.inner.next_back().map(|(r, l)| (&*l.0, &*r.0)) } } impl<'a, L, R> ExactSizeIterator for RightRange<'a, L, R> {} impl<'a, L, R> FusedIterator for RightRange<'a, L, R> {} impl<'a, L, R> Iterator for RightRange<'a, L, R> { type Item = (&'a L, &'a R); fn next(&mut self) -> Option { self.inner.next().map(|(r, l)| (&*l.0, &*r.0)) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } // safe because internal Rcs are not exposed by the api and the reference counts // only change in methods with &mut self unsafe impl Send for BiBTreeMap where L: Send, R: Send, { } unsafe impl Sync for BiBTreeMap where L: Sync, R: Sync, { } #[cfg(test)] mod tests { use super::*; #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[test] fn clone() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); let bimap2 = bimap.clone(); assert_eq!(bimap, bimap2); } #[test] fn deep_clone() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); let mut bimap2 = bimap.clone(); // would panic if clone() didn't deep clone bimap.insert('b', 5); bimap2.insert('a', 12); bimap2.remove_by_left(&'a'); bimap.remove_by_right(&2); } #[test] fn debug() { let mut bimap = BiBTreeMap::new(); assert_eq!("{}", format!("{:?}", bimap)); bimap.insert('a', 1); assert_eq!("{'a' <> 1}", format!("{:?}", bimap)); bimap.insert('b', 2); assert_eq!("{'a' <> 1, 'b' <> 2}", format!("{:?}", bimap)); } #[test] fn default() { let _ = BiBTreeMap::::default(); } #[test] fn eq() { let mut bimap = BiBTreeMap::new(); assert_eq!(bimap, bimap); bimap.insert('a', 1); assert_eq!(bimap, bimap); bimap.insert('b', 2); assert_eq!(bimap, bimap); let mut bimap2 = BiBTreeMap::new(); assert_ne!(bimap, bimap2); bimap2.insert('a', 1); assert_ne!(bimap, bimap2); bimap2.insert('b', 2); assert_eq!(bimap, bimap2); bimap2.insert('c', 3); assert_ne!(bimap, bimap2); } #[test] fn from_iter() { let bimap = BiBTreeMap::from_iter(vec![ ('a', 1), ('b', 2), ('c', 3), ('b', 2), ('a', 4), ('b', 3), ]); let mut bimap2 = BiBTreeMap::new(); bimap2.insert('a', 4); bimap2.insert('b', 3); assert_eq!(bimap, bimap2); } #[test] fn into_iter() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let pairs = bimap.into_iter().collect::>(); assert_eq!(pairs, vec![('a', 3), ('b', 2), ('c', 1)]); } #[test] fn into_iter_ref() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let pairs = (&bimap).into_iter().collect::>(); assert_eq!(pairs, vec![(&'a', &3), (&'b', &2), (&'c', &1)]); } #[test] fn extend() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.extend(vec![('c', 3), ('b', 1), ('a', 4)]); let mut bimap2 = BiBTreeMap::new(); bimap2.insert('a', 4); bimap2.insert('b', 1); bimap2.insert('c', 3); assert_eq!(bimap, bimap2); } #[test] fn cmp() { let bimap = BiBTreeMap::from_iter(vec![('a', 2)]); let bimap2 = BiBTreeMap::from_iter(vec![('b', 1)]); assert_eq!(bimap.partial_cmp(&bimap2), Some(Ordering::Less)); assert_eq!(bimap.cmp(&bimap2), Ordering::Less); assert_eq!(bimap2.partial_cmp(&bimap), Some(Ordering::Greater)); assert_eq!(bimap2.cmp(&bimap), Ordering::Greater); assert_eq!(bimap.cmp(&bimap), Ordering::Equal); assert_eq!(bimap2.cmp(&bimap2), Ordering::Equal); } #[test] fn iter() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); bimap.insert('c', 3); let pairs = bimap.iter().map(|(c, i)| (*c, *i)).collect::>(); assert_eq!(pairs, vec![('a', 1), ('b', 2), ('c', 3)]); } #[test] fn iter_rev() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); bimap.insert('c', 3); let mut iter = bimap.iter(); assert_eq!(iter.next_back(), Some((&'c', &3))); assert_eq!(iter.next_back(), Some((&'b', &2))); assert_eq!(iter.next_back(), Some((&'a', &1))); } #[test] fn into_iter_rev() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); bimap.insert('c', 3); let mut iter = bimap.into_iter(); assert_eq!(iter.next_back(), Some(('c', 3))); assert_eq!(iter.next_back(), Some(('b', 2))); assert_eq!(iter.next_back(), Some(('a', 1))); } #[test] fn left_values() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let left_values = bimap.left_values().cloned().collect::>(); assert_eq!(left_values, vec!['a', 'b', 'c']) } #[test] fn left_values_rev() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let mut iter = bimap.left_values(); assert_eq!(iter.next_back(), Some(&'c')); assert_eq!(iter.next_back(), Some(&'b')); assert_eq!(iter.next_back(), Some(&'a')); } #[test] fn right_values() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let right_values = bimap.right_values().cloned().collect::>(); assert_eq!(right_values, vec![1, 2, 3]) } #[test] fn right_values_rev() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let mut iter = bimap.right_values(); assert_eq!(iter.next_back(), Some(&3)); assert_eq!(iter.next_back(), Some(&2)); assert_eq!(iter.next_back(), Some(&1)); } #[test] fn left_range() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 4); bimap.insert('b', 3); bimap.insert('c', 2); bimap.insert('d', 1); let left_range = bimap .left_range('b'..'d') .map(|(l, r)| (*l, *r)) .collect::>(); assert_eq!(left_range, vec![('b', 3), ('c', 2)]) } #[test] fn left_range_rev() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 4); bimap.insert('b', 3); bimap.insert('c', 2); bimap.insert('d', 1); let mut left_range = bimap.left_range('b'..'d'); assert_eq!(left_range.next_back(), Some((&'c', &2))); assert_eq!(left_range.next_back(), Some((&'b', &3))); assert_eq!(left_range.next_back(), None); } #[test] fn right_range() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 4); bimap.insert('b', 3); bimap.insert('c', 2); bimap.insert('d', 1); let right_range = bimap .right_range(2..4) .map(|(l, r)| (*l, *r)) .collect::>(); assert_eq!(right_range, vec![('c', 2), ('b', 3)]) } #[test] fn right_range_rev() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 4); bimap.insert('b', 3); bimap.insert('c', 2); bimap.insert('d', 1); let mut right_range = bimap.right_range(2..4); assert_eq!(right_range.next_back(), Some((&'b', &3))); assert_eq!(right_range.next_back(), Some((&'c', &2))); assert_eq!(right_range.next_back(), None); } #[test] fn clear() { let mut bimap = BiBTreeMap::from_iter(vec![('a', 1)]); assert_eq!(bimap.len(), 1); assert!(!bimap.is_empty()); bimap.clear(); assert_eq!(bimap.len(), 0); assert!(bimap.is_empty()); } #[test] fn get_contains() { let bimap = BiBTreeMap::from_iter(vec![('a', 1)]); assert_eq!(bimap.get_by_left(&'a'), Some(&1)); assert!(bimap.contains_left(&'a')); assert_eq!(bimap.get_by_left(&'b'), None); assert!(!bimap.contains_left(&'b')); assert_eq!(bimap.get_by_right(&1), Some(&'a')); assert!(bimap.contains_right(&1)); assert_eq!(bimap.get_by_right(&2), None); assert!(!bimap.contains_right(&2)); } #[test] fn insert() { let mut bimap = BiBTreeMap::new(); assert_eq!(bimap.insert('a', 1), Overwritten::Neither); assert_eq!(bimap.insert('a', 2), Overwritten::Left('a', 1)); assert_eq!(bimap.insert('b', 2), Overwritten::Right('a', 2)); assert_eq!(bimap.insert('b', 2), Overwritten::Pair('b', 2)); assert_eq!(bimap.insert('c', 3), Overwritten::Neither); assert_eq!(bimap.insert('b', 3), Overwritten::Both(('b', 2), ('c', 3))); } #[test] fn insert_no_overwrite() { let mut bimap = BiBTreeMap::new(); assert!(bimap.insert_no_overwrite('a', 1).is_ok()); assert!(bimap.insert_no_overwrite('a', 2).is_err()); assert!(bimap.insert_no_overwrite('b', 1).is_err()); } #[test] #[cfg(feature = "std")] fn hash() { use core::iter::{self, FromIterator}; use std::collections::HashSet; let mut hashset = HashSet::new(); hashset.insert(BiBTreeMap::new()); hashset.insert(BiBTreeMap::from_iter(iter::once((0, '0')))); hashset.insert(BiBTreeMap::from_iter(vec![(0, '0'), (0, '1'), (1, '0')])); hashset.insert(BiBTreeMap::from_iter(vec![(1, '0'), (0, '1'), (0, '0')])); hashset.insert(BiBTreeMap::from_iter(vec![(0, '0'), (0, '1'), (1, '0')])); assert_eq!( hashset, HashSet::from_iter(vec![ BiBTreeMap::new(), BiBTreeMap::from_iter(iter::once((0, '0'))), BiBTreeMap::from_iter(vec![(0, '0'), (1, '0'), (0, '1')]), ]) ); } } bimap-0.6.3/src/hash.rs000064400000000000000000001045161046102023000130110ustar 00000000000000//! A bimap backed by two `HashMap`s. use crate::{ mem::{Ref, Wrapper}, Overwritten, }; use std::{ borrow::Borrow, collections::{hash_map, HashMap}, fmt, hash::{BuildHasher, Hash}, iter::{Extend, FromIterator, FusedIterator}, rc::Rc, }; /// A bimap backed by two `HashMap`s. /// /// See the [module-level documentation] for more details and examples. /// /// [module-level documentation]: crate pub struct BiHashMap { left2right: HashMap, Ref, LS>, right2left: HashMap, Ref, RS>, } impl BiHashMap where L: Eq + Hash, R: Eq + Hash, { /// Creates an empty `BiHashMap`. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let bimap = BiHashMap::::new(); /// ``` pub fn new() -> Self { Self { left2right: HashMap::new(), right2left: HashMap::new(), } } /// Creates a new empty `BiHashMap` with the given capacity. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let bimap = BiHashMap::::with_capacity(10); /// assert!(bimap.capacity() >= 10); /// ``` pub fn with_capacity(capacity: usize) -> Self { Self { left2right: HashMap::with_capacity(capacity), right2left: HashMap::with_capacity(capacity), } } } impl BiHashMap where L: Eq + Hash, R: Eq + Hash, { /// Returns the number of left-right pairs in the bimap. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// assert_eq!(bimap.len(), 3); /// ``` pub fn len(&self) -> usize { self.left2right.len() } /// Returns `true` if the bimap contains no left-right pairs, and `false` /// otherwise. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// assert!(bimap.is_empty()); /// bimap.insert('a', 1); /// assert!(!bimap.is_empty()); /// bimap.remove_by_right(&1); /// assert!(bimap.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.left2right.is_empty() } /// Returns a lower bound on the number of left-right pairs the `BiHashMap` /// can store without reallocating memory. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let bimap = BiHashMap::::with_capacity(10); /// assert!(bimap.capacity() >= 10); /// ``` pub fn capacity(&self) -> usize { self.left2right.capacity().min(self.right2left.capacity()) } /// Removes all left-right pairs from the bimap. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// bimap.clear(); /// assert!(bimap.len() == 0); /// ``` pub fn clear(&mut self) { self.left2right.clear(); self.right2left.clear(); } /// Creates an iterator over the left-right pairs in the bimap in arbitrary /// order. /// /// The iterator element type is `(&L, &R)`. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// for (left, right) in bimap.iter() { /// println!("({}, {})", left, right); /// } /// ``` pub fn iter(&self) -> Iter<'_, L, R> { Iter { inner: self.left2right.iter(), } } /// Creates an iterator over the left values in the bimap in arbitrary /// order. /// /// The iterator element type is `&L`. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// for char_value in bimap.left_values() { /// println!("{}", char_value); /// } /// ``` pub fn left_values(&self) -> LeftValues<'_, L, R> { LeftValues { inner: self.left2right.iter(), } } /// Creates an iterator over the right values in the bimap in arbitrary /// order. /// /// The iterator element type is `&R`. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// for int_value in bimap.right_values() { /// println!("{}", int_value); /// } /// ``` pub fn right_values(&self) -> RightValues<'_, L, R> { RightValues { inner: self.right2left.iter(), } } } impl BiHashMap where L: Eq + Hash, R: Eq + Hash, LS: BuildHasher, RS: BuildHasher, { /// Creates a new empty `BiHashMap` using `hash_builder_left` to hash left /// values and `hash_builder_right` to hash right values. /// /// # Examples /// /// ``` /// use std::collections::hash_map::RandomState; /// use bimap::BiHashMap; /// /// let s_left = RandomState::new(); /// let s_right = RandomState::new(); /// let mut bimap = BiHashMap::::with_hashers(s_left, s_right); /// bimap.insert('a', 42); /// ``` pub fn with_hashers(hash_builder_left: LS, hash_builder_right: RS) -> Self { Self { left2right: HashMap::with_hasher(hash_builder_left), right2left: HashMap::with_hasher(hash_builder_right), } } /// Creates a new empty `BiHashMap` with the given capacity, using /// `hash_builder_left` to hash left values and `hash_builder_right` to /// hash right values. /// /// # Examples /// /// ``` /// use std::collections::hash_map::RandomState; /// use bimap::BiHashMap; /// /// let s_left = RandomState::new(); /// let s_right = RandomState::new(); /// let bimap = BiHashMap::::with_capacity_and_hashers(10, s_left, s_right); /// assert!(bimap.capacity() >= 10); /// ``` pub fn with_capacity_and_hashers( capacity: usize, hash_builder_left: LS, hash_builder_right: RS, ) -> Self { Self { left2right: HashMap::with_capacity_and_hasher(capacity, hash_builder_left), right2left: HashMap::with_capacity_and_hasher(capacity, hash_builder_right), } } /// Reserves capacity for at least `additional` more elements to be inserted /// in the `BiHashMap`. The collection may reserve more space to avoid /// frequent reallocations. /// /// # Panics /// /// Panics if the new allocation size overflows [`usize`]. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::::new(); /// bimap.reserve(10); /// assert!(bimap.capacity() >= 10); /// ``` pub fn reserve(&mut self, additional: usize) { self.left2right.reserve(additional); self.right2left.reserve(additional); } /// Shrinks the capacity of the bimap as much as possible. It will drop /// down as much as possible while maintaining the internal rules /// and possibly leaving some space in accordance with the resize policy. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::::with_capacity(100); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// assert!(bimap.capacity() >= 100); /// bimap.shrink_to_fit(); /// assert!(bimap.capacity() >= 2); /// ``` pub fn shrink_to_fit(&mut self) { self.left2right.shrink_to_fit(); self.right2left.shrink_to_fit(); } /// Shrinks the capacity of the bimap with a lower limit. It will drop /// down no lower than the supplied limit while maintaining the internal /// rules and possibly leaving some space in accordance with the resize /// policy. /// /// If the current capacity is less than the lower limit, this is a no-op. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::::with_capacity(100); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// assert!(bimap.capacity() >= 100); /// bimap.shrink_to(10); /// assert!(bimap.capacity() >= 10); /// bimap.shrink_to(0); /// assert!(bimap.capacity() >= 2); /// ``` pub fn shrink_to(&mut self, min_capacity: usize) { self.left2right.shrink_to(min_capacity); self.right2left.shrink_to(min_capacity); } /// Returns a reference to the right value corresponding to the given left /// value. /// /// The input may be any borrowed form of the bimap's left type, but `Eq` /// and `Hash` on the borrowed form *must* match those for the left type. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// assert_eq!(bimap.get_by_left(&'a'), Some(&1)); /// assert_eq!(bimap.get_by_left(&'z'), None); /// ``` pub fn get_by_left(&self, left: &Q) -> Option<&R> where L: Borrow, Q: Eq + Hash + ?Sized, { self.left2right.get(Wrapper::wrap(left)).map(|r| &*r.0) } /// Returns a reference to the left value corresponding to the given right /// value. /// /// The input may be any borrowed form of the bimap's right type, but `Eq` /// and `Hash` on the borrowed form *must* match those for the right type. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// assert_eq!(bimap.get_by_right(&1), Some(&'a')); /// assert_eq!(bimap.get_by_right(&2), None); /// ``` pub fn get_by_right(&self, right: &Q) -> Option<&L> where R: Borrow, Q: Eq + Hash + ?Sized, { self.right2left.get(Wrapper::wrap(right)).map(|l| &*l.0) } /// Returns `true` if the bimap contains the given left value and `false` /// otherwise. /// /// The input may be any borrowed form of the bimap's left type, but `Eq` /// and `Hash` on the borrowed form *must* match those for the left type. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// assert!(bimap.contains_left(&'a')); /// assert!(!bimap.contains_left(&'b')); /// ``` pub fn contains_left(&self, left: &Q) -> bool where L: Borrow, Q: Eq + Hash + ?Sized, { self.left2right.contains_key(Wrapper::wrap(left)) } /// Returns `true` if the map contains the given right value and `false` /// otherwise. /// /// The input may be any borrowed form of the bimap's right type, but `Eq` /// and `Hash` on the borrowed form *must* match those for the right type. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// assert!(bimap.contains_right(&1)); /// assert!(!bimap.contains_right(&2)); /// ``` pub fn contains_right(&self, right: &Q) -> bool where R: Borrow, Q: Eq + Hash + ?Sized, { self.right2left.contains_key(Wrapper::wrap(right)) } /// Removes the left-right pair corresponding to the given left value. /// /// Returns the previous left-right pair if the map contained the left value /// and `None` otherwise. /// /// The input may be any borrowed form of the bimap's left type, but `Eq` /// and `Hash` on the borrowed form *must* match those for the left type. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// assert_eq!(bimap.remove_by_left(&'b'), Some(('b', 2))); /// assert_eq!(bimap.remove_by_left(&'b'), None); /// ``` pub fn remove_by_left(&mut self, left: &Q) -> Option<(L, R)> where L: Borrow, Q: Eq + Hash + ?Sized, { self.left2right.remove(Wrapper::wrap(left)).map(|right_rc| { // unwrap is safe because we know right2left contains the key (it's a bimap) let left_rc = self.right2left.remove(&right_rc).unwrap(); // at this point we can safely unwrap because the other pointers are gone ( Rc::try_unwrap(left_rc.0).ok().unwrap(), Rc::try_unwrap(right_rc.0).ok().unwrap(), ) }) } /// Removes the left-right pair corresponding to the given right value. /// /// Returns the previous left-right pair if the map contained the right /// value and `None` otherwise. /// /// The input may be any borrowed form of the bimap's right type, but `Eq` /// and `Hash` on the borrowed form *must* match those for the right type. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// /// assert_eq!(bimap.remove_by_right(&2), Some(('b', 2))); /// assert_eq!(bimap.remove_by_right(&2), None); /// ``` pub fn remove_by_right(&mut self, right: &Q) -> Option<(L, R)> where R: Borrow, Q: Eq + Hash + ?Sized, { self.right2left.remove(Wrapper::wrap(right)).map(|left_rc| { // unwrap is safe because we know left2right contains the key (it's a bimap) let right_rc = self.left2right.remove(&left_rc).unwrap(); // at this point we can safely unwrap because the other pointers are gone ( Rc::try_unwrap(left_rc.0).ok().unwrap(), Rc::try_unwrap(right_rc.0).ok().unwrap(), ) }) } /// Inserts the given left-right pair into the bimap. /// /// Returns an enum `Overwritten` representing any left-right pairs that /// were overwritten by the call to `insert`. The example below details /// all possible enum variants that can be returned. /// /// # Warnings /// /// Somewhat paradoxically, calling `insert()` can actually reduce the size /// of the bimap! This is because of the invariant that each left value /// maps to exactly one right value and vice versa. /// /// # Examples /// /// ``` /// use bimap::{BiHashMap, Overwritten}; /// /// let mut bimap = BiHashMap::new(); /// assert_eq!(bimap.len(), 0); // {} /// /// // no values are overwritten. /// assert_eq!(bimap.insert('a', 1), Overwritten::Neither); /// assert_eq!(bimap.len(), 1); // {'a' <> 1} /// /// // no values are overwritten. /// assert_eq!(bimap.insert('b', 2), Overwritten::Neither); /// assert_eq!(bimap.len(), 2); // {'a' <> 1, 'b' <> 2} /// /// // ('a', 1) already exists, so inserting ('a', 4) overwrites 'a', the left value. /// // the previous left-right pair ('a', 1) is returned. /// assert_eq!(bimap.insert('a', 4), Overwritten::Left('a', 1)); /// assert_eq!(bimap.len(), 2); // {'a' <> 4, 'b' <> 2} /// /// // ('b', 2) already exists, so inserting ('c', 2) overwrites 2, the right value. /// // the previous left-right pair ('b', 2) is returned. /// assert_eq!(bimap.insert('c', 2), Overwritten::Right('b', 2)); /// assert_eq!(bimap.len(), 2); // {'a' <> 1, 'c' <> 2} /// /// // both ('a', 4) and ('c', 2) already exist, so inserting ('a', 2) overwrites both. /// // ('a', 4) has the overwritten left value ('a'), so it's the first tuple returned. /// // ('c', 2) has the overwritten right value (2), so it's the second tuple returned. /// assert_eq!(bimap.insert('a', 2), Overwritten::Both(('a', 4), ('c', 2))); /// assert_eq!(bimap.len(), 1); // {'a' <> 2} // bimap is smaller than before! /// /// // ('a', 2) already exists, so inserting ('a', 2) overwrites the pair. /// // the previous left-right pair ('a', 2) is returned. /// assert_eq!(bimap.insert('a', 2), Overwritten::Pair('a', 2)); /// assert_eq!(bimap.len(), 1); // {'a' <> 2} /// ``` pub fn insert(&mut self, left: L, right: R) -> Overwritten { let retval = match (self.remove_by_left(&left), self.remove_by_right(&right)) { (None, None) => Overwritten::Neither, (None, Some(r_pair)) => Overwritten::Right(r_pair.0, r_pair.1), (Some(l_pair), None) => { // since remove_by_left() was called first, it's possible the right value was // removed if a duplicate pair is being inserted if l_pair.1 == right { Overwritten::Pair(l_pair.0, l_pair.1) } else { Overwritten::Left(l_pair.0, l_pair.1) } } (Some(l_pair), Some(r_pair)) => Overwritten::Both(l_pair, r_pair), }; self.insert_unchecked(left, right); retval } /// Inserts the given left-right pair into the bimap without overwriting any /// existing values. /// /// Returns `Ok(())` if the pair was successfully inserted into the bimap. /// If either value exists in the map, `Err((left, right)` is returned /// with the attempted left-right pair and the map is unchanged. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// assert_eq!(bimap.insert_no_overwrite('a', 1), Ok(())); /// assert_eq!(bimap.insert_no_overwrite('b', 2), Ok(())); /// assert_eq!(bimap.insert_no_overwrite('a', 3), Err(('a', 3))); /// assert_eq!(bimap.insert_no_overwrite('c', 2), Err(('c', 2))); /// ``` pub fn insert_no_overwrite(&mut self, left: L, right: R) -> Result<(), (L, R)> { if self.contains_left(&left) || self.contains_right(&right) { Err((left, right)) } else { self.insert_unchecked(left, right); Ok(()) } } /// Retains only the elements specified by the predicate. /// /// In other words, remove all left-right pairs `(l, r)` such that `f(&l, /// &r)` returns `false`. /// /// # Examples /// /// ``` /// use bimap::BiHashMap; /// /// let mut bimap = BiHashMap::new(); /// bimap.insert('a', 1); /// bimap.insert('b', 2); /// bimap.insert('c', 3); /// bimap.retain(|&l, &r| r >= 2); /// assert_eq!(bimap.len(), 2); /// assert_eq!(bimap.get_by_left(&'b'), Some(&2)); /// assert_eq!(bimap.get_by_left(&'c'), Some(&3)); /// assert_eq!(bimap.get_by_left(&'a'), None); /// ``` pub fn retain(&mut self, f: F) where F: FnMut(&L, &R) -> bool, { let mut f = f; let right2left = &mut self.right2left; self.left2right.retain(|l, r| { let to_retain = f(&l.0, &r.0); if !to_retain { right2left.remove(r); } to_retain }); } /// Inserts the given left-right pair into the bimap without checking if the /// pair already exists. fn insert_unchecked(&mut self, left: L, right: R) { let left = Ref(Rc::new(left)); let right = Ref(Rc::new(right)); self.left2right.insert(left.clone(), right.clone()); self.right2left.insert(right, left); } } impl Clone for BiHashMap where L: Clone + Eq + Hash, R: Clone + Eq + Hash, LS: BuildHasher + Clone, RS: BuildHasher + Clone, { fn clone(&self) -> BiHashMap { let mut new_bimap = BiHashMap::with_capacity_and_hashers( self.capacity(), self.left2right.hasher().clone(), self.right2left.hasher().clone(), ); for (l, r) in self.iter() { new_bimap.insert(l.clone(), r.clone()); } new_bimap } } impl fmt::Debug for BiHashMap where L: fmt::Debug, R: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct EntryDebugger<'a, L, R> { left: &'a L, right: &'a R, } impl<'a, L, R> fmt::Debug for EntryDebugger<'a, L, R> where L: fmt::Debug, R: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.left.fmt(f)?; write!(f, " <> ")?; self.right.fmt(f) } } f.debug_set() .entries( self.left2right .iter() .map(|(left, right)| EntryDebugger { left, right }), ) .finish() } } impl Default for BiHashMap where L: Eq + Hash, R: Eq + Hash, LS: BuildHasher + Default, RS: BuildHasher + Default, { fn default() -> BiHashMap { BiHashMap { left2right: HashMap::default(), right2left: HashMap::default(), } } } impl Eq for BiHashMap where L: Eq + Hash, R: Eq + Hash, LS: BuildHasher, RS: BuildHasher, { } impl FromIterator<(L, R)> for BiHashMap where L: Eq + Hash, R: Eq + Hash, LS: BuildHasher + Default, RS: BuildHasher + Default, { fn from_iter(iter: I) -> BiHashMap where I: IntoIterator, { let iter = iter.into_iter(); let mut bimap = match iter.size_hint() { (lower, None) => { BiHashMap::with_capacity_and_hashers(lower, LS::default(), RS::default()) } (_, Some(upper)) => { BiHashMap::with_capacity_and_hashers(upper, LS::default(), RS::default()) } }; for (left, right) in iter { bimap.insert(left, right); } bimap } } impl<'a, L, R, LS, RS> IntoIterator for &'a BiHashMap where L: Eq + Hash, R: Eq + Hash, { type Item = (&'a L, &'a R); type IntoIter = Iter<'a, L, R>; fn into_iter(self) -> Iter<'a, L, R> { self.iter() } } impl IntoIterator for BiHashMap where L: Eq + Hash, R: Eq + Hash, { type Item = (L, R); type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { IntoIter { inner: self.left2right.into_iter(), } } } impl Extend<(L, R)> for BiHashMap where L: Eq + Hash, R: Eq + Hash, LS: BuildHasher, RS: BuildHasher, { fn extend>(&mut self, iter: T) { iter.into_iter().for_each(move |(l, r)| { self.insert(l, r); }); } } impl PartialEq for BiHashMap where L: Eq + Hash, R: Eq + Hash, LS: BuildHasher, RS: BuildHasher, { fn eq(&self, other: &Self) -> bool { self.left2right == other.left2right } } /// An owning iterator over the left-right pairs in a `BiHashMap`. pub struct IntoIter { inner: hash_map::IntoIter, Ref>, } impl ExactSizeIterator for IntoIter {} impl FusedIterator for IntoIter {} impl Iterator for IntoIter { type Item = (L, R); fn next(&mut self) -> Option { self.inner.next().map(|(l, r)| { ( Rc::try_unwrap(l.0).ok().unwrap(), Rc::try_unwrap(r.0).ok().unwrap(), ) }) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } /// An iterator over the left-right pairs in a `BiHashMap`. /// /// This struct is created by the [`iter`] method of `BiHashMap`. /// /// [`iter`]: BiHashMap::iter #[derive(Debug, Clone)] pub struct Iter<'a, L, R> { inner: hash_map::Iter<'a, Ref, Ref>, } impl<'a, L, R> ExactSizeIterator for Iter<'a, L, R> {} impl<'a, L, R> FusedIterator for Iter<'a, L, R> {} impl<'a, L, R> Iterator for Iter<'a, L, R> { type Item = (&'a L, &'a R); fn next(&mut self) -> Option { self.inner.next().map(|(l, r)| (&*l.0, &*r.0)) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } /// An iterator over the left values in a `BiHashMap`. /// /// This struct is created by the [`left_values`] method of `BiHashMap`. /// /// [`left_values`]: BiHashMap::left_values #[derive(Debug, Clone)] pub struct LeftValues<'a, L, R> { inner: hash_map::Iter<'a, Ref, Ref>, } impl<'a, L, R> ExactSizeIterator for LeftValues<'a, L, R> {} impl<'a, L, R> FusedIterator for LeftValues<'a, L, R> {} impl<'a, L, R> Iterator for LeftValues<'a, L, R> { type Item = &'a L; fn next(&mut self) -> Option { self.inner.next().map(|(l, _)| &*l.0) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } /// An iterator over the right values in a `BiHashMap`. /// /// This struct is created by the [`right_values`] method of `BiHashMap`. /// /// [`right_values`]: BiHashMap::right_values #[derive(Debug, Clone)] pub struct RightValues<'a, L, R> { inner: hash_map::Iter<'a, Ref, Ref>, } impl<'a, L, R> ExactSizeIterator for RightValues<'a, L, R> {} impl<'a, L, R> FusedIterator for RightValues<'a, L, R> {} impl<'a, L, R> Iterator for RightValues<'a, L, R> { type Item = &'a R; fn next(&mut self) -> Option { self.inner.next().map(|(r, _)| &*r.0) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } // safe because internal Rcs are not exposed by the api and the reference counts // only change in methods with &mut self unsafe impl Send for BiHashMap where L: Send, R: Send, LS: Send, RS: Send, { } unsafe impl Sync for BiHashMap where L: Sync, R: Sync, LS: Sync, RS: Sync, { } #[cfg(test)] mod tests { use super::*; #[test] fn clone() { let mut bimap = BiHashMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); let bimap2 = bimap.clone(); assert_eq!(bimap, bimap2); } #[test] fn deep_clone() { let mut bimap = BiHashMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); let mut bimap2 = bimap.clone(); // would panic if clone() didn't deep clone bimap.insert('b', 5); bimap2.insert('a', 12); bimap2.remove_by_left(&'a'); bimap.remove_by_right(&2); } #[test] fn debug() { let mut bimap = BiHashMap::new(); assert_eq!("{}", format!("{:?}", bimap)); bimap.insert('a', 1); assert_eq!("{'a' <> 1}", format!("{:?}", bimap)); bimap.insert('b', 2); let expected1 = "{'a' <> 1, 'b' <> 2}"; let expected2 = "{'b' <> 2, 'a' <> 1}"; let formatted = format!("{:?}", bimap); assert!(formatted == expected1 || formatted == expected2); } #[test] fn default() { let _ = BiHashMap::::default(); } #[test] fn eq() { let mut bimap = BiHashMap::new(); assert_eq!(bimap, bimap); bimap.insert('a', 1); assert_eq!(bimap, bimap); bimap.insert('b', 2); assert_eq!(bimap, bimap); let mut bimap2 = BiHashMap::new(); assert_ne!(bimap, bimap2); bimap2.insert('a', 1); assert_ne!(bimap, bimap2); bimap2.insert('b', 2); assert_eq!(bimap, bimap2); bimap2.insert('c', 3); assert_ne!(bimap, bimap2); } #[test] fn from_iter() { let bimap = BiHashMap::from_iter(vec![ ('a', 1), ('b', 2), ('c', 3), ('b', 2), ('a', 4), ('b', 3), ]); let mut bimap2 = BiHashMap::new(); bimap2.insert('a', 4); bimap2.insert('b', 3); assert_eq!(bimap, bimap2); } #[test] fn into_iter() { let mut bimap = BiHashMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let mut pairs = bimap.into_iter().collect::>(); pairs.sort(); assert_eq!(pairs, vec![('a', 3), ('b', 2), ('c', 1)]); } #[test] fn into_iter_ref() { let mut bimap = BiHashMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let mut pairs = (&bimap).into_iter().collect::>(); pairs.sort(); assert_eq!(pairs, vec![(&'a', &3), (&'b', &2), (&'c', &1)]); } #[test] fn extend() { let mut bimap = BiHashMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.extend(vec![('c', 3), ('b', 1), ('a', 4)]); let mut bimap2 = BiHashMap::new(); bimap2.insert('a', 4); bimap2.insert('b', 1); bimap2.insert('c', 3); assert_eq!(bimap, bimap2); } #[test] fn iter() { let mut bimap = BiHashMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); bimap.insert('c', 3); let mut pairs = bimap.iter().map(|(c, i)| (*c, *i)).collect::>(); pairs.sort(); assert_eq!(pairs, vec![('a', 1), ('b', 2), ('c', 3)]); } #[test] fn left_values() { let mut bimap = BiHashMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let mut left_values = bimap.left_values().cloned().collect::>(); left_values.sort(); assert_eq!(left_values, vec!['a', 'b', 'c']) } #[test] fn right_values() { let mut bimap = BiHashMap::new(); bimap.insert('a', 3); bimap.insert('b', 2); bimap.insert('c', 1); let mut right_values = bimap.right_values().cloned().collect::>(); right_values.sort(); assert_eq!(right_values, vec![1, 2, 3]) } #[test] fn capacity() { let bimap = BiHashMap::::with_capacity(10); assert!(bimap.capacity() >= 10); } #[test] fn with_hashers() { let s_left = hash_map::RandomState::new(); let s_right = hash_map::RandomState::new(); let mut bimap = BiHashMap::::with_hashers(s_left, s_right); bimap.insert('a', 42); assert_eq!(Some(&'a'), bimap.get_by_right(&42)); assert_eq!(Some(&42), bimap.get_by_left(&'a')); } #[test] fn reserve() { let mut bimap = BiHashMap::::new(); assert!(bimap.is_empty()); assert_eq!(bimap.len(), 0); assert_eq!(bimap.capacity(), 0); bimap.reserve(10); assert!(bimap.is_empty()); assert_eq!(bimap.len(), 0); assert!(bimap.capacity() >= 10); } #[test] fn shrink_to_fit() { let mut bimap = BiHashMap::::with_capacity(100); assert!(bimap.is_empty()); assert_eq!(bimap.len(), 0); assert!(bimap.capacity() >= 100); bimap.insert('a', 1); bimap.insert('b', 2); assert!(!bimap.is_empty()); assert_eq!(bimap.len(), 2); assert!(bimap.capacity() >= 100); bimap.shrink_to_fit(); assert!(!bimap.is_empty()); assert_eq!(bimap.len(), 2); assert!(bimap.capacity() >= 2); } #[test] fn shrink_to() { let mut bimap = BiHashMap::::with_capacity(100); assert!(bimap.is_empty()); assert_eq!(bimap.len(), 0); assert!(bimap.capacity() >= 100); bimap.insert('a', 1); bimap.insert('b', 2); assert!(!bimap.is_empty()); assert_eq!(bimap.len(), 2); assert!(bimap.capacity() >= 100); bimap.shrink_to(10); assert!(!bimap.is_empty()); assert_eq!(bimap.len(), 2); assert!(bimap.capacity() >= 10); bimap.shrink_to(0); assert!(!bimap.is_empty()); assert_eq!(bimap.len(), 2); assert!(bimap.capacity() >= 2); } #[test] fn clear() { let mut bimap = vec![('a', 1)].into_iter().collect::>(); assert_eq!(bimap.len(), 1); assert!(!bimap.is_empty()); bimap.clear(); assert_eq!(bimap.len(), 0); assert!(bimap.is_empty()); } #[test] fn get_contains() { let bimap = vec![('a', 1)].into_iter().collect::>(); assert_eq!(bimap.get_by_left(&'a'), Some(&1)); assert!(bimap.contains_left(&'a')); assert_eq!(bimap.get_by_left(&'b'), None); assert!(!bimap.contains_left(&'b')); assert_eq!(bimap.get_by_right(&1), Some(&'a')); assert!(bimap.contains_right(&1)); assert_eq!(bimap.get_by_right(&2), None); assert!(!bimap.contains_right(&2)); } #[test] fn insert() { let mut bimap = BiHashMap::new(); assert_eq!(bimap.insert('a', 1), Overwritten::Neither); assert_eq!(bimap.insert('a', 2), Overwritten::Left('a', 1)); assert_eq!(bimap.insert('b', 2), Overwritten::Right('a', 2)); assert_eq!(bimap.insert('b', 2), Overwritten::Pair('b', 2)); assert_eq!(bimap.insert('c', 3), Overwritten::Neither); assert_eq!(bimap.insert('b', 3), Overwritten::Both(('b', 2), ('c', 3))); } #[test] fn insert_no_overwrite() { let mut bimap = BiHashMap::new(); assert!(bimap.insert_no_overwrite('a', 1).is_ok()); assert!(bimap.insert_no_overwrite('a', 2).is_err()); assert!(bimap.insert_no_overwrite('b', 1).is_err()); } #[test] fn retain_calls_f_once() { let mut bimap = BiHashMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); bimap.insert('c', 3); // retain one element let mut i = 0; bimap.retain(|_l, _r| { i += 1; i <= 1 }); assert_eq!(bimap.len(), 1); assert_eq!(i, 3); } } bimap-0.6.3/src/lib.rs000064400000000000000000000220671046102023000126340ustar 00000000000000//! A fast two-way bijective map. //! //! A bimap is a [bijective map] between values of type `L`, called left values, //! and values of type `R`, called right values. This means every left value is //! associated with exactly one right value and vice versa. Compare this to a //! [`HashMap`] or [`BTreeMap`], where every key is associated with exactly one //! value but a value can be associated with more than one key. //! //! This crate provides two kinds of bimap: a [`BiHashMap`] and a //! [`BiBTreeMap`]. Internally, each one is composed of two maps, one for the //! left-to-right direction and one for right-to-left. As such, the big-O //! performance of the `get`, `remove`, `insert`, and `contains` methods are the //! same as those of the backing map. //! //! For convenience, the type definition [`BiMap`] corresponds to a `BiHashMap`. //! If you're using this crate without the standard library, it instead //! corresponds to a `BiBTreeMap`. //! //! # Examples //! //! ``` //! use bimap::BiMap; //! //! let mut elements = BiMap::new(); //! //! // insert chemicals and their corresponding symbols //! elements.insert("hydrogen", "H"); //! elements.insert("carbon", "C"); //! elements.insert("bromine", "Br"); //! elements.insert("neodymium", "Nd"); //! //! // retrieve chemical symbol by name (left to right) //! assert_eq!(elements.get_by_left(&"bromine"), Some(&"Br")); //! assert_eq!(elements.get_by_left(&"oxygen"), None); //! //! // retrieve name by chemical symbol (right to left) //! assert_eq!(elements.get_by_right(&"C"), Some(&"carbon")); //! assert_eq!(elements.get_by_right(&"Al"), None); //! //! // check membership //! assert!(elements.contains_left(&"hydrogen")); //! assert!(!elements.contains_right(&"He")); //! //! // remove elements //! assert_eq!( //! elements.remove_by_left(&"neodymium"), //! Some(("neodymium", "Nd")) //! ); //! assert_eq!(elements.remove_by_right(&"Nd"), None); //! //! // iterate over elements //! for (left, right) in &elements { //! println!("the chemical symbol for {} is {}", left, right); //! } //! ``` //! //! ## Insertion and overwriting //! //! Consider the following example: //! //! ``` //! use bimap::BiMap; //! //! let mut bimap = BiMap::new(); //! bimap.insert('a', 1); //! bimap.insert('b', 1); // what to do here? //! ``` //! //! In order to maintain the bijection, the bimap cannot have both left-right //! pairs `('a', 1)` and `('b', 1)`. Otherwise, the right-value `1` would have //! two left values associated with it. Either we should allow the call to //! `insert` to go through and overwrite `('a', 1)`, or not let `('b', 1)` be //! inserted at all. This crate allows for both possibilities. To insert with //! overwriting, use [`insert`], and to insert without overwriting, use //! [`insert_no_overwrite`]. The return type of `insert` is the `enum` //! [`Overwritten`], which indicates what values, if any, were overwritten; the //! return type of `insert_no_overwrite` is a `Result` indicating if the //! insertion was successful. //! //! This is especially important when dealing with types that can be equal while //! having different data. Unlike a `HashMap` or `BTreeMap`, which [doesn't //! update an equal key upon insertion], a bimap updates both the left values //! and the right values. //! //! ``` //! use bimap::{BiMap, Overwritten}; //! use std::cmp::Ordering; //! use std::hash::{Hash, Hasher}; //! //! #[derive(Clone, Copy, Debug)] //! struct Foo { //! important: char, //! unimportant: u32, //! } //! //! // equality only depends on the important data //! impl PartialEq for Foo { //! fn eq(&self, other: &Foo) -> bool { //! self.important == other.important //! } //! } //! //! impl Eq for Foo {} //! //! impl PartialOrd for Foo { //! fn partial_cmp(&self, other: &Foo) -> Option { //! Some(self.cmp(other)) //! } //! } //! //! // ordering only depends on the important data //! impl Ord for Foo { //! fn cmp(&self, other: &Foo) -> Ordering { //! self.important.cmp(&other.important) //! } //! } //! //! // hash only depends on the important data //! impl Hash for Foo { //! fn hash(&self, state: &mut H) { //! self.important.hash(state); //! } //! } //! //! // create two Foos that are equal but have different data //! let foo1 = Foo { //! important: 'a', //! unimportant: 1, //! }; //! let foo2 = Foo { //! important: 'a', //! unimportant: 2, //! }; //! assert_eq!(foo1, foo2); //! //! // insert both Foos into a bimap //! let mut bimap = BiMap::new(); //! bimap.insert(foo1, 99); //! let overwritten = bimap.insert(foo2, 100); //! //! // foo1 is overwritten and returned //! match overwritten { //! Overwritten::Left(foo, 99) => assert_eq!(foo.unimportant, foo1.unimportant), //! _ => unreachable!(), //! }; //! //! // foo2 is in the bimap //! assert_eq!( //! bimap.get_by_right(&100).unwrap().unimportant, //! foo2.unimportant //! ); //! ``` //! //! Note that the `FromIterator` and `Extend` implementations for both //! `BiHashMap` and `BiBTreeMap` use the `insert` method internally, meaning //! that values from the original iterator/collection can be silently //! overwritten. //! //! ``` //! use bimap::BiMap; //! use std::iter::FromIterator; //! //! // note that both 'b' and 'c' have the right-value 2 //! let mut bimap = BiMap::from_iter(vec![('a', 1), ('b', 2), ('c', 2)]); //! //! // ('b', 2) was overwritten by ('c', 2) //! assert_eq!(bimap.len(), 2); //! assert_eq!(bimap.get_by_left(&'b'), None); //! assert_eq!(bimap.get_by_left(&'c'), Some(&2)); //! ``` //! //! ## `no_std` compatibility //! //! This crate can be used without the standard library when the `std` feature //! is disabled. If you choose to do this, only `BiBTreeMap` is available, not //! `BiHashMap`. //! //! ## serde compatibility //! //! When the `serde` feature is enabled, implementations of `Serialize` and //! `Deserialize` are provided for [`BiHashMap`] and [`BiBTreeMap`], allowing //! them to be serialized or deserialized painlessly. See the [`serde`] module //! for examples and more information. //! //! [bijective map]: https://en.wikipedia.org/wiki/Bijection //! [doesn't update an equal key upon insertion]: //! https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys //! [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html //! [`BTreeMap`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html //! [`insert`]: BiHashMap::insert //! [`insert_no_overwrite`]: BiHashMap::insert_no_overwrite // Document everything! #![deny(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] // Necessary to support no_std setups #[allow(unused_imports)] #[macro_use] extern crate alloc; mod mem; pub mod btree; pub use btree::BiBTreeMap; #[cfg(feature = "std")] pub mod hash; #[cfg(feature = "std")] pub use hash::BiHashMap; /// Type definition for convenience and compatibility with older versions of /// this crate. #[cfg(feature = "std")] pub type BiMap = BiHashMap; /// Type definition for convenience and compatibility with older versions of /// this crate. #[cfg(not(feature = "std"))] pub type BiMap = BiBTreeMap; #[cfg(all(feature = "serde", feature = "std"))] pub mod serde; /// The previous left-right pairs, if any, that were overwritten by a call to /// the [`insert`](BiHashMap::insert) method of a bimap. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Overwritten { /// Neither the left nor the right value previously existed in the bimap. Neither, /// The left value existed in the bimap, and the previous left-right pair is /// returned. Left(L, R), /// The right value existed in the bimap, and the previous left-right pair /// is returned. Right(L, R), /// The left-right pair already existed in the bimap, and the previous /// left-right pair is returned. Pair(L, R), /// Both the left and the right value existed in the bimap, but as part of /// separate pairs. The first tuple is the left-right pair of the /// previous left value, and the second is the left-right pair of the /// previous right value. Both((L, R), (L, R)), } impl Overwritten { /// Returns a boolean indicating if the `Overwritten` variant implies any /// values were overwritten. /// /// This method is `true` for all variants other than `Neither`. /// /// # Examples /// /// ``` /// use bimap::{BiMap, Overwritten}; /// /// let mut bimap = BiMap::new(); /// assert!(!bimap.insert('a', 1).did_overwrite()); /// assert!(bimap.insert('a', 2).did_overwrite()); /// ``` pub fn did_overwrite(&self) -> bool { !matches!(self, Overwritten::Neither) } } #[cfg(test)] mod tests { use super::*; #[test] fn did_overwrite() { assert_eq!(Overwritten::::Neither.did_overwrite(), false); assert_eq!(Overwritten::Left('a', 1).did_overwrite(), true); assert_eq!(Overwritten::Right('a', 1).did_overwrite(), true); assert_eq!(Overwritten::Pair('a', 1).did_overwrite(), true); assert_eq!(Overwritten::Both(('a', 1), ('b', 2)).did_overwrite(), true); } } bimap-0.6.3/src/mem.rs000064400000000000000000000023361046102023000126410ustar 00000000000000use alloc::rc::Rc; use core::{borrow::Borrow, fmt, ops::Bound}; #[derive(Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Ref(pub Rc); impl Clone for Ref { fn clone(&self) -> Self { Self(self.0.clone()) } } impl fmt::Debug for Ref where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } #[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[repr(transparent)] pub struct Wrapper(pub T); impl Wrapper { pub fn wrap(value: &T) -> &Self { // safe because Wrapper is #[repr(transparent)] unsafe { &*(value as *const T as *const Self) } } pub fn wrap_bound(bound: Bound<&T>) -> Bound<&Self> { match bound { Bound::Included(t) => Bound::Included(Self::wrap(t)), Bound::Excluded(t) => Bound::Excluded(Self::wrap(t)), Bound::Unbounded => Bound::Unbounded, } } } impl Borrow> for Ref where K: Borrow, Q: ?Sized, { fn borrow(&self) -> &Wrapper { // Rc: Borrow let k: &K = self.0.borrow(); // K: Borrow let q: &Q = k.borrow(); Wrapper::wrap(q) } } bimap-0.6.3/src/serde.rs000064400000000000000000000254011046102023000131630ustar 00000000000000//! Implementations of `serde::Serialize` and `serde::Deserialize` for //! `BiHashMap` and `BiBTreeMap`. //! //! You do not need to import anything from this module to use this //! functionality, simply enable the `serde` feature in your dependency //! manifest. Note that currently, this requires the `std` feature to also be //! enabled, and thus cannot be used in `no_std` enviroments. //! //! # Examples //! //! You can easily serialize and deserialize bimaps with any serde-compatbile //! serializer or deserializer. //! //! Serializing and deserializing a [`BiHashMap`]: //! //! ``` //! # use bimap::BiHashMap; //! // create a new bimap //! let mut map = BiHashMap::new(); //! //! // insert some pairs //! map.insert('A', 1); //! map.insert('B', 2); //! map.insert('C', 3); //! //! // convert the bimap to json //! let json = serde_json::to_string(&map).unwrap(); //! //! // convert the json back into a bimap //! let map2 = serde_json::from_str(&json).unwrap(); //! //! // check that the two bimaps are equal //! assert_eq!(map, map2); //! ``` //! //! Serializing and deserializing a [`BiBTreeMap`]: //! ``` //! # use bimap::BiBTreeMap; //! // create a new bimap //! let mut map = BiBTreeMap::new(); //! //! // insert some pairs //! map.insert('A', 3); //! map.insert('B', 2); //! map.insert('C', 1); //! //! // convert the bimap to json //! let json = serde_json::to_string(&map).unwrap(); //! //! // convert the json back into a bimap //! let map2 = serde_json::from_str(&json).unwrap(); //! //! // check that the two bimaps are equal //! assert_eq!(map, map2); //! ``` //! //! Of course, this is only possible for bimaps where the values also implement //! `Serialize` and `Deserialize` respectively: //! //! ```compile_fail //! # use bimap::BiHashMap; //! // this type doesn't implement Serialize or Deserialize! //! #[derive(PartialEq, Eq, Hash)] //! enum MyEnum { A, B, C } //! //! // create a bimap and add some pairs //! let mut map = BiHashMap::new(); //! map.insert(MyEnum::A, 1); //! map.insert(MyEnum::B, 2); //! map.insert(MyEnum::C, 3); //! //! // this line will cause the code to fail to compile //! let json = serde_json::to_string(&map).unwrap(); //! ``` //! //! # Implementation details //! //! Bimaps are serialized and deserialized as a map data type in serde. //! Consequentially, it is possible to serialize and deserialize bimaps to/from //! other types that are represented the same way. *This is considered an //! implementation detail and should not be relied upon.* //! //! For example, a bimap can be deserialized from the serialized form of a //! standard [`HashMap`]. However, *deserializing a bimap silently overwrites //! any conflicting pairs*, leading to non-deterministic results. //! ``` //! # use std::collections::HashMap; //! # use bimap::BiHashMap; //! // construct a regular map //! let mut map = HashMap::new(); //! //! // insert some entries //! // note that both 'B' and 'C' are associated with the value 2 here //! map.insert('A', 1); //! map.insert('B', 2); //! map.insert('C', 2); //! //! // serialize the map //! let json = serde_json::to_string(&map).unwrap(); //! //! // deserialize it into a bimap //! let bimap: BiHashMap = serde_json::from_str(&json).unwrap(); //! //! // deserialization succeeds, but the bimap is now in a non-deterministic //! // state - either ('B', 2) or ('C', 2) will have been overwritten while //! // deserializing, but this depends on the iteration order of the original //! // HashMap that was serialized. //! //! // we can still demonstrate that certain properties of the bimap are still //! // in a known state, but this shouldn't be relied upon //! assert_eq!(bimap.len(), 2); //! assert_eq!(bimap.get_by_left(&'A'), Some(&1)); //! assert!(bimap.get_by_left(&'B') == Some(&2) || bimap.get_by_left(&'C') == Some(&2)) //! ``` //! //! The reverse is also possible: bimaps may be serialized and then //! deserialized as other compatible types, such as a [`HashMap`]. //! //! ``` //! # use std::collections::HashMap; //! # use bimap::BiHashMap; //! // construct a bimap //! let mut bimap = BiHashMap::new(); //! //! // insert some pairs //! bimap.insert('A', 1); //! bimap.insert('B', 2); //! bimap.insert('C', 3); //! //! // serialize the bimap //! let json = serde_json::to_string(&bimap).unwrap(); //! //! // deserialize it as a regular map //! let map: HashMap = serde_json::from_str(&json).unwrap(); //! //! // this succeeds and the result is sensible, but this is still an //! // implementation detail and shouldn't be relied upon. //! assert_eq!(map.len(), 3); //! assert_eq!(map[&'A'], 1); //! assert_eq!(map[&'B'], 2); //! assert_eq!(map[&'C'], 3); //! ``` //! [`BiHashMap`]: crate::BiHashMap //! [`BiBTreeMap`]: crate::BiBTreeMap //! [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html use crate::{BiBTreeMap, BiHashMap}; use serde::{ de::{MapAccess, Visitor}, Deserialize, Deserializer, Serialize, Serializer, }; use std::{ default::Default, fmt::{Formatter, Result as FmtResult}, hash::{BuildHasher, Hash}, marker::PhantomData, }; /// Serializer for `BiHashMap` impl Serialize for BiHashMap where L: Serialize + Eq + Hash, R: Serialize + Eq + Hash, LS: BuildHasher + Default, RS: BuildHasher + Default, { fn serialize(&self, ser: S) -> Result { ser.collect_map(self.iter()) } } /// Visitor to construct `BiHashMap` from serialized map entries struct BiHashMapVisitor { marker: PhantomData>, } impl<'de, L, R, LS, RS> Visitor<'de> for BiHashMapVisitor where L: Deserialize<'de> + Eq + Hash, R: Deserialize<'de> + Eq + Hash, LS: BuildHasher + Default, RS: BuildHasher + Default, { fn expecting(&self, f: &mut Formatter) -> FmtResult { write!(f, "a map") } type Value = BiHashMap; fn visit_map>(self, mut entries: A) -> Result { let mut map = match entries.size_hint() { Some(s) => BiHashMap::::with_capacity_and_hashers( s, LS::default(), RS::default(), ), None => BiHashMap::::with_hashers(LS::default(), RS::default()), }; while let Some((l, r)) = entries.next_entry()? { map.insert(l, r); } Ok(map) } } /// Deserializer for `BiHashMap` impl<'de, L, R, LS, RS> Deserialize<'de> for BiHashMap where L: Deserialize<'de> + Eq + Hash, R: Deserialize<'de> + Eq + Hash, LS: BuildHasher + Default, RS: BuildHasher + Default, { fn deserialize>(de: D) -> Result { de.deserialize_map(BiHashMapVisitor:: { marker: PhantomData::default(), }) } } /// Serializer for `BiBTreeMap` impl Serialize for BiBTreeMap where L: Serialize + Ord, R: Serialize + Ord, { fn serialize(&self, ser: S) -> Result { ser.collect_map(self.iter()) } } /// Visitor to construct `BiBTreeMap` from serialized map entries struct BiBTreeMapVisitor { marker: PhantomData>, } impl<'de, L, R> Visitor<'de> for BiBTreeMapVisitor where L: Deserialize<'de> + Ord, R: Deserialize<'de> + Ord, { fn expecting(&self, f: &mut Formatter) -> FmtResult { write!(f, "a map") } type Value = BiBTreeMap; fn visit_map>(self, mut entries: A) -> Result { let mut map = BiBTreeMap::new(); while let Some((l, r)) = entries.next_entry()? { map.insert(l, r); } Ok(map) } } /// Deserializer for `BiBTreeMap` impl<'de, L, R> Deserialize<'de> for BiBTreeMap where L: Deserialize<'de> + Ord, R: Deserialize<'de> + Ord, { fn deserialize>(de: D) -> Result { de.deserialize_map(BiBTreeMapVisitor { marker: PhantomData::default(), }) } } #[cfg(test)] mod tests { use super::*; use serde::de::value::Error; use std::hash::BuildHasherDefault; #[test] fn serde_hash() { let mut bimap = BiHashMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); bimap.insert('c', 3); let json = serde_json::to_string(&bimap).unwrap(); let bimap2 = serde_json::from_str(&json).unwrap(); assert_eq!(bimap, bimap2); } #[test] fn serde_hash_w_fnv_hasher() { let hasher_builder = BuildHasherDefault::::default(); let mut bimap = BiHashMap::< char, u8, BuildHasherDefault, BuildHasherDefault, >::with_capacity_and_hashers( 4, hasher_builder.clone(), hasher_builder.clone() ); bimap.insert('f', 1); bimap.insert('g', 2); bimap.insert('h', 3); let json = serde_json::to_string(&bimap).unwrap(); let bimap2 = serde_json::from_str(&json).unwrap(); assert_eq!(bimap, bimap2); } #[test] fn serde_hash_w_hashbrown_hasher() { let hasher_builder = hashbrown::hash_map::DefaultHashBuilder::default(); let mut bimap = BiHashMap::< char, u8, hashbrown::hash_map::DefaultHashBuilder, hashbrown::hash_map::DefaultHashBuilder, >::with_capacity_and_hashers( 4, hasher_builder.clone(), hasher_builder.clone() ); bimap.insert('x', 1); bimap.insert('y', 2); bimap.insert('z', 3); let json = serde_json::to_string(&bimap).unwrap(); let bimap2 = serde_json::from_str(&json).unwrap(); assert_eq!(bimap, bimap2); } #[test] fn serde_btree() { let mut bimap = BiBTreeMap::new(); bimap.insert('a', 1); bimap.insert('b', 2); bimap.insert('c', 3); let json = serde_json::to_string(&bimap).unwrap(); let bimap2 = serde_json::from_str(&json).unwrap(); assert_eq!(bimap, bimap2); } #[test] fn expecting_btree() { let visitor = BiBTreeMapVisitor { marker: PhantomData::>, }; let error_str = format!("{:?}", visitor.visit_bool::(true)); let expected = "Err(Error(\"invalid type: boolean `true`, expected a map\"))"; assert_eq!(error_str, expected); } #[test] fn expecting_hash() { let visitor = BiHashMapVisitor { marker: PhantomData::>, }; let error_str = format!("{:?}", visitor.visit_bool::(true)); let expected = "Err(Error(\"invalid type: boolean `true`, expected a map\"))"; assert_eq!(error_str, expected); } } bimap-0.6.3/tests/hello_world.rs000064400000000000000000000007221046102023000147450ustar 00000000000000//! This is the Hello World example from the README. #[test] fn main() { // A bijective map between letters of the English alphabet and their positions. let mut alphabet = bimap::BiMap::::new(); alphabet.insert('A', 1); // some letters omitted for brevity alphabet.insert('Z', 26); println!("A is at position {}", alphabet.get_by_left(&'A').unwrap()); println!("{} is at position 26", alphabet.get_by_right(&26).unwrap()); }