use super::json::Json;
use std::sync::OnceLock;
pub const HOLE_FITS: &[&str] = &["close fit", "normal fit", "loose fit", "tap"];
pub fn standards() -> &'static Json {
static DATA: OnceLock<Json> = OnceLock::new();
DATA.get_or_init(|| Json::parse(include_str!("standards_data.json")).expect("standards_data.json is JSON"))
}
fn entries(v: Option<&Json>) -> &[(String, Json)] {
match v {
Some(Json::Obj(e)) => e,
_ => &[],
}
}
fn items(v: Option<&Json>) -> &[Json] {
match v {
Some(Json::Arr(a)) => a,
_ => &[],
}
}
fn norm(id: &str) -> String {
id.trim().to_lowercase().split(|c: char| c.is_whitespace() || c == '_').filter(|p| !p.is_empty()).collect::<Vec<_>>().join("-")
}
fn id_of(row: &Json) -> &str {
row.get("id").and_then(Json::as_str).unwrap_or_default()
}
pub fn materials() -> &'static [Json] {
items(standards().get("materials"))
}
pub fn material(id: &str, tables: &[Json]) -> Result<Json, String> {
let want = norm(id);
tables.iter().chain(materials()).find(|m| norm(id_of(m)) == want).cloned().ok_or_else(|| {
format!("no materials table has a row \"{id}\" (the shipped table has {})", materials().iter().map(id_of).collect::<Vec<_>>().join(", "))
})
}
pub fn mass_grams(volume_mm3: f64, material_id: &str, tables: &[Json]) -> Result<f64, String> {
let row = material(material_id, tables)?;
Ok(volume_mm3 / 1000.0 * row.get("densityGCm3").and_then(Json::as_f64).unwrap_or_default())
}
pub fn hole_size(name: &str) -> Result<Json, String> {
let text = name.split_whitespace().collect::<Vec<_>>().join(" ");
let (thread, rest) = text.split_once(' ').unwrap_or((text.as_str(), ""));
let fit = rest.to_lowercase();
let sizes = entries(standards().get("holeSizes"));
let Some((_, row)) = sizes.iter().find(|(k, _)| k.to_lowercase() == thread.to_lowercase()) else {
let known = sizes.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>().join(", ");
return Err(format!("\"{name}\": no hole table has the thread {} (it has {known})", if thread.is_empty() { "(none)" } else { thread }));
};
let row_thread = row.get("thread").and_then(Json::as_str).unwrap_or_default();
if !HOLE_FITS.contains(&fit.as_str()) {
return Err(format!("\"{name}\": a hole size is a thread and one of {} (\"{row_thread} close fit\")", HOLE_FITS.join(", ")));
}
let source = |what: &str| row.get("sources").and_then(|s| s.get(what)).and_then(Json::as_str).unwrap_or_default().to_string();
let (diameter, source) = if fit == "tap" {
match row.get("tap") {
Some(d) => (d.clone(), source("tap")),
None => return Err(format!("\"{name}\": the tap drill table has no {row_thread}")),
}
} else {
(row.get(&fit[..fit.len() - 4]).cloned().unwrap_or(Json::Null), source("clearance"))
};
Ok(Json::obj().with("thread", row_thread).with("fit", fit.as_str()).with("diameter", diameter).with("row", row.clone()).with("source", source))
}
pub fn sized_hole(hole: &Json) -> Result<Json, String> {
let Some(size) = hole.get("size").and_then(Json::as_str) else { return Ok(hole.clone()) };
let named = hole_size(size)?;
let diameter = named.get("diameter").and_then(Json::as_f64).unwrap_or_default();
let mut says: Vec<(&str, f64)> = vec![("diameter", diameter)];
let tap = named.get("fit").and_then(Json::as_str) == Some("tap");
let row = named.get("row");
let style = hole.get("style").and_then(Json::as_str);
let num = |v: Option<&Json>, k: &str| v.and_then(|j| j.get(k)).and_then(Json::as_f64);
if let (false, Some("counterbore"), Some(bore)) = (tap, style, row.and_then(|r| r.get("counterbore"))) {
says.push(("headDiameter", num(Some(bore), "diameter").unwrap_or_default()));
let table = num(Some(bore), "depth").unwrap_or_default();
let written = hole.get("headDepth").and_then(Json::as_f64).filter(|d| *d > table);
says.push(("headDepth", written.unwrap_or(table)));
} else if let (false, Some("countersink"), Some(sink)) = (tap, style, row.and_then(|r| r.get("countersink"))) {
let head = num(Some(sink), "diameter").unwrap_or_default();
let angle = num(Some(sink), "angleDeg").unwrap_or(90.0);
let depth = (head - diameter) / 2.0 / (angle * std::f64::consts::PI / 360.0).tan();
says.push(("headDiameter", head));
says.push(("headDepth", (depth * 1e4 + 0.5).floor() / 1e4));
}
let mut out = hole.clone();
for (field, value) in says {
if let Some(written) = hole.get(field).and_then(Json::as_f64) {
if (written - value).abs() > 1e-9 {
let deeper = if field == "headDepth" && style == Some("counterbore") { " (a counterbore may be deeper than the size's, not shallower)" } else { "" };
return Err(format!("{field}: \"{size}\" is {} mm (got {}); leave {field} out, or clear size{deeper}", Json::Num(value).text(), Json::Num(written).text()));
}
}
out.set(field, value);
}
Ok(out)
}
pub fn standard_row(table: &str, key: &str) -> Result<Json, String> {
let tables = entries(standards().get("tables"));
let Some((_, rows)) = tables.iter().find(|(k, _)| k == table) else {
return Err(format!("no table \"{table}\" (the tables are {})", tables.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>().join(", ")));
};
let rows = items(Some(rows));
let first = |r: &Json| match r {
Json::Obj(e) => e.first().map(|(_, v)| v.as_str().map(str::to_string).unwrap_or_else(|| v.text())).unwrap_or_default(),
_ => String::new(),
};
rows.iter()
.find(|r| first(r).to_lowercase() == key.to_lowercase())
.cloned()
.ok_or_else(|| format!("table \"{table}\" has no row \"{key}\" (it has {})", rows.iter().map(first).collect::<Vec<_>>().join(", ")))
}