use std::io::Cursor;
use crate::error::Result;
const RDF_DESCRIPTION: &[u8] = b"rdf:Description";
const XMP_PACKET_END: &str = "<?xpacket end=\"w\"?>";
const MIN_PACKET_SIZE: usize = 4096;
#[derive(Debug, Clone)]
pub struct MiniXmp {
data: String,
}
impl MiniXmp {
pub fn new(xmp: impl Into<String>) -> Self {
Self { data: xmp.into() }
}
pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
std::str::from_utf8(bytes).ok().map(Self::new)
}
pub fn as_str(&self) -> &str {
&self.data
}
pub fn as_bytes(&self) -> &[u8] {
self.data.as_bytes()
}
pub fn into_string(self) -> String {
self.data
}
pub fn into_inner(self) -> String {
self.data
}
pub fn into_bytes(self) -> Vec<u8> {
self.data.into_bytes()
}
pub fn get(&self, key: &str) -> Option<String> {
get_keys_impl(&self.data, &[key])
.into_iter()
.next()
.flatten()
}
pub fn get_many(&self, keys: &[&str]) -> Vec<Option<String>> {
get_keys_impl(&self.data, keys)
}
pub fn set(&self, key: &str, value: &str) -> Result<Self> {
apply_updates_impl(&self.data, &[(key, Some(value))]).map(Self::new)
}
pub fn remove(&self, key: &str) -> Result<Self> {
apply_updates_impl(&self.data, &[(key, None)]).map(Self::new)
}
pub fn apply_updates(&self, updates: &[(&str, Option<&str>)]) -> Result<Self> {
apply_updates_impl(&self.data, updates).map(Self::new)
}
pub fn contains(&self, key: &str) -> bool {
self.get(key).is_some()
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
}
impl std::fmt::Display for MiniXmp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.data)
}
}
impl From<String> for MiniXmp {
fn from(s: String) -> Self {
Self::new(s)
}
}
impl From<&str> for MiniXmp {
fn from(s: &str) -> Self {
Self::new(s)
}
}
impl AsRef<str> for MiniXmp {
fn as_ref(&self) -> &str {
&self.data
}
}
fn validate_key(key: &str) -> Result<()> {
if key.is_empty() {
return Err(crate::Error::InvalidFormat(
"XMP key cannot be empty".to_string(),
));
}
if key.contains(|c: char| c.is_whitespace() || c == '"' || c == '\'' || c == '<' || c == '>') {
return Err(crate::Error::InvalidFormat(format!(
"Invalid XMP key '{}': contains whitespace or XML special characters",
key
)));
}
Ok(())
}
fn get_keys_impl(xmp: &str, keys: &[&str]) -> Vec<Option<String>> {
use quick_xml::{events::Event, name::QName, Reader};
let mut reader = Reader::from_str(xmp);
reader.config_mut().trim_text(true);
let mut results = vec![None; keys.len()];
loop {
match reader.read_event() {
Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e)) => {
if e.name() == QName(RDF_DESCRIPTION) {
for attr in e.attributes().flatten() {
for (i, key) in keys.iter().enumerate() {
if attr.key == QName(key.as_bytes()) {
if let Ok(s) = attr.decoded_and_normalized_value(
quick_xml::XmlVersion::Implicit1_0,
reader.decoder(),
) {
results[i] = Some(s.to_string());
}
}
}
}
} else {
for (i, key) in keys.iter().enumerate() {
if e.name() == QName(key.as_bytes()) {
if let Ok(s) = reader.read_text(e.name()) {
if let Ok(s) = s.xml_content(quick_xml::XmlVersion::Implicit1_0) {
if let Ok(s) = quick_xml::escape::unescape(&s) {
results[i] = Some(s.into_owned());
}
}
}
}
}
}
}
Ok(Event::Eof) => break,
_ => {}
}
}
results
}
fn detect_packet_size(xmp: &str) -> Option<usize> {
if xmp.contains("<?xpacket end") {
Some(xmp.len())
} else {
None
}
}
fn adjust_packet_padding(xmp: String, target_size: usize) -> String {
const END_MARKER: &str = "<?xpacket end";
let end_pos = match xmp.rfind(END_MARKER) {
Some(pos) => pos,
None => return xmp,
};
let content_end = xmp.as_bytes()[..end_pos]
.iter()
.rposition(|&b| !b.is_ascii_whitespace())
.map(|i| i + 1)
.unwrap_or(0);
let suffix = &xmp[end_pos..];
let non_padded_size = content_end + suffix.len();
let padding_len = target_size.saturating_sub(non_padded_size);
let mut result = String::with_capacity(content_end + padding_len + suffix.len());
result.push_str(&xmp[..content_end]);
for _ in 0..padding_len {
result.push(' ');
}
result.push_str(suffix);
result
}
fn format_packet_padding(len: usize) -> String {
let mut out = String::with_capacity(len + 2);
out.push('\n');
let mut remaining = len.saturating_sub(1);
if remaining > 0 {
remaining -= 1; while remaining > 0 {
let chunk = remaining.min(99);
out.extend(std::iter::repeat_n(' ', chunk));
remaining -= chunk;
if remaining > 0 {
out.push('\n');
remaining -= 1;
}
}
out.push('\n');
}
out
}
fn append_packet_wrapper(body: String) -> String {
let target_len = body.len().max(MIN_PACKET_SIZE);
let padding_len = target_len.saturating_sub(body.len());
let mut result = body;
result.push_str(&format_packet_padding(padding_len));
result.push_str(XMP_PACKET_END);
result
}
fn apply_updates_impl(xmp: &str, updates: &[(&str, Option<&str>)]) -> Result<String> {
use quick_xml::{
events::{BytesStart, Event},
name::QName,
Reader, Writer,
};
for (key, _) in updates {
validate_key(key)?;
}
let target_packet_size = detect_packet_size(xmp);
let mut reader = Reader::from_str(xmp);
reader.config_mut().trim_text(false);
reader.config_mut().expand_empty_elements = false;
let mut writer = Writer::new(Cursor::new(Vec::new()));
let mut applied = false;
let mut skipping_key: Option<Vec<u8>> = None;
let is_removal_key = |name: QName| {
updates
.iter()
.any(|(key, value)| value.is_none() && name == QName(key.as_bytes()))
};
loop {
let event = reader.read_event()?;
if let Some(skip_name) = &skipping_key {
match &event {
Event::End(e) if e.name().as_ref() == skip_name.as_slice() => {
skipping_key = None;
}
Event::Eof => break,
_ => {}
}
continue;
}
match event {
Event::Start(ref e) if is_removal_key(e.name()) => {
skipping_key = Some(e.name().as_ref().to_vec());
}
Event::Empty(ref e) if is_removal_key(e.name()) => {
}
Event::Start(ref e) if e.name() == QName(RDF_DESCRIPTION) && !applied => {
let elem_name = std::str::from_utf8(RDF_DESCRIPTION).map_err(|_| {
crate::Error::InvalidFormat("Invalid RDF_DESCRIPTION constant".into())
})?;
let mut elem = BytesStart::new(elem_name);
let mut seen_keys = std::collections::HashSet::new();
for attr_result in e.attributes() {
match attr_result {
Ok(attr) => {
let attr_key_str = std::str::from_utf8(attr.key.as_ref()).ok();
let mut handled = false;
if let Some(key_str) = attr_key_str {
seen_keys.insert(key_str.to_string());
for (update_key, update_value) in updates {
if key_str == *update_key {
if let Some(new_value) = update_value {
elem.push_attribute((*update_key, *new_value));
}
handled = true;
break;
}
}
}
if !handled {
elem.extend_attributes([attr]);
}
}
Err(e) => return Err(crate::Error::InvalidFormat(e.to_string())),
}
}
for (key, value) in updates {
if let Some(v) = value {
if !seen_keys.contains(*key) {
elem.push_attribute((*key, *v));
}
}
}
applied = true;
writer.write_event(Event::Start(elem))?;
}
Event::Empty(ref e) if e.name() == QName(RDF_DESCRIPTION) && !applied => {
let elem_name = std::str::from_utf8(RDF_DESCRIPTION).map_err(|_| {
crate::Error::InvalidFormat("Invalid RDF_DESCRIPTION constant".into())
})?;
let mut elem = BytesStart::new(elem_name);
let mut seen_keys = std::collections::HashSet::new();
for attr_result in e.attributes() {
match attr_result {
Ok(attr) => {
let attr_key_str = std::str::from_utf8(attr.key.as_ref()).ok();
let mut handled = false;
if let Some(key_str) = attr_key_str {
seen_keys.insert(key_str.to_string());
for (update_key, update_value) in updates {
if key_str == *update_key {
if let Some(new_value) = update_value {
elem.push_attribute((*update_key, *new_value));
}
handled = true;
break;
}
}
}
if !handled {
elem.extend_attributes([attr]);
}
}
Err(e) => return Err(crate::Error::InvalidFormat(e.to_string())),
}
}
for (key, value) in updates {
if let Some(v) = value {
if !seen_keys.contains(*key) {
elem.push_attribute((*key, *v));
}
}
}
applied = true;
writer.write_event(Event::Empty(elem))?;
}
Event::Eof => break,
e => writer.write_event(e)?,
}
}
let result = writer.into_inner().into_inner();
let result_str =
String::from_utf8(result).map_err(|e| crate::Error::InvalidFormat(e.to_string()))?;
match target_packet_size {
Some(target_size) => Ok(adjust_packet_padding(result_str, target_size)),
None => Ok(append_packet_wrapper(result_str)),
}
}
#[cfg(test)]
mod tests {
use super::*;
const TEST_XMP: &str = r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/"
dc:format="image/jpeg"
xmpMM:DocumentID="xmp.did:1234">
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>"#;
#[test]
fn test_get_key() {
let xmp = MiniXmp::new(TEST_XMP);
assert_eq!(xmp.get("dc:format"), Some("image/jpeg".to_string()));
assert_eq!(
xmp.get("xmpMM:DocumentID"),
Some("xmp.did:1234".to_string())
);
assert_eq!(xmp.get("nonexistent"), None);
}
#[test]
fn test_add_key() {
let xmp = MiniXmp::new(TEST_XMP);
let updated = xmp.set("dc:title", "My Photo").unwrap();
assert_eq!(updated.get("dc:title"), Some("My Photo".to_string()));
assert_eq!(updated.get("dc:format"), Some("image/jpeg".to_string()));
}
#[test]
fn test_replace_key() {
let xmp = MiniXmp::new(TEST_XMP);
let updated = xmp.set("dc:format", "image/png").unwrap();
assert_eq!(updated.get("dc:format"), Some("image/png".to_string()));
}
#[test]
fn test_remove_key() {
let xmp = MiniXmp::new(TEST_XMP);
let updated = xmp.remove("dc:format").unwrap();
assert_eq!(updated.get("dc:format"), None);
assert_eq!(
updated.get("xmpMM:DocumentID"),
Some("xmp.did:1234".to_string())
);
}
#[test]
fn test_remove_nonexistent_key() {
let xmp = MiniXmp::new(TEST_XMP);
let updated = xmp.remove("nonexistent").unwrap();
assert_eq!(updated.get("dc:format"), Some("image/jpeg".to_string()));
}
#[test]
fn test_remove_key_stored_as_element() {
let xmp = MiniXmp::new(
r#"<rdf:Description dc:format="image/jpeg"><dc:title>Photo</dc:title></rdf:Description>"#,
);
assert_eq!(xmp.get("dc:title"), Some("Photo".to_string()));
let updated = xmp.remove("dc:title").unwrap();
assert_eq!(updated.get("dc:title"), None);
assert!(!updated.as_str().contains("dc:title"));
assert_eq!(updated.get("dc:format"), Some("image/jpeg".to_string()));
}
#[test]
fn test_remove_self_closing_key_element() {
let xmp = MiniXmp::new(r#"<rdf:Description><dc:title/></rdf:Description>"#);
let updated = xmp.remove("dc:title").unwrap();
assert_eq!(updated.get("dc:title"), None);
assert!(!updated.as_str().contains("dc:title"));
}
#[test]
fn test_get_keys_batch() {
let xmp = MiniXmp::new(TEST_XMP);
let values = xmp.get_many(&["dc:format", "xmpMM:DocumentID", "nonexistent"]);
assert_eq!(values.len(), 3);
assert_eq!(values[0], Some("image/jpeg".to_string()));
assert_eq!(values[1], Some("xmp.did:1234".to_string()));
assert_eq!(values[2], None);
}
#[test]
fn test_get_unescapes_attribute_and_element_values() {
let xmp = MiniXmp::new(
r#"<rdf:Description dc:attribute="Tom & Jerry"><dc:element>Tom & Jerry</dc:element></rdf:Description>"#,
);
assert_eq!(xmp.get("dc:attribute"), Some("Tom & Jerry".to_string()));
assert_eq!(xmp.get("dc:element"), Some("Tom & Jerry".to_string()));
}
#[test]
fn test_get_keys_empty() {
let xmp = MiniXmp::new(TEST_XMP);
let values = xmp.get_many(&[]);
assert_eq!(values.len(), 0);
}
#[test]
fn test_apply_updates_add_and_replace() {
let xmp = MiniXmp::new(TEST_XMP);
let updates = [
("dc:title", Some("My Photo")),
("dc:format", Some("image/png")), ("dc:subject", Some("Landscape")), ];
let updated = xmp.apply_updates(&updates).unwrap();
assert_eq!(updated.get("dc:title"), Some("My Photo".to_string()));
assert_eq!(updated.get("dc:format"), Some("image/png".to_string()));
assert_eq!(updated.get("dc:subject"), Some("Landscape".to_string()));
assert_eq!(
updated.get("xmpMM:DocumentID"),
Some("xmp.did:1234".to_string())
);
}
#[test]
fn test_apply_updates_remove() {
let xmp = MiniXmp::new(TEST_XMP);
let updates = [
("dc:format", None), ("dc:title", Some("New")), ];
let updated = xmp.apply_updates(&updates).unwrap();
assert_eq!(updated.get("dc:format"), None);
assert_eq!(updated.get("dc:title"), Some("New".to_string()));
assert_eq!(
updated.get("xmpMM:DocumentID"),
Some("xmp.did:1234".to_string())
);
}
#[test]
fn test_apply_updates_mixed() {
let xmp = MiniXmp::new(TEST_XMP);
let updates = [
("dc:format", Some("image/png")), ("dc:title", Some("Photo")), ("xmpMM:DocumentID", None), ("dc:creator", Some("John")), ];
let updated = xmp.apply_updates(&updates).unwrap();
assert_eq!(updated.get("dc:format"), Some("image/png".to_string()));
assert_eq!(updated.get("dc:title"), Some("Photo".to_string()));
assert_eq!(updated.get("xmpMM:DocumentID"), None);
assert_eq!(updated.get("dc:creator"), Some("John".to_string()));
}
#[test]
fn test_batch_vs_single_consistency() {
let xmp = MiniXmp::new(TEST_XMP);
let batch_result = xmp.apply_updates(&[("dc:title", Some("Test"))]).unwrap();
let single_result = xmp.set("dc:title", "Test").unwrap();
assert_eq!(batch_result.get("dc:title"), single_result.get("dc:title"));
}
#[test]
fn test_xml_entity_escaping() {
let test_cases = [
("&", "ampersand"),
("<", "less than"),
(">", "greater than"),
("\"", "double quote"),
("'", "single quote"),
("Photo & Video", "mixed ampersand"),
("<tag>", "tags"),
("Quote: \"test\"", "quoted text"),
];
let xmp = MiniXmp::new(r#"<rdf:Description />"#);
for (input, description) in test_cases {
let updated = xmp.set("dc:title", input).unwrap();
let value = updated.get("dc:title");
assert_eq!(
value,
Some(input.to_string()),
"XML entity round-trip failed for {}: input={:?}",
description,
input
);
}
}
#[test]
fn test_key_validation() {
let xmp = MiniXmp::new(r#"<rdf:Description dc:title="Photo" />"#);
assert!(xmp.set("", "value").is_err(), "Empty key should fail");
assert!(
xmp.set("dc:title with space", "value").is_err(),
"Key with space should fail"
);
assert!(
xmp.set("dc:title\"quote", "value").is_err(),
"Key with quote should fail"
);
assert!(
xmp.set("dc:title<tag", "value").is_err(),
"Key with < should fail"
);
assert!(
xmp.set("dc:title>tag", "value").is_err(),
"Key with > should fail"
);
assert!(
xmp.set("dc:title", "value").is_ok(),
"Normal key should work"
);
assert!(
xmp.set("dc:subject", "value").is_ok(),
"Another normal key should work"
);
assert!(
xmp.set("my_custom:field", "value").is_ok(),
"Underscore key should work"
);
}
#[test]
fn test_multiple_rdf_description_blocks() {
let xmp_str = r#"<?xml version="1.0"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/">
<rdf:Description rdf:about=""
dc:title="First Block Title"
dc:creator="Alice">
</rdf:Description>
<rdf:Description rdf:about=""
photoshop:DateCreated="2024-01-15"
dc:title="Second Block Title">
</rdf:Description>
<rdf:Description rdf:about=""
dc:subject="Landscape">
</rdf:Description>
</rdf:RDF>"#;
let xmp = MiniXmp::new(xmp_str);
let values = xmp.get_many(&[
"dc:title",
"dc:creator",
"photoshop:DateCreated",
"dc:subject",
]);
assert_eq!(
values[0],
Some("Second Block Title".to_string()),
"Should get title from second block (last wins)"
);
assert_eq!(
values[1],
Some("Alice".to_string()),
"Should get creator from first block"
);
assert_eq!(
values[2],
Some("2024-01-15".to_string()),
"Should get date from second block"
);
assert_eq!(
values[3],
Some("Landscape".to_string()),
"Should get subject from third block"
);
assert_eq!(xmp.get("dc:title"), Some("Second Block Title".to_string()));
assert_eq!(xmp.get("dc:creator"), Some("Alice".to_string()));
assert_eq!(
xmp.get("photoshop:DateCreated"),
Some("2024-01-15".to_string())
);
}
#[test]
fn test_write_only_modifies_first_block() {
let xmp = MiniXmp::new(
r#"<rdf:RDF>
<rdf:Description dc:title="First" dc:creator="Alice" />
<rdf:Description photoshop:DateCreated="2024-01-15" />
</rdf:RDF>"#,
);
let updated = xmp
.apply_updates(&[("dc:title", Some("Modified"))])
.unwrap();
assert!(
updated.as_ref().contains("dc:title=\"Modified\""),
"First block should be updated"
);
assert!(
updated
.as_ref()
.contains("photoshop:DateCreated=\"2024-01-15\""),
"Second block should be preserved"
);
let values = updated.get_many(&["dc:title", "photoshop:DateCreated"]);
assert_eq!(values[0], Some("Modified".to_string()));
assert_eq!(values[1], Some("2024-01-15".to_string()));
}
#[test]
fn test_contains() {
let xmp = MiniXmp::new(TEST_XMP);
assert!(xmp.contains("dc:format"));
assert!(!xmp.contains("nonexistent"));
}
#[test]
fn test_into_inner() {
let xmp = MiniXmp::new(TEST_XMP);
let inner: String = xmp.into_inner();
assert!(inner.contains("dc:format"));
}
#[test]
fn test_as_ref() {
let xmp = MiniXmp::new(TEST_XMP);
let s: &str = xmp.as_ref();
assert!(s.contains("dc:format"));
}
fn make_padded_xmp(padding: usize) -> String {
let content = r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description dc:title="Photo" dc:format="image/jpeg" />
</rdf:RDF>
</x:xmpmeta>"#;
format!(
"{}{:>width$}<?xpacket end=\"w\"?>",
content,
"",
width = padding
)
}
#[test]
fn test_packet_padding_maintained_on_shrink() {
let xmp_str = make_padded_xmp(500);
let original_size = xmp_str.len();
let xmp = MiniXmp::new(xmp_str);
let updated = xmp.remove("dc:format").unwrap();
assert_eq!(
updated.len(),
original_size,
"Packet size should be unchanged after removal"
);
assert_eq!(updated.get("dc:format"), None);
assert_eq!(updated.get("dc:title"), Some("Photo".to_string()));
}
#[test]
fn test_packet_padding_maintained_on_add() {
let xmp_str = make_padded_xmp(500);
let original_size = xmp_str.len();
let xmp = MiniXmp::new(xmp_str);
let updated = xmp.set("dc:creator", "John").unwrap();
assert_eq!(
updated.len(),
original_size,
"Packet size should be unchanged after add within padding"
);
assert_eq!(updated.get("dc:creator"), Some("John".to_string()));
}
#[test]
fn test_packet_padding_grows_when_content_exceeds_original() {
let xmp_str = make_padded_xmp(3);
let original_size = xmp_str.len();
let xmp = MiniXmp::new(xmp_str);
let large_value = "x".repeat(500);
let updated = xmp.set("dc:description", &large_value).unwrap();
assert!(
updated.len() > original_size,
"Packet should grow when content exceeds original size"
);
assert_eq!(updated.get("dc:description"), Some(large_value));
}
#[test]
fn test_write_adds_packet_wrapper_with_min_padding() {
let xmp = MiniXmp::new(r#"<rdf:Description dc:title="Photo" />"#);
let updated = xmp.set("dc:creator", "John").unwrap();
assert!(updated.as_str().contains("<?xpacket end"));
assert!(
updated.len() >= MIN_PACKET_SIZE,
"Fresh packet should reserve at least the minimum padding"
);
assert_eq!(updated.get("dc:creator"), Some("John".to_string()));
}
#[test]
fn test_write_wraps_large_content_without_shrinking_below_min() {
let large_value = "x".repeat(5000);
let xmp = MiniXmp::new(r#"<rdf:Description />"#);
let updated = xmp.set("dc:description", &large_value).unwrap();
assert!(updated.as_str().ends_with("<?xpacket end=\"w\"?>"));
assert_eq!(updated.get("dc:description"), Some(large_value));
}
}