use alloc::boxed::Box;
use alloc::sync::Arc;
use alloc::vec::Vec;
use crate::block::DictEntropy;
use crate::error::{Error, Result};
use crate::fse::SeqTables;
use crate::fse::{self, LL_KIND, ML_KIND, OF_KIND};
use crate::huf::HufDt;
const DICT_MAGIC: u32 = 0xEC30_A437;
#[derive(Clone)]
pub struct Dictionary {
inner: Arc<Inner>,
}
struct Inner {
id: u32,
content: Vec<u8>,
entropy: Option<Box<DictEntropy>>,
}
impl core::fmt::Debug for Dictionary {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Dictionary")
.field("id", &self.inner.id)
.field("content_len", &self.inner.content.len())
.field("has_entropy", &self.inner.entropy.is_some())
.finish()
}
}
impl Dictionary {
pub fn new(data: &[u8]) -> Result<Dictionary> {
if data.len() < 8 || u32::from_le_bytes(data[..4].try_into().unwrap()) != DICT_MAGIC {
return Ok(Self::raw(data));
}
let id = u32::from_le_bytes(data[4..8].try_into().unwrap());
let mut ent = Box::new(DictEntropy {
huf: HufDt::new(),
seq: SeqTables::new(),
rep: [0; 3],
});
let mut p = 8;
p += ent
.huf
.read(&data[p..])
.map_err(|_| Error::InvalidDictionary)?;
for kind in [OF_KIND, ML_KIND, LL_KIND] {
let mut norm = [0i16; fse::MAX_ML + 1];
let (max_sym, log, used) = fse::read_ncount(&data[p..], kind.max, &mut norm)
.map_err(|_| Error::InvalidDictionary)?;
if log > kind.max_log {
return Err(Error::InvalidDictionary);
}
ent.seq.build(
kind,
&norm,
max_sym + 1,
log,
crate::cpu::Features::detect(),
);
p += used;
}
if p + 12 > data.len() {
return Err(Error::InvalidDictionary);
}
let content_len = data.len() - (p + 12);
for rep in &mut ent.rep {
let r = u32::from_le_bytes(data[p..p + 4].try_into().unwrap());
p += 4;
if r == 0 || r as usize > content_len {
return Err(Error::InvalidDictionary);
}
*rep = r;
}
Ok(Dictionary {
inner: Arc::new(Inner {
id,
content: data[p..].to_vec(),
entropy: Some(ent),
}),
})
}
pub fn raw(data: &[u8]) -> Dictionary {
Dictionary {
inner: Arc::new(Inner {
id: 0,
content: data.to_vec(),
entropy: None,
}),
}
}
pub fn id(&self) -> u32 {
self.inner.id
}
pub(crate) fn same(&self, other: &Dictionary) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
pub(crate) fn content(&self) -> &[u8] {
&self.inner.content
}
pub(crate) fn entropy(&self) -> Option<&DictEntropy> {
self.inner.entropy.as_deref()
}
}