intid_core/lib.rs
1//! Defines the [`IntegerId`] trait, for types that can be identified by an integer value.
2//!
3//! This contains all the same types that the [`intid`] crate does,
4//! but has no dependency on [`intid_derive`] (even when the `intid/derive` feature is enabled).
5//! This reduces compile times, similar to the separation between `serde_core` and `serde` introduced in [serde-rs/serde#2608].
6//!
7//! It may be convenient to rename the `intid_core` dependency to `intid` using [dependency renaming].
8//! ```toml
9//! intid = { version = "0.3", package = "intid_core" }
10//! ```
11//! This renaming comes at no loss of clarity,
12//! since the items in `intid_core` are simply a subset of the items in the `intid` crate.
13//! If for some reason you decide to use `intid_derive` directly without depending on `intid`,
14//! then you will need to do this renaming since the derived code references the `intid` crate.
15//!
16//! [dependency renaming]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#renaming-dependencies-in-cargotoml
17//! [serde-rs/serde#2608]: https://github.com/serde-rs/serde/pull/2608
18//! [`intid`]: https://docs.rs/intid/latest/intid
19//! [`intid_derive`]: https://docs.rs/intid-derive/latest/intid_derive
20#![no_std]
21extern crate alloc;
22
23/// The `primint` crate used to abstract over primitive integer types.
24///
25/// The central traits used are [`primint::PrimitiveInt`] and [`primint::UnsignedPrimInt`].
26/// All bounds in this crate use [`primint::UnsignedPrimInt`],
27/// as signed integers are not useful for our purposes.
28pub extern crate primint;
29
30use core::fmt::Debug;
31
32#[macro_use]
33mod macros;
34#[doc(hidden)]
35pub mod array;
36mod impls;
37pub mod trusted;
38pub mod uint;
39pub mod utils;
40
41pub use primint::UnsignedPrimInt;
42
43/// An identifier which can be sensibly converted to/from an unsigned integer value.
44///
45///
46/// The type should not carry any information beyond that of the integer index,
47/// and be able to losslessly convert back and forth from [`Self::Int`].
48/// It is possible that not all values of the underlying integer type are valid,
49/// allowing [`core::num::NonZero`] and C-like enums to implement this trait.
50///
51///
52/// This is intended mostly for newtype wrappers around integer indexes,
53/// and the primitive integer types themselves.
54///
55/// The value of the underlying integer must be consistent.
56/// It cannot change over the course of the program's lifetime.
57///
58/// ## Safety
59/// With one exception, this trait is safe to implement and cannot be relied upon by memory safety.
60///
61/// If the implementation of [`IntegerId::from_int_unchecked`] makes any sort of unsafe assumptions
62/// about the validity of the input, then the rest of the trait must be implemented correctly.
63/// This means that implementations of this trait fall into two categories:
64/// 1. Potentially incorrect implemented entirely using safe code, where `from_int_unchecked(x)`
65/// is equivalent to calling `from_int_checked(x).unwrap()`;
66/// 2. Traits where `from_int_unchecked` could trigger undefined behavior on an invalid value,
67/// but every other part of this trait can be trusted to be implemented correctly.
68///
69/// In both these cases, the following code is always safe:
70/// ```no_run
71/// # use intid_core::IntegerId;
72/// fn foo<T: IntegerId>(x: T) -> T {
73/// let y = x.to_int();
74/// let z = unsafe { T::from_int_unchecked(y) };
75/// z
76/// }
77/// ```
78/// In case 1, it doesn't matter if [`x.to_int()`](Self::to_int) produces garbage data,
79/// because `T::from_int_unchecked` method is safe to call.
80/// In case 2, the `to_int` method can be trusted to produce a valid value `y` that cannot fail
81/// when passed to `T::from_int_unchecked`.
82///
83/// The requirement for correctness in this case also apply to all sub-traits in this crate,
84/// including [`IntegerIdContiguous`] and [`IntegerIdCounter`].
85/// So an unsafe implementation of `from_int_unchecked` can be similarly trusted to accept
86/// all integer values between [`IntegerId::MIN_ID`] and [`IntegerId::MAX_ID`].
87///
88/// This restriction allows avoiding unnecessary checks when ids are stored to/from another data structure.
89/// Despite this requirement, I still consider this trait safe to implement,
90/// because safety can only be violated by an unsafe implementation of`from_int_unchecked`.
91///
92/// This type should not have interior mutability.
93/// This is guaranteed by the `Copy` bound.
94pub trait IntegerId: Copy + Eq + Debug + Send + Sync + 'static {
95 /// The underlying integer type.
96 ///
97 /// Every valid instance of `Self` should correspond to a valid `Self::Int`.
98 /// However, the other direction may not always be true.
99 type Int: primint::UnsignedPrimInt;
100 /// The value of this type with the smallest integer value,
101 /// or `None` if this type is uninhabited.
102 const MIN_ID: Option<Self>;
103 /// The value of this type with the largest integer value,
104 /// or `None` if this type is uninhabited.
105 const MAX_ID: Option<Self>;
106 /// The value of [`Self::MIN_ID`] a primitive integer,
107 /// or `None` if this type is uninhabited.
108 ///
109 /// This is necessary because trait methods cannot be marked `const`.
110 const MIN_ID_INT: Option<Self::Int>;
111 /// The value of [`Self::MAX_ID`] a primitive integer,
112 /// or `None` if this type is uninhabited.
113 ///
114 /// This is necessary because trait methods cannot be marked `const`.
115 const MAX_ID_INT: Option<Self::Int>;
116
117 /// Indicates that the type's implementation of [`IntegerId::to_int`] can be trusted
118 /// to only return values in the range `MIN_ID_INT..=MAX_ID_INT`.
119 ///
120 /// Creating this token means that all of these guarantees can be relied upon for memory safety.
121 /// This allows unsafe code to avoid bounds checks,
122 /// but turns a correctness invariant into a soundness invariant.
123 ///
124 /// # Safety
125 /// The result of [`Self::to_int`] must always fall in the range `MIN_ID_INT..=MAX_ID_INT`.
126 ///
127 /// If [`EnumId`] is implemented,
128 /// then the requirements of the [`EnumId`] trait must be met as well.
129 /// In particular, the index must always fit in a `u32`
130 /// and have the appropriately `Array` and `BitSet` items.
131 const TRUSTED_RANGE: Option<trusted::TrustedRangeToken<Self>> = None;
132
133 /// Create an id from the underlying integer value,
134 /// panicking if the value is invalid.
135 ///
136 /// ## Correctness
137 /// A value returned by this method should never trigger
138 /// an error if passed to [`Self::from_int_checked`].
139 /// This means the validity of certain ids can't change over the course of the program.
140 #[inline]
141 #[track_caller]
142 fn from_int(id: Self::Int) -> Self {
143 match Self::from_int_checked(id) {
144 Some(success) => success,
145 None => uint::invalid_id(id),
146 }
147 }
148
149 /// Create an id from the underlying integer value,
150 /// returning `None` if the value is invalid.
151 fn from_int_checked(id: Self::Int) -> Option<Self>;
152
153 /// Create an id from the underlying integer value,
154 /// triggering undefined behavior if the value is invalid.
155 ///
156 /// ## Safety
157 /// If the corresponding [`Self::from_int_checked`] method would fail,
158 /// this triggers undefined behavior.
159 /// The default implementation just invokes [`Self::from_int`].
160 #[inline]
161 unsafe fn from_int_unchecked(id: Self::Int) -> Self {
162 Self::from_int(id)
163 }
164
165 /// Convert this id into an underlying integer type.
166 ///
167 /// This method can never fail,
168 /// since valid instances `Self` always correspond to valid instances of `Self::Int`.
169 fn to_int(self) -> Self::Int;
170}
171
172/// Indicates that an id occupies contiguous range of contiguous values,
173/// and all values between [`IntegerId::MIN_ID`] and [`IntegerId::MAX_ID`] are valid.
174///
175/// This is similar to [`bytemuck::Contiguous`].
176/// However, since it is safe to implement,
177/// it must not be relied upon for correctness.
178///
179/// ## Safety
180/// This trait is safe to implement, so may not usually be relied upon for memory safety.
181///
182/// However, if [`Self::from_int_unchecked`](IntegerId::from_int_unchecked) makes unsafe assumptions (satisfying the condition set forth in the [`IntegerId`] safety docs),
183/// then this trait must also be implemented correctly.
184/// More specifically, all integers between [`IntegerId::MIN_ID`] and [`IntegerId::MAX_ID`] must be valid
185/// and cannot fail when passed to [`IntegerId::from_int_checked`].
186pub trait IntegerIdContiguous: IntegerId {}
187
188/// An [`IntegerId`] that can be sensibly used as a counter,
189/// starting at a [`Self::START`] value and being incremented from there.
190///
191/// This is used by the `intid-allocator` crate to provide an atomic counter to allocate new ids.
192/// It also provides more complex allocators that can reuse ids that have been freed.
193///
194/// This type cannot be implemented for uninhabited types like [`core::convert::Infallible`] or `!`,
195/// as there is no valid implementation of [`Self::START`].
196pub trait IntegerIdCounter: IntegerId + IntegerIdContiguous {
197 /// Where a counter a should start from.
198 ///
199 /// This should be the [`Default`] value if one is defined.
200 /// It is usually equal to the [`IntegerId::MIN_ID`],
201 /// but this is not required.
202 const START: Self;
203 /// The value of [`Self::START`] as a [`T::Int`](IntegerId::Int).
204 ///
205 /// This is necessary because trait methods ([`IntegerId::to_int`])
206 /// can not currently be const methods.
207 const START_INT: Self::Int;
208
209 /// Increment this value by the specified offset,
210 /// returning `None` if the value overflows or is invalid.
211 ///
212 /// This should behave consistently with [`IntegerIdContiguous`]
213 /// and [`IntegerId::from_int_checked`].
214 /// However, that can not be relied upon for memory safety.
215 ///
216 /// This is implemented as an associated method to avoid namespace pollution.
217 #[inline]
218 fn checked_add(this: Self, offset: Self::Int) -> Option<Self> {
219 primint::checked_add(this.to_int(), offset).and_then(Self::from_int_checked)
220 }
221
222 /// Increment this value by the specified offset,
223 /// returning `None` if the value overflows or is invalid.
224 ///
225 /// This should behave consistently with [`IntegerIdContiguous`]
226 /// and [`IntegerId::from_int_checked`].
227 /// However, that can not be relied upon for memory safety.
228 ///
229 /// This is implemented as an associated method to avoid namespace pollution.
230 #[inline]
231 fn checked_sub(this: Self, offset: Self::Int) -> Option<Self> {
232 primint::checked_sub(this.to_int(), offset).and_then(Self::from_int_checked)
233 }
234}
235
236/// An [`IntegerId`] which are limited to small set of indexes.
237///
238/// As the name suggests, it is most useful for C-style enums,
239/// allowing use with [`EnumMap`] and [`EnumSet`] collections which do not do any allocation.
240/// Is not implemented for types like `u32` where inline storage
241/// would require inordinate amounts of space (an `EnumMap<u32, u8>`would take 4GiB).
242///
243/// For this reason, all valid indexes and the value [`Self::MAX_ID_INT + 1`](IntegerId::MAX_ID_INT)
244/// must fit into both a [`u32`] and a [`usize`].
245/// This requirement prevents a `u32` from implementing `EnumId`,
246/// as `u32::MAX + 1` exceeds 32-bits. Implementing `EnumId for u32` would also be invalid on
247/// 16-bit architectures, as then a `u32` index would not fit into a `usize`.
248///
249/// Note that this trait does not imply [`IntegerIdContiguous`].
250/// This means that while [`x <= Self::MAX_ID_INT`](IntegerId::MAX_ID_INT) is a necessary condition
251/// for [`Self::from_int(x)`](IntegerId::from_int) to succeed, it is not always a sufficient condition.
252///
253/// [`EnumMap`]: https://docs.rs/idmap/latest/idmap/enums/map/struct.EnumMap.html
254/// [`EnumSet`]: https://docs.rs/idmap/latest/idmap/enums/set/struct.EnumSet.html
255pub trait EnumId: IntegerId {
256 /// The total number of valid values.
257 ///
258 /// This value is at most equal to [`Self::MAX_ID_INT`](IntegerId::MAX_ID_INT),
259 /// which must fit in a [`u32`] due to the trait requirements.
260 const COUNT: u32;
261 /// A builtin array of `[T; {Self::MAX_ID_INT + 1}]`.
262 ///
263 /// Necessary to work around the current (Rust 1.90) restrictions on const generics
264 ///
265 /// # Safety
266 /// Since the [`array::Array`] trait is sealed,
267 /// this is guaranteed to be a builtin array of type `T`.
268 /// Since this is a safe trait, the length could be any value.
269 /// However, that is easily checked using a const assertion.
270 type Array<T>: array::Array<T>;
271 /// An array of words, whose bits can store all valid ids.
272 ///
273 /// Necessary to work around the current (Rust 1.90) restrictions on const generics.
274 ///
275 /// # Safety
276 /// Has similar safety guarantees as [`Self::Array`].
277 /// The type is correct, but the length must be checked with a const assertion.
278 type BitSet: array::Array<array::BitsetLimb>;
279}
280impl EnumId for u8 {
281 const COUNT: u32 = {
282 assert!(u8::MAX as u32 + 1 == 256);
283 256
284 };
285 type Array<T> = [T; 256];
286 type BitSet = [u64; 4];
287}
288
289/// A type that can be for lookup as an [`IntegerId`].
290///
291/// Used for key lookup in maps, similar to [`core::borrow::Borrow`] or [`equivalent::Equivalent`].
292/// These traits are not suitable for id maps,
293/// which need conversion to integers rather than hashing/equality.
294///
295/// [`equivalent::Equivalent`]: https://docs.rs/equivalent/latest/equivalent/trait.Equivalent.html
296pub trait EquivalentId<K: IntegerId> {
297 /// Convert this type to an id `K`.
298 fn as_id(&self) -> K;
299}
300impl<K: IntegerId> EquivalentId<K> for K {
301 #[inline]
302 fn as_id(&self) -> K {
303 *self
304 }
305}
306impl<K: IntegerId> EquivalentId<K> for &'_ K {
307 #[inline]
308 fn as_id(&self) -> K {
309 **self
310 }
311}
312impl<K: IntegerId> EquivalentId<K> for &'_ mut K {
313 #[inline]
314 fn as_id(&self) -> K {
315 **self
316 }
317}