FAQ - Help and questions

Why does my ported program print map entries in a different order?

#porting#collections#javascriptpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Languages promise different things about the order of map entries. JavaScript objects order integer-like keys first, then insertion order, and a Map keeps insertion order. A Rust HashMap promises no order and may differ between runs. Use a BTreeMap for sorted keys, a Vec of pairs or sorting for a fixed order.

Checked with rustc 1.93.0, Node.js v22.19.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

If the old program printed entries in a stable order and the port does not, the old program was relying on an ordering guarantee that its language gave and Rust's HashMap does not. Look up what the old container promised, then pick the Rust container that promises the same.

ContainerOrder of iteration
JavaScript objectInteger-like keys in ascending order first, then the other string keys in the order they were added
JavaScript MapInsertion order
Python dictInsertion order (a language guarantee since Python 3.7)
Rust HashMapNot specified; can change between runs and versions
Rust BTreeMapSorted by key
Rust Vec<(K, V)>The order you push

The same four keys in JavaScript (Node.js v22.19.0) show the object rule and the Map rule:

javascript
const o = { b: 1, a: 2, "2": 3, "1": 4 };
console.log(Object.keys(o));
const m = new Map([["b", 1], ["a", 2], ["2", 3], ["1", 4]]);
console.log([...m.keys()]);
text
[ '1', '2', 'b', 'a' ]
[ 'b', 'a', '2', '1' ]

In Rust (rustc 1.93.0), the program below ran twice. The HashMap printed a different order in the two runs; BTreeMap and the Vec printed the same both times:

src/main.rsrust
use std::collections::{BTreeMap, HashMap};

fn main() {
    let pairs = [("b", 1), ("a", 2), ("2", 3), ("1", 4)];
    let h: HashMap<_, _> = pairs.into_iter().collect();
    println!("HashMap  : {:?}", h.keys().collect::<Vec<_>>());
    let b: BTreeMap<_, _> = pairs.into_iter().collect();
    println!("BTreeMap : {:?}", b.keys().collect::<Vec<_>>());
    let v: Vec<_> = pairs.to_vec();
    println!("Vec pairs: {:?}", v.iter().map(|p| p.0).collect::<Vec<_>>());
}
text
(first run)
HashMap  : ["2", "b", "1", "a"]
BTreeMap : ["1", "2", "a", "b"]
Vec pairs: ["b", "a", "2", "1"]
(second run)
HashMap  : ["1", "2", "b", "a"]
BTreeMap : ["1", "2", "a", "b"]
Vec pairs: ["b", "a", "2", "1"]

The HashMap order differs between the runs because the standard HashMap seeds its hash function randomly for each map, as a defence against attacks that craft colliding keys. Your own run will print yet another order, so treat these two as examples of "not stable", not as values to expect.

How to do it#

  1. Find where the old code iterates over a map to produce output (a report, JSON, a log, a test expectation).
  2. If the old order was insertion order and it matters, port the container as a Vec<(K, V)> (small maps) or use an insertion-ordered map crate such as indexmap; that crate was not run for this thread.
  3. If sorted order is acceptable or required, use BTreeMap, or collect the keys into a Vec and sort() before printing.
  4. If order never mattered and only tests broke, fix the tests so that they sort or compare as sets.
  5. Check the golden files from the old program (see the thread on golden files): a test that compares text including map order will fail on every other run if you leave HashMap in.

Common mistakes#

  • Taking the order of the first run as the truth and writing it into a test.
  • Switching to BTreeMap for order when the old order was insertion order: sorted order is different from insertion order.
  • Forgetting that JavaScript objects reorder integer-like keys: a port that reads JSON objects and writes them back may reorder keys even in JavaScript.

Can I make HashMap deterministic?#

You can supply a hasher with a fixed seed, but even then the order is still unspecified. Do not rely on it.

Is BTreeMap slower than HashMap?#

They have different costs for different operations (hashing against comparing and tree walking). This thread did not measure them.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet