Skip to main content

asset_io/
updates.rs

1// Copyright 2026 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6
7// Unless required by applicable law or agreed to in writing,
8// this software is distributed on an "AS IS" BASIS, WITHOUT
9// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11// specific language governing permissions and limitations under
12// each license.
13
14//! Metadata updates to apply when writing an asset.
15
16use std::{
17    any::{Any, TypeId},
18    collections::HashMap,
19};
20
21/// What to do with one kind of metadata when writing an asset.
22///
23/// By default, all metadata is kept unchanged. A handler reads it from
24/// [`Updates::xmp`] and [`Updates::c2pa`].
25#[derive(Debug, Clone, Default)]
26#[non_exhaustive]
27pub enum MetadataUpdate {
28    /// Keep existing metadata (default)
29    #[default]
30    Keep,
31    /// Remove existing metadata
32    Remove,
33    /// Replace or add metadata
34    Set(Vec<u8>),
35}
36
37/// What to do with an item of metadata the asset already has; see
38/// [`MetadataSlot::existing`].
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum Existing<'a> {
42    /// Write the item as it is.
43    Keep,
44    /// Leave the item out.
45    Drop,
46    /// Write these bytes in its place.
47    Replace(&'a [u8]),
48}
49
50/// Applies a [`MetadataUpdate`] to the items of one kind of metadata (XMP, C2PA)
51/// as a handler meets them, and says what is left to insert.
52///
53/// A handler asks [`existing`](Self::existing) for each item of that kind in the
54/// source, in order. A new value replaces the first and drops the rest, so the
55/// output never holds two. After the point where new metadata belongs, whether
56/// that is a place the format prefers or the end, it asks [`pending`](Self::pending)
57/// for a value that no existing item took.
58///
59/// ```
60/// use asset_io::{
61///     container_api::{Existing, MetadataSlot},
62///     Updates,
63/// };
64///
65/// let updates = Updates::new().set_xmp(b"new".to_vec());
66/// let mut xmp = MetadataSlot::new(updates.xmp());
67/// assert_eq!(xmp.existing(), Existing::Replace(&b"new"[..]));
68/// assert_eq!(xmp.existing(), Existing::Drop);
69/// assert_eq!(xmp.pending(), None);
70/// ```
71#[derive(Debug, Clone, Copy)]
72pub struct MetadataSlot<'a> {
73    update: &'a MetadataUpdate,
74    done: bool,
75}
76
77impl<'a> MetadataSlot<'a> {
78    /// A slot that applies `update`.
79    pub fn new(update: &'a MetadataUpdate) -> Self {
80        Self {
81            update,
82            done: false,
83        }
84    }
85
86    /// What to do with the next item the source has.
87    pub fn existing(&mut self) -> Existing<'a> {
88        match self.update {
89            MetadataUpdate::Keep => {
90                self.done = true;
91                Existing::Keep
92            }
93            MetadataUpdate::Set(d) if !self.done => {
94                self.done = true;
95                Existing::Replace(d)
96            }
97            _ => Existing::Drop,
98        }
99    }
100
101    /// The bytes still to insert, once: a new value no existing item replaced.
102    pub fn pending(&mut self) -> Option<&'a [u8]> {
103        match self.update {
104            MetadataUpdate::Set(d) if !self.done => {
105                self.done = true;
106                Some(d)
107            }
108            _ => None,
109        }
110    }
111
112    /// Whether a new value is still waiting for a place.
113    pub fn is_pending(&self) -> bool {
114        matches!(self.update, MetadataUpdate::Set(_)) && !self.done
115    }
116}
117
118/// Updates to apply when writing a file
119///
120/// This struct uses a builder pattern where the default is to keep all existing
121/// metadata unchanged. Use the builder methods to explicitly specify changes.
122///
123/// # Example
124///
125/// ```
126/// use asset_io::Updates;
127///
128/// // Default: keep everything
129/// let keep = Updates::new();
130///
131/// // Remove XMP, keep everything else
132/// let no_xmp = Updates::new().remove_xmp();
133///
134/// // Set a new C2PA manifest store, remove XMP, keep everything else
135/// let updates = Updates::new()
136///     .set_c2pa(b"new manifest store".to_vec())
137///     .remove_xmp();
138/// ```
139#[derive(Debug, Default)]
140pub struct Updates {
141    /// XMP data update strategy (use builder methods to modify)
142    pub(crate) xmp: MetadataUpdate,
143
144    /// C2PA manifest store update strategy (use builder methods to modify)
145    pub(crate) c2pa: MetadataUpdate,
146
147    /// The store being set adds to the existing store
148    /// (see [`Updates::as_update`]).
149    pub(crate) c2pa_is_update: bool,
150
151    /// Set by [`Updates::remove_all`], for handlers that remove more than XMP and
152    /// the C2PA store then.
153    pub(crate) remove_all: bool,
154
155    /// Options a container defines for itself (see [`Updates::set_extension`]).
156    extensions: Extensions,
157}
158
159/// Values of any type, one per type, kept by [`Updates`].
160#[derive(Default)]
161struct Extensions(HashMap<TypeId, Box<dyn Any + Send + Sync>>);
162
163impl std::fmt::Debug for Extensions {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        write!(f, "Extensions({})", self.0.len())
166    }
167}
168
169impl Updates {
170    /// Create a new `Updates` builder with all metadata set to keep (no changes)
171    ///
172    /// This is the same as `Updates::default()` but more explicit.
173    pub fn new() -> Self {
174        Self::default()
175    }
176
177    /// Set XMP metadata to a new value
178    ///
179    /// # Example
180    ///
181    /// ```no_run
182    /// use asset_io::Updates;
183    ///
184    /// let updates = Updates::new().set_xmp(b"<xmp>...</xmp>".to_vec());
185    /// ```
186    pub fn set_xmp(mut self, xmp: Vec<u8>) -> Self {
187        self.xmp = MetadataUpdate::Set(xmp);
188        self
189    }
190
191    /// Remove XMP metadata
192    ///
193    /// # Example
194    ///
195    /// ```no_run
196    /// use asset_io::Updates;
197    ///
198    /// let updates = Updates::new().remove_xmp();
199    /// ```
200    pub fn remove_xmp(mut self) -> Self {
201        self.xmp = MetadataUpdate::Remove;
202        self
203    }
204
205    /// Keep existing XMP metadata (explicit, same as default)
206    ///
207    /// # Example
208    ///
209    /// ```no_run
210    /// use asset_io::Updates;
211    ///
212    /// let updates = Updates::new().keep_xmp();
213    /// ```
214    pub fn keep_xmp(mut self) -> Self {
215        self.xmp = MetadataUpdate::Keep;
216        self
217    }
218
219    /// Set the C2PA manifest store (a JUMBF superbox) to a new value.
220    ///
221    /// The store replaces the existing one, or is added where the container's C2PA
222    /// embedding puts it. Other JUMBF, which containers such as JPEG may carry
223    /// alongside, is left as it is. A container that carries JUMBF of any type
224    /// tells a store by its superbox type, so there the store must have the type
225    /// [`C2PA_STORE_TYPE`](crate::jumbf::C2PA_STORE_TYPE).
226    ///
227    /// # Example
228    ///
229    /// ```no_run
230    /// use asset_io::Updates;
231    ///
232    /// let updates = Updates::new().set_c2pa(b"manifest store".to_vec());
233    /// ```
234    pub fn set_c2pa(mut self, store: Vec<u8>) -> Self {
235        self.c2pa = MetadataUpdate::Set(store);
236        self.c2pa_is_update = false;
237        self
238    }
239
240    /// What to do with the XMP.
241    pub fn xmp(&self) -> &MetadataUpdate {
242        &self.xmp
243    }
244
245    /// What to do with the C2PA manifest store.
246    pub fn c2pa(&self) -> &MetadataUpdate {
247        &self.c2pa
248    }
249
250    /// Whether the store being set is an update to the existing store; see
251    /// [`as_update`](Self::as_update).
252    pub fn is_c2pa_update(&self) -> bool {
253        self.c2pa_is_update
254    }
255
256    /// Whether these updates came from [`remove_all`](Self::remove_all). A handler
257    /// that has options of its own (see [`extension`](Self::extension)) treats an
258    /// option that was not set as removed then.
259    pub fn removes_all(&self) -> bool {
260        self.remove_all
261    }
262
263    /// Attach an option that one container defines for itself, such as the merkle
264    /// boxes of ISO BMFF. One value is kept per type; a later value of the same
265    /// type replaces the earlier. Containers that do not know the type ignore it.
266    /// A container that defines an option usually offers builder methods that call
267    /// this, so callers rarely do.
268    pub fn set_extension<T: Any + Send + Sync>(mut self, value: T) -> Self {
269        self.extensions.0.insert(TypeId::of::<T>(), Box::new(value));
270        self
271    }
272
273    /// The option of type `T`, if one was set with
274    /// [`set_extension`](Self::set_extension).
275    pub fn extension<T: Any + Send + Sync>(&self) -> Option<&T> {
276        self.extensions
277            .0
278            .get(&TypeId::of::<T>())
279            .and_then(|v| v.downcast_ref::<T>())
280    }
281
282    /// Forget the option of type `T`.
283    pub fn clear_extension<T: Any + Send + Sync>(mut self) -> Self {
284        self.extensions.0.remove(&TypeId::of::<T>());
285        self
286    }
287
288    /// Mark the store given to [`set_c2pa`](Self::set_c2pa) as an update
289    /// manifest added to the existing store: `set_c2pa(store).as_update()`. Call it
290    /// after `set_c2pa`; a later `set_c2pa`, `remove_c2pa` or `keep_c2pa`
291    /// clears it.
292    ///
293    /// Most containers ignore this. A container that keeps the original store apart
294    /// from later additions (ISO BMFF) uses it: if the new store begins with the
295    /// existing store's manifests, byte for byte, it leaves them in place and
296    /// stores only the rest as an update. Otherwise (nothing to update, or the
297    /// existing manifests changed) it writes the new store as a whole. The hint is
298    /// needed because a standard manifest added to a signed file extends the store
299    /// in the same way, and must not be treated as an update.
300    pub fn as_update(mut self) -> Self {
301        self.c2pa_is_update = true;
302        self
303    }
304
305    /// Remove the C2PA manifest store. Other JUMBF is kept.
306    ///
307    /// # Example
308    ///
309    /// ```no_run
310    /// use asset_io::Updates;
311    ///
312    /// let updates = Updates::new().remove_c2pa();
313    /// ```
314    pub fn remove_c2pa(mut self) -> Self {
315        self.c2pa = MetadataUpdate::Remove;
316        self.c2pa_is_update = false;
317        self
318    }
319
320    /// Keep the existing C2PA manifest store (explicit, same as default)
321    ///
322    /// # Example
323    ///
324    /// ```no_run
325    /// use asset_io::Updates;
326    ///
327    /// let updates = Updates::new().keep_c2pa();
328    /// ```
329    pub fn keep_c2pa(mut self) -> Self {
330        self.c2pa = MetadataUpdate::Keep;
331        self.c2pa_is_update = false;
332        self
333    }
334
335    /// Create updates that keep all existing metadata (no changes)
336    ///
337    /// This is an alias for `Updates::new()` or `Updates::default()`.
338    pub fn keep_all() -> Self {
339        Self::default()
340    }
341
342    /// Create updates that remove all metadata
343    ///
344    /// # Example
345    ///
346    /// ```no_run
347    /// use asset_io::Updates;
348    ///
349    /// let updates = Updates::remove_all();
350    /// ```
351    pub fn remove_all() -> Self {
352        let mut updates = Self::new().remove_xmp().remove_c2pa();
353        updates.remove_all = true;
354        updates
355    }
356
357    /// Create updates that set new XMP (legacy constructor)
358    ///
359    /// Prefer using `Updates::new().set_xmp(xmp)` for consistency with
360    /// the builder pattern.
361    pub fn with_xmp(xmp: Vec<u8>) -> Self {
362        Self::new().set_xmp(xmp)
363    }
364
365    /// Create updates that set a new C2PA manifest store (legacy constructor)
366    ///
367    /// Prefer using `Updates::new().set_c2pa(store)` for consistency with
368    /// the builder pattern.
369    pub fn with_c2pa(store: Vec<u8>) -> Self {
370        Self::new().set_c2pa(store)
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    #[derive(Debug, PartialEq)]
379    struct Opt(u8);
380
381    #[test]
382    fn extensions_are_kept_per_type() {
383        let u = Updates::new();
384        assert!(u.extension::<Opt>().is_none());
385        let u = u.set_extension(Opt(1)).set_extension(7u32);
386        assert_eq!(u.extension::<Opt>(), Some(&Opt(1)));
387        assert_eq!(u.extension::<u32>(), Some(&7));
388        let u = u.set_extension(Opt(2));
389        assert_eq!(u.extension::<Opt>(), Some(&Opt(2)));
390        let u = u.clear_extension::<Opt>();
391        assert!(u.extension::<Opt>().is_none());
392        assert_eq!(u.extension::<u32>(), Some(&7));
393    }
394
395    #[test]
396    fn remove_all_is_remembered() {
397        assert!(!Updates::new().remove_xmp().remove_c2pa().removes_all());
398        assert!(Updates::remove_all().removes_all());
399    }
400}