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
35        let mut fields = BTreeMap::new();
36        if let Some(ex) = &self.exif {
37            for f in ex {
38                let key = f.tag.to_string();
39
40                // some tags may have leading quotes yet they
41                // are enclosed in a string.
42                // This helps remove them
43                let value = f
44                    .display_value()
45                    .with_unit(f)
46                    .to_string()
47                    .trim_start_matches(|x| x == '\"')
48                    .trim_end_matches(|x| x == '\"')
49                    .to_string();
50
51                if value.len() < 100 {
52                    fields.insert(key, value);
53                }
54            }
55        }
56        if fields.is_empty() {
57            state.serialize_field::<Option<BTreeMap<String, String>>>("exif", &None)?;
58        } else {
59            state.serialize_field("exif", &fields)?;
60        }
61
62        state.end()
63    }
64}
65
66impl Serialize for ImageFormat {
67    #[allow(clippy::uninlined_format_args)]
68    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
69    where
70        S: Serializer
71    {
72        serializer.serialize_str(&format!("{:?}", self))
73    }
74}