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
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 ExtractFrom;
use MyEnum; // foreign — cannot be changed
; // LOCAL type — orphan rule satisfied
// user_downstream
use ;
use MyEnumExtractor;
let split = split_by_discriminant;
let mut extractor = new;
let ints: = extractor.extract.unwrap;
For a one-off extraction without setting up an extractor type, pass a closure
directly to extract_with:
let ints: = split
.extract_with
.unwrap;
Examples
use ;
use discriminant;
;
let mut data = vec!;
let a_disc = discriminant;
let b_disc = discriminant;
let split = split_by_discriminant;
let mut extractor = new;
// Ergonomic extraction — no closure at the call site.
// Each call lives in its own scope so &mut borrows do not overlap.
// Consuming methods are reached via into_inner().
let = extractor.into_inner.into_parts;
assert_eq!; // E::C
You can also pass an owned iterator:
use split_by_discriminant;
use discriminant;
let owned = vec!;
let a_disc = discriminant;
let split = split_by_discriminant;
let = split.into_parts;
assert_eq!;
Or use immutable references (extraction not available on immutable refs):
use ;
use discriminant;
let data = ;
let a_disc = discriminant;
let mut split: = split_by_discriminant;
assert_eq!;
Use map_by_discriminant when you need to transform matched and unmatched
items during partitioning:
use map_by_discriminant;
use discriminant;
let data = ;
let a_disc = discriminant;
let b_disc = discriminant;
let mut split = map_by_discriminant;
assert_eq!;
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.