#059 Apr 2026

59. split_first_chunk — Destructure Slices into Arrays

Parsing a header from a byte buffer? Extracting the first N elements of a slice? split_first_chunk hands you a fixed-size array and the remainder in one call — no manual indexing, no panics.

The Problem

You have a byte slice and need to pull out a fixed-size prefix — say a 4-byte magic number or a 2-byte length field. The manual approach is fragile:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
fn parse_header(data: &[u8]) -> Option<([u8; 4], &[u8])> {
    if data.len() < 4 {
        return None;
    }
    let header: [u8; 4] = data[..4].try_into().unwrap();
    let rest = &data[4..];
    Some((header, rest))
}

fn main() {
    let packet = b"RUST is awesome";
    let (header, rest) = parse_header(packet).unwrap();
    assert_eq!(&header, b"RUST");
    assert_eq!(rest, b" is awesome");
}

That try_into().unwrap() is ugly, and if you get the index arithmetic wrong, you get a panic at runtime.

After: split_first_chunk

Stabilized in Rust 1.77, split_first_chunk splits a slice into a &[T; N] array reference and the remaining slice — returning None if the slice is too short:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fn parse_header(data: &[u8]) -> Option<(&[u8; 4], &[u8])> {
    data.split_first_chunk::<4>()
}

fn main() {
    let packet = b"RUST is awesome";
    let (magic, rest) = parse_header(packet).unwrap();
    assert_eq!(magic, b"RUST");
    assert_eq!(rest, b" is awesome");

    // Too short — returns None instead of panicking
    let tiny = b"RS";
    assert!(tiny.split_first_chunk::<4>().is_none());
}

One method call. No manual slicing, no try_into, and the const generic N ensures the compiler knows the exact array size.

Chaining Chunks for Protocol Parsing

Real protocols have multiple fields. Chain split_first_chunk calls to peel them off one at a time:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fn parse_packet(data: &[u8]) -> Option<([u8; 2], [u8; 4], &[u8])> {
    let (version, rest) = data.split_first_chunk::<2>()?;
    let (length, payload) = rest.split_first_chunk::<4>()?;
    Some((*version, *length, payload))
}

fn main() {
    let raw = b"\x01\x02\x00\x00\x00\x05hello";
    let (version, length, payload) = parse_packet(raw).unwrap();

    assert_eq!(version, [0x01, 0x02]);
    assert_eq!(length, [0x00, 0x00, 0x00, 0x05]);
    assert_eq!(payload, b"hello");
}

Each ? short-circuits if the remaining data is too short. No bounds checks scattered across your code.

From the Other End: split_last_chunk

Need to grab a suffix instead — like a trailing checksum? split_last_chunk mirrors the API from the back:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fn strip_checksum(data: &[u8]) -> Option<(&[u8], &[u8; 2])> {
    data.split_last_chunk::<2>()
}

fn main() {
    let msg = b"payload\xAB\xCD";
    let (body, checksum) = strip_checksum(msg).unwrap();
    assert_eq!(body, b"payload");
    assert_eq!(checksum, &[0xAB, 0xCD]);

    let short = b"\x01";
    assert!(strip_checksum(short).is_none());
}

Same safety, same ergonomics — just peeling from the tail.

The Full Family

These methods come in mutable variants too, all stabilized in 1.77:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
fn main() {
    // Immutable — borrow array refs from a slice
    let data: &[u8] = &[1, 2, 3, 4, 5];
    let (head, tail) = data.split_first_chunk::<2>().unwrap();
    assert_eq!(head, &[1, 2]);
    assert_eq!(tail, &[3, 4, 5]);

    // split_last_chunk — from the back
    let (init, last) = data.split_last_chunk::<2>().unwrap();
    assert_eq!(init, &[1, 2, 3]);
    assert_eq!(last, &[4, 5]);

    // first_chunk / last_chunk — just the array, no remainder
    let first: &[u8; 3] = data.first_chunk::<3>().unwrap();
    assert_eq!(first, &[1, 2, 3]);

    let last: &[u8; 3] = data.last_chunk::<3>().unwrap();
    assert_eq!(last, &[3, 4, 5]);
}

Wherever you reach for &data[..N] and a try_into(), there’s probably a chunk method that does it better. Type-safe, bounds-checked, and zero-cost.

#058 Apr 2026

58. Option::is_none_or — The Guard Clause You Were Missing

You know is_some_and — it checks if the Option holds a value matching a predicate. But what about “it’s fine if it’s missing, just validate it when it’s there”? That’s is_none_or.

The Problem

You have an optional field and want to validate it only when present. Without is_none_or, this gets awkward fast:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
struct Query {
    max_results: Option<usize>,
}

fn is_valid(q: &Query) -> bool {
    // "None is fine, but if set, must be ≤ 100"
    match q.max_results {
        None => true,
        Some(n) => n <= 100,
    }
}

fn main() {
    assert!(is_valid(&Query { max_results: None }));
    assert!(is_valid(&Query { max_results: Some(50) }));
    assert!(!is_valid(&Query { max_results: Some(200) }));
}

That match is fine once, but when you’re validating five optional fields, it bloats your code.

After: is_none_or

Stabilized in Rust 1.82, is_none_or collapses the pattern into a single call — returns true if the Option is None, or applies the predicate if it’s Some:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
struct Query {
    max_results: Option<usize>,
    page: Option<usize>,
    prefix: Option<String>,
}

fn is_valid(q: &Query) -> bool {
    q.max_results.is_none_or(|n| n <= 100)
        && q.page.is_none_or(|p| p >= 1)
        && q.prefix.is_none_or(|s| !s.is_empty())
}

fn main() {
    let good = Query {
        max_results: Some(50),
        page: Some(1),
        prefix: None,
    };
    assert!(is_valid(&good));

    let bad = Query {
        max_results: Some(200),
        page: Some(0),
        prefix: Some(String::new()),
    };
    assert!(!is_valid(&bad));

    let empty = Query {
        max_results: None,
        page: None,
        prefix: None,
    };
    assert!(is_valid(&empty));
}

Three fields validated in three clean lines. Every None passes, every Some must satisfy the predicate.

is_some_and vs is_none_or — Pick the Right Default

Think of it this way — what happens when the value is None?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
fn main() {
    let val: Option<i32> = None;

    // is_some_and: None → false (strict: must be present AND valid)
    assert_eq!(val.is_some_and(|x| x > 0), false);

    // is_none_or: None → true (lenient: absence is acceptable)
    assert_eq!(val.is_none_or(|x| x > 0), true);

    let val = Some(5);

    // Both agree when value is present and valid
    assert_eq!(val.is_some_and(|x| x > 0), true);
    assert_eq!(val.is_none_or(|x| x > 0), true);

    let val = Some(-1);

    // Both agree when value is present and invalid
    assert_eq!(val.is_some_and(|x| x > 0), false);
    assert_eq!(val.is_none_or(|x| x > 0), false);
}

Use is_some_and when a value must be present. Use is_none_or when absence is fine — optional config, nullable API fields, or any “default-if-missing” scenario.

Real-World: Filtering with Optional Criteria

This pattern is perfect for search filters where users only set the criteria they care about:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
struct Filter {
    min_price: Option<f64>,
    category: Option<String>,
}

struct Product {
    name: String,
    price: f64,
    category: String,
}

fn matches(product: &Product, filter: &Filter) -> bool {
    filter.min_price.is_none_or(|min| product.price >= min)
        && filter.category.is_none_or(|cat| product.category == *cat)
}

fn main() {
    let products = vec![
        Product { name: "Laptop".into(), price: 999.0, category: "Electronics".into() },
        Product { name: "Book".into(), price: 15.0, category: "Books".into() },
        Product { name: "Phone".into(), price: 699.0, category: "Electronics".into() },
    ];

    let filter = Filter {
        min_price: Some(100.0),
        category: Some("Electronics".into()),
    };

    let results: Vec<_> = products.iter().filter(|p| matches(p, &filter)).collect();
    assert_eq!(results.len(), 2);
    assert_eq!(results[0].name, "Laptop");
    assert_eq!(results[1].name, "Phone");
}

Every None filter lets everything through. Every Some filter narrows the results. No match statements, no nested ifs — just composable guards.

#057 Apr 2026

57. New Math Constants — GOLDEN_RATIO and EULER_GAMMA in std

Tired of defining your own golden ratio or Euler-Mascheroni constant? As of Rust 1.94, std ships them out of the box — no more copy-pasting magic numbers.

Before: Roll Your Own

If you needed the golden ratio or the Euler-Mascheroni constant before Rust 1.94, you had to define them yourself:

1
2
const PHI: f64 = 1.618033988749895;
const EULER_GAMMA: f64 = 0.5772156649015329;

This works, but it’s error-prone. One wrong digit and your calculations drift. And every project that needs these ends up with its own slightly-different copy.

After: Just Use std

Rust 1.94 added GOLDEN_RATIO and EULER_GAMMA to the standard consts modules for both f32 and f64:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use std::f64::consts::{GOLDEN_RATIO, EULER_GAMMA};

fn main() {
    // Golden ratio: (1 + √5) / 2
    let phi = GOLDEN_RATIO;
    assert!((phi * phi - phi - 1.0).abs() < 1e-10);

    // Euler-Mascheroni constant
    let gamma = EULER_GAMMA;
    assert!((gamma - 0.5772156649015329).abs() < 1e-10);

    println!("φ = {phi}");
    println!("γ = {gamma}");
}

These sit right alongside the constants you already know — PI, TAU, E, SQRT_2, and friends.

Where You’d Actually Use Them

Golden ratio shows up in algorithm design (Fibonacci heaps, golden-section search), generative art, and UI layout proportions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use std::f64::consts::GOLDEN_RATIO;

fn golden_section_dimensions(width: f64) -> (f64, f64) {
    let height = width / GOLDEN_RATIO;
    (width, height)
}

fn main() {
    let (w, h) = golden_section_dimensions(800.0);
    assert!((w / h - GOLDEN_RATIO).abs() < 1e-10);
    println!("Width: {w}, Height: {h:.2}");
}

Euler-Mascheroni constant appears in number theory, harmonic series approximations, and probability:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use std::f64::consts::EULER_GAMMA;

/// Approximate the N-th harmonic number using the
/// asymptotic expansion: H_n ≈ ln(n) + γ + 1/(2n)
fn harmonic_approx(n: u64) -> f64 {
    let nf = n as f64;
    nf.ln() + EULER_GAMMA + 1.0 / (2.0 * nf)
}

fn main() {
    // Exact H_10 = 1 + 1/2 + 1/3 + ... + 1/10
    let exact: f64 = (1..=10).map(|i| 1.0 / i as f64).sum();
    let approx = harmonic_approx(10);

    println!("Exact H_10:  {exact:.6}");
    println!("Approx H_10: {approx:.6}");
    assert!((exact - approx).abs() < 0.01);
}

The Full Lineup

With these additions, std::f64::consts now includes: PI, TAU, E, SQRT_2, SQRT_3, LN_2, LN_10, LOG2_E, LOG2_10, LOG10_2, LOG10_E, FRAC_1_PI, FRAC_1_SQRT_2, FRAC_1_SQRT_2PI, FRAC_2_PI, FRAC_2_SQRT_PI, FRAC_PI_2, FRAC_PI_3, FRAC_PI_4, FRAC_PI_6, FRAC_PI_8, GOLDEN_RATIO, and EULER_GAMMA. That’s a pretty complete toolkit for numerical work — all with full f64 precision, available at compile time.

56. Iterator::map_while — Take While Transforming

Need to take elements from an iterator while a condition holds and transform them at the same time? map_while does both in one step — no awkward take_while + map chains needed.

The Problem

Imagine you’re parsing leading digits from a string. With take_while and map, you’d write something like this:

1
2
3
4
5
6
7
8
9
let input = "42abc";

let digits: Vec<u32> = input
    .chars()
    .take_while(|c| c.is_ascii_digit())
    .map(|c| c.to_digit(10).unwrap())
    .collect();

assert_eq!(digits, vec![4, 2]);

This works, but the condition and the transformation are split across two combinators. The unwrap() in map is also a code smell — you know the char is a digit because take_while checked, but the compiler doesn’t.

The Solution

map_while combines both steps. Your closure returns Some(value) to keep going or None to stop:

1
2
3
4
5
6
7
8
let input = "42abc";

let digits: Vec<u32> = input
    .chars()
    .map_while(|c| c.to_digit(10))
    .collect();

assert_eq!(digits, vec![4, 2]);

char::to_digit already returns Option<u32> — it’s Some(n) for digits and None otherwise. That’s a perfect fit for map_while. No separate condition, no unwrap.

A More Practical Example

Parse key-value config lines until you hit a blank line:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let lines = vec![
    "host=localhost",
    "port=8080",
    "",
    "ignored=true",
];

let config: Vec<(&str, &str)> = lines
    .iter()
    .map_while(|line| line.split_once('='))
    .collect();

assert_eq!(config, vec![("host", "localhost"), ("port", "8080")]);

When split_once('=') hits the empty line "", it returns None — and the iterator stops. Everything after the blank line is skipped, no extra logic required.

map_while vs take_while + map

The key difference: map_while fuses the predicate and the transformation into one closure, which means:

  • No redundant checks — you don’t test a condition in take_while and then repeat similar logic in map.
  • No unwrap — since the closure returns Option, you never need to unwrap inside a subsequent map.
  • Cleaner intent — one combinator says “transform elements until you can’t.”

Reach for map_while whenever your stopping condition and your transformation are two sides of the same coin.

#055 Apr 2026

55. floor_char_boundary — Truncate Strings Without Breaking UTF-8

Ever tried to truncate a string to a byte limit and got a panic because you sliced in the middle of a multi-byte character? floor_char_boundary fixes that.

The Problem

Slicing a string at an arbitrary byte index panics if that index lands inside a multi-byte UTF-8 character:

1
2
3
4
5
6
let s = "Héllo 🦀 world";
// This panics at runtime!
// let truncated = &s[..5]; // 'é' spans bytes 1..3, index 5 is fine here
// but what if we don't know the content?
let s = "🦀🦀🦀"; // each crab is 4 bytes
// &s[..5] would panic — byte 5 is inside the second crab!

You could scan backward byte-by-byte checking is_char_boundary(), but that’s tedious and easy to get wrong.

The Fix: floor_char_boundary

str::floor_char_boundary(index) returns the largest byte position at or before index that sits on a valid character boundary. Its counterpart ceil_char_boundary gives you the smallest position at or after the index.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fn main() {
    let s = "🦀🦀🦀"; // each 🦀 is 4 bytes, total 12 bytes

    // We want ~6 bytes, but byte 6 is inside the second crab
    let i = s.floor_char_boundary(6);
    assert_eq!(i, 4); // rounds down to end of first 🦀
    assert_eq!(&s[..i], "🦀");

    // ceil_char_boundary rounds up instead
    let j = s.ceil_char_boundary(6);
    assert_eq!(j, 8); // rounds up to end of second 🦀
    assert_eq!(&s[..j], "🦀🦀");
}

Real-World Use: Safe Truncation

Here’s a practical helper that truncates a string to fit a byte budget, adding an ellipsis if it was shortened:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
fn truncate(s: &str, max_bytes: usize) -> String {
    if s.len() <= max_bytes {
        return s.to_string();
    }
    let end = s.floor_char_boundary(max_bytes.saturating_sub(3));
    format!("{}...", &s[..end])
}

fn main() {
    let bio = "I love Rust 🦀 and crabs!";
    let short = truncate(bio, 16);
    assert_eq!(short, "I love Rust 🦀...");
    // 'I love Rust 🦀' = 15 bytes + '...' = 18 total
    // Safe! No panics, no broken characters.

    // Short strings pass through unchanged
    assert_eq!(truncate("hi", 10), "hi");
}

No more manual boundary scanning — these two methods handle the UTF-8 dance for you.

54. Cell::update — Modify Interior Values Without the Gymnastics

Tired of writing cell.set(cell.get() + 1) every time you want to tweak a Cell value? Rust 1.88 added Cell::update — one call to read, transform, and write back.

The old way

Cell<T> gives you interior mutability for Copy types, but updating a value always felt clunky:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use std::cell::Cell;

fn main() {
    let counter = Cell::new(0u32);

    // Read, modify, write back — three steps for one logical operation
    counter.set(counter.get() + 1);
    counter.set(counter.get() + 1);
    counter.set(counter.get() + 1);

    assert_eq!(counter.get(), 3);
    println!("Counter: {}", counter.get());
}

You’re calling .get() and .set() in the same expression, which is repetitive and visually noisy — especially when the transformation is more complex than + 1.

Enter Cell::update

Stabilized in Rust 1.88, update takes a closure that receives the current value and returns the new one:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use std::cell::Cell;

fn main() {
    let counter = Cell::new(0u32);

    counter.update(|n| n + 1);
    counter.update(|n| n + 1);
    counter.update(|n| n + 1);

    assert_eq!(counter.get(), 3);
    println!("Counter: {}", counter.get());
}

One call. No repetition of the cell name. The intent — “increment this value” — is immediately clear.

Beyond simple increments

update shines when the transformation is more involved:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use std::cell::Cell;

fn main() {
    let flags = Cell::new(0b0000_1010u8);

    // Toggle bit 0
    flags.update(|f| f ^ 0b0000_0001);
    assert_eq!(flags.get(), 0b0000_1011);

    // Clear the top nibble
    flags.update(|f| f & 0b0000_1111);
    assert_eq!(flags.get(), 0b0000_1011);

    // Saturating shift left
    flags.update(|f| f.saturating_mul(2));
    assert_eq!(flags.get(), 22);

    println!("Flags: {:#010b}", flags.get());
}

Compare that to flags.set(flags.get() ^ 0b0000_0001) — the update version reads like a pipeline of transformations.

A practical example: tracking state in callbacks

Cell::update is especially handy inside closures where you need shared mutable state without reaching for RefCell:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use std::cell::Cell;

fn main() {
    let total = Cell::new(0i64);

    let prices = [199, 450, 85, 320, 1200];
    let discounted: Vec<i64> = prices.iter().map(|&price| {
        let final_price = if price > 500 { price * 9 / 10 } else { price };
        total.update(|t| t + final_price);
        final_price
    }).collect();

    assert_eq!(discounted, vec![199, 450, 85, 320, 1080]);
    assert_eq!(total.get(), 2134);
    println!("Prices: {:?}, Total: {}", discounted, total.get());
}

No RefCell, no runtime borrow checks, no panics — just a clean in-place update.

The signature

1
2
3
impl<T: Copy> Cell<T> {
    pub fn update(&self, f: impl FnOnce(T) -> T);
}

Note the T: Copy bound — this works because Cell copies the value out, passes it to your closure, and copies the result back in. If you need this for non-Copy types, you’ll still want RefCell.

Simple, ergonomic, and long overdue. Available since Rust 1.88.0.

#053 Mar 2026

53. element_offset — Find an Element's Index by Reference

Ever had a reference to an element inside a slice but needed its index? Before Rust 1.94, you’d reach for .position() with value equality or resort to pointer math. Now there’s a cleaner way.

The problem

Imagine you’re scanning a slice and a helper function hands you back a reference to the element it found. You know the reference points somewhere inside your slice, but you need the index — not a value-based search.

1
2
3
fn first_long_word<'a>(words: &'a [&str]) -> Option<&'a &'a str> {
    words.iter().find(|w| w.len() > 5)
}

You could call .position() with value comparison, but that re-scans the slice and compares by value — which is wasteful when you already hold the exact reference.

The solution: element_offset

<[T]>::element_offset takes a reference to an element and returns its Option<usize> index by comparing pointers, not values. If the reference points into the slice, you get Some(index). If it doesn’t, you get None.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fn main() {
    let words = ["hi", "hello", "rustacean", "world"];

    // A helper hands us a reference into the slice
    let found: &&str = words.iter().find(|w| w.len() > 5).unwrap();

    // Get the index by reference identity — no value scan needed
    let index = words.element_offset(found).unwrap();

    assert_eq!(index, 2);
    assert_eq!(words[index], "rustacean");

    println!("Found '{}' at index {}", found, index);
}

Why not .position()?

.position() compares by value and has to walk the slice from the start. element_offset is an O(1) pointer comparison — it checks whether your reference falls within the slice’s memory range and computes the offset directly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
fn main() {
    let values = [10, 20, 10, 30];

    let third = &values[2]; // points at the second '10'

    // position() finds the FIRST 10 (index 0) — wrong!
    let by_value = values.iter().position(|v| v == third);
    assert_eq!(by_value, Some(0));

    // element_offset() finds THIS exact element (index 2) — correct!
    let by_ref = values.element_offset(third);
    assert_eq!(by_ref, Some(2));

    println!("By value: {:?}, By reference: {:?}", by_value, by_ref);
}

This distinction matters whenever your slice has duplicate values.

When the reference is outside the slice

If the reference doesn’t point into the slice, you get None:

1
2
3
4
5
6
7
8
fn main() {
    let a = [1, 2, 3];
    let outside = &42;

    assert_eq!(a.element_offset(outside), None);

    println!("Outside reference: {:?}", a.element_offset(outside));
}

Clean, safe, and no unsafe pointer arithmetic required. Available since Rust 1.94.0.

52. Peekable::next_if_map — Peek, Match, and Transform in One Step

Tired of peeking at the next element, checking if it matches, and then consuming and transforming it? next_if_map collapses that entire dance into a single call.

The problem

When writing parsers or processing token streams, you often need to conditionally consume the next element and extract something from it. With next_if and peek, you end up doing the work twice — once to check, once to transform:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let mut iter = vec![1_i64, 2, -3, 4].into_iter().peekable();

// Clunky: peek, check, consume, transform — separately
let val = if iter.peek().is_some_and(|n| *n > 0) {
    iter.next().map(|n| n * 10)
} else {
    None
};

assert_eq!(val, Some(10));

It works, but you’re expressing the same logic in two places and the code doesn’t clearly convey its intent.

Enter next_if_map

Stabilized in Rust 1.94, Peekable::next_if_map takes a closure that returns Result<R, I::Item>. Return Ok(transformed) to consume the element, or Err(original) to put it back:

1
2
3
4
5
6
7
8
9
let mut iter = vec![1_i64, 2, -3, 4].into_iter().peekable();

// Clean: one closure handles the check AND the transformation
let val = iter.next_if_map(|n| {
    if n > 0 { Ok(n * 10) } else { Err(n) }
});

assert_eq!(val, Some(10));
assert_eq!(iter.next(), Some(2)); // iterator continues normally

The element is only consumed when you return Ok. If you return Err, the original value goes back and the iterator is unchanged.

Parsing example: extract leading digits

This is where next_if_map really shines — pulling typed tokens out of a character stream:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let mut chars = "42abc".chars().peekable();

let mut number = 0u32;
while let Some(digit) = chars.next_if_map(|c| {
    c.to_digit(10).ok_or(c)
}) {
    number = number * 10 + digit;
}

assert_eq!(number, 42);
assert_eq!(chars.next(), Some('a')); // non-digit stays unconsumed

Each character is inspected once: digits are consumed and converted, and the first non-digit stops the loop without being eaten.

Key details

  • Atomic peek + consume + transform: no redundant checks, no repeated logic
  • Non-destructive on rejection: returning Err(item) puts the element back
  • Also available: next_if_map_mut takes FnOnce(&mut I::Item) -> Option<R> for when you don’t need ownership
  • Stable since Rust 1.94

Next time you’re writing a peek-then-consume pattern, reach for next_if_map — your parser will thank you.

51. File::lock — File Locking in the Standard Library

Multiple processes writing to the same file? That’s a recipe for corruption. Since Rust 1.89, File::lock gives you OS-backed file locking without external crates.

The problem

You have a CLI tool that appends to a shared log file. Two instances run at the same time, and suddenly your log entries are garbled — half a line from one process interleaved with another. Before 1.89, you’d reach for the fslock or file-lock crate. Now it’s built in.

Exclusive locking

File::lock() acquires an exclusive (write) lock. Only one handle can hold an exclusive lock at a time — all other attempts block until the lock is released:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use std::fs::File;
use std::io::{self, Write};

fn main() -> io::Result<()> {
    let mut file = File::options()
        .write(true)
        .create(true)
        .open("/tmp/rustbites_lock_demo.txt")?;

    // Blocks until the lock is acquired
    file.lock()?;

    writeln!(file, "safe write from process {}", std::process::id())?;

    // Lock is released when the file is closed (dropped)
    Ok(())
}

When the File is dropped, the lock is automatically released. No manual unlock() needed — though you can call file.unlock() explicitly if you want to release it early.

Shared (read) locking

Sometimes you want to allow multiple readers but block writers. That’s what lock_shared() is for:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use std::fs::File;
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let mut file = File::open("/tmp/rustbites_lock_demo.txt")?;

    // Multiple processes can hold a shared lock simultaneously
    file.lock_shared()?;

    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    println!("Read: {contents}");

    file.unlock()?; // explicit release
    Ok(())
}

Shared locks coexist with other shared locks, but block exclusive lock attempts. Classic reader-writer pattern, enforced at the OS level.

Non-blocking with try_lock

Don’t want to wait? try_lock() and try_lock_shared() return immediately instead of blocking:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use std::fs::{self, File, TryLockError};

fn main() -> std::io::Result<()> {
    let file = File::options()
        .write(true)
        .create(true)
        .open("/tmp/rustbites_trylock.txt")?;

    match file.try_lock() {
        Ok(()) => println!("Lock acquired!"),
        Err(TryLockError::WouldBlock) => println!("File is busy, try later"),
        Err(TryLockError::Error(e)) => return Err(e),
    }

    Ok(())
}

If another process holds the lock, you get TryLockError::WouldBlock instead of hanging. Perfect for tools that should fail fast rather than block when another instance is already running.

Key details

  • Advisory locks: these locks are advisory on most platforms — they don’t prevent other processes from reading/writing the file unless those processes also use locking
  • Automatic release: locks are released when the File handle is dropped
  • Cross-platform: works on Linux, macOS, and Windows (uses flock on Unix, LockFileEx on Windows)
  • Stable since Rust 1.89

50. slice::chunk_by — Group Consecutive Elements

Need to split a slice into groups of consecutive elements that share a property? chunk_by does exactly that — no allocations, no manual index tracking.

The problem

Imagine you have a sorted list of temperatures and want to group them into runs of non-decreasing values. Without chunk_by, you’d write a loop tracking where each group starts and ends:

1
2
let temps = [18, 20, 22, 19, 21, 25, 24];
// Manual grouping... indices, slicing, off-by-one bugs 😬

Enter chunk_by

Stabilized in Rust 1.77, slice::chunk_by splits a slice between consecutive elements where the predicate returns false. Each chunk is a sub-slice where every adjacent pair satisfies the predicate:

1
2
3
4
5
6
7
8
9
let temps = [18, 20, 22, 19, 21, 25, 24];

let runs: Vec<&[i32]> = temps.chunk_by(|a, b| a <= b).collect();

assert_eq!(runs, vec![
    &[18, 20, 22] as &[i32],
    &[19, 21, 25],
    &[24],
]);

The predicate |a, b| a <= b keeps elements in the same chunk as long as values are non-decreasing. The moment a value drops, a new chunk begins.

Group by equality

A common use case is grouping runs of equal elements:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let data = [1, 1, 2, 3, 3, 3, 2, 2];

let groups: Vec<&[i32]> = data.chunk_by(|a, b| a == b).collect();

assert_eq!(groups, vec![
    &[1, 1] as &[i32],
    &[2],
    &[3, 3, 3],
    &[2, 2],
]);

Notice this groups consecutive equal elements — it’s not the same as a GROUP BY in SQL. The two runs of 2 stay separate because they aren’t adjacent.

Mutable chunks

There’s also chunk_by_mut if you need to modify elements within each group:

1
2
3
4
5
6
7
8
let mut data = [1, 1, 2, 3, 3, 3, 2, 2];

for chunk in data.chunk_by_mut(|a, b| a == b) {
    // Double the first element in each run
    chunk[0] *= 2;
}

assert_eq!(data, [2, 1, 4, 6, 3, 3, 4, 2]);

Key details

  • Zero-cost: returns sub-slices of the original data — no allocations
  • Predicate sees pairs: |a, b| receives each consecutive pair; a new chunk starts where it returns false
  • Works on any slice: &[T], &mut [T], Vec<T> (via deref)
  • Stable since Rust 1.77

Next time you reach for a manual loop to group consecutive elements, try chunk_by instead.