1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#![deny(missing_docs)]
mod gen;
use std::{
collections::HashMap, convert::TryInto, fs, io, path::Path,
string::FromUtf8Error,
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Location {
pub latitude: f32,
pub longitude: f32,
}
impl Location {
pub fn new(latitude: f32, longitude: f32) -> Location {
Location {
latitude,
longitude,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Zone {
pub polygon_id: u32,
pub meta_id: u32,
pub fields: HashMap<String, String>,
}
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ZoneMatchKind {
InZone,
InExcludedZone,
OnBorderVertex,
OnBorderSegment,
}
impl ZoneMatchKind {
fn from_point_lookup(r: gen::PointLookupResult) -> Option<ZoneMatchKind> {
match r {
gen::PointLookupResult::InZone => Some(ZoneMatchKind::InZone),
gen::PointLookupResult::InExcludedZone => {
Some(ZoneMatchKind::InExcludedZone)
}
gen::PointLookupResult::OnBorderVertex => {
Some(ZoneMatchKind::OnBorderVertex)
}
gen::PointLookupResult::OnBorderSegment => {
Some(ZoneMatchKind::OnBorderSegment)
}
_ => None,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ZoneMatch {
pub kind: ZoneMatchKind,
pub zone: Zone,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ZoneLookup {
pub matches: Vec<ZoneMatch>,
pub safezone: f32,
}
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("IO error")]
IoError(#[from] io::Error),
#[error("database header is truncated")]
TruncatedDatabase(usize),
#[error("invalid magic bytes")]
InvalidMagic([u8; 3]),
#[error("invalid version")]
InvalidVersion(u8),
#[error("invalid table type")]
InvalidTableType(u8),
#[error("invalid field name")]
InvalidFieldName(u8, StringParseError),
#[error("invalid notice")]
InvalidNotice(StringParseError),
#[error("invalid metadata offset")]
InvalidMetadataOffset,
#[error("invalid data offset")]
InvalidDataOffset,
#[error("invalid padding offset")]
InvalidPaddingOffset,
#[error("length mismatch")]
LengthMismatch(usize),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TableType {
Country,
Timezone,
}
#[allow(missing_docs)]
pub type Result<T> = std::result::Result<T, Error>;
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum StringParseError {
#[error("encoding error")]
EncodingError,
#[error("invalid UTF-8")]
InvalidUtf8(#[from] FromUtf8Error),
}
fn parse_string(
db: &Database,
index: &mut u32,
) -> std::result::Result<String, StringParseError> {
if let Some(bytes) = gen::parse_string(db, index) {
let string = String::from_utf8(bytes)?;
Ok(string)
} else {
Err(StringParseError::EncodingError)
}
}
pub struct Database {
bbox_offset: u32,
data_offset: u32,
mapping: Vec<u8>,
metadata_offset: u32,
pub field_names: Vec<String>,
pub notice: String,
pub precision: u8,
pub table_type: crate::TableType,
pub version: u8,
}
impl Database {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Database> {
let mapping = fs::read(path)?;
Self::from_vec(mapping)
}
pub fn from_vec(mapping: Vec<u8>) -> Result<Database> {
let mut db = Database {
mapping,
notice: String::new(),
table_type: TableType::Country,
version: 0,
precision: 0,
field_names: Vec::new(),
bbox_offset: 0,
metadata_offset: 0,
data_offset: 0,
};
Self::parse_header(&mut db)?;
Ok(db)
}
fn parse_header(db: &mut Database) -> Result<()> {
if db.mapping.len() < 7 {
return Err(Error::TruncatedDatabase(db.mapping.len()));
}
let expected_magic = b"PLB";
let actual_magic = &db.mapping[0..3];
if actual_magic != expected_magic {
return Err(Error::InvalidMagic(
actual_magic.try_into().unwrap_or([0; 3]),
));
}
let table_type = db.mapping[3];
db.version = db.mapping[4];
db.precision = db.mapping[5];
let num_fields = db.mapping[6];
if table_type == b'T' {
db.table_type = TableType::Timezone;
} else if table_type == b'C' {
db.table_type = TableType::Country;
} else {
return Err(Error::InvalidTableType(table_type));
}
if db.version >= 2 {
return Err(Error::InvalidVersion(db.version));
}
let mut index = 7;
db.field_names.reserve(num_fields as usize);
for field_index in 0..num_fields {
let name = parse_string(db, &mut index)
.map_err(|err| Error::InvalidFieldName(field_index, err))?;
db.field_names.push(name);
}
db.notice =
parse_string(db, &mut index).map_err(Error::InvalidNotice)?;
let mut tmp: u64 = 0;
if gen::decode_variable_length_unsigned(db, &mut index, &mut tmp) == 0 {
return Err(Error::InvalidMetadataOffset);
}
db.metadata_offset = tmp as u32 + db.bbox_offset;
if gen::decode_variable_length_unsigned(db, &mut index, &mut tmp) == 0 {
return Err(Error::InvalidDataOffset);
}
db.data_offset = tmp as u32 + db.metadata_offset;
if gen::decode_variable_length_unsigned(db, &mut index, &mut tmp) == 0 {
return Err(Error::InvalidPaddingOffset);
}
db.bbox_offset += index;
db.metadata_offset += index;
db.data_offset += index;
let length = (tmp + db.data_offset as u64) as usize;
if length != db.mapping.len() {
return Err(Error::LengthMismatch(length as usize));
}
Ok(())
}
pub fn simple_lookup(&self, location: Location) -> Option<String> {
let results = gen::lookup(self, location, None);
if let Some(result) = results.first() {
match self.table_type {
TableType::Country => result.zone.fields.get("Name"),
TableType::Timezone => {
if let Some(prefix) =
result.zone.fields.get("TimezoneIdPrefix")
{
if let Some(id) = result.zone.fields.get("TimezoneId") {
return Some(format!("{}{}", prefix, id));
}
}
None
}
}
.cloned()
} else {
None
}
}
pub fn lookup(&self, location: Location) -> ZoneLookup {
let mut safezone: f32 = 0.0;
let results = gen::lookup(self, location, Some(&mut safezone));
let matches = results
.iter()
.map(|r| {
ZoneMatch {
kind: ZoneMatchKind::from_point_lookup(r.result)
.expect("invalid match kind"),
zone: r.zone.clone(),
}
})
.collect::<Vec<_>>();
ZoneLookup { matches, safezone }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_open() {
let db = Database::open("data/timezone21.bin").unwrap();
assert_eq!(db.bbox_offset, 288);
assert_eq!(db.metadata_offset, 34032);
assert_eq!(db.data_offset, 43157);
assert_eq!(db.notice, "Contains data from Natural Earth, placed in the Public Domain. Contains information from https://github.com/evansiroky/timezone-boundary-builder, which is made available here under the Open Database License \\(ODbL\\).".to_string());
assert_eq!(db.table_type, TableType::Timezone);
assert_eq!(db.precision, 21);
assert_eq!(
db.field_names,
vec![
"TimezoneIdPrefix".to_string(),
"TimezoneId".to_string(),
"CountryAlpha2".to_string(),
"CountryName".to_string(),
]
);
}
#[test]
fn test_simple_lookup() {
let db = Database::open("data/timezone21.bin").unwrap();
assert_eq!(
db.simple_lookup(Location::new(39.9042, 116.4074)).unwrap(),
"Asia/Shanghai"
);
assert_eq!(
db.simple_lookup(Location::new(-34.6037, -58.3816)).unwrap(),
"America/Argentina/Buenos_Aires"
);
assert_eq!(
db.simple_lookup(Location::new(-35.2809, 149.1300)).unwrap(),
"Australia/Sydney"
);
assert_eq!(
db.simple_lookup(Location::new(40.7128, -74.0060)).unwrap(),
"America/New_York"
);
}
}