#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct LocationQuery {
pub text: String,
#[cfg_attr(feature = "uniffi", uniffi(default = None))]
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub limit: Option<u32>,
#[cfg_attr(feature = "uniffi", uniffi(default = []))]
#[cfg_attr(
feature = "unstable-wasm",
serde(default, deserialize_with = "crate::wasm::or_default")
)]
pub kinds: Vec<LocationKind>,
}
impl<T: Into<String>> From<T> for LocationQuery {
fn from(text: T) -> Self {
Self::new(text)
}
}
impl From<&Self> for LocationQuery {
fn from(query: &Self) -> Self {
query.clone()
}
}
impl<T: Into<Place>> From<T> for DeparturesQuery {
fn from(stop: T) -> Self {
Self::new(stop)
}
}
impl From<&Self> for DeparturesQuery {
fn from(query: &Self) -> Self {
query.clone()
}
}
impl From<&Self> for TripsQuery {
fn from(query: &Self) -> Self {
query.clone()
}
}
impl LocationQuery {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
limit: None,
kinds: Vec::new(),
}
}
#[must_use]
pub fn with_kinds(mut self, kinds: impl IntoIterator<Item = LocationKind>) -> Self {
self.kinds = kinds.into_iter().collect();
self
}
#[must_use]
pub fn with_limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Location {
pub id: String,
#[cfg_attr(
feature = "unstable-wasm",
serde(default, deserialize_with = "crate::wasm::or_default")
)]
pub global_ids: Vec<GlobalId>,
pub kind: LocationKind,
pub name: String,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub locality: Option<String>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub coordinate: Option<Coordinate>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub timezone: Option<String>,
#[cfg_attr(feature = "uniffi", uniffi(default = None))]
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub network: Option<String>,
}
impl Location {
#[must_use]
pub fn station_ids(&self) -> Vec<GlobalId> {
self.global_ids.iter().map(GlobalId::station).collect()
}
#[must_use]
pub fn same_station(&self, other: &Self) -> bool {
let stations = other.station_ids();
self.station_ids().iter().any(|id| stations.contains(id))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct GlobalId {
pub scheme: IdScheme,
pub value: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub enum IdScheme {
Ifopt,
}
impl GlobalId {
pub(crate) fn ifopt(id: &str) -> Option<Self> {
let parts: Vec<&str> = id.split(':').collect();
let [country, region, stop, rest @ ..] = parts.as_slice() else {
return None;
};
let is_number = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
let valid = country.len() == 2
&& country.bytes().all(|b| b.is_ascii_lowercase())
&& is_number(region)
&& is_number(stop)
&& rest.len() <= 2
&& rest.iter().all(|part| !part.is_empty());
valid.then(|| Self {
scheme: IdScheme::Ifopt,
value: id.to_owned(),
})
}
fn station(&self) -> Self {
let parts = match self.scheme {
IdScheme::Ifopt => 3,
};
let end = self
.value
.match_indices(':')
.nth(parts - 1)
.map_or(self.value.len(), |(index, _)| index);
Self {
scheme: self.scheme,
value: self.value.get(..end).unwrap_or(&self.value).to_owned(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub enum LocationKind {
Stop,
Address,
Poi,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Coordinate {
pub latitude: f64,
pub longitude: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "unstable-wasm", derive(tsify::Tsify), tsify(type = "Date"))]
pub struct Timestamp {
pub unix_seconds: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(
feature = "unstable-wasm",
derive(tsify::Tsify),
tsify(type = "string")
)]
pub struct LocalTime {
pub year: u16,
pub month: u8,
pub day: u8,
pub hour: u8,
pub minute: u8,
pub second: u8,
pub utc_offset_seconds: i32,
}
impl std::fmt::Display for LocalTime {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{:02}:{:02}", self.hour, self.minute)
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct DeparturesQuery {
pub stop: Place,
#[cfg_attr(feature = "uniffi", uniffi(default = None))]
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub time: Option<Timestamp>,
#[cfg_attr(feature = "uniffi", uniffi(default = None))]
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub limit: Option<u32>,
}
impl DeparturesQuery {
pub fn new(stop: impl Into<Place>) -> Self {
Self {
stop: stop.into(),
time: None,
limit: None,
}
}
#[must_use]
pub fn with_time(mut self, time: Timestamp) -> Self {
self.time = Some(time);
self
}
#[must_use]
pub fn with_limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Departure {
pub stop: Location,
pub line: Line,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub direction: Option<String>,
pub scheduled_time: Timestamp,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub realtime_time: Option<Timestamp>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub scheduled_platform: Option<String>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub realtime_platform: Option<String>,
pub cancelled: bool,
}
#[cfg_attr(feature = "uniffi", uniffi::export)]
impl Departure {
#[must_use]
pub fn expected_time(&self) -> Timestamp {
self.realtime_time.unwrap_or(self.scheduled_time)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Line {
pub name: String,
pub mode: Mode,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub product: Option<String>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub operator: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub enum Mode {
HighSpeedTrain,
LongDistanceTrain,
NightTrain,
RegionalTrain,
SuburbanTrain,
Subway,
Tram,
Bus,
Coach,
Ferry,
CableCar,
Funicular,
OnDemand,
Airplane,
Other,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct TripsQuery {
pub origin: Place,
pub destination: Place,
#[cfg_attr(feature = "uniffi", uniffi(default = None))]
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub time: Option<TripTime>,
#[cfg_attr(feature = "uniffi", uniffi(default = None))]
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub limit: Option<u32>,
#[cfg_attr(feature = "uniffi", uniffi(default = None))]
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub page: Option<String>,
}
const LATER: &str = "departure:";
const EARLIER: &str = "arrival:";
impl TripsQuery {
#[must_use]
pub fn new(origin: impl Into<Place>, destination: impl Into<Place>) -> Self {
Self {
origin: origin.into(),
destination: destination.into(),
time: None,
limit: None,
page: None,
}
}
#[must_use]
pub fn with_page(mut self, reference: impl Into<String>) -> Self {
self.page = Some(reference.into());
self
}
pub(crate) fn paged_time(&self) -> Result<Option<TripTime>, crate::Error> {
let Some(page) = &self.page else {
return Ok(self.time);
};
let time = |text: &str| {
text.parse()
.ok()
.map(|unix_seconds| Timestamp { unix_seconds })
};
let later = page.strip_prefix(LATER).and_then(time);
let earlier = page.strip_prefix(EARLIER).and_then(time);
later
.map(TripTime::DepartAt)
.or(earlier.map(TripTime::ArriveBy))
.map(Some)
.ok_or_else(|| crate::Error::InvalidQuery {
message: "the page is not a reference from this network".to_owned(),
})
}
#[must_use]
pub fn with_departure(mut self, time: Timestamp) -> Self {
self.time = Some(TripTime::DepartAt(time));
self
}
#[must_use]
pub fn with_arrival(mut self, time: Timestamp) -> Self {
self.time = Some(TripTime::ArriveBy(time));
self
}
#[must_use]
pub fn with_limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
}
pub(crate) enum Target {
Id(String),
Coordinate(Coordinate),
}
impl Place {
pub(crate) fn target(&self, network: &crate::Network) -> Result<Target, crate::Error> {
let invalid = |message: &str| crate::Error::InvalidQuery {
message: message.to_owned(),
};
match self {
Self::Id(id) => Ok(Target::Id(id.clone())),
Self::Coordinate(coordinate)
if (-90.0..=90.0).contains(&coordinate.latitude)
&& (-180.0..=180.0).contains(&coordinate.longitude) =>
{
Ok(Target::Coordinate(*coordinate))
}
Self::Coordinate(_) => Err(invalid("the coordinate is not on the globe")),
Self::Location(location) => network
.place(location)
.ok_or_else(|| {
invalid(&format!(
"{} cannot name the location {}: it has neither a stop ID that the \
network takes nor a coordinate",
network.id, location.name
))
})?
.target(network),
}
}
pub(crate) fn stop_id(&self, network: &crate::Network) -> Result<String, crate::Error> {
let invalid = |message: &str| crate::Error::InvalidQuery {
message: message.to_owned(),
};
match self {
Self::Id(id) => Ok(id.clone()),
Self::Coordinate(_) => Err(invalid("departures need a stop, not a position")),
Self::Location(location) => network.stop_id(location).ok_or_else(|| {
invalid(&format!(
"{} cannot name the location {} as a stop: it is no stop, or it comes from \
another network and has no global ID that this one takes",
network.id, location.name
))
}),
}
}
}
impl From<&str> for Place {
fn from(id: &str) -> Self {
Self::Id(id.to_owned())
}
}
impl From<&String> for Place {
fn from(id: &String) -> Self {
Self::Id(id.clone())
}
}
impl From<&Self> for Place {
fn from(place: &Self) -> Self {
place.clone()
}
}
impl From<String> for Place {
fn from(id: String) -> Self {
Self::Id(id)
}
}
impl From<Coordinate> for Place {
fn from(coordinate: Coordinate) -> Self {
Self::Coordinate(coordinate)
}
}
impl From<Location> for Place {
fn from(location: Location) -> Self {
Self::Location(location)
}
}
impl From<&Location> for Place {
fn from(location: &Location) -> Self {
Self::Location(location.clone())
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, tsify::Tsify),
serde(untagged)
)]
pub enum Place {
Id(String),
Coordinate(Coordinate),
Location(Location),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub enum TripTime {
DepartAt(Timestamp),
ArriveBy(Timestamp),
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Trips {
pub trips: Vec<Trip>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub earlier: Option<String>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub later: Option<String>,
}
impl Trips {
pub(crate) fn paged_by_time(trips: Vec<Trip>) -> Self {
let time = |end: Option<&LegEnd>| {
end.map(|end| end.realtime_time.unwrap_or(end.scheduled_time).unix_seconds)
};
let last = trips.iter().filter_map(|trip| time(trip.departure())).max();
let first = trips.iter().filter_map(|trip| time(trip.arrival())).min();
Self {
later: last.map(|time| format!("{LATER}{}", time.saturating_add(60))),
earlier: first.map(|time| format!("{EARLIER}{}", time.saturating_sub(60))),
trips,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Trip {
pub legs: Vec<Leg>,
}
impl Trip {
#[must_use]
pub fn departure(&self) -> Option<&LegEnd> {
self.legs.first().map(|leg| &leg.departure)
}
#[must_use]
pub fn arrival(&self) -> Option<&LegEnd> {
self.legs.last().map(|leg| &leg.arrival)
}
#[must_use]
pub fn transfers(&self) -> usize {
self.legs
.iter()
.filter(|leg| matches!(leg.kind, LegKind::Transit { .. }))
.count()
.saturating_sub(1)
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Leg {
pub kind: LegKind,
pub departure: LegEnd,
pub arrival: LegEnd,
pub intermediate_stops: Vec<Stopover>,
pub cancelled: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(tag = "type", rename_all = "camelCase")
)]
pub enum LegKind {
Transit {
line: Line,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
direction: Option<String>,
},
Walk,
Other,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct LegEnd {
pub stop: Location,
pub scheduled_time: Timestamp,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub realtime_time: Option<Timestamp>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub scheduled_platform: Option<String>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub realtime_platform: Option<String>,
pub cancelled: bool,
}
#[cfg_attr(feature = "uniffi", uniffi::export)]
impl LegEnd {
#[must_use]
pub fn expected_time(&self) -> Timestamp {
self.realtime_time.unwrap_or(self.scheduled_time)
}
}
impl Stopover {
pub(crate) fn into_leg_start(self) -> Option<LegEnd> {
Some(LegEnd {
stop: self.stop,
scheduled_time: self.scheduled_departure?,
realtime_time: self.realtime_departure,
scheduled_platform: self.scheduled_platform,
realtime_platform: self.realtime_platform,
cancelled: self.cancelled,
})
}
pub(crate) fn into_leg_end(self) -> Option<LegEnd> {
Some(LegEnd {
stop: self.stop,
scheduled_time: self.scheduled_arrival?,
realtime_time: self.realtime_arrival,
scheduled_platform: self.scheduled_platform,
realtime_platform: self.realtime_platform,
cancelled: self.cancelled,
})
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Stopover {
pub stop: Location,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub scheduled_arrival: Option<Timestamp>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub realtime_arrival: Option<Timestamp>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub scheduled_departure: Option<Timestamp>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub realtime_departure: Option<Timestamp>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub scheduled_platform: Option<String>,
#[cfg_attr(
feature = "unstable-wasm",
serde(skip_serializing_if = "Option::is_none")
)]
pub realtime_platform: Option<String>,
pub cancelled: bool,
}