Skip to main content

zenpsy_api/
identity.rs

1//! Configured scoring identity and actual implementation provenance.
2//! Hashing, persistence columns and cache keys belong to consumers.
3
4use alloc::borrow::Cow;
5use alloc::string::ToString;
6use alloc::vec::Vec;
7use core::fmt;
8
9/// Where a metric's arithmetic runs.
10#[non_exhaustive]
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum Backend {
13    /// Host CPU (any SIMD tier; tiers must agree bit for bit).
14    Cpu,
15    /// A GPU through the named API (`"cuda"`, `"wgpu"`, `"metal"`).
16    #[non_exhaustive]
17    Gpu {
18        /// The GPU API, lowercase.
19        api: &'static str,
20    },
21}
22
23impl Backend {
24    /// GPU through the named API; device details may be added independently.
25    pub const fn gpu(api: &'static str) -> Self {
26        Self::Gpu { api }
27    }
28}
29
30/// Which code computed a score. Build it with [`crate::implementation!`] so the
31/// crate name and version come from Cargo, not from hand-typed strings.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub struct Implementation {
35    /// The implementing crate (`CARGO_PKG_NAME`).
36    crate_name: &'static str,
37    /// Its version (`CARGO_PKG_VERSION`). Implementation provenance.
38    crate_version: &'static str,
39    /// Output revision. Bump whenever any output can change.
40    score_revision: u32,
41    /// Where it runs.
42    backend: Backend,
43    /// Optional build id (a commit hash), from `ZENMETRICS_BUILD_ID` at
44    /// compile time. Implementation provenance.
45    build: Option<&'static str>,
46}
47
48impl Implementation {
49    /// A CPU implementation with no build id.
50    pub const fn new(
51        crate_name: &'static str,
52        crate_version: &'static str,
53        score_revision: u32,
54    ) -> Self {
55        Self {
56            crate_name,
57            crate_version,
58            score_revision,
59            backend: Backend::Cpu,
60            build: None,
61        }
62    }
63
64    /// Implementing crate name.
65    pub const fn crate_name(&self) -> &'static str {
66        self.crate_name
67    }
68    /// Implementing crate version.
69    pub const fn crate_version(&self) -> &'static str {
70        self.crate_version
71    }
72    /// Output definition revision.
73    pub const fn score_revision(&self) -> u32 {
74        self.score_revision
75    }
76    /// Actual compute backend.
77    pub const fn backend(&self) -> Backend {
78        self.backend
79    }
80    /// Optional implementation build identity.
81    pub const fn build(&self) -> Option<&'static str> {
82        self.build
83    }
84    /// Replace the backend.
85    #[must_use]
86    pub const fn with_backend(mut self, backend: Backend) -> Self {
87        self.backend = backend;
88        self
89    }
90
91    /// Record a build id.
92    #[must_use]
93    pub const fn with_build(mut self, build: Option<&'static str>) -> Self {
94        self.build = build;
95        self
96    }
97}
98
99/// The calling crate's [`Implementation`] at `score_revision`, CPU backend,
100/// with the build id from the `ZENMETRICS_BUILD_ID` environment variable
101/// when it was set at compile time.
102///
103/// ```
104/// let imp = zenpsy_api::implementation!(3);
105/// assert_eq!(imp.crate_name(), "zenpsy-api");
106/// assert_eq!(imp.score_revision(), 3);
107/// ```
108#[macro_export]
109macro_rules! implementation {
110    ($rev:expr) => {
111        $crate::Implementation::new(
112            ::core::env!("CARGO_PKG_NAME"),
113            ::core::env!("CARGO_PKG_VERSION"),
114            $rev,
115        )
116        .with_build(::core::option_env!("ZENMETRICS_BUILD_ID"))
117    };
118}
119
120/// Full identity of one configured metric instance. See the
121/// crate documentation.
122#[derive(Clone, Debug, PartialEq, Eq, Hash)]
123#[non_exhaustive]
124pub struct MetricId {
125    family: &'static str,
126    variant: Option<&'static str>,
127    reference: Cow<'static, str>,
128    implementation: Implementation,
129    config: Vec<(Cow<'static, str>, Cow<'static, str>)>,
130}
131
132impl MetricId {
133    /// `family` (`"fsim"`) as computed by `implementation`.
134    pub fn new(family: &'static str, implementation: Implementation) -> Self {
135        Self {
136            family,
137            variant: None,
138            reference: Cow::Borrowed(""),
139            implementation,
140            config: Vec::new(),
141        }
142    }
143
144    /// Set the variant within the family (`"vifvec"`, `"v3"`).
145    #[must_use]
146    pub fn with_variant(mut self, variant: &'static str) -> Self {
147        self.variant = Some(variant);
148        self
149    }
150
151    /// Name the published reference this implementation reproduces
152    /// (`"pycvvdp 0.5.7"`, `"MATLAB FeatureSIM.m (Zhang 2011)"`).
153    #[must_use]
154    pub fn with_reference(mut self, reference: impl Into<Cow<'static, str>>) -> Self {
155        self.reference = reference.into();
156        self
157    }
158
159    /// Replace the backend.
160    #[must_use]
161    pub fn with_backend(mut self, backend: Backend) -> Self {
162        self.implementation.backend = backend;
163        self
164    }
165
166    /// Record one configuration knob. Values render through `Display`
167    /// (Rust prints floats as their shortest round-trip form, so `0.5`
168    /// stays `0.5`). Setting a key twice keeps the last value. Keys stay
169    /// sorted, so insertion order never changes the fingerprint.
170    #[must_use]
171    pub fn with_config(
172        mut self,
173        key: impl Into<Cow<'static, str>>,
174        value: impl fmt::Display,
175    ) -> Self {
176        let key = key.into();
177        let value: Cow<'static, str> = Cow::Owned(value.to_string());
178        match self
179            .config
180            .binary_search_by(|(k, _)| k.as_ref().cmp(key.as_ref()))
181        {
182            Ok(i) => self.config[i].1 = value,
183            Err(i) => self.config.insert(i, (key, value)),
184        }
185        self
186    }
187
188    /// The metric family.
189    pub fn family(&self) -> &'static str {
190        self.family
191    }
192
193    /// The variant, if any.
194    pub fn variant(&self) -> Option<&'static str> {
195        self.variant
196    }
197
198    /// The reproduced reference (empty when unset).
199    pub fn reference(&self) -> &str {
200        &self.reference
201    }
202
203    /// The implementation.
204    pub fn implementation(&self) -> &Implementation {
205        &self.implementation
206    }
207
208    /// Configuration knobs, sorted by key.
209    pub fn config(&self) -> &[(Cow<'static, str>, Cow<'static, str>)] {
210        &self.config
211    }
212
213    /// One configuration value.
214    pub fn config_value(&self, key: &str) -> Option<&str> {
215        self.config
216            .binary_search_by(|(k, _)| k.as_ref().cmp(key))
217            .ok()
218            .map(|i| self.config[i].1.as_ref())
219    }
220}
221
222impl fmt::Display for MetricId {
223    /// `family[/variant] (crate@version r{rev} {backend})`.
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        f.write_str(self.family)?;
226        if let Some(v) = self.variant {
227            write!(f, "/{v}")?;
228        }
229        let imp = &self.implementation;
230        write!(
231            f,
232            " ({}@{} r{} {:?})",
233            imp.crate_name, imp.crate_version, imp.score_revision, imp.backend
234        )
235    }
236}