priority-queue-2.6.0/.cargo_vcs_info.json0000644000000001360000000000100140440ustar { "git": { "sha1": "1caf7c75050f8cfbce5057dc7b84ee9333e46635" }, "path_in_vcs": "" }priority-queue-2.6.0/.github/workflows/build.yml000064400000000000000000000022411046102023000200520ustar 00000000000000name: Build on: push: branches: [ "*" ] pull_request: branches: [ master ] env: CARGO_TERM_COLOR: always TARGET: thumbv6m-none-eabi jobs: build: runs-on: ubuntu-latest strategy: matrix: include: - rust: stable features: std - rust: stable features: serde - rust: beta features: - rust: nightly features: steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.rust }} - name: Build run: cargo build --verbose --features "${{ matrix.features }}" nostd_build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: toolchain: stable target: $TARGET - name: Build run: cargo build -v -p test-nostd --target=$TARGET docs_rs_build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: toolchain: nightly - name: Docs.rs run: RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features priority-queue-2.6.0/.github/workflows/static-checks.yml000064400000000000000000000016041046102023000215020ustar 00000000000000name: Static checks on: push: branches: [ "*" ] pull_request: branches: [ master ] env: CARGO_TERM_COLOR: always jobs: format: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Check format run: cargo fmt --all -- --check clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@beta with: components: clippy - run: cargo clippy --all-features miri: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly with: components: miri - run: cargo miri test msrv-verify: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable - run: cargo install cargo-msrv - run: cargo msrv verify --all-features priority-queue-2.6.0/.github/workflows/test.yml000064400000000000000000000014141046102023000177330ustar 00000000000000name: Test on: push: branches: [ "*" ] pull_request: branches: [ master ] env: CARGO_TERM_COLOR: always TARGET: thumbv6m-none-eabi jobs: test: runs-on: ubuntu-latest strategy: matrix: include: - rust: stable features: std - rust: stable features: serde - rust: beta features: - rust: nightly features: steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.rust }} - name: Run tests run: cargo test --verbose --features "${{ matrix.features }}" - name: Run tests in release mode run: cargo test --release --verbose --features "${{ matrix.features }}" priority-queue-2.6.0/.gitignore000064400000000000000000000000501046102023000146170ustar 00000000000000target/ **/*.rs.bk Cargo.lock *~ .lapce/priority-queue-2.6.0/Cargo.lock0000644000000147540000000000100120320ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "ahash" version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ "cfg-if", "once_cell", "version_check", "zerocopy", ] [[package]] name = "allocator-api2" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "bitflags" version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "getrandom" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" dependencies = [ "cfg-if", "libc", "r-efi", "wasi", ] [[package]] name = "hashbrown" version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash", "allocator-api2", ] [[package]] name = "hashbrown" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" [[package]] name = "indexmap" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3954d50fe15b02142bf25d3b8bdadb634ec3948f103d04ffe3031bc8fe9d7058" dependencies = [ "equivalent", "hashbrown 0.15.2", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "libc" version = "0.2.171" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "once_cell" version = "1.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d75b0bedcc4fe52caa0e03d9f1151a323e4aa5e2d78ba3580400cd3c9e2bc4bc" [[package]] name = "priority-queue" version = "2.6.0" dependencies = [ "equivalent", "hashbrown 0.14.5", "indexmap", "serde", "serde_json", "serde_test", "uuid", ] [[package]] name = "proc-macro2" version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "serde" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "serde_test" version = "1.0.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f901ee573cab6b3060453d2d5f0bae4e6d628c23c0a962ff9b5f1d7c8d4f1ed" dependencies = [ "serde", ] [[package]] name = "syn" version = "2.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "uuid" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9" dependencies = [ "getrandom", "serde", ] [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "wasi" version = "0.14.2+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "wit-bindgen-rt" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ "bitflags", ] [[package]] name = "zerocopy" version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", "syn", ] priority-queue-2.6.0/Cargo.toml0000644000000037400000000000100120460ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.65.0" name = "priority-queue" version = "2.6.0" authors = ["Gianmarco Garrisi "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A Priority Queue implemented as a heap with a function to efficiently change the priority of an item." documentation = "https://docs.rs/priority-queue" readme = "README.md" keywords = [ "priority", "queue", "heap", ] categories = [ "data-structures", "algorithms", ] license = "LGPL-3.0-or-later OR MPL-2.0" repository = "https://github.com/garro95/priority-queue" [package.metadata.docs.rs] features = ["serde"] rustdoc-args = [ "--cfg", "docsrs", ] [features] benchmarks = [] default = ["std"] std = ["indexmap/std"] [lib] name = "priority_queue" path = "src/lib.rs" [[test]] name = "double_priority_queue" path = "tests/double_priority_queue.rs" [[test]] name = "priority_queue" path = "tests/priority_queue.rs" [[bench]] name = "priority_queue" path = "benches/priority_queue.rs" [dependencies.equivalent] version = "1.0.1" [dependencies.indexmap] version = "2.2" features = [] default-features = false [dependencies.serde] version = "1" optional = true [dev-dependencies.hashbrown] version = "0.14" [dev-dependencies.serde] version = "1" features = ["derive"] [dev-dependencies.serde_json] version = "1" [dev-dependencies.serde_test] version = "1" [dev-dependencies.uuid] version = "1" features = [ "v4", "serde", ] priority-queue-2.6.0/Cargo.toml.orig000064400000000000000000000020251046102023000155220ustar 00000000000000[package] name = "priority-queue" version = "2.6.0" authors = ["Gianmarco Garrisi "] description = "A Priority Queue implemented as a heap with a function to efficiently change the priority of an item." repository = "https://github.com/garro95/priority-queue" documentation = "https://docs.rs/priority-queue" readme = "README.md" keywords = ["priority", "queue", "heap"] categories = ["data-structures", "algorithms"] license = "LGPL-3.0-or-later OR MPL-2.0" edition = "2021" rust-version = "1.65.0" [dependencies] equivalent = "1.0.1" indexmap = {version = "2.2", features = [], default-features = false} serde = { version = "1", optional = true } [dev-dependencies] serde_test = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" uuid = {version= "1", features = ["v4", "serde"] } hashbrown = "0.14" [features] default = ["std"] std = ["indexmap/std"] benchmarks = [] [workspace] members = ["test-nostd"] [package.metadata.docs.rs] features = ["serde"] rustdoc-args = ["--cfg", "docsrs"] priority-queue-2.6.0/LGPL-3.0-or-later.txt000064400000000000000000000167431046102023000161670ustar 00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. priority-queue-2.6.0/MPL-2.0.txt000064400000000000000000000352011046102023000143230ustar 00000000000000Mozilla Public License Version 2.0 1. Definitions 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. 6. Disclaimer of Warranty Covered Software is provided under this License on an "as is" basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. 7. Limitation of Liability Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 8. Litigation Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. priority-queue-2.6.0/README.md000064400000000000000000000263071046102023000141230ustar 00000000000000# PriorityQueue [![crate](https://img.shields.io/crates/v/priority-queue.svg)](https://crates.io/crates/priority-queue) [![Build](https://github.com/garro95/priority-queue/actions/workflows/build.yml/badge.svg)](https://github.com/garro95/priority-queue/actions/workflows/build.yml) [![Test](https://github.com/garro95/priority-queue/actions/workflows/test.yml/badge.svg)](https://github.com/garro95/priority-queue/actions/workflows/test.yml) ![MSRV](https://img.shields.io/crates/msrv/priority-queue) This crate implements a Priority Queue with a function to change the priority of an object. Priority and items are stored in an `IndexMap` and the queue is implemented as a Heap of indexes. Please read the [API documentation here](https://docs.rs/priority-queue/) ## Usage To use this crate, simply add the following string to your `Cargo.toml`: ``` priority-queue = "2.0.0" ``` or use the command `cargo add priority-queue` Version numbers follow the [semver](https://semver.org/) convention. Then use the data structure inside your Rust source code as in the following Example. Remember that, if you need serde support, you should compile using `--features serde`. ## Examples ```rust use priority_queue::PriorityQueue; fn main() { let mut pq = PriorityQueue::new(); assert!(pq.is_empty()); pq.push("Apples", 5); pq.push("Bananas", 8); pq.push("Strawberries", 23); assert_eq!(pq.peek(), Some((&"Strawberries", &23))); for (item, _) in pq.into_sorted_iter() { println!("{}", item); } } ``` By default, the highest priority element will be extracted first. The order can be easily reversed using the standard wrapper [`Reverse`](https://doc.rust-lang.org/std/cmp/struct.Reverse.html). ```rust use priority_queue::PriorityQueue; use std::cmp::Reverse; fn main() { let mut pq = PriorityQueue::new(); assert!(pq.is_empty()); pq.push("Apples", Reverse(5)); pq.push("Bananas", Reverse(8)); pq.push("Strawberries", Reverse(23)); assert_eq!(pq.peek(), Some((&"Apples", &Reverse(5)))); for (item, _) in pq.into_sorted_iter() { println!("{}", item); } } ``` ## Speeding up You can use custom BuildHasher for the underlying IndexMap and therefore achieve better performance. For example you can create the queue with the speedy [FxHash](https://github.com/Amanieu/hashbrown) hasher: ```rust use hashbrown::hash_map::DefaultHashBuilder; let mut pq = PriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); ``` Attention: FxHash does not offer any protection for dos attacks. This means that some pathological inputs can make the operations on the hashmap O(n^2). Use the standard hasher if you cannot control the inputs. ## Benchmarks Some benchmarks have been run to compare the performances of this priority queue to the standard BinaryHeap, also using the FxHash hasher. On a Ryzen 9 3900X, the benchmarks produced the following results: ``` test benchmarks::priority_change_on_large_double_queue ... bench: 25 ns/iter (+/- 1) test benchmarks::priority_change_on_large_double_queue_fx ... bench: 21 ns/iter (+/- 1) test benchmarks::priority_change_on_large_queue ... bench: 15 ns/iter (+/- 0) test benchmarks::priority_change_on_large_queue_fx ... bench: 11 ns/iter (+/- 0) test benchmarks::priority_change_on_large_queue_std ... bench: 190,345 ns/iter (+/- 4,976) test benchmarks::priority_change_on_small_double_queue ... bench: 26 ns/iter (+/- 0) test benchmarks::priority_change_on_small_double_queue_fx ... bench: 20 ns/iter (+/- 0) test benchmarks::priority_change_on_small_queue ... bench: 15 ns/iter (+/- 0) test benchmarks::priority_change_on_small_queue_fx ... bench: 10 ns/iter (+/- 0) test benchmarks::priority_change_on_small_queue_std ... bench: 1,694 ns/iter (+/- 21) test benchmarks::push_and_pop ... bench: 31 ns/iter (+/- 0) test benchmarks::push_and_pop_double ... bench: 31 ns/iter (+/- 0) test benchmarks::push_and_pop_double_fx ... bench: 24 ns/iter (+/- 1) test benchmarks::push_and_pop_fx ... bench: 26 ns/iter (+/- 0) test benchmarks::push_and_pop_min_on_large_double_queue ... bench: 101 ns/iter (+/- 2) test benchmarks::push_and_pop_min_on_large_double_queue_fx ... bench: 98 ns/iter (+/- 0) test benchmarks::push_and_pop_on_large_double_queue ... bench: 107 ns/iter (+/- 2) test benchmarks::push_and_pop_on_large_double_queue_fx ... bench: 106 ns/iter (+/- 2) test benchmarks::push_and_pop_on_large_queue ... bench: 84 ns/iter (+/- 1) test benchmarks::push_and_pop_on_large_queue_fx ... bench: 78 ns/iter (+/- 2) test benchmarks::push_and_pop_on_large_queue_std ... bench: 71 ns/iter (+/- 1) test benchmarks::push_and_pop_std ... bench: 4 ns/iter (+/- 0) ``` The priority change on the standard queue was obtained with the following: ```rust pq = pq.drain().map(|Entry(i, p)| { if i == 50_000 { Entry(i, p/2) } else { Entry(i, p) } }).collect() ``` The interpretation of the benchmarks is that the data structures provided by this crate is generally slightly slower than the standard Binary Heap. On small queues (<10000 elements), the change_priority function, obtained on the standard Binary Heap with the code above, is way slower than the one provided by `PriorityQueue` and `DoublePriorityQueue`. With the queue becoming bigger, the operation takes almost the same amount of time on `PriorityQueue` and `DoublePriorityQueue`, while it takes more and more time for the standard queue. It also emerges that the ability to arbitrarily pop the minimum or maximum element comes with a cost, that is visible in all the operations on `DoublePriorityQueue`, that are slower then the corresponding operations executed on the `PriorityQueue`. ## Contributing Feel free to contribute to this project with pull requests and/or issues. All contribution shall be under a license compatible with the GNU LGPL version 3 or any later version and with the MPL version 2.0. ## Changes * 2.6.0 Add equivalent trait support for flexible key lookups: [#74](https://github.com/garro95/priority-queue/pull/74). Convert `with_hasher` to const function: [#73](https://github.com/garro95/priority-queue/pull/73). Thanks to [liwenjieQu](https://github.com/liwenjieQu) and [AsakuraMizu](https://github.com/AsakuraMizu) * 2.5.0 Implement `contains`. * 2.4.1 Documentation improvements: add examples for `extract_if` * 2.4.0 Implement `extract_if`. * 2.3.1 Declare rust-version in Crate manifest: [#65](https://github.com/garro95/priority-queue/pull/65). Thanks to [aborgna-q](https://github.com/aborgna-q) * 2.3.0 Implement retain and retain_mut * 2.2.2 Fix a bug in the heapify_up implementation for DoublePriorityQueue * 2.2.1 Fix docs.rs build * 2.2.0 Implement `pop_if`. Documentation Improvements * 2.1.2 Documentation improvements: [#58](https://github.com/garro95/priority-queue/pull/58). Thanks to [jmr](https://github.com/jmr) * 2.1.1 Bug fix: [#56](https://github.com/garro95/priority-queue/issues/56) * 2.1.0 Implement `drain` and `reserve` variations * 2.0.3 Some licensing-related housekeeping: [#54](https://github.com/garro95/priority-queue/pull/54). Thanks to [musicinmybrain](https://github.com/musicinmybrain) * 2.0.2 Fix docs.rs build * 2.0.1 Documentation improvements * 2.0.0 This release contains **breaking changes** * Some methods now require the trait bound `H: BuildHasher`. This change will likely have a small impact or none. * The standard library support is no longer auto-detected. The feature "std" is included in the default feature set, or else can be enabled like any other Cargo feature. Users that need to support `no_std` targets will have to disable default features. * 1.4.0 Improve `shrink_to_fit` to also shrink the internal IndexMap ([#50](https://github.com/garro95/priority-queue/issues/50)) * 1.3.2 Bug fix in the `log2_fast` internal function * 1.3.1 Bug fix: [#42](https://github.com/garro95/priority-queue/issues/42) * 1.3.0 Return bool from `change_priority_by` (Merged [#41](https://github.com/garro95/priority-queue/pull/41)) * 1.2.3 Further performance optimizations (mainly on `DoublePriorityQueue`) * 1.2.2 Performance optimizations * 1.2.1 Bug fix: [#34](https://github.com/garro95/priority-queue/issues/34) * 1.2.0 Implement DoublePriorityQueue data structure * 1.1.1 Convert documentation to Markdown * 1.1.0 Smooth `Q: Sized` requirement on some methods (fix [#32](https://github.com/garro95/priority-queue/issues/32)) * 1.0.5 Bug fix: [#28](https://github.com/garro95/priority-queue/issues/28) * 1.0.4 Bug fix: [#28](https://github.com/garro95/priority-queue/issues/28) * 1.0.3 Bug fix: [#26](https://github.com/garro95/priority-queue/issues/26) * 1.0.2 Added documentation link to Cargo.toml so the link is shown in the results page of crates.io * 1.0.1 Documentation * 1.0.0 This release contains **breaking changes!** * `From` and `FromIterator` now accept custom hashers -- **Breaking:** every usage of `from` and `from_iter` must specify some type to help the type inference. To use the default hasher (`RandomState`), often it will be enough to add something like ```rust let pq: PriorityQueue<_, _> = PriorityQueue::from... ``` or you can add a type definition like ```rust type Pq = PriorityQueue ``` and then use `Pq::from()` or `Pq::from_iter()` * Support no-std architectures * Add a method to remove elements at arbitrary positions * Remove `take_mut` dependency -- **Breaking:** `change_priority_by` signature has changed. Now it takes a priority_setter `F: FnOnce(&mut P)`. If you want you can use the unsafe `take_mut` yourself or also use `std::mem::replace` * 0.7.0 Implement the `push_increase` and `push_decrease` convenience methods. * 0.6.0 Allow the usage of custom hasher * 0.5.4 Prevent panic on extending an empty queue * 0.5.3 New implementation of the `Default` trait avoids the requirement that `P: Default` * 0.5.2 Fix documentation formatting * 0.5.1 Add some documentation for `iter_mut()` * 0.5.0 Fix [#7](https://github.com/garro95/priority-queue/issues/7) implementing the `iter_mut` features * 0.4.5 Fix [#6](https://github.com/garro95/priority-queue/issues/6) for `change_priority` and `change_priority_by` * 0.4.4 Fix [#6](https://github.com/garro95/priority-queue/issues/6) * 0.4.3 Fix [#4](https://github.com/garro95/priority-queue/issues/4) changing the way `PriorityQueue` serializes. Note that old serialized `PriorityQueue`s may be incompatible with the new version. The API should not be changed instead. * 0.4.2 Improved performance using some unsafe code in the implementation. * 0.4.1 Support for `serde` when compiled with `--features serde`. `serde` marked as optional and `serde-test` as dev-dipendency. Now compiling the crate won't download and compile also `serde-test`, neither `serde` if not needed. * 0.4.0 Support for serde when compiled with `cfg(serde)` * 0.3.1 Fix [#3](https://github.com/garro95/priority-queue/issues/3) * 0.3.0 Implement PartialEq and Eq traits priority-queue-2.6.0/benches/priority_queue.rs000064400000000000000000000260251046102023000177030ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi and contributors * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ #![cfg_attr(feature = "benchmarks", feature(test))] #[cfg(all(test, feature = "benchmarks"))] mod benchmarks { extern crate test; use hashbrown::hash_map::DefaultHashBuilder; use priority_queue::{DoublePriorityQueue, PriorityQueue}; use test::{black_box, Bencher}; #[bench] fn push_and_pop(b: &mut Bencher) { type PqType = PriorityQueue; let mut pq: PqType = PriorityQueue::new(); b.iter(|| { pq.push(black_box(0), black_box(0)); assert_eq![pq.pop().unwrap().1, 0]; }); } #[bench] fn push_and_pop_double(b: &mut Bencher) { type PqType = DoublePriorityQueue; let mut pq: PqType = DoublePriorityQueue::new(); b.iter(|| { pq.push(black_box(0), black_box(0)); assert_eq![pq.pop_max().unwrap().1, 0]; }); } #[bench] fn push_and_pop_fx(b: &mut Bencher) { let mut pq = PriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); b.iter(|| { pq.push(black_box(0), black_box(0)); assert_eq![pq.pop().unwrap().1, 0]; }); } #[bench] fn push_and_pop_double_fx(b: &mut Bencher) { let mut pq = DoublePriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); b.iter(|| { pq.push(black_box(0), black_box(0)); assert_eq![pq.pop_max().unwrap().1, 0]; }); } //for comparison, using the BinaryHeap #[bench] fn push_and_pop_std(b: &mut Bencher) { use std::collections::BinaryHeap; type PqType = BinaryHeap<(usize, i32)>; let mut pq: PqType = BinaryHeap::new(); b.iter(|| { pq.push((black_box(0), black_box(0))); assert_eq![pq.pop().unwrap().1, 0]; }); } #[bench] fn push_and_pop_on_large_queue(b: &mut Bencher) { type PqType = PriorityQueue; let mut pq: PqType = PriorityQueue::new(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.push(black_box(100_000), black_box(100_000)); assert_eq![pq.pop().unwrap().1, black_box(100_000)]; }); } #[bench] fn push_and_pop_on_large_double_queue(b: &mut Bencher) { type PqType = DoublePriorityQueue; let mut pq: PqType = DoublePriorityQueue::new(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.push(black_box(100_000), black_box(100_000)); assert_eq![pq.pop_max().unwrap().1, black_box(100_000)]; }); } #[bench] fn push_and_pop_min_on_large_double_queue(b: &mut Bencher) { type PqType = DoublePriorityQueue; let mut pq: PqType = DoublePriorityQueue::new(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.push(black_box(0), black_box(0)); assert_eq![pq.pop_min().unwrap().1, black_box(0)]; }); } #[bench] fn push_and_pop_on_large_queue_fx(b: &mut Bencher) { let mut pq = PriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.push(black_box(100_000), black_box(100_000)); assert_eq![pq.pop().unwrap().1, black_box(100_000)]; }); } #[bench] fn push_and_pop_on_large_double_queue_fx(b: &mut Bencher) { let mut pq = DoublePriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.push(black_box(100_000), black_box(100_000)); assert_eq![pq.pop_max().unwrap().1, black_box(100_000)]; }); } #[bench] fn push_and_pop_min_on_large_double_queue_fx(b: &mut Bencher) { let mut pq = DoublePriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.push(black_box(0), black_box(0)); assert_eq![pq.pop_min().unwrap().1, black_box(0)]; }); } #[bench] fn push_and_pop_on_large_queue_std(b: &mut Bencher) { use std::collections::BinaryHeap; type PqType = BinaryHeap<(usize, i32)>; let mut pq: PqType = BinaryHeap::new(); for i in 0..100_000 { pq.push((black_box(i as usize), black_box(i))); } b.iter(|| { pq.push((black_box(100_000), black_box(100_000))); assert_eq![pq.pop().unwrap().1, black_box(100_000)]; }); } #[bench] fn priority_change_on_large_queue_std(b: &mut Bencher) { use std::collections::BinaryHeap; struct Entry(usize, i32); impl Ord for Entry { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.cmp(&other.0) } } impl PartialOrd for Entry { fn partial_cmp(&self, other: &Self) -> Option { self.0.partial_cmp(&other.0) } } impl Eq for Entry {} impl PartialEq for Entry { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } type PqType = BinaryHeap; let mut pq: PqType = BinaryHeap::new(); for i in 0..100_000 { pq.push(Entry(black_box(i as usize), black_box(i))); } b.iter(|| { pq = pq .drain() .map(|Entry(i, p)| { if i == 50_000 { Entry(i, p / 2) } else { Entry(i, p) } }) .collect() }); } #[bench] fn priority_change_on_large_queue(b: &mut Bencher) { type PqType = PriorityQueue; let mut pq: PqType = PriorityQueue::new(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.change_priority_by(&50_000, |p| *p = *p / 2); }); } #[bench] fn priority_change_on_large_double_queue(b: &mut Bencher) { type PqType = DoublePriorityQueue; let mut pq: PqType = DoublePriorityQueue::new(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.change_priority_by(&50_000, |p| *p = *p / 2); }); } #[bench] fn priority_change_on_large_queue_fx(b: &mut Bencher) { let mut pq = PriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.change_priority_by(&50_000, |p| *p = *p / 2); }); } #[bench] fn priority_change_on_large_double_queue_fx(b: &mut Bencher) { let mut pq = DoublePriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); for i in 0..100_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.change_priority_by(&50_000, |p| *p = *p / 2); }); } #[bench] fn priority_change_on_small_queue_std(b: &mut Bencher) { use std::collections::BinaryHeap; struct Entry(usize, i32); impl Ord for Entry { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.cmp(&other.0) } } impl PartialOrd for Entry { fn partial_cmp(&self, other: &Self) -> Option { self.0.partial_cmp(&other.0) } } impl Eq for Entry {} impl PartialEq for Entry { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } type PqType = BinaryHeap; let mut pq: PqType = BinaryHeap::new(); for i in 0..1_000 { pq.push(Entry(black_box(i as usize), black_box(i))); } b.iter(|| { pq = pq .drain() .map(|Entry(i, p)| { if i == 500 { Entry(i, p / 2) } else { Entry(i, p) } }) .collect() }); } #[bench] fn priority_change_on_small_queue(b: &mut Bencher) { type PqType = PriorityQueue; let mut pq: PqType = PriorityQueue::new(); for i in 0..1_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.change_priority_by(&500, |p| *p = *p / 2); }); } #[bench] fn priority_change_on_small_double_queue(b: &mut Bencher) { type PqType = DoublePriorityQueue; let mut pq: PqType = DoublePriorityQueue::new(); for i in 0..1_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.change_priority_by(&500, |p| *p = *p / 2); }); } #[bench] fn priority_change_on_small_queue_fx(b: &mut Bencher) { let mut pq = PriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); for i in 0..1_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.change_priority_by(&500, |p| *p = *p / 2); }); } #[bench] fn priority_change_on_small_double_queue_fx(b: &mut Bencher) { let mut pq = DoublePriorityQueue::<_, _, DefaultHashBuilder>::with_default_hasher(); for i in 0..1_000 { pq.push(black_box(i as usize), black_box(i)); } b.iter(|| { pq.change_priority_by(&500, |p| *p = *p / 2); }); } } priority-queue-2.6.0/src/core_iterators.rs000064400000000000000000000067611046102023000170270ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ //! This module defines iterator types that are used with //! both the [`PriorityQueue`](super::PriorityQueue) and the [`DoublePriorityQueue`](super::DoublePriorityQueue) //! //! Usually you don't need to explicitly `use` any of the types declared here. use core::iter::FusedIterator; #[cfg(not(feature = "std"))] pub(crate) mod std { pub use ::alloc::vec; pub use core::*; } /// A draining iterator in arbitrary order over the couples /// `(item, priority)` in the queue. /// /// It can be obtained calling the `drain` method. pub struct Drain<'a, I: 'a, P: 'a> { pub(crate) iter: ::indexmap::map::Drain<'a, I, P>, } impl<'a, I: 'a, P: 'a> Iterator for Drain<'a, I, P> { type Item = (I, P); fn next(&mut self) -> Option<(I, P)> { self.iter.next() } } impl DoubleEndedIterator for Drain<'_, I, P> { fn next_back(&mut self) -> Option { self.iter.next_back() } } impl ExactSizeIterator for Drain<'_, I, P> { fn len(&self) -> usize { self.iter.len() } } impl FusedIterator for Drain<'_, I, P> {} /// An iterator in arbitrary order over the couples /// `(item, priority)` in the queue. /// /// It can be obtained calling the `iter` method. pub struct Iter<'a, I: 'a, P: 'a> { pub(crate) iter: ::indexmap::map::Iter<'a, I, P>, } impl<'a, I: 'a, P: 'a> Iterator for Iter<'a, I, P> { type Item = (&'a I, &'a P); fn next(&mut self) -> Option<(&'a I, &'a P)> { self.iter.next() } } impl DoubleEndedIterator for Iter<'_, I, P> { fn next_back(&mut self) -> Option { self.iter.next_back() } } impl ExactSizeIterator for Iter<'_, I, P> { fn len(&self) -> usize { self.iter.len() } } impl FusedIterator for Iter<'_, I, P> {} /// An iterator in arbitrary order over the couples /// `(item, priority)` that consumes the queue. /// /// It can be obtained calling the `into_iter` method from the [`IntoIterator`] trait. pub struct IntoIter { pub(crate) iter: ::indexmap::map::IntoIter, } impl Iterator for IntoIter { type Item = (I, P); fn next(&mut self) -> Option<(I, P)> { self.iter.next() } } impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option { self.iter.next_back() } } impl ExactSizeIterator for IntoIter { fn len(&self) -> usize { self.iter.len() } } impl FusedIterator for IntoIter {} priority-queue-2.6.0/src/double_priority_queue/iterators.rs000064400000000000000000000162701046102023000224320ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ //! This module defines iterator types that are used only with the [`DoublePriorityQueue`] //! //! Usually you don't need to explicitly `use` any of the types declared here. #[cfg(not(feature = "std"))] use crate::core_iterators::std; use core::hash::BuildHasher; use std::cmp::Ord; #[cfg(feature = "std")] use std::collections::hash_map::RandomState; use std::iter::*; use crate::DoublePriorityQueue; use super::Index; /// An `Iterator` in arbitrary order which uses a `predicate` to determine if /// an element should be removed from the `DoublePriorityQueue`. /// /// It can be obtained calling the [`extract_if`](DoublePriorityQueue::extract_if) method. /// /// The `predicate` has mutable access to the `(item, priority)` pairs. /// /// It can update the priorities of the elements in the queue and the items /// in a way that does not change the result of any of `hash` or `eq`. /// /// When the iterator goes out of scope, the heap is rebuilt to restore the /// structural properties. #[cfg(feature = "std")] pub struct ExtractIf<'a, I: 'a, P: 'a, F, H: 'a = RandomState> where P: Ord, { pq: &'a mut DoublePriorityQueue, predicate: F, idx: Index, } #[cfg(not(feature = "std"))] pub struct ExtractIf<'a, I: 'a, P: 'a, F, H: 'a> where P: Ord, { pq: &'a mut DoublePriorityQueue, predicate: F, idx: Index, } impl<'a, I: 'a, P: 'a, F, H: 'a> ExtractIf<'a, I, P, F, H> where P: Ord, { pub(crate) fn new(pq: &'a mut DoublePriorityQueue, predicate: F) -> Self { ExtractIf { pq, predicate, idx: Index(0), } } } impl<'a, I: 'a, P: 'a, F, H: 'a> Iterator for ExtractIf<'a, I, P, F, H> where P: Ord, F: FnMut(&mut I, &mut P) -> bool, H: BuildHasher, { type Item = (I, P); fn next(&mut self) -> Option { use indexmap::map::MutableKeys; loop { let r: Option = self .pq .store .map .get_index_mut2(self.idx.0) .map(|(i, p)| (self.predicate)(i, p)); match r { Some(true) => return self.pq.store.swap_remove_index(self.idx), Some(false) => self.idx.0 += 1, None => return None, } } } } impl<'a, I: 'a, P: 'a, F, H: 'a> Drop for ExtractIf<'a, I, P, F, H> where P: Ord, { fn drop(&mut self) { self.pq.heap_build(); } } /// A mutable iterator over the couples `(item, priority)` of the `DoublePriorityQueue` /// in arbitrary order. /// /// It can be obtained calling the [`iter_mut`](DoublePriorityQueue::iter_mut) method. /// /// It can be used to update the priorities of the elements in the queue. /// When the iterator goes out of scope, the heap is rebuilt to restore the /// structural properties. /// /// The item is mutable too, but it is a logical error to modify it in a way that /// changes the result of any of `hash` or `eq`. #[cfg(feature = "std")] pub struct IterMut<'a, I: 'a, P: 'a, H: 'a = RandomState> where P: Ord, { pq: &'a mut DoublePriorityQueue, pos: usize, } #[cfg(not(feature = "std"))] pub struct IterMut<'a, I: 'a, P: 'a, H: 'a> where P: Ord, { pq: &'a mut DoublePriorityQueue, pos: usize, } impl<'a, I: 'a, P: 'a, H: 'a> IterMut<'a, I, P, H> where P: Ord, { pub(crate) fn new(pq: &'a mut DoublePriorityQueue) -> Self { IterMut { pq, pos: 0 } } } impl<'a, I: 'a, P: 'a, H: 'a> Iterator for IterMut<'a, I, P, H> where P: Ord, H: BuildHasher, { type Item = (&'a mut I, &'a mut P); fn next(&mut self) -> Option { use indexmap::map::MutableKeys; let r: Option<(&'a mut I, &'a mut P)> = self .pq .store .map .get_index_mut2(self.pos) .map(|(i, p)| (i as *mut I, p as *mut P)) .map(|(i, p)| unsafe { (i.as_mut().unwrap(), p.as_mut().unwrap()) }); self.pos += 1; r } } impl<'a, I: 'a, P: 'a, H: 'a> DoubleEndedIterator for IterMut<'a, I, P, H> where P: Ord, H: BuildHasher, { fn next_back(&mut self) -> Option { use indexmap::map::MutableKeys; let r: Option<(&'a mut I, &'a mut P)> = self .pq .store .map .get_index_mut2(self.pos) .map(|(i, p)| (i as *mut I, p as *mut P)) .map(|(i, p)| unsafe { (i.as_mut().unwrap(), p.as_mut().unwrap()) }); self.pos -= 1; r } } impl ExactSizeIterator for IterMut<'_, I, P, H> where P: Ord, H: BuildHasher, { fn len(&self) -> usize { self.pq.len() } } impl FusedIterator for IterMut<'_, I, P, H> where P: Ord, H: BuildHasher, { } impl<'a, I: 'a, P: 'a, H: 'a> Drop for IterMut<'a, I, P, H> where P: Ord, { fn drop(&mut self) { self.pq.heap_build(); } } /// A consuming iterator over the couples `(item, priority)` of the `PriorityQueue` /// ordered by priority, from the lowest to the highest. /// /// It can be obtained calling the [`into_sorted_iter`](DoublePriorityQueue::into_sorted_iter) method. /// /// Since it implements [`DoubleEndedIterator`], this iterator can be reversed at any time /// calling `rev`, at which point, elements will be extracted from the one with maximum priority /// to the one with minimum priority. #[cfg(feature = "std")] pub struct IntoSortedIter where P: Ord, { pub(crate) pq: DoublePriorityQueue, } #[cfg(not(feature = "std"))] pub struct IntoSortedIter where P: Ord, { pub(crate) pq: DoublePriorityQueue, } impl Iterator for IntoSortedIter where P: Ord, { type Item = (I, P); fn next(&mut self) -> Option<(I, P)> { self.pq.pop_min() } } impl DoubleEndedIterator for IntoSortedIter where P: Ord, { fn next_back(&mut self) -> Option<(I, P)> { self.pq.pop_max() } } impl ExactSizeIterator for IntoSortedIter where P: Ord, { fn len(&self) -> usize { self.pq.len() } } impl FusedIterator for IntoSortedIter where P: Ord {} priority-queue-2.6.0/src/double_priority_queue/mod.rs000064400000000000000000001212271046102023000211740ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ //! This module contains the [`DoublePriorityQueue`] type and the related iterators. //! //! See the type level documentation for more details and examples. pub mod iterators; #[cfg(not(feature = "std"))] use std::vec::Vec; use crate::better_to_rebuild; use crate::core_iterators::*; use crate::store::{left, level, parent, right}; use crate::store::{Index, Position, Store}; use crate::TryReserveError; use equivalent::Equivalent; use iterators::*; use std::cmp::{Eq, Ord}; #[cfg(feature = "std")] use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hash}; use std::iter::{Extend, FromIterator, IntoIterator, Iterator}; use std::mem::replace; /// A double priority queue with efficient change function to change the priority of an /// element. /// /// The priority is of type P, that must implement `std::cmp::Ord`. /// /// The item is of type I, that must implement `Hash` and `Eq`. /// /// Implemented as a heap of indexes, stores the items inside an `IndexMap` /// to be able to retrieve them quickly. /// /// With this data structure it is possible to efficiently extract both /// the maximum and minimum elements arbitrarily. /// /// If your need is to always extract the minimum, use a /// `PriorityQueue>` wrapping /// your priorities in the standard wrapper /// [`Reverse`](https://doc.rust-lang.org/std/cmp/struct.Reverse.html). /// /// /// # Example /// ```rust /// use priority_queue::DoublePriorityQueue; /// /// let mut pq = DoublePriorityQueue::new(); /// /// assert!(pq.is_empty()); /// pq.push("Apples", 5); /// pq.push("Bananas", 8); /// pq.push("Strawberries", 23); /// /// assert_eq!(pq.peek_max(), Some((&"Strawberries", &23))); /// assert_eq!(pq.peek_min(), Some((&"Apples", &5))); /// /// pq.change_priority("Bananas", 25); /// assert_eq!(pq.peek_max(), Some((&"Bananas", &25))); /// /// for (item, _) in pq.into_sorted_iter() { /// println!("{}", item); /// } /// ``` #[derive(Clone)] #[cfg(feature = "std")] pub struct DoublePriorityQueue { pub(crate) store: Store, } #[derive(Clone)] #[cfg(not(feature = "std"))] pub struct DoublePriorityQueue { pub(crate) store: Store, } // do not [derive(Eq)] to loosen up trait requirements for other types and impls impl Eq for DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { } impl Default for DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn default() -> Self { Self::with_default_hasher() } } #[cfg(feature = "std")] impl DoublePriorityQueue where P: Ord, I: Hash + Eq, { /// Creates an empty `DoublePriorityQueue` pub fn new() -> Self { Self::with_capacity(0) } /// Creates an empty `DoublePriorityQueue` with the specified capacity. pub fn with_capacity(capacity: usize) -> Self { Self::with_capacity_and_default_hasher(capacity) } } impl DoublePriorityQueue where P: Ord, I: Hash + Eq, H: BuildHasher + Default, { /// Creates an empty `DoublePriorityQueue` with the default hasher pub fn with_default_hasher() -> Self { Self::with_capacity_and_default_hasher(0) } /// Creates an empty `DoublePriorityQueue` with the specified capacity and default hasher pub fn with_capacity_and_default_hasher(capacity: usize) -> Self { Self::with_capacity_and_hasher(capacity, H::default()) } } impl DoublePriorityQueue where P: Ord, I: Hash + Eq, H: BuildHasher, { /// Creates an empty `DoublePriorityQueue` with the specified hasher pub const fn with_hasher(hash_builder: H) -> Self { Self { store: Store::with_hasher(hash_builder), } } /// Creates an empty `DoublePriorityQueue` with the specified capacity and hasher /// /// The internal collections will be able to hold at least `capacity` /// elements without reallocating. /// If `capacity` is 0, there will be no allocation. pub fn with_capacity_and_hasher(capacity: usize, hash_builder: H) -> Self { Self { store: Store::with_capacity_and_hasher(capacity, hash_builder), } } } impl DoublePriorityQueue { /// Returns the number of elements the internal map can hold without /// reallocating. /// /// This number is a lower bound; the map might be able to hold more, /// but is guaranteed to be able to hold at least this many. pub fn capacity(&self) -> usize { self.store.capacity() } /// Returns an iterator in arbitrary order over the /// (item, priority) elements in the queue pub fn iter(&self) -> Iter { self.store.iter() } /// Clears the PriorityQueue, returning an iterator over the removed elements in arbitrary order. /// If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order. pub fn drain(&mut self) -> Drain { self.store.drain() } /// Shrinks the capacity of the internal data structures /// that support this operation as much as possible. pub fn shrink_to_fit(&mut self) { self.store.shrink_to_fit(); } /// Returns the number of elements in the priority queue. #[inline] pub fn len(&self) -> usize { self.store.len() } /// Returns true if the priority queue contains no elements. pub fn is_empty(&self) -> bool { self.store.is_empty() } /// Returns the couple (item, priority) with the lowest /// priority in the queue, or None if it is empty. /// /// Computes in **O(1)** time pub fn peek_min(&self) -> Option<(&I, &P)> { self.find_min().and_then(|i| { self.store .map .get_index(unsafe { *self.store.heap.get_unchecked(i.0) }.0) }) } /// Reserves capacity for at least `additional` more elements to be inserted /// in the given `DoublePriorityQueue`. The collection may reserve more space to avoid /// frequent reallocations. After calling `reserve`, capacity will be /// greater than or equal to `self.len() + additional`. Does nothing if /// capacity is already sufficient. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. pub fn reserve(&mut self, additional: usize) { self.store.reserve(additional); } /// Reserve capacity for `additional` more elements, without over-allocating. /// /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid /// frequent re-allocations. However, the underlying data structures may still have internal /// capacity requirements, and the allocator itself may give more space than requested, so this /// cannot be relied upon to be precisely minimal. /// /// Computes in **O(n)** time. pub fn reserve_exact(&mut self, additional: usize) { self.store.reserve_exact(additional); } /// Try to reserve capacity for at least `additional` more elements. /// /// Computes in O(n) time. pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { self.store.try_reserve(additional) } /// Try to reserve capacity for `additional` more elements, without over-allocating. /// /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid /// frequent re-allocations. However, the underlying data structures may still have internal /// capacity requirements, and the allocator itself may give more space than requested, so this /// cannot be relied upon to be precisely minimal. /// /// Computes in **O(n)** time. pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { self.store.try_reserve_exact(additional) } } impl DoublePriorityQueue where P: Ord, { /// Return an iterator in arbitrary order over the /// (item, priority) elements in the queue. /// /// The item and the priority are mutable references, but it's a logic error /// to modify the item in a way that change the result of `Hash` or `Eq`. /// /// It's *not* an error, instead, to modify the priorities, because the heap /// will be rebuilt once the `IterMut` goes out of scope. It would be /// rebuilt even if no priority value would have been modified, but the /// procedure will not move anything, but just compare the priorities. pub fn iter_mut(&mut self) -> IterMut { IterMut::new(self) } /// Returns the couple (item, priority) with the greatest /// priority in the queue, or None if it is empty. /// /// Computes in **O(1)** time pub fn peek_max(&self) -> Option<(&I, &P)> { self.find_max().and_then(|i| { self.store .map .get_index(unsafe { *self.store.heap.get_unchecked(i.0) }.0) }) } /// Removes the item with the lowest priority from /// the priority queue and returns the pair (item, priority), /// or None if the queue is empty. pub fn pop_min(&mut self) -> Option<(I, P)> { self.find_min().and_then(|i| { let r = self.store.swap_remove(i); self.heapify(i); r }) } /// Removes the item with the greatest priority from /// the priority queue and returns the pair (item, priority), /// or None if the queue is empty. pub fn pop_max(&mut self) -> Option<(I, P)> { self.find_max().and_then(|i| { let r = self.store.swap_remove(i); self.heapify(i); r }) } /// Implements a HeapSort. /// /// Consumes the PriorityQueue and returns a vector /// with all the items sorted from the one associated to /// the lowest priority to the highest. pub fn into_ascending_sorted_vec(mut self) -> Vec { let mut res = Vec::with_capacity(self.store.size); while let Some((i, _)) = self.pop_min() { res.push(i); } res } /// Implements a HeapSort /// /// Consumes the PriorityQueue and returns a vector /// with all the items sorted from the one associated to /// the highest priority to the lowest. pub fn into_descending_sorted_vec(mut self) -> Vec { let mut res = Vec::with_capacity(self.store.size); while let Some((i, _)) = self.pop_max() { res.push(i); } res } /// Generates a new double ended iterator from self that /// will extract the elements from the one with the lowest priority /// to the highest one. pub fn into_sorted_iter(self) -> IntoSortedIter { IntoSortedIter { pq: self } } } impl DoublePriorityQueue where H: BuildHasher, { /// Returns the couple (item, priority) with the lowest /// priority in the queue, or None if it is empty. /// /// The item is a mutable reference, but it's a logic error to modify it /// in a way that change the result of `Hash` or `Eq`. /// /// The priority cannot be modified with a call to this function. /// To modify the priority use [`push`](DoublePriorityQueue::push), /// [`change_priority`](DoublePriorityQueue::change_priority) or /// [`change_priority_by`](DoublePriorityQueue::change_priority_by). /// /// Computes in **O(1)** time pub fn peek_min_mut(&mut self) -> Option<(&mut I, &P)> { use indexmap::map::MutableKeys; self.find_min() .and_then(move |i| { self.store .map .get_index_mut2(unsafe { *self.store.heap.get_unchecked(i.0) }.0) }) .map(|(k, v)| (k, &*v)) } } impl DoublePriorityQueue where P: Ord, H: BuildHasher, { /// Returns the couple (item, priority) with the greatest /// priority in the queue, or None if it is empty. /// /// The item is a mutable reference, but it's a logic error to modify it /// in a way that change the result of `Hash` or `Eq`. /// /// The priority cannot be modified with a call to this function. /// To modify the priority use [`push`](DoublePriorityQueue::push), /// [`change_priority`](DoublePriorityQueue::change_priority) or /// [`change_priority_by`](DoublePriorityQueue::change_priority_by). /// /// Computes in **O(1)** time pub fn peek_max_mut(&mut self) -> Option<(&mut I, &P)> { use indexmap::map::MutableKeys; self.find_max() .and_then(move |i| { self.store .map .get_index_mut2(unsafe { *self.store.heap.get_unchecked(i.0) }.0) }) .map(|(k, v)| (k, &*v)) } } impl DoublePriorityQueue where P: Ord, I: Hash + Eq, H: BuildHasher, { /// Retains only the elements specified by the `predicate`. /// /// In other words, remove all elements e for which `predicate(&i, &p)` returns `false`. /// The elements are visited in arbitrary order. pub fn retain(&mut self, predicate: F) where F: FnMut(&I, &P) -> bool, { self.store.retain(predicate); self.heap_build(); } /// Retains only the elements specified by the `predicate`. /// /// In other words, remove all elements e for which `predicate(&mut i, &mut p)` returns `false`. /// The elements are visited in arbitrary order. /// /// The `predicate` receives mutable references to both the item and /// the priority. /// /// It's a logical error to change the item in a way /// that changes the result of `Hash` or `Eq`. /// /// The `predicate` can change the priority. If the element is retained, /// it will have the updated one. pub fn retain_mut(&mut self, predicate: F) where F: FnMut(&mut I, &mut P) -> bool, { self.store.retain_mut(predicate); self.heap_build(); } /// Returns an `Iterator` removing from the queue the `(item, priority)` /// pairs for which the `predicate` returns `true`, in arbitraty order. /// /// The `predicate` receives mutable references to both the item and /// the priority. /// /// It's a logical error to change the item in a way /// that changes the result of `Hash` or `Eq`. /// /// The `predicate` can change the priority. If it returns `true`, the /// extracted pair will have the updated priority, otherwise, the /// heap structural property will be restored once the iterator is `Drop`ped. /// /// # Example /// ``` /// # use priority_queue::DoublePriorityQueue; /// let mut pq = DoublePriorityQueue::new(); /// /// pq.push("Apples", 5); /// pq.push("Bananas", 10); /// /// assert_eq!(pq.extract_if(|i, p| { /// *p = 15; /// i == &"Apples" /// }).collect::>(), vec![("Apples", 15)]); /// /// assert_eq!(pq.peek_min(), Some((&"Bananas", &15))); /// assert_eq!(pq.into_vec(), vec!["Bananas"]); /// ``` pub fn extract_if(&mut self, predicate: F) -> ExtractIf where F: FnMut(&mut I, &mut P) -> bool, { ExtractIf::new(self, predicate) } /// Removes the item with the lowest priority from /// the priority queue if the predicate returns `true`. /// /// Returns the pair (item, priority), or None if the /// queue is empty or the predicate returns `false`. /// /// The predicate receives mutable references to both the item and /// the priority. /// /// It's a logical error to change the item in a way /// that changes the result of `Hash` or `EQ`. /// /// The predicate can change the priority. If it returns true, the /// returned couple will have the updated priority, otherwise, the /// heap structural property will be restored. /// /// # Example /// ``` /// # use priority_queue::DoublePriorityQueue; /// let mut pq = DoublePriorityQueue::new(); /// /// pq.push("Apples", 5); /// pq.push("Bananas", 10); /// /// assert_eq!(pq.pop_min_if(|i, p| { /// *p = 15; /// false /// }), None); /// /// assert_eq!(pq.pop_min(), Some(("Bananas", 10))); /// ``` pub fn pop_min_if(&mut self, f: F) -> Option<(I, P)> where F: FnOnce(&mut I, &mut P) -> bool, { self.find_min().and_then(|i| { let r = self.store.swap_remove_if(i, f); self.heapify(i); r }) } /// Removes the item with the greatest priority from /// the priority queue if the predicate returns `true`. /// /// Returns the pair (item, priority), or None if the /// queue is empty or the predicate returns `false`. /// /// The predicate receives mutable references to both the item and /// the priority. /// /// It's a logical error to change the item in a way /// that changes the result of `Hash` or `EQ`. /// /// The predicate can change the priority. If it returns true, the /// returned couple will have the updated priority, otherwise, the /// heap structural property will be restored. /// /// # Example /// ``` /// # use priority_queue::DoublePriorityQueue; /// let mut pq = DoublePriorityQueue::new(); /// pq.push("Apples", 5); /// pq.push("Bananas", 10); /// assert_eq!(pq.pop_max_if(|i, p| { /// *p = 3; /// false /// }), None); /// assert_eq!(pq.pop_max(), Some(("Apples", 5))); /// ``` pub fn pop_max_if(&mut self, f: F) -> Option<(I, P)> where F: FnOnce(&mut I, &mut P) -> bool, { self.find_max().and_then(|i| { let r = self.store.swap_remove_if(i, f); self.up_heapify(i); r }) } /// Insert the item-priority pair into the queue. /// /// If an element equal to `item` is already in the queue, its priority /// is updated and the old priority is returned in `Some`; otherwise, /// `item` is inserted with `priority` and `None` is returned. /// /// # Example /// ``` /// # use priority_queue::DoublePriorityQueue; /// let mut pq = DoublePriorityQueue::new(); /// assert_eq!(pq.push("Apples", 5), None); /// assert_eq!(pq.get_priority("Apples"), Some(&5)); /// assert_eq!(pq.push("Apples", 6), Some(5)); /// assert_eq!(pq.get_priority("Apples"), Some(&6)); /// assert_eq!(pq.push("Apples", 4), Some(6)); /// assert_eq!(pq.get_priority("Apples"), Some(&4)); /// ``` /// /// Computes in **O(log(N))** time. pub fn push(&mut self, item: I, priority: P) -> Option

{ use indexmap::map::Entry::*; let mut pos = Position(0); let mut oldp = None; match self.store.map.entry(item) { Occupied(mut e) => { oldp = Some(replace(e.get_mut(), priority)); pos = unsafe { *self.store.qp.get_unchecked(e.index()) }; } Vacant(e) => { e.insert(priority); } } if oldp.is_some() { self.up_heapify(pos); return oldp; } // get a reference to the priority // copy the current size of the heap let i = self.len(); // add the new element in the qp vector as the last in the heap self.store.qp.push(Position(i)); self.store.heap.push(Index(i)); self.bubble_up(Position(i), Index(i)); self.store.size += 1; None } /// Increase the priority of an existing item in the queue, or /// insert it if not present. /// /// If an element equal to `item` is already in the queue with a /// lower priority, its priority is increased to the new one /// without replacing the element and the old priority is returned /// in `Some`. /// /// If an element equal to `item` is already in the queue with an /// equal or higher priority, its priority is not changed and the /// `priority` argument is returned in `Some`. /// /// If no element equal to `item` is already in the queue, the new /// element is inserted and `None` is returned. /// /// # Example /// ``` /// # use priority_queue::DoublePriorityQueue; /// let mut pq = DoublePriorityQueue::new(); /// assert_eq!(pq.push_increase("Apples", 5), None); /// assert_eq!(pq.get_priority("Apples"), Some(&5)); /// assert_eq!(pq.push_increase("Apples", 6), Some(5)); /// assert_eq!(pq.get_priority("Apples"), Some(&6)); /// // Already present with higher priority, so requested (lower) /// // priority is returned. /// assert_eq!(pq.push_increase("Apples", 4), Some(4)); /// assert_eq!(pq.get_priority("Apples"), Some(&6)); /// ``` /// /// Computes in **O(log(N))** time. pub fn push_increase(&mut self, item: I, priority: P) -> Option

{ if self.get_priority(&item).map_or(true, |p| priority > *p) { self.push(item, priority) } else { Some(priority) } } /// Decrease the priority of an existing item in the queue, or /// insert it if not present. /// /// If an element equal to `item` is already in the queue with a /// higher priority, its priority is decreased to the new one /// without replacing the element and the old priority is returned /// in `Some`. /// /// If an element equal to `item` is already in the queue with an /// equal or lower priority, its priority is not changed and the /// `priority` argument is returned in `Some`. /// /// If no element equal to `item` is already in the queue, the new /// element is inserted and `None` is returned. /// /// # Example /// ``` /// # use priority_queue::DoublePriorityQueue; /// let mut pq = DoublePriorityQueue::new(); /// assert_eq!(pq.push_decrease("Apples", 5), None); /// assert_eq!(pq.get_priority("Apples"), Some(&5)); /// assert_eq!(pq.push_decrease("Apples", 4), Some(5)); /// assert_eq!(pq.get_priority("Apples"), Some(&4)); /// // Already present with lower priority, so requested (higher) /// // priority is returned. /// assert_eq!(pq.push_decrease("Apples", 6), Some(6)); /// assert_eq!(pq.get_priority("Apples"), Some(&4)); /// ``` /// /// Computes in **O(log(N))** time. pub fn push_decrease(&mut self, item: I, priority: P) -> Option

{ if self.get_priority(&item).map_or(true, |p| priority < *p) { self.push(item, priority) } else { Some(priority) } } /// Change the priority of an Item returning the old value of priority, /// or `None` if the item wasn't in the queue. /// /// The argument `item` is only used for lookup, and is not used to overwrite the item's data /// in the priority queue. /// /// # Example /// ``` /// # use priority_queue::DoublePriorityQueue; /// let mut pq = DoublePriorityQueue::new(); /// assert_eq!(pq.change_priority("Apples", 5), None); /// assert_eq!(pq.get_priority("Apples"), None); /// assert_eq!(pq.push("Apples", 6), None); /// assert_eq!(pq.get_priority("Apples"), Some(&6)); /// assert_eq!(pq.change_priority("Apples", 4), Some(6)); /// assert_eq!(pq.get_priority("Apples"), Some(&4)); /// ``` /// /// The item is found in **O(1)** thanks to the hash table. /// The operation is performed in **O(log(N))** time. pub fn change_priority(&mut self, item: &Q, new_priority: P) -> Option

where Q: ?Sized + Equivalent + Hash, { self.store .change_priority(item, new_priority) .map(|(r, pos)| { self.up_heapify(pos); r }) } /// Change the priority of an Item using the provided function. /// Return a boolean value where `true` means the item was in the queue and update was successful /// /// The argument `item` is only used for lookup, and is not used to overwrite the item's data /// in the priority queue. /// /// The item is found in **O(1)** thanks to the hash table. /// The operation is performed in **O(log(N))** time (worst case). pub fn change_priority_by(&mut self, item: &Q, priority_setter: F) -> bool where Q: ?Sized + Equivalent + Hash, F: FnOnce(&mut P), { self.store .change_priority_by(item, priority_setter) .map(|pos| { self.up_heapify(pos); }) .is_some() } /// Get the priority of an item, or `None`, if the item is not in the queue pub fn get_priority(&self, item: &Q) -> Option<&P> where Q: ?Sized + Equivalent + Hash, { self.store.get_priority(item) } /// Check if the queue contains `item`. /// /// Returns `true` if `item` is in the queue, `false` if it is not. pub fn contains(&self, item: &Q) -> bool where Q: ?Sized + Equivalent + Hash, { self.store.contains(item) } /// Get the couple (item, priority) of an arbitrary element, as reference /// or `None` if the item is not in the queue. pub fn get(&self, item: &Q) -> Option<(&I, &P)> where Q: ?Sized + Equivalent + Hash, { self.store.get(item) } /// Get the couple (item, priority) of an arbitrary element, or `None` /// if the item was not in the queue. /// /// The item is a mutable reference, but it's a logic error to modify it /// in a way that change the result of `Hash` or `Eq`. /// /// The priority cannot be modified with a call to this function. /// To modify the priority use use [`push`](DoublePriorityQueue::push), /// [`change_priority`](DoublePriorityQueue::change_priority) or /// [`change_priority_by`](DoublePriorityQueue::change_priority_by). pub fn get_mut(&mut self, item: &Q) -> Option<(&mut I, &P)> where Q: ?Sized + Equivalent + Hash, { self.store.get_mut(item) } /// Remove an arbitrary element from the priority queue. /// Returns the (item, priority) couple or None if the item /// is not found in the queue. /// /// The operation is performed in **O(log(N))** time (worst case). pub fn remove(&mut self, item: &Q) -> Option<(I, P)> where Q: ?Sized + Equivalent + Hash, { self.store.remove(item).map(|(item, priority, pos)| { if pos.0 < self.len() { self.up_heapify(pos); } (item, priority) }) } /// Returns the items not ordered pub fn into_vec(self) -> Vec { self.store.into_vec() } /// Drops all items from the priority queue pub fn clear(&mut self) { self.store.clear(); } /// Move all items of the `other` queue to `self` /// ignoring the items Eq to elements already in `self` /// At the end, `other` will be empty. /// /// **Note** that at the end, the priority of the duplicated elements /// inside `self` may be the one of the elements in `other`, /// if `other` is longer than `self` pub fn append(&mut self, other: &mut Self) { self.store.append(&mut other.store); self.heap_build(); } } impl DoublePriorityQueue { /// Returns the index of the min element fn find_min(&self) -> Option { match self.len() { 0 => None, _ => Some(Position(0)), } } } impl DoublePriorityQueue where P: Ord, { /**************************************************************************/ /* internal functions */ fn heapify(&mut self, i: Position) { if self.len() <= 1 { return; } if level(i) % 2 == 0 { self.heapify_min(i) } else { self.heapify_max(i) } } fn heapify_min(&mut self, mut i: Position) { while i <= parent(Position(self.len() - 1)) { let m = i; let l = left(i); let r = right(i); // Minimum of childs and grandchilds i = *[l, r, left(l), right(l), left(r), right(r)] .iter() .map_while(|i| self.store.heap.get(i.0).map(|index| (i, index))) .min_by_key(|(_, index)| { self.store .map .get_index(index.0) .map(|(_, priority)| priority) .unwrap() }) .unwrap() .0; if unsafe { self.store.get_priority_from_position(i) < self.store.get_priority_from_position(m) } { self.store.swap(i, m); if i > r { // i is a grandchild of m let p = parent(i); if unsafe { self.store.get_priority_from_position(i) > self.store.get_priority_from_position(p) } { self.store.swap(i, p); } } else { break; } } else { break; } } } fn heapify_max(&mut self, mut i: Position) { while i <= parent(Position(self.len() - 1)) { let m = i; let l = left(i); let r = right(i); // Minimum of childs and grandchilds i = *[l, r, left(l), right(l), left(r), right(r)] .iter() .map_while(|i| self.store.heap.get(i.0).map(|index| (i, index))) .max_by_key(|(_, index)| { self.store .map .get_index(index.0) .map(|(_, priority)| priority) .unwrap() }) .unwrap() .0; if unsafe { self.store.get_priority_from_position(i) > self.store.get_priority_from_position(m) } { self.store.swap(i, m); if i > r { // i is a grandchild of m let p = parent(i); if unsafe { self.store.get_priority_from_position(i) < self.store.get_priority_from_position(p) } { self.store.swap(i, p); } } else { break; } } else { break; } } } fn bubble_up(&mut self, mut position: Position, map_position: Index) -> Position { let priority = self.store.map.get_index(map_position.0).unwrap().1; if position.0 > 0 { let parent = parent(position); let parent_priority = unsafe { self.store.get_priority_from_position(parent) }; let parent_index = unsafe { *self.store.heap.get_unchecked(parent.0) }; position = match (level(position) % 2 == 0, parent_priority < priority) { // on a min level and greater then parent (true, true) => { unsafe { *self.store.heap.get_unchecked_mut(position.0) = parent_index; *self.store.qp.get_unchecked_mut(parent_index.0) = position; } self.bubble_up_max(parent, map_position) } // on a min level and less then parent (true, false) => self.bubble_up_min(position, map_position), // on a max level and greater then parent (false, true) => self.bubble_up_max(position, map_position), // on a max level and less then parent (false, false) => { unsafe { *self.store.heap.get_unchecked_mut(position.0) = parent_index; *self.store.qp.get_unchecked_mut(parent_index.0) = position; } self.bubble_up_min(parent, map_position) } } } unsafe { // put the new element into the heap and // update the qp translation table and the size *self.store.heap.get_unchecked_mut(position.0) = map_position; *self.store.qp.get_unchecked_mut(map_position.0) = position; } position } fn bubble_up_min(&mut self, mut position: Position, map_position: Index) -> Position { let priority = self.store.map.get_index(map_position.0).unwrap().1; let mut grand_parent = Position(0); while if position.0 > 0 && parent(position).0 > 0 { grand_parent = parent(parent(position)); (unsafe { self.store.get_priority_from_position(grand_parent) }) > priority } else { false } { unsafe { let grand_parent_index = *self.store.heap.get_unchecked(grand_parent.0); *self.store.heap.get_unchecked_mut(position.0) = grand_parent_index; *self.store.qp.get_unchecked_mut(grand_parent_index.0) = position; } position = grand_parent; } position } fn bubble_up_max(&mut self, mut position: Position, map_position: Index) -> Position { let priority = self.store.map.get_index(map_position.0).unwrap().1; let mut grand_parent = Position(0); while if position.0 > 0 && parent(position).0 > 0 { grand_parent = parent(parent(position)); (unsafe { self.store.get_priority_from_position(grand_parent) }) < priority } else { false } { unsafe { let grand_parent_index = *self.store.heap.get_unchecked(grand_parent.0); *self.store.heap.get_unchecked_mut(position.0) = grand_parent_index; *self.store.qp.get_unchecked_mut(grand_parent_index.0) = position; } position = grand_parent; } position } fn up_heapify(&mut self, i: Position) { if let Some(&tmp) = self.store.heap.get(i.0) { let pos = self.bubble_up(i, tmp); if i != pos { self.heapify(i) } self.heapify(pos); } } /// Internal function that transform the `heap` /// vector in a heap with its properties /// /// Computes in **O(N)** pub(crate) fn heap_build(&mut self) { if self.is_empty() { return; } for i in (0..=parent(Position(self.len())).0).rev() { self.heapify(Position(i)); } } /// Returns the index of the max element fn find_max(&self) -> Option { match self.len() { 0 => None, 1 => Some(Position(0)), 2 => Some(Position(1)), _ => Some( *[Position(1), Position(2)] .iter() .max_by_key(|i| unsafe { self.store.get_priority_from_position(**i) }) .unwrap(), ), } } } //FIXME: fails when the vector contains repeated items // FIXED: repeated items ignored impl From> for DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn from(vec: Vec<(I, P)>) -> Self { let store = Store::from(vec); let mut pq = DoublePriorityQueue { store }; pq.heap_build(); pq } } use crate::PriorityQueue; impl From> for DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { fn from(pq: PriorityQueue) -> Self { let store = pq.store; let mut this = Self { store }; this.heap_build(); this } } //FIXME: fails when the iterator contains repeated items // FIXED: the item inside the pq is updated // so there are two functions with different behaviours. impl FromIterator<(I, P)> for DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn from_iter(iter: IT) -> Self where IT: IntoIterator, { let store = Store::from_iter(iter); let mut pq = DoublePriorityQueue { store }; pq.heap_build(); pq } } impl IntoIterator for DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { type Item = (I, P); type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { self.store.into_iter() } } impl<'a, I, P, H> IntoIterator for &'a DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { type Item = (&'a I, &'a P); type IntoIter = Iter<'a, I, P>; fn into_iter(self) -> Iter<'a, I, P> { self.store.iter() } } impl<'a, I, P, H> IntoIterator for &'a mut DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { type Item = (&'a mut I, &'a mut P); type IntoIter = IterMut<'a, I, P, H>; fn into_iter(self) -> IterMut<'a, I, P, H> { IterMut::new(self) } } impl Extend<(I, P)> for DoublePriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { fn extend>(&mut self, iter: T) { let iter = iter.into_iter(); let (min, max) = iter.size_hint(); let rebuild = if let Some(max) = max { self.reserve(max); better_to_rebuild(self.len(), max) } else if min != 0 { self.reserve(min); better_to_rebuild(self.len(), min) } else { false }; if rebuild { self.store.extend(iter); self.heap_build(); } else { for (item, priority) in iter { self.push(item, priority); } } } } use std::fmt; impl fmt::Debug for DoublePriorityQueue where I: Hash + Eq + fmt::Debug, P: Ord + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { self.store.fmt(f) } } use std::cmp::PartialEq; impl PartialEq> for DoublePriorityQueue where I: Hash + Eq, P1: Ord, P1: PartialEq, Option: PartialEq>, P2: Ord, H1: BuildHasher, H2: BuildHasher, { fn eq(&self, other: &DoublePriorityQueue) -> bool { self.store == other.store } } #[cfg(feature = "serde")] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] mod serde { use std::cmp::{Eq, Ord}; use std::hash::{BuildHasher, Hash}; use serde::de::{Deserialize, Deserializer}; use serde::ser::{Serialize, Serializer}; use super::DoublePriorityQueue; use crate::store::Store; impl Serialize for DoublePriorityQueue where I: Hash + Eq + Serialize, P: Ord + Serialize, H: BuildHasher, { fn serialize(&self, serializer: S) -> Result where S: Serializer, { self.store.serialize(serializer) } } impl<'de, I, P, H> Deserialize<'de> for DoublePriorityQueue where I: Hash + Eq + Deserialize<'de>, P: Ord + Deserialize<'de>, H: BuildHasher + Default, { fn deserialize(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { Store::deserialize(deserializer).map(|store| { let mut pq = DoublePriorityQueue { store }; pq.heap_build(); pq }) } } } priority-queue-2.6.0/src/lib.rs000064400000000000000000000130451046102023000145420ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi and contributors * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ //! This crate provides 2 main data structures: //! * a [priority queue](PriorityQueue) //! * a [double priority queue](DoublePriorityQueue). //! //! Both data structures are backed by an hashmap, allowing //! to change the priority of an element with some efficient methods in //! **O(log(N))** time (worst case). //! //! The elements (called `Item`s, of type `I`) must implement //! [`Hash`](https://doc.rust-lang.org/std/hash/trait.Hash.html) //! and [`Eq`](https://doc.rust-lang.org/std/cmp/trait.Eq.html) traits. //! //! This can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`. //! If you implement these yourself, it is important that the following property holds: //! //! ```text //! k1 == k2 -> hash(k1) == hash(k2) //! ``` //! //! In other words, if two keys are equal, their hashes must be equal. //! //! The priority `P` may be any type that implements //! [`Ord`](https://doc.rust-lang.org/std/cmp/trait.Ord.html). //! For reverse order remember the standard wrapper //! [`Reverse`](https://doc.rust-lang.org/std/cmp/struct.Reverse.html) //! //! # Examples //! ```rust //! use priority_queue::PriorityQueue; //! //! let mut pq = PriorityQueue::new(); //! //! assert!(pq.is_empty()); //! pq.push("Apples", 5); //! pq.push("Bananas", 8); //! pq.push("Strawberries", 23); //! //! assert_eq!(pq.peek(), Some((&"Strawberries", &23))); //! //! pq.change_priority("Bananas", 25); //! assert_eq!(pq.peek(), Some((&"Bananas", &25))); //! //! for (item, _) in pq.into_sorted_iter() { //! println!("{}", item); // Will print Bananas, Strawberries, Apples //! } //! ``` //! //! ## Reverse ordering //! ```rust //! use priority_queue::PriorityQueue; //! use std::cmp::Reverse; //! //! let mut pq = PriorityQueue::new(); //! //! assert!(pq.is_empty()); //! pq.push("Apples", Reverse(5)); //! pq.push("Bananas", Reverse(8)); //! pq.push("Strawberries", Reverse(23)); //! //! assert_eq!(pq.peek(), Some((&"Apples", &Reverse(5)))); //! //! for (item, _) in pq.into_sorted_iter() { //! println!("{}", item); // Will print Apples, Bananas, Strawberries //! } //! ``` //! //! # Crate features //! //! * **std** - Use the standard library. This enables the creation of queues //! with the standard hasher `RandomState` using the `new` and `with_capacity` //! static methods. //! This feature is **enabled by default** and can be disabled when compiling //! for no_std targets. //! * **serde** - Enables serialization/deserialization using serde #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg))] #[cfg(not(feature = "std"))] extern crate alloc; #[cfg(not(feature = "std"))] pub(crate) mod std { pub use ::alloc::collections; pub use core::*; } pub mod core_iterators; pub mod double_priority_queue; pub mod priority_queue; mod store; pub use crate::double_priority_queue::DoublePriorityQueue; pub use crate::priority_queue::PriorityQueue; use crate::store::log2_fast; use indexmap::TryReserveError as IndexMapTryReserveError; use std::collections::TryReserveError as StdTryReserveError; #[derive(Clone, PartialEq, Eq, Debug)] pub struct TryReserveError { kind: TryReserveErrorKind, } /// The error type for `try_reserve` methods. #[derive(Clone, PartialEq, Eq, Debug)] enum TryReserveErrorKind { Std(StdTryReserveError), IndexMap(IndexMapTryReserveError), } #[cfg(feature = "std")] impl std::error::Error for TryReserveError {} impl core::fmt::Display for TryReserveError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match &self.kind { TryReserveErrorKind::Std(e) => core::fmt::Display::fmt(e, f), TryReserveErrorKind::IndexMap(e) => core::fmt::Display::fmt(e, f), } } } use TryReserveErrorKind::*; impl From for TryReserveError { fn from(source: StdTryReserveError) -> Self { Self { kind: Std(source) } } } impl From for TryReserveError { fn from(source: IndexMapTryReserveError) -> Self { Self { kind: IndexMap(source), } } } // `rebuild` takes O(len1 + len2) operations // and about 2 * (len1 + len2) comparisons in the worst case // while `extend` takes O(len2 * log_2(len1)) operations // and about 1 * len2 * log_2(len1) comparisons in the worst case, // assuming len1 >= len2. fn better_to_rebuild(len1: usize, len2: usize) -> bool { // log(1) == 0, so the inequation always falsy // log(0) is inapplicable and produces panic if len1 <= 1 { return false; } 2 * (len1 + len2) < len2 * log2_fast(len1) } priority-queue-2.6.0/src/priority_queue/iterators.rs000064400000000000000000000133131046102023000210730ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ //! This module defines iterator types that are used only with the [`PriorityQueue`]. //! //! Usually you don't need to explicitly `use` any of the types declared here. #[cfg(not(feature = "std"))] use crate::core_iterators::std; use core::hash::BuildHasher; use std::cmp::Ord; #[cfg(feature = "std")] use std::collections::hash_map::RandomState; use std::iter::*; use crate::PriorityQueue; use super::Index; /// An `Iterator` in arbitrary order which uses a `predicate` to determine if /// an element should be removed from the `PriorityQueue`. /// /// It can be obtained calling the [`extract_if`](PriorityQueue::extract_if) method. /// /// The `predicate` has mutable access to the `(item, priority)` pairs. /// /// It can update the priorities of the elements in the queue and the items /// in a way that does not change the result of any of `hash` or `eq`. /// /// When the iterator goes out of scope, the heap is rebuilt to restore the /// structural properties. #[cfg(feature = "std")] pub struct ExtractIf<'a, I: 'a, P: 'a, F, H: 'a = RandomState> where P: Ord, { pq: &'a mut PriorityQueue, predicate: F, idx: Index, } #[cfg(not(feature = "std"))] pub struct ExtractIf<'a, I: 'a, P: 'a, F, H: 'a> where P: Ord, { pq: &'a mut PriorityQueue, predicate: F, idx: Index, } impl<'a, I: 'a, P: 'a, F, H: 'a> ExtractIf<'a, I, P, F, H> where P: Ord, { pub(crate) fn new(pq: &'a mut PriorityQueue, predicate: F) -> Self { ExtractIf { pq, predicate, idx: Index(0), } } } impl<'a, I: 'a, P: 'a, F, H: 'a> Iterator for ExtractIf<'a, I, P, F, H> where P: Ord, F: FnMut(&mut I, &mut P) -> bool, H: BuildHasher, { type Item = (I, P); fn next(&mut self) -> Option { use indexmap::map::MutableKeys; loop { let r: Option = self .pq .store .map .get_index_mut2(self.idx.0) .map(|(i, p)| (self.predicate)(i, p)); match r { Some(true) => return self.pq.store.swap_remove_index(self.idx), Some(false) => self.idx.0 += 1, None => return None, } } } } impl<'a, I: 'a, P: 'a, F, H: 'a> Drop for ExtractIf<'a, I, P, F, H> where P: Ord, { fn drop(&mut self) { self.pq.heap_build(); } } /// A mutable iterator over the couples `(item, priority)` of the `PriorityQueue` /// in arbitrary order. /// /// It can be obtained calling the [`iter_mut`](PriorityQueue::iter_mut) method. /// /// It can be used to update the priorities of the elements in the queue. /// When the iterator goes out of scope, the heap is rebuilt to restore the /// structural properties. /// /// The item is mutable too, but it is a logical error to modify it in a way that /// changes the result of any of `hash` or `eq`. #[cfg(feature = "std")] pub struct IterMut<'a, I: 'a, P: 'a, H: 'a = RandomState> where P: Ord, { pq: &'a mut PriorityQueue, pos: usize, } #[cfg(not(feature = "std"))] pub struct IterMut<'a, I: 'a, P: 'a, H: 'a> where P: Ord, { pq: &'a mut PriorityQueue, pos: usize, } impl<'a, I: 'a, P: 'a, H: 'a> IterMut<'a, I, P, H> where P: Ord, { pub(crate) fn new(pq: &'a mut PriorityQueue) -> Self { IterMut { pq, pos: 0 } } } impl<'a, I: 'a, P: 'a, H: 'a> Iterator for IterMut<'a, I, P, H> where P: Ord, H: BuildHasher, { type Item = (&'a mut I, &'a mut P); fn next(&mut self) -> Option { use indexmap::map::MutableKeys; let r: Option<(&'a mut I, &'a mut P)> = self .pq .store .map .get_index_mut2(self.pos) .map(|(i, p)| (i as *mut I, p as *mut P)) .map(|(i, p)| unsafe { (i.as_mut().unwrap(), p.as_mut().unwrap()) }); self.pos += 1; r } } impl<'a, I: 'a, P: 'a, H: 'a> Drop for IterMut<'a, I, P, H> where P: Ord, { fn drop(&mut self) { self.pq.heap_build(); } } /// A consuming iterator over the couples `(item, priority)` of the `PriorityQueue` /// ordered by priority, from the highest to the lowest. /// /// It can be obtained calling the [`into_sorted_iter`](PriorityQueue::into_sorted_iter) method. #[cfg(feature = "std")] pub struct IntoSortedIter { pub(crate) pq: PriorityQueue, } #[cfg(not(feature = "std"))] pub struct IntoSortedIter { pub(crate) pq: PriorityQueue, } impl Iterator for IntoSortedIter where P: Ord, { type Item = (I, P); fn next(&mut self) -> Option<(I, P)> { self.pq.pop() } } priority-queue-2.6.0/src/priority_queue/mod.rs000064400000000000000000000775151046102023000176540ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ //! This module contains the [`PriorityQueue`] type and the related iterators. //! //! See the type level documentation for more details and examples. pub mod iterators; #[cfg(not(feature = "std"))] use std::vec::Vec; use crate::better_to_rebuild; use crate::core_iterators::*; use crate::store::{left, parent, right}; use crate::store::{Index, Position, Store}; use crate::TryReserveError; use equivalent::Equivalent; use iterators::*; use std::cmp::{Eq, Ord}; #[cfg(feature = "std")] use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hash}; use std::iter::{Extend, FromIterator, IntoIterator, Iterator}; use std::mem::replace; /// A priority queue with efficient change function to change the priority of an /// element. /// /// The priority is of type `P`, that must implement `std::cmp::Ord`. /// /// The item is of type `I`, that must implement `Hash` and `Eq`. /// /// Implemented as a heap of indexes, stores the items inside an `IndexMap` /// to be able to retrieve them quickly. /// /// # Example /// ```rust /// use priority_queue::PriorityQueue; /// /// let mut pq = PriorityQueue::new(); /// /// assert!(pq.is_empty()); /// pq.push("Apples", 5); /// pq.push("Bananas", 8); /// pq.push("Strawberries", 23); /// /// assert_eq!(pq.peek(), Some((&"Strawberries", &23))); /// /// pq.change_priority("Bananas", 25); /// assert_eq!(pq.peek(), Some((&"Bananas", &25))); /// /// for (item, _) in pq.into_sorted_iter() { /// println!("{}", item); /// } /// ``` #[derive(Clone, Debug)] #[cfg(feature = "std")] pub struct PriorityQueue { pub(crate) store: Store, } #[derive(Clone, Debug)] #[cfg(not(feature = "std"))] pub struct PriorityQueue { pub(crate) store: Store, } // do not [derive(Eq)] to loosen up trait requirements for other types and impls impl Eq for PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { } impl Default for PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn default() -> Self { Self::with_default_hasher() } } #[cfg(feature = "std")] impl PriorityQueue where P: Ord, I: Hash + Eq, { /// Creates an empty `PriorityQueue` pub fn new() -> Self { Self::with_capacity(0) } /// Creates an empty `PriorityQueue` with the specified capacity. pub fn with_capacity(capacity: usize) -> Self { Self::with_capacity_and_default_hasher(capacity) } } impl PriorityQueue where P: Ord, I: Hash + Eq, H: BuildHasher + Default, { /// Creates an empty `PriorityQueue` with the default hasher pub fn with_default_hasher() -> Self { Self::with_capacity_and_default_hasher(0) } /// Creates an empty `PriorityQueue` with the specified capacity and default hasher pub fn with_capacity_and_default_hasher(capacity: usize) -> Self { Self::with_capacity_and_hasher(capacity, H::default()) } } impl PriorityQueue where P: Ord, I: Hash + Eq, H: BuildHasher, { /// Creates an empty `PriorityQueue` with the specified hasher pub const fn with_hasher(hash_builder: H) -> Self { Self { store: Store::with_hasher(hash_builder), } } /// Creates an empty `PriorityQueue` with the specified capacity and hasher /// /// The internal collections will be able to hold at least `capacity` /// elements without reallocating. /// If `capacity` is 0, there will be no allocation. pub fn with_capacity_and_hasher(capacity: usize, hash_builder: H) -> Self { Self { store: Store::with_capacity_and_hasher(capacity, hash_builder), } } } impl PriorityQueue { /// Returns an iterator in arbitrary order over the /// `(item, priority)` elements in the queue pub fn iter(&self) -> Iter { self.store.iter() } /// Shrinks the capacity of the internal data structures /// that support this operation as much as possible. pub fn shrink_to_fit(&mut self) { self.store.shrink_to_fit(); } /// Clears the `PriorityQueue`, returning an iterator over the removed elements in arbitrary order. /// If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order. pub fn drain(&mut self) -> Drain { self.store.drain() } /// Returns the couple `(item, priority)` with the greatest /// priority in the queue, or `None` if it is empty. /// /// Computes in **O(1)** time pub fn peek(&self) -> Option<(&I, &P)> { self.store .heap .first() .and_then(|index| self.store.map.get_index(index.0)) } /// Returns the number of elements the internal map can hold without /// reallocating. /// /// This number is a lower bound; the map might be able to hold more, /// but is guaranteed to be able to hold at least this many. pub fn capacity(&self) -> usize { self.store.capacity() } /// Returns the number of elements in the priority queue. #[inline] pub fn len(&self) -> usize { self.store.len() } /// Returns `true` if the priority queue contains no elements. pub fn is_empty(&self) -> bool { self.store.is_empty() } /// Returns the items not ordered pub fn into_vec(self) -> Vec { self.store.into_vec() } /// Drops all items from the priority queue pub fn clear(&mut self) { self.store.clear(); } /// Reserves capacity for at least `additional` more elements to be inserted /// in the given `PriorityQueue`. The collection may reserve more space to avoid /// frequent reallocations. After calling `reserve`, capacity will be /// greater than or equal to `self.len() + additional`. Does nothing if /// capacity is already sufficient. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. pub fn reserve(&mut self, additional: usize) { self.store.reserve(additional); } /// Reserve capacity for `additional` more elements, without over-allocating. /// /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid /// frequent re-allocations. However, the underlying data structures may still have internal /// capacity requirements, and the allocator itself may give more space than requested, so this /// cannot be relied upon to be precisely minimal. /// /// Computes in **O(n)** time. pub fn reserve_exact(&mut self, additional: usize) { self.store.reserve_exact(additional); } /// Try to reserve capacity for at least `additional` more elements. /// /// Computes in O(n) time. pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { self.store.try_reserve(additional) } /// Try to reserve capacity for `additional` more elements, without over-allocating. /// /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid /// frequent re-allocations. However, the underlying data structures may still have internal /// capacity requirements, and the allocator itself may give more space than requested, so this /// cannot be relied upon to be precisely minimal. /// /// Computes in **O(n)** time. pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { self.store.try_reserve_exact(additional) } } impl PriorityQueue where P: Ord, { /// Returns an iterator in arbitrary order over the /// `(item, priority)` elements in the queue. /// /// The item and the priority are mutable references, but it's a logic error /// to modify the item in a way that change the result of `Hash` or `Eq`. /// /// It's *not* an error, instead, to modify the priorities, because the heap /// will be rebuilt once the `IterMut` goes out of scope. /// /// It would be rebuilt even if no priority value would have been modified, /// but the procedure will not move anything, but just compare the priorities. pub fn iter_mut(&mut self) -> IterMut { IterMut::new(self) } /// Removes the item with the greatest priority from /// the priority queue and returns the pair `(item, priority)`, /// or `None` if the queue is empty. pub fn pop(&mut self) -> Option<(I, P)> { match self.len() { 0 => None, 1 => self.store.swap_remove(Position(0)), _ => { let r = self.store.swap_remove(Position(0)); self.heapify(Position(0)); r } } } /// Implements a heap sort. /// /// Returns a `Vec` sorted from the item associated to the highest priority to the lowest. pub fn into_sorted_vec(mut self) -> Vec { let mut res = Vec::with_capacity(self.store.size); while let Some((i, _)) = self.pop() { res.push(i); } res } /// Generates a new iterator from `self` that /// will extract the elements from the one with the highest priority /// to the lowest one. pub fn into_sorted_iter(self) -> IntoSortedIter { IntoSortedIter { pq: self } } } impl PriorityQueue where P: Ord, I: Hash + Eq, H: BuildHasher, { /// Retains only the elements specified by the `predicate`. /// /// In other words, remove all elements e for which `predicate(&i, &p)` returns `false`. /// The elements are visited in arbitrary order. pub fn retain(&mut self, predicate: F) where F: FnMut(&I, &P) -> bool, { self.store.retain(predicate); self.heap_build(); } /// Retains only the elements specified by the `predicate`. /// /// In other words, remove all elements e for which `predicate(&mut i, &mut p)` returns `false`. /// The elements are visited in arbitrary order. /// /// The `predicate` receives mutable references to both the item and /// the priority. /// /// It's a logical error to change the item in a way /// that changes the result of `Hash` or `Eq`. /// /// The `predicate` can change the priority. If the element is retained, /// it will have the updated one. pub fn retain_mut(&mut self, predicate: F) where F: FnMut(&mut I, &mut P) -> bool, { self.store.retain_mut(predicate); self.heap_build(); } /// Returns an `Iterator` removing from the queue the `(item, priority)` /// pairs for which the `predicate` returns `true`, in arbitraty order. /// /// The `predicate` receives mutable references to both the item and /// the priority. /// /// It's a logical error to change the item in a way /// that changes the result of `Hash` or `Eq`. /// /// The `predicate` can change the priority. If it returns `true`, the /// extracted pair will have the updated priority, otherwise, the /// heap structural property will be restored once the iterator is `Drop`ped. /// /// # Example /// ``` /// # use priority_queue::PriorityQueue; /// let mut pq = PriorityQueue::new(); /// /// pq.push("Apples", 5); /// pq.push("Bananas", 10); /// /// assert_eq!(pq.extract_if(|i, p| { /// *p = 15; /// i == &"Apples" /// }).collect::>(), vec![("Apples", 15)]); /// /// assert_eq!(pq.peek(), Some((&"Bananas", &15))); /// assert_eq!(pq.into_vec(), vec!["Bananas"]); /// ``` pub fn extract_if(&mut self, predicate: F) -> ExtractIf where F: FnMut(&mut I, &mut P) -> bool, { ExtractIf::new(self, predicate) } /// Removes the item with the greatest priority from /// the priority queue if the `predicate` returns `true`. /// /// Returns the pair `(item, priority)`, or `None` if the /// queue is empty or the `predicate` returns `false`. /// /// The `predicate` receives mutable references to both the item /// and the priority. /// /// It's a logical error to change the item in a way /// that changes the result of `Hash` or `Eq`. /// /// The `predicate` can change the priority. If it returns `true`, /// the returned couple will have the updated priority, /// otherwise, the heap structural property will be restored. /// /// # Example /// ``` /// # use priority_queue::PriorityQueue; /// let mut pq = PriorityQueue::new(); /// /// pq.push("Apples", 5); /// pq.push("Bananas", 10); /// /// assert_eq!(pq.pop_if(|i, p| { /// *p = 3; /// false /// }), None); /// /// assert_eq!(pq.pop(), Some(("Apples", 5))); /// ``` pub fn pop_if(&mut self, predicate: F) -> Option<(I, P)> where F: FnOnce(&mut I, &mut P) -> bool, { match self.len() { 0 => None, 1 => self.store.swap_remove_if(Position(0), predicate), _ => { let r = self.store.swap_remove_if(Position(0), predicate); self.heapify(Position(0)); r } } } /// Insert the `(item, priority)` pair into the queue. /// /// If an element equal to `item` is already in the queue, its priority /// is updated and the old priority is returned in `Some`; otherwise, /// `item` is inserted with `priority` and `None` is returned. /// /// # Example /// ``` /// # use priority_queue::PriorityQueue; /// let mut pq = PriorityQueue::new(); /// assert_eq!(pq.push("Apples", 5), None); /// assert_eq!(pq.get_priority("Apples"), Some(&5)); /// assert_eq!(pq.push("Apples", 6), Some(5)); /// assert_eq!(pq.get_priority("Apples"), Some(&6)); /// assert_eq!(pq.push("Apples", 4), Some(6)); /// assert_eq!(pq.get_priority("Apples"), Some(&4)); /// ``` /// /// Computes in **O(log(N))** time. pub fn push(&mut self, item: I, priority: P) -> Option

{ use indexmap::map::Entry::*; let mut pos = Position(0); let mut oldp = None; match self.store.map.entry(item) { Occupied(mut e) => { oldp = Some(replace(e.get_mut(), priority)); pos = unsafe { *self.store.qp.get_unchecked(e.index()) }; } Vacant(e) => { e.insert(priority); } } if oldp.is_some() { self.up_heapify(pos); return oldp; } // copy the current size of the heap let i = self.len(); // add the new element in the qp vector as the last in the heap self.store.qp.push(Position(i)); self.store.heap.push(Index(i)); self.bubble_up(Position(i), Index(i)); self.store.size += 1; None } /// Increase the priority of an existing item in the queue, or /// insert it if not present. /// /// If an element equal to `item` is already in the queue with a /// lower priority, its priority is increased to the new one /// without replacing the element and the old priority is returned /// in `Some`. /// /// If an element equal to `item` is already in the queue with an /// equal or higher priority, its priority is not changed and the /// `priority` argument is returned in `Some`. /// /// If no element equal to `item` is already in the queue, the new /// element is inserted and `None` is returned. /// /// # Example /// ``` /// # use priority_queue::PriorityQueue; /// let mut pq = PriorityQueue::new(); /// assert_eq!(pq.push_increase("Apples", 5), None); /// assert_eq!(pq.get_priority("Apples"), Some(&5)); /// assert_eq!(pq.push_increase("Apples", 6), Some(5)); /// assert_eq!(pq.get_priority("Apples"), Some(&6)); /// // Already present with higher priority, so requested (lower) /// // priority is returned. /// assert_eq!(pq.push_increase("Apples", 4), Some(4)); /// assert_eq!(pq.get_priority("Apples"), Some(&6)); /// ``` /// /// Computes in **O(log(N))** time. pub fn push_increase(&mut self, item: I, priority: P) -> Option

{ if self.get_priority(&item).map_or(true, |p| priority > *p) { self.push(item, priority) } else { Some(priority) } } /// Decrease the priority of an existing item in the queue, or /// insert it if not present. /// /// If an element equal to `item` is already in the queue with a /// higher priority, its priority is decreased to the new one /// without replacing the element and the old priority is returned /// in `Some`. /// /// If an element equal to `item` is already in the queue with an /// equal or lower priority, its priority is not changed and the /// `priority` argument is returned in `Some`. /// /// If no element equal to `item` is already in the queue, the new /// element is inserted and `None` is returned. /// /// # Example /// ``` /// # use priority_queue::PriorityQueue; /// let mut pq = PriorityQueue::new(); /// assert_eq!(pq.push_decrease("Apples", 5), None); /// assert_eq!(pq.get_priority("Apples"), Some(&5)); /// assert_eq!(pq.push_decrease("Apples", 4), Some(5)); /// assert_eq!(pq.get_priority("Apples"), Some(&4)); /// // Already present with lower priority, so requested (higher) /// // priority is returned. /// assert_eq!(pq.push_decrease("Apples", 6), Some(6)); /// assert_eq!(pq.get_priority("Apples"), Some(&4)); /// ``` /// /// Computes in **O(log(N))** time. pub fn push_decrease(&mut self, item: I, priority: P) -> Option

{ if self.get_priority(&item).map_or(true, |p| priority < *p) { self.push(item, priority) } else { Some(priority) } } /// Change the priority of an item returning the old value of priority, /// or `None` if the item wasn't in the queue. /// /// The argument `item` is only used for lookup, and is not used to overwrite the item's data /// in the priority queue. /// /// # Example /// ``` /// # use priority_queue::PriorityQueue; /// let mut pq = PriorityQueue::new(); /// assert_eq!(pq.change_priority("Apples", 5), None); /// assert_eq!(pq.get_priority("Apples"), None); /// assert_eq!(pq.push("Apples", 6), None); /// assert_eq!(pq.get_priority("Apples"), Some(&6)); /// assert_eq!(pq.change_priority("Apples", 4), Some(6)); /// assert_eq!(pq.get_priority("Apples"), Some(&4)); /// ``` /// /// The item is found in **O(1)** thanks to the hash table. /// The operation is performed in **O(log(N))** time. pub fn change_priority(&mut self, item: &Q, new_priority: P) -> Option

where Q: ?Sized + Equivalent + Hash, { self.store .change_priority(item, new_priority) .map(|(r, pos)| { self.up_heapify(pos); r }) } /// Change the priority of an item using the provided function. /// /// Returns a boolean value where `true` means the item was in the queue and update was successful. /// /// The argument `item` is only used for lookup, and is not used to overwrite the item's data /// in the priority queue. /// /// The item is found in **O(1)** thanks to the hash table. /// The operation is performed in **O(log(N))** time (worst case). pub fn change_priority_by(&mut self, item: &Q, priority_setter: F) -> bool where Q: ?Sized + Equivalent + Hash, F: FnOnce(&mut P), { self.store .change_priority_by(item, priority_setter) .map(|pos| { self.up_heapify(pos); }) .is_some() } /// Get the priority of an item, or `None`, if the item is not in the queue pub fn get_priority(&self, item: &Q) -> Option<&P> where Q: ?Sized + Equivalent + Hash, { self.store.get_priority(item) } /// Check if the queue contains `item`. /// /// Returns `true` if `item` is in the queue, `false` if it is not. pub fn contains(&self, item: &Q) -> bool where Q: ?Sized + Equivalent + Hash, { self.store.contains(item) } /// Get the couple `(item, priority)` of an arbitrary element, as reference /// or `None` if the item is not in the queue. pub fn get(&self, item: &Q) -> Option<(&I, &P)> where Q: ?Sized + Equivalent + Hash, { self.store.get(item) } /// Get the couple `(item, priority)` of an arbitrary element, or `None` /// if the item was not in the queue. /// /// The item is a mutable reference, but it's a logic error to modify it /// in a way that change the result of `Hash` or `Eq`. /// /// The priority cannot be modified with a call to this function. /// To modify the priority use [`push`](PriorityQueue::push), /// [`change_priority`](PriorityQueue::change_priority) or /// [`change_priority_by`](PriorityQueue::change_priority_by). pub fn get_mut(&mut self, item: &Q) -> Option<(&mut I, &P)> where Q: ?Sized + Equivalent + Hash, { self.store.get_mut(item) } /// Returns the couple `(item, priority)` with the greatest /// priority in the queue, or `None` if it is empty. /// /// The item is a mutable reference, but it's a logic error to modify it /// in a way that change the result of `Hash` or `Eq`. /// /// The priority cannot be modified with a call to this function. /// To modify the priority use[`push`](PriorityQueue::push), /// [`change_priority`](PriorityQueue::change_priority) or /// [`change_priority_by`](PriorityQueue::change_priority_by). /// /// Computes in **O(1)** time pub fn peek_mut(&mut self) -> Option<(&mut I, &P)> { use indexmap::map::MutableKeys; if self.store.size == 0 { return None; } self.store .map .get_index_mut2(unsafe { self.store.heap.get_unchecked(0) }.0) .map(|(k, v)| (k, &*v)) } /// Remove an arbitrary element from the priority queue. /// /// Returns the `(item, priority)` couple or `None` if the item /// is not found in the queue. /// /// The operation is performed in **O(log(N))** time (worst case). pub fn remove(&mut self, item: &Q) -> Option<(I, P)> where Q: ?Sized + Equivalent + Hash, { self.store.remove(item).map(|(item, priority, pos)| { if pos.0 < self.len() { self.up_heapify(pos); } (item, priority) }) } /// Move all items of the `other` queue to `self` /// ignoring the items Eq to elements already in `self` /// At the end, `other` will be empty. /// /// **Note** that at the end, the priority of the duplicated elements /// inside `self` may be the one of the elements in `other`, /// if `other` is longer than `self` pub fn append(&mut self, other: &mut Self) { self.store.append(&mut other.store); self.heap_build(); } } impl PriorityQueue where P: Ord, { /**************************************************************************/ /* internal functions */ /// Internal function that restores the functional property of the sub-heap rooted in `i` /// /// Computes in **O(log(N))** time fn heapify(&mut self, mut i: Position) { if self.len() <= 1 { return; } let (mut l, mut r) = (left(i), right(i)); let mut largest = i; let mut largestp = unsafe { self.store.get_priority_from_position(i) }; if l.0 < self.len() { let childp = unsafe { self.store.get_priority_from_position(l) }; if childp > largestp { largest = l; largestp = childp; } if r.0 < self.len() && unsafe { self.store.get_priority_from_position(r) } > largestp { largest = r; } } while largest != i { self.store.swap(i, largest); i = largest; largestp = unsafe { self.store.get_priority_from_position(i) }; l = left(i); if l.0 < self.len() { let childp = unsafe { self.store.get_priority_from_position(l) }; if childp > largestp { largest = l; largestp = childp; } r = right(i); if r.0 < self.len() && unsafe { self.store.get_priority_from_position(r) } > largestp { largest = r; } } } } /// from the leaf go up to root or until an element with priority greater /// than the new element is found fn bubble_up(&mut self, mut position: Position, map_position: Index) -> Position { let priority = self.store.map.get_index(map_position.0).unwrap().1; let mut parent_position = Position(0); while if position.0 > 0 { parent_position = parent(position); (unsafe { self.store.get_priority_from_position(parent_position) }) < priority } else { false } { unsafe { let parent_index = *self.store.heap.get_unchecked(parent_position.0); *self.store.heap.get_unchecked_mut(position.0) = parent_index; *self.store.qp.get_unchecked_mut(parent_index.0) = position; } position = parent_position; } unsafe { *self.store.heap.get_unchecked_mut(position.0) = map_position; *self.store.qp.get_unchecked_mut(map_position.0) = position; } position } /// Internal function that moves a leaf in position `i` to its correct place in the heap /// and restores the functional property /// /// Computes in **O(log(N))** fn up_heapify(&mut self, i: Position) { let tmp = unsafe { *self.store.heap.get_unchecked(i.0) }; let pos = self.bubble_up(i, tmp); self.heapify(pos) } /// Internal function that transform the `heap` /// vector in a heap with its properties /// /// Computes in **O(N)** pub(crate) fn heap_build(&mut self) { if self.is_empty() { return; } for i in (0..=parent(Position(self.len())).0).rev() { self.heapify(Position(i)); } } } //FIXME: fails when the vector contains repeated items // FIXED: repeated items ignored impl From> for PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn from(vec: Vec<(I, P)>) -> Self { let store = Store::from(vec); let mut pq = PriorityQueue { store }; pq.heap_build(); pq } } use crate::DoublePriorityQueue; impl From> for PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { fn from(pq: DoublePriorityQueue) -> Self { let store = pq.store; let mut this = Self { store }; this.heap_build(); this } } //FIXME: fails when the iterator contains repeated items // FIXED: the item inside the pq is updated // so there are two functions with different behaviours. impl FromIterator<(I, P)> for PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn from_iter(iter: IT) -> Self where IT: IntoIterator, { let store = Store::from_iter(iter); let mut pq = PriorityQueue { store }; pq.heap_build(); pq } } impl IntoIterator for PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { type Item = (I, P); type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { self.store.into_iter() } } impl<'a, I, P, H> IntoIterator for &'a PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { type Item = (&'a I, &'a P); type IntoIter = Iter<'a, I, P>; fn into_iter(self) -> Iter<'a, I, P> { self.store.iter() } } impl<'a, I, P, H> IntoIterator for &'a mut PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { type Item = (&'a mut I, &'a mut P); type IntoIter = IterMut<'a, I, P, H>; fn into_iter(self) -> IterMut<'a, I, P, H> { IterMut::new(self) } } impl Extend<(I, P)> for PriorityQueue where I: Hash + Eq, P: Ord, H: BuildHasher, { fn extend>(&mut self, iter: T) { let iter = iter.into_iter(); let (min, max) = iter.size_hint(); let rebuild = if let Some(max) = max { self.reserve(max); better_to_rebuild(self.len(), max) } else if min != 0 { self.reserve(min); better_to_rebuild(self.len(), min) } else { false }; if rebuild { self.store.extend(iter); self.heap_build(); } else { for (item, priority) in iter { self.push(item, priority); } } } } use std::cmp::PartialEq; impl PartialEq> for PriorityQueue where I: Hash + Eq, P1: Ord, P1: PartialEq, Option: PartialEq>, P2: Ord, H1: BuildHasher, H2: BuildHasher, { fn eq(&self, other: &PriorityQueue) -> bool { self.store == other.store } } #[cfg(feature = "serde")] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] mod serde { use std::cmp::{Eq, Ord}; use std::hash::{BuildHasher, Hash}; use serde::de::{Deserialize, Deserializer}; use serde::ser::{Serialize, Serializer}; use super::PriorityQueue; use crate::store::Store; impl Serialize for PriorityQueue where I: Hash + Eq + Serialize, P: Ord + Serialize, H: BuildHasher, { fn serialize(&self, serializer: S) -> Result where S: Serializer, { self.store.serialize(serializer) } } impl<'de, I, P, H> Deserialize<'de> for PriorityQueue where I: Hash + Eq + Deserialize<'de>, P: Ord + Deserialize<'de>, H: BuildHasher + Default, { fn deserialize(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { Store::deserialize(deserializer).map(|store| { let mut pq = PriorityQueue { store }; pq.heap_build(); pq }) } } } priority-queue-2.6.0/src/store.rs000064400000000000000000000603731046102023000151360ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ #[cfg(not(feature = "std"))] use std::vec::Vec; // an improvement in terms of complexity would be to use a bare HashMap // as vec instead of the IndexMap use crate::core_iterators::*; use crate::TryReserveError; use equivalent::Equivalent; use std::cmp::{Eq, Ord}; #[cfg(feature = "std")] use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hash}; use std::iter::{FromIterator, IntoIterator, Iterator}; use std::mem::swap; use indexmap::map::{IndexMap, MutableKeys}; /// The Index of the element in the Map #[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] pub(crate) struct Index(pub usize); /// The Position of the element in the Heap #[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] pub(crate) struct Position(pub usize); /// Compute the index of the left child of an item from its index #[inline(always)] pub(crate) const fn left(i: Position) -> Position { Position((i.0 * 2) + 1) } /// Compute the index of the right child of an item from its index #[inline(always)] pub(crate) const fn right(i: Position) -> Position { Position((i.0 * 2) + 2) } /// Compute the index of the parent element in the heap from its index #[inline(always)] pub(crate) const fn parent(i: Position) -> Position { Position((i.0 - 1) / 2) } // Compute the level of a node from its index #[inline(always)] pub(crate) const fn level(i: Position) -> usize { log2_fast(i.0 + 1) } #[inline(always)] pub(crate) const fn log2_fast(x: usize) -> usize { (usize::BITS - x.leading_zeros() - 1) as usize } /// Internal storage of PriorityQueue and DoublePriorityQueue #[derive(Clone)] #[cfg(feature = "std")] pub(crate) struct Store { pub map: IndexMap, // Stores the items and assign them an index pub heap: Vec, // Implements the heap of indexes pub qp: Vec, // Performs the translation from the index // of the map to the index of the heap pub size: usize, // The size of the heap } #[derive(Clone)] #[cfg(not(feature = "std"))] pub(crate) struct Store { pub map: IndexMap, // Stores the items and assign them an index pub heap: Vec, // Implements the heap of indexes pub qp: Vec, // Performs the translation from the index // of the map to the index of the heap pub size: usize, // The size of the heap } impl Default for Store where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn default() -> Self { Self::with_default_hasher() } } impl Store where P: Ord, I: Hash + Eq, H: BuildHasher + Default, { /// Creates an empty `Store` with the default hasher pub fn with_default_hasher() -> Self { Self::with_capacity_and_default_hasher(0) } /// Creates an empty `Store` with the specified capacity and default hasher pub fn with_capacity_and_default_hasher(capacity: usize) -> Self { Self::with_capacity_and_hasher(capacity, H::default()) } } impl Store where P: Ord, I: Hash + Eq, H: BuildHasher, { /// Creates an empty `Store` with the specified hasher pub const fn with_hasher(hash_builder: H) -> Self { Self { map: IndexMap::with_hasher(hash_builder), heap: Vec::new(), qp: Vec::new(), size: 0, } } /// Creates an empty `Store` with the specified capacity and hasher /// /// The internal collections will be able to hold at least `capacity` /// elements without reallocating. /// If `capacity` is 0, there will be no allocation. pub fn with_capacity_and_hasher(capacity: usize, hash_builder: H) -> Self { Self { map: IndexMap::with_capacity_and_hasher(capacity, hash_builder), heap: Vec::with_capacity(capacity), qp: Vec::with_capacity(capacity), size: 0, } } } impl Store { /// Returns an iterator in arbitrary order over the /// (item, priority) elements in the queue pub fn iter(&self) -> Iter { Iter { iter: self.map.iter(), } } /// Shrinks the capacity of the internal data structures /// that support this operation as much as possible. #[inline(always)] pub fn shrink_to_fit(&mut self) { self.heap.shrink_to_fit(); self.qp.shrink_to_fit(); self.map.shrink_to_fit(); } /// Reserves capacity for at least `additional` more elements to be inserted /// in the given `PriorityQueue`. The collection may reserve more space to avoid /// frequent reallocations. After calling `reserve`, capacity will be /// greater than or equal to `self.len() + additional`. Does nothing if /// capacity is already sufficient. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. /// /// Computes in O(n) time. pub fn reserve(&mut self, additional: usize) { self.map.reserve(additional); self.heap.reserve(additional); self.qp.reserve(additional); } /// Reserve capacity for `additional` more elements, without over-allocating. /// /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid /// frequent re-allocations. However, the underlying data structures may still have internal /// capacity requirements, and the allocator itself may give more space than requested, so this /// cannot be relied upon to be precisely minimal. /// /// Computes in **O(n)** time. pub fn reserve_exact(&mut self, additional: usize) { self.map.reserve_exact(additional); self.heap.reserve_exact(additional); self.qp.reserve_exact(additional); } /// Try to reserve capacity for at least `additional` more elements. /// /// Computes in O(n) time. pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { self.map.try_reserve(additional)?; self.heap.try_reserve(additional)?; self.qp.try_reserve(additional)?; Ok(()) } /// Try to reserve capacity for `additional` more elements, without over-allocating. /// /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid /// frequent re-allocations. However, the underlying data structures may still have internal /// capacity requirements, and the allocator itself may give more space than requested, so this /// cannot be relied upon to be precisely minimal. /// /// Computes in **O(n)** time. pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { self.map.try_reserve_exact(additional)?; self.heap.try_reserve_exact(additional)?; self.qp.try_reserve_exact(additional)?; Ok(()) } /// Clears the store, returning an iterator over the removed elements in arbitrary order. /// If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order. pub fn drain(&mut self) -> Drain<'_, I, P> { self.heap.clear(); self.qp.clear(); self.size = 0; Drain { iter: self.map.drain(..), } } /// Returns the number of elements the internal map can hold without /// reallocating. /// /// This number is a lower bound; the map might be able to hold more, /// but is guaranteed to be able to hold at least this many. #[inline(always)] pub fn capacity(&self) -> usize { self.map.capacity() } /// Returns the number of elements in the priority queue. #[inline(always)] pub fn len(&self) -> usize { self.size } /// Returns true if the priority queue contains no elements. #[inline(always)] pub fn is_empty(&self) -> bool { self.size == 0 } /// Returns the items not ordered pub fn into_vec(self) -> Vec { self.map.into_iter().map(|(i, _)| i).collect() } /// Drops all items from the priority queue pub fn clear(&mut self) { self.heap.clear(); self.qp.clear(); self.map.clear(); self.size = 0; } /// Swap two elements keeping a consistent state. /// /// Computes in **O(1)** time #[inline(always)] pub fn swap(&mut self, a: Position, b: Position) { self.qp.swap( unsafe { self.heap.get_unchecked(a.0) }.0, unsafe { self.heap.get_unchecked(b.0) }.0, ); self.heap.swap(a.0, b.0); } /// Remove and return the element at index `idx` /// and swap it with the last element keeping a consistent /// state. /// /// Computes in **O(1)** time (average) pub fn swap_remove_index(&mut self, idx: Index) -> Option<(I, P)> { // swap_remove the position from the qp let position = self.qp.swap_remove(idx.0); self.size -= 1; if idx.0 < self.size { // SAFETY: head validity checked on the previous line. // All positions point to valid heap items because we already // updated the qp. unsafe { *self.heap.get_unchecked_mut(self.qp.get_unchecked(idx.0).0) = idx; } } self.heap.swap_remove(position.0); // Fix indexes and swap remove the old heap head from the qp if position.0 < self.size { // SAFETY: position validity checked on the previous line. // Indexes still point to valid qp items because we didn't // remove anything from qp yet unsafe { *self .qp .get_unchecked_mut(self.heap.get_unchecked(position.0).0) = position; } } // swap remove from the map and return to the client self.map.swap_remove_index(idx.0) } /// Remove and return the element in position `position` /// and swap it with the last element keeping a consistent /// state. /// /// Computes in **O(1)** time (average) pub fn swap_remove(&mut self, position: Position) -> Option<(I, P)> { // swap_remove the head let head: Index = self.heap.swap_remove(position.0); self.size -= 1; // Fix indexes and swap remove the old heap head from the qp if position.0 < self.size { // SAFETY: position validity checked on the previous line. // Indexes still point to valid qp items because we didn't // remove anything from qp yet unsafe { *self .qp .get_unchecked_mut(self.heap.get_unchecked(position.0).0) = position; } } self.qp.swap_remove(head.0); if head.0 < self.size { // SAFETY: head validity checked on the previous line. // All positions point to valid heap items because we already // updated the qp. unsafe { *self.heap.get_unchecked_mut(self.qp.get_unchecked(head.0).0) = head; } } // swap remove from the map and return to the client self.map.swap_remove_index(head.0) } #[inline(always)] pub unsafe fn get_priority_from_position(&self, position: Position) -> &P { unsafe { self.map .get_index(self.heap.get_unchecked(position.0).0) .unwrap() .1 } } } impl Store where P: Ord, I: Hash + Eq, H: BuildHasher, { pub fn retain(&mut self, mut predicate: F) where F: FnMut(&I, &P) -> bool, { self.retain_mut(|i, p| predicate(&*i, &*p)); } pub fn retain_mut(&mut self, predicate: F) where F: FnMut(&mut I, &mut P) -> bool, { self.map.retain2(predicate); if self.map.len() != self.size { self.size = self.map.len(); self.heap = (0..self.size).map(Index).collect(); self.qp = (0..self.size).map(Position).collect(); } } /// If the predicate returns true for the element in position `position`, /// remove it and swap it with the last element keeping a consistent /// state. /// /// Computes in **O(1)** time (average) pub fn swap_remove_if(&mut self, position: Position, f: F) -> Option<(I, P)> where F: FnOnce(&mut I, &mut P) -> bool, { let head: Index = unsafe { *self.heap.get_unchecked(position.0) }; let (i, p) = self.map.get_index_mut2(head.0).unwrap(); if f(i, p) { self.swap_remove(position) } else { None } } /// Change the priority of an Item returning the old value of priority, /// or `None` if the item wasn't in the queue. /// /// The argument `item` is only used for lookup, and is not used to overwrite the item's data /// in the priority queue. /// /// The item is found in **O(1)** thanks to the hash table. /// The operation is performed in **O(log(N))** time. pub fn change_priority(&mut self, item: &Q, mut new_priority: P) -> Option<(P, Position)> where Q: ?Sized + Equivalent + Hash, { let Store { map, qp, .. } = self; map.get_full_mut(item).map(|(index, _, p)| { swap(p, &mut new_priority); let pos = unsafe { *qp.get_unchecked(index) }; (new_priority, pos) }) } /// Change the priority of an Item using the provided function. /// The item is found in **O(1)** thanks to the hash table. /// The operation is performed in **O(log(N))** time (worst case). pub fn change_priority_by(&mut self, item: &Q, priority_setter: F) -> Option where Q: ?Sized + Equivalent + Hash, F: FnOnce(&mut P), { let Store { map, qp, .. } = self; map.get_full_mut(item).map(|(index, _, p)| { priority_setter(p); unsafe { *qp.get_unchecked(index) } }) } /// Get the priority of an item, or `None`, if the item is not in the queue pub fn get_priority(&self, item: &Q) -> Option<&P> where Q: ?Sized + Equivalent + Hash, { self.map.get(item) } /// Check if the store contains `item`. /// /// Returns `true` if `item` is in the store, `false` if it is not. pub fn contains(&self, item: &Q) -> bool where Q: ?Sized + Equivalent + Hash, { self.map.contains_key(item) } /// Get the couple (item, priority) of an arbitrary element, as reference /// or `None` if the item is not in the queue. pub fn get(&self, item: &Q) -> Option<(&I, &P)> where Q: ?Sized + Equivalent + Hash, { self.map.get_full(item).map(|(_, k, v)| (k, v)) } /// Get the couple (item, priority) of an arbitrary element, or `None` /// if the item was not in the queue. /// /// The item is a mutable reference, but it's a logic error to modify it /// in a way that change the result of `Hash` or `Eq`. /// /// The priority cannot be modified with a call to this function. /// To modify the priority use `push`, `change_priority` or /// `change_priority_by`. pub fn get_mut(&mut self, item: &Q) -> Option<(&mut I, &P)> where Q: ?Sized + Equivalent + Hash, { self.map.get_full_mut2(item).map(|(_, k, v)| (k, &*v)) } pub fn remove(&mut self, item: &Q) -> Option<(I, P, Position)> where Q: ?Sized + Equivalent + Hash, { self.map.swap_remove_full(item).map(|(i, item, priority)| { let i = Index(i); self.size -= 1; let pos: Position = self.qp.swap_remove(i.0); self.heap.swap_remove(pos.0); if i.0 < self.size { unsafe { let qpi = self.qp.get_unchecked_mut(i.0); if qpi.0 == self.size { *qpi = pos; } else { *self.heap.get_unchecked_mut(qpi.0) = i; } } } if pos.0 < self.size { unsafe { let heap_pos = self.heap.get_unchecked_mut(pos.0); if heap_pos.0 == self.size { *heap_pos = i; } else { *self.qp.get_unchecked_mut(heap_pos.0) = pos; } } } (item, priority, pos) }) } /// Move all items of the `other` queue to `self` /// ignoring the items Eq to elements already in `self` /// At the end, `other` will be empty. /// /// **Note** that at the end, the priority of the duplicated elements /// inside self may be the one of the elements in other, /// if other is longer than self pub fn append(&mut self, other: &mut Self) { if other.size > self.size { std::mem::swap(self, other); } if other.size == 0 { return; } // what should we do for duplicated keys? // ignore for (k, v) in other.drain() { if !self.map.contains_key(&k) { let i = self.size; self.map.insert(k, v); self.heap.push(Index(i)); self.qp.push(Position(i)); self.size += 1; } } } } impl IntoIterator for Store { type Item = (I, P); type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { IntoIter { iter: self.map.into_iter(), } } } impl<'a, I, P, H> IntoIterator for &'a Store { type Item = (&'a I, &'a P); type IntoIter = Iter<'a, I, P>; fn into_iter(self) -> Iter<'a, I, P> { Iter { iter: self.map.iter(), } } } use std::cmp::PartialEq; impl PartialEq> for Store where I: Hash + Eq, P1: Ord, P1: PartialEq, Option: PartialEq>, P2: Ord, H1: BuildHasher, H2: BuildHasher, { fn eq(&self, other: &Store) -> bool { self.map == other.map } } impl From> for Store where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn from(vec: Vec<(I, P)>) -> Self { let mut store = Self::with_capacity_and_hasher(vec.len(), <_>::default()); let mut i = 0; for (item, priority) in vec { if !store.map.contains_key(&item) { store.map.insert(item, priority); store.qp.push(Position(i)); store.heap.push(Index(i)); i += 1; } } store.size = i; store } } impl FromIterator<(I, P)> for Store where I: Hash + Eq, P: Ord, H: BuildHasher + Default, { fn from_iter(iter: IT) -> Self where IT: IntoIterator, { let iter = iter.into_iter(); let (min, max) = iter.size_hint(); let mut store = if let Some(max) = max { Self::with_capacity_and_hasher(max, <_>::default()) } else if min > 0 { Self::with_capacity_and_hasher(min, <_>::default()) } else { Self::with_hasher(<_>::default()) }; for (item, priority) in iter { if store.map.contains_key(&item) { let (_, old_item, old_priority) = store.map.get_full_mut2(&item).unwrap(); *old_item = item; *old_priority = priority; } else { store.map.insert(item, priority); store.qp.push(Position(store.size)); store.heap.push(Index(store.size)); store.size += 1; } } store } } impl Extend<(I, P)> for Store where I: Hash + Eq, P: Ord, H: BuildHasher, { fn extend>(&mut self, iter: T) { for (item, priority) in iter { if self.map.contains_key(&item) { let (_, old_item, old_priority) = self.map.get_full_mut2(&item).unwrap(); *old_item = item; *old_priority = priority; } else { self.map.insert(item, priority); self.qp.push(Position(self.size)); self.heap.push(Index(self.size)); self.size += 1; } } } } use std::fmt; impl fmt::Debug for Store where I: fmt::Debug, P: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map() .entries( self.heap .iter() .map(|&i| (i, self.map.get_index(i.0).unwrap())), ) .finish() } } #[cfg(feature = "serde")] mod serde { use crate::store::{Index, Position, Store}; use std::cmp::{Eq, Ord}; use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hash}; use std::marker::PhantomData; use serde::ser::{Serialize, SerializeSeq, Serializer}; impl Serialize for Store where I: Serialize, P: Serialize, { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut map_serializer = serializer.serialize_seq(Some(self.size))?; for (k, v) in &self.map { map_serializer.serialize_element(&(k, v))?; } map_serializer.end() } } use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor}; impl<'de, I, P, H> Deserialize<'de> for Store where I: Hash + Eq + Deserialize<'de>, P: Ord + Deserialize<'de>, H: BuildHasher + Default, { fn deserialize(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(StoreVisitor { marker: PhantomData, }) } } struct StoreVisitor where I: Hash + Eq, P: Ord, { marker: PhantomData>, } impl<'de, I, P, H> Visitor<'de> for StoreVisitor where I: Hash + Eq + Deserialize<'de>, P: Ord + Deserialize<'de>, H: BuildHasher + Default, { type Value = Store; fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(formatter, "A priority queue") } fn visit_unit(self) -> Result { Ok(Store::with_default_hasher()) } fn visit_seq(self, mut seq: A) -> Result where A: SeqAccess<'de>, { let mut store: Store = if let Some(size) = seq.size_hint() { Store::with_capacity_and_default_hasher(size) } else { Store::with_default_hasher() }; while let Some((item, priority)) = seq.next_element()? { store.map.insert(item, priority); store.qp.push(Position(store.size)); store.heap.push(Index(store.size)); store.size += 1; } Ok(store) } } } priority-queue-2.6.0/tests/double_priority_queue.rs000064400000000000000000001277471046102023000210050ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi and contributors * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ #[cfg(test)] mod doublepq_tests { pub use priority_queue::DoublePriorityQueue; #[test] fn init() { let pq: DoublePriorityQueue = DoublePriorityQueue::new(); println!("{:?}", pq); } #[test] fn push_len() { let mut pq = DoublePriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); println!("{:?}", pq); assert_eq!(pq.len(), 2); } #[test] fn push_pop() { let mut pq = DoublePriorityQueue::new(); assert_eq!(pq.peek_max(), None); assert_eq!(pq.peek_min(), None); assert_eq!(pq.pop_min(), None); assert_eq!(pq.pop_max(), None); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 4); pq.push("h", 3); println!("{:?}", pq); assert_eq!(pq.pop_max(), Some(("f", 7))); println!("{:?}", pq); assert_eq!(pq.peek_max(), Some((&"g", &4))); assert_eq!(pq.peek_min(), Some((&"a", &1))); assert_eq!(pq.pop_max(), Some(("g", 4))); assert_eq!(pq.len(), 3); } #[test] fn contains() { let mut pq = DoublePriorityQueue::new(); assert!(!pq.contains("a")); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 5); pq.push("h", 3); assert!(pq.contains("f")); pq.pop_max(); assert!(!pq.contains("f")); } #[test] fn pop_if() { let mut pq = DoublePriorityQueue::new(); assert_eq!(pq.pop_min_if(|_, _| true), None); assert_eq!(pq.pop_max_if(|_, _| true), None); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 4); pq.push("h", 3); println!("{:?}", pq); assert_eq!(pq.pop_min_if(|_, _| false), None); assert_eq!(pq.pop_max_if(|_, _| false), None); println!("{:?}", pq); assert_eq!( pq.pop_min_if(|_, p| { *p = 10; true }), Some(("a", 10)) ); assert_eq!( pq.pop_max_if(|_, p| { *p = 10; true }), Some(("f", 10)) ); println!("{:?}", pq); assert_eq!( pq.pop_min_if(|_, p| { *p = 10; false }), None ); println!("{:?}", pq); assert_eq!(pq.peek_min(), Some((&"h", &3))); assert_eq!(pq.peek_max(), Some((&"b", &10))); println!("{:?}", pq); assert_eq!( pq.pop_max_if(|_, p| { *p = 2; false }), None ); assert_eq!(pq.peek_min(), Some((&"b", &2))); assert_eq!(pq.peek_max(), Some((&"g", &4))); println!("{:?}", pq); } #[test] fn peek_mut() { use std::hash::{Hash, Hasher}; #[derive(Debug)] struct Person { id: u32, name: String, phone: u64, } impl Hash for Person { fn hash(&self, state: &mut H) { self.id.hash(state); self.phone.hash(state); } } impl PartialEq for Person { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.phone == other.phone } } impl Eq for Person {} let mut pq = DoublePriorityQueue::new(); assert_eq!(pq.peek_max_mut(), None); assert_eq!(pq.peek_min_mut(), None); pq.push( Person { id: 1, name: "a".to_string(), phone: 39281048279, }, 1, ); pq.push( Person { id: 2, name: "b".to_string(), phone: 23912750234, }, 2, ); pq.push( Person { id: 3, name: "c".to_string(), phone: 1298275802947, }, 3, ); pq.push( Person { id: 4, name: "d".to_string(), phone: 65723012057, }, 4, ); pq.push( Person { id: 5, name: "e".to_string(), phone: 7237569870239, }, 5, ); pq.push( Person { id: 6, name: "f".to_string(), phone: 35756872497, }, 6, ); println!("{:?}", pq); let (item_max, _) = pq.peek_max_mut().unwrap(); item_max.name.push('g'); let (item_max, priority_max) = pq.pop_max().unwrap(); assert_eq!( item_max, Person { id: 6, // name is not used for checking equality name: "f".to_string(), phone: 35756872497 } ); assert_eq!(6, priority_max); assert_eq!("fg", item_max.name); let (item_min, _) = pq.peek_min_mut().unwrap(); item_min.name.push('b'); let (item_min, priority_min) = pq.pop_min().unwrap(); assert_eq!( item_min, Person { id: 1, // name is not used for checking equality name: "f".to_string(), phone: 39281048279 } ); assert_eq!(1, priority_min); assert_eq!("ab", item_min.name); println!("{:?}", pq); assert_eq!(pq.len(), 4); } #[test] fn get_mut() { use std::hash::{Hash, Hasher}; #[derive(Debug)] struct Person { id: u32, name: String, phone: u64, } impl Hash for Person { fn hash(&self, state: &mut H) { self.id.hash(state); self.phone.hash(state); } } impl PartialEq for Person { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.phone == other.phone } } impl Eq for Person {} let mut pq = DoublePriorityQueue::new(); assert_eq!( pq.get_mut(&Person { id: 1, name: "a".to_string(), phone: 39281048279, }), None ); pq.push( Person { id: 1, name: "a".to_string(), phone: 39281048279, }, 1, ); pq.push( Person { id: 2, name: "b".to_string(), phone: 23912750234, }, 2, ); pq.push( Person { id: 3, name: "c".to_string(), phone: 1298275802947, }, 3, ); pq.push( Person { id: 4, name: "d".to_string(), phone: 65723012057, }, 4, ); pq.push( Person { id: 5, name: "e".to_string(), phone: 7237569870239, }, 5, ); pq.push( Person { id: 6, name: "f".to_string(), phone: 35756872497, }, 6, ); println!("{:?}", pq); let (item, _) = pq .get_mut(&Person { id: 1, name: "a".to_string(), phone: 39281048279, }) .unwrap(); item.name.push('g'); let (item_min, priority_min) = pq.pop_min().unwrap(); assert_eq!( item_min, Person { id: 1, // name is not used for checking equality name: "f".to_string(), phone: 39281048279 } ); assert_eq!(1, priority_min); assert_eq!("ag", item_min.name); println!("{:?}", pq); assert_eq!(pq.len(), 5); } #[test] fn push_update() { let mut pq = DoublePriorityQueue::new(); pq.push("a", 9); pq.push("b", 8); pq.push("c", 7); pq.push("d", 6); pq.push("e", 5); pq.push("f", 4); pq.push("g", 10); pq.push("k", 11); assert_eq!(pq.push("d", 20), Some(6)); assert_eq!(pq.peek_max(), Some((&"d", &20))); assert_eq!(pq.pop_max(), Some(("d", 20))); } #[test] fn push_increase() { let mut pq = DoublePriorityQueue::new(); pq.push("Processor", 1); pq.push("Mainboard", 2); pq.push("RAM", 5); pq.push("GPU", 4); pq.push("Disk", 3); let processor_priority = |pq: &DoublePriorityQueue<&str, i32>| { *pq.iter() .find_map(|(i, p)| if *i == "Processor" { Some(p) } else { None }) .unwrap() }; pq.push_increase("SSD", 5); assert_eq!(pq.get("SSD"), Some((&"SSD", &5))); pq.push_increase("Processor", 3); assert_eq!(processor_priority(&pq), 3); pq.push_increase("Processor", 1); assert_eq!(processor_priority(&pq), 3); pq.push_increase("Processor", 6); assert_eq!(pq.peek_max(), Some((&"Processor", &6))); } #[test] fn push_decrease() { let mut pq = DoublePriorityQueue::new(); pq.push("Processor", 1); pq.push("Mainboard", 2); pq.push("RAM", 5); pq.push("GPU", 4); pq.push("Disk", 3); let processor_priority = |pq: &DoublePriorityQueue<&str, i32>| { *pq.iter() .find_map(|(i, p)| if *i == "Processor" { Some(p) } else { None }) .unwrap() }; pq.push_decrease("SSD", 5); assert_eq!(pq.get("SSD"), Some((&"SSD", &5))); pq.push_decrease("Processor", 3); assert_eq!(processor_priority(&pq), 1); pq.push_decrease("Processor", 0); assert_eq!(processor_priority(&pq), 0); assert_eq!(pq.peek_min(), Some((&"Processor", &0))); } #[test] fn change_priority1() { let mut pq = DoublePriorityQueue::new(); assert_eq!(pq.push("Processor", 1), None); assert_eq!(pq.push("Mainboard", 2), None); assert_eq!(pq.push("RAM", 5), None); assert_eq!(pq.push("GPU", 4), None); assert_eq!(pq.push("Disk", 3), None); assert_eq!(pq.change_priority("SSD", 12), None); assert_eq!(pq.change_priority("Processor", 10), Some(1)); assert_eq!(pq.peek_max(), Some((&"Processor", &10))); assert_eq!(pq.change_priority("RAM", 11), Some(5)); assert_eq!(pq.peek_max(), Some((&"RAM", &11))); } #[test] fn change_priority_does_not_change_contents() { use std::hash::{Hash, Hasher}; struct MyFn { name: &'static str, func: fn(&mut i32), } impl Default for MyFn { fn default() -> Self { Self { name: "", func: |_| {}, } } } impl PartialEq for MyFn { fn eq(&self, other: &Self) -> bool { self.name == other.name } } impl Eq for MyFn {} impl Hash for MyFn { fn hash(&self, state: &mut H) { self.name.hash(state); } } impl std::fmt::Debug for MyFn { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write![f, "{:?}", self.name] } } let mut pq = DoublePriorityQueue::new(); pq.push( MyFn { name: "increment-one", func: |x| *x += 1, }, 2, ); pq.push( MyFn { name: "increment-two", func: |x| *x += 2, }, 1, ); let mut cnt = 0; assert_eq![ pq.peek_max(), Some(( &MyFn { name: "increment-one", func: |_| {} }, &2 )) ]; pq.change_priority( &MyFn { name: "increment-one", func: |_| {}, }, 0, ); assert_eq![ pq.peek_max(), Some(( &MyFn { name: "increment-two", func: |_| {} }, &1 )) ]; assert_eq![cnt, 0]; (pq.pop_max().unwrap().0.func)(&mut cnt); assert_eq![cnt, 2]; (pq.pop_max().unwrap().0.func)(&mut cnt); assert_eq![cnt, 3]; } #[test] fn reversed_order() { use std::cmp::Reverse; let mut pq: DoublePriorityQueue<_, Reverse> = DoublePriorityQueue::new(); pq.push("a", Reverse(1)); pq.push("b", Reverse(2)); assert_eq![pq.pop_max(), Some(("a", Reverse(1)))]; } #[test] fn from_vec() { let v = vec![("a", 1), ("b", 2), ("f", 7)]; let mut pq: DoublePriorityQueue<_, _> = DoublePriorityQueue::from(v); assert_eq!(pq.pop_max(), Some(("f", 7))); assert_eq!(pq.len(), 2); } #[test] fn clear() { let v = vec![("a", 1), ("b", 2), ("f", 7)]; let mut pq: DoublePriorityQueue<_, _> = DoublePriorityQueue::from(v); assert_eq!(pq.len(), 3); pq.clear(); assert_eq!(pq.len(), 0); } #[test] fn from_vec_with_repeated() { let v = vec![("a", 1), ("b", 2), ("f", 7), ("a", 2)]; let mut pq: DoublePriorityQueue<_, _> = v.into(); assert_eq!(pq.pop_max(), Some(("f", 7))); assert_eq!(pq.len(), 2); } #[test] fn from_iter() { use std::iter::FromIterator; let v = vec![("a", 1), ("b", 2), ("f", 7)]; let mut pq: DoublePriorityQueue<_, _> = DoublePriorityQueue::from_iter(v); assert_eq!(pq.pop_max(), Some(("f", 7))); assert_eq!(pq.len(), 2); } #[test] fn heap_sort() { type Pq = DoublePriorityQueue; let v = vec![("a", 2), ("b", 7), ("f", 1)]; let sorted = (Pq::from(v)).into_descending_sorted_vec(); assert_eq!(sorted.as_slice(), &["b", "a", "f"]); } #[test] fn heap_sort_asc() { type Pq = DoublePriorityQueue; let v = vec![("a", 2), ("b", 7), ("f", 1)]; let sorted = (Pq::from(v)).into_ascending_sorted_vec(); assert_eq!(sorted.as_slice(), &["f", "a", "b"]); } #[test] fn change_priority_by() { use std::iter::FromIterator; let v = vec![("a", 1), ("b", 2), ("f", 7), ("g", 6), ("h", 5)]; let mut pq: DoublePriorityQueue<_, _> = DoublePriorityQueue::from_iter(v); assert!(!pq.change_priority_by("z", |z| *z += 8)); assert!(pq.change_priority_by("b", |b| *b += 8)); assert_eq!( pq.into_descending_sorted_vec().as_slice(), &["b", "f", "g", "h", "a"] ); } #[test] fn remove_empty() { let mut pq: DoublePriorityQueue<&str, i32> = DoublePriorityQueue::new(); assert_eq!(pq.remove(&"b"), None); assert_eq!(pq.len(), 0); } #[test] fn remove_one() { let mut pq = DoublePriorityQueue::new(); assert_eq!(pq.push("b", 21), None); assert_eq!(Some(("b", 21)), pq.remove(&"b")); assert_eq!(pq.len(), 0); } #[test] fn remove() { use std::iter::FromIterator; type Pq = DoublePriorityQueue; let v = vec![("a", 1), ("b", 2), ("f", 7), ("g", 6), ("h", 5)]; let mut pq = Pq::from_iter(v); pq.remove(&"b").unwrap(); assert!(pq.remove(&"b").is_none()); pq.push("b", 2); pq.remove(&"b"); assert_eq!( ["f", "g", "h", "a"], pq.into_descending_sorted_vec().as_slice() ); } #[test] fn remove2() { use std::collections::hash_map::RandomState; let mut queue = DoublePriorityQueue::::default(); for i in 0..7 { queue.push(i, i); } queue.remove(&0); let mut last_priority = *queue.peek_max().unwrap().1; while let Some((_, priority)) = queue.pop_max() { assert!(last_priority >= priority); last_priority = priority; } let mut queue: DoublePriorityQueue = [20, 7, 19, 5, 6, 15, 18, 1, 2, 3, 4, 13, 14, 16, 17] .iter() .map(|i| (*i, *i)) .collect(); queue.remove(&1); let mut last_priority = *queue.peek_max().unwrap().1; while let Some((_, priority)) = queue.pop_max() { assert!(last_priority >= priority); last_priority = priority; } } #[test] fn drain() { use std::collections::hash_map::RandomState; let mut queue = DoublePriorityQueue::::default(); for i in 0..7 { queue.push(i, i); } let previous_capacity = queue.capacity(); queue.drain(); assert_eq!(queue.len(), 0); assert_eq!(queue.capacity(), previous_capacity); assert_eq!(queue.pop_min(), None); assert_eq!(queue.pop_max(), None); } #[test] fn reserve() { use std::collections::hash_map::RandomState; let mut queue = DoublePriorityQueue::::default(); queue.reserve(100); assert_eq!(queue.len(), 0); assert!(queue.capacity() >= 100); } #[test] fn reserve_exact() { use std::collections::hash_map::RandomState; let mut queue = DoublePriorityQueue::::default(); queue.reserve_exact(100); assert_eq!(queue.len(), 0); assert_eq!(queue.capacity(), 100); } #[test] fn try_reserve() { use std::collections::hash_map::RandomState; let mut queue = DoublePriorityQueue::::default(); queue.try_reserve(100).unwrap(); assert_eq!(queue.len(), 0); assert!(queue.capacity() >= 100); } #[test] fn try_reserve_exact() { use std::collections::hash_map::RandomState; let mut queue = DoublePriorityQueue::::default(); queue.try_reserve_exact(100).unwrap(); assert_eq!(queue.len(), 0); assert_eq!(queue.capacity(), 100); } #[test] fn extend() { let mut pq = DoublePriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); let v = vec![("c", 4), ("d", 6), ("e", 3)]; pq.extend(v); assert_eq!(pq.len(), 6); assert_eq!( pq.into_descending_sorted_vec().as_slice(), &["f", "d", "c", "e", "b", "a"] ); } #[test] fn extend_empty() { let mut pq = DoublePriorityQueue::new(); let v = vec![("c", 4), ("d", 6), ("e", 3)]; pq.extend(v); assert_eq!(pq.len(), 3); assert_eq!(pq.into_descending_sorted_vec().as_slice(), &["d", "c", "e"]); } #[test] fn iter() { let mut pq = DoublePriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); assert_eq!(pq.iter().count(), 3); } #[test] fn iter_mut() { let mut pq = DoublePriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 4); pq.push("h", 3); for (i, p) in &mut pq { if *i < "f" { *p += 18; } } assert_eq!(pq.pop_max(), Some(("b", 20))); /* // As expected, this does not compile let iter_mut = pq.iter_mut(); assert_eq!(pq.pop_max(), Some(("a", 21))); iter_mut.for_each(|(_, p)| {*p += 2}); */ } #[test] fn retain() { #[derive(Hash, PartialEq, Eq, Debug)] struct Animal { name: String, can_fly: bool, can_swim: bool, } impl Animal { pub fn new(name: String, can_fly: bool, can_swim: bool) -> Self { Animal { name, can_fly, can_swim, } } } let mut pq = DoublePriorityQueue::new(); pq.push(Animal::new("dog".to_string(), false, true), 1); pq.push(Animal::new("cat".to_string(), false, false), 2); pq.push(Animal::new("bird".to_string(), true, false), 7); pq.push(Animal::new("fish".to_string(), false, true), 4); pq.push(Animal::new("cow".to_string(), false, false), 3); pq.retain(|i, _| i.can_swim); assert_eq!( pq.pop_max(), Some((Animal::new("fish".to_string(), false, true), 4)) ); assert_eq!( pq.pop_max(), Some((Animal::new("dog".to_string(), false, true), 1)) ); } #[test] fn retain_mut() { #[derive(Hash, PartialEq, Eq, Debug)] struct Animal { name: String, can_fly: bool, can_swim: bool, } impl Animal { pub fn new(name: String, can_fly: bool, can_swim: bool) -> Self { Animal { name, can_fly, can_swim, } } } let mut pq = DoublePriorityQueue::new(); pq.push(Animal::new("dog".to_string(), false, true), 1); pq.push(Animal::new("cat".to_string(), false, false), 2); pq.push(Animal::new("bird".to_string(), true, false), 7); pq.push(Animal::new("fish".to_string(), false, true), 4); pq.push(Animal::new("cow".to_string(), false, false), 3); pq.retain_mut(|i, p| { *p += 10; i.can_swim }); assert_eq!( pq.pop_max(), Some((Animal::new("fish".to_string(), false, true), 14)) ); assert_eq!( pq.pop_max(), Some((Animal::new("dog".to_string(), false, true), 11)) ); } #[test] fn extract_if() { #[derive(Hash, PartialEq, Eq, Debug)] struct Animal { name: String, can_fly: bool, can_swim: bool, } impl Animal { pub fn new(name: String, can_fly: bool, can_swim: bool) -> Self { Animal { name, can_fly, can_swim, } } } let mut pq = DoublePriorityQueue::new(); pq.push(Animal::new("dog".to_string(), false, true), 1); pq.push(Animal::new("cat".to_string(), false, false), 2); pq.push(Animal::new("bird".to_string(), true, false), 7); pq.push(Animal::new("fish".to_string(), false, true), 4); pq.push(Animal::new("cow".to_string(), false, false), 3); let swimming_animals: Vec<(Animal, i32)> = pq .extract_if(|i, p| { if i.can_fly { *p -= 18; return false; } i.can_swim }) .collect(); assert_eq!( swimming_animals, [ (Animal::new("dog".to_string(), false, true), 1), (Animal::new("fish".to_string(), false, true), 4) ] ); assert_eq!( pq.pop_max(), Some((Animal::new("cow".to_string(), false, false), 3)) ); assert_eq!( pq.pop_max(), Some((Animal::new("cat".to_string(), false, false), 2)) ); assert_eq!( pq.pop_max(), Some((Animal::new("bird".to_string(), true, false), -11)) ); /* // As expected, this does not compile let extract_if = pq.extract_if(|i, p| { i.can_fly }); assert_eq!(pq.pop_max(), None); extract_if.for_each(|(_, p)| println!("{:?}", p)); */ } #[test] fn into_sorted_iter() { let mut pq = DoublePriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); assert_eq!( pq.into_sorted_iter().collect::>(), vec!(("a", 1), ("b", 2), ("f", 7)) ); } #[test] fn into_sorted_iter_reverse() { let mut pq = DoublePriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); assert_eq!( pq.into_sorted_iter().rev().collect::>(), vec!(("f", 7), ("b", 2), ("a", 1)) ); } #[test] fn iter_mut1() { let mut queue: DoublePriorityQueue<&'static str, i32> = Default::default(); queue.push("a", 0); queue.push("b", 1); assert_eq!(queue.peek_max().unwrap().0, &"b"); let iter_mut = queue.iter_mut(); for (k, v) in iter_mut { if k == &"a" { *v = 2; } } assert_eq!(queue.peek_max().unwrap().0, &"a"); } #[test] fn iter_mut_empty() { let mut queue: DoublePriorityQueue<&'static str, i32> = Default::default(); let iter_mut = queue.iter_mut(); for (k, v) in iter_mut { if k == &"a" { *v = 2; } } } #[test] fn eq() { let mut a = DoublePriorityQueue::new(); let mut b = DoublePriorityQueue::new(); assert_eq!(a, b); a.push("a", 1); b.push("a", 1); assert_eq!(a, b); a.push("b", 2); assert_ne!(a, b); b.push("f", 7); b.push("g", 4); b.push("h", 3); b.push("b", 2); a.push("g", 4); a.push("f", 7); a.push("h", 3); assert_eq!(a, b); assert_eq!(b, a); } #[test] fn non_default_key() { use std::time::*; type PqType = DoublePriorityQueue; let _: PqType = DoublePriorityQueue::default(); } #[test] fn conversion() { use priority_queue::PriorityQueue; let mut pq = PriorityQueue::new(); pq.push('a', 3); pq.push('b', 5); pq.push('c', 1); let mut dpq: DoublePriorityQueue<_, _> = pq.into(); assert_eq!(dpq.pop_max(), Some(('b', 5))); assert_eq!(dpq.pop_min(), Some(('c', 1))); } #[test] fn equivalent_blanket_implementation() { let mut dpq = DoublePriorityQueue::new(); // Push with owned String dpq.push("Alice".to_string(), 10); dpq.push("Bob".to_string(), 20); // Test get_priority with &str (uses String's blanket Equivalent impl) assert_eq!(dpq.get_priority("Alice"), Some(&10)); assert_eq!(dpq.get_priority("Bob"), Some(&20)); assert_eq!(dpq.get_priority("Charlie"), None); // Test contains with &str assert!(dpq.contains("Alice")); assert!(dpq.contains("Bob")); assert!(!dpq.contains("Charlie")); // Test change_priority with &str assert_eq!(dpq.change_priority("Alice", 25), Some(10)); assert_eq!(dpq.get_priority("Alice"), Some(&25)); // Test change_priority_by with &str assert!(dpq.change_priority_by("Alice", |p| *p += 5)); assert_eq!(dpq.get_priority("Alice"), Some(&30)); // Test get with &str let (item, priority) = dpq.get("Bob").unwrap(); assert_eq!(item, "Bob"); assert_eq!(*priority, 20); // Test get_mut with &str let (item_mut, priority) = dpq.get_mut("Bob").unwrap(); assert_eq!(item_mut, "Bob"); assert_eq!(*priority, 20); // Test remove with &str assert_eq!(dpq.remove("Bob"), Some(("Bob".to_string(), 20))); assert!(!dpq.contains("Bob")); } #[test] fn equivalent_custom_implementation() { use equivalent::Equivalent; use std::hash::Hash; #[derive(Debug, PartialEq, Eq, Hash)] struct Person { id: u32, name: String, age: u16, } #[derive(Debug, PartialEq, Eq, Hash)] struct PersonView<'a> { id: u32, name: &'a str, age: u16, } impl<'a> Equivalent for PersonView<'a> { fn equivalent(&self, key: &Person) -> bool { self.id == key.id && self.name == key.name && self.age == key.age } } let mut dpq = DoublePriorityQueue::new(); // Create test persons let alice = Person { id: 1, name: "Alice".to_string(), age: 30, }; let bob = Person { id: 2, name: "Bob".to_string(), age: 25, }; // Push persons into queue dpq.push(alice, 100); dpq.push(bob, 200); // Create PersonView instances for querying let alice_view = PersonView { id: 1, name: "Alice", age: 30, }; let bob_view = PersonView { id: 2, name: "Bob", age: 25, }; let charlie_view = PersonView { id: 3, name: "Charlie", age: 35, }; // Test get_priority with PersonView assert_eq!(dpq.get_priority(&alice_view), Some(&100)); assert_eq!(dpq.get_priority(&bob_view), Some(&200)); assert_eq!(dpq.get_priority(&charlie_view), None); // Test contains with PersonView assert!(dpq.contains(&alice_view)); assert!(dpq.contains(&bob_view)); assert!(!dpq.contains(&charlie_view)); // Test change_priority with PersonView assert_eq!(dpq.change_priority(&alice_view, 300), Some(100)); assert_eq!(dpq.get_priority(&alice_view), Some(&300)); // Test change_priority_by with PersonView assert!(dpq.change_priority_by(&alice_view, |p| *p += 50)); assert_eq!(dpq.get_priority(&alice_view), Some(&350)); // Test get with PersonView let (person, priority) = dpq.get(&bob_view).unwrap(); assert_eq!(person.name, "Bob"); assert_eq!(*priority, 200); // Test get_mut with PersonView let (person_mut, priority) = dpq.get_mut(&bob_view).unwrap(); assert_eq!(person_mut.name, "Bob"); assert_eq!(*priority, 200); // Test remove with PersonView let removed = dpq.remove(&bob_view); assert!(removed.is_some()); let (removed_person, removed_priority) = removed.unwrap(); assert_eq!(removed_person.id, 2); assert_eq!(removed_person.name, "Bob"); assert_eq!(removed_priority, 200); assert!(!dpq.contains(&bob_view)); } #[test] fn user_test() { use priority_queue::PriorityQueue; use std::cmp::Reverse; let mut double_queue = DoublePriorityQueue::new(); let mut simple_queue = PriorityQueue::new(); let data = vec![ 23403400, 23375200, 23395900, 23400100, 23401600, 23375200, 23391100, 23410300, 23391600, 23402200, 23407600, 23414500, 23421000, 23430500, 23430500, 23441600, 23441600, 23440200, 23424200, 23465500, 23273300, 23232300, 23183100, 23315600, 23328500, 23328500, 23346900, 23350000, 23363600, 23388100, 23403600, 23385300, 23385800, 23385800, 23363600, 23363600, 23398900, 23400700, 23401700, 23370000, 23370000, 23396700, 23370000, 23370000, 23396800, 23385000, 23369100, 23381800, 23372300, 23382600, 23382300, 23401500, 23405000, 23392000, 23392000, 23398400, 23393800, 23382300, 23382800, 23376200, 23379300, 23380600, 23380600, 23384400, 23379500, 23381700, 23391700, 23396300, 23402000, 23414800, 23410900, 23423600, 23419300, 23419300, 23420900, 23397100, 23425900, 23397100, 23397100, 23417400, 23413600, 23422700, 23422700, 23413600, 23407400, 23413900, 23407400, 23397100, 23391100, 23390000, 23388500, 23383000, 23375900, 23355100, 23354300, 23370400, 23381800, 23381800, 23383600, 23391400, 23393800, 23393800, 23379100, 23380800, 23384900, 23384900, 23390200, 23382000, 23380800, 23379900, 23370500, 23377300, 23378000, 23391700, 23386700, 23374200, 23392200, 23394500, 23403200, 23413500, 23420400, 23443800, 23441600, 23441600, 23485300, 23488500, 23488500, 23505300, 23471400, 23471400, 23477900, 23488700, 23488700, 23483200, 23463200, 23463200, 23463600, 23463600, 23468800, 23485700, 23487800, 23508600, 23512900, 23507700, 23507700, 23539200, 23541700, 23539200, 23507700, 23487800, 23487800, 23553500, 23553500, 23553500, 23553500, 23553500, 23553500, 23565500, 23566700, 23566700, 23566700, 23565500, 23566700, 23565500, 23566700, 23566700, 23549900, 23541300, 23560800, 23566800, 23563500, 23563500, 23541300, 23538300, 23535300, 23543700, 23549100, 23549600, 23520000, 23500000, 23545600, 23554300, 23558600, 23526700, 23452100, 23526700, 23520000, 23520000, 23526700, 23524300, 23524300, 23526700, 23524300, 23450000, 23450000, 23354300, 23350000, 23521100, 23542700, 23553700, ]; let window = 32; for idx in 0..window { let val = data[idx]; simple_queue.push(idx, Reverse(val)); double_queue.push(idx, val); } for idx in window..data.len() { let val = data[idx]; simple_queue.change_priority(&(idx % window), Reverse(val)); double_queue.change_priority(&(idx % window), val); let simple_min_result = (*simple_queue.peek().unwrap().1).0; let double_min_result = *double_queue.peek_min().unwrap().1; assert_eq!( simple_min_result, double_min_result, "{} {:?} {:?}\n {:?}\n{:?}", idx, simple_queue.peek(), double_queue.peek_min(), simple_queue, double_queue ); } } } #[cfg(all(feature = "serde", test))] mod serde_tests_basics { use priority_queue::DoublePriorityQueue; use serde_test::{assert_tokens, Token}; #[test] fn serde_empty() { let pq: DoublePriorityQueue = DoublePriorityQueue::new(); assert_tokens(&pq, &[Token::Seq { len: Some(0) }, Token::SeqEnd]); } #[test] fn serde() { let mut pq = DoublePriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 4); pq.push("h", 3); assert_tokens( &pq, &[ Token::Seq { len: Some(5) }, Token::Tuple { len: 2 }, Token::BorrowedStr("a"), Token::I32(1), Token::TupleEnd, Token::Tuple { len: 2 }, Token::BorrowedStr("b"), Token::I32(2), Token::TupleEnd, Token::Tuple { len: 2 }, Token::BorrowedStr("f"), Token::I32(7), Token::TupleEnd, Token::Tuple { len: 2 }, Token::BorrowedStr("g"), Token::I32(4), Token::TupleEnd, Token::Tuple { len: 2 }, Token::BorrowedStr("h"), Token::I32(3), Token::TupleEnd, Token::SeqEnd, ], ); } } //more complex tests //thanks to ckaran #[cfg(all(feature = "serde", test))] mod serde_tests_custom_structs { use priority_queue::DoublePriorityQueue; use std::cmp::{Ord, Ordering, PartialOrd}; use std::default::Default; use std::time::Duration; use uuid::Uuid; use serde::{Deserialize, Serialize}; // Abusing Duration as a mutable std::time::Instant type ActivationDate = Duration; /// Events are compared by EventComparables instances. /// /// EventComparables instances are similar to instances of time, but with the /// extra wrinkle of having a Uuid instance. When EventComparables instances /// are compared, they are first compared by their activation date, with the /// date that occurs earlier being greater than a date that occurs later. This /// ordering exists because of how priority_queue::DoublePriorityQueue works; it is /// naturally a max priority queue; using this ordering makes it a min /// priority queue. EventComparables go one step beyond using time as the key /// though; they also have uuid::Uuid instances which are used to guarantee /// that every EventComparables is unique. This ensures that if a set of /// events all occur at the same time, they will still be executed in a /// deterministic order, every single time the queue's contents are executed. /// This is critical for deterministic simulators. #[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Debug)] #[serde(default)] #[serde(deny_unknown_fields)] struct EventComparables { /// This is when the event will be fired. activation_date: ActivationDate, /// This is a unique ID. Except for ensuring that different events are /// guaranteed to compare as being different, it has no purpose. id: Uuid, } /// Default events activate at time (0, 0) /// /// All default events first at time (0, 0), but every single one has a unique /// id. This ensures that regardless of the number of default events you /// create, they will always execute in the same order. impl Default for EventComparables { fn default() -> Self { EventComparables { activation_date: ActivationDate::new(0, 0), id: Uuid::new_v4(), } } } /// The priority queue depends on `Ord`. Explicitly implement the trait so the /// queue becomes a min-heap instead of a max-heap. impl Ord for EventComparables { fn cmp(&self, other: &Self) -> Ordering { // Notice that the we flip the ordering on costs. In case of a tie we // compare by id - this step is necessary to make implementations of // `PartialEq` and `Ord` consistent. other .activation_date .cmp(&self.activation_date) .then_with(|| self.id.cmp(&other.id)) } } // `PartialOrd` needs to be implemented as well. impl PartialOrd for EventComparables { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } /// A fake event to fire on some date. /// /// This is a fake event that I'll fire when the corresponding /// EventComparables instance comes up. The contents are immaterial; I'm just /// using it for testing #[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Debug)] #[serde(default)] #[serde(deny_unknown_fields)] struct ConcreteEvent1 { a: i32, b: i64, } impl Default for ConcreteEvent1 { fn default() -> Self { ConcreteEvent1 { a: 0, b: 0 } } } ////////////////////////////////////////////////////////////////////////////// // Test 1 ////////////////////////////////////////////////////////////////////////////// #[test] fn test1() { println!("test1()"); type PqType = DoublePriorityQueue; let mut pq: PqType = DoublePriorityQueue::new(); pq.push(0, 0); pq.push(1, 1); let serialized = serde_json::to_string(&pq).unwrap(); println!("serialized = {:?}", serialized); let deserialized: PqType = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); } ////////////////////////////////////////////////////////////////////////////// // Test 2 ////////////////////////////////////////////////////////////////////////////// #[test] fn test2() { println!("\n\ntest2()"); type PqType = DoublePriorityQueue; let mut pq: PqType = DoublePriorityQueue::new(); pq.push(0, Default::default()); // Uuids will be different pq.push(1, Default::default()); let serialized = serde_json::to_string(&pq).unwrap(); println!("serialized = {:?}", serialized); let deserialized: PqType = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); } ////////////////////////////////////////////////////////////////////////////// // Test 3 ////////////////////////////////////////////////////////////////////////////// #[test] fn test3() { println!("\n\ntest3()"); // Create some concrete events and comparables, and test to see that they // can be serialized/deserialized let ce1 = ConcreteEvent1 { a: 12, b: 45 }; let ec1 = EventComparables { activation_date: ActivationDate::new(0, 1), id: Uuid::new_v4(), }; let ce2 = ConcreteEvent1 { a: 37, b: 123 }; let ec2 = EventComparables { activation_date: ActivationDate::new(0, 1), id: Uuid::new_v4(), }; let serialized = serde_json::to_string(&ce1).unwrap(); println!("serialized = {:?}", serialized); let deserialized: ConcreteEvent1 = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); assert_eq!(ce1, deserialized); let serialized = serde_json::to_string(&ec1).unwrap(); println!("serialized = {:?}", serialized); let deserialized: EventComparables = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); assert_eq!(ec1, deserialized); let serialized = serde_json::to_string(&ce2).unwrap(); println!("serialized = {:?}", serialized); let deserialized: ConcreteEvent1 = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); assert_eq!(ce2, deserialized); let serialized = serde_json::to_string(&ec2).unwrap(); println!("serialized = {:?}", serialized); let deserialized: EventComparables = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); assert_eq!(ec2, deserialized); { type PqType = DoublePriorityQueue; let mut pq: PqType = DoublePriorityQueue::new(); pq.push(ce1, ec1); pq.push(ce2, ec2); let serialized = serde_json::to_string(&pq).unwrap(); println!("serialized = {:?}", serialized); let deserialized: PqType = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); } } } priority-queue-2.6.0/tests/priority_queue.rs000064400000000000000000001113771046102023000174430ustar 00000000000000/* * Copyright 2017 Gianmarco Garrisi and contributors * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version, or (at your option) under the terms * of the Mozilla Public License version 2.0. * * ---- * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * ---- * * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. * */ #[cfg(test)] mod pqueue_tests { pub use priority_queue::PriorityQueue; #[test] fn init() { let pq: PriorityQueue = PriorityQueue::new(); println!("{:?}", pq); } #[test] fn push_len_clear() { let mut pq = PriorityQueue::new(); assert_eq!(pq.len(), 0); pq.push("a", 1); pq.push("b", 2); println!("{:?}", pq); assert_eq!(pq.len(), 2); pq.clear(); assert_eq!(pq.len(), 0); assert_eq!(None, pq.pop()); } #[test] fn push_pop() { let mut pq = PriorityQueue::new(); assert_eq!(pq.peek(), None); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 4); pq.push("h", 3); println!("{:?}", pq); assert_eq!(pq.pop(), Some(("f", 7))); println!("{:?}", pq); assert_eq!(pq.peek(), Some((&"g", &4))); assert_eq!(pq.pop(), Some(("g", 4))); assert_eq!(pq.len(), 3); } #[test] fn push_pop_if() { let mut pq = PriorityQueue::new(); assert_eq!(pq.pop_if(|_, _| true), None); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 5); pq.push("h", 3); println!("{:?}", pq); assert_eq!( pq.pop_if(|i, p| { assert_eq!(&"f", i); assert_eq!(&7, p); *p = 4; false }), None ); assert_eq!( pq.pop_if(|i, p| { assert_eq!(&"g", i); assert_eq!(&5, p); *p = 4; true }), Some(("g", 4)) ); println!("{:?}", pq); assert_eq!(pq.peek(), Some((&"f", &4))); assert_eq!(pq.pop(), Some(("f", 4))); assert_eq!(pq.len(), 3); } #[test] fn contains() { let mut pq = PriorityQueue::new(); assert!(!pq.contains("a")); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 5); pq.push("h", 3); assert!(pq.contains("f")); pq.pop(); assert!(!pq.contains("f")); } #[test] fn peek_get_mut() { use std::hash::{Hash, Hasher}; #[derive(Debug)] struct Person { id: u32, name: String, phone: u64, } impl Hash for Person { fn hash(&self, state: &mut H) { self.id.hash(state); self.phone.hash(state); } } impl PartialEq for Person { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.phone == other.phone } } impl Eq for Person {} let mut pq = PriorityQueue::new(); assert_eq!(pq.peek_mut(), None); pq.push( Person { id: 1, name: "a".to_string(), phone: 39281048279, }, 1, ); pq.push( Person { id: 2, name: "b".to_string(), phone: 23912750234, }, 2, ); pq.push( Person { id: 3, name: "c".to_string(), phone: 1298275802947, }, 3, ); pq.push( Person { id: 4, name: "d".to_string(), phone: 65723012057, }, 4, ); pq.push( Person { id: 5, name: "e".to_string(), phone: 7237569870239, }, 5, ); pq.push( Person { id: 6, name: "f".to_string(), phone: 35756872497, }, 6, ); println!("{:?}", pq); let (item, _) = pq.peek_mut().unwrap(); item.name.push('g'); let (item, priority) = pq.pop().unwrap(); assert_eq!( item, Person { id: 6, // name is not used for checking equality name: "f".to_string(), phone: 35756872497 } ); assert_eq!(6, priority); assert_eq!("fg", item.name); let (item, _) = pq .get_mut(&Person { id: 4, // name is not used for checking equality name: String::new(), phone: 65723012057, }) .unwrap(); item.name.push('g'); let (item, priority) = pq .get(&Person { id: 4, // name is not used for checking equality name: String::new(), phone: 65723012057, }) .unwrap(); assert_eq!( item, &Person { id: 4, // name is not used for checking equality name: String::new(), phone: 65723012057 } ); assert_eq!(&4, priority); assert_eq!("dg", item.name); println!("{:?}", pq); assert_eq!(pq.len(), 5); } #[test] fn append() { let mut pq1 = PriorityQueue::new(); let mut pq2 = PriorityQueue::new(); pq1.push("a", 9); pq1.push("b", 8); pq1.push("c", 7); pq1.push("d", 6); pq1.push("e", 5); pq1.push("f", 4); pq1.push("g", 10); pq1.push("k", 11); pq1.push("d", 20); pq2.push("h", 2); pq2.push("x", 18); pq2.push("v", 28); pq2.push("y", 0); pq2.push("z", 21); pq1.append(&mut pq2); let expected = [ "v", "z", "d", "x", "k", "g", "a", "b", "c", "e", "f", "h", "y", ]; let v = pq1.into_sorted_vec(); assert_eq!(expected, v.as_slice()); } #[test] fn push_update() { let mut pq = PriorityQueue::new(); pq.push("a", 9); pq.push("b", 8); pq.push("c", 7); pq.push("d", 6); pq.push("e", 5); pq.push("f", 4); pq.push("g", 10); pq.push("k", 11); pq.push("d", 20); assert_eq!(pq.peek(), Some((&"d", &20))); assert_eq!(pq.pop(), Some(("d", 20))); } #[test] fn push_increase() { let mut pq = PriorityQueue::new(); pq.push("Processor", 1); pq.push("Mainboard", 2); pq.push("RAM", 5); pq.push("GPU", 4); pq.push("Disk", 3); let processor_priority = |pq: &PriorityQueue<&str, i32>| { *pq.iter() .find_map(|(i, p)| if *i == "Processor" { Some(p) } else { None }) .unwrap() }; pq.push_increase("Processor", 3); assert_eq!(processor_priority(&pq), 3); pq.push_increase("Processor", 1); assert_eq!(processor_priority(&pq), 3); pq.push_increase("Processor", 6); assert_eq!(pq.peek(), Some((&"Processor", &6))); } #[test] fn push_decrease() { let mut pq = PriorityQueue::new(); pq.push("Processor", 1); pq.push("Mainboard", 2); pq.push("RAM", 5); pq.push("GPU", 4); pq.push("Disk", 3); let processor_priority = |pq: &PriorityQueue<&str, i32>| *pq.get("Processor").unwrap().1; pq.push_decrease("Processor", 3); assert_eq!(processor_priority(&pq), 1); pq.push_decrease("Processor", 0); assert_eq!(processor_priority(&pq), 0); pq.push_decrease("Processor", 6); assert_eq!(pq.peek(), Some((&"RAM", &5))); } #[test] fn change_priority() { let mut pq = PriorityQueue::new(); pq.push("Processor", 1); pq.push("Mainboard", 2); pq.push("RAM", 5); pq.push("GPU", 4); pq.push("Disk", 3); pq.change_priority("Processor", 10); assert_eq!(pq.peek(), Some((&"Processor", &10))); pq.change_priority("RAM", 11); assert_eq!(pq.peek(), Some((&"RAM", &11))); } #[test] fn change_priority_does_not_change_contents() { use std::hash::{Hash, Hasher}; struct MyFn { name: &'static str, func: fn(&mut i32), } impl Default for MyFn { fn default() -> Self { Self { name: "", func: |_| {}, } } } impl PartialEq for MyFn { fn eq(&self, other: &Self) -> bool { self.name == other.name } } impl Eq for MyFn {} impl Hash for MyFn { fn hash(&self, state: &mut H) { self.name.hash(state); } } impl std::fmt::Debug for MyFn { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write![f, "{:?}", self.name] } } let mut pq = PriorityQueue::new(); pq.push( MyFn { name: "increment-one", func: |x| *x += 1, }, 2, ); pq.push( MyFn { name: "increment-two", func: |x| *x += 2, }, 1, ); let mut cnt = 0; assert_eq![ pq.peek(), Some(( &MyFn { name: "increment-one", func: |_| {} }, &2 )) ]; pq.change_priority( &MyFn { name: "increment-one", func: |_| {}, }, 0, ); assert_eq![ pq.peek(), Some(( &MyFn { name: "increment-two", func: |_| {} }, &1 )) ]; assert_eq![cnt, 0]; (pq.pop().unwrap().0.func)(&mut cnt); assert_eq![cnt, 2]; (pq.pop().unwrap().0.func)(&mut cnt); assert_eq![cnt, 3]; } #[test] fn reversed_order() { use std::cmp::Reverse; let mut pq: PriorityQueue<_, Reverse> = PriorityQueue::new(); pq.push("a", Reverse(1)); pq.push("b", Reverse(2)); assert_eq![pq.pop(), Some(("a", Reverse(1)))]; } #[test] fn from_vec() { let v = vec![("a", 1), ("b", 2), ("f", 7)]; let mut pq: PriorityQueue<_, _> = PriorityQueue::from(v); assert_eq!(pq.pop(), Some(("f", 7))); assert_eq!(pq.len(), 2); } #[test] fn into_vec() { let v = vec![("a", 1), ("b", 2), ("f", 7)]; let pq: PriorityQueue<_, _> = PriorityQueue::from(v); let mut v = pq.into_vec(); v.sort_unstable(); assert!(v.iter().enumerate().all(|(i, x)| &["a", "b", "f"][i] == x)); assert_eq!(v.len(), 3); } #[test] fn from_vec_with_repeated() { let v = vec![("a", 1), ("b", 2), ("f", 7), ("a", 2)]; let mut pq: PriorityQueue<_, _> = v.into(); assert_eq!(pq.pop(), Some(("f", 7))); assert_eq!(pq.len(), 2); } #[test] fn from_iter() { use std::iter::FromIterator; let v = vec![("a", 1), ("b", 2), ("f", 7)]; let mut pq: PriorityQueue<_, _> = PriorityQueue::from_iter(v); assert_eq!(pq.pop(), Some(("f", 7))); assert_eq!(pq.len(), 2); } #[test] fn heap_sort() { type Pq = PriorityQueue; let v = vec![("a", 2), ("b", 7), ("f", 1)]; let sorted = (Pq::from(v)).into_sorted_vec(); assert_eq!(sorted.as_slice(), &["b", "a", "f"]); } #[test] fn change_priority_by() { use std::iter::FromIterator; let v = vec![("a", 1), ("b", 2), ("f", 7), ("g", 6), ("h", 5)]; let mut pq: PriorityQueue<_, _> = PriorityQueue::from_iter(v); assert!(!pq.change_priority_by("z", |z| *z += 8)); assert!(pq.change_priority_by("b", |b| *b += 8)); assert_eq!(pq.into_sorted_vec().as_slice(), &["b", "f", "g", "h", "a"]); } #[test] fn remove_empty() { let mut pq: PriorityQueue<&str, i32> = PriorityQueue::new(); pq.remove(&"b"); assert_eq!(pq.len(), 0); } #[test] fn remove_one() { let mut pq = PriorityQueue::new(); pq.push("b", 21); assert_eq!(Some(("b", 21)), pq.remove(&"b")); assert_eq!(pq.len(), 0); } #[test] fn remove() { use std::iter::FromIterator; type Pq = PriorityQueue; let v = vec![("a", 1), ("b", 2), ("f", 7), ("g", 6), ("h", 5)]; let mut pq = Pq::from_iter(v); pq.remove(&"b").unwrap(); pq.push("b", 2); pq.remove(&"b"); assert_eq!(["f", "g", "h", "a"], pq.into_sorted_vec().as_slice()); } #[test] fn remove2() { use std::collections::hash_map::RandomState; let mut queue = PriorityQueue::::default(); for i in 0..7 { queue.push(i, i); } queue.remove(&0); let mut last_priority = *queue.peek().unwrap().1; while let Some((_, priority)) = queue.pop() { dbg!(priority); assert!(last_priority >= priority); last_priority = priority; } let mut queue: PriorityQueue = [20, 7, 19, 5, 6, 15, 18, 1, 2, 3, 4, 13, 14, 16, 17] .iter() .map(|i| (*i, *i)) .collect(); queue.remove(&1); let mut last_priority = *queue.peek().unwrap().1; while let Some((_, priority)) = queue.pop() { dbg!(priority); assert!(last_priority >= priority); last_priority = priority; } } #[test] fn drain() { use std::collections::hash_map::RandomState; let mut queue = PriorityQueue::::default(); for i in 0..7 { queue.push(i, i); } let previous_capacity = queue.capacity(); queue.drain(); assert_eq!(queue.len(), 0); assert_eq!(queue.capacity(), previous_capacity); assert_eq!(queue.pop(), None); } #[test] fn reserve() { use std::collections::hash_map::RandomState; let mut queue = PriorityQueue::::default(); queue.reserve(100); assert_eq!(queue.len(), 0); assert!(queue.capacity() >= 100); } #[test] fn reserve_exact() { use std::collections::hash_map::RandomState; let mut queue = PriorityQueue::::default(); queue.reserve_exact(100); assert_eq!(queue.len(), 0); assert_eq!(queue.capacity(), 100); } #[test] fn try_reserve() { use std::collections::hash_map::RandomState; let mut queue = PriorityQueue::::default(); queue.try_reserve(100).unwrap(); assert_eq!(queue.len(), 0); assert!(queue.capacity() >= 100); } #[test] fn try_reserve_exact() { use std::collections::hash_map::RandomState; let mut queue = PriorityQueue::::default(); queue.try_reserve_exact(100).unwrap(); assert_eq!(queue.len(), 0); assert_eq!(queue.capacity(), 100); } #[test] fn extend() { let mut pq = PriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); let v = vec![("c", 4), ("d", 6), ("e", 3)]; pq.extend(v); assert_eq!(pq.len(), 6); assert_eq!( pq.into_sorted_vec().as_slice(), &["f", "d", "c", "e", "b", "a"] ); } #[test] fn extend_empty() { let mut pq = PriorityQueue::new(); let v = vec![("c", 4), ("d", 6), ("e", 3)]; pq.extend(v); assert_eq!(pq.len(), 3); assert_eq!(pq.into_sorted_vec().as_slice(), &["d", "c", "e"]); } #[test] fn iter() { let mut pq = PriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); assert_eq!(pq.iter().count(), 3); } #[test] fn iter_mut() { let mut pq = PriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 4); pq.push("h", 3); for (i, p) in &mut pq { if *i < "f" { *p += 18; } } assert_eq!(pq.pop(), Some(("b", 20))); /* As expected, this does not compile let iter_mut = pq.iter_mut(); assert_eq!(pq.pop(), Some(("f", 9))); iter_mut.for_each(|(_, p)| {*p += 2}); */ } #[test] fn extract_if() { #[derive(Hash, PartialEq, Eq, Debug)] struct Animal { name: String, can_fly: bool, can_swim: bool, } impl Animal { pub fn new(name: String, can_fly: bool, can_swim: bool) -> Self { Animal { name, can_fly, can_swim, } } } let mut pq = PriorityQueue::new(); pq.push(Animal::new("dog".to_string(), false, true), 1); pq.push(Animal::new("cat".to_string(), false, false), 2); pq.push(Animal::new("bird".to_string(), true, false), 7); pq.push(Animal::new("fish".to_string(), false, true), 4); pq.push(Animal::new("cow".to_string(), false, false), 3); let swimming_animals: Vec<(Animal, i32)> = pq .extract_if(|i, p| { if i.can_fly { *p -= 18; return false; } i.can_swim }) .collect(); assert_eq!( swimming_animals, [ (Animal::new("dog".to_string(), false, true), 1), (Animal::new("fish".to_string(), false, true), 4) ] ); assert_eq!( pq.pop(), Some((Animal::new("cow".to_string(), false, false), 3)) ); assert_eq!( pq.pop(), Some((Animal::new("cat".to_string(), false, false), 2)) ); assert_eq!( pq.pop(), Some((Animal::new("bird".to_string(), true, false), -11)) ); /* // As expected, this does not compile let extract_if = pq.extract_if(|i, p| { i.can_fly }); assert_eq!(pq.pop(), None); extract_if.for_each(|(_, p)| println!("{:?}", p)); */ } #[test] fn retain() { #[derive(Hash, PartialEq, Eq, Debug)] struct Animal { name: String, can_fly: bool, can_swim: bool, } impl Animal { pub fn new(name: String, can_fly: bool, can_swim: bool) -> Self { Animal { name, can_fly, can_swim, } } } let mut pq = PriorityQueue::new(); pq.push(Animal::new("dog".to_string(), false, true), 1); pq.push(Animal::new("cat".to_string(), false, false), 2); pq.push(Animal::new("bird".to_string(), true, false), 7); pq.push(Animal::new("fish".to_string(), false, true), 4); pq.push(Animal::new("cow".to_string(), false, false), 3); pq.retain(|i, _| i.can_swim); assert_eq!( pq.pop(), Some((Animal::new("fish".to_string(), false, true), 4)) ); assert_eq!( pq.pop(), Some((Animal::new("dog".to_string(), false, true), 1)) ); } #[test] fn retain_mut() { #[derive(Hash, PartialEq, Eq, Debug)] struct Animal { name: String, can_fly: bool, can_swim: bool, } impl Animal { pub fn new(name: String, can_fly: bool, can_swim: bool) -> Self { Animal { name, can_fly, can_swim, } } } let mut pq = PriorityQueue::new(); pq.push(Animal::new("dog".to_string(), false, true), 1); pq.push(Animal::new("cat".to_string(), false, false), 2); pq.push(Animal::new("bird".to_string(), true, false), 7); pq.push(Animal::new("fish".to_string(), false, true), 4); pq.push(Animal::new("cow".to_string(), false, false), 3); pq.retain_mut(|i, p| { *p += 10; i.can_swim }); assert_eq!( pq.pop(), Some((Animal::new("fish".to_string(), false, true), 14)) ); assert_eq!( pq.pop(), Some((Animal::new("dog".to_string(), false, true), 11)) ); } #[test] fn into_sorted_iter() { let mut pq = PriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); assert_eq!( pq.into_sorted_iter().collect::>(), vec!(("f", 7), ("b", 2), ("a", 1)) ); } #[test] fn iter_mut1() { let mut queue: PriorityQueue<&'static str, i32> = Default::default(); queue.push("a", 0); queue.push("b", 1); assert_eq!(queue.peek().unwrap().0, &"b"); let iter_mut = queue.iter_mut(); for (k, v) in iter_mut { if k == &"a" { *v = 2; } } assert_eq!(queue.peek().unwrap().0, &"a"); } #[test] fn iter_mut_empty() { let mut queue: PriorityQueue<&'static str, i32> = Default::default(); let iter_mut = queue.iter_mut(); for (k, v) in iter_mut { if k == &"a" { *v = 2; } } } #[test] fn eq() { let mut a = PriorityQueue::new(); let mut b = PriorityQueue::new(); assert_eq!(a, b); a.push("a", 1); b.push("a", 1); assert_eq!(a, b); a.push("b", 2); assert_ne!(a, b); b.push("f", 7); b.push("g", 4); b.push("h", 3); b.push("b", 2); a.push("g", 4); a.push("f", 7); a.push("h", 3); assert_eq!(a, b); assert_eq!(b, a); } #[test] fn non_default_key() { use std::time::*; type PqType = PriorityQueue; let _: PqType = PriorityQueue::default(); } #[test] fn conversion() { use priority_queue::DoublePriorityQueue; let mut dpq = DoublePriorityQueue::new(); dpq.push('a', 3); dpq.push('b', 5); dpq.push('c', 1); let mut pq: PriorityQueue<_, _> = dpq.into(); assert_eq!(pq.pop(), Some(('b', 5))); } #[test] fn equivalent_blanket_implementation() { let mut pq = PriorityQueue::new(); // Push with owned String pq.push("Alice".to_string(), 10); pq.push("Bob".to_string(), 20); // Test get_priority with &str (uses String's blanket Equivalent impl) assert_eq!(pq.get_priority("Alice"), Some(&10)); assert_eq!(pq.get_priority("Bob"), Some(&20)); assert_eq!(pq.get_priority("Charlie"), None); // Test contains with &str assert!(pq.contains("Alice")); assert!(pq.contains("Bob")); assert!(!pq.contains("Charlie")); // Test change_priority with &str assert_eq!(pq.change_priority("Alice", 25), Some(10)); assert_eq!(pq.get_priority("Alice"), Some(&25)); // Test change_priority_by with &str assert!(pq.change_priority_by("Alice", |p| *p += 5)); assert_eq!(pq.get_priority("Alice"), Some(&30)); // Test get with &str let (item, priority) = pq.get("Bob").unwrap(); assert_eq!(item, "Bob"); assert_eq!(*priority, 20); // Test get_mut with &str let (item_mut, priority) = pq.get_mut("Bob").unwrap(); assert_eq!(item_mut, "Bob"); assert_eq!(*priority, 20); // Test remove with &str assert_eq!(pq.remove("Bob"), Some(("Bob".to_string(), 20))); assert!(!pq.contains("Bob")); } #[test] fn equivalent_custom_implementation() { use equivalent::Equivalent; use std::hash::Hash; #[derive(Debug, PartialEq, Eq, Hash)] struct Person { id: u32, name: String, age: u16, } #[derive(Debug, PartialEq, Eq, Hash)] struct PersonView<'a> { id: u32, name: &'a str, age: u16, } impl<'a> Equivalent for PersonView<'a> { fn equivalent(&self, key: &Person) -> bool { self.id == key.id && self.name == key.name && self.age == key.age } } let mut pq = PriorityQueue::new(); // Create test persons let alice = Person { id: 1, name: "Alice".to_string(), age: 30, }; let bob = Person { id: 2, name: "Bob".to_string(), age: 25, }; // Push persons into queue pq.push(alice, 100); pq.push(bob, 200); // Create PersonView instances for querying let alice_view = PersonView { id: 1, name: "Alice", age: 30, }; let bob_view = PersonView { id: 2, name: "Bob", age: 25, }; let charlie_view = PersonView { id: 3, name: "Charlie", age: 35, }; // Test get_priority with PersonView assert_eq!(pq.get_priority(&alice_view), Some(&100)); assert_eq!(pq.get_priority(&bob_view), Some(&200)); assert_eq!(pq.get_priority(&charlie_view), None); // Test contains with PersonView assert!(pq.contains(&alice_view)); assert!(pq.contains(&bob_view)); assert!(!pq.contains(&charlie_view)); // Test change_priority with PersonView assert_eq!(pq.change_priority(&alice_view, 300), Some(100)); assert_eq!(pq.get_priority(&alice_view), Some(&300)); // Test change_priority_by with PersonView assert!(pq.change_priority_by(&alice_view, |p| *p += 50)); assert_eq!(pq.get_priority(&alice_view), Some(&350)); // Test get with PersonView let (person, priority) = pq.get(&bob_view).unwrap(); assert_eq!(person.name, "Bob"); assert_eq!(*priority, 200); // Test get_mut with PersonView let (person_mut, priority) = pq.get_mut(&bob_view).unwrap(); assert_eq!(person_mut.name, "Bob"); assert_eq!(*priority, 200); // Test remove with PersonView let removed = pq.remove(&bob_view); assert!(removed.is_some()); let (removed_person, removed_priority) = removed.unwrap(); assert_eq!(removed_person.id, 2); assert_eq!(removed_person.name, "Bob"); assert_eq!(removed_priority, 200); assert!(!pq.contains(&bob_view)); } } #[cfg(all(feature = "serde", test))] mod serde_tests_basics { use priority_queue::PriorityQueue; use serde_test::{assert_tokens, Token}; #[test] fn serde_empty() { let pq: PriorityQueue = PriorityQueue::new(); assert_tokens(&pq, &[Token::Seq { len: Some(0) }, Token::SeqEnd]); } #[test] fn serde() { let mut pq = PriorityQueue::new(); pq.push("a", 1); pq.push("b", 2); pq.push("f", 7); pq.push("g", 4); pq.push("h", 3); assert_tokens( &pq, &[ Token::Seq { len: Some(5) }, Token::Tuple { len: 2 }, Token::BorrowedStr("a"), Token::I32(1), Token::TupleEnd, Token::Tuple { len: 2 }, Token::BorrowedStr("b"), Token::I32(2), Token::TupleEnd, Token::Tuple { len: 2 }, Token::BorrowedStr("f"), Token::I32(7), Token::TupleEnd, Token::Tuple { len: 2 }, Token::BorrowedStr("g"), Token::I32(4), Token::TupleEnd, Token::Tuple { len: 2 }, Token::BorrowedStr("h"), Token::I32(3), Token::TupleEnd, Token::SeqEnd, ], ); } } //more complex tests //thanks to ckaran #[cfg(all(feature = "serde", test))] mod serde_tests_custom_structs { use priority_queue::PriorityQueue; use std::cmp::{Ord, Ordering, PartialOrd}; use std::default::Default; use std::time::Duration; use uuid::Uuid; use serde::{Deserialize, Serialize}; // Abusing Duration as a mutable std::time::Instant type ActivationDate = Duration; /// Events are compared by EventComparables instances. /// /// EventComparables instances are similar to instances of time, but with the /// extra wrinkle of having a Uuid instance. When EventComparables instances /// are compared, they are first compared by their activation date, with the /// date that occurs earlier being greater than a date that occurs later. This /// ordering exists because of how priority_queue::PriorityQueue works; it is /// naturally a max priority queue; using this ordering makes it a min /// priority queue. EventComparables go one step beyond using time as the key /// though; they also have uuid::Uuid instances which are used to guarantee /// that every EventComparables is unique. This ensures that if a set of /// events all occur at the same time, they will still be executed in a /// deterministic order, every single time the queue's contents are executed. /// This is critical for deterministic simulators. #[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Debug)] #[serde(default)] #[serde(deny_unknown_fields)] struct EventComparables { /// This is when the event will be fired. activation_date: ActivationDate, /// This is a unique ID. Except for ensuring that different events are /// guaranteed to compare as being different, it has no purpose. id: Uuid, } /// Default events activate at time (0, 0) /// /// All default events first at time (0, 0), but every single one has a unique /// id. This ensures that regardless of the number of default events you /// create, they will always execute in the same order. impl Default for EventComparables { fn default() -> Self { EventComparables { activation_date: ActivationDate::new(0, 0), id: Uuid::new_v4(), } } } /// The priority queue depends on `Ord`. Explicitly implement the trait so the /// queue becomes a min-heap instead of a max-heap. impl Ord for EventComparables { fn cmp(&self, other: &Self) -> Ordering { // Notice that the we flip the ordering on costs. In case of a tie we // compare by id - this step is necessary to make implementations of // `PartialEq` and `Ord` consistent. other .activation_date .cmp(&self.activation_date) .then_with(|| self.id.cmp(&other.id)) } } // `PartialOrd` needs to be implemented as well. impl PartialOrd for EventComparables { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } /// A fake event to fire on some date. /// /// This is a fake event that I'll fire when the corresponding /// EventComparables instance comes up. The contents are immaterial; I'm just /// using it for testing #[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Debug)] #[serde(default)] #[serde(deny_unknown_fields)] struct ConcreteEvent1 { a: i32, b: i64, } impl Default for ConcreteEvent1 { fn default() -> Self { ConcreteEvent1 { a: 0, b: 0 } } } ////////////////////////////////////////////////////////////////////////////// // Test 1 ////////////////////////////////////////////////////////////////////////////// #[test] fn test1() { println!("test1()"); type PqType = PriorityQueue; let mut pq: PqType = PriorityQueue::new(); pq.push(0, 0); pq.push(1, 1); let serialized = serde_json::to_string(&pq).unwrap(); println!("serialized = {:?}", serialized); let deserialized: PqType = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); } ////////////////////////////////////////////////////////////////////////////// // Test 2 ////////////////////////////////////////////////////////////////////////////// #[test] fn test2() { println!("\n\ntest2()"); type PqType = PriorityQueue; let mut pq: PqType = PriorityQueue::new(); pq.push(0, Default::default()); // Uuids will be different pq.push(1, Default::default()); let serialized = serde_json::to_string(&pq).unwrap(); println!("serialized = {:?}", serialized); let deserialized: PqType = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); } ////////////////////////////////////////////////////////////////////////////// // Test 3 ////////////////////////////////////////////////////////////////////////////// #[test] fn test3() { println!("\n\ntest3()"); // Create some concrete events and comparables, and test to see that they // can be serialized/deserialized let ce1 = ConcreteEvent1 { a: 12, b: 45 }; let ec1 = EventComparables { activation_date: ActivationDate::new(0, 1), id: Uuid::new_v4(), }; let ce2 = ConcreteEvent1 { a: 37, b: 123 }; let ec2 = EventComparables { activation_date: ActivationDate::new(0, 1), id: Uuid::new_v4(), }; let serialized = serde_json::to_string(&ce1).unwrap(); println!("serialized = {:?}", serialized); let deserialized: ConcreteEvent1 = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); assert_eq!(ce1, deserialized); let serialized = serde_json::to_string(&ec1).unwrap(); println!("serialized = {:?}", serialized); let deserialized: EventComparables = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); assert_eq!(ec1, deserialized); let serialized = serde_json::to_string(&ce2).unwrap(); println!("serialized = {:?}", serialized); let deserialized: ConcreteEvent1 = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); assert_eq!(ce2, deserialized); let serialized = serde_json::to_string(&ec2).unwrap(); println!("serialized = {:?}", serialized); let deserialized: EventComparables = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); assert_eq!(ec2, deserialized); { type PqType = PriorityQueue; let mut pq: PqType = PriorityQueue::new(); pq.push(ce1, ec1); pq.push(ce2, ec2); let serialized = serde_json::to_string(&pq).unwrap(); println!("serialized = {:?}", serialized); let deserialized: PqType = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); } } }