pub const MAX_BIN_DATA_BYTES: usize = 256 * 1024 * 1024;
#[derive(Debug, Clone)]
pub struct StoredBinData {
pub bytes: Vec<u8>,
pub compressed: bool,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct BinData {
pub raw_data: Option<Vec<u8>>,
pub attr: u16,
pub data_type: BinDataType,
pub compression: BinDataCompression,
pub status: BinDataStatus,
pub abs_path: Option<String>,
pub rel_path: Option<String>,
pub storage_id: u16,
pub extension: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub enum BinDataType {
#[default]
Link,
Embedding,
Storage,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub enum BinDataCompression {
#[default]
Default,
Compress,
NoCompress,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub enum BinDataStatus {
#[default]
NotAccessed,
Success,
Error,
Ignored,
}
#[derive(Debug, Clone)]
pub struct BinDataContent {
pub id: u16,
pub data: BinDataBytes,
pub extension: String,
}
pub trait BinDataResolver:
std::fmt::Debug + Send + Sync + std::panic::RefUnwindSafe + std::panic::UnwindSafe
{
fn stable_size_bound(&self, _key: &str) -> Option<usize> {
None
}
fn resolve(&self, key: &str) -> Vec<u8>;
fn resolve_shared(&self, key: &str) -> std::sync::Arc<[u8]> {
self.resolve(key).into()
}
fn resolve_limited(&self, _key: &str, _max_bytes: usize) -> Option<Vec<u8>> {
None
}
fn resolve_limited_shared(&self, key: &str, max_bytes: usize) -> Option<std::sync::Arc<[u8]>> {
self.resolve_limited(key, max_bytes).map(Into::into)
}
fn resolved_len(&self, key: &str) -> usize {
self.resolve(key).len()
}
fn resolved_is_empty(&self, key: &str) -> bool {
self.resolve(key).is_empty()
}
fn resolve_raw(&self, _key: &str) -> Option<StoredBinData> {
None
}
fn resolve_deflated_zip_entry(&self, _key: &str) -> Option<DeflatedZipEntry> {
None
}
}
#[derive(Debug, Clone)]
pub struct DeflatedZipEntry {
pub crc32: u32,
pub uncompressed_size: u64,
pub compressed_bytes: Vec<u8>,
}
struct InMemorySharedBinDataResolver {
bytes: std::sync::Arc<[u8]>,
}
impl std::fmt::Debug for InMemorySharedBinDataResolver {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InMemorySharedBinDataResolver")
.field("len", &self.bytes.len())
.finish()
}
}
impl BinDataResolver for InMemorySharedBinDataResolver {
fn stable_size_bound(&self, _key: &str) -> Option<usize> {
Some(self.bytes.len())
}
fn resolve(&self, _key: &str) -> Vec<u8> {
self.bytes.to_vec()
}
fn resolve_shared(&self, _key: &str) -> std::sync::Arc<[u8]> {
std::sync::Arc::clone(&self.bytes)
}
fn resolve_limited(&self, _key: &str, max_bytes: usize) -> Option<Vec<u8>> {
(self.bytes.len() <= max_bytes).then(|| self.bytes.to_vec())
}
fn resolve_limited_shared(&self, _key: &str, max_bytes: usize) -> Option<std::sync::Arc<[u8]>> {
(self.bytes.len() <= max_bytes).then(|| std::sync::Arc::clone(&self.bytes))
}
fn resolved_len(&self, _key: &str) -> usize {
self.bytes.len()
}
fn resolved_is_empty(&self, _key: &str) -> bool {
self.bytes.is_empty()
}
}
#[derive(Debug, Clone)]
pub enum BinDataBytes {
Loaded(Vec<u8>),
Lazy {
resolver: std::sync::Arc<dyn BinDataResolver>,
key: String,
},
}
impl BinDataBytes {
pub fn from_shared(data: impl Into<std::sync::Arc<[u8]>>) -> Self {
Self::Lazy {
resolver: std::sync::Arc::new(InMemorySharedBinDataResolver { bytes: data.into() }),
key: "<in-memory>".to_string(),
}
}
pub fn load(&self) -> Vec<u8> {
match self {
BinDataBytes::Loaded(v) => v.clone(),
BinDataBytes::Lazy { resolver, key } => resolver.resolve(key),
}
}
pub fn load_shared(&self) -> std::sync::Arc<[u8]> {
match self {
BinDataBytes::Loaded(v) => std::sync::Arc::from(v.as_slice()),
BinDataBytes::Lazy { resolver, key } => resolver.resolve_shared(key),
}
}
pub fn load_limited(&self, max_bytes: usize) -> Option<Vec<u8>> {
match self {
BinDataBytes::Loaded(v) if v.len() <= max_bytes => Some(v.clone()),
BinDataBytes::Loaded(_) => None,
BinDataBytes::Lazy { resolver, key } => resolver
.resolve_limited(key, max_bytes)
.filter(|bytes| bytes.len() <= max_bytes),
}
}
pub fn load_limited_shared(&self, max_bytes: usize) -> Option<std::sync::Arc<[u8]>> {
match self {
BinDataBytes::Loaded(v) if v.len() <= max_bytes => {
Some(std::sync::Arc::from(v.as_slice()))
}
BinDataBytes::Loaded(_) => None,
BinDataBytes::Lazy { resolver, key } => resolver
.resolve_limited_shared(key, max_bytes)
.filter(|bytes| bytes.len() <= max_bytes),
}
}
pub fn load_raw(&self) -> Option<StoredBinData> {
match self {
BinDataBytes::Loaded(_) => None,
BinDataBytes::Lazy { resolver, key } => resolver.resolve_raw(key),
}
}
pub fn load_deflated_zip_entry(&self) -> Option<DeflatedZipEntry> {
match self {
BinDataBytes::Loaded(_) => None,
BinDataBytes::Lazy { resolver, key } => resolver.resolve_deflated_zip_entry(key),
}
}
pub fn len(&self) -> usize {
match self {
BinDataBytes::Loaded(v) => v.len(),
BinDataBytes::Lazy { resolver, key } => resolver.resolved_len(key),
}
}
pub fn is_empty(&self) -> bool {
match self {
BinDataBytes::Loaded(v) => v.is_empty(),
BinDataBytes::Lazy { resolver, key } => resolver.resolved_is_empty(key),
}
}
}
impl Default for BinDataBytes {
fn default() -> Self {
BinDataBytes::Loaded(Vec::new())
}
}
impl From<Vec<u8>> for BinDataBytes {
fn from(v: Vec<u8>) -> Self {
BinDataBytes::Loaded(v)
}
}
pub(crate) fn hwp5_link_slot() -> BinDataContent {
BinDataContent {
id: 0,
data: BinDataBytes::Loaded(Vec::new()),
extension: String::new(),
}
}
pub(crate) fn is_hwp5_link_slot(content: &BinDataContent, record: Option<&BinData>) -> bool {
content.id == 0
&& content.extension.is_empty()
&& matches!(&content.data, BinDataBytes::Loaded(v) if v.is_empty())
&& record.is_some_and(|bd| bd.data_type == BinDataType::Link && bd.storage_id == 0)
}
pub(crate) fn content_index(contents: &[BinDataContent], id: u16) -> Option<usize> {
let index = usize::from(id.checked_sub(1)?);
if index < contents.len() {
Some(index)
} else {
contents.iter().position(|c| c.id == id)
}
}
pub(crate) fn register_embedded_bin_data(
document: &mut super::document::Document,
image_data: impl Into<std::sync::Arc<[u8]>>,
extension: &str,
) -> u16 {
let position_id = document.bin_data_content.len() as u16 + 1;
let storage_id = document.next_bin_data_storage_id();
document.bin_data_content.push(BinDataContent {
id: storage_id,
data: BinDataBytes::from_shared(image_data),
extension: extension.to_string(),
});
let bin_attr: u16 = 0x0101;
document.doc_info.bin_data_list.push(BinData {
raw_data: None,
attr: bin_attr,
data_type: BinDataType::Embedding,
compression: BinDataCompression::Default,
status: BinDataStatus::Success,
abs_path: None,
rel_path: None,
storage_id,
extension: Some(extension.to_string()),
});
document.doc_info.raw_stream = None; position_id
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[test]
fn legacy_loaded_and_from_vec_keep_the_vec_variant_contract() {
let direct = BinDataBytes::Loaded(vec![1, 2, 3]);
let converted: BinDataBytes = vec![4, 5, 6].into();
assert!(matches!(direct, BinDataBytes::Loaded(ref bytes) if bytes == &[1, 2, 3]));
assert!(matches!(converted, BinDataBytes::Loaded(ref bytes) if bytes == &[4, 5, 6]));
let loaded: Vec<u8> = direct.load();
let limited: Option<Vec<u8>> = direct.load_limited(3);
assert_eq!(loaded, vec![1, 2, 3]);
assert_eq!(limited, Some(vec![1, 2, 3]));
}
#[test]
fn shared_in_memory_bytes_keep_one_allocation_across_clones() {
let bytes = BinDataBytes::from_shared(vec![1, 2, 3, 4]);
let cloned = bytes.clone();
let first = bytes.load_shared();
let second = cloned.load_shared();
assert!(std::sync::Arc::ptr_eq(&first, &second));
assert_eq!(bytes.load(), vec![1, 2, 3, 4]);
assert_eq!(bytes.load_limited(4), Some(vec![1, 2, 3, 4]));
let limited_first = bytes.load_limited_shared(4).expect("within limit");
let limited_second = cloned.load_limited_shared(4).expect("within limit");
assert!(std::sync::Arc::ptr_eq(&limited_first, &limited_second));
assert!(bytes.load_limited_shared(3).is_none());
}
#[test]
fn document_snapshot_clone_shares_in_memory_bin_data() {
let mut document = crate::model::document::Document::default();
document.bin_data_content.push(BinDataContent {
id: 1,
data: BinDataBytes::from_shared(vec![0x89, b'P', b'N', b'G']),
extension: "png".to_string(),
});
let snapshot = document.clone();
let current = document.bin_data_content[0].data.load_shared();
let snapshotted = snapshot.bin_data_content[0].data.load_shared();
assert!(std::sync::Arc::ptr_eq(¤t, &snapshotted));
}
#[test]
fn test_bin_data_default() {
let bd = BinData::default();
assert_eq!(bd.data_type, BinDataType::Link);
assert_eq!(bd.compression, BinDataCompression::Default);
assert_eq!(bd.status, BinDataStatus::NotAccessed);
}
#[test]
fn test_bin_data_embedding() {
let bd = BinData {
data_type: BinDataType::Embedding,
storage_id: 1,
extension: Some("jpg".to_string()),
..Default::default()
};
assert_eq!(bd.data_type, BinDataType::Embedding);
assert_eq!(bd.extension.as_deref(), Some("jpg"));
}
#[test]
fn load_raw_exposes_stored_form_only_for_container_resolvers() {
#[derive(Debug)]
struct RawResolver;
impl BinDataResolver for RawResolver {
fn resolve(&self, _key: &str) -> Vec<u8> {
vec![0; 8]
}
fn resolve_raw(&self, key: &str) -> Option<StoredBinData> {
Some(StoredBinData {
bytes: key.as_bytes().to_vec(),
compressed: true,
})
}
}
let lazy = BinDataBytes::Lazy {
resolver: std::sync::Arc::new(RawResolver),
key: "BIN0001.jpg".to_string(),
};
let stored = lazy
.load_raw()
.expect("컨테이너 리졸버는 저장 형태를 노출한다");
assert_eq!(stored.bytes, b"BIN0001.jpg".to_vec());
assert!(stored.compressed);
assert!(BinDataBytes::Loaded(vec![1, 2]).load_raw().is_none());
assert!(BinDataBytes::from_shared(vec![1, 2, 3])
.load_raw()
.is_none());
}
#[test]
fn limited_lazy_load_never_falls_back_to_unbounded_resolution() {
#[derive(Debug)]
struct LimitedOnlyResolver {
requested_limit: AtomicUsize,
}
impl BinDataResolver for LimitedOnlyResolver {
fn resolve(&self, key: &str) -> Vec<u8> {
panic!("bounded load must not call unbounded resolver: {key}")
}
fn resolve_limited(&self, _key: &str, max_bytes: usize) -> Option<Vec<u8>> {
self.requested_limit.store(max_bytes, Ordering::SeqCst);
Some(vec![0; max_bytes + 1])
}
}
let resolver = std::sync::Arc::new(LimitedOnlyResolver {
requested_limit: AtomicUsize::new(0),
});
let bytes = BinDataBytes::Lazy {
resolver: resolver.clone(),
key: "compressed-font".to_string(),
};
assert!(bytes.load_limited(16).is_none());
assert_eq!(resolver.requested_limit.load(Ordering::SeqCst), 16);
}
}