Skip to main content

nom_exif/exif/
exif_iter.rs

1use std::{fmt::Debug, sync::Arc};
2
3use nom::{
4    number::{complete, Endianness},
5    sequence::tuple,
6};
7use thiserror::Error;
8
9use crate::{
10    partial_vec::{AssociatedInput, PartialVec},
11    slice::SliceChecked,
12    values::{DataFormat, EntryData, IRational, ParseEntryError, URational},
13    EntryValue, ExifTag,
14};
15
16use super::{exif_exif::IFD_ENTRY_SIZE, tags::ExifTagCode, GPSInfo, TiffHeader};
17
18/// Parses header from input data, and returns an [`ExifIter`].
19///
20/// All entries are lazy-parsed. That is, only when you iterate over
21/// [`ExifIter`] will the IFD entries be parsed one by one.
22///
23/// The one exception is the time zone entries. The method will try to find
24/// and parse the time zone data first, so we can correctly parse all time
25/// information in subsequent iterates.
26#[tracing::instrument]
27pub(crate) fn input_into_iter(
28    input: impl Into<PartialVec> + Debug,
29    state: Option<TiffHeader>,
30) -> crate::Result<ExifIter> {
31    let input = input.into();
32    let (header, start) = match state {
33        // header has been parsed, and header has been skipped, input data
34        // is the IFD data
35        Some(header) => (header, 0),
36        _ => {
37            // header has not been parsed, input data includes IFD header
38            let (_, header) = TiffHeader::parse(&input[..])?;
39            let start = header.ifd0_offset as usize;
40            if start > input.len() {
41                return Err(crate::Error::ParseFailed("no enough bytes".into()));
42            }
43
44            (header, start)
45        }
46    };
47
48    tracing::debug!(?header, offset = start);
49
50    let data = &input[..];
51
52    let mut ifd0 = IfdIter::try_new(
53        0,
54        input.partial(&data[start..]),
55        header.ifd0_offset,
56        header.endian,
57        None,
58    )?;
59
60    let tz = ifd0.find_tz_offset();
61    ifd0.tz = tz.clone();
62    let iter: ExifIter = ExifIter::new(input, header, tz, ifd0);
63
64    tracing::debug!(?iter, "got IFD0");
65
66    Ok(iter)
67}
68
69/// An iterator version of [`Exif`](crate::Exif). Use [`ParsedExifEntry`] as
70/// iterator items.
71///
72/// Clone an `ExifIter` is very cheap, the underlying data is shared
73/// through `Arc`.
74///
75/// The new cloned `ExifIter`'s iteration index will be reset to the first one.
76///
77/// If you want to convert an `ExifIter` `into` an [`Exif`], you probably want
78/// to clone the `ExifIter` and use the new cloned one to do the converting.
79/// Since the original's iteration index may have been modified by
80/// `Iterator::next()` calls.
81pub struct ExifIter {
82    // Use Arc to make sure we won't clone the owned data.
83    input: Arc<PartialVec>,
84    tiff_header: TiffHeader,
85    tz: Option<String>,
86    ifd0: IfdIter,
87
88    // Iterating status
89    ifds: Vec<IfdIter>,
90}
91
92impl Debug for ExifIter {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.debug_struct("ExifIter")
95            .field("data len", &self.input.len())
96            .field("tiff_header", &self.tiff_header)
97            .field("ifd0", &self.ifd0)
98            .field("state", &self.ifds.first().map(|x| (x.index, x.pos)))
99            .field("ifds num", &self.ifds.len())
100            .finish_non_exhaustive()
101    }
102}
103
104impl Clone for ExifIter {
105    fn clone(&self) -> Self {
106        self.clone_and_rewind()
107    }
108}
109
110impl ExifIter {
111    pub(crate) fn new(
112        input: impl Into<PartialVec>,
113        tiff_header: TiffHeader,
114        tz: Option<String>,
115        ifd0: IfdIter,
116    ) -> ExifIter {
117        let ifds = vec![ifd0.clone()];
118        ExifIter {
119            input: Arc::new(input.into()),
120            tiff_header,
121            tz,
122            ifd0,
123            ifds,
124        }
125    }
126
127    /// Clone and rewind the iterator's index.
128    ///
129    /// Clone an `ExifIter` is very cheap, the underlying data is shared
130    /// through Arc.
131    pub fn clone_and_rewind(&self) -> Self {
132        let ifd0 = self.ifd0.clone_and_rewind();
133        let ifds = vec![ifd0.clone()];
134        Self {
135            input: self.input.clone(),
136            tiff_header: self.tiff_header.clone(),
137            tz: self.tz.clone(),
138            ifd0,
139            ifds,
140        }
141    }
142
143    /// Try to find and parse gps information.
144    ///
145    /// Calling this method won't affect the iterator's state.
146    ///
147    /// Returns:
148    ///
149    /// - An `Ok<Some<GPSInfo>>` if gps info is found and parsed successfully.
150    /// - An `Ok<None>` if gps info is not found.
151    /// - An `Err` if gps info is found but parsing failed.
152    #[tracing::instrument(skip_all)]
153    pub fn parse_gps_info(&self) -> crate::Result<Option<GPSInfo>> {
154        let mut iter = self.clone_and_rewind();
155        let Some(gps) = iter.find(|x| {
156            tracing::info!(?x, "find");
157            x.tag.tag().is_some_and(|t| t == ExifTag::GPSInfo)
158        }) else {
159            tracing::warn!(ifd0 = ?iter.ifds.first(), "GPSInfo not found");
160            return Ok(None);
161        };
162
163        let offset = match gps.get_result() {
164            Ok(v) => {
165                if let Some(offset) = v.as_u32() {
166                    offset
167                } else {
168                    return Err(EntryError(ParseEntryError::InvalidData(
169                        "invalid gps offset".into(),
170                    ))
171                    .into());
172                }
173            }
174            Err(e) => return Err(e.clone().into()),
175        };
176
177        let mut gps_subifd = match IfdIter::try_new(
178            gps.ifd,
179            iter.input.partial(&iter.input[offset as usize..]),
180            offset,
181            iter.tiff_header.endian,
182            iter.tz.clone(),
183        ) {
184            Ok(ifd0) => ifd0.tag_code(ExifTag::GPSInfo.code()),
185            Err(e) => return Err(e),
186        };
187        Ok(gps_subifd.parse_gps_info())
188    }
189
190    pub(crate) fn to_owned(&self) -> ExifIter {
191        ExifIter::new(
192            self.input.to_vec(),
193            self.tiff_header.clone(),
194            self.tz.clone(),
195            self.ifd0.clone_and_rewind(),
196        )
197    }
198}
199
200#[derive(Debug, Clone, Error)]
201#[error("ifd entry error: {0}")]
202pub struct EntryError(ParseEntryError);
203
204impl From<EntryError> for crate::Error {
205    fn from(value: EntryError) -> Self {
206        Self::ParseFailed(value.into())
207    }
208}
209
210/// Represents a parsed IFD entry. Used as iterator items in [`ExifIter`].
211#[derive(Clone)]
212pub struct ParsedExifEntry {
213    // 0: ifd0, 1: ifd1
214    ifd: usize,
215    tag: ExifTagCode,
216    res: Option<Result<EntryValue, EntryError>>,
217}
218
219impl ParsedExifEntry {
220    /// Get the IFD index value where this entry is located.
221    /// - 0: ifd0 (main image)
222    /// - 1: ifd1 (thumbnail)
223    pub fn ifd_index(&self) -> usize {
224        self.ifd
225    }
226
227    /// Get recognized Exif tag of this entry, maybe return `None` if the tag
228    /// is unrecognized.
229    ///
230    /// If you have any custom defined tag which does not exist in [`ExifTag`],
231    /// then you should use [`Self::tag_code`] to get the raw tag code.
232    ///
233    /// **Note**: You can always get the raw tag code via [`Self::tag_code`],
234    /// no matter if it's recognized.
235    pub fn tag(&self) -> Option<ExifTag> {
236        match self.tag {
237            ExifTagCode::Tag(t) => Some(t),
238            ExifTagCode::Code(_) => None,
239        }
240    }
241
242    /// Get the raw tag code of this entry.
243    ///
244    /// In case you have some custom defined tags which doesn't exist in
245    /// [`ExifTag`], you can use this method to get the raw tag code of this
246    /// entry.
247    pub fn tag_code(&self) -> u16 {
248        self.tag.code()
249    }
250
251    /// Returns true if there is an `EntryValue` in self.
252    ///
253    /// Both of the following situations may cause this method to return false:
254    /// - An error occurred while parsing this entry
255    /// - The value has been taken by calling [`Self::take_value`] or
256    ///   [`Self::take_result`] methods.
257    pub fn has_value(&self) -> bool {
258        self.res.as_ref().map(|e| e.is_ok()).is_some_and(|b| b)
259    }
260
261    /// Get the parsed entry value of this entry.
262    pub fn get_value(&self) -> Option<&EntryValue> {
263        match self.res.as_ref() {
264            Some(Ok(v)) => Some(v),
265            Some(Err(_)) | None => None,
266        }
267    }
268
269    /// Takes out the parsed entry value of this entry.
270    ///
271    /// If you need to convert this `ExifIter` to an [`crate::Exif`], please
272    /// don't call this method! Otherwise the converted `Exif` is incomplete.
273    ///
274    /// **Note**: This method can only be called once! Once it has been called,
275    /// calling it again always returns `None`. You may want to check it by
276    /// calling [`Self::has_value`] before calling this method.
277    pub fn take_value(&mut self) -> Option<EntryValue> {
278        match self.res.take() {
279            Some(v) => v.ok(),
280            None => None,
281        }
282    }
283
284    /// Get the parsed result of this entry.
285    ///
286    /// Returns:
287    ///
288    /// - If any error occurred while parsing this entry, an
289    ///   Err(&[`EntryError`]) is returned.
290    ///
291    /// - Otherwise, an Ok(&[`EntryValue`]) is returned.
292    pub fn get_result(&self) -> Result<&EntryValue, &EntryError> {
293        match self.res {
294            Some(ref v) => v.as_ref(),
295            None => panic!("take result of entry twice"),
296        }
297    }
298
299    /// Takes out the parsed result of this entry.
300    ///
301    /// If you need to convert this `ExifIter` to an [`crate::Exif`], please
302    /// don't call this method! Otherwise the converted `Exif` is incomplete.
303    ///
304    /// Returns:
305    ///
306    /// - If any error occurred while parsing this entry, an
307    ///   Err([`InvalidEntry`](crate::Error::InvalidEntry)) is returned.
308    ///
309    /// - Otherwise, an Ok([`EntryValue`]) is returned.
310    ///
311    /// **Note**: This method can ONLY be called once! If you call it twice, it
312    /// will **panic** directly!
313    pub fn take_result(&mut self) -> Result<EntryValue, EntryError> {
314        match self.res.take() {
315            Some(v) => v,
316            None => panic!("take result of entry twice"),
317        }
318    }
319
320    fn make_ok(ifd: usize, tag: ExifTagCode, v: EntryValue) -> Self {
321        Self {
322            ifd,
323            tag,
324            res: Some(Ok(v)),
325        }
326    }
327
328    fn make_err(ifd: usize, tag: ExifTagCode, e: ParseEntryError) -> Self {
329        Self {
330            ifd,
331            tag,
332            res: Some(Err(EntryError(e))),
333        }
334    }
335}
336
337impl Debug for ParsedExifEntry {
338    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339        let value = match self.get_result() {
340            Ok(v) => format!("{v}"),
341            Err(e) => format!("{e:?}"),
342        };
343        f.debug_struct("IfdEntryResult")
344            .field("ifd", &format!("ifd{}", self.ifd))
345            .field("tag", &self.tag)
346            .field("value", &value)
347            .finish()
348    }
349}
350
351const MAX_IFD_DEPTH: usize = 8;
352
353impl Iterator for ExifIter {
354    type Item = ParsedExifEntry;
355
356    #[tracing::instrument(skip_all)]
357    fn next(&mut self) -> Option<Self::Item> {
358        loop {
359            if self.ifds.is_empty() {
360                tracing::debug!(?self, "all IFDs has been parsed");
361                return None;
362            }
363
364            if self.ifds.len() > MAX_IFD_DEPTH {
365                self.ifds.clear();
366                tracing::error!(
367                    ifds_depth = self.ifds.len(),
368                    "ifd depth is too deep, just go back to ifd0"
369                );
370                self.ifds.push(self.ifd0.clone_with_state());
371            }
372
373            let mut ifd = self.ifds.pop()?;
374            let cur_ifd_idx = ifd.ifd_idx;
375            match ifd.next() {
376                Some((tag_code, entry)) => {
377                    // tracing::debug!(ifd = ifd.ifd_idx, ?tag_code, ?entry, "next tag entry");
378
379                    match entry {
380                        IfdEntry::IfdNew(new_ifd) => {
381                            let is_subifd = if new_ifd.ifd_idx == ifd.ifd_idx {
382                                // Push the current ifd before enter sub-ifd.
383                                self.ifds.push(ifd);
384                                tracing::debug!(?tag_code, ?new_ifd, "got new SUB-IFD");
385                                true
386                            } else {
387                                // Otherwise this is a next ifd. It means that the
388                                // current ifd has been parsed, so we don't need to
389                                // push it.
390                                tracing::debug!("IFD{} parsing completed", cur_ifd_idx);
391                                tracing::debug!(?new_ifd, "got new IFD");
392                                false
393                            };
394
395                            let (ifd_idx, offset) = (new_ifd.ifd_idx, new_ifd.offset);
396                            self.ifds.push(new_ifd);
397
398                            if is_subifd {
399                                // Return sub-ifd as an entry
400                                return Some(ParsedExifEntry::make_ok(
401                                    ifd_idx,
402                                    tag_code.unwrap(),
403                                    EntryValue::U32(offset),
404                                ));
405                            }
406                        }
407                        IfdEntry::Entry(v) => {
408                            let res =
409                                Some(ParsedExifEntry::make_ok(ifd.ifd_idx, tag_code.unwrap(), v));
410                            self.ifds.push(ifd);
411                            return res;
412                        }
413                        IfdEntry::Err(e) => {
414                            tracing::warn!(?tag_code, ?e, "parse ifd entry error");
415                            let res =
416                                Some(ParsedExifEntry::make_err(ifd.ifd_idx, tag_code.unwrap(), e));
417                            return res;
418                        }
419                    }
420                }
421                None => continue,
422            }
423        }
424    }
425}
426
427#[derive(Clone)]
428pub(crate) struct IfdIter {
429    ifd_idx: usize,
430    tag_code: Option<ExifTagCode>,
431
432    // starts from "ifd/sub-ifd entries" (two bytes of ifd/sub-ifd entry num)
433    input: AssociatedInput,
434
435    // IFD data offset relative to the TIFF header.
436    offset: u32,
437
438    pub tz: Option<String>,
439    endian: Endianness,
440    entry_num: u16,
441
442    // Iterating status
443    index: u16,
444    pos: usize,
445}
446
447impl Debug for IfdIter {
448    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449        f.debug_struct("IfdIter")
450            .field("ifd_idx", &self.ifd_idx)
451            .field("tag", &self.tag_code)
452            .field("data len", &self.input.len())
453            .field("offset", &self.offset)
454            .field("tz", &self.tz)
455            .field("endian", &self.endian)
456            .field("entry_num", &self.entry_num)
457            .field("index", &self.index)
458            .field("pos", &self.pos)
459            .finish()
460    }
461}
462
463impl IfdIter {
464    pub fn rewind(&mut self) {
465        self.index = 0;
466        // Skip the first two bytes, which is the entry num
467        self.pos = 2;
468    }
469
470    pub fn clone_and_rewind(&self) -> Self {
471        let mut it = self.clone();
472        it.rewind();
473        it
474    }
475
476    pub fn tag_code_maybe(mut self, code: Option<u16>) -> Self {
477        self.tag_code = code.map(|x| x.into());
478        self
479    }
480
481    pub fn tag_code(mut self, code: u16) -> Self {
482        self.tag_code = Some(code.into());
483        self
484    }
485
486    #[allow(unused)]
487    pub fn tag(mut self, tag: ExifTagCode) -> Self {
488        self.tag_code = Some(tag);
489        self
490    }
491
492    #[tracing::instrument(skip(input))]
493    pub fn try_new(
494        ifd_idx: usize,
495        input: AssociatedInput,
496        offset: u32,
497        endian: Endianness,
498        tz: Option<String>,
499    ) -> crate::Result<Self> {
500        if input.len() < 2 {
501            return Err(crate::Error::ParseFailed(
502                "ifd data is too small to decode entry num".into(),
503            ));
504        }
505        // should use the complete header data to parse ifd entry num
506        let (_, entry_num) = TiffHeader::parse_ifd_entry_num(&input[..], endian)?;
507
508        Ok(Self {
509            ifd_idx,
510            tag_code: None,
511            input,
512            offset,
513            entry_num,
514            tz,
515            endian,
516            // Skip the first two bytes, which is the entry num
517            pos: 2,
518            index: 0,
519        })
520    }
521
522    fn parse_tag_entry(&self, entry_data: &[u8]) -> Option<(u16, IfdEntry)> {
523        let endian = self.endian;
524        let (_, (tag, data_format, components_num, value_or_offset)) = tuple((
525            complete::u16::<_, nom::error::Error<_>>(endian),
526            complete::u16(endian),
527            complete::u32(endian),
528            complete::u32(endian),
529        ))(entry_data)
530        .ok()?;
531
532        if tag == 0 {
533            return None;
534        }
535
536        let df: DataFormat = match data_format.try_into() {
537            Ok(df) => df,
538            Err(e) => {
539                let t: ExifTagCode = tag.into();
540                tracing::warn!(tag = ?t, ?e, "invalid entry data format");
541                return Some((tag, IfdEntry::Err(e)));
542            }
543        };
544        let (tag, res) = self.parse_entry(tag, df, components_num, entry_data, value_or_offset);
545        Some((tag, res))
546    }
547
548    fn get_data_pos(&self, value_or_offset: u32) -> u32 {
549        value_or_offset.saturating_sub(self.offset)
550    }
551
552    fn parse_entry(
553        &self,
554        tag: u16,
555        data_format: DataFormat,
556        components_num: u32,
557        entry_data: &[u8],
558        value_or_offset: u32,
559    ) -> (u16, IfdEntry) {
560        // get component_size according to data format
561        let component_size = data_format.component_size();
562
563        // get entry data
564        let size = components_num as usize * component_size;
565        let data = if size <= 4 {
566            &entry_data[8..8 + size] // Safe-slice
567        } else {
568            let start = self.get_data_pos(value_or_offset) as usize;
569            let end = start + size;
570            let Some(data) = self.input.slice_checked(start..end) else {
571                tracing::warn!(
572                    "entry data overflow, self.offset: {:08x} tag: {:04x} start: {:08x} end: {:08x} ifd data len {:08x}",
573                    self.offset,
574                    tag,
575                    start,
576                    end,
577                    self.input.len(),
578                );
579                return (tag, IfdEntry::Err(ParseEntryError::EntrySizeTooBig));
580            };
581
582            data
583        };
584
585        if SUBIFD_TAGS.contains(&tag) {
586            if let Some(value) = self.new_ifd_iter(self.ifd_idx, value_or_offset, Some(tag)) {
587                return (tag, value);
588            }
589        }
590
591        let entry = EntryData {
592            endian: self.endian,
593            tag,
594            data,
595            data_format,
596            components_num,
597        };
598        match EntryValue::parse(&entry, &self.tz) {
599            Ok(v) => (tag, IfdEntry::Entry(v)),
600            Err(e) => (tag, IfdEntry::Err(e)),
601        }
602    }
603
604    fn new_ifd_iter(
605        &self,
606        ifd_idx: usize,
607        value_or_offset: u32,
608        tag: Option<u16>,
609    ) -> Option<IfdEntry> {
610        let pos = self.get_data_pos(value_or_offset) as usize;
611        if pos < self.input.len() {
612            match IfdIter::try_new(
613                ifd_idx,
614                self.input.partial(&self.input[pos..]),
615                value_or_offset,
616                self.endian,
617                self.tz.clone(),
618            ) {
619                Ok(iter) => return Some(IfdEntry::IfdNew(iter.tag_code_maybe(tag))),
620                Err(e) => {
621                    tracing::warn!(?tag, ?e, "Create next/sub IFD failed");
622                }
623            }
624            // return (
625            //     tag,
626            //     // IfdEntry::Ifd {
627            //     //     idx: self.ifd_idx,
628            //     //     offset: value_or_offset,
629            //     // },
630            //     IfdEntry::IfdNew(),
631            // );
632        }
633        None
634    }
635
636    pub fn find_exif_iter(&self) -> Option<IfdIter> {
637        let endian = self.endian;
638        // find ExifOffset
639        for i in 0..self.entry_num {
640            let pos = self.pos + i as usize * IFD_ENTRY_SIZE;
641            let (_, tag) =
642                complete::u16::<_, nom::error::Error<_>>(endian)(&self.input[pos..]).ok()?;
643            if tag == ExifTag::ExifOffset.code() {
644                let entry_data = self.input.slice_checked(pos..pos + IFD_ENTRY_SIZE)?;
645                let (_, entry) = self.parse_tag_entry(entry_data)?;
646                match entry {
647                    IfdEntry::IfdNew(iter) => return Some(iter),
648                    IfdEntry::Entry(_) | IfdEntry::Err(_) => return None,
649                }
650            }
651        }
652        None
653    }
654
655    pub fn find_tz_offset(&self) -> Option<String> {
656        let iter = self.find_exif_iter()?;
657        let mut offset = None;
658        for entry in iter {
659            let Some(tag) = entry.0 else {
660                continue;
661            };
662            if tag.code() == ExifTag::OffsetTimeOriginal.code()
663                || tag.code() == ExifTag::OffsetTimeDigitized.code()
664            {
665                return entry.1.as_str().map(|x| x.to_owned());
666            } else if tag.code() == ExifTag::OffsetTime.code() {
667                offset = entry.1.as_str().map(|x| x.to_owned());
668            }
669        }
670
671        offset
672    }
673
674    // Assume the current ifd is GPSInfo subifd.
675    pub fn parse_gps_info(&mut self) -> Option<GPSInfo> {
676        let mut gps = GPSInfo::default();
677        let mut has_data = false;
678        for (tag, entry) in self {
679            let Some(tag) = tag.and_then(|x| x.tag()) else {
680                continue;
681            };
682            has_data = true;
683            match tag {
684                ExifTag::GPSLatitudeRef => {
685                    if let Some(c) = entry.as_char() {
686                        gps.latitude_ref = c;
687                    }
688                }
689                ExifTag::GPSLongitudeRef => {
690                    if let Some(c) = entry.as_char() {
691                        gps.longitude_ref = c;
692                    }
693                }
694                ExifTag::GPSAltitudeRef => {
695                    if let Some(c) = entry.as_u8() {
696                        gps.altitude_ref = c;
697                    }
698                }
699                ExifTag::GPSLatitude => {
700                    if let Some(v) = entry.as_urational_array() {
701                        gps.latitude = v.iter().collect();
702                    } else if let Some(v) = entry.as_irational_array() {
703                        gps.latitude = v.iter().collect();
704                    }
705                }
706                ExifTag::GPSLongitude => {
707                    if let Some(v) = entry.as_urational_array() {
708                        gps.longitude = v.iter().collect();
709                    } else if let Some(v) = entry.as_irational_array() {
710                        gps.longitude = v.iter().collect();
711                    }
712                }
713                ExifTag::GPSAltitude => {
714                    if let Some(v) = entry.as_urational() {
715                        gps.altitude = *v;
716                    } else if let Some(v) = entry.as_irational() {
717                        gps.altitude = (*v).into();
718                    }
719                }
720                ExifTag::GPSSpeedRef => {
721                    if let Some(c) = entry.as_char() {
722                        gps.speed_ref = Some(c);
723                    }
724                }
725                ExifTag::GPSSpeed => {
726                    if let Some(v) = entry.as_urational() {
727                        gps.speed = Some(*v);
728                    } else if let Some(v) = entry.as_irational() {
729                        gps.speed = Some((*v).into());
730                    }
731                }
732                _ => (),
733            }
734        }
735
736        if has_data {
737            Some(gps)
738        } else {
739            tracing::warn!("GPSInfo data not found");
740            None
741        }
742    }
743
744    fn clone_with_state(&self) -> IfdIter {
745        let mut it = self.clone();
746        it.index = self.index;
747        it.pos = self.pos;
748        it
749    }
750}
751
752#[derive(Debug)]
753pub(crate) enum IfdEntry {
754    IfdNew(IfdIter), // ifd index
755    Entry(EntryValue),
756    Err(ParseEntryError),
757}
758
759impl IfdEntry {
760    pub fn as_u8(&self) -> Option<u8> {
761        if let IfdEntry::Entry(EntryValue::U8(v)) = self {
762            Some(*v)
763        } else {
764            None
765        }
766    }
767
768    pub fn as_char(&self) -> Option<char> {
769        if let IfdEntry::Entry(EntryValue::Text(s)) = self {
770            s.chars().next()
771        } else {
772            None
773        }
774    }
775
776    fn as_irational(&self) -> Option<&IRational> {
777        if let IfdEntry::Entry(EntryValue::IRational(v)) = self {
778            Some(v)
779        } else {
780            None
781        }
782    }
783
784    fn as_irational_array(&self) -> Option<&Vec<IRational>> {
785        if let IfdEntry::Entry(EntryValue::IRationalArray(v)) = self {
786            Some(v)
787        } else {
788            None
789        }
790    }
791
792    fn as_urational(&self) -> Option<&URational> {
793        if let IfdEntry::Entry(EntryValue::URational(v)) = self {
794            Some(v)
795        } else {
796            None
797        }
798    }
799
800    fn as_urational_array(&self) -> Option<&Vec<URational>> {
801        if let IfdEntry::Entry(EntryValue::URationalArray(v)) = self {
802            Some(v)
803        } else {
804            None
805        }
806    }
807
808    fn as_str(&self) -> Option<&str> {
809        if let IfdEntry::Entry(e) = self {
810            e.as_str()
811        } else {
812            None
813        }
814    }
815}
816
817pub(crate) const SUBIFD_TAGS: &[u16] = &[ExifTag::ExifOffset.code(), ExifTag::GPSInfo.code()];
818
819impl Iterator for IfdIter {
820    type Item = (Option<ExifTagCode>, IfdEntry);
821
822    #[tracing::instrument(skip(self))]
823    fn next(&mut self) -> Option<Self::Item> {
824        // tracing::debug!(
825        //     ifd = self.ifd_idx,
826        //     index = self.index,
827        //     entry_num = self.entry_num,
828        //     pos = format!("{:08x}", self.pos),
829        //     "next IFD entry"
830        // );
831        if self.input.len() < self.pos + IFD_ENTRY_SIZE {
832            return None;
833        }
834
835        let endian = self.endian;
836        if self.index > self.entry_num {
837            return None;
838        }
839        if self.index == self.entry_num {
840            tracing::debug!(
841                self.ifd_idx,
842                self.index,
843                pos = self.pos,
844                "try to get next ifd"
845            );
846            self.index += 1;
847
848            // next IFD offset
849            let (_, offset) =
850                complete::u32::<_, nom::error::Error<_>>(endian)(&self.input[self.pos..]).ok()?;
851
852            if offset == 0 {
853                // IFD parsing completed
854                tracing::debug!(?self, "IFD parsing completed");
855                return None;
856            }
857
858            return self
859                .new_ifd_iter(self.ifd_idx + 1, offset, None)
860                .map(|x| (None, x));
861        }
862
863        let entry_data = self
864            .input
865            .slice_checked(self.pos..self.pos + IFD_ENTRY_SIZE)?;
866        self.index += 1;
867        self.pos += IFD_ENTRY_SIZE;
868
869        let (tag, res) = self.parse_tag_entry(entry_data)?;
870
871        Some((Some(tag.into()), res)) // Safe-slice
872    }
873}
874
875#[cfg(test)]
876mod tests {
877
878    use crate::exif::extract_exif_with_mime;
879    use crate::exif::input_into_iter;
880    use crate::file::MimeImage;
881    use crate::slice::SubsliceRange;
882    use crate::testkit::read_sample;
883    use test_case::test_case;
884
885    #[test_case("exif.jpg", "+08:00", MimeImage::Jpeg)]
886    #[test_case("broken.jpg", "", MimeImage::Jpeg)]
887    #[test_case("exif.heic", "+08:00", MimeImage::Heic)]
888    #[test_case("tif.tif", "", MimeImage::Tiff)]
889    #[test_case("fujifilm_x_t1_01.raf.meta", "", MimeImage::Raf)]
890    fn exif_iter_tz(path: &str, tz: &str, img_type: MimeImage) {
891        let buf = read_sample(path).unwrap();
892        let (data, _) = extract_exif_with_mime(img_type, &buf, None).unwrap();
893        let subslice_range = data.and_then(|x| buf.subslice_in_range(x)).unwrap();
894        let iter = input_into_iter((buf, subslice_range), None).unwrap();
895        let expect = if tz.is_empty() {
896            None
897        } else {
898            Some(tz.to_string())
899        };
900        assert_eq!(iter.tz, expect);
901    }
902}