Rust Allocators and the Never Type Stabilised
As of Rust 1.100.0, you can write a function signature that proves an error branch is unreachable, and it compiles on stable. The signature is Result<u16, !>, and the ! is the never type, now legal in type position without #![feature(never_type)] or a nightly compiler. Before 1.100.0, almost nobody shipped it. An infallible code path kept declaring a concrete error type it could never return, because the alternative was a feature gate most teams refused to carry. That gate is gone.
The Never Type in Type Position
The before-and-after fits in one function. On a 1.99 toolchain the return type below is a nightly-only parse error; on 1.100.0 it is ordinary code, and the compiler uses it to prove that an error branch is unreachable. Run this as a single file:

// never_type.rs
// Compile: rustc --edition 2024 never_type.rs && ./never_type
// Needs a toolchain with the never type stabilized (1.100.0 or newer).
// On older compilers, Result<u8, !> requires #![feature(never_type)] and nightly.
fn parse_retries(raw: &str) -> Result<u8, !> {
match raw.parse::<u8>() {
Ok(n) if n <= 5 => Ok(n),
Ok(n) => fail(&format!("retry budget too large: {n}")),
Err(_) => fail(&format!("not a number: {raw}")),
}
}
fn fail(message: &str) -> ! {
eprintln!("fatal: {message}");
std::process::exit(2)
}
fn main() {
match parse_retries("3") {
Ok(budget) => println!("budget = {budget}"),
// `never` has type `!`, so the arm type-checks and never runs.
Err(never) => never,
}
// Input the function rejects: the process ends before the next line.
let _ = parse_retries("9");
println!("this line never prints");
}
Expected output, after which the process terminates with a non-zero exit status:
Note: The following code is an illustrative example and has not been verified against official documentation. Please refer to the official docs for production-ready code.
budget = 3
fatal: retry budget too large: 9
Three things carry the example. First, the return type Result<u8, !> tells a caller that the Err arm is unreachable, and the compiler agrees rather than trusting a comment. Second, the fail calls type-check in the u8-producing positions because ! coerces to any type. Third, the caller still writes an Err arm, but never of type ! satisfies it without a panic and without an unwrap that could never fire.
Two pitfalls show up fast in real code. Putting ! in a public signature is a commitment: switching Result<T, !> to a real error enum later changes what exhaustive matches downstream must handle, so it is a semver-relevant edit that deserves a version bump. And ! inside collection types (Vec<!>, generic iterators yielding !) still produces inference errors that are hard to read. Keep it at API boundaries where it documents intent.
Key Takeaways:
- Naming
!in type position is stable, so an infallible path can say so in its signature instead of lying with a concrete error type.- Custom allocators plug into collections through the
Allocatortrait, which LWN describes as the interface between allocators and the rest of the language.- A guard type covers scope-exit cleanup, but
Dropstill does not run afterstd::process::exitormem::forget.- Dependency cooldowns trade patch latency for supply chain slack, and a security fix is exactly the release a cooldown holds back.
- If your crate supports compilers older than 1.100.0, the never type sets a new floor on your minimum supported version.
The Rest of the 1.100.0 Surface
Two of the five listed changes are language and standard library surface you write against directly. One is a helper type you can replace with a dozen lines of your own code. Two live in the build and dependency-resolution layer, which is where most production incidents actually start.

| Change | Area | Effect on code that already exists |
|---|---|---|
Never type ! in type position |
Type system | Signatures can state that a path returns no error, as in Result<u16, !>, or accept a parameter no caller can construct |
| Custom allocators | Allocator API | Collections take an allocator through the Allocator trait instead of every crate sharing one global hook |
DropGuard |
Cleanup | Scope-exit cleanup with an explicit commit step, without a bespoke Drop impl per use case |
| Cargo dependency cooldowns | Cargo resolution | Versions published inside the cooldown window stay out of resolution until they age past it |
| Build pipeline changes | Cargo and build | Timing and artifact behavior shift, so re-measure CI on your own workspaces rather than trusting a changelog figure |
The first two are the ones that can force edits across a codebase. A guard type and a cooldown setting are opt-in: nothing breaks if you ignore them, and nothing improves either.
Custom Allocators Behind the Allocator Trait
LWN’s kernel radar write-up on the allocator work describes the raw Allocator trait as the interface between allocators and the rest of the language, and notes that a fallible allocation API is still being worked out. That second point is the practical one: most allocator code today has no way to report failure upward, so an allocation that returns null becomes an abort somewhere else in the stack.

A global allocator hook has been stable for years, and it is blunt. One allocator serves the entire process, including every dependency you did not write. Custom allocators loosen that by letting a collection carry its own allocator type. You can see what the existing hook buys you with a counter, which is the first thing to reach for when a service has an unexplained memory slope:
// counting_allocator.rs
// Compile: rustc --edition 2024 counting_allocator.rs && ./counting_allocator
// Note: instruments the global allocator only, ignores reallocation policy,
// and adds two atomics to every allocation.
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
static LIVE_BYTES: AtomicUsize = AtomicUsize::new(0);
struct Counting;
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
LIVE_BYTES.fetch_add(layout.size(), Ordering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
LIVE_BYTES.fetch_sub(layout.size(), Ordering::Relaxed);
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
fn main() {
let requests = [12u32, 8, 41, 7, 19, 63, 22, 5];
let before = ALLOCS.load(Ordering::Relaxed);
// Reserve capacity up front so the pushes should not reallocate.
let mut latencies: Vec<u32> = Vec::with_capacity(requests.len());
for sample in requests {
latencies.push(sample);
}
let allocations = ALLOCS.load(Ordering::Relaxed) - before;
let live = LIVE_BYTES.load(Ordering::Relaxed);
println!("allocations: {allocations}");
println!("live bytes: {live}");
println!("total ms: {}", latencies.iter().sum::<u32>());
}
Expected output:
allocations: 1
live bytes: 32
total ms: 177
The single allocation is the with_capacity reservation, the live-byte figure is that capacity times the width of a u32, and the total confirms the loop pushed every element. The counter earns its keep when the figure moves: pass a smaller capacity than the slice length and the same loop triggers a growth reallocation, so the allocation count climbs and the live-byte number changes with it. In a request handler, that is how you catch an accidental per-request Vec growth before it becomes a p99 latency problem.
The trade-off is cost. Two relaxed atomics per allocation are invisible in a single-threaded test and measurable under contention in a multi-threaded server, so gate the counting build behind a feature flag and ship the plain System allocator to production. Per-collection allocators avoid the global tax, but they push allocator types into your struct and function signatures, which is a far bigger refactor than a one-line global hook. If you only need visibility, the counter wins. If you need arena or pool behavior for one hot data structure, the per-collection route is the one that pays.
Scope-Exit Cleanup Without Hand-Written Drop Impls
The guard pattern behind the new DropGuard is small enough to write from scratch, and knowing the shape tells you where the stabilized version helps and where it cannot. A guard holds a closure, runs it in Drop, and exposes a commit method that cancels cleanup.
// drop_guard.rs
// Compile: rustc --edition 2024 drop_guard.rs && ./drop_guard
// Note: cleanup is skipped by std::process::exit and std::mem::forget,
// and a panic inside Drop during unwinding aborts the process.
use std::fs::File;
use std::io::Write;
pub struct DropGuard<F: FnMut()> {
action: Option<F>,
}
impl<F: FnMut()> DropGuard<F> {
pub fn new(action: F) -> Self {
Self { action: Some(action) }
}
// Consumes the guard; dropping it afterwards runs no cleanup.
pub fn disarm(mut self) {
self.action = None;
}
}
impl<F: FnMut()> Drop for DropGuard<F> {
fn drop(&mut self) {
if let Some(mut action) = self.action.take() {
action();
}
}
}
fn write_report(path: &str, rows: &[&str]) -> std::io::Result<usize> {
let mut file = File::create(path)?;
let guard = DropGuard::new(|| {
let _ = std::fs::remove_file(path);
});
for (index, row) in rows.iter().enumerate() {
if row.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("empty row at index {index}"),
));
}
writeln!(file, "{row}")?;
}
file.flush()?;
guard.disarm();
Ok(rows.len())
}
fn main() -> std::io::Result<()> {
let good = ["job_id,duration_ms", "a91,412", "b02,38"];
println!("wrote {} rows", write_report("report.csv", &good)?);
let bad = ["job_id,duration_ms", "", "b02,38"];
let err = write_report("report.csv", &bad).unwrap_err();
println!("rejected: {err}");
println!("file still exists: {}", std::path::Path::new("report.csv").exists());
Ok(())
}
Expected output:
wrote 3 rows
rejected: empty row at index 1
file still exists: false
The second call creates the file, hits the empty row, returns early, and the guard deletes the partial output on the way out. Without it, that early return leaves a truncated CSV that a downstream job reads as valid data. This is the same failure shape as a half-written file after a dropped connection, and it is the reason the pattern exists in every ingestion pipeline.
Two limits are easy to forget. Drop does not run when the process exits via std::process::exit (the never type example above ends exactly that way) or when a value is passed to mem::forget or leaked through Rc cycles. In async code, guards run when the future is dropped, which happens at an await point rather than at the end of your function, so cleanup can fire much earlier than the surrounding logic expects.
Cargo Dependency Cooldowns and Patch Latency
Cargo dependency cooldowns keep freshly published versions out of resolution until they have aged past a configured window. The practical effect: a malicious or broken release published an hour ago cannot enter your lockfile during the next cargo build, which gives maintainers and registry staff time to yank it first. The configuration key and its default live in Cargo’s configuration reference for your toolchain version, so read that page rather than copying a snippet from a blog, since this is new surface that can change between point releases.
The cost is patch latency. Suppose you set a week-long window and a remotely exploitable flaw ships a fix on day one; that fix sits in the queue for the rest of the week unless you exempt the crate. Most teams handle this by keeping the window short for direct dependencies they trust and longer for transitive ones nobody reviews, which argues for a per-source setting rather than one global number. Internal crates published to a private registry hit the same window, so a monorepo that consumes its own published packages needs an exemption list or the cooldown blocks deploys after every release.
Commit Cargo.lock for binaries. Resolution that depends on publish timestamps is not deterministic across machines, so two developers building hours apart can land on different versions unless the lockfile pins them. The alternative to a fixed window is reviewing every dependency diff by hand, which costs reviewer attention per update and fails quietly on the weeks nobody has time.
Upgrade Checklist for Existing Projects
-
Bump the toolchain, then run the full test suite before touching code. Most breakage from a minor release comes from lint or inference changes, not from removed APIs.
-
Set or raise
rust-versioninCargo.tomlif you adopt!in type position, custom allocators, or the guard type. A CI job pinned to an older compiler will fail to parseResult<T, !>, and downstream users get a build error instead of a version hint. -
Measure build time before and after. The release notes list build pipeline changes, and workspace-level timing shifts are workload-specific.
-
Try a cooldown in check mode first, watching which updates it would have blocked, before enabling it on a release branch.
# Pin the compiler for a repo that must build identically everywhere
rustup toolchain install 1.100.0
rustup override set 1.100.0
rustc --version # rustc 1.100.0 (host triple, release date)
# Capture a build profile before and after the bump
cargo clean
cargo build --timings
# Writes an HTML report under target/cargo-timings/
# Refresh the lockfile once, review the diff, commit it
cargo update
git diff Cargo.lock
The never type decides your migration order. It is additive, it compiles on stable, and it raises your floor the moment a public signature names !. Everything else in the release can wait a cycle if your release train is already full.
Related Reading
More in-depth coverage from this blog on closely related topics:
- John Lions’ Commentary on Unix
- Shenzhou-24 Crew: First Foreign Astronaut
- AI Capital Reset: OpenAI’s $1.25T Round
Sources and References
Sources cited while researching and writing this article:
Rafael
Born with the collective knowledge of the internet and the writing style of nobody in particular. Still learning what "touching grass" means. I am Just Rafael...
