Skip to main content

jevrs_core/
options.rs

1use alloc::{string::String, vec::Vec};
2use core::{
3    fmt,
4    marker::PhantomData,
5    ops::{Index, IndexMut},
6};
7
8use crate::Error;
9
10pub(crate) const OPTIONS_TOO_FEW: &str = "options must contain at least one entry";
11pub(crate) const OPTIONS_TOO_MANY: &str = "options must contain at most 255 entries";
12pub(crate) const OPTION_KEY_EMPTY: &str = "option keys must not be empty";
13pub(crate) const OPTION_KEY_DUPLICATE: &str = "option keys must be unique";
14pub(crate) const LEVELS_TOO_FEW: &str = "levels must contain at least two entries";
15pub(crate) const LEVELS_TOO_MANY: &str = "levels must contain at most 10 entries";
16
17/// A finite set whose values have a dense canonical order.
18///
19/// Implement this shared contract when implementing [`Options`] or [`Levels`]
20/// by hand. Derives implement it automatically. Each value in
21/// [`Indexed::all`] must occupy the position returned by [`Indexed::index`].
22pub trait Indexed: Copy + Eq + Send + Sync + 'static {
23    /// Returns every value in the order used for maps and wire criteria.
24    fn all() -> &'static [Self];
25
26    /// Returns this value's position for indexing its associated map.
27    fn index(self) -> usize;
28}
29
30/// A statically defined set of named choices.
31///
32/// Most applications use the `Options` derive re-exported by `jevrs`.
33/// Implement this trait by hand when generated choice sets are not suitable.
34/// The order returned by [`Indexed::all`] defines their indexes and wire order.
35///
36/// ```
37/// use jevrs_core::{ArrayMap, Indexed, Options};
38///
39/// #[derive(Clone, Copy, Eq, PartialEq)]
40/// enum Department { Billing, Technical, Sales }
41///
42/// impl Indexed for Department {
43///     fn all() -> &'static [Self] {
44///         &[Self::Billing, Self::Technical, Self::Sales]
45///     }
46///     fn index(self) -> usize { self as usize }
47/// }
48///
49/// impl Options for Department {
50///     const N: usize = 3;
51///     type Map<T: Send + Sync + 'static> = ArrayMap<Self, T, 3>;
52///     fn key(self) -> &'static str {
53///         match self {
54///             Self::Billing => "billing",
55///             Self::Technical => "technical",
56///             Self::Sales => "sales",
57///         }
58///     }
59///     fn description(self) -> Option<&'static str> { None }
60///     fn from_key(key: &str) -> Option<Self> {
61///         Self::all().iter().copied().find(|option| option.key() == key)
62///     }
63///     fn map_from_fn<T: Send + Sync + 'static>(f: impl FnMut(Self) -> T) -> Self::Map<T> {
64///         let mut f = f;
65///         ArrayMap::new([f(Self::Billing), f(Self::Technical), f(Self::Sales)])
66///     }
67/// }
68/// ```
69pub trait Options: Indexed {
70    /// Declares the choice count so invalid derived or manual sets fail early.
71    const N: usize;
72
73    /// Forces a compile-time check of the API's 1-to-255 choice limit.
74    #[doc(hidden)]
75    const COUNT_OK: () = assert!(Self::N >= 1 && Self::N <= 255);
76
77    /// Selects dense storage for one value per choice.
78    type Map<T: Send + Sync + 'static>: Index<Self, Output = T>
79        + IndexMut<Self>
80        + Send
81        + Sync
82        + 'static;
83
84    /// Returns the stable wire key used in criteria and response probabilities.
85    fn key(self) -> &'static str;
86
87    /// Returns guidance for the model, or `None` when the key is sufficient.
88    fn description(self) -> Option<&'static str>;
89
90    /// Converts the model's selected wire key back into the enum.
91    fn from_key(key: &str) -> Option<Self>;
92
93    /// Builds the associated map when decoding one value per choice.
94    fn map_from_fn<T: Send + Sync + 'static>(f: impl FnMut(Self) -> T) -> Self::Map<T>;
95}
96
97/// A statically defined ordered scoring scale.
98///
99/// Most applications use the `Levels` derive re-exported by `jevrs`.
100/// Implement this trait by hand when generated scoring scales are not suitable.
101/// Use [`DynLevels`] when a scale comes from configuration or a database.
102pub trait Levels: Indexed + Ord {
103    /// Declares the scale length so invalid sets fail early.
104    const N: usize;
105
106    /// Forces a compile-time check of the API's 2-to-10 level limit.
107    #[doc(hidden)]
108    const COUNT_OK: () = assert!(Self::N >= 2 && Self::N <= 10);
109
110    /// Selects dense storage for one value per level.
111    type Map<T: Send + Sync + 'static>: Index<Self, Output = T>
112        + IndexMut<Self>
113        + Send
114        + Sync
115        + 'static;
116
117    /// Returns the model guidance sent for this level.
118    fn description(self) -> &'static str;
119
120    /// Converts a zero-based wire index back into the level enum.
121    fn from_index(index: usize) -> Option<Self>;
122
123    /// Builds the associated map when decoding one value per level.
124    fn map_from_fn<T: Send + Sync + 'static>(f: impl FnMut(Self) -> T) -> Self::Map<T>;
125}
126
127/// A runtime-defined set of named choices.
128///
129/// [`Questions::choice_dyn`](crate::Questions::choice_dyn) validates raw items
130/// and fills the question ID in [`Error::InvalidCriteria`]. Use this type to
131/// validate once up front and reuse configured criteria across batches; use
132/// [`Options`] for static criteria and [`crate::ChoiceAnswer`] for its typed
133/// result.
134#[derive(Clone, Debug, PartialEq)]
135pub struct DynOptions {
136    keys: Vec<String>,
137    descriptions: Vec<Option<String>>,
138}
139
140impl DynOptions {
141    /// Validates runtime choices before they reach a request builder.
142    ///
143    /// ```
144    /// use jevrs_core::DynOptions;
145    ///
146    /// let options = DynOptions::new([
147    ///     ("billing", Some("Payments and refunds")),
148    ///     ("sales", None),
149    /// ])?;
150    /// assert_eq!(options.index_of("sales"), Some(1));
151    /// # Ok::<(), jevrs_core::Error>(())
152    /// ```
153    ///
154    /// # Errors
155    ///
156    /// Returns [`Error::InvalidCriteria`] when there are no options, there are
157    /// more than 255, or a key is empty or duplicated.
158    pub fn new<K, D, I>(options: I) -> Result<Self, Error>
159    where
160        K: Into<String>,
161        D: Into<String>,
162        I: IntoIterator<Item = (K, Option<D>)>,
163    {
164        let mut keys = Vec::new();
165        let mut descriptions = Vec::new();
166        for (key, description) in options {
167            let key = key.into();
168            if key.is_empty() {
169                return Err(invalid_criteria(OPTION_KEY_EMPTY));
170            }
171            if keys.iter().any(|existing| existing == &key) {
172                return Err(invalid_criteria(OPTION_KEY_DUPLICATE));
173            }
174            if keys.len() == 255 {
175                return Err(invalid_criteria(OPTIONS_TOO_MANY));
176            }
177            keys.push(key);
178            descriptions.push(description.map(Into::into));
179        }
180        if keys.is_empty() {
181            return Err(invalid_criteria(OPTIONS_TOO_FEW));
182        }
183        Ok(Self { keys, descriptions })
184    }
185
186    /// Returns option keys in wire order for display or configuration checks.
187    #[must_use]
188    pub fn keys(&self) -> &[String] {
189        &self.keys
190    }
191
192    /// Looks up model guidance when inspecting configured criteria.
193    #[must_use]
194    pub fn description(&self, key: &str) -> Option<&str> {
195        self.index_of(key)
196            .and_then(|index| self.descriptions[index].as_deref())
197    }
198
199    /// Finds a key's position when aligning external data with this set.
200    #[must_use]
201    pub fn index_of(&self, key: &str) -> Option<usize> {
202        self.keys.iter().position(|candidate| candidate == key)
203    }
204
205    /// Returns the count when reporting or validating configured criteria.
206    #[must_use]
207    pub fn len(&self) -> usize {
208        self.keys.len()
209    }
210
211    /// Reports whether the set has no options.
212    ///
213    /// A successfully constructed set is never empty.
214    #[must_use]
215    pub fn is_empty(&self) -> bool {
216        self.keys.is_empty()
217    }
218}
219
220impl IntoIterator for DynOptions {
221    type Item = (String, Option<String>);
222    type IntoIter =
223        core::iter::Zip<alloc::vec::IntoIter<String>, alloc::vec::IntoIter<Option<String>>>;
224
225    fn into_iter(self) -> Self::IntoIter {
226        self.keys.into_iter().zip(self.descriptions)
227    }
228}
229
230/// A runtime-defined ordered scoring scale.
231///
232/// [`Questions::score_dyn`](crate::Questions::score_dyn) validates raw items and
233/// fills the question ID in [`Error::InvalidCriteria`]. Use this type to
234/// validate once up front and reuse configured criteria across batches; use
235/// [`Levels`] for a static scale and [`crate::ScoreAnswer`] for its typed result.
236#[derive(Clone, Debug, PartialEq)]
237pub struct DynLevels(Vec<String>);
238
239impl DynLevels {
240    /// Validates a runtime scale while preserving ascending score order.
241    ///
242    /// ```
243    /// use jevrs_core::DynLevels;
244    ///
245    /// let levels = DynLevels::new(["Calm", "Frustrated", "Very angry"])?;
246    /// assert_eq!(levels.levels()[1], "Frustrated");
247    /// # Ok::<(), jevrs_core::Error>(())
248    /// ```
249    ///
250    /// # Errors
251    ///
252    /// Returns [`Error::InvalidCriteria`] unless the scale contains between
253    /// two and ten levels.
254    pub fn new<S: Into<String>>(levels: impl IntoIterator<Item = S>) -> Result<Self, Error> {
255        let mut levels = levels
256            .into_iter()
257            .map(Into::into)
258            .take(11)
259            .collect::<Vec<_>>();
260        if levels.len() < 2 {
261            return Err(invalid_criteria(LEVELS_TOO_FEW));
262        }
263        if levels.len() > 10 {
264            return Err(invalid_criteria(LEVELS_TOO_MANY));
265        }
266        levels.shrink_to_fit();
267        Ok(Self(levels))
268    }
269
270    /// Returns descriptions when displaying or inspecting the configured scale.
271    #[must_use]
272    pub fn levels(&self) -> &[String] {
273        &self.0
274    }
275
276    /// Returns the count when reporting or validating a configured scale.
277    #[must_use]
278    pub fn len(&self) -> usize {
279        self.0.len()
280    }
281
282    /// Reports whether the scale has no levels.
283    ///
284    /// A successfully constructed scale is never empty.
285    #[must_use]
286    pub fn is_empty(&self) -> bool {
287        self.0.is_empty()
288    }
289}
290
291impl IntoIterator for DynLevels {
292    type Item = String;
293    type IntoIter = alloc::vec::IntoIter<String>;
294
295    fn into_iter(self) -> Self::IntoIter {
296        self.0.into_iter()
297    }
298}
299
300fn invalid_criteria(reason: &'static str) -> Error {
301    Error::InvalidCriteria { id: None, reason }
302}
303
304/// Dense per-key storage for a static [`Options`] or [`Levels`] implementation.
305///
306/// Use this as the `Map` associated type in a manual implementation. Derived
307/// implementations choose it automatically.
308#[derive(Clone, PartialEq)]
309pub struct ArrayMap<K: Indexed, T, const N: usize>([T; N], PhantomData<K>);
310
311impl<K, T, const N: usize> ArrayMap<K, T, N>
312where
313    K: Indexed,
314{
315    /// Creates storage when values are already arranged in [`Indexed`] order.
316    pub const fn new(values: [T; N]) -> Self {
317        Self(values, PhantomData)
318    }
319
320    /// Iterates in schema order when every key needs its decoded value.
321    pub fn iter(&self) -> impl Iterator<Item = (K, &T)> {
322        K::all().iter().copied().zip(self.0.iter())
323    }
324
325    /// Returns the array when a fixed-size consumer no longer needs typed keys.
326    pub fn into_inner(self) -> [T; N] {
327        self.0
328    }
329}
330
331impl<K, T, const N: usize> Index<K> for ArrayMap<K, T, N>
332where
333    K: Indexed,
334{
335    type Output = T;
336
337    fn index(&self, key: K) -> &Self::Output {
338        &self.0[key.index()]
339    }
340}
341
342impl<K, T, const N: usize> IndexMut<K> for ArrayMap<K, T, N>
343where
344    K: Indexed,
345{
346    fn index_mut(&mut self, key: K) -> &mut Self::Output {
347        &mut self.0[key.index()]
348    }
349}
350
351impl<K, T, const N: usize> fmt::Debug for ArrayMap<K, T, N>
352where
353    K: Indexed + fmt::Debug,
354    T: fmt::Debug,
355{
356    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
357        formatter.debug_map().entries(self.iter()).finish()
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use alloc::{
364        string::{String, ToString},
365        vec,
366        vec::Vec,
367    };
368
369    use super::{
370        DynLevels, DynOptions, LEVELS_TOO_FEW, LEVELS_TOO_MANY, OPTION_KEY_DUPLICATE,
371        OPTION_KEY_EMPTY, OPTIONS_TOO_FEW, OPTIONS_TOO_MANY,
372    };
373    use crate::{
374        Error, Indexed, Levels, Options,
375        test_support::{Dept, Frustration},
376    };
377
378    #[test]
379    fn option_lookups_round_trip_and_reject_unknown_keys() {
380        for option in Dept::all() {
381            assert_eq!(Dept::from_key(option.key()), Some(*option));
382            assert_eq!(Dept::all().get(option.index()), Some(option));
383        }
384        assert_eq!(Dept::from_key("support"), None);
385    }
386
387    #[test]
388    fn level_lookups_round_trip_and_reject_unknown_indexes() {
389        for level in Frustration::all() {
390            assert_eq!(Frustration::from_index(level.index()), Some(*level));
391        }
392        assert_eq!(Frustration::from_index(3), None);
393    }
394
395    #[test]
396    fn array_map_indexes_mutates_and_unwraps() {
397        let mut map = Dept::map_from_fn(Dept::index);
398        assert_eq!(map[Dept::Technical], 1);
399        map[Dept::Sales] = 9;
400        assert_eq!(map.into_inner(), [0, 1, 9]);
401    }
402
403    #[test]
404    fn array_map_iterates_in_key_order() {
405        let map = Frustration::map_from_fn(Frustration::description);
406        let entries: alloc::vec::Vec<_> = map.iter().collect();
407        assert_eq!(
408            entries,
409            alloc::vec![
410                (Frustration::Calm, &"Calm"),
411                (Frustration::Frustrated, &"Frustrated"),
412                (Frustration::VeryAngry, &"Very angry"),
413            ]
414        );
415    }
416
417    fn invalid_reason(error: Error) -> &'static str {
418        match error {
419            Error::InvalidCriteria { id: None, reason } => reason,
420            other => panic!("unexpected error: {other}"),
421        }
422    }
423
424    #[test]
425    fn dynamic_options_reject_every_invalid_shape() {
426        let empty: Vec<(String, Option<String>)> = Vec::new();
427        assert_eq!(
428            invalid_reason(DynOptions::new(empty).unwrap_err()),
429            OPTIONS_TOO_FEW
430        );
431        let too_many = (0..256)
432            .map(|index| (index.to_string(), None::<String>))
433            .collect::<Vec<_>>();
434        assert_eq!(
435            invalid_reason(DynOptions::new(too_many).unwrap_err()),
436            OPTIONS_TOO_MANY
437        );
438        assert_eq!(
439            invalid_reason(
440                DynOptions::new([("billing", None::<&str>), ("billing", None)]).unwrap_err()
441            ),
442            OPTION_KEY_DUPLICATE
443        );
444        assert_eq!(
445            invalid_reason(DynOptions::new([(String::new(), None::<String>)]).unwrap_err()),
446            OPTION_KEY_EMPTY
447        );
448    }
449
450    #[test]
451    fn dynamic_options_accept_borrowed_and_owned_strings() {
452        let borrowed =
453            DynOptions::new([("billing", Some("Payments and refunds")), ("sales", None)]).unwrap();
454        assert_eq!(
455            borrowed.description("billing"),
456            Some("Payments and refunds")
457        );
458
459        let owned = DynOptions::new([(
460            "technical".to_string(),
461            Some("Bugs and outages".to_string()),
462        )])
463        .unwrap();
464        assert_eq!(owned.keys(), &["technical"]);
465
466        let entries: Vec<(String, Option<String>)> =
467            vec![("sales".to_string(), Some("New accounts".to_string()))];
468        let from_vec = DynOptions::new(entries).unwrap();
469        assert_eq!(from_vec.description("sales"), Some("New accounts"));
470    }
471
472    #[test]
473    fn dynamic_options_accept_255_entries_and_expose_accessors() {
474        let entries = (0..255)
475            .map(|index| {
476                let key = index.to_string();
477                let description = (index == 1).then(|| "Technical support".to_string());
478                (key, description)
479            })
480            .collect::<Vec<_>>();
481        let options = DynOptions::new(entries).unwrap();
482
483        assert_eq!(options.len(), 255);
484        assert_eq!(options.keys().first().map(String::as_str), Some("0"));
485        assert_eq!(options.keys().last().map(String::as_str), Some("254"));
486        assert_eq!(options.description("1"), Some("Technical support"));
487        assert_eq!(options.description("2"), None);
488        assert_eq!(options.description("missing"), None);
489        assert_eq!(options.index_of("254"), Some(254));
490        assert_eq!(options.index_of("missing"), None);
491    }
492
493    #[test]
494    fn dynamic_levels_validate_bounds_and_expose_accessors() {
495        assert_eq!(
496            invalid_reason(DynLevels::new(["Calm"]).unwrap_err()),
497            LEVELS_TOO_FEW
498        );
499        assert_eq!(
500            invalid_reason(DynLevels::new((0..11).map(|index| index.to_string())).unwrap_err()),
501            LEVELS_TOO_MANY
502        );
503
504        let levels = DynLevels::new((0..10).map(|index| index.to_string())).unwrap();
505        assert_eq!(levels.len(), 10);
506        assert_eq!(levels.levels().first().map(String::as_str), Some("0"));
507        assert_eq!(levels.levels().last().map(String::as_str), Some("9"));
508    }
509
510    #[test]
511    fn dynamic_levels_accept_borrowed_and_owned_strings() {
512        let borrowed = DynLevels::new(["Calm", "Frustrated"]).unwrap();
513        assert_eq!(borrowed.levels(), &["Calm", "Frustrated"]);
514
515        let owned = DynLevels::new(["Calm".to_string(), "Frustrated".to_string()]).unwrap();
516        assert_eq!(owned.levels(), &["Calm", "Frustrated"]);
517    }
518}