use std::fmt::{self, Write as _};
use std::str::FromStr;
use laminapdf_cos::{DirectPath, Error, ObjRef, PathSegment};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Kind {
Page,
OutlineItem,
Annot,
Field,
}
impl Kind {
const fn letter(self) -> char {
match self {
Self::Page => 'p',
Self::OutlineItem => 'o',
Self::Annot => 'a',
Self::Field => 'f',
}
}
const fn from_letter(c: char) -> Option<Self> {
match c {
'p' => Some(Self::Page),
'o' => Some(Self::OutlineItem),
'a' => Some(Self::Annot),
'f' => Some(Self::Field),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Anchor {
Object(ObjRef),
Trailer,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Segment {
Key(Box<str>),
Index(usize),
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LaminaPdfId {
kind: Kind,
anchor: Anchor,
path: Box<[Segment]>,
}
impl LaminaPdfId {
#[must_use]
pub fn object(kind: Kind, r: ObjRef) -> Self {
Self {
kind,
anchor: Anchor::Object(r),
path: Box::new([]),
}
}
#[must_use]
pub fn path(kind: Kind, path: &DirectPath) -> Self {
let segments = path
.segments
.iter()
.map(|s| match *s {
PathSegment::Key(k) => Segment::Key(k.into()),
PathSegment::Index(i) => Segment::Index(i),
})
.collect();
Self {
kind,
anchor: path.anchor.map_or(Anchor::Trailer, Anchor::Object),
path: segments,
}
}
#[must_use]
pub const fn kind(&self) -> Kind {
self.kind
}
#[must_use]
pub const fn obj_ref(&self) -> Option<ObjRef> {
match self.anchor {
Anchor::Object(r) if self.path.is_empty() => Some(r),
_ => None,
}
}
#[must_use]
pub const fn is_path(&self) -> bool {
!self.path.is_empty()
}
}
impl fmt::Display for LaminaPdfId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind.letter())?;
match self.anchor {
Anchor::Object(r) => write!(f, "{}.{}", r.num, r.gen_nr)?,
Anchor::Trailer => f.write_str("t")?,
}
for segment in &self.path {
match segment {
Segment::Key(k) => write!(f, "/{}", escape_key(k))?,
Segment::Index(i) => write!(f, "/{i}")?,
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseIdError {
#[error("not a lamina ID")]
Syntax(String),
#[error("expected a {expected:?} ID, found a {found:?} ID")]
WrongKind {
expected: Kind,
found: Kind,
},
}
fn canonical_number<T: FromStr>(s: &str) -> Option<T> {
let canonical = !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0'));
canonical.then(|| s.parse().ok()).flatten()
}
fn escape_key(key: &str) -> String {
if key.is_empty() {
return "#".to_owned();
}
let mut out = String::with_capacity(key.len());
for (i, b) in key.bytes().enumerate() {
if b.is_ascii_alphabetic() || (b.is_ascii_digit() && i > 0) {
out.push(char::from(b));
} else {
let _ = write!(out, "#{b:02X}");
}
}
out
}
fn unescape_key(part: &str) -> Option<String> {
if part == "#" {
return Some(String::new());
}
let bytes = part.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while let Some(&b) = bytes.get(i) {
if b == b'#' {
let hex = part.get(i + 1..i + 3)?;
if !hex.bytes().all(|h| h.is_ascii_digit() || (b'A'..=b'F').contains(&h)) {
return None;
}
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else if b.is_ascii_alphanumeric() && !(i == 0 && b.is_ascii_digit()) {
out.push(b);
i += 1;
} else {
return None;
}
}
let key = String::from_utf8(out).ok()?;
(escape_key(&key) == part).then_some(key)
}
impl FromStr for LaminaPdfId {
type Err = ParseIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseIdError::Syntax(s.to_owned());
let mut chars = s.chars();
let kind = chars.next().and_then(Kind::from_letter).ok_or_else(err)?;
let mut parts = chars.as_str().split('/');
let anchor = match parts.next().ok_or_else(err)? {
"t" => Anchor::Trailer,
head => {
let (num, gen_nr) = head.split_once('.').ok_or_else(err)?;
let num = canonical_number(num).ok_or_else(err)?;
let gen_nr = canonical_number(gen_nr).ok_or_else(err)?;
Anchor::Object(ObjRef::new(num, gen_nr))
}
};
let path = parts
.map(|part| {
if let Some(i) = canonical_number(part) {
Some(Segment::Index(i))
} else {
unescape_key(part).map(|k| Segment::Key(k.into()))
}
})
.collect::<Option<Box<[Segment]>>>()
.ok_or_else(err)?;
Ok(Self { kind, anchor, path })
}
}
macro_rules! typed_id {
($(#[$doc:meta])* $name:ident, $kind:expr) => {
$(#[$doc])*
#[doc = ""]
#[doc = "Added in 0.2.0."]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct $name(LaminaPdfId);
impl $name {
pub const KIND: Kind = $kind;
#[must_use]
pub fn object(r: ObjRef) -> Self {
Self(LaminaPdfId::object(Self::KIND, r))
}
#[must_use]
pub fn path(path: &DirectPath) -> Self {
Self(LaminaPdfId::path(Self::KIND, path))
}
#[must_use]
pub const fn as_lamina_id(&self) -> &LaminaPdfId {
&self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for $name {
type Err = ParseIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s.parse::<LaminaPdfId>()?)
}
}
impl TryFrom<LaminaPdfId> for $name {
type Error = ParseIdError;
fn try_from(id: LaminaPdfId) -> Result<Self, Self::Error> {
if id.kind == Self::KIND {
Ok(Self(id))
} else {
Err(ParseIdError::WrongKind {
expected: Self::KIND,
found: id.kind,
})
}
}
}
impl From<$name> for LaminaPdfId {
fn from(id: $name) -> Self {
id.0
}
}
};
}
typed_id!(
PageId,
Kind::Page
);
typed_id!(
OutlineItemId,
Kind::OutlineItem
);
typed_id!(
AnnotId,
Kind::Annot
);
typed_id!(
FieldId,
Kind::Field
);
#[derive(Debug, Clone, Copy)]
pub struct IdAllocator<'d> {
cos: &'d laminapdf_cos::Document,
}
impl<'d> IdAllocator<'d> {
#[must_use]
pub const fn new(cos: &'d laminapdf_cos::Document) -> Self {
Self { cos }
}
#[must_use]
pub fn is_allocated(&self, id: &LaminaPdfId) -> bool {
id.obj_ref()
.is_some_and(|r| r.gen_nr == 0 && self.cos.is_reserved_number(r.num))
}
pub fn allocate(&self, kind: Kind) -> Result<(ObjRef, LaminaPdfId), Error> {
let r = self.cos.reserve_number()?;
Ok((r, LaminaPdfId::object(kind, r)))
}
}
#[cfg(test)]
mod tests {
use super::{escape_key, unescape_key};
#[test]
fn keys_with_any_characters_round_trip_and_never_read_as_indexes() {
for key in ["Kids", "My-Key", "A_B", "3D", "0", "", "รnรฏ", "a/b#c"] {
let escaped = escape_key(key);
assert_eq!(unescape_key(&escaped).as_deref(), Some(key), "{key:?} -> {escaped:?}");
assert!(escaped.parse::<usize>().is_err(), "{key:?} must not look like an index");
}
}
#[test]
fn non_canonical_key_spellings_are_rejected() {
for part in ["#4B", "my-key", "#zz", "#4"] {
assert_eq!(unescape_key(part), None, "{part:?}");
}
}
use super::*;
fn round_trip(s: &str) -> String {
s.parse::<LaminaPdfId>().unwrap().to_string()
}
#[test]
fn object_ids_round_trip_through_their_string_form() {
for s in ["p12.0", "o1.3", "a0.0", "f4294967295.65535"] {
assert_eq!(round_trip(s), s);
}
}
#[test]
fn path_ids_round_trip_through_their_string_form() {
for s in [
"p5.0/Kids/3",
"p1.0/Pages/Kids/0/Kids/12",
"pt/Root/Pages/Kids/0",
"o9.0/First/Next",
] {
assert_eq!(round_trip(s), s);
}
}
#[test]
fn parse_rejects_malformed_strings() {
for s in [
"",
"p",
"x1.0",
"p1",
"p1.",
"p.0",
"p01.0",
"p1.00",
"p-1.0",
"p1.0/",
"p1.0//Kids",
"p1.0/Ki ds",
"p1.0/3x",
"p4294967296.0",
"p1.65536",
"p1.0/07",
] {
assert!(s.parse::<LaminaPdfId>().is_err(), "{s:?}");
}
}
#[test]
fn path_id_from_a_direct_path_names_anchor_and_steps() {
let path = DirectPath::new(
Some(ObjRef::new(5, 0)),
vec![PathSegment::Key("Kids"), PathSegment::Index(3)],
);
assert_eq!(PageId::path(&path).to_string(), "p5.0/Kids/3");
}
#[test]
fn obj_ref_is_only_set_for_object_ids() {
let object: LaminaPdfId = "p3.1".parse().unwrap();
let path: LaminaPdfId = "p3.1/Kids/0".parse().unwrap();
assert_eq!((object.obj_ref(), path.obj_ref()), (Some(ObjRef::new(3, 1)), None));
}
#[test]
fn typed_ids_reject_another_kind() {
assert_eq!(
"o3.0".parse::<PageId>(),
Err(ParseIdError::WrongKind {
expected: Kind::Page,
found: Kind::OutlineItem
})
);
}
#[test]
fn typed_ids_parse_their_own_kind() {
let id: OutlineItemId = "o3.0".parse().unwrap();
assert_eq!(id, OutlineItemId::object(ObjRef::new(3, 0)));
}
#[test]
fn ids_of_different_kinds_for_one_object_differ() {
let r = ObjRef::new(7, 0);
assert_ne!(LaminaPdfId::object(Kind::Page, r), LaminaPdfId::object(Kind::Annot, r));
}
#[test]
fn a_trailer_rooted_empty_path_round_trips() {
let id = LaminaPdfId::path(Kind::Page, &DirectPath::new(None, Vec::new()));
assert_eq!(id.to_string().parse::<LaminaPdfId>().unwrap(), id);
}
}