Skip to main content

d3_hierarchy/
lib.rs

1//! A port of d3-hierarchy 3.1.2 to Rust.
2//!
3//! f64 throughout, and the same operation order as the JS, so results match to
4//! the bit. See `README.md` for the node representation.
5
6pub mod cluster;
7pub mod node;
8pub mod pack;
9pub mod partition;
10pub mod stratify;
11pub mod tree;
12pub mod treemap;
13
14pub use node::{hierarchy, hierarchy_with, object_children, Datum, Node, Tree};
15
16/// `src/constant.js` / `src/array.js`: d3's `lcg()`.
17pub fn lcg() -> impl FnMut() -> f64 {
18    const A: f64 = 1664525.0;
19    const C: f64 = 1013904223.0;
20    const M: f64 = 4294967296.0; // 2^32
21    let mut s: f64 = 1.0;
22    move || {
23        s = (A * s + C) % M;
24        s / M
25    }
26}
27
28/// `src/array.js`'s `shuffle(array, random)`.
29pub fn shuffle<T>(array: &mut [T], random: &mut impl FnMut() -> f64) {
30    let mut m = array.len();
31    while m != 0 {
32        let i = (random() * m as f64) as usize; // `| 0`
33        m -= 1;
34        array.swap(m, i);
35    }
36}