A port of d3-hierarchy 3.1.2
(tag 7bea49e) to Rust. f64 throughout, and the same operation order as the
JS, so results match to the bit. The only dependency is serde_json.
Stage 2 of the d33 ladder: d33 ports d3 gallery examples to Three.js keeping
d3's layout half as a JS dependency; this crate is that layout half in Rust,
with d3's own tests as the grader. The renderer half lives in
three-rs, whose sdf-text crate
draws a d3 treemap with this layout in its d33_treemap_labels example.
cargo add d3-hierarchy
The JS is built on mutable node objects with parent pointers, shared
identities (links() returns the very node objects, a.parent === b.parent)
and dynamically added layout properties. The Rust shape is an arena:
pub struct Tree { pub nodes: Vec<Node>, pub root: usize } pub struct Node { pub data: serde_json::Value, pub depth: usize, pub height: usize, pub parent: Option<usize>, pub children: Option<Vec<usize>>, pub value: Option<f64>, pub id: Option<String>, pub x: f64, pub y: f64, // cluster, tree pub x0: f64, pub y0: f64, pub x1: f64, pub y1: f64, // partition, treemap pub r: f64, // pack }
parent/childrenareusizeindices intoTree::nodes. Node identity is the index, so d3's===comparisons become==on indices.children: Noneis JSundefined(a leaf); d3 distinguishes "no children" from "empty children" in places (count,treemap), soSome(vec![])is kept distinct.- Layout fields always exist and default to 0, rather than being absent until a
layout runs.
valuestaysOptionbecause d3 leaves itundefineduntilsum/countand several algorithms branch on that. dataisserde_json::Valuerather than a genericD. Every d3 test and every d33 input (flare.json, flare.csv) is JSON, and the children/value accessors are then plain closures over&Value. A genericDis the obvious later extension; nothing in the algorithms depends on the choice.- Traversal is exposed twice:
order_each/order_before/order_afterreturn the visit order asVec<usize>(built with the same stack operations as the JS, so the order is identical), andeach*call a closure over that order. The algorithms use theorder_*form because a callback cannot hold&mut Treewhile the traversal does.
tests/ holds ports of d3's own tape tests, expectations verbatim, one Rust
test per it(...), named after it. Where d3 has no test for a module (see
below) the expectations are generated by running the vendor JS itself; the test
file says so and names the command.
| module | source | tests |
|---|---|---|
node |
src/hierarchy/*.js |
tests/hierarchy.rs (11) |
cluster |
src/cluster.js |
tests/cluster.rs (8) |
tree |
src/tree.js |
tests/tree.rs (9) |
partition |
src/partition.js |
tests/partition.rs (8) |
pack |
src/pack/*.js |
tests/pack.rs (6) |
treemap |
src/treemap/*.js |
tests/treemap.rs (28) |
stratify |
src/stratify.js |
tests/stratify.rs (30) |
100 tests. They read d3's own fixtures (test/data/*.json, flare.csv) from
a checkout of d3-hierarchy 3.1.2: D3_HIERARCHY_DIR if set, else
~/src/vendor/d3-hierarchy. A test whose fixture is missing fails on the open
with the path it looked for.
git clone --branch v3.1.2 --depth 1 https://github.com/d3/d3-hierarchy ~/src/vendor/d3-hierarchy cargo test
d3-hierarchy 3.1.2 ships no test/cluster-test.js, test/tree-test.js or
test/partition-test.js (its test/ holds only data/, hierarchy/, pack/,
treemap/ and stratify-test.js). For those three modules the expectations
were generated by running the vendor JS itself and pasted in as literals; each
test file's header gives the exact node command. Everything else is a verbatim
port of the tape test.
d3.hierarchy(Map)/mapChildren, and thechildren: new Set([...])half oftest/hierarchy/index-test.js: JS-only data shapes thatserde_json::Valuecannot express. The array form of the same assertion is ported.test/pack/bench-enclose.js,find-bugs.js,find-enclose-bugs.js,find-place-bugs.js: a benchmark and three random fuzzers, not tape tests.test/stratify-test.js, 5 of 38it()blocks: the two "accepts an iterable" cases (input is a JSSet; with&[Datum]they are identical to the array cases that precede them), the second "allows the id to be undefined for leaf nodes" (datum is{parentId: {toString(){…}}}), and the two "tests that id is a function" cases (d3'soptional()throwing on a non-function). Listed again at the foot of that test file.test/treemap/index-test.js, 3 cases: "coerces the specified round to boolean" (!!"yes"), "coerces the specified size to numbers" (+x[0]on a string), "makes defensive copies" ([f64; 2]isCopy, there is no aliasing to defend against).test/treemap/flare-test.js, both cases: they needd3-dsvCSV parsing plusstratify, andflare-phi.json/flare-one.jsonare in the D3 3.xx/y/dx/dyshape with a reverse-children fixup. The tiling itself is covered by the seven tiling test files; worth revisiting now thatstratifyexists.- Single assertions dropped inside otherwise-ported tests: function and
prototype identity (
root instanceof hierarchy,t.tile() === squarify,s.id() === foo) and getter-overloading asserts, which test JS'sarguments.lengthAPI rather than behaviour. The Rust API has separate setters and getters, so there is nothing to assert.
leaf_left/leaf_rightincluster: the JSwhile (children = node.children)treats an empty array as truthy and then throws onundefined.children; the Rust version ends the descent onSome(vec![]). Unreachable for trees built byhierarchy().squarifyuses Rust'sf64::max, which ignores NaN where JS'sMath.maxpropagates it. Only reachable with a NaN node value, whichsumalready coerces to 0.stratifynumber→string id coercion goes throughserde_json's formatting, so a float-typed whole number would give"1.0"where JS gives"1". No test reaches it; integer and non-integer ids both match.stratifyleaves unreachable arena entries behind when the imputed root is collapsed, sotree.nodes.len()is not the tree's node count. Traversals all start fromroot, so nothing observable changes.resquarifystate is shared between instances derived viaratio(), because in d3 the state lives on the node (parent._squarify), not on the layout.
MIT. See LICENSE, which also carries the d3-hierarchy (ISC) notice this
port derives from.