use serde_json::{Map, Value};
use std::collections::{BTreeMap, HashMap};
pub const LANGS: [&str; 7] = [
"HANGUL", "LATIN", "HANJA", "JAPANESE", "OTHER", "SYMBOL", "USER",
];
pub const LANG_SUFFIX: [&str; 7] = ["1", "2", "3", "4", "5", "6", "7"];
const OBJECT_TABLES: [&str; 11] = [
"bf", "cp", "tp", "nu", "bu", "pp", "st", "mp", "ro", "sl", "cs",
];
pub struct Model {
d: Value,
}
impl Model {
pub fn new(mut d: Value) -> Option<Self> {
let root = d.as_object_mut()?;
for name in OBJECT_TABLES {
root.entry(name.to_string())
.or_insert_with(|| Value::Object(Map::new()));
}
root.entry("bi".to_string())
.or_insert_with(|| Value::Array(Vec::new()));
root.entry("bidt".to_string())
.or_insert_with(|| Value::Object(Map::new()));
Some(Model { d })
}
pub fn table(&self, name: &str) -> &Map<String, Value> {
match self.d.get(name).and_then(Value::as_object) {
Some(m) => m,
None => empty_map(),
}
}
pub fn bi(&self) -> &[Value] {
self.d
.get("bi")
.and_then(Value::as_array)
.map_or(&[], |v| v)
}
pub fn bidt(&self) -> &Map<String, Value> {
self.table("bidt")
}
pub fn body_paragraph_ids(&self) -> Vec<String> {
let ro = self.table("ro");
let head = ro.get("hp").and_then(Value::as_str).unwrap_or("");
chain(ro, head)
}
pub fn sublist_paragraph_ids(&self, head: &str) -> Vec<String> {
chain(self.table("sl"), head)
}
}
fn chain(pool: &Map<String, Value>, head: &str) -> Vec<String> {
let mut out = Vec::new();
let mut seen: HashMap<String, ()> = HashMap::new();
let mut cur = head.to_string();
while !cur.is_empty() {
let Some(node) = pool.get(&cur) else { break };
if seen.insert(cur.clone(), ()).is_some() {
break;
}
out.push(cur.clone());
cur = node
.get("np")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
}
out
}
#[derive(Default)]
pub struct Ids {
pub fonts: Vec<Vec<(String, i64)>>,
pub font_id: HashMap<(usize, String), usize>,
pub charpr_id: BTreeMap<String, i64>,
pub parapr_id: BTreeMap<String, i64>,
pub borderfill_id: BTreeMap<String, i64>,
pub style_id: BTreeMap<String, i64>,
pub bin_id: BTreeMap<String, u16>,
}
pub fn issue(table: &mut BTreeMap<String, i64>, objid: &str) -> Option<i64> {
if objid.is_empty() {
return None;
}
if let Some(v) = table.get(objid) {
return Some(*v);
}
let nid = table.len() as i64;
table.insert(objid.to_string(), nid);
Some(nid)
}
fn empty_map() -> &'static Map<String, Value> {
static EMPTY: std::sync::OnceLock<Map<String, Value>> = std::sync::OnceLock::new();
EMPTY.get_or_init(Map::new)
}
pub fn geti(v: &Value, k: &str, dflt: i64) -> i64 {
match v.get(k) {
None | Some(Value::Null) => dflt,
Some(Value::Bool(b)) => i64::from(*b),
Some(Value::Number(n)) => n
.as_i64()
.or_else(|| n.as_f64().map(|f| f as i64))
.unwrap_or(dflt),
Some(Value::String(s)) => s.parse::<i64>().unwrap_or(dflt),
_ => dflt,
}
}
pub fn getb(v: &Value, k: &str) -> bool {
match v.get(k) {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(Value::Number(n)) => n.as_f64().map(|f| f != 0.0).unwrap_or(false),
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
}
}
pub fn gets<'a>(v: &'a Value, k: &str) -> &'a str {
v.get(k).and_then(Value::as_str).unwrap_or("")
}
pub fn getobj<'a>(v: &'a Value, k: &str) -> Option<&'a Map<String, Value>> {
v.get(k).and_then(Value::as_object)
}
pub fn getarr<'a>(v: &'a Value, k: &str) -> &'a [Value] {
v.get(k).and_then(Value::as_array).map_or(&[], |v| v)
}
pub fn nullv() -> &'static Value {
static NULL: Value = Value::Null;
&NULL
}
pub fn sub<'a>(v: &'a Value, k: &str) -> &'a Value {
match v.get(k) {
Some(x) if x.is_object() => x,
_ => nullv(),
}
}
pub fn esc_attr(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
_ => out.push(c),
}
}
out
}
pub fn esc_text(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
_ => out.push(c),
}
}
out
}
pub fn attrs(pairs: &[(&str, Option<String>)]) -> String {
let mut out = String::new();
for (k, v) in pairs {
if let Some(v) = v {
out.push(' ');
out.push_str(k);
out.push_str("=\"");
out.push_str(&esc_attr(v));
out.push('"');
}
}
out
}
pub fn av<T: std::fmt::Display>(v: T) -> Option<String> {
Some(v.to_string())
}
pub fn b01(v: bool) -> &'static str {
if v {
"1"
} else {
"0"
}
}
pub fn u32v(v: i64) -> u32 {
v.rem_euclid(1i64 << 32) as u32
}
pub fn enum0(table: &[&'static str], v: i64) -> &'static str {
if v < 0 {
return table[0];
}
table.get(v as usize).copied().unwrap_or(table[0])
}
pub fn enum_raw(table: &[&'static str], v: i64) -> String {
if v >= 0 {
if let Some(s) = table.get(v as usize) {
return (*s).to_string();
}
}
v.to_string()
}
pub fn sorted_items<'a>(t: &'a Map<String, Value>) -> Vec<(&'a String, &'a Value)> {
let mut items: Vec<(&String, &Value)> = t.iter().collect();
items.sort_by(|a, b| {
geti(a.1, "id", 0)
.cmp(&geti(b.1, "id", 0))
.then_with(|| a.0.cmp(b.0))
});
items
}