snail.rs
2.1 kB · rust · 56 lines
1use crate::Fault;2use mrlycore::json;3use mrlynum::spiral::{self, Growth, Snail};4use wasm_bindgen::prelude::*;56const TOP: u32 = 2000;7const BASE: u32 = 8;89fn read(base: u32, top: u32, growth: &str) -> Result<Snail, Fault> {10 let growth =11 Growth::named(growth).ok_or_else(|| Fault::new("the growth is prime or every."))?;12 if !(2..=BASE).contains(&base) {13 return Err(Fault::new(format!("the base is 2 to {BASE}.")));14 }15 if top == 0 || top > TOP {16 return Err(Fault::new(format!("the top is 1 to {TOP}.")));17 }18 Ok(spiral::snail(u64::from(base), u64::from(top), growth))19}2021/// Packs the snail of the whole numbers to the top: five numbers a tile, the x and y of its lower-left corner, its side, its level and one when the number is prime, in the order one, two, three and on.22#[wasm_bindgen]23pub fn snail_cells(base: u32, top: u32, growth: &str) -> Result<Vec<i32>, Fault> {24 let shell = read(base, top, growth)?;25 let mut out = Vec::with_capacity(5 * shell.tiles.len());26 for tile in &shell.tiles {27 out.push(tile.x as i32);28 out.push(tile.y as i32);29 out.push(tile.side as i32);30 out.push(tile.level as i32);31 out.push(i32::from(tile.prime));32 }33 Ok(out)34}3536/// Reads the snail: the count of tiles, the primes at or below the top, the tiles grown past a unit cell, the tally at each level, the largest side, the drawn area and the box the tiles fill, as JSON.37#[wasm_bindgen]38pub fn snail_read(base: u32, top: u32, growth: &str) -> Result<String, Fault> {39 let shell = read(base, top, growth)?;40 let grown = shell.tiles.iter().filter(|tile| tile.level > 0).count();41 let side = shell.tiles.iter().map(|tile| tile.side).max().unwrap_or(1);42 Ok(json!({43 "tiles": shell.tiles.len(),44 "primes": shell.primes,45 "grown": grown,46 "levels": shell.levels,47 "peak": shell.levels.len() - 1,48 "side": side,49 "area": shell.area as u64,50 "low": [shell.low.0, shell.low.1],51 "high": [shell.high.0, shell.high.1],52 "width": shell.high.0 - shell.low.0,53 "height": shell.high.1 - shell.low.1,54 })55 .to_string())56}