Skip to content

Commit

Permalink
Merge pull request 822 from deankarn/master
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Nov 13, 2021
2 parents 5c4f8b2 + 2e5b990 commit 37da27f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
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> {
}
}

/// Retains only the elements specified by the predicate.
///
/// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)`
/// returns `false`.
#[cfg(not(no_btreemap_retain))]
#[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
11 changes: 11 additions & 0 deletions tests/map.rs
Expand Up @@ -34,3 +34,14 @@ fn test_append() {
assert_eq!(keys, EXPECTED);
assert!(val.is_empty());
}

#[cfg(not(no_btreemap_retain))]
#[test]
fn test_retain() {
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, &["a", "c"]);
}

0 comments on commit 37da27f

Please sign in to comment.