use crate::bit::{BitReader, HandleRef};
use crate::core::error::{DwgError, ErrorKind};
use crate::core::result::Result;
use crate::dwg::version::DwgVersion;
use crate::objects::handle::Handle;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DictionaryEntry {
pub name: String,
pub value_handle: Option<Handle>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dictionary {
pub handle: Handle,
pub numitems: u32,
pub cloning: Option<u16>,
pub is_hardowner: Option<u8>,
pub entries: Vec<DictionaryEntry>,
pub num_reactors: u32,
pub is_xdic_missing: bool,
pub has_ds_data: bool,
pub owner_handle: Option<Handle>,
pub reactors: Vec<Handle>,
pub xdic_handle: Option<Handle>,
}
impl Dictionary {
pub fn get(&self, name: &str) -> Option<&DictionaryEntry> {
self.entries.iter().find(|e| e.name == name)
}
pub fn get_ignore_ascii_case(&self, name: &str) -> Option<&DictionaryEntry> {
self.entries
.iter()
.find(|e| e.name.eq_ignore_ascii_case(name))
}
}
#[derive(Debug)]
pub struct DictionaryDecodeCtx<'a> {
pub version: DwgVersion,
pub object_handle: u64,
pub handle_stream_bit_start: Option<u64>,
pub string_reader: Option<&'a mut BitReader<'a>>,
}
pub fn decode_dictionary_data(
reader: &mut BitReader<'_>,
ctx: &mut DictionaryDecodeCtx<'_>,
) -> Result<DictionaryData> {
let numitems = reader.read_bl()?;
const MAX_ITEMS: u32 = 100_000;
if numitems > MAX_ITEMS {
return Err(DwgError::new(
ErrorKind::Format,
format!("DICTIONARY numitems {numitems} exceeds safe limit {MAX_ITEMS}"),
));
}
let cloning = if version_at_least(&ctx.version, &DwgVersion::R2000) {
Some(reader.read_bs()?)
} else {
None
};
let is_hardowner = if version_at_least(&ctx.version, &DwgVersion::R13) {
Some(reader.read_rc()?)
} else {
None
};
let mut names = Vec::with_capacity(numitems as usize);
for i in 0..numitems {
let name = read_dictionary_text(reader, ctx, i)?;
names.push(name);
}
Ok(DictionaryData {
numitems,
cloning,
is_hardowner,
names,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DictionaryData {
pub numitems: u32,
pub cloning: Option<u16>,
pub is_hardowner: Option<u8>,
pub names: Vec<String>,
}
pub fn decode_dictionary_handles(
handle_reader: &mut BitReader<'_>,
version: &DwgVersion,
object_handle: u64,
numitems: u32,
data_section_common: Option<(u32, bool, bool)>,
) -> Result<DictionaryHandles> {
let common = match data_section_common {
Some((num_reactors, is_xdic_missing, has_ds_data)) => decode_common_object_handle_refs(
handle_reader,
version,
object_handle,
num_reactors,
is_xdic_missing,
has_ds_data,
)?,
None => decode_common_object_handles(handle_reader, version, object_handle)?,
};
let mut item_handles = Vec::with_capacity(numitems as usize);
for _ in 0..numitems {
let href = handle_reader.read_h()?;
let absolute = resolve_handle_ref(&href, object_handle)?;
item_handles.push(absolute.map(Handle));
}
Ok(DictionaryHandles {
common,
item_handles,
})
}
pub fn decode_common_object_handle_refs(
handle_reader: &mut BitReader<'_>,
version: &DwgVersion,
object_handle: u64,
num_reactors: u32,
is_xdic_missing: bool,
has_ds_data: bool,
) -> Result<CommonObjectHandles> {
const MAX_REACTORS: u32 = 10_000;
if num_reactors > MAX_REACTORS {
return Err(DwgError::new(
ErrorKind::Format,
format!("num_reactors {num_reactors} exceeds safe limit {MAX_REACTORS}"),
));
}
let owner_handle = if version_at_least(version, &DwgVersion::R13) {
let href = handle_reader.read_h()?;
resolve_handle_ref(&href, object_handle)?.map(Handle)
} else {
None
};
let mut reactors = Vec::with_capacity(num_reactors as usize);
for _ in 0..num_reactors {
let href = handle_reader.read_h()?;
if let Some(h) = resolve_handle_ref(&href, object_handle)? {
reactors.push(Handle(h));
}
}
let xdic_handle = if !is_xdic_missing && version_at_least(version, &DwgVersion::R13) {
let href = handle_reader.read_h()?;
resolve_handle_ref(&href, object_handle)?.map(Handle)
} else {
None
};
Ok(CommonObjectHandles {
num_reactors,
is_xdic_missing,
has_ds_data,
owner_handle,
reactors,
xdic_handle,
})
}
pub fn assemble_dictionary(
object_handle: u64,
data: DictionaryData,
handles: DictionaryHandles,
) -> Result<Dictionary> {
if data.names.len() != handles.item_handles.len() {
return Err(DwgError::new(
ErrorKind::Decode,
format!(
"DICTIONARY name count ({}) != item handle count ({})",
data.names.len(),
handles.item_handles.len()
),
));
}
let entries = data
.names
.into_iter()
.zip(handles.item_handles)
.map(|(name, value_handle)| DictionaryEntry { name, value_handle })
.collect();
Ok(Dictionary {
handle: Handle(object_handle),
numitems: data.numitems,
cloning: data.cloning,
is_hardowner: data.is_hardowner,
entries,
num_reactors: handles.common.num_reactors,
is_xdic_missing: handles.common.is_xdic_missing,
has_ds_data: handles.common.has_ds_data,
owner_handle: handles.common.owner_handle,
reactors: handles.common.reactors,
xdic_handle: handles.common.xdic_handle,
})
}
pub fn decode_dictionary(
reader: &mut BitReader<'_>,
handle_reader: &mut BitReader<'_>,
ctx: &mut DictionaryDecodeCtx<'_>,
) -> Result<Dictionary> {
let data = decode_dictionary_data(reader, ctx)?;
let handles = decode_dictionary_handles(
handle_reader,
&ctx.version,
ctx.object_handle,
data.numitems,
None, )?;
assemble_dictionary(ctx.object_handle, data, handles)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommonObjectHandles {
pub num_reactors: u32,
pub is_xdic_missing: bool,
pub has_ds_data: bool,
pub owner_handle: Option<Handle>,
pub reactors: Vec<Handle>,
pub xdic_handle: Option<Handle>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DictionaryHandles {
pub common: CommonObjectHandles,
pub item_handles: Vec<Option<Handle>>,
}
pub fn decode_common_object_handles(
handle_reader: &mut BitReader<'_>,
version: &DwgVersion,
object_handle: u64,
) -> Result<CommonObjectHandles> {
let num_reactors = if version_at_least(version, &DwgVersion::R13) {
let n = handle_reader.read_bl()?;
const MAX_REACTORS: u32 = 10_000;
if n > MAX_REACTORS {
return Err(DwgError::new(
ErrorKind::Format,
format!("num_reactors {n} exceeds safe limit {MAX_REACTORS}"),
));
}
n
} else {
0
};
let is_xdic_missing = if version_at_least(version, &DwgVersion::R2004) {
handle_reader.read_b()? != 0
} else {
false
};
let has_ds_data = if version_at_least(version, &DwgVersion::R2013) {
handle_reader.read_b()? != 0
} else {
false
};
let owner_handle = if version_at_least(version, &DwgVersion::R13) {
let href = handle_reader.read_h()?;
resolve_handle_ref(&href, object_handle)?.map(Handle)
} else {
None
};
let mut reactors = Vec::with_capacity(num_reactors as usize);
for _ in 0..num_reactors {
let href = handle_reader.read_h()?;
if let Some(h) = resolve_handle_ref(&href, object_handle)? {
reactors.push(Handle(h));
}
}
let xdic_handle = if !is_xdic_missing && version_at_least(version, &DwgVersion::R13) {
let href = handle_reader.read_h()?;
resolve_handle_ref(&href, object_handle)?.map(Handle)
} else {
None
};
Ok(CommonObjectHandles {
num_reactors,
is_xdic_missing,
has_ds_data,
owner_handle,
reactors,
xdic_handle,
})
}
pub fn resolve_handle_ref(href: &HandleRef, object_handle: u64) -> Result<Option<u64>> {
let absolute = match href.code {
0x06 => object_handle.saturating_add(1),
0x08 => object_handle.saturating_sub(1),
0x0A => object_handle.saturating_add(href.value),
0x0C => object_handle.saturating_sub(href.value),
0x02..=0x05 => {
if href.value == 0 {
return Ok(None);
}
href.value
}
_ => {
if href.value == 0 {
return Ok(None);
}
href.value
}
};
Ok(Some(absolute))
}
fn read_dictionary_text(
reader: &mut BitReader<'_>,
ctx: &mut DictionaryDecodeCtx<'_>,
index: u32,
) -> Result<String> {
if version_at_least(&ctx.version, &DwgVersion::R2007) {
match ctx.string_reader.as_mut() {
Some(sreader) => sreader.read_tu().map_err(|e| {
DwgError::new(
ErrorKind::Decode,
format!("DICTIONARY text[{index}] TU read failed: {e}"),
)
}),
None => reader.read_tu().map_err(|e| {
DwgError::new(
ErrorKind::Decode,
format!(
"DICTIONARY text[{index}] TU fallback (no string stream) failed on {}: {e}",
ctx.version.as_str()
),
)
}),
}
} else {
reader.read_tv().map_err(|e| {
DwgError::new(
ErrorKind::Decode,
format!("DICTIONARY text[{index}] TV read failed: {e}"),
)
})
}
}
pub fn version_at_least(version: &DwgVersion, min: &DwgVersion) -> bool {
use DwgVersion::*;
let rank = |v: &DwgVersion| -> u8 {
match v {
R13 => 1,
R14 => 2,
R2000 => 3,
R2004 => 4,
R2007 => 5,
R2010 => 6,
R2013 => 7,
R2018 => 8,
Unknown(_) => 9,
}
};
rank(version) >= rank(min)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bit::BitWriter;
#[test]
fn version_at_least_ordering() {
assert!(version_at_least(&DwgVersion::R2007, &DwgVersion::R2000));
assert!(!version_at_least(&DwgVersion::R2000, &DwgVersion::R2007));
assert!(version_at_least(&DwgVersion::R2018, &DwgVersion::R13));
}
#[test]
fn resolve_null_handle() {
let href = HandleRef {
code: 4,
counter: 0,
value: 0,
};
assert_eq!(resolve_handle_ref(&href, 0x10).unwrap(), None);
}
#[test]
fn resolve_soft_pointer_is_absolute() {
let href = HandleRef {
code: 4,
counter: 1,
value: 0x13,
};
assert_eq!(resolve_handle_ref(&href, 0x10).unwrap(), Some(0x13));
}
#[test]
fn resolve_offset_plus_code_0a() {
let href = HandleRef {
code: 0x0A,
counter: 1,
value: 3,
};
assert_eq!(resolve_handle_ref(&href, 0x10).unwrap(), Some(0x13));
}
#[test]
fn empty_dictionary_data_r2000() {
let mut w = BitWriter::new();
w.write_bb(0b10).unwrap();
w.write_bb(0b10).unwrap();
w.write_rc(0).unwrap();
let bytes = w.into_bytes();
let mut reader = BitReader::new(&bytes);
let mut ctx = DictionaryDecodeCtx {
version: DwgVersion::R2000,
object_handle: 0x20,
handle_stream_bit_start: None,
string_reader: None,
};
let data = decode_dictionary_data(&mut reader, &mut ctx).unwrap();
assert_eq!(data.numitems, 0);
assert_eq!(data.cloning, Some(0));
assert_eq!(data.is_hardowner, Some(0));
assert!(data.names.is_empty());
}
}