Skip to main content

maxminddb/
metadata.rs

1//! Database metadata types.
2
3use std::collections::btree_map::Entry;
4use std::collections::BTreeMap;
5use std::fmt;
6use std::time::{Duration, SystemTime, UNIX_EPOCH};
7
8use serde::de::{self, MapAccess, Visitor};
9use serde::{Deserialize, Deserializer, Serialize};
10
11use crate::error::MaxMindDbError;
12
13/// Metadata about the MaxMind DB file.
14#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
15pub struct Metadata {
16    /// Major version of the binary format (always 2).
17    pub binary_format_major_version: u16,
18    /// Minor version of the binary format.
19    /// Minor versions are accepted for forward compatibility.
20    pub binary_format_minor_version: u16,
21    /// Unix timestamp when the database was built.
22    pub build_epoch: u64,
23    /// Database type (e.g., "GeoIP2-City", "GeoLite2-Country").
24    pub database_type: String,
25    /// Map of language codes to database descriptions.
26    #[serde(deserialize_with = "deserialize_description")]
27    pub description: BTreeMap<String, String>,
28    /// IP version supported (4 or 6).
29    pub ip_version: u16,
30    /// Languages available in the database.
31    ///
32    /// The spec makes this key optional. It is empty when the database
33    /// omits it.
34    #[serde(default)]
35    pub languages: Vec<String>,
36    /// Number of nodes in the search tree.
37    pub node_count: u32,
38    /// Size of each record in bits (24, 28, or 32).
39    pub record_size: u16,
40}
41
42/// Deserializes the `description` map, rejecting repeated language keys.
43///
44/// The spec requires metadata keys to be unique. Serde's derived struct
45/// deserializer already rejects repeated top-level keys, but a plain
46/// `BTreeMap` would silently keep the last value for a repeated key in the
47/// nested `description` map.
48fn deserialize_description<'de, D>(deserializer: D) -> Result<BTreeMap<String, String>, D::Error>
49where
50    D: Deserializer<'de>,
51{
52    struct DescriptionVisitor;
53
54    impl<'de> Visitor<'de> for DescriptionVisitor {
55        type Value = BTreeMap<String, String>;
56
57        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
58            formatter.write_str("a map of language codes to descriptions")
59        }
60
61        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
62        where
63            A: MapAccess<'de>,
64        {
65            let mut description = BTreeMap::new();
66            while let Some((language, text)) = map.next_entry::<String, String>()? {
67                match description.entry(language) {
68                    Entry::Vacant(entry) => {
69                        entry.insert(text);
70                    }
71                    Entry::Occupied(entry) => {
72                        return Err(de::Error::custom(format!(
73                            "duplicate key `{}` in metadata field `description`",
74                            entry.key()
75                        )));
76                    }
77                }
78            }
79            Ok(description)
80        }
81    }
82
83    deserializer.deserialize_map(DescriptionVisitor)
84}
85
86impl Metadata {
87    /// Returns the database build time as a `SystemTime`.
88    ///
89    /// This converts the `build_epoch` Unix timestamp to a `SystemTime`.
90    /// If `build_epoch` is too large to represent on this platform, this
91    /// returns an [`InvalidDatabase`](MaxMindDbError::InvalidDatabase) error.
92    ///
93    /// # Example
94    ///
95    /// ```
96    /// use maxminddb::Reader;
97    ///
98    /// let reader = Reader::open_readfile("test-data/test-data/GeoIP2-City-Test.mmdb").unwrap();
99    /// let build_time = reader.metadata().build_time().unwrap();
100    /// println!("Database built: {:?}", build_time);
101    /// ```
102    #[inline]
103    pub fn build_time(&self) -> Result<SystemTime, MaxMindDbError> {
104        UNIX_EPOCH
105            .checked_add(Duration::from_secs(self.build_epoch))
106            .ok_or_else(|| {
107                MaxMindDbError::invalid_database(format!(
108                    "build_epoch - Unix timestamp is too large to represent as SystemTime: {}",
109                    self.build_epoch
110                ))
111            })
112    }
113}