Debian Codegraph @

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