Debian Codegraph @

debian/missing-sources/chrono/src/offset/local/tz_data.rs

raw
1 //! Rust parser of ZoneInfoDb(`tzdata`) on Android and OpenHarmony
2 //!
3 //! Ported from: https://android.googlesource.com/platform/prebuilts/fullsdk/sources/+/refs/heads/androidx-appcompat-release/android-34/com/android/i18n/timezone/ZoneInfoDb.java
4 use std::{
5 ffi::CStr,
6 fmt::Debug,
7 fs::File,
8 io::{Error, ErrorKind, Read, Result, Seek, SeekFrom},
9 };
10
11 /// Get timezone data from the `tzdata` file of HarmonyOS NEXT.
12 #[cfg(target_env = "ohos")]
13 pub(crate) fn for_zone(tz_string: &str) -> Result<Option<Vec<u8>>> {
14 let mut file = File::open("/system/etc/zoneinfo/tzdata")?;
15 find_tz_data::<OHOS_ENTRY_LEN>(&mut file, tz_string.as_bytes())
16 }
17
18 /// Get timezone data from the `tzdata` file of Android.
19 #[cfg(target_os = "android")]
20 pub(crate) fn for_zone(tz_string: &str) -> Result<Option<Vec<u8>>> {
21 let mut file = open_android_tz_data_file()?;
22 find_tz_data::<ANDROID_ENTRY_LEN>(&mut file, tz_string.as_bytes())
23 }
24
25 /// Open the `tzdata` file of Android from the environment variables.
26 #[cfg(target_os = "android")]
27 fn open_android_tz_data_file() -> Result<File> {
28 for (env_var, path) in
29 [("ANDROID_DATA", "/misc/zoneinfo"), ("ANDROID_ROOT", "/usr/share/zoneinfo")]
30 {
31 if let Ok(env_value) = std::env::var(env_var) {
32 if let Ok(file) = File::open(format!("{}{}/tzdata", env_value, path)) {
33 return Ok(file);
34 }
35 }
36 }
37 Err(Error::from(ErrorKind::NotFound))
38 }
39
40 /// Get timezone data from the `tzdata` file reader
41 #[cfg(any(test, target_env = "ohos", target_os = "android"))]
42 fn find_tz_data<const ENTRY_LEN: usize>(
43 mut reader: impl Read + Seek,
44 tz_name: &[u8],
45 ) -> Result<Option<Vec<u8>>> {
46 let header = TzDataHeader::new(&mut reader)?;
47 let index = TzDataIndexes::new::<ENTRY_LEN>(&mut reader, &header)?;
48 Ok(if let Some(entry) = index.find_timezone(tz_name) {
49 Some(index.find_tzdata(reader, &header, entry)?)
50 } else {
51 None
52 })
53 }
54
55 /// Header of the `tzdata` file.
56 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
57 struct TzDataHeader {
58 version: [u8; 5],
59 index_offset: u32,
60 data_offset: u32,
61 zonetab_offset: u32,
62 }
63
64 impl TzDataHeader {
65 /// Parse the header of the `tzdata` file.
66 fn new(mut data: impl Read) -> Result<Self> {
67 let version = {
68 let mut magic = [0; TZDATA_VERSION_LEN];
69 data.read_exact(&mut magic)?;
70 if !magic.starts_with(b"tzdata") || magic[TZDATA_VERSION_LEN - 1] != 0 {
71 return Err(Error::new(ErrorKind::Other, "invalid tzdata header magic"));
72 }
73 let mut version = [0; 5];
74 version.copy_from_slice(&magic[6..11]);
75 version
76 };
77
78 let mut offset = [0; 4];
79 data.read_exact(&mut offset)?;
80 let index_offset = u32::from_be_bytes(offset);
81 data.read_exact(&mut offset)?;
82 let data_offset = u32::from_be_bytes(offset);
83 data.read_exact(&mut offset)?;
84 let zonetab_offset = u32::from_be_bytes(offset);
85
86 Ok(Self { version, index_offset, data_offset, zonetab_offset })
87 }
88 }
89
90 /// Indexes of the `tzdata` file.
91 struct TzDataIndexes {
92 indexes: Vec<TzDataIndex>,
93 }
94
95 impl TzDataIndexes {
96 /// Create a new `TzDataIndexes` from the `tzdata` file reader.
97 fn new<const ENTRY_LEN: usize>(mut reader: impl Read, header: &TzDataHeader) -> Result<Self> {
98 let mut buf = vec![0; header.data_offset.saturating_sub(header.index_offset) as usize];
99 reader.read_exact(&mut buf)?;
100 // replace chunks with array_chunks when it's stable
101 Ok(TzDataIndexes {
102 indexes: buf
103 .chunks(ENTRY_LEN)
104 .filter_map(|chunk| {
105 from_bytes_until_nul(&chunk[..TZ_NAME_LEN]).map(|name| {
106 let name = name.to_bytes().to_vec().into_boxed_slice();
107 let offset = u32::from_be_bytes(
108 chunk[TZ_NAME_LEN..TZ_NAME_LEN + 4].try_into().unwrap(),
109 );
110 let length = u32::from_be_bytes(
111 chunk[TZ_NAME_LEN + 4..TZ_NAME_LEN + 8].try_into().unwrap(),
112 );
113 TzDataIndex { name, offset, length }
114 })
115 })
116 .collect(),
117 })
118 }
119
120 /// Find a timezone by name.
121 fn find_timezone(&self, timezone: &[u8]) -> Option<&TzDataIndex> {
122 // timezones in tzdata are sorted by name.
123 self.indexes.binary_search_by_key(&timezone, |x| &x.name).map(|x| &self.indexes[x]).ok()
124 }
125
126 /// Retrieve a chunk of timezone data by the index.
127 fn find_tzdata(
128 &self,
129 mut reader: impl Read + Seek,
130 header: &TzDataHeader,
131 index: &TzDataIndex,
132 ) -> Result<Vec<u8>> {
133 reader.seek(SeekFrom::Start(index.offset as u64 + header.data_offset as u64))?;
134 let mut buffer = vec![0; index.length as usize];
135 reader.read_exact(&mut buffer)?;
136 Ok(buffer)
137 }
138 }
139
140 /// Index entry of the `tzdata` file.
141 struct TzDataIndex {
142 name: Box<[u8]>,
143 offset: u32,
144 length: u32,
145 }
146
147 /// TODO: Change this `CStr::from_bytes_until_nul` once MSRV was bumped above 1.72.0
148 fn from_bytes_until_nul(bytes: &[u8]) -> Option<&CStr> {
149 let nul_pos = bytes.iter().position(|&b| b == 0)?;
150 // SAFETY:
151 // 1. nul_pos + 1 <= bytes.len()
152 // 2. We know there is a nul byte at nul_pos, so this slice (ending at the nul byte) is a well-formed C string.
153 Some(unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[..=nul_pos]) })
154 }
155
156 /// Ohos tzdata index entry size: `name + offset + length`
157 #[cfg(any(test, target_env = "ohos"))]
158 const OHOS_ENTRY_LEN: usize = TZ_NAME_LEN + 2 * size_of::<u32>();
159 /// Android tzdata index entry size: `name + offset + length + raw_utc_offset(legacy)`:
160 /// [reference](https://android.googlesource.com/platform/prebuilts/fullsdk/sources/+/refs/heads/androidx-appcompat-release/android-34/com/android/i18n/timezone/ZoneInfoDb.java#271)
161 #[cfg(any(test, target_os = "android"))]
162 const ANDROID_ENTRY_LEN: usize = TZ_NAME_LEN + 3 * size_of::<u32>();
163 /// The database reserves 40 bytes for each id.
164 const TZ_NAME_LEN: usize = 40;
165 /// Size of the version string in the header of `tzdata` file.
166 /// e.g. `tzdata2024b\0`
167 const TZDATA_VERSION_LEN: usize = 12;
168
169 #[cfg(test)]
170 mod tests {
171 use super::*;
172
173 #[test]
174 fn test_ohos_tzdata_header_and_index() {
175 let file = File::open("./tests/ohos/tzdata").unwrap();
176 let header = TzDataHeader::new(&file).unwrap();
177 assert_eq!(header.version, *b"2024a");
178 assert_eq!(header.index_offset, 24);
179 assert_eq!(header.data_offset, 21240);
180 assert_eq!(header.zonetab_offset, 272428);
181
182 let iter = TzDataIndexes::new::<OHOS_ENTRY_LEN>(&file, &header).unwrap();
183 assert_eq!(iter.indexes.len(), 442);
184 assert!(iter.find_timezone(b"Asia/Shanghai").is_some());
185 assert!(iter.find_timezone(b"Pacific/Noumea").is_some());
186 }
187
188 #[test]
189 fn test_ohos_tzdata_loading() {
190 let file = File::open("./tests/ohos/tzdata").unwrap();
191 let header = TzDataHeader::new(&file).unwrap();
192 let iter = TzDataIndexes::new::<OHOS_ENTRY_LEN>(&file, &header).unwrap();
193 let timezone = iter.find_timezone(b"Asia/Shanghai").unwrap();
194 let tzdata = iter.find_tzdata(&file, &header, timezone).unwrap();
195 assert_eq!(tzdata.len(), 393);
196 }
197
198 #[test]
199 fn test_invalid_tzdata_header() {
200 TzDataHeader::new(&b"tzdaaa2024aaaaaaaaaaaaaaa\0"[..]).unwrap_err();
201 }
202
203 #[test]
204 fn test_android_tzdata_header_and_index() {
205 let file = File::open("./tests/android/tzdata").unwrap();
206 let header = TzDataHeader::new(&file).unwrap();
207 assert_eq!(header.version, *b"2021a");
208 assert_eq!(header.index_offset, 24);
209 assert_eq!(header.data_offset, 30860);
210 assert_eq!(header.zonetab_offset, 491837);
211
212 let iter = TzDataIndexes::new::<ANDROID_ENTRY_LEN>(&file, &header).unwrap();
213 assert_eq!(iter.indexes.len(), 593);
214 assert!(iter.find_timezone(b"Asia/Shanghai").is_some());
215 assert!(iter.find_timezone(b"Pacific/Noumea").is_some());
216 }
217
218 #[test]
219 fn test_android_tzdata_loading() {
220 let file = File::open("./tests/android/tzdata").unwrap();
221 let header = TzDataHeader::new(&file).unwrap();
222 let iter = TzDataIndexes::new::<ANDROID_ENTRY_LEN>(&file, &header).unwrap();
223 let timezone = iter.find_timezone(b"Asia/Shanghai").unwrap();
224 let tzdata = iter.find_tzdata(&file, &header, timezone).unwrap();
225 assert_eq!(tzdata.len(), 573);
226 }
227
228 #[test]
229 fn test_ohos_tzdata_find() {
230 let file = File::open("./tests/ohos/tzdata").unwrap();
231 let tzdata = find_tz_data::<OHOS_ENTRY_LEN>(file, b"Asia/Shanghai").unwrap().unwrap();
232 assert_eq!(tzdata.len(), 393);
233 }
234
235 #[test]
236 fn test_ohos_tzdata_find_missing() {
237 let file = File::open("./tests/ohos/tzdata").unwrap();
238 assert!(find_tz_data::<OHOS_ENTRY_LEN>(file, b"Asia/Sjasdfai").unwrap().is_none());
239 }
240
241 #[test]
242 fn test_android_tzdata_find() {
243 let file = File::open("./tests/android/tzdata").unwrap();
244 let tzdata = find_tz_data::<ANDROID_ENTRY_LEN>(file, b"Asia/Shanghai").unwrap().unwrap();
245 assert_eq!(tzdata.len(), 573);
246 }
247
248 #[test]
249 fn test_android_tzdata_find_missing() {
250 let file = File::open("./tests/android/tzdata").unwrap();
251 assert!(find_tz_data::<ANDROID_ENTRY_LEN>(file, b"Asia/S000000i").unwrap().is_none());
252 }
253
254 #[cfg(target_env = "ohos")]
255 #[test]
256 fn test_ohos_machine_tz_data_loading() {
257 let tzdata = for_zone(b"Asia/Shanghai").unwrap().unwrap();
258 assert!(!tzdata.is_empty());
259 }
260
261 #[cfg(target_os = "android")]
262 #[test]
263 fn test_android_machine_tz_data_loading() {
264 let tzdata = for_zone(b"Asia/Shanghai").unwrap().unwrap();
265 assert!(!tzdata.is_empty());
266 }
267 }