use super::control::{Control, FieldType};
use super::document::Document;
use super::identity::walk::{walk_ref, RefNode};
use std::collections::HashSet;
pub const HWP_STREAM: &str = "/MemoExtended";
pub const HWPX_ENTRY: &str = "Contents/memoExtended.xml";
pub const MAX_BYTES: usize = 4 * 1024 * 1024;
const TAG: u32 = 0x65;
pub fn decode_hwp(data: &[u8]) -> Option<Vec<(u32, u32)>> {
let header = u32::from_le_bytes(data.get(..4)?.try_into().ok()?);
let (tag, size) = (header & 0x3FF, header >> 20);
let (size, body): (usize, usize) = if size == 0xFFF {
(
u32::from_le_bytes(data.get(4..8)?.try_into().ok()?) as usize,
8,
)
} else {
(size as usize, 4)
};
let record = data.get(body..body.checked_add(size)?)?;
if tag != TAG || record.len() < 4 {
return None;
}
let at = |i: usize| -> Option<u32> {
Some(u32::from_le_bytes(record.get(i..i + 4)?.try_into().ok()?))
};
let count = at(0)? as usize;
if record.len() != 4 + count.checked_mul(8)? {
return None;
}
(0..count)
.map(|i| Some((at(4 + i * 8)?, at(8 + i * 8)?)))
.collect()
}
pub fn encode_hwp(links: &[(u32, u32)]) -> Vec<u8> {
let size = 4 + links.len() * 8;
let mut data = Vec::with_capacity(size + 8);
if size < 0xFFF {
data.extend_from_slice(&(TAG | ((size as u32) << 20)).to_le_bytes());
} else {
data.extend_from_slice(&(TAG | (0xFFF << 20)).to_le_bytes());
data.extend_from_slice(&(size as u32).to_le_bytes());
}
data.extend_from_slice(&(links.len() as u32).to_le_bytes());
for (id, parent) in links {
data.extend_from_slice(&id.to_le_bytes());
data.extend_from_slice(&parent.to_le_bytes());
}
data
}
pub fn decode_hwpx(xml: &str) -> Vec<(u32, u32)> {
let attr = |tag: &str, name: &str| -> Option<u32> {
let start = tag.find(&format!(" {name}=\""))? + name.len() + 3;
tag[start..].split('"').next()?.parse().ok()
};
xml.split("<he:memo ")
.skip(1)
.filter_map(|rest| {
let tag = format!(" {}", rest.split('>').next()?);
Some((attr(&tag, "id")?, attr(&tag, "parentId")?))
})
.collect()
}
pub fn encode_hwpx(links: &[(u32, u32)]) -> String {
let mut xml = String::from(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><he:memosEx xmlns:he="http://www.hancom.co.kr/hwpml/2021/extended">"#,
);
for (id, parent) in links {
xml.push_str(&format!(r#"<he:memo id="{id}" parentId="{parent}"/>"#));
}
xml.push_str("</he:memosEx>");
xml
}
pub fn memo_field_ids(doc: &Document) -> HashSet<u32> {
let mut ids = HashSet::new();
for section in &doc.sections {
let Ok(()) = walk_ref(§ion.paragraphs, &crate::storage::Unbounded, |node| {
if let RefNode::Control(Control::Field(field)) = node {
if field.field_type == FieldType::Memo || field.command.starts_with("MEMO/") {
ids.insert(field.field_id);
}
}
Ok(())
});
}
ids
}
pub fn live_links(doc: &Document) -> Vec<(u32, u32)> {
if doc.memo_parents.is_empty() {
return Vec::new();
}
let ids = memo_field_ids(doc);
doc.memo_parents
.iter()
.copied()
.filter(|(id, parent)| ids.contains(id) && ids.contains(parent))
.collect()
}