Skip to main content

maplike/
one.rs

1// SPDX-FileCopyrightText: 2026 maplike contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! `One`, a collection that holds always exactly one element.
6
7use crate::containers::Container;
8use crate::iter::IntoIter;
9use crate::ops::{Assign, Get, Len, Modify, Put, Set, WithOne};
10
11/// A collection that holds exactly one element.
12#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
13pub struct One<V> {
14    value: V,
15}
16
17impl<V> One<V> {
18    /// Create a new always-single-valued collection.
19    pub fn new(value: V) -> Self {
20        Self { value }
21    }
22}
23
24impl<V> Container for One<V> {
25    type Key = usize;
26    type Value = V;
27}
28
29impl<V> WithOne<V> for One<V> {
30    #[inline(always)]
31    fn with_one(value: V) -> Self {
32        Self { value }
33    }
34}
35
36impl<V> Assign for One<V> {
37    #[inline(always)]
38    fn assign(&mut self, value: Self) {
39        *self = value;
40    }
41}
42
43impl<V> Get<usize> for One<V> {
44    #[inline(always)]
45    fn get(&self, index: &usize) -> Option<&V> {
46        if *index == 0 { Some(&self.value) } else { None }
47    }
48}
49
50impl<V> Set<usize> for One<V> {
51    type Output = Option<V>;
52
53    #[inline(always)]
54    fn set(&mut self, index: usize, value: V) -> Option<V> {
55        assert_eq!(index, 0);
56        Some(core::mem::replace(&mut self.value, value))
57    }
58}
59
60impl<V> Modify<usize> for One<V> {
61    #[inline(always)]
62    fn modify<F>(&mut self, index: &usize, f: F)
63    where
64        F: FnOnce(&mut V),
65    {
66        assert_eq!(*index, 0);
67        f(&mut self.value)
68    }
69}
70
71// No implementation of `Remove` because there is always exactly one element.
72// Removing an element would violate this invariant property.
73
74impl<V> Put<V> for One<V> {
75    #[inline(always)]
76    fn put(&mut self, value: V) -> Option<V> {
77        Some(core::mem::replace(&mut self.value, value))
78    }
79}
80
81// No implementation of `Clear` for the same reason as `Remove`.
82
83impl<V> Len for One<V> {
84    #[inline(always)]
85    fn len(&self) -> usize {
86        1
87    }
88}
89
90impl<V> IntoIter<usize> for One<V> {
91    type IntoIter = core::iter::Enumerate<core::iter::Once<V>>;
92
93    #[inline(always)]
94    fn into_iter(self) -> Self::IntoIter {
95        core::iter::once(self.value).enumerate()
96    }
97}