#mutable #reference #mut #split #ref #multiple-values

splitmut

Safely retrieves multiple mutable values from the same collection

2 unstable releases

Uses old Rust 2015

0.2.1 Feb 27, 2018
0.1.1 Feb 5, 2016
0.1.0 Feb 4, 2016

#1266 in Rust patterns

Download history 3224/week @ 2023-11-23 4865/week @ 2023-11-30 4368/week @ 2023-12-07 3895/week @ 2023-12-14 3232/week @ 2023-12-21 2869/week @ 2023-12-28 5215/week @ 2024-01-04 4034/week @ 2024-01-11 5525/week @ 2024-01-18 4680/week @ 2024-01-25 4000/week @ 2024-02-01 3583/week @ 2024-02-08 4612/week @ 2024-02-15 6361/week @ 2024-02-22 7266/week @ 2024-02-29 3196/week @ 2024-03-07

22,460 downloads per month
Used in 4 crates (via indexical)

Apache-2.0/MIT

17KB
199 lines

SplitMut

A Rust library for safely retrieving multiple mutable values within the same collection.

API Documentation Crates.io

get2_mut, get3_mut and get4_mut return a tuple or 2, 3 or 4 values, each one of them being one of:

  • Ok(&mut V)
  • Err(SplitMutError::NoValue) in case there was no value for the key (i e, when your usual get_mut would have returned None)
  • Err(SplitMutError::SameValue) in case the same value has already been returned earlier in the tuple.

Add use splitmut::SplitMut to your code have these functions implemented for mutable slices, Vec, VecDeque, HashMap and BTreeMap.

Example

extern crate splitmut;

use std::collections::HashMap;
use splitmut::{SplitMut, SplitMutError};

// Create a hashmap
let mut h = HashMap::new();
h.insert(1, "Hello");
h.insert(2, "world");

// Swap two values easily
{
    let (m1, m2) = h.get2_mut(&1, &2);
    std::mem::swap(m1.unwrap(), m2.unwrap());
}
assert_eq!(h.get(&1), Some(&"world"));
assert_eq!(h.get(&2), Some(&"Hello"));

// Show error handling
let (m0, m1a, m1b) = h.get3_mut(&0, &1, &1);
// No value for the key "0"
assert_eq!(m0, Err(SplitMutError::NoValue));
// First value for the key "1" is returned successfully
assert_eq!(m1a, Ok(&mut "world"));
// Second value for the key "1" returns an error
assert_eq!(m1b, Err(SplitMutError::SameValue));

No runtime deps