use std::fmt;
use crate::span::ByteSpan;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ObjId {
pub num: u32,
pub generation: u16,
}
impl ObjId {
#[must_use]
pub const fn new(num: u32, generation: u16) -> Self {
Self { num, generation }
}
}
impl fmt::Display for ObjId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.num, self.generation)
}
}
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Name(pub Vec<u8>);
impl Name {
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
}
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl fmt::Display for Object {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Null => f.write_str("null"),
Self::Boolean(b) => write!(f, "{b}"),
Self::Integer(i) => write!(f, "{i}"),
Self::Real(r) => write!(f, "{r}"),
Self::String(bytes) => {
if bytes.iter().all(|&b| b.is_ascii_graphic() || b == b' ') {
write!(f, "({})", String::from_utf8_lossy(bytes))
} else {
f.write_str("<")?;
for &b in bytes {
write!(f, "{b:02X}")?;
}
f.write_str(">")
}
}
Self::Name(n) => write!(f, "{n}"),
Self::Array(items) => write!(f, "an array of {}", plural(items.len(), "item")),
Self::Dict(d) => write!(f, "a dictionary of {}", plural(d.len(), "entry")),
Self::Stream(st) => write!(f, "a stream of {}", plural(st.dict.len(), "entry")),
Self::Reference(id) => write!(f, "{id} R"),
}
}
}
fn plural(n: usize, noun: &str) -> String {
if n == 1 {
format!("1 {noun}")
} else if noun == "entry" {
format!("{n} entries")
} else {
format!("{n} {noun}s")
}
}
impl fmt::Debug for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "/")?;
for &b in &self.0 {
if b.is_ascii_graphic() && b != b'#' {
write!(f, "{}", b as char)?;
} else {
write!(f, "#{b:02X}")?;
}
}
Ok(())
}
}
impl From<&[u8]> for Name {
fn from(bytes: &[u8]) -> Self {
Self(bytes.to_vec())
}
}
impl<const N: usize> From<&[u8; N]> for Name {
fn from(bytes: &[u8; N]) -> Self {
Self(bytes.to_vec())
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Dict(pub Vec<(Name, Object)>);
impl Dict {
#[must_use]
pub const fn new() -> Self {
Self(Vec::new())
}
#[must_use]
pub fn get(&self, key: &[u8]) -> Option<&Object> {
self.0
.iter()
.find(|(k, _)| k.as_bytes() == key)
.map(|(_, v)| v)
.filter(|v| !matches!(v, Object::Null))
}
#[must_use]
pub fn contains_key(&self, key: &[u8]) -> bool {
self.get(key).is_some()
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&Name, &Object)> {
self.0.iter().map(|(k, v)| (k, v))
}
pub fn insert(&mut self, key: Name, value: Object) {
match self.0.iter_mut().find(|(k, _)| *k == key) {
Some(slot) => slot.1 = value,
None => self.0.push((key, value)),
}
}
pub fn remove(&mut self, key: &[u8]) -> Option<Object> {
let mut removed = None;
self.0.retain(|(k, v)| {
if k.as_bytes() == key {
if removed.is_none() {
removed = Some(v.clone());
}
false
} else {
true
}
});
removed
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stream {
pub dict: Dict,
pub data_span: ByteSpan,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Object {
Null,
Boolean(bool),
Integer(i64),
Real(f64),
String(Vec<u8>),
Name(Name),
Array(Vec<Object>),
Dict(Dict),
Stream(Stream),
Reference(ObjId),
}
impl Object {
#[must_use]
pub const fn as_int(&self) -> Option<i64> {
match self {
Self::Integer(v) => Some(*v),
_ => None,
}
}
#[must_use]
pub const fn as_number(&self) -> Option<f64> {
match self {
Self::Integer(v) => Some(*v as f64),
Self::Real(v) => Some(*v),
_ => None,
}
}
#[must_use]
pub fn as_name(&self) -> Option<&Name> {
match self {
Self::Name(n) => Some(n),
_ => None,
}
}
#[must_use]
pub fn as_dict(&self) -> Option<&Dict> {
match self {
Self::Dict(d) => Some(d),
Self::Stream(s) => Some(&s.dict),
_ => None,
}
}
#[must_use]
pub fn as_array(&self) -> Option<&[Object]> {
match self {
Self::Array(a) => Some(a),
_ => None,
}
}
#[must_use]
pub const fn as_reference(&self) -> Option<ObjId> {
match self {
Self::Reference(id) => Some(*id),
_ => None,
}
}
}
#[must_use]
pub fn equivalent_across_buffers(a: &Object, a_source: &[u8], b: &Object, b_source: &[u8]) -> bool {
match (a, b) {
(Object::Stream(x), Object::Stream(y)) => {
let xd = x.data_span.slice(a_source).unwrap_or(&[]);
let yd = y.data_span.slice(b_source).unwrap_or(&[]);
xd == yd && dicts_equivalent(&x.dict, a_source, &y.dict, b_source)
}
(Object::Dict(x), Object::Dict(y)) => dicts_equivalent(x, a_source, y, b_source),
(Object::Array(x), Object::Array(y)) => {
x.len() == y.len()
&& x.iter()
.zip(y.iter())
.all(|(i, j)| equivalent_across_buffers(i, a_source, j, b_source))
}
_ => a == b,
}
}
fn dicts_equivalent(a: &Dict, a_source: &[u8], b: &Dict, b_source: &[u8]) -> bool {
a.len() == b.len()
&& a.iter().zip(b.iter()).all(|((ak, av), (bk, bv))| {
ak == bk && equivalent_across_buffers(av, a_source, bv, b_source)
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Provenance {
File(ByteSpan),
RecoveredFile(ByteSpan),
ObjectStream {
container: ObjId,
index: u32,
},
}
impl Provenance {
#[must_use]
pub const fn file_span(self) -> Option<ByteSpan> {
match self {
Self::File(span) | Self::RecoveredFile(span) => Some(span),
Self::ObjectStream { .. } => None,
}
}
#[must_use]
pub const fn is_verbatim_safe(self) -> bool {
matches!(self, Self::File(_))
}
#[must_use]
pub const fn container(self) -> Option<ObjId> {
match self {
Self::File(_) | Self::RecoveredFile(_) => None,
Self::ObjectStream { container, .. } => Some(container),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct IndirectObject {
pub id: ObjId,
pub value: Object,
pub provenance: Provenance,
}
impl IndirectObject {
#[must_use]
pub const fn file_span(&self) -> Option<ByteSpan> {
self.provenance.file_span()
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
mod tests {
use super::*;
#[test]
fn provenance_separates_having_bytes_from_trusting_them() {
let span = ByteSpan::from_range(0..10);
let file = Provenance::File(span);
let recovered = Provenance::RecoveredFile(span);
let compressed = Provenance::ObjectStream {
container: ObjId::new(7, 0),
index: 2,
};
assert_eq!(file.file_span(), Some(span));
assert_eq!(recovered.file_span(), Some(span));
assert_eq!(compressed.file_span(), None);
assert!(file.is_verbatim_safe());
assert!(!recovered.is_verbatim_safe());
assert!(!compressed.is_verbatim_safe());
assert_eq!(file.container(), None);
assert_eq!(recovered.container(), None);
assert_eq!(compressed.container(), Some(ObjId::new(7, 0)));
}
#[test]
fn dict_null_value_collapses_to_absent() {
let mut d = Dict::new();
d.insert(Name::from(b"Alive"), Object::Integer(1));
d.insert(Name::from(b"Ghost"), Object::Null);
assert!(d.get(b"Alive").is_some());
assert!(d.get(b"Ghost").is_none());
assert!(!d.contains_key(b"Ghost"));
assert_eq!(d.len(), 2);
}
#[test]
fn dict_insert_replaces_in_place_preserving_order() {
let mut d = Dict::new();
d.insert(Name::from(b"A"), Object::Integer(1));
d.insert(Name::from(b"B"), Object::Integer(2));
d.insert(Name::from(b"A"), Object::Integer(9));
let keys: Vec<&[u8]> = d.iter().map(|(k, _)| k.as_bytes()).collect();
assert_eq!(keys, vec![&b"A"[..], b"B"]);
assert_eq!(d.get(b"A").unwrap().as_int(), Some(9));
}
#[test]
fn as_number_widens_integer_only() {
assert_eq!(Object::Integer(4).as_number(), Some(4.0));
assert_eq!(Object::Real(4.5).as_number(), Some(4.5));
assert_eq!(Object::Real(4.5).as_int(), None);
}
#[test]
fn stream_exposes_its_dict_via_as_dict() {
let s = Object::Stream(Stream {
dict: {
let mut d = Dict::new();
d.insert(Name::from(b"Length"), Object::Integer(0));
d
},
data_span: ByteSpan::new(0, 0),
});
assert!(s.as_dict().unwrap().contains_key(b"Length"));
}
#[test]
fn name_debug_form_is_readable() {
assert_eq!(format!("{:?}", Name::from(b"Type")), "/Type");
assert_eq!(format!("{:?}", Name::from(b"lime Green")), "/lime#20Green");
}
#[test]
fn objid_display_matches_reference_order() {
assert_eq!(ObjId::new(12, 3).to_string(), "12 3");
}
#[test]
fn cross_buffer_equivalence_ignores_stream_position() {
let mut dict = Dict::new();
dict.insert(Name::from(b"Length"), Object::Integer(2));
let a = Object::Stream(Stream {
dict: dict.clone(),
data_span: ByteSpan::new(0, 2),
});
let b = Object::Stream(Stream {
dict,
data_span: ByteSpan::new(5, 2),
});
assert_ne!(
a, b,
"derived equality is span-sensitive (that is the trap)"
);
assert!(equivalent_across_buffers(&a, b"hi", &b, b"xxxxxhi"));
}
#[test]
fn cross_buffer_equivalence_still_catches_real_differences() {
let a = Object::Stream(Stream {
dict: Dict::new(),
data_span: ByteSpan::new(0, 2),
});
let b = Object::Stream(Stream {
dict: Dict::new(),
data_span: ByteSpan::new(0, 2),
});
assert!(!equivalent_across_buffers(&a, b"hi", &b, b"ho"));
let mut d = Dict::new();
d.insert(Name::from(b"K"), Object::Integer(1));
let c = Object::Stream(Stream {
dict: d,
data_span: ByteSpan::new(0, 2),
});
assert!(!equivalent_across_buffers(&a, b"hi", &c, b"hi"));
}
#[test]
fn cross_buffer_equivalence_recurses_and_is_order_sensitive() {
let mut x = Dict::new();
x.insert(Name::from(b"A"), Object::Integer(1));
x.insert(Name::from(b"B"), Object::Integer(2));
let mut y = Dict::new();
y.insert(Name::from(b"B"), Object::Integer(2));
y.insert(Name::from(b"A"), Object::Integer(1));
assert!(!equivalent_across_buffers(
&Object::Dict(x.clone()),
b"",
&Object::Dict(y),
b""
));
assert!(equivalent_across_buffers(
&Object::Array(vec![Object::Dict(x.clone())]),
b"",
&Object::Array(vec![Object::Dict(x)]),
b""
));
assert!(!equivalent_across_buffers(
&Object::Array(vec![Object::Null]),
b"",
&Object::Array(vec![]),
b""
));
}
#[test]
fn provenance_distinguishes_file_backed_from_compressed_objects() {
let file = Provenance::File(ByteSpan::new(10, 20));
assert_eq!(file.file_span(), Some(ByteSpan::new(10, 20)));
assert_eq!(file.container(), None);
let compressed = Provenance::ObjectStream {
container: ObjId::new(7, 0),
index: 3,
};
assert_eq!(compressed.file_span(), None);
assert_eq!(compressed.container(), Some(ObjId::new(7, 0)));
}
}