Skip to content

Commit

Permalink
refactor(core): make rkyv and serde optional
Browse files Browse the repository at this point in the history
  • Loading branch information
cathaypacific8747 committed Aug 20, 2024
1 parent f65ec35 commit 324995f
Show file tree
Hide file tree
Showing 15 changed files with 142 additions and 91 deletions.
19 changes: 8 additions & 11 deletions am4-web/src/components/aircraft.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::db::Database;
use am4::aircraft::db::{AircraftSearchError, LENGTH_MAX, LENGTH_MEAN};
use am4::aircraft::{Aircraft, AircraftType};
use am4::aircraft::Aircraft;
use leptos::{wasm_bindgen::JsCast, *};
use web_sys::HtmlInputElement;

Expand Down Expand Up @@ -58,7 +58,10 @@ fn ACErr(e: AircraftSearchError) -> impl IntoView {
.into_iter()
.map(|sugg| {
view! {
<li>{&sugg.item.shortname.0} " (" {&sugg.item.name.0} ")"</li>
<li>
{&sugg.item.shortname.to_string()} " ("
{&sugg.item.name.to_string()} ")"
</li>
}
})
.collect::<Vec<_>>()}
Expand All @@ -79,12 +82,6 @@ fn ACErr(e: AircraftSearchError) -> impl IntoView {

#[component]
fn Ac(aircraft: Aircraft) -> impl IntoView {
let ac_type = move || match aircraft.ac_type {
AircraftType::Pax => "Pax",
AircraftType::Cargo => "Cargo",
AircraftType::Vip => "VIP",
};

let width = if aircraft.length == 0 {
LENGTH_MEAN / LENGTH_MAX
} else {
Expand All @@ -94,8 +91,8 @@ fn Ac(aircraft: Aircraft) -> impl IntoView {
view! {
<div class="ac-card">
<h3>
{&aircraft.manufacturer} " " {&aircraft.name.0} " ("
<code>{&aircraft.shortname.0}</code> ", " {ac_type} ")"
{aircraft.manufacturer} " " {aircraft.name.to_string()} " ("
<code>{aircraft.shortname.to_string()}</code> ", " {aircraft.r#type.to_string()} ")"
</h3>
<table>
<tr>
Expand Down Expand Up @@ -164,7 +161,7 @@ fn Ac(aircraft: Aircraft) -> impl IntoView {
</tr>
</table>
<div id="ac-img">
<img src=format!("/assets/img/aircraft/{}.webp", aircraft.img) width=width/>
<img src=format!("/assets/img/aircraft/{}.webp", aircraft.img) width=width/>
</div>
</div>
}
Expand Down
9 changes: 5 additions & 4 deletions am4-web/src/components/airport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ fn APErr(e: AirportSearchError) -> impl IntoView {
.map(|sugg| {
view! {
<li>
{&sugg.item.iata.0} " / " {&sugg.item.icao.0} " ("
{&sugg.item.name.0} ", " {&sugg.item.country} ")"
{&sugg.item.iata.to_string()} " / "
{&sugg.item.icao.to_string()} " ("
{&sugg.item.name.to_string()} ", " {&sugg.item.country} ")"
</li>
}
})
Expand All @@ -84,8 +85,8 @@ fn Ap<'a>(airport: &'a Airport) -> impl IntoView {
view! {
<div class="ap-card">
<h3>
{&airport.name.0} ", " {&airport.country} " (" {&airport.iata.0} " / "
{&airport.icao.0} ")"
{&airport.name.to_string()} ", " {&airport.country} " (" {&airport.iata.to_string()}
" / " {&airport.icao.to_string()} ")"
</h3>
<table>
<tr>
Expand Down
14 changes: 12 additions & 2 deletions am4/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,26 @@ edition = "2021"

[dependencies]
jaro_winkler = "0.1.0"
serde = { version = "1.0.203", features = ["derive"] }
thiserror = "1.0.61"
rkyv = { version = "0.7.44", features = ["validation", "strict", "archive_le"] }
uuid = { version = "1.10.0", features = ["v4"] }
derive_more = { version = "1.0.0", features = [
"from",
"into",
"display",
"add",
"constructor",
] }
serde = { version = "1.0.203", optional = true, features = ["derive"] }
rkyv = { version = "0.7.44", optional = true, features = [
"validation",
"strict",
"archive_le",
] }

[features]
default = ["rkyv"]
serde = ["dep:serde"]
rkyv = ["dep:rkyv"]

[dev-dependencies]
rstest = "0.20.0"
Expand Down
21 changes: 12 additions & 9 deletions am4/src/aircraft/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,17 @@ Apply the modifiers and return a [CustomAircraft].
*/
use crate::aircraft::custom::{CustomAircraft, Modification};
use crate::aircraft::{Aircraft, AircraftError, EnginePriority, Id, Name, ShortName};
use crate::utils::ParseError;
use crate::utils::{queue_suggestions, Suggestion, MAX_SUGGESTIONS};
use jaro_winkler::jaro_winkler;
use rkyv::{self, Deserialize};
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::{BinaryHeap, HashMap};
use std::str::FromStr;
use thiserror::Error;

#[cfg(feature = "rkyv")]
use crate::utils::ParseError;
#[cfg(feature = "rkyv")]
use rkyv::{self, Deserialize};

pub static LENGTH_MAX: f32 = 77.0;
pub static LENGTH_MEAN: f32 = 34.278454;

Expand Down Expand Up @@ -125,7 +127,7 @@ impl From<&QueryCtx> for Result<SearchKey, AircraftSearchError> {
Err(AircraftSearchError::AircraftNotFound(ctx.clone()))
}
}
QueryKey::Id(id) => Ok(SearchKey::from(id.clone())),
QueryKey::Id(id) => Ok(SearchKey::from(*id)),
QueryKey::ShortName(sn) => Ok(SearchKey::from(sn.clone())),
QueryKey::Name(name) => Ok(SearchKey::from(name.clone())),
}
Expand All @@ -144,6 +146,7 @@ pub struct Aircrafts {
}

impl Aircrafts {
#[cfg(feature = "rkyv")]
pub fn from_bytes(buffer: &[u8]) -> Result<Self, ParseError> {
let archived = rkyv::check_archived_root::<Vec<Aircraft>>(buffer)
.map_err(|e| ParseError::ArchiveError(e.to_string()))?;
Expand All @@ -156,19 +159,19 @@ impl Aircrafts {

for (i, ac) in data.iter().enumerate() {
index
.entry(SearchKey::from(ac.id.clone()))
.entry(SearchKey::from(ac.id))
.or_default()
.insert(ac.priority.clone(), i);
.insert(ac.priority, i);

index
.entry(SearchKey::from(ac.shortname.clone()))
.or_default()
.insert(ac.priority.clone(), i);
.insert(ac.priority, i);

index
.entry(SearchKey::from(ac.name.clone()))
.or_default()
.insert(ac.priority.clone(), i);
.insert(ac.priority, i);
}

Ok(Self { data, index })
Expand Down
63 changes: 35 additions & 28 deletions am4/src/aircraft/mod.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
pub mod custom;
pub mod db;

use rkyv::{Archive as Ra, Deserialize as Rd, Serialize as Rs};
use serde::Deserialize;
use std::fmt;
use derive_more::{Constructor, Display, From, Into};
use std::str::FromStr;
use thiserror::Error;

#[derive(Debug, Clone, Deserialize, PartialEq, Ra, Rd, Rs)]
#[archive(check_bytes)]
#[cfg(feature = "rkyv")]
use rkyv::{Archive as Ra, Deserialize as Rd, Serialize as Rs};
#[cfg(feature = "serde")]
use serde::Deserialize;

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "rkyv", derive(Ra, Rd, Rs), archive(check_bytes))]
#[cfg_attr(feature = "serde", derive(Deserialize))]
pub struct Aircraft {
pub id: Id,
pub shortname: ShortName,
pub manufacturer: String,
pub name: Name,
#[serde(rename = "type")]
pub ac_type: AircraftType,
pub r#type: AircraftType,
pub priority: EnginePriority,
pub eid: u16,
pub ename: String,
Expand All @@ -38,9 +41,10 @@ pub struct Aircraft {
pub length: u8,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash, Ra, Rd, Rs)]
#[archive(check_bytes)]
pub struct Id(pub u16);
#[derive(Debug, Clone, Copy, Display, PartialEq, Eq, Hash, Constructor, Into)]
#[cfg_attr(feature = "rkyv", derive(Ra, Rd, Rs), archive(check_bytes))]
#[cfg_attr(feature = "serde", derive(Deserialize))]
pub struct Id(u16);

impl FromStr for Id {
type Err = AircraftError;
Expand All @@ -52,9 +56,10 @@ impl FromStr for Id {
}
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash, Ra, Rd, Rs)]
#[archive(check_bytes)]
pub struct ShortName(pub String);
#[derive(Debug, Clone, Display, PartialEq, Eq, Hash, Into)]
#[cfg_attr(feature = "rkyv", derive(Ra, Rd, Rs), archive(check_bytes))]
#[cfg_attr(feature = "serde", derive(Deserialize))]
pub struct ShortName(String);

impl FromStr for ShortName {
type Err = AircraftError;
Expand All @@ -67,9 +72,10 @@ impl FromStr for ShortName {
}
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash, Ra, Rd, Rs)]
#[archive(check_bytes)]
pub struct Name(pub String);
#[derive(Debug, Clone, Display, PartialEq, Eq, Hash, Into)]
#[cfg_attr(feature = "rkyv", derive(Ra, Rd, Rs), archive(check_bytes))]
#[cfg_attr(feature = "serde", derive(Deserialize))]
pub struct Name(String);

impl FromStr for Name {
type Err = AircraftError;
Expand All @@ -82,9 +88,10 @@ impl FromStr for Name {
}
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash, Ra, Rd, Rs)]
#[archive(check_bytes)]
pub struct EnginePriority(pub u8);
#[derive(Debug, Clone, Copy, Display, PartialEq, Eq, Hash, Constructor, Into, From)]
#[cfg_attr(feature = "rkyv", derive(Ra, Rd, Rs), archive(check_bytes))]
#[cfg_attr(feature = "serde", derive(Deserialize))]
pub struct EnginePriority(u8);

impl FromStr for EnginePriority {
type Err = AircraftError;
Expand All @@ -96,18 +103,17 @@ impl FromStr for EnginePriority {
}
}

impl fmt::Display for EnginePriority {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}

#[derive(Debug, Clone, Deserialize, PartialEq, Ra, Rd, Rs)]
#[archive(check_bytes)]
#[serde(rename_all = "lowercase")]
#[derive(Debug, Clone, Display, PartialEq)]
#[cfg_attr(feature = "rkyv", derive(Ra, Rd, Rs), archive(check_bytes))]
#[cfg_attr(
feature = "serde",
derive(Deserialize),
serde(rename_all = "lowercase")
)]
pub enum AircraftType {
Pax,
Cargo,
#[display("VIP")]
Vip,
}

Expand All @@ -124,6 +130,7 @@ impl FromStr for AircraftType {
}
}

// TODO: wrap ParseIntError and manually derive serde and rkyv
#[derive(Debug, Error)]
pub enum AircraftError {
#[error("Invalid aircraft ID: {0}")]
Expand Down
12 changes: 8 additions & 4 deletions am4/src/airport/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@ Given &[[Airport]], build hashmaps that point [SearchKey]s to the array index.
*/

use crate::airport::{Airport, AirportError, Iata, Icao, Id, Name};
use crate::utils::ParseError;
use crate::utils::{queue_suggestions, Suggestion, MAX_SUGGESTIONS};
use jaro_winkler::jaro_winkler;
use rkyv::{self, Deserialize};
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::str::FromStr;
use thiserror::Error;

#[cfg(feature = "rkyv")]
use crate::utils::ParseError;
#[cfg(feature = "rkyv")]
use rkyv::{self, Deserialize};

pub const AIRPORT_COUNT: usize = 3907;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -110,7 +113,7 @@ impl From<QueryKey> for Result<SearchKey, AirportSearchError> {
Err(AirportSearchError::AirportNotFound(key.clone()))
}
}
QueryKey::Id(id) => Ok(SearchKey::from(id.clone())),
QueryKey::Id(id) => Ok(SearchKey::from(*id)),
QueryKey::Iata(iata) => Ok(SearchKey::from(iata.clone())),
QueryKey::Icao(icao) => Ok(SearchKey::from(icao.clone())),
QueryKey::Name(name) => Ok(SearchKey::from(name.clone())),
Expand All @@ -128,6 +131,7 @@ pub struct Airports {
}

impl Airports {
#[cfg(feature = "rkyv")]
pub fn from_bytes(buffer: &[u8]) -> Result<Self, ParseError> {
let archived = rkyv::check_archived_root::<Vec<Airport>>(buffer)
.map_err(|e| ParseError::ArchiveError(e.to_string()))?;
Expand All @@ -139,7 +143,7 @@ impl Airports {
let mut index = HashMap::<SearchKey, usize>::new();

for (i, ap) in data.iter().enumerate() {
index.entry(SearchKey::from(ap.idx.clone())).or_insert(i);
index.entry(SearchKey::from(ap.idx)).or_insert(i);
index.entry(SearchKey::from(ap.iata.clone())).or_insert(i);
index.entry(SearchKey::from(ap.icao.clone())).or_insert(i);
index.entry(SearchKey::from(ap.name.clone())).or_insert(i);
Expand Down
Loading

0 comments on commit 324995f

Please sign in to comment.