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
use std::fmt;
use std::io::{Read, Seek, SeekFrom, Write};

use crate::{core::atom, data, Atom, AtomT, Data, DataT, ErrorKind, Ident};

/// An enum representing the different types of content an atom might have.
#[derive(Clone, Eq, PartialEq)]
pub enum Content {
    /// A value containing a list of children atoms.
    Atoms(Vec<Atom>),
    /// A value containing raw data.
    RawData(Data),
    /// A value containing data defined by a
    /// [Table 3-5 Well-known data types](https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/Metadata/Metadata.html#//apple_ref/doc/uid/TP40000939-CH1-SW34)
    /// code.
    TypedData(Data),
    /// Empty content.
    Empty,
}

impl Default for Content {
    fn default() -> Self {
        Self::Empty
    }
}

impl fmt::Debug for Content {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Content::Atoms(a) => write!(f, "Content::Atoms{{ {:#?} }}", a),
            Content::RawData(d) => write!(f, "Content::RawData{{ {:?} }}", d),
            Content::TypedData(d) => write!(f, "Content::TypedData{{ {:?} }}", d),
            Content::Empty => write!(f, "Content::Empty"),
        }
    }
}

impl IntoIterator for Content {
    type Item = Atom;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        match self {
            Self::Atoms(v) => v.into_iter(),
            _ => Vec::new().into_iter(),
        }
    }
}

impl Content {
    /// Creates new empty content of type [Self::Atoms](Self::Atoms).
    pub fn atoms() -> Self {
        Self::Atoms(Vec::new())
    }

    /// Creates new content of type [Self::Atoms](Self::Atoms) containing the
    /// atom.
    pub fn atom(atom: Atom) -> Self {
        Self::Atoms(vec![atom])
    }

    /// Creates new content of type [Self::Atoms](Self::Atoms) containing a data
    /// [`Atom`](struct.Atom.html) with the data.
    pub fn data_atom_with(data: Data) -> Self {
        Self::atom(Atom::data_atom_with(data))
    }

    /// Returns the length in bytes.
    pub fn len(&self) -> usize {
        match self {
            Self::Atoms(v) => v.iter().map(|a| a.len()).sum(),
            Self::RawData(d) => d.len(),
            Self::TypedData(d) => 8 + d.len(),
            Self::Empty => 0,
        }
    }

    /// Returns true if the content is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns an iterator over the children atoms.
    pub fn iter(&self) -> std::slice::Iter<Atom> {
        match self {
            Self::Atoms(v) => v.iter(),
            _ => [].iter(),
        }
    }

    /// Returns a mutable iterator over the children atoms.
    pub fn iter_mut(&mut self) -> std::slice::IterMut<Atom> {
        match self {
            Self::Atoms(v) => v.iter_mut(),
            _ => [].iter_mut(),
        }
    }

    /// Returns a reference to the first children atom matching the `identifier`, if present.
    pub fn child(&self, ident: Ident) -> Option<&Atom> {
        self.iter().find(|a| a.ident == ident)
    }

    /// Return a reference to the first children atom, if present.
    pub fn first_child(&self) -> Option<&Atom> {
        if let Self::Atoms(v) = self {
            return v.first();
        }
        None
    }

    /// Returns a mutable reference to the first children atom matching the `identfier`, if present.
    pub fn child_mut(&mut self, ident: Ident) -> Option<&mut Atom> {
        self.iter_mut().find(|a| a.ident == ident)
    }

    /// Returns a mutable reference to the first children atom, if present.
    pub fn first_child_mut(&mut self) -> Option<&mut Atom> {
        if let Self::Atoms(v) = self {
            return v.first_mut();
        }
        None
    }

    /// Consumes self and returns the first children atom matching the `identfier`, if present.
    pub fn take_child(self, ident: Ident) -> Option<Atom> {
        self.into_iter().find(|a| a.ident == ident)
    }

    /// Consumes self and returns the first children atom, if present.
    pub fn take_first_child(self) -> Option<Atom> {
        self.into_iter().next()
    }

    /// Replaces `self` with it's default value and returns the data, if present.
    pub fn take_data(&mut self) -> Option<Data> {
        let content = std::mem::take(self);

        match content {
            Self::TypedData(d) => Some(d),
            Self::RawData(d) => Some(d),
            _ => None,
        }
    }

    /// Attempts to write the content to the `writer`.
    pub fn write_to(&self, writer: &mut impl Write) -> crate::Result<()> {
        match self {
            Self::Atoms(v) => {
                for a in v {
                    a.write_to(writer)?;
                }
            }
            Self::RawData(d) => d.write_raw(writer)?,
            Self::TypedData(d) => d.write_typed(writer)?,
            Self::Empty => (),
        }

        Ok(())
    }
}

/// A template representing the different types of content an atom template might have.
#[derive(Clone, Eq, PartialEq)]
pub enum ContentT {
    /// A value containing a list of children atom templates.
    Atoms(Vec<AtomT>),
    /// A value containing a data template specifying the datatype.
    RawData(DataT),
    /// A template representing typed data that is defined by a
    /// [Table 3-5 Well-known data types](https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/Metadata/Metadata.html#//apple_ref/doc/uid/TP40000939-CH1-SW34)
    /// code prior to the data parsed.
    TypedData,
    /// Empty content.
    Empty,
}

impl Default for ContentT {
    fn default() -> Self {
        Self::Empty
    }
}

impl fmt::Debug for ContentT {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ContentT::Atoms(a) => write!(f, "ContentT::Atoms{{ {:#?} }}", a),
            ContentT::RawData(d) => write!(f, "ContentT::RawData{{ {:?} }}", d),
            ContentT::TypedData => write!(f, "ContentT::TypedData"),
            ContentT::Empty => write!(f, "ContentT::Empty"),
        }
    }
}

impl IntoIterator for ContentT {
    type Item = AtomT;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        match self {
            Self::Atoms(v) => v.into_iter(),
            _ => Vec::new().into_iter(),
        }
    }
}

impl ContentT {
    /// Creates a new empty content template of type [Self::Atoms](Self::Atoms).
    pub const fn atoms_t() -> Self {
        Self::Atoms(Vec::new())
    }

    /// Creates a new content template of type [Self::Atoms](Self::Atoms)
    /// containing the `atom` template.
    pub fn atom_t(atom: AtomT) -> Self {
        Self::Atoms(vec![atom])
    }

    /// Creates a new content template of type [Self::Atoms](Self::Atoms)
    /// containing a data atom template.
    pub fn data_atom_t() -> Self {
        Self::atom_t(AtomT::data_atom())
    }

    /// Returns an iterator over the children atoms.
    pub fn iter(&self) -> std::slice::Iter<AtomT> {
        match self {
            Self::Atoms(v) => v.iter(),
            _ => [].iter(),
        }
    }

    /// Returns a mutable iterator over the children atoms.
    pub fn iter_mut(&mut self) -> std::slice::IterMut<AtomT> {
        match self {
            Self::Atoms(v) => v.iter_mut(),
            _ => [].iter_mut(),
        }
    }

    /// Returns a reference to the first children atom matching the `identifier`, if present.
    pub fn child(&self, ident: Ident) -> Option<&AtomT> {
        self.iter().find(|a| a.ident == ident)
    }

    /// Return a reference to the first children atom, if present.
    pub fn first_child(&self) -> Option<&AtomT> {
        if let Self::Atoms(v) = self {
            return v.first();
        }
        None
    }

    /// Returns a mutable reference to the first children atom matching the `identfier`, if present.
    pub fn child_mut(&mut self, ident: Ident) -> Option<&mut AtomT> {
        self.iter_mut().find(|a| a.ident == ident)
    }

    /// Returns a mutable reference to the first children atom, if present.
    pub fn first_child_mut(&mut self) -> Option<&mut AtomT> {
        if let Self::Atoms(v) = self {
            return v.first_mut();
        }
        None
    }

    /// Consumes self and returns the first children atom matching the `identfier`, if present.
    pub fn take_child(self, ident: Ident) -> Option<AtomT> {
        self.into_iter().find(|a| a.ident == ident)
    }

    /// Consumes self and returns the first children atom, if present.
    pub fn take_first_child(self) -> Option<AtomT> {
        self.into_iter().next()
    }

    /// Attempts to parse corresponding content from the `reader`.
    pub fn parse(&self, reader: &mut (impl Read + Seek), length: usize) -> crate::Result<Content> {
        Ok(match self {
            ContentT::Atoms(v) => Content::Atoms(atom::parse_atoms(reader, v, length)?),
            ContentT::RawData(d) => Content::RawData(d.parse(reader, length)?),
            ContentT::TypedData => {
                if length >= 8 {
                    let datatype = match data::read_u32(reader) {
                        Ok(d) => d,
                        Err(e) => {
                            return Err(crate::Error::new(
                                e.kind,
                                "Error reading typed data head".to_owned(),
                            ));
                        }
                    };

                    // Skipping 4 byte locale indicator
                    reader.seek(SeekFrom::Current(4))?;

                    Content::TypedData(DataT::new(datatype).parse(reader, length - 8)?)
                } else {
                    return Err(crate::Error::new(
                        ErrorKind::Parsing,
                        "Typed data head to short".to_owned(),
                    ));
                }
            }
            ContentT::Empty => Content::Empty,
        })
    }
}