feat: add display UI with splash screen, dashboard, and RSSI sparkline
Implement full SSD1306 OLED display support: - Splash screen on boot (1.5s) with project name, version, board - Dashboard showing radio state, config, counters, RSSI/SNR - RSSI history sparkline (64-sample ring buffer, 2px-wide bars) - DisplayOn/DisplayOff host commands routed via dedicated channel - Pure render functions against generic DrawTarget (no hardware coupling) - Display on/off control bypasses radio task entirely Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
17624 files changed
+4564928
-38
No files matched your search
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"files":{".cargo_vcs_info.json":"8502e93026ad381038e5c02edab6fc170618c8e8a3b5170fa7f21fa564e2b4f3",".github/FUNDING.yml":"73c9566ed57dc7c3a71f1a97fd0e81f85512f7954d0ac3228de83678bf170bc8",".github/workflows/clippy.yml":"7f7849dcfdaa6ed72737bb67ef58f9f1a65873b9305e4125ae700ee06f72bdf5",".github/workflows/rustfmt.yml":"1d208980bd5e239c25e8aa2d801b78dc97fb170f4228235b9083f74478d96079",".github/workflows/tests.yml":"9efe4debe280953c314321e985c2ef4f5cb6e17fd6f5513f5ece077997ec5692","CHANGELOG.md":"81a7f1d67927c1161f4fb60d9bf3021d7f34ca8362ca45dc7cc84b2c56a336ed","Cargo.toml":"04bf78ae30ebdb1469fd0fb25063b005503e5e1ffcd36c7661da4cbba4f2b958","Cargo.toml.orig":"5b1672ce99ebc55426870061b728bb66c6d7b0e9cd6a60711b819123a0bc4c48","LICENSE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","Makefile":"88d19db43c3f406fdea1978691f7109782b3767e0d909f788ab6d8b7c8c129bd","README.md":"2321d8f66f75808f4fcc8d89b571fa8b88e20456f37af7033ffcec94f8149358","src/lib.rs":"c1bedfddef4d7024d814d69ef2fd592177bbf451aaeb87f84987e7f1080185a6"},"package":"38d1115007560874e373613744c6fba374c17688327a71c1476d1a5954cc857b"}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "235b67db21e70293e6f76c422f4fdde67f9319be"
|
||||
},
|
||||
"path_in_vcs": ""
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
github: [mitsuhiko]
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
name: Clippy
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
components: clippy, rustfmt
|
||||
override: true
|
||||
- name: Run clippy
|
||||
run: make lint
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
name: Rustfmt
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
components: clippy, rustfmt
|
||||
override: true
|
||||
- name: Run rustfmt
|
||||
run: make format-check
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
name: Tests
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
build-latest:
|
||||
name: Test on Latest
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
override: true
|
||||
- name: Test
|
||||
run: make test
|
||||
|
||||
build-stable:
|
||||
name: Build on 1.43.0
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: 1.43.0
|
||||
profile: minimal
|
||||
override: true
|
||||
- name: Test
|
||||
run: cargo check --all-features
|
||||
|
||||
miri-test-latest:
|
||||
name: Miri Test
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: nightly
|
||||
profile: minimal
|
||||
components: miri
|
||||
override: true
|
||||
- name: Miri Test
|
||||
run: make miri-test
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to memo-map are documented here.
|
||||
|
||||
## 0.3.3
|
||||
|
||||
* Added `MemoMap::get_or_insert_owned` and `MemoMap::get_or_try_insert_owned`.
|
||||
|
||||
## 0.3.2
|
||||
|
||||
* Added `MemoMap::get_mut`, `MemoMap::iter_mut` and `MemoMap::values_mut`.
|
||||
|
||||
## 0.3.1
|
||||
|
||||
* Added `MemoMap::replace`.
|
||||
|
||||
## 0.3.0
|
||||
|
||||
* Box up individual values. Previously this crate did not survive
|
||||
resizes of the map in all circumstances. This no longer requiers
|
||||
`StableDeref` now at the cost of potential extra allocations.
|
||||
|
||||
## 0.2.1
|
||||
|
||||
* Fixed an incorrect statement in the readme.
|
||||
|
||||
## 0.2.0
|
||||
|
||||
* Added support for `remove` and `clear`.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
* Initial release.
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2018"
|
||||
rust-version = "1.43"
|
||||
name = "memo-map"
|
||||
version = "0.3.3"
|
||||
authors = ["Armin Ronacher <armin.ronacher@active-4.com>"]
|
||||
description = "A crate implementing a synchronized map for memoization"
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"memo",
|
||||
"upsert",
|
||||
]
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/mitsuhiko/memo-map"
|
||||
Vendored
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
all: test
|
||||
|
||||
build:
|
||||
@cargo build --all-features
|
||||
|
||||
doc:
|
||||
@cargo doc --all-features
|
||||
|
||||
test:
|
||||
@cargo test
|
||||
|
||||
miri-test:
|
||||
@cargo +nightly miri test
|
||||
|
||||
format:
|
||||
@rustup component add rustfmt 2> /dev/null
|
||||
@cargo fmt --all
|
||||
|
||||
format-check:
|
||||
@rustup component add rustfmt 2> /dev/null
|
||||
@cargo fmt --all -- --check
|
||||
|
||||
lint:
|
||||
@rustup component add clippy 2> /dev/null
|
||||
@cargo clippy
|
||||
|
||||
.PHONY: all doc test format format-check lint
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
# memo-map
|
||||
|
||||
[](https://github.com/mitsuhiko/memo-map/actions?query=workflow%3ATests)
|
||||
[](https://crates.io/crates/memo-map)
|
||||
[](https://github.com/mitsuhiko/memo-map/blob/main/LICENSE)
|
||||
[](https://img.shields.io/badge/rust-1.43%2B-orange.svg)
|
||||
[](https://docs.rs/memo-map)
|
||||
|
||||
A concurrent insert only hash map.
|
||||
|
||||
This crate implements a “memo map” which is in many ways similar to a HashMap with some crucial differences:
|
||||
|
||||
* Unlike a regular hash map, a memo map is thread safe and synchronized.
|
||||
* Adding or retrieving keys works through a shared reference, removing only
|
||||
through a mutable reference.
|
||||
* Retrieving a value from a memo map returns a plain old reference.
|
||||
|
||||
```rust
|
||||
use memo_map::MemoMap;
|
||||
|
||||
let memo = MemoMap::new();
|
||||
let one = memo.get_or_insert(&1, || "one".to_string());
|
||||
let one2 = memo.get_or_insert(&1, || "not one".to_string());
|
||||
assert_eq!(one, "one");
|
||||
assert_eq!(one2, "one");
|
||||
```
|
||||
|
||||
## License and Links
|
||||
|
||||
- [Documentation](https://docs.rs/memo-map/)
|
||||
- [Issue Tracker](https://github.com/mitsuhiko/memo-map/issues)
|
||||
- License: [Apache-2.0](https://github.com/mitsuhiko/memo-map/blob/main/LICENSE)
|
||||
|
||||
Vendored
+558
@@ -0,0 +1,558 @@
|
||||
//! A concurrent insert only hash map.
|
||||
//!
|
||||
//! This crate implements a "memo map" which is in many ways similar to a
|
||||
//! [`HashMap`] with some crucial differences:
|
||||
//!
|
||||
//! * Unlike a regular hash map, a memo map is thread safe and synchronized.
|
||||
//! * Adding or retrieving keys works through a shared reference, removing only
|
||||
//! through a mutable reference.
|
||||
//! * Retrieving a value from a memo map returns a plain old reference.
|
||||
//!
|
||||
//! Together these purposes allow one to use this type of structure to
|
||||
//! implement something similar to lazy loading in places where the API
|
||||
//! has been constrained to references before.
|
||||
//!
|
||||
//! The values in the map are individually boxed up so that resizing of the
|
||||
//! map retains the previously issued references.
|
||||
//!
|
||||
//! ```
|
||||
//! use memo_map::MemoMap;
|
||||
//!
|
||||
//! let memo = MemoMap::new();
|
||||
//! let one = memo.get_or_insert(&1, || "one".to_string());
|
||||
//! let one2 = memo.get_or_insert(&1, || "not one".to_string());
|
||||
//! assert_eq!(one, "one");
|
||||
//! assert_eq!(one2, "one");
|
||||
//! ```
|
||||
//!
|
||||
//! # Notes on Iteration
|
||||
//!
|
||||
//! Because the memo map internally uses a mutex it needs to be held during
|
||||
//! iteration. This is potentially dangerous as it means you can easily
|
||||
//! deadlock yourself when trying to use the memo map while iterating. The
|
||||
//! iteration functionality thus has to be used with great care.
|
||||
//!
|
||||
//! # Notes on Removal
|
||||
//!
|
||||
//! Items can be removed from a memo map but this operation requires a mutable
|
||||
//! reference to the memo map. This is so that it can ensure that there are no
|
||||
//! borrows outstanding that would be invalidated through the removal of the item.
|
||||
use std::borrow::Borrow;
|
||||
use std::collections::hash_map::{self, Entry, RandomState};
|
||||
use std::collections::HashMap;
|
||||
use std::convert::Infallible;
|
||||
use std::hash::{BuildHasher, Hash};
|
||||
use std::mem::{transmute, ManuallyDrop};
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
macro_rules! lock {
|
||||
($mutex:expr) => {
|
||||
match $mutex.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! get_mut {
|
||||
(let $target:ident, $mutex:expr) => {
|
||||
let mut $target = $mutex.get_mut();
|
||||
let $target = match $target {
|
||||
Ok(guard) => guard,
|
||||
Err(ref mut poisoned) => poisoned.get_mut(),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/// An insert only, thread safe hash map to memoize values.
|
||||
#[derive(Debug)]
|
||||
pub struct MemoMap<K, V, S = RandomState> {
|
||||
inner: Mutex<HashMap<K, Box<V>, S>>,
|
||||
}
|
||||
|
||||
impl<K: Clone, V: Clone, S: Clone> Clone for MemoMap<K, V, S> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(lock!(self.inner).clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V, S: Default> Default for MemoMap<K, V, S> {
|
||||
fn default() -> Self {
|
||||
MemoMap {
|
||||
inner: Mutex::new(HashMap::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> MemoMap<K, V, RandomState> {
|
||||
/// Creates an empty `MemoMap`.
|
||||
pub fn new() -> MemoMap<K, V, RandomState> {
|
||||
MemoMap {
|
||||
inner: Mutex::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V, S> MemoMap<K, V, S> {
|
||||
/// Creates an empty `MemoMap` which will use the given hash builder to hash
|
||||
/// keys.
|
||||
pub fn with_hasher(hash_builder: S) -> MemoMap<K, V, S> {
|
||||
MemoMap {
|
||||
inner: Mutex::new(HashMap::with_hasher(hash_builder)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V, S> MemoMap<K, V, S>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
S: BuildHasher,
|
||||
{
|
||||
/// Inserts a value into the memo map.
|
||||
///
|
||||
/// This inserts a value for a specific key into the memo map. If the
|
||||
/// key already exists, this method does nothing and instead returns `false`.
|
||||
/// Otherwise the value is inserted and `true` is returned. It's generally
|
||||
/// recommended to instead use [`get_or_insert`](Self::get_or_insert) or
|
||||
/// it's sibling [`get_or_try_insert`](Self::get_or_try_insert).
|
||||
pub fn insert(&self, key: K, value: V) -> bool {
|
||||
let mut inner = lock!(self.inner);
|
||||
match inner.entry(key) {
|
||||
Entry::Occupied(_) => false,
|
||||
Entry::Vacant(vacant) => {
|
||||
vacant.insert(Box::new(value));
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a value into the memo map replacing the old value.
|
||||
///
|
||||
/// This has the same restrictions as [`remove`](Self::remove) and
|
||||
/// [`clear`](Self::clear) in that it requires a mutable reference to
|
||||
/// the map.
|
||||
pub fn replace(&mut self, key: K, value: V) {
|
||||
lock!(self.inner).insert(key, Box::new(value));
|
||||
}
|
||||
|
||||
/// Returns true if the map contains a value for the specified key.
|
||||
///
|
||||
/// The key may be any borrowed form of the map's key type, but [`Hash`] and
|
||||
/// [`Eq`] on the borrowed form must match those for the key type.
|
||||
pub fn contains_key<Q>(&self, key: &Q) -> bool
|
||||
where
|
||||
Q: Hash + Eq + ?Sized,
|
||||
K: Borrow<Q>,
|
||||
{
|
||||
lock!(self.inner).contains_key(key)
|
||||
}
|
||||
|
||||
/// Returns a reference to the value corresponding to the key.
|
||||
///
|
||||
/// The key may be any borrowed form of the map's key type, but [`Hash`] and
|
||||
/// [`Eq`] on the borrowed form must match those for the key type.
|
||||
pub fn get<Q>(&self, key: &Q) -> Option<&V>
|
||||
where
|
||||
Q: Hash + Eq + ?Sized,
|
||||
K: Borrow<Q>,
|
||||
{
|
||||
let inner = lock!(self.inner);
|
||||
let value = inner.get(key)?;
|
||||
Some(unsafe { transmute::<&V, &V>(&**value) })
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the value corresponding to the key.
|
||||
///
|
||||
/// The key may be any borrowed form of the map's key type, but [`Hash`] and
|
||||
/// [`Eq`] on the borrowed form must match those for the key type.
|
||||
pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
|
||||
where
|
||||
Q: Hash + Eq + ?Sized,
|
||||
K: Borrow<Q>,
|
||||
{
|
||||
get_mut!(let map, self.inner);
|
||||
Some(unsafe { transmute::<&mut V, &mut V>(&mut **map.get_mut(key)?) })
|
||||
}
|
||||
|
||||
/// Returns a reference to the value corresponding to the key or inserts.
|
||||
///
|
||||
/// This is the preferred way to work with a memo map: if the value has not
|
||||
/// been in the map yet the creator function is invoked to create the value,
|
||||
/// otherwise the already stored value is returned. The creator function itself
|
||||
/// can be falliable and the error is passed through.
|
||||
///
|
||||
/// If the creator is infallible, [`get_or_insert`](Self::get_or_insert) can be used.
|
||||
pub fn get_or_try_insert<Q, F, E>(&self, key: &Q, creator: F) -> Result<&V, E>
|
||||
where
|
||||
Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
|
||||
K: Borrow<Q>,
|
||||
F: FnOnce() -> Result<V, E>,
|
||||
{
|
||||
let mut inner = lock!(self.inner);
|
||||
let value = if let Some(value) = inner.get(key) {
|
||||
value
|
||||
} else {
|
||||
inner.insert(key.to_owned(), Box::new(creator()?));
|
||||
inner.get(key).unwrap()
|
||||
};
|
||||
Ok(unsafe { transmute::<&V, &V>(&**value) })
|
||||
}
|
||||
|
||||
/// Like [`get_or_insert`](Self::get_or_insert) but with an owned key.
|
||||
pub fn get_or_insert_owned<F>(&self, key: K, creator: F) -> &V
|
||||
where
|
||||
F: FnOnce() -> V,
|
||||
{
|
||||
self.get_or_try_insert_owned(key, || Ok::<_, Infallible>(creator()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Like [`get_or_try_insert`](Self::get_or_try_insert) but with an owned key.
|
||||
///
|
||||
/// If the creator is infallible, [`get_or_insert_owned`](Self::get_or_insert_owned) can be used.
|
||||
pub fn get_or_try_insert_owned<F, E>(&self, key: K, creator: F) -> Result<&V, E>
|
||||
where
|
||||
F: FnOnce() -> Result<V, E>,
|
||||
{
|
||||
let mut inner = lock!(self.inner);
|
||||
let entry = inner.entry(key);
|
||||
let value = match entry {
|
||||
Entry::Occupied(ref val) => val.get(),
|
||||
Entry::Vacant(entry) => entry.insert(Box::new(creator()?)),
|
||||
};
|
||||
Ok(unsafe { transmute::<&V, &V>(&**value) })
|
||||
}
|
||||
|
||||
/// Returns a reference to the value corresponding to the key or inserts.
|
||||
///
|
||||
/// This is the preferred way to work with a memo map: if the value has not
|
||||
/// been in the map yet the creator function is invoked to create the value,
|
||||
/// otherwise the already stored value is returned.
|
||||
///
|
||||
/// If the creator is fallible, [`get_or_try_insert`](Self::get_or_try_insert) can be used.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use memo_map::MemoMap;
|
||||
/// let memo = MemoMap::new();
|
||||
///
|
||||
/// // first time inserts
|
||||
/// let value = memo.get_or_insert("key", || "23");
|
||||
/// assert_eq!(*value, "23");
|
||||
///
|
||||
/// // second time returns old value
|
||||
/// let value = memo.get_or_insert("key", || "24");
|
||||
/// assert_eq!(*value, "23");
|
||||
/// ```
|
||||
pub fn get_or_insert<Q, F>(&self, key: &Q, creator: F) -> &V
|
||||
where
|
||||
Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
|
||||
K: Borrow<Q>,
|
||||
F: FnOnce() -> V,
|
||||
{
|
||||
self.get_or_try_insert(key, || Ok::<_, Infallible>(creator()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Removes a key from the memo map, returning the value at the key if the key
|
||||
/// was previously in the map.
|
||||
///
|
||||
/// A key can only be removed if a mutable reference to the memo map exists.
|
||||
/// In other words a key can not be removed if there can be borrows to the item.
|
||||
pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
|
||||
where
|
||||
Q: Hash + Eq + ?Sized,
|
||||
K: Borrow<Q>,
|
||||
{
|
||||
lock!(self.inner).remove(key).map(|x| *x)
|
||||
}
|
||||
|
||||
/// Clears the map, removing all elements.
|
||||
pub fn clear(&mut self) {
|
||||
lock!(self.inner).clear();
|
||||
}
|
||||
|
||||
/// Returns the number of items in the map.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use memo_map::MemoMap;
|
||||
/// let memo = MemoMap::new();
|
||||
///
|
||||
/// assert_eq!(memo.len(), 0);
|
||||
/// memo.insert(1, "a");
|
||||
/// memo.insert(2, "b");
|
||||
/// memo.insert(2, "not b");
|
||||
/// assert_eq!(memo.len(), 2);
|
||||
/// ```
|
||||
pub fn len(&self) -> usize {
|
||||
lock!(self.inner).len()
|
||||
}
|
||||
|
||||
/// Returns `true` if the memo map contains no items.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
lock!(self.inner).is_empty()
|
||||
}
|
||||
|
||||
/// An iterator visiting all key-value pairs in arbitrary order. The
|
||||
/// iterator element type is `(&'a K, &'a V)`.
|
||||
///
|
||||
/// Important note: during iteration the map is locked! This means that you
|
||||
/// must not perform calls to the map or you will run into deadlocks. This
|
||||
/// makes the iterator rather useless in practice for a lot of operations.
|
||||
pub fn iter(&self) -> Iter<'_, K, V, S> {
|
||||
let guard = lock!(self.inner);
|
||||
let iter = guard.iter();
|
||||
Iter {
|
||||
iter: unsafe {
|
||||
transmute::<hash_map::Iter<'_, K, Box<V>>, hash_map::Iter<'_, K, Box<V>>>(iter)
|
||||
},
|
||||
guard: ManuallyDrop::new(guard),
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator visiting all key-value pairs in arbitrary order, with mutable
|
||||
/// references to the values. The iterator element type is `(&'a K, &'a mut V)`.
|
||||
///
|
||||
/// This iterator requires a mutable reference to the map.
|
||||
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
|
||||
get_mut!(let map, self.inner);
|
||||
IterMut {
|
||||
iter: unsafe {
|
||||
transmute::<hash_map::IterMut<'_, K, Box<V>>, hash_map::IterMut<'_, K, Box<V>>>(
|
||||
map.iter_mut(),
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator visiting all values mutably in arbitrary order. The iterator
|
||||
/// element type is `&'a mut V`.
|
||||
///
|
||||
/// This iterator requires a mutable reference to the map.
|
||||
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
|
||||
get_mut!(let map, self.inner);
|
||||
ValuesMut {
|
||||
iter: unsafe {
|
||||
transmute::<hash_map::ValuesMut<'_, K, Box<V>>, hash_map::ValuesMut<'_, K, Box<V>>>(
|
||||
map.values_mut(),
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator visiting all keys in arbitrary order. The iterator element
|
||||
/// type is `&'a K`.
|
||||
pub fn keys(&self) -> Keys<'_, K, V, S> {
|
||||
Keys { iter: self.iter() }
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator over the items of a [`MemoMap`].
|
||||
///
|
||||
/// This struct is created by the [`iter`](MemoMap::iter) method on [`MemoMap`].
|
||||
/// See its documentation for more information.
|
||||
pub struct Iter<'a, K, V, S> {
|
||||
guard: ManuallyDrop<MutexGuard<'a, HashMap<K, Box<V>, S>>>,
|
||||
iter: hash_map::Iter<'a, K, Box<V>>,
|
||||
}
|
||||
|
||||
impl<'a, K, V, S> Drop for Iter<'a, K, V, S> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ManuallyDrop::drop(&mut self.guard);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, K, V, S> Iterator for Iter<'a, K, V, S> {
|
||||
type Item = (&'a K, &'a V);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.iter.next().map(|(k, v)| (k, &**v))
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator over the keys of a [`MemoMap`].
|
||||
///
|
||||
/// This struct is created by the [`keys`](MemoMap::keys) method on [`MemoMap`].
|
||||
/// See its documentation for more information.
|
||||
pub struct Keys<'a, K, V, S> {
|
||||
iter: Iter<'a, K, V, S>,
|
||||
}
|
||||
|
||||
impl<'a, K, V, S> Iterator for Keys<'a, K, V, S> {
|
||||
type Item = &'a K;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.iter.next().map(|(k, _)| k)
|
||||
}
|
||||
}
|
||||
|
||||
/// A mutable iterator over a [`MemoMap`].
|
||||
pub struct IterMut<'a, K, V> {
|
||||
iter: hash_map::IterMut<'a, K, Box<V>>,
|
||||
}
|
||||
|
||||
impl<'a, K, V> Iterator for IterMut<'a, K, V> {
|
||||
type Item = (&'a K, &'a mut V);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.iter.next().map(|(k, v)| (k, &mut **v))
|
||||
}
|
||||
}
|
||||
|
||||
/// A mutable iterator over a [`MemoMap`].
|
||||
pub struct ValuesMut<'a, K, V> {
|
||||
iter: hash_map::ValuesMut<'a, K, Box<V>>,
|
||||
}
|
||||
|
||||
impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
|
||||
type Item = &'a mut V;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.iter.next().map(|v| &mut **v)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_insert() {
|
||||
let memo = MemoMap::new();
|
||||
assert!(memo.insert(23u32, Box::new(1u32)));
|
||||
assert!(!memo.insert(23u32, Box::new(2u32)));
|
||||
assert_eq!(memo.get(&23u32).cloned(), Some(Box::new(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_iter() {
|
||||
let memo = MemoMap::new();
|
||||
memo.insert(1, "one");
|
||||
memo.insert(2, "two");
|
||||
memo.insert(3, "three");
|
||||
let mut values = memo.iter().map(|(k, v)| (*k, *v)).collect::<Vec<_>>();
|
||||
values.sort();
|
||||
assert_eq!(values, vec![(1, "one"), (2, "two"), (3, "three")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_keys() {
|
||||
let memo = MemoMap::new();
|
||||
memo.insert(1, "one");
|
||||
memo.insert(2, "two");
|
||||
memo.insert(3, "three");
|
||||
let mut values = memo.keys().map(|k| *k).collect::<Vec<_>>();
|
||||
values.sort();
|
||||
assert_eq!(values, vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_contains() {
|
||||
let memo = MemoMap::new();
|
||||
memo.insert(1, "one");
|
||||
assert!(memo.contains_key(&1));
|
||||
assert!(!memo.contains_key(&2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remove() {
|
||||
let mut memo = MemoMap::new();
|
||||
memo.insert(1, "one");
|
||||
let value = memo.get(&1);
|
||||
assert!(value.is_some());
|
||||
let old_value = memo.remove(&1);
|
||||
assert_eq!(old_value, Some("one"));
|
||||
let value = memo.get(&1);
|
||||
assert!(value.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clear() {
|
||||
let mut memo = MemoMap::new();
|
||||
memo.insert(1, "one");
|
||||
memo.insert(2, "two");
|
||||
assert_eq!(memo.len(), 2);
|
||||
assert!(!memo.is_empty());
|
||||
memo.clear();
|
||||
assert_eq!(memo.len(), 0);
|
||||
assert!(memo.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ref_after_resize() {
|
||||
let memo = MemoMap::new();
|
||||
let mut refs = Vec::new();
|
||||
|
||||
let iterations = if cfg!(miri) { 100 } else { 10000 };
|
||||
|
||||
for key in 0..iterations {
|
||||
refs.push((key, memo.get_or_insert(&key, || Box::new(key))));
|
||||
}
|
||||
for (key, val) in refs {
|
||||
dbg!(key, val);
|
||||
assert_eq!(memo.get(&key), Some(val));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ref_after_resize_owned() {
|
||||
let memo = MemoMap::new();
|
||||
let mut refs = Vec::new();
|
||||
|
||||
let iterations = if cfg!(miri) { 100 } else { 10000 };
|
||||
|
||||
for key in 0..iterations {
|
||||
refs.push((
|
||||
key,
|
||||
memo.get_or_insert_owned(key.to_string(), || Box::new(key)),
|
||||
));
|
||||
}
|
||||
for (key, val) in refs {
|
||||
dbg!(key, val);
|
||||
assert_eq!(memo.get(&key.to_string()), Some(val));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_replace() {
|
||||
let mut memo = MemoMap::new();
|
||||
memo.insert("foo", "bar");
|
||||
memo.replace("foo", "bar2");
|
||||
assert_eq!(memo.get("foo"), Some(&"bar2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_mut() {
|
||||
let mut memo = MemoMap::new();
|
||||
memo.insert("foo", "bar");
|
||||
*memo.get_mut("foo").unwrap() = "bar2";
|
||||
assert_eq!(memo.get("foo"), Some(&"bar2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_iter_mut() {
|
||||
let mut memo = MemoMap::new();
|
||||
memo.insert("foo", "bar");
|
||||
for item in memo.iter_mut() {
|
||||
*item.1 = "bar2";
|
||||
}
|
||||
assert_eq!(memo.get("foo"), Some(&"bar2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_values_mut() {
|
||||
let mut memo = MemoMap::new();
|
||||
memo.insert("foo", "bar");
|
||||
for item in memo.values_mut() {
|
||||
*item = "bar2";
|
||||
}
|
||||
assert_eq!(memo.get("foo"), Some(&"bar2"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user