use alloc::borrow::Cow;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use crate::models::currency::Currency;
use crate::models::{requests::RequestMethod, Model, PathStep};
use super::{CommonFields, Request};
pub type Path<'a> = Vec<PathStep<'a>>;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum PathFindSubcommand {
#[default]
Create,
Close,
Status,
}
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct PathFind<'a> {
#[serde(flatten)]
pub common_fields: CommonFields<'a>,
pub destination_account: Cow<'a, str>,
pub destination_amount: Currency<'a>,
pub source_account: Cow<'a, str>,
pub subcommand: PathFindSubcommand,
pub paths: Option<Vec<Path<'a>>>,
pub send_max: Option<Currency<'a>>,
}
impl<'a> Model for PathFind<'a> {}
impl<'a> Request<'a> for PathFind<'a> {
fn get_common_fields(&self) -> &CommonFields<'a> {
&self.common_fields
}
fn get_common_fields_mut(&mut self) -> &mut CommonFields<'a> {
&mut self.common_fields
}
}
impl<'a> PathFind<'a> {
pub fn new(
id: Option<Cow<'a, str>>,
destination_account: Cow<'a, str>,
destination_amount: Currency<'a>,
source_account: Cow<'a, str>,
subcommand: PathFindSubcommand,
paths: Option<Vec<Vec<PathStep<'a>>>>,
send_max: Option<Currency<'a>>,
) -> Self {
Self {
common_fields: CommonFields {
command: RequestMethod::PathFind,
id,
},
subcommand,
source_account,
destination_account,
destination_amount,
send_max,
paths,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::currency::XRP;
#[test]
fn test_serde_round_trip() {
let req = PathFind::new(
Some("pf-1".into()),
"rDest11111111111111111111111111111".into(),
Currency::XRP(XRP::new()),
"rSrc111111111111111111111111111111".into(),
PathFindSubcommand::Create,
None,
Some(Currency::XRP(XRP::new())),
);
let serialized = serde_json::to_string(&req).unwrap();
let deserialized: PathFind = serde_json::from_str(&serialized).unwrap();
assert_eq!(req, deserialized);
assert!(serialized.contains("\"command\":\"path_find\""));
assert!(serialized.contains("\"subcommand\":\"create\""));
}
#[test]
fn test_subcommand_default() {
assert_eq!(PathFindSubcommand::default(), PathFindSubcommand::Create);
}
}