Skip to main content

zune_image/
serde.rs

1/*
2 * Copyright (c) 2023.
3 *
4 * This software is free software;
5 *
6 * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
7 */
8
9#![cfg(feature = "serde-support")]
10
11use std::collections::BTreeMap;
12
13use serde::ser::SerializeStruct;
14use serde::{Serialize, Serializer};
15
16use crate::codecs::ImageFormat;
17use crate::metadata::ImageMetadata;
18
19impl Serialize for ImageMetadata {
20    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
21    where
22        S: Serializer
23    {
24        const STRUCT_FIELDS: usize = 7;
25        let mut state = serializer.serialize_struct("Metadata", STRUCT_FIELDS)?;
26
27        state.serialize_field("width", &self.width)?;
28        state.serialize_field("height", &self.height)?;
29        state.serialize_field("colorspace", &self.colorspace)?;
30        state.serialize_field("depth", &self.depth)?;
31        state.serialize_field("format", &self.format)?;
32        state.serialize_field("color_transfer_characteristics", &self.color_trc)?;
33        state.serialize_field("gamma_value", &self.default_gamma)?;
34        (state).serialize_field("is_linear", &self.is_linear)?;
35
36        #[cfg(feature = "metadata")]
37        {
38            let mut fields = BTreeMap::new();
39            if let Some(ex) = &self.exif {
40                for f in ex {
41                    let key = f.tag.to_string();
42
43                    // some tags may have leading quotes yet they
44                    // are enclosed in a string.
45                    // This helps remove them
46                    let value = f
47                        .display_value()
48                        .with_unit(f)
49                        .to_string()
50                        .trim_start_matches(|x| x == '\"')
51                        .trim_end_matches(|x| x == '\"')
52                        .to_string();
53
54                    if value.len() < 100 {
55                        fields.insert(key, value);
56                    }
57                }
58            }
59            if fields.is_empty() {
60                state.serialize_field::<Option<BTreeMap<String, String>>>("exif", &None)?;
61            } else {
62                state.serialize_field("exif", &fields)?;
63            }
64        }
65
66        state.end()
67    }
68}
69
70impl Serialize for ImageFormat {
71    #[allow(clippy::uninlined_format_args)]
72    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
73    where
74        S: Serializer
75    {
76        serializer.serialize_str(&format!("{:?}", self))
77    }
78}