xmpkit 0.1.6

Pure Rust implementation of Adobe XMP Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! XMP node types
//!
//! This module defines the node types used in the XMP data model:
//! - SimpleNode: A simple value node
//! - ArrayNode: An array of nodes (ordered, unordered, or alternative)
//! - StructureNode: A structure containing named fields

use crate::core::error::{XmpError, XmpResult};
use crate::types::qualifier::Qualifier;
use indexmap::IndexMap;

/// Type of array node
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArrayType {
    /// Ordered array (rdf:Seq)
    Ordered,
    /// Unordered array (rdf:Bag)
    Unordered,
    /// Alternative array (rdf:Alt)
    Alternative,
}

impl ArrayType {
    /// Get the RDF type name for this array type
    pub fn rdf_type(&self) -> &'static str {
        match self {
            ArrayType::Ordered => "Seq",
            ArrayType::Unordered => "Bag",
            ArrayType::Alternative => "Alt",
        }
    }
}

/// A simple value node
#[derive(Debug, Clone)]
pub struct SimpleNode {
    /// The value of the node
    pub value: String,
    /// Qualifiers attached to this node
    pub qualifiers: Vec<Qualifier>,
}

impl SimpleNode {
    /// Create a new simple node
    pub fn new(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            qualifiers: Vec::new(),
        }
    }

    /// Add a qualifier to this node
    pub fn add_qualifier(&mut self, qualifier: Qualifier) {
        self.qualifiers.push(qualifier);
    }

    /// Get a qualifier by name
    pub fn get_qualifier(&self, namespace: &str, name: &str) -> Option<&Qualifier> {
        self.qualifiers
            .iter()
            .find(|q| q.namespace == namespace && q.name == name)
    }

    /// Remove a qualifier
    pub fn remove_qualifier(&mut self, namespace: &str, name: &str) -> bool {
        let initial_len = self.qualifiers.len();
        self.qualifiers
            .retain(|q| !(q.namespace == namespace && q.name == name));
        self.qualifiers.len() < initial_len
    }
}

/// An array node containing multiple child nodes
#[derive(Debug, Clone)]
pub struct ArrayNode {
    /// The items in the array
    pub items: Vec<Node>,
    /// The type of array
    pub array_type: ArrayType,
    /// Qualifiers attached to this node
    pub qualifiers: Vec<Qualifier>,
}

impl ArrayNode {
    /// Create a new array node
    pub fn new(array_type: ArrayType) -> Self {
        Self {
            items: Vec::new(),
            array_type,
            qualifiers: Vec::new(),
        }
    }

    /// Get the number of items in the array
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Check if the array is empty
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Get an item by index
    pub fn get(&self, index: usize) -> Option<&Node> {
        self.items.get(index)
    }

    /// Get a mutable reference to an item by index
    pub fn get_mut(&mut self, index: usize) -> Option<&mut Node> {
        self.items.get_mut(index)
    }

    /// Append an item to the array
    pub fn append(&mut self, node: Node) {
        self.items.push(node);
    }

    /// Insert an item at a specific index
    pub fn insert(&mut self, index: usize, node: Node) -> XmpResult<()> {
        if index > self.items.len() {
            return Err(XmpError::BadParam(format!(
                "Index {} out of bounds for array of length {}",
                index,
                self.items.len()
            )));
        }
        self.items.insert(index, node);
        Ok(())
    }

    /// Remove an item at a specific index
    pub fn remove(&mut self, index: usize) -> XmpResult<Node> {
        if index >= self.items.len() {
            return Err(XmpError::BadParam(format!(
                "Index {} out of bounds for array of length {}",
                index,
                self.items.len()
            )));
        }
        Ok(self.items.remove(index))
    }

    /// Add a qualifier to this node
    pub fn add_qualifier(&mut self, qualifier: Qualifier) {
        self.qualifiers.push(qualifier);
    }

    /// Get a qualifier by name
    pub fn get_qualifier(&self, namespace: &str, name: &str) -> Option<&Qualifier> {
        self.qualifiers
            .iter()
            .find(|q| q.namespace == namespace && q.name == name)
    }
}

/// A structure node containing named fields
#[derive(Debug, Clone)]
pub struct StructureNode {
    /// The fields in the structure
    pub fields: IndexMap<String, Node>,
    /// Qualifiers attached to this node
    pub qualifiers: Vec<Qualifier>,
}

impl StructureNode {
    /// Create a new structure node
    pub fn new() -> Self {
        Self {
            fields: IndexMap::new(),
            qualifiers: Vec::new(),
        }
    }

    /// Get a field by name
    pub fn get_field(&self, name: &str) -> Option<&Node> {
        self.fields.get(name)
    }

    /// Get a mutable reference to a field by name
    pub fn get_field_mut(&mut self, name: &str) -> Option<&mut Node> {
        self.fields.get_mut(name)
    }

    /// Set a field
    pub fn set_field(&mut self, name: impl Into<String>, node: Node) {
        self.fields.insert(name.into(), node);
    }

    /// Remove a field
    pub fn remove_field(&mut self, name: &str) -> Option<Node> {
        self.fields.shift_remove(name)
    }

    /// Check if a field exists
    pub fn has_field(&self, name: &str) -> bool {
        self.fields.contains_key(name)
    }

    /// Get all field names
    pub fn field_names(&self) -> impl Iterator<Item = &String> {
        self.fields.keys()
    }

    /// Add a qualifier to this node
    pub fn add_qualifier(&mut self, qualifier: Qualifier) {
        self.qualifiers.push(qualifier);
    }

    /// Get a qualifier by name
    pub fn get_qualifier(&self, namespace: &str, name: &str) -> Option<&Qualifier> {
        self.qualifiers
            .iter()
            .find(|q| q.namespace == namespace && q.name == name)
    }
}

impl Default for StructureNode {
    fn default() -> Self {
        Self::new()
    }
}

/// A node in the XMP data model
#[derive(Debug, Clone)]
pub enum Node {
    /// A simple value node
    Simple(SimpleNode),
    /// An array node
    Array(ArrayNode),
    /// A structure node
    Structure(StructureNode),
}

impl From<&Node> for crate::XmpValue {
    fn from(node: &Node) -> Self {
        match node {
            Node::Simple(node) => Self::String(node.value.clone()),
            Node::Array(node) => {
                let array = node.items.iter().map(|item| item.into()).collect();
                Self::Array(array)
            }
            Node::Structure(node) => {
                let values = node
                    .fields
                    .iter()
                    .map(|(key, value)| (key.into(), value.into()));
                Self::Structure(std::collections::HashMap::from_iter(values))
            }
        }
    }
}

impl Node {
    /// Create a new simple node
    pub fn simple(value: impl Into<String>) -> Self {
        Node::Simple(SimpleNode::new(value))
    }

    /// Create a new array node
    pub fn array(array_type: ArrayType) -> Self {
        Node::Array(ArrayNode::new(array_type))
    }

    /// Create a new structure node
    pub fn structure() -> Self {
        Node::Structure(StructureNode::new())
    }

    /// Check if this is a simple node
    pub fn is_simple(&self) -> bool {
        matches!(self, Node::Simple(_))
    }

    /// Check if this is an array node
    pub fn is_array(&self) -> bool {
        matches!(self, Node::Array(_))
    }

    /// Check if this is a structure node
    pub fn is_structure(&self) -> bool {
        matches!(self, Node::Structure(_))
    }

    /// Get the simple node, if this is a simple node
    pub fn as_simple(&self) -> Option<&SimpleNode> {
        match self {
            Node::Simple(node) => Some(node),
            _ => None,
        }
    }

    /// Get the array node, if this is an array node
    pub fn as_array(&self) -> Option<&ArrayNode> {
        match self {
            Node::Array(node) => Some(node),
            _ => None,
        }
    }

    /// Get the structure node, if this is a structure node
    pub fn as_structure(&self) -> Option<&StructureNode> {
        match self {
            Node::Structure(node) => Some(node),
            _ => None,
        }
    }

    /// Get a mutable reference to the simple node, if this is a simple node
    pub fn as_simple_mut(&mut self) -> Option<&mut SimpleNode> {
        match self {
            Node::Simple(node) => Some(node),
            _ => None,
        }
    }

    /// Get a mutable reference to the array node, if this is an array node
    pub fn as_array_mut(&mut self) -> Option<&mut ArrayNode> {
        match self {
            Node::Array(node) => Some(node),
            _ => None,
        }
    }

    /// Get a mutable reference to the structure node, if this is a structure node
    pub fn as_structure_mut(&mut self) -> Option<&mut StructureNode> {
        match self {
            Node::Structure(node) => Some(node),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_node() {
        let mut node = SimpleNode::new("test");
        assert_eq!(node.value, "test");
        assert_eq!(node.qualifiers.len(), 0);

        let qual = Qualifier::new("http://ns.adobe.com/xap/1.0/", "lang", "en-US");
        node.add_qualifier(qual.clone());
        assert_eq!(node.qualifiers.len(), 1);
        assert_eq!(
            node.get_qualifier("http://ns.adobe.com/xap/1.0/", "lang"),
            Some(&qual)
        );
    }

    #[test]
    fn test_array_node() {
        let mut array = ArrayNode::new(ArrayType::Ordered);
        assert_eq!(array.len(), 0);
        assert!(array.is_empty());

        array.append(Node::simple("item1"));
        array.append(Node::simple("item2"));
        assert_eq!(array.len(), 2);

        assert_eq!(
            array.get(0).and_then(|n| n.as_simple()).map(|n| &n.value),
            Some(&"item1".to_string())
        );
        assert_eq!(
            array.get(1).and_then(|n| n.as_simple()).map(|n| &n.value),
            Some(&"item2".to_string())
        );

        let removed = array.remove(0).unwrap();
        assert_eq!(array.len(), 1);
        assert_eq!(
            removed.as_simple().map(|n| &n.value),
            Some(&"item1".to_string())
        );
    }

    #[test]
    fn test_structure_node() {
        let mut structure = StructureNode::new();
        assert!(!structure.has_field("field1"));

        structure.set_field("field1", Node::simple("value1"));
        assert!(structure.has_field("field1"));
        assert_eq!(
            structure
                .get_field("field1")
                .and_then(|n| n.as_simple())
                .map(|n| &n.value),
            Some(&"value1".to_string())
        );

        structure.remove_field("field1");
        assert!(!structure.has_field("field1"));
    }

    #[test]
    fn test_structure_node_to_value() {
        use crate::XmpValue;

        let mut node = Node::structure();
        let value: XmpValue = (&node).into();
        assert!(matches!(value, XmpValue::Structure(_)));
        if let XmpValue::Structure(structure) = &value {
            assert_eq!(structure.len(), 0);
        } else {
            unreachable!();
        }

        if let Some(ref mut structure) = node.as_structure_mut() {
            structure.set_field("field1", Node::simple("value1"));
            structure.set_field("field2", Node::simple("value2"));
            let mut array_node = ArrayNode::new(ArrayType::Unordered);
            array_node.items.push(Node::simple("item1"));
            array_node.items.push(Node::simple("item2"));
            structure.set_field("bag1", Node::Array(array_node));
        } else {
            unreachable!();
        }
        let value: XmpValue = (&node).into();
        if let XmpValue::Structure(structure) = &value {
            assert_eq!(structure.len(), 3);
            assert!(structure.contains_key("field1"));
            assert!(matches!(structure.get("field1"), Some(XmpValue::String(s)) if s == "value1"));
            assert!(structure.contains_key("bag1"));
            assert!(matches!(structure.get("bag1"), Some(XmpValue::Array(a)) if a.len() == 2));
        } else {
            unreachable!();
        }
    }

    #[test]
    fn test_node_creation() {
        let simple = Node::simple("test");
        assert!(simple.is_simple());

        let array = Node::array(ArrayType::Ordered);
        assert!(array.is_array());

        let structure = Node::structure();
        assert!(structure.is_structure());
    }

    #[test]
    fn test_array_type_rdf() {
        assert_eq!(ArrayType::Ordered.rdf_type(), "Seq");
        assert_eq!(ArrayType::Unordered.rdf_type(), "Bag");
        assert_eq!(ArrayType::Alternative.rdf_type(), "Alt");
    }
}