use std::{ collections::{BTreeMap, BTreeSet}, time::Duration, }; use fader_core::{ ApplicationId, ApplicationMatcher, ApplicationSelector as DomainSelector, FaderId, GroupId, MetadataField, MidiChannel, MidiData, ProfileId, SurfaceId, }; use serde::{Deserialize, Serialize}; use crate::{ConfigError, SCHEMA_VERSION}; const DEFAULT_POLL_INTERVAL_MS: u64 = 10; const MIN_POLL_INTERVAL_MS: u64 = 1; const MAX_POLL_INTERVAL_MS: u64 = 100; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct RuntimeSettings { #[serde(default = "default_poll_interval_ms")] poll_interval_ms: u64, } impl Default for RuntimeSettings { fn default() -> Self { Self { poll_interval_ms: DEFAULT_POLL_INTERVAL_MS, } } } const fn default_poll_interval_ms() -> u64 { DEFAULT_POLL_INTERVAL_MS } /// Behavior when a profile becomes active. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum StartupPolicy { /// Observe live audio without issuing writes. Adopt, /// Deliberately apply saved desired object state after discovery. Restore, } /// Behavior when a new stream joins a configured application. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum NewStreamPolicy { /// Preserve the stream's live state. Adopt, /// Apply a saved desired value when one exists. Restore, } /// Audio adapter selection value. #[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] #[serde(rename_all = "kebab-case")] pub enum Adapter { Auto, Pulse, Pipewire, } /// Validated audio selection and write ceiling. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Audio { adapter: Adapter, #[serde(default)] preference: Vec, max_gain: f64, } /// A validated virtual application. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Application { id: String, label: String, selectors: Vec, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Selector { field: SelectorField, #[serde(skip_serializing_if = "Option::is_none")] exact: Option, #[serde(skip_serializing_if = "Option::is_none")] regex: Option, } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] pub enum SelectorField { #[serde(rename = "application.name")] ApplicationName, #[serde(rename = "application.id")] ApplicationId, #[serde(rename = "application.process.binary")] ProcessBinary, #[serde(rename = "media.name")] MediaName, } impl SelectorField { pub(crate) const fn as_str(self) -> &'static str { match self { Self::ApplicationName => "application.name", Self::ApplicationId => "application.id", Self::ProcessBinary => "application.process.binary", Self::MediaName => "media.name", } } } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] enum VolumeMode { Absolute, Relative, } /// A validated non-nesting application group. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Group { id: String, label: String, members: Vec, volume_mode: VolumeMode, } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] enum IdentityPolicy { RequireUnique, Manual, } /// A configured physical control surface. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Surface { id: String, label: String, input_port: String, #[serde(skip_serializing_if = "Option::is_none")] output_port: Option, #[serde(default, skip_serializing_if = "Option::is_none")] usb_vendor_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] usb_product_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] usb_serial: Option, #[serde(default, skip_serializing_if = "Option::is_none")] usb_path: Option, #[serde(default, skip_serializing_if = "Option::is_none")] manual_backend_id: Option, identity_policy: IdentityPolicy, motorized: bool, } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum TargetKind { Application, Group, Output, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Target { kind: TargetKind, id: String, } /// A logical fader targeting one application, group, or audio output. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Fader { id: String, target: Target, pickup: bool, pickup_tolerance: f64, } /// Vertical presentation density for one mixer fader. #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum FaderDensity { Slim, #[default] Standard, Thick, } /// One durable entry in the user-arranged mixer presentation. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum MixerLayoutEntry { /// A logical fader, optionally retained in place while hidden. Fader { fader: String, #[serde(default, skip_serializing_if = "std::ops::Not::not")] hidden: bool, #[serde(default, skip_serializing_if = "is_standard_density")] density: FaderDensity, }, /// A presentation-only named divider. Separator { id: String, label: String }, } fn is_standard_density(density: &FaderDensity) -> bool { *density == FaderDensity::Standard } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum Action { Volume, ToggleMute, } #[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] #[serde(rename_all = "snake_case")] pub enum MessageKind { Cc, Note, } #[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] #[serde(deny_unknown_fields)] struct Message { kind: MessageKind, channel: u16, number: u16, } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] enum Edge { Press, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Feedback { kind: MessageKind, channel: u16, number: u16, on: u16, off: u16, } /// A validated physical-message-to-logical-fader binding. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct Binding { surface: String, fader: String, action: Action, #[serde(skip_serializing_if = "Option::is_none")] edge: Option, message: Message, #[serde(skip_serializing_if = "Option::is_none")] feedback: Option, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct RawProfile { schema_version: u16, id: String, startup: StartupPolicy, new_stream: NewStreamPolicy, #[serde(default)] runtime: RuntimeSettings, audio: Audio, #[serde(default)] applications: Vec, #[serde(default)] groups: Vec, #[serde(default)] surfaces: Vec, #[serde(default)] faders: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] mixer_layout: Vec, #[serde(default)] bindings: Vec, } /// A complete, semantically validated runtime profile document. #[derive(Clone, Debug, PartialEq)] pub struct Profile { raw: RawProfile, id: ProfileId, mixer_layout: Vec, } impl Profile { /// Parses strict TOML and validates all cross-document invariants. pub fn parse(input: &str) -> Result { let raw: RawProfile = toml::from_str(input)?; validate_version(raw.schema_version)?; let id = parse_id::(&raw.id, "profile.id")?; validate_runtime(&raw.runtime)?; validate_audio(&raw.audio)?; validate_profile_members(&raw)?; let mixer_layout = effective_mixer_layout(&raw); Ok(Self { raw, id, mixer_layout, }) } /// Serializes a canonical representation of this validated profile. pub fn to_toml(&self) -> Result { Ok(toml::to_string_pretty(&self.raw)?) } /// Stable profile identifier. pub fn id(&self) -> &ProfileId { &self.id } /// Startup state policy. pub const fn startup(&self) -> StartupPolicy { self.raw.startup } /// Policy for streams first observed after profile activation. #[must_use] pub const fn new_stream(&self) -> NewStreamPolicy { self.raw.new_stream } /// Validated audio adapter selection and preference order. pub const fn audio(&self) -> &Audio { &self.raw.audio } /// Applications in declared order. pub fn applications(&self) -> &[Application] { &self.raw.applications } /// Groups in declared restore-conflict order. pub fn groups(&self) -> &[Group] { &self.raw.groups } /// Configured MIDI surfaces in declared order. pub fn surfaces(&self) -> &[Surface] { &self.raw.surfaces } pub fn faders(&self) -> &[Fader] { &self.raw.faders } /// Ordered effective mixer presentation, including synthesized legacy entries. pub fn mixer_layout(&self) -> &[MixerLayoutEntry] { &self.mixer_layout } /// Validated bindings. pub fn bindings(&self) -> &[Binding] { &self.raw.bindings } /// Maximum configured gain for outbound writes and restored intents. pub fn max_gain(&self) -> f64 { self.raw.audio.max_gain } /// Interval used by the server and native audio worker while waiting for /// MIDI, IPC, adapter commands, and subscription notifications. #[must_use] pub const fn poll_interval(&self) -> Duration { Duration::from_millis(self.raw.runtime.poll_interval_ms) } } impl Audio { /// Configured automatic or manual adapter choice. #[must_use] pub const fn adapter(&self) -> Adapter { self.adapter } /// Concrete automatic-probe order; an empty list uses runtime defaults. #[must_use] pub fn preference(&self) -> &[Adapter] { &self.preference } /// Maximum configured gain for outbound writes. #[must_use] pub const fn max_gain(&self) -> f64 { self.max_gain } } impl Application { /// Stable application identifier from the validated profile. #[must_use] pub fn id(&self) -> &str { &self.id } /// User-facing application label. #[must_use] pub fn label(&self) -> &str { &self.label } /// Ordered capture selectors used by this virtual application. #[must_use] pub fn selectors(&self) -> &[Selector] { &self.selectors } /// Compiles this validated application's selectors for live stream matching. pub fn matcher(&self) -> Result { let id = parse_id::(&self.id, "application.id")?; let selectors = self .selectors .iter() .map(Selector::compile) .collect::, _>>()?; ApplicationMatcher::new(id, selectors) .map_err(|error| ConfigError::validation("application.selectors", error.to_string())) } } impl Selector { /// Normalized metadata field tested by this selector. #[must_use] pub const fn field(&self) -> SelectorField { self.field } /// Exact or regex source pattern and whether regex mode is active. #[must_use] pub fn pattern(&self) -> (&str, bool) { match (&self.exact, &self.regex) { (Some(pattern), None) => (pattern, false), (None, Some(pattern)) => (pattern, true), _ => ("", false), } } fn compile(&self) -> Result { let field = match self.field { SelectorField::ApplicationName => MetadataField::ApplicationName, SelectorField::ApplicationId => MetadataField::ApplicationId, SelectorField::ProcessBinary => MetadataField::ProcessBinary, SelectorField::MediaName => MetadataField::MediaName, }; match (&self.exact, &self.regex) { (Some(pattern), None) => DomainSelector::exact(field, pattern), (None, Some(pattern)) => DomainSelector::regex(field, pattern), _ => { return Err(ConfigError::validation( "application.selector", "exactly one of exact or regex is required", )); } } .map_err(|error| ConfigError::validation("application.selector", error.to_string())) } } impl Group { /// Stable group identifier from the validated profile. #[must_use] pub fn id(&self) -> &str { &self.id } /// User-facing group label. #[must_use] pub fn label(&self) -> &str { &self.label } /// Stable application IDs included in this group. #[must_use] pub fn members(&self) -> &[String] { &self.members } /// Group gain semantics used when planning writes. #[must_use] pub const fn volume_mode(&self) -> fader_core::VolumeMode { match self.volume_mode { VolumeMode::Absolute => fader_core::VolumeMode::Absolute, VolumeMode::Relative => fader_core::VolumeMode::Relative, } } } impl Surface { /// Stable user-assigned surface identifier. #[must_use] pub fn id(&self) -> &str { &self.id } /// User-facing surface label. #[must_use] pub fn label(&self) -> &str { &self.label } /// Stable portion of the expected MIDI input-port name. #[must_use] pub fn input_port(&self) -> &str { &self.input_port } /// Optional independently assigned output-port name. #[must_use] pub fn output_port(&self) -> Option<&str> { self.output_port.as_deref() } #[must_use] pub fn usb_vendor_id(&self) -> Option<&str> { self.usb_vendor_id.as_deref() } #[must_use] pub fn usb_product_id(&self) -> Option<&str> { self.usb_product_id.as_deref() } #[must_use] pub fn usb_serial(&self) -> Option<&str> { self.usb_serial.as_deref() } #[must_use] pub fn usb_path(&self) -> Option<&str> { self.usb_path.as_deref() } /// Explicit current backend selection used only to resolve ambiguity. #[must_use] pub fn manual_backend_id(&self) -> Option<&str> { self.manual_backend_id.as_deref() } } impl Fader { pub fn id(&self) -> &str { &self.id } pub const fn target_kind(&self) -> TargetKind { self.target.kind } pub fn target_id(&self) -> &str { &self.target.id } pub const fn pickup(&self) -> bool { self.pickup } pub const fn pickup_tolerance(&self) -> f64 { self.pickup_tolerance } } impl Binding { pub fn surface(&self) -> &str { &self.surface } pub fn fader(&self) -> &str { &self.fader } pub const fn action(&self) -> Action { self.action } pub const fn message_kind(&self) -> MessageKind { self.message.kind } pub const fn channel(&self) -> u16 { self.message.channel } pub const fn number(&self) -> u16 { self.message.number } } fn validate_version(version: u16) -> Result<(), ConfigError> { if version == SCHEMA_VERSION { Ok(()) } else { Err(ConfigError::validation( "schema_version", format!("unsupported version {version}; expected {SCHEMA_VERSION}"), )) } } fn validate_runtime(runtime: &RuntimeSettings) -> Result<(), ConfigError> { if (MIN_POLL_INTERVAL_MS..=MAX_POLL_INTERVAL_MS).contains(&runtime.poll_interval_ms) { Ok(()) } else { Err(ConfigError::validation( "runtime.poll_interval_ms", format!("must be within {MIN_POLL_INTERVAL_MS}..={MAX_POLL_INTERVAL_MS}"), )) } } fn validate_audio(audio: &Audio) -> Result<(), ConfigError> { if !audio.max_gain.is_finite() || audio.max_gain < 0.0 { return Err(ConfigError::validation( "audio.max_gain", "must be finite and non-negative", )); } let mut seen = BTreeSet::new(); for (index, adapter) in audio.preference.iter().enumerate() { if *adapter == Adapter::Auto { return Err(ConfigError::validation( format!("audio.preference[{index}]"), "auto is a selection policy, not a concrete adapter", )); } if !seen.insert(adapter) { return Err(ConfigError::validation( format!("audio.preference[{index}]"), "duplicate adapter", )); } } Ok(()) } fn validate_profile_members(raw: &RawProfile) -> Result<(), ConfigError> { let applications = unique_ids::( raw.applications.iter().map(|item| item.id.as_str()), "applications", )?; for (index, application) in raw.applications.iter().enumerate() { if application.selectors.is_empty() { return Err(ConfigError::validation( format!("applications[{index}].selectors"), "at least one selector is required", )); } for (selector_index, selector) in application.selectors.iter().enumerate() { validate_selector(selector, index, selector_index)?; } } let groups = unique_ids::(raw.groups.iter().map(|item| item.id.as_str()), "groups")?; for (index, group) in raw.groups.iter().enumerate() { if group.volume_mode == VolumeMode::Relative { return Err(ConfigError::validation( format!("groups[{index}].volume_mode"), "relative groups are reserved for a future stateful runtime; use absolute", )); } let mut members = BTreeSet::new(); for (member_index, member) in group.members.iter().enumerate() { let member_id = parse_id::( member, &format!("groups[{index}].members[{member_index}]"), )?; if !applications.contains_key(member_id.as_str()) { return Err(ConfigError::validation( format!("groups[{index}].members[{member_index}]"), format!("unknown application {member:?}"), )); } if !members.insert(member) { return Err(ConfigError::validation( format!("groups[{index}].members[{member_index}]"), "duplicate member", )); } } } let surfaces = unique_ids::(raw.surfaces.iter().map(|item| item.id.as_str()), "surfaces")?; for (index, surface) in raw.surfaces.iter().enumerate() { if surface.input_port.is_empty() { return Err(ConfigError::validation( format!("surfaces[{index}].input_port"), "must not be empty", )); } if surface.motorized && surface.output_port.is_none() { return Err(ConfigError::validation( format!("surfaces[{index}].output_port"), "a motorized surface requires an output port", )); } match (&surface.usb_vendor_id, &surface.usb_product_id) { (Some(vendor), Some(product)) => { validate_usb_id(vendor, &format!("surfaces[{index}].usb_vendor_id"))?; validate_usb_id(product, &format!("surfaces[{index}].usb_product_id"))?; } (None, None) => {} _ => { return Err(ConfigError::validation( format!("surfaces[{index}].usb_vendor_id"), "USB vendor_id and product_id must be provided together", )); } } for (field, value) in [ ("usb_serial", surface.usb_serial.as_deref()), ("usb_path", surface.usb_path.as_deref()), ("manual_backend_id", surface.manual_backend_id.as_deref()), ] { if value.is_some_and(str::is_empty) { return Err(ConfigError::validation( format!("surfaces[{index}].{field}"), "must not be empty", )); } } } let faders = unique_ids::(raw.faders.iter().map(|item| item.id.as_str()), "faders")?; for (index, fader) in raw.faders.iter().enumerate() { if !fader.pickup_tolerance.is_finite() || !(0.0..=1.0).contains(&fader.pickup_tolerance) { return Err(ConfigError::validation( format!("faders[{index}].pickup_tolerance"), "must be finite and within 0..=1", )); } let found = match fader.target.kind { TargetKind::Application => applications.contains_key(&fader.target.id), TargetKind::Group => groups.contains_key(&fader.target.id), TargetKind::Output => fader.target.id == "default", }; if !found { return Err(ConfigError::validation( format!("faders[{index}].target.id"), format!("unknown {:?} {:?}", fader.target.kind, fader.target.id), )); } } validate_mixer_layout(raw, &faders)?; validate_bindings(raw, &surfaces, &faders) } fn validate_mixer_layout( raw: &RawProfile, faders: &BTreeMap, ) -> Result<(), ConfigError> { let mut ids = BTreeSet::new(); let mut referenced_faders = BTreeSet::new(); for (index, entry) in raw.mixer_layout.iter().enumerate() { let (id, is_fader) = match entry { MixerLayoutEntry::Fader { fader, .. } => { parse_id::(fader, &format!("mixer_layout[{index}].fader"))?; if !faders.contains_key(fader) { return Err(ConfigError::validation( format!("mixer_layout[{index}].fader"), format!("unknown fader {fader:?}"), )); } if !referenced_faders.insert(fader.as_str()) { return Err(ConfigError::validation( format!("mixer_layout[{index}].fader"), "duplicate fader", )); } (fader, true) } MixerLayoutEntry::Separator { id, label } => { parse_id::(id, &format!("mixer_layout[{index}].id"))?; if label.trim().is_empty() { return Err(ConfigError::validation( format!("mixer_layout[{index}].label"), "must not be empty", )); } (id, false) } }; if !ids.insert(id.as_str()) { let kind = if is_fader { "fader" } else { "separator" }; return Err(ConfigError::validation( format!("mixer_layout[{index}]"), format!("duplicate layout id for {kind} {id:?}"), )); } } Ok(()) } fn effective_mixer_layout(raw: &RawProfile) -> Vec { let mut layout = raw.mixer_layout.clone(); let referenced = layout .iter() .filter_map(|entry| match entry { MixerLayoutEntry::Fader { fader, .. } => Some(fader.clone()), MixerLayoutEntry::Separator { .. } => None, }) .collect::>(); layout.extend( raw.faders .iter() .filter(|fader| !referenced.contains(&fader.id)) .map(|fader| MixerLayoutEntry::Fader { fader: fader.id.clone(), hidden: false, density: FaderDensity::Standard, }), ); layout } fn validate_usb_id(value: &str, path: &str) -> Result<(), ConfigError> { if value.len() == 4 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) { Ok(()) } else { Err(ConfigError::validation( path, "must contain exactly four hexadecimal digits", )) } } fn validate_selector( selector: &Selector, application: usize, index: usize, ) -> Result<(), ConfigError> { let path = format!("applications[{application}].selectors[{index}]"); let field = match selector.field { SelectorField::ApplicationName => MetadataField::ApplicationName, SelectorField::ApplicationId => MetadataField::ApplicationId, SelectorField::ProcessBinary => MetadataField::ProcessBinary, SelectorField::MediaName => MetadataField::MediaName, }; match (&selector.exact, &selector.regex) { (Some(pattern), None) => DomainSelector::exact(field, pattern) .map(|_| ()) .map_err(|error| ConfigError::validation(format!("{path}.exact"), error.to_string())), (None, Some(pattern)) => DomainSelector::regex(field, pattern) .map(|_| ()) .map_err(|error| ConfigError::validation(format!("{path}.regex"), error.to_string())), _ => Err(ConfigError::validation( path, "exactly one of exact or regex is required", )), } } fn validate_bindings( raw: &RawProfile, surfaces: &BTreeMap, faders: &BTreeMap, ) -> Result<(), ConfigError> { let mut physical = BTreeSet::new(); for (index, binding) in raw.bindings.iter().enumerate() { if !surfaces.contains_key(&binding.surface) { return Err(ConfigError::validation( format!("bindings[{index}].surface"), format!("unknown surface {:?}", binding.surface), )); } if !faders.contains_key(&binding.fader) { return Err(ConfigError::validation( format!("bindings[{index}].fader"), format!("unknown fader {:?}", binding.fader), )); } validate_message(&binding.message, &format!("bindings[{index}].message"))?; let key = (&binding.surface, binding.message.clone()); if !physical.insert(key) { return Err(ConfigError::validation( format!("bindings[{index}].message"), "duplicate physical binding for this surface", )); } match (binding.action, binding.message.kind, binding.edge) { (Action::Volume, MessageKind::Cc, None) => {} (Action::Volume, _, _) => { return Err(ConfigError::validation( format!("bindings[{index}].action"), "volume requires a cc message and no edge", )); } (Action::ToggleMute, _, Some(Edge::Press)) => {} (Action::ToggleMute, _, None) => { return Err(ConfigError::validation( format!("bindings[{index}].edge"), "toggle_mute requires edge = press", )); } } if let Some(feedback) = &binding.feedback { let surface = raw .surfaces .iter() .find(|surface| surface.id == binding.surface) .expect("validated surface lookup is consistent"); if surface.output_port.is_none() { return Err(ConfigError::validation( format!("bindings[{index}].feedback"), "surface output_port is required for feedback", )); } validate_feedback(feedback, &format!("bindings[{index}].feedback"))?; } } Ok(()) } fn validate_message(message: &Message, path: &str) -> Result<(), ConfigError> { MidiChannel::new(message.channel) .map_err(|error| ConfigError::validation(format!("{path}.channel"), error.to_string()))?; MidiData::new(message.number) .map_err(|error| ConfigError::validation(format!("{path}.number"), error.to_string()))?; Ok(()) } fn validate_feedback(feedback: &Feedback, path: &str) -> Result<(), ConfigError> { validate_message( &Message { kind: feedback.kind, channel: feedback.channel, number: feedback.number, }, path, )?; MidiData::new(feedback.on) .map_err(|error| ConfigError::validation(format!("{path}.on"), error.to_string()))?; MidiData::new(feedback.off) .map_err(|error| ConfigError::validation(format!("{path}.off"), error.to_string()))?; Ok(()) } fn unique_ids(values: I, collection: &str) -> Result, ConfigError> where T: std::str::FromStr, T::Err: std::fmt::Display, I: IntoIterator, I::Item: AsRef, { let mut result = BTreeMap::new(); for (index, value) in values.into_iter().enumerate() { let value = value.as_ref(); let id = parse_id::(value, &format!("{collection}[{index}].id"))?; if result.insert(value.to_owned(), id).is_some() { return Err(ConfigError::validation( format!("{collection}[{index}].id"), format!("duplicate ID {value:?}"), )); } } Ok(result) } pub(crate) fn parse_id(value: &str, path: &str) -> Result where T: std::str::FromStr, T::Err: std::fmt::Display, { value .parse() .map_err(|error: T::Err| ConfigError::validation(path, error.to_string())) }