Skip to content

Instantly share code, notes, and snippets.

@Xevion
Created July 21, 2023 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xevion/532c6db74efd487d7195a38e0bf7336c to your computer and use it in GitHub Desktop.
Save Xevion/532c6db74efd487d7195a38e0bf7336c to your computer and use it in GitHub Desktop.
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::Path;
use regex::Regex;
use chrono::{FixedOffset};
const HOUR: u32 = 3600;
fn parse_offset(raw_offset: &str) -> i32 {
let is_west = raw_offset.starts_with('−');
let hours = raw_offset[1..3].parse::<u32>().unwrap();
let minutes = match raw_offset.contains(':') {
true => raw_offset[4..6].parse::<u32>().unwrap(),
false => 0,
};
let value = (hours * HOUR) + (minutes * 60);
return if is_west { value as i32 * -1 } else { value as i32 };
}
fn main() {
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("codegen.rs");
let raw_tz = BufReader::new(File::open("./src/abbr_tz").unwrap());
let re = Regex::new(r"([A-Z]+)\s\t.+\s\tUTC([−+±]\d{2}(?::\d{2})?)").unwrap();
let mut file = BufWriter::new(File::create(&path).unwrap());
let mut builder: phf_codegen::Map<String> = phf_codegen::Map::new();
let mut entries: Vec<(String, String)> = vec!();
for line in raw_tz.lines() {
let line = line.unwrap();
// println!("{line}");
let capture = re.captures(&line).expect("RegEx failed to match line");
let abbreviation = capture.get(1).unwrap().as_str();
let offset = if line.starts_with('±') {
parse_offset(capture.get(2).unwrap().as_str())
} else {
0
};
builder.entry(String::from(abbreviation), &offset.to_string());
}
write!(
&mut file,
"static TIMEZONES: phf::Map<&'static str, &'static str> = {}",
builder.build()
)
.unwrap();
write!(&mut file, ";\n").unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment