skip to content

For a Rust order book in a BTreeMap<u64, u32>, how do you query a price band with range, and when does range panic?

level: middleimportance: must knowfreq 50%

answer

  1. anything implementing RangeBounds
  2. Bound::Excluded for a strict edge
  3. walking from the back
  4. start greater than end
  5. equal bounds, both excluded

basics

~20 s

Call range with any RangeBounds value (a..b, ..=b, a.., or a Bound tuple like (Excluded(a), Unbounded)) to iterate only those keys, in order, from either end. It panics when start exceeds end, or when equal bounds are both Excluded.

solid answer

~40 s

`BTreeMap::range` takes any `R: RangeBounds<T>` and returns a double-ended iterator over the entries whose keys fall inside, in ascending order. It descends straight to the first matching key instead of scanning from the smallest one. For an ask book, `asks.range((Excluded(10_000), Unbounded)).next()` is the cheapest ask strictly above 10 000. `asks.range(..=10_100).next_back()` is the highest level at or below 10 100, and `asks.range(10_000..10_100)` walks a half-open band. `range_mut` takes the same bounds but yields `&mut V`, so quantities change in place while keys stay read-only. The docs promise two panics: `start > end`, and `start == end` with both bounds `Excluded`. Validate user-supplied bounds first. With `String` keys, pass `str` bounds as `range::<str, _>((Included("b"), Excluded("c")))`, because `"b".."c"` fails with E0277.

code

rust · 28 lines
rust
use std::collections::BTreeMap;
use std::ops::Bound::{Excluded, Unbounded};

fn main() {
    // Ask side of an order book: price in cents -> resting quantity.
    let mut asks: BTreeMap<u64, u32> = BTreeMap::new();
    for (price, qty) in [(10_050, 7), (10_000, 3), (10_100, 12), (10_200, 5)] {
        asks.insert(price, qty);
    }

    // Best (lowest) ask strictly above 10_000.
    let next = asks.range((Excluded(10_000), Unbounded)).next();
    println!("next ask above 10000: {next:?}");

    // Highest ask at or below 10_100: walk the range from the back.
    let ceiling = asks.range(..=10_100).next_back();
    println!("highest ask <= 10100: {ceiling:?}");

    // Every level in [10_000, 10_100): a price band, ascending.
    let band: Vec<_> = asks.range(10_000..10_100).collect();
    println!("band: {band:?}");

    // Halve the quantity on every level from 10_100 upward, in place.
    for (_, qty) in asks.range_mut(10_100..) {
        *qty /= 2;
    }
    println!("after range_mut: {asks:?}");
}

go deeper

for a junior

Recall that BTreeMap::range takes range syntax like a..b or a..=b and yields the matching entries in ascending key order.

for a middle

Explain Bound::Included, Excluded and Unbounded, the double-ended iterator with next_back, and the two documented panics for inverted or empty-excluded bounds.

for a senior

Treat request-supplied bounds as untrusted: order or validate them before range, and know the String-key Borrow trap that turns a str range into E0277.

for a principal

Weigh exposing range queries in an internal API: they tie callers to an ordered map, which constrains later switching to a hashed or sharded store.

## What `range` accepts `BTreeMap::range` returns an iterator over the entries whose keys lie inside a range. Its signature is generic over **`R: RangeBounds<T>`**, the trait in `std::ops` that describes a start bound and an end bound. Each bound is a **`std::ops::Bound`**: `Included(x)`, `Excluded(x)` or `Unbounded`. Range syntax and explicit tuples both implement the trait: | Argument | Start bound | End bound | |---|---|---| | `a..b` | `Included(a)` | `Excluded(b)` | | `a..=b` | `Included(a)` | `Included(b)` | | `a..` | `Included(a)` | `Unbounded` | | `..=b` | `Unbounded` | `Included(b)` | | `..` | `Unbounded` | `Unbounded` | | `(Excluded(a), Included(b))` | `Excluded(a)` | `Included(b)` | | `(Excluded(a), Unbounded)` | `Excluded(a)` | `Unbounded` | Only the tuple form can **exclude the start**, which is why `Bound` exists at all. The iterator, `btree_map::Range`, is **double-ended**: `next()` walks up from the low end and `next_back()` walks down from the high end. `BTreeSet::range` works the same way over elements. ## Querying an order book Take the ask side of a book as `BTreeMap<u64, u32>`, mapping price in cents to resting quantity. Typical queries map onto one call each: 1. **Next ask strictly above a price**: `asks.range((Excluded(p), Unbounded)).next()`. 2. **Highest level at or below a limit**: `asks.range(..=limit).next_back()`. 3. **Every level in a band**: `asks.range(lo..hi)`, ascending, half-open. 4. **Adjust levels in place**: `asks.range_mut(lo..)` yields `(&u64, &mut u32)`. `range` does not iterate over keys outside the bounds. It descends the tree to the first key inside the range, then stops at the end bound. A filter over `iter()` would start at the smallest key and test every entry. On a book with many levels, that difference is the whole reason to use `range`. ## `range_mut` `range_mut` takes the same arguments and hands out **`&mut V`** while the key stays **`&K`**. You can change quantities but never a price, because changing a key in place would break the sorted order. To move an order to a new price, remove it and insert it again. ## When `range` panics The std docs list two panics, for both `range` and `range_mut`: - **`start > end`**, for example `asks.range(lo..hi)` when a caller swapped `lo` and `hi`. std 1.99.1 panics with `range start is greater than range end in BTreeMap`. - **`start == end` with both bounds `Excluded`**: `(Excluded(5), Excluded(5))` panics with `range start and end are equal and excluded in BTreeMap`. Some ranges that look empty are **not** panics: `5..5` and `5..=5` are valid, and so is `..0`. They just yield nothing, or a single key. Also, in 1.99.1 the check runs during the tree search, so a map that has never held an entry returns an empty iterator even for swapped bounds. Do not rely on that: the documented contract is the panic. **Validate bounds that come from a request** before calling `range`, or build them with `Bound` after ordering them yourself. ## `String` keys and `str` bounds For `BTreeMap<String, u32>`, writing `m.range("b".."c")` fails with **E0277** ("the trait bound `String: Borrow<&str>` is not satisfied"). The range's element type is `&str`, and `String` borrows as `str`, not as `&str`. The working form names the borrowed type and passes a tuple of `Bound<&str>`: ```rust m.range::<str, _>((Included("b"), Excluded("c"))) ``` That works because `(Bound<&T>, Bound<&T>)` implements `RangeBounds<T>` for an unsized `T`. The `Borrow` contract itself is covered with the conversion traits. ## The same calls on `BTreeSet` `BTreeSet::range` takes the same `RangeBounds` argument, has the same two panics, and yields `&T` in ascending order. A set of active order ids, for example, answers "every id from 5 000 up to 6 000" with `ids.range(5_000..6_000)`. A set has no `range_mut`, because its elements are keys and keys are never handed out mutably. To find the nearest element on either side of a value: 1. `set.range(..x).next_back()` gives the largest element **below** `x`; 2. `set.range(x..).next()` gives the smallest element **at or above** `x`. Both are single searches down the tree. Std also has `lower_bound` and `upper_bound` cursors, but they are still unstable (`btree_cursors`), so stable code uses `range`. ## Mistakes to avoid - Assuming `range(a..b)` includes `b`. It does not; use `a..=b`. - Filtering `iter()` for a narrow band of a large map. - Treating a swapped user range as harmless. On a populated map it panics. - Reaching for `range_mut` to "fix" a key. Keys are read-only for a reason.

  • Why does m.range("b".."c") fail to compile on a Rust BTreeMap<String, u32>, and what compiles instead?
    With `"b".."c"` the range's element type is `&str`, so `range` needs `String: Borrow<&str>`, which does not exist. rustc reports E0277. `String` borrows as `str`, so name that type and pass `Bound<&str>` values: `m.range::<str, _>((Included("b"), Excluded("c")))`. Owned bounds such as `"b".to_string().."c".to_string()` also compile, but they allocate.
  • Is BTreeMap::range faster than iter().filter() for a narrow band of a large map?
    Yes. `range` searches down the tree to the first key in bounds and stops yielding at the end bound, so the work is logarithmic plus the entries returned. `iter().filter(...)` starts at the smallest key and tests every entry, which is linear in the map's size however few entries match.
  • Can BTreeMap::range_mut change an order's price?
    No. `range_mut` yields `(&K, &mut V)`, so only values are writable. A key's position depends on its ordering, and editing it in place would corrupt the tree. Remove the entry and insert it under the new price, or use `entry` on the new key.

  • range only accepts two plain values, so an exclusive start needs a filter.
  • range(a..b) on a BTreeMap includes the key b.
  • An inverted range like range(10..5) on a populated map just yields nothing.
  • Filtering iter() is as fast as range for a narrow band.
  • range_mut lets you edit keys as long as the order is preserved.