heliwatch/heliwatch/src/aircrafts.rs

68 lines
1.9 KiB
Rust
Raw Normal View History

2021-10-28 18:15:00 +02:00
use std::collections::HashMap;
use std::io::BufReader;
2021-10-28 18:15:00 +02:00
use std::fs::File;
2021-10-30 21:01:12 +02:00
use std::sync::Arc;
2021-10-28 18:15:00 +02:00
use serde::Deserialize;
2021-10-30 18:50:52 +02:00
#[derive(Debug)]
2021-10-28 18:15:00 +02:00
pub struct Aircraft {
2021-10-30 21:01:12 +02:00
pub owner: Option<Arc<String>>,
pub registration: Option<Arc<String>>,
pub model: Option<Arc<String>>,
2021-10-30 18:50:52 +02:00
}
#[derive(Debug, Deserialize)]
struct Record {
2021-10-28 18:15:00 +02:00
pub icao24: String,
pub registration: String,
pub manufacturername: String,
pub model: String,
pub owner: String,
}
pub struct Aircrafts {
data: HashMap<String, Aircraft>,
}
impl Aircrafts {
pub fn load(file: &str) -> Self {
2021-10-30 21:01:12 +02:00
let mut strings = HashMap::new();
let mut nullable = move |s: String| {
if s.len() > 0 {
let e = strings.entry(s.clone())
.or_insert_with(|| Arc::new(s));
Some(e.clone())
} else {
None
}
};
2021-10-28 18:15:00 +02:00
let mut data = HashMap::new();
2021-10-30 21:01:12 +02:00
let mut rdr = csv::Reader::from_reader(BufReader::new(File::open(file).unwrap()));
2021-10-28 18:15:00 +02:00
for result in rdr.deserialize() {
2021-10-30 18:50:52 +02:00
let rec: Record = result.unwrap();
if rec.registration != "" {
data.insert(rec.icao24, Aircraft {
owner: nullable(rec.owner),
registration: nullable(rec.registration),
model: if rec.manufacturername == "" && rec.model == "" {
None
} else if rec.model.starts_with(&rec.manufacturername) {
2021-10-30 21:01:12 +02:00
nullable(rec.model)
2021-10-30 18:50:52 +02:00
} else {
2021-10-30 21:01:12 +02:00
nullable(format!("{} {}", rec.manufacturername, rec.model))
2021-10-30 18:50:52 +02:00
},
});
2021-10-29 03:10:38 +02:00
}
2021-10-28 18:15:00 +02:00
}
println!("Loaded aircraft database with {} entries", data.len());
Aircrafts {
data,
}
}
pub fn find<'s>(&'s self, hex: &str) -> Option<&'s Aircraft> {
self.data.get(hex)
}
}