5 unstable releases
Uses new Rust 2024
| new 0.3.1 | Feb 23, 2026 |
|---|---|
| 0.3.0 | Feb 23, 2026 |
| 0.2.0 | Feb 22, 2026 |
| 0.1.1 | Feb 21, 2026 |
| 0.1.0 | Feb 21, 2026 |
#619 in Rust patterns
44KB
369 lines
split_by_discriminant
split_by_discriminant is a lightweight Rust utility for partitioning a sequence of items by the discriminant of an enum.
It provides two closely-related helpers:
split_by_discriminant— the simple grouping operation.map_by_discriminant— a more flexible variant that applies separate mapping closures to matched and unmatched items, allowing you to change the output types on the fly.
Both are useful when you need to gather all values of a particular variant, operate on them, and then return them to the original collection.
Primary API
split_by_discriminant
Generic function that takes:
- An iterable of items (
items) whose element typeRimplementsBorrow<T>(e.g.&T,&mut T, orT). - An iterable of discriminants (
kinds) to match against; duplicates are ignored.
Returns a SplitByDiscriminant<T, R> containing:
groups: a map from discriminant to aVec<R>of matching items.others: aVec<R>of items whose discriminant was not requested.
Type inference normally deduces the return type; you rarely need to annotate it explicitly.
map_by_discriminant
A more flexible variant of split_by_discriminant that accepts two mapping closures.
The first closure is applied to items whose discriminant is requested, and the second
handles all others. This allows the types of grouped elements and the "others" bucket
to differ, and lets you perform on-the-fly transformations during partitioning.
SplitByDiscriminant<T, G, O> struct
The result of a split. G is the group element type and O is the "others"
element type (defaults to G for split_by_discriminant).
Methods:
into_parts(self)— consume and return(Map<Discriminant<T>, Vec<G>>, Vec<O>). The concrete map type isHashMapby default; enable theindexmapfeature forIndexMap/IndexSetinstead.group(&mut self, id)— borrow a particular group by discriminant.extract_with(&mut self, id, f)— closure-based extraction of inner values;fmaps&mut T → Option<&mut U>. RequiresG: BorrowMut<T>.map_groups(self, f)— transform every group at once, consumingself.map_others(self, f)— transform the others vector, consumingself.
ExtractFrom<T, U> trait
pub trait ExtractFrom<T, U> {
fn extract_from<'a>(&self, t: &'a mut T) -> Option<&'a mut U>;
}
Implement this on a local extractor type to describe how to borrow a &mut U
from a &mut T. Because the impl is on your type (not on T), the orphan rule
is satisfied even when T and U both come from external crates.
SplitWithExtractor<T, G, O, E> struct
Wraps a SplitByDiscriminant by binding it to an extractor E. Provides an
ergonomic extract(disc) that requires no closure at the call site —
U is resolved via E: ExtractFrom<T, U>.
Methods available directly on SplitWithExtractor:
group— forwarded from the inner split.extract_with— forwarded from the inner split.extract<U>(&mut self, id)— ergonomic extraction via the bound extractor.into_inner(self) -> SplitByDiscriminant<T, G, O>— unwrap to reach consuming methods (into_parts,map_groups,map_others).
Construct with SplitWithExtractor::new(split, extractor).
Four-crate pattern (foreign enums)
The orphan rule prevents implementing a trait from crate A on a type from crate B
inside a third crate C. SplitWithExtractor + ExtractFrom sidestep this completely:
| Crate | Role |
|---|---|
external_enums |
Defines MyEnum. Cannot be changed. |
split_by_discriminant |
This crate. |
user_helper |
Defines a local MyEnumExtractor and implements ExtractFrom<MyEnum, _> on it. Written once, reused everywhere. |
user_downstream |
Calls SplitWithExtractor::extract — no trait impl needed. |
// user_helper
use split_by_discriminant::ExtractFrom;
use external_enums::MyEnum; // foreign — cannot be changed
pub struct MyEnumExtractor; // LOCAL type — orphan rule satisfied
impl ExtractFrom<MyEnum, i32> for MyEnumExtractor {
fn extract_from<'a>(&self, t: &'a mut MyEnum) -> Option<&'a mut i32> {
if let MyEnum::A(v) = t { Some(v) } else { None }
}
}
// user_downstream
use split_by_discriminant::{split_by_discriminant, SplitWithExtractor};
use user_helper::MyEnumExtractor;
let split = split_by_discriminant(&mut data, &[a_disc]);
let mut extractor = SplitWithExtractor::new(split, MyEnumExtractor);
let ints: Vec<&mut i32> = extractor.extract(a_disc).unwrap();
For a one-off extraction without setting up an extractor type, pass a closure
directly to extract_with:
let ints: Vec<&mut i32> = split
.extract_with(a_disc, |e| if let MyEnum::A(v) = e { Some(v) } else { None })
.unwrap();
Examples
use split_by_discriminant::{split_by_discriminant, SplitWithExtractor, ExtractFrom};
use std::mem::discriminant;
#[derive(Debug)]
enum E { A(i32), B(String), C }
struct EExtractor;
impl ExtractFrom<E, i32> for EExtractor {
fn extract_from<'a>(&self, t: &'a mut E) -> Option<&'a mut i32> {
if let E::A(v) = t { Some(v) } else { None }
}
}
let mut data = vec![E::A(1), E::B("hello".into()), E::A(2), E::C];
let a_disc = discriminant(&E::A(0));
let b_disc = discriminant(&E::B(String::new()));
let split = split_by_discriminant(&mut data, &[a_disc, b_disc]);
let mut extractor = SplitWithExtractor::new(split, EExtractor);
// Ergonomic extraction — no closure at the call site.
// Each call lives in its own scope so &mut borrows do not overlap.
{
let ints: Vec<&mut i32> = extractor.extract(a_disc).unwrap();
assert_eq!(ints.len(), 2);
}
// Consuming methods are reached via into_inner().
let (groups, others) = extractor.into_inner().into_parts();
assert_eq!(others.len(), 1); // E::C
You can also pass an owned iterator:
use split_by_discriminant::split_by_discriminant;
use std::mem::discriminant;
#[derive(Debug)] enum E { A(i32), B(String) }
let owned = vec![E::A(4), E::B(String::new())];
let a_disc = discriminant(&E::A(0));
let split = split_by_discriminant(owned.into_iter(), &[a_disc]);
let (groups, _) = split.into_parts();
assert_eq!(groups[&a_disc].len(), 1);
Or use immutable references (extraction not available on immutable refs):
use split_by_discriminant::{split_by_discriminant, SplitByDiscriminant};
use std::mem::discriminant;
#[derive(Debug)] enum E { A(i32), B(String) }
let data = [E::A(2), E::B(String::new())];
let a_disc = discriminant(&E::A(0));
let mut split: SplitByDiscriminant<_, &E> = split_by_discriminant(&data[..], &[a_disc]);
assert_eq!(split.group(a_disc).unwrap().len(), 1);
Use map_by_discriminant when you need to transform matched and unmatched
items during partitioning:
use split_by_discriminant::map_by_discriminant;
use std::mem::discriminant;
#[derive(Debug)]
enum E { A(i32), B }
let data = [E::A(1), E::B];
let a_disc = discriminant(&E::A(0));
let b_disc = discriminant(&E::B);
let mut split = map_by_discriminant(&data[..], &[a_disc, b_disc],
|e| format!("match:{:?}", e),
|e| format!("other:{:?}", e),
);
assert_eq!(split.group(a_disc).unwrap(), &vec!["match:A(1)".to_string()]);
Supported inputs
&mut [T]or&mut Vec<T>→SplitByDiscriminant<T, &mut T>&[T]or&Vec<T>→SplitByDiscriminant<T, &T>- Any owning iterator, e.g.
Vec<T>::into_iter()→R = T
Features
indexmap— useIndexMap/IndexSetinstead ofHashMap/HashSet. Enables deterministic iteration order over groups.
Notes
- Discriminants can be precomputed with
std::mem::discriminantand stored inconsts for reuse. - Items not matching any requested discriminant are preserved in
othersin original order. extract_withandSplitWithExtractor::extractare only available when the group element type implementsBorrowMut<T>(i.e.&mut TorTitself).
Testing
Unit and integration-style tests live in src/tests.rs, including a
foreign_enum_workflow module that demonstrates the four-crate pattern using
std::net::IpAddr as a real foreign enum.
Dependencies
~210KB