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
17pub trait Indexed: Copy + Eq + Send + Sync + 'static {
23 fn all() -> &'static [Self];
25
26 fn index(self) -> usize;
28}
29
30pub trait Options: Indexed {
70 const N: usize;
72
73 #[doc(hidden)]
75 const COUNT_OK: () = assert!(Self::N >= 1 && Self::N <= 255);
76
77 type Map<T: Send + Sync + 'static>: Index<Self, Output = T>
79 + IndexMut<Self>
80 + Send
81 + Sync
82 + 'static;
83
84 fn key(self) -> &'static str;
86
87 fn description(self) -> Option<&'static str>;
89
90 fn from_key(key: &str) -> Option<Self>;
92
93 fn map_from_fn<T: Send + Sync + 'static>(f: impl FnMut(Self) -> T) -> Self::Map<T>;
95}
96
97pub trait Levels: Indexed + Ord {
103 const N: usize;
105
106 #[doc(hidden)]
108 const COUNT_OK: () = assert!(Self::N >= 2 && Self::N <= 10);
109
110 type Map<T: Send + Sync + 'static>: Index<Self, Output = T>
112 + IndexMut<Self>
113 + Send
114 + Sync
115 + 'static;
116
117 fn description(self) -> &'static str;
119
120 fn from_index(index: usize) -> Option<Self>;
122
123 fn map_from_fn<T: Send + Sync + 'static>(f: impl FnMut(Self) -> T) -> Self::Map<T>;
125}
126
127#[derive(Clone, Debug, PartialEq)]
135pub struct DynOptions {
136 keys: Vec<String>,
137 descriptions: Vec<Option<String>>,
138}
139
140impl DynOptions {
141 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 #[must_use]
188 pub fn keys(&self) -> &[String] {
189 &self.keys
190 }
191
192 #[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 #[must_use]
201 pub fn index_of(&self, key: &str) -> Option<usize> {
202 self.keys.iter().position(|candidate| candidate == key)
203 }
204
205 #[must_use]
207 pub fn len(&self) -> usize {
208 self.keys.len()
209 }
210
211 #[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#[derive(Clone, Debug, PartialEq)]
237pub struct DynLevels(Vec<String>);
238
239impl DynLevels {
240 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 #[must_use]
272 pub fn levels(&self) -> &[String] {
273 &self.0
274 }
275
276 #[must_use]
278 pub fn len(&self) -> usize {
279 self.0.len()
280 }
281
282 #[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#[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 pub const fn new(values: [T; N]) -> Self {
317 Self(values, PhantomData)
318 }
319
320 pub fn iter(&self) -> impl Iterator<Item = (K, &T)> {
322 K::all().iter().copied().zip(self.0.iter())
323 }
324
325 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}