simulator_client/recipes.rs
1//! Venue templates for rerouting swaps directly to a venue.
2//!
3//! Load a template file with [`parse_templates`] and pass the result to [`crate::CreateSession`]'s
4//! `reroute_venue_templates`.
5
6use std::collections::HashSet;
7
8use simulator_api::VenueTemplate;
9
10/// The templates a JSON array names, refused if it names none or repeats a label. `source` only
11/// names the input in the error.
12///
13/// Labels are a template's identity on every row the server writes, so it refuses a repeat;
14/// caught here first to save the round trip.
15///
16/// # Errors
17///
18/// A message naming `source` when `raw` does not parse, is empty, or repeats a label.
19pub fn parse_templates(source: &str, raw: &str) -> Result<Vec<VenueTemplate>, String> {
20 let templates: Vec<VenueTemplate> = crate::error::from_json(raw.as_bytes())
21 .map_err(|error| format!("parsing {source}: {error}"))?;
22 if templates.is_empty() {
23 return Err(format!("{source}: names no templates"));
24 }
25 let mut labels = HashSet::new();
26 if let Some(duplicate) = templates
27 .iter()
28 .map(|template| template.label.as_str())
29 .find(|label| !labels.insert(*label))
30 {
31 return Err(format!(
32 "{source}: template label {duplicate:?} appears more than once"
33 ));
34 }
35 Ok(templates)
36}