use crate::error::{Error, Result};
use std::collections::BTreeMap;
use std::fmt;
use std::ops::Range;
use std::sync::Arc;
pub type ObjectId = (u32, u16);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StringFormat {
#[default]
Literal,
Hex,
}
#[derive(Clone, PartialEq)]
pub enum Object {
Null,
Boolean(bool),
Integer(i64),
Real(f64),
Name(Vec<u8>),
String(Vec<u8>, StringFormat),
Array(Vec<Object>),
Dictionary(Dictionary),
Stream(Stream),
Reference(ObjectId),
}
pub(crate) static NULL: Object = Object::Null;
fn type_error<T>(expected: &'static str, found: &Object) -> Result<T> {
Err(Error::Type { expected, found: found.type_name() })
}
impl Object {
pub fn string(bytes: impl Into<Vec<u8>>) -> Self {
Self::String(bytes.into(), StringFormat::Literal)
}
pub fn name(bytes: impl Into<Vec<u8>>) -> Self {
Self::Name(bytes.into())
}
#[must_use]
pub const fn type_name(&self) -> &'static str {
match self {
Self::Null => "null",
Self::Boolean(_) => "boolean",
Self::Integer(_) => "integer",
Self::Real(_) => "real",
Self::Name(_) => "name",
Self::String(..) => "string",
Self::Array(_) => "array",
Self::Dictionary(_) => "dictionary",
Self::Stream(_) => "stream",
Self::Reference(_) => "reference",
}
}
#[must_use]
pub const fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
pub fn as_bool(&self) -> Result<bool> {
match self {
Self::Boolean(b) => Ok(*b),
o => type_error("boolean", o),
}
}
pub fn as_i64(&self) -> Result<i64> {
match self {
Self::Integer(i) => Ok(*i),
#[allow(clippy::cast_possible_truncation)]
Self::Real(r) if r.fract() == 0.0 && r.abs() < 9.0e15 => Ok(*r as i64),
o => type_error("integer", o),
}
}
pub fn as_f64(&self) -> Result<f64> {
match self {
#[allow(clippy::cast_precision_loss)]
Self::Integer(i) => Ok(*i as f64),
Self::Real(r) => Ok(*r),
o => type_error("number", o),
}
}
pub fn as_name(&self) -> Result<&[u8]> {
match self {
Self::Name(n) => Ok(n),
o => type_error("name", o),
}
}
pub fn as_str(&self) -> Result<&[u8]> {
match self {
Self::String(s, _) => Ok(s),
o => type_error("string", o),
}
}
pub fn as_array(&self) -> Result<&[Object]> {
match self {
Self::Array(a) => Ok(a),
o => type_error("array", o),
}
}
pub fn as_array_mut(&mut self) -> Result<&mut Vec<Object>> {
match self {
Self::Array(a) => Ok(a),
o => type_error("array", o),
}
}
pub fn as_dict(&self) -> Result<&Dictionary> {
match self {
Self::Dictionary(d) => Ok(d),
Self::Stream(s) => Ok(&s.dict),
o => type_error("dictionary", o),
}
}
pub fn as_dict_mut(&mut self) -> Result<&mut Dictionary> {
match self {
Self::Dictionary(d) => Ok(d),
Self::Stream(s) => Ok(&mut s.dict),
o => type_error("dictionary", o),
}
}
pub fn as_stream(&self) -> Result<&Stream> {
match self {
Self::Stream(s) => Ok(s),
o => type_error("stream", o),
}
}
pub fn as_stream_mut(&mut self) -> Result<&mut Stream> {
match self {
Self::Stream(s) => Ok(s),
o => type_error("stream", o),
}
}
pub fn as_reference(&self) -> Result<ObjectId> {
match self {
Self::Reference(id) => Ok(*id),
o => type_error("reference", o),
}
}
}
impl fmt::Debug 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::Name(n) => write!(f, "/{}", String::from_utf8_lossy(n)),
Self::String(s, _) => write!(f, "({})", String::from_utf8_lossy(s)),
Self::Array(a) => f.debug_list().entries(a).finish(),
Self::Dictionary(d) => d.fmt(f),
Self::Stream(s) => write!(f, "{:?} stream[{} bytes]", s.dict, s.raw().len()),
Self::Reference((n, g)) => write!(f, "{n} {g} R"),
}
}
}
impl From<bool> for Object {
fn from(v: bool) -> Self {
Self::Boolean(v)
}
}
impl From<i64> for Object {
fn from(v: i64) -> Self {
Self::Integer(v)
}
}
impl From<i32> for Object {
fn from(v: i32) -> Self {
Self::Integer(i64::from(v))
}
}
impl From<u32> for Object {
fn from(v: u32) -> Self {
Self::Integer(i64::from(v))
}
}
impl From<usize> for Object {
fn from(v: usize) -> Self {
Self::Integer(i64::try_from(v).unwrap_or(i64::MAX))
}
}
impl From<f64> for Object {
fn from(v: f64) -> Self {
Self::Real(v)
}
}
impl From<f32> for Object {
fn from(v: f32) -> Self {
Self::Real(f64::from(v))
}
}
impl From<&str> for Object {
fn from(v: &str) -> Self {
Self::Name(v.as_bytes().to_vec())
}
}
impl From<Vec<Object>> for Object {
fn from(v: Vec<Object>) -> Self {
Self::Array(v)
}
}
impl From<Dictionary> for Object {
fn from(v: Dictionary) -> Self {
Self::Dictionary(v)
}
}
impl From<Stream> for Object {
fn from(v: Stream) -> Self {
Self::Stream(v)
}
}
impl From<ObjectId> for Object {
fn from(v: ObjectId) -> Self {
Self::Reference(v)
}
}
#[derive(Clone, PartialEq, Default)]
pub struct Dictionary(BTreeMap<Vec<u8>, Object>);
impl Dictionary {
#[must_use]
pub const fn new() -> Self {
Self(BTreeMap::new())
}
#[must_use]
pub fn get(&self, key: &[u8]) -> Option<&Object> {
self.0.get(key)
}
pub fn get_mut(&mut self, key: &[u8]) -> Option<&mut Object> {
self.0.get_mut(key)
}
pub fn require(&self, key: &[u8]) -> Result<&Object> {
self.0
.get(key)
.ok_or_else(|| Error::MissingKey(String::from_utf8_lossy(key).into_owned()))
}
#[must_use]
pub fn has(&self, key: &[u8]) -> bool {
self.0.contains_key(key)
}
pub fn set(&mut self, key: impl Into<Vec<u8>>, value: impl Into<Object>) {
self.0.insert(key.into(), value.into());
}
pub fn remove(&mut self, key: &[u8]) -> Option<Object> {
self.0.remove(key)
}
#[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 = (&[u8], &Object)> {
self.0.iter().map(|(k, v)| (k.as_slice(), v))
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&[u8], &mut Object)> {
self.0.iter_mut().map(|(k, v)| (k.as_slice(), v))
}
#[must_use]
pub fn get_name(&self, key: &[u8]) -> Option<&[u8]> {
self.get(key).and_then(|o| o.as_name().ok())
}
#[must_use]
pub fn get_i64(&self, key: &[u8]) -> Option<i64> {
self.get(key).and_then(|o| o.as_i64().ok())
}
#[must_use]
pub fn get_f64(&self, key: &[u8]) -> Option<f64> {
self.get(key).and_then(|o| o.as_f64().ok())
}
#[must_use]
pub fn get_bool(&self, key: &[u8]) -> Option<bool> {
self.get(key).and_then(|o| o.as_bool().ok())
}
#[must_use]
pub fn is_type(&self, ty: &[u8]) -> bool {
self.get_name(b"Type") == Some(ty)
}
}
impl fmt::Debug for Dictionary {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut m = f.debug_map();
for (k, v) in &self.0 {
m.entry(&format_args!("/{}", String::from_utf8_lossy(k)), v);
}
m.finish()
}
}
impl<K: Into<Vec<u8>>, V: Into<Object>> FromIterator<(K, V)> for Dictionary {
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let mut d = Self::new();
for (k, v) in iter {
d.set(k, v);
}
d
}
}
#[macro_export]
macro_rules! dictionary {
() => { $crate::Dictionary::new() };
($( $key:expr => $value:expr ),+ $(,)?) => {{
let mut d = $crate::Dictionary::new();
$( d.set($key, $value); )+
d
}};
}
#[derive(Clone)]
pub(crate) struct Blob {
buf: Arc<[u8]>,
range: Range<usize>,
}
impl Blob {
pub(crate) fn owned(data: Vec<u8>) -> Self {
let range = 0..data.len();
Self { buf: data.into(), range }
}
pub(crate) fn window(buf: &Arc<[u8]>, range: Range<usize>) -> Self {
let range = if range.start <= range.end && range.end <= buf.len() {
range
} else {
0..0
};
Self { buf: Arc::clone(buf), range }
}
pub(crate) fn as_slice(&self) -> &[u8] {
self.buf.get(self.range.clone()).unwrap_or(&[])
}
}
#[derive(Clone)]
pub struct Stream {
pub dict: Dictionary,
data: Blob,
}
impl Stream {
#[must_use]
pub fn new(mut dict: Dictionary, data: Vec<u8>) -> Self {
dict.set("Length", data.len());
Self { dict, data: Blob::owned(data) }
}
pub(crate) const fn from_blob(dict: Dictionary, data: Blob) -> Self {
Self { dict, data }
}
#[must_use]
pub fn raw(&self) -> &[u8] {
self.data.as_slice()
}
pub fn set_raw(&mut self, data: Vec<u8>) {
self.dict.set("Length", data.len());
self.data = Blob::owned(data);
}
pub fn set_plain(&mut self, plain: Vec<u8>) {
self.dict.remove(b"Filter");
self.dict.remove(b"DecodeParms");
self.set_raw(plain);
}
pub fn set_flate(&mut self, plain: &[u8]) {
self.dict.remove(b"DecodeParms");
self.dict.set("Filter", "FlateDecode");
self.set_raw(crate::filters::flate_encode(plain));
}
#[must_use]
pub fn filters(&self) -> Vec<&[u8]> {
match self.dict.get(b"Filter") {
Some(Object::Name(n)) => vec![n.as_slice()],
Some(Object::Array(a)) => a.iter().filter_map(|o| o.as_name().ok()).collect(),
_ => Vec::new(),
}
}
}
impl PartialEq for Stream {
fn eq(&self, other: &Self) -> bool {
self.dict == other.dict && self.raw() == other.raw()
}
}
impl fmt::Debug for Stream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?} stream[{} bytes]", self.dict, self.raw().len())
}
}