use std::future::Future;
use serde::Deserialize;
use serde::Serialize;
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[derive(Serialize, Deserialize)]
pub struct Location<Name> {
pub descendant: Name,
pub distance: u64,
}
impl<Name> Location<Name> {
pub fn new(descendant: Name, distance: u64) -> Self {
Self {
descendant,
distance,
}
}
pub fn map_descendant<T, F>(self, f: F) -> Location<T>
where
F: FnOnce(Name) -> T,
{
let new_name = f(self.descendant);
Location::new(new_name, self.distance)
}
pub fn try_map_descendant<T, E, F>(self, f: F) -> Result<Location<T>, E>
where
F: FnOnce(Name) -> Result<T, E>,
{
let new_name = f(self.descendant)?;
Ok(Location::new(new_name, self.distance))
}
pub async fn then_descendant<T, Fut, F>(self, f: F) -> Location<T>
where
F: FnOnce(Name) -> Fut,
Fut: Future<Output = T>,
{
let new_name = f(self.descendant).await;
Location::new(new_name, self.distance)
}
pub async fn and_then_descendant<T, E, Fut, F>(self, f: F) -> Result<Location<T>, E>
where
F: FnOnce(Name) -> Fut,
Fut: Future<Output = Result<T, E>>,
{
let new_name = f(self.descendant).await?;
Ok(Location::new(new_name, self.distance))
}
pub fn with_descendant<T>(self, descendant: T) -> Location<T> {
Location::new(descendant, self.distance)
}
}
#[cfg(any(test, feature = "for-tests"))]
use quickcheck::Arbitrary;
#[cfg(any(test, feature = "for-tests"))]
use quickcheck::Gen;
#[cfg(any(test, feature = "for-tests"))]
impl<Name> Arbitrary for Location<Name>
where
Name: Arbitrary,
{
fn arbitrary(g: &mut Gen) -> Self {
Location {
descendant: Name::arbitrary(g),
distance: u64::arbitrary(g),
}
}
}