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 operation. Every parameter has a clear responsibility:
| Parameter | Role |
|---|---|
T |
The underlying enum (or any type with a Discriminant). Used to |
compute the map keys (Discriminant<T>) and for Borrow<T> bounds on |
|
| input items. | |
G |
Type stored inside each matching group. Defaults to the iterator's |
item type, but may be transformed by map_by_discriminant (e.g. |
|
String, &mut i32, etc.). |
|
O |
Type stored in the “others” bucket. Defaults to G to make the |
| common case ergonomic, but you can choose a different type to handle | |
unmatched items specially (e.g. map them to () or a count). |
The generic trio lets you express use cases where the group and
others types differ without resorting to enum or Box<dyn>.
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
A thin wrapper around SplitByDiscriminant that pairs it with an extractor
value E. The four type parameters serve these roles:
T– the enum/Discriminanttarget, carried through from the inner split.G– group element type; forwarded fromSplitByDiscriminant.O– others element type; also forwarded and defaults toGwhen the split is originally constructed.E– the extractor type that implementsExtractFrom<T, U>for one or more output typesU. The extractor is usually a zero-sized local struct; its purpose is to give you a constraint that allowsextract::<U>to infer the rightUwithout a closure. Because the impl lives on your local type, the orphan rule is satisfied even whenTandUare foreign.
With this design every parameter can vary independently and has a real use case in the docs and tests.
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.