Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add retain to Map #822

Merged
merged 9 commits into from Nov 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions build.rs
Expand Up @@ -31,6 +31,12 @@ fn main() {
if minor < 45 {
println!("cargo:rustc-cfg=no_btreemap_remove_entry");
}

// BTreeMap::retain
// https://blog.rust-lang.org/2021/06/17/Rust-1.53.0.html#stabilized-apis
if minor < 53 {
println!("cargo:rustc-cfg=no_btreemap_retain");
}
}

fn rustc_minor_version() -> Option<u32> {
Expand Down
13 changes: 13 additions & 0 deletions src/map.rs
Expand Up @@ -234,6 +234,19 @@ impl Map<String, Value> {
}
}

#[cfg(not(no_btreemap_retain))]
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
/// The elements are visited in ascending key order.
#[inline]
pub fn retain<F>(&mut self, f: F)
where
F: FnMut(&String, &mut Value) -> bool,
{
self.map.retain(f);
}

/// Gets an iterator over the values of the map.
#[inline]
pub fn values(&self) -> Values {
Expand Down
13 changes: 13 additions & 0 deletions tests/map.rs
Expand Up @@ -34,3 +34,16 @@ fn test_append() {
assert_eq!(keys, EXPECTED);
assert!(val.is_empty());
}

#[cfg(not(no_btreemap_retain))]
#[test]
fn test_retain() {
const EXPECTED: &[&str] = &["a", "c"];

let mut v: Value = from_str(r#"{"b":null,"a":null,"c":null}"#).unwrap();
let val = v.as_object_mut().unwrap();
val.retain(|k, _| k.as_str() != "b");

let keys: Vec<_> = val.keys().collect();
assert_eq!(keys, EXPECTED);
}