1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use alloc::{
    borrow::{Borrow, Cow, ToOwned},
    boxed::Box,
    string::{String, ToString},
};
use core::{
    convert::{TryFrom, TryInto},
    fmt,
    marker::PhantomData,
    num::{
        NonZeroI128,
        NonZeroI16,
        NonZeroI32,
        NonZeroI64,
        NonZeroI8,
        NonZeroIsize,
        NonZeroU128,
        NonZeroU16,
        NonZeroU32,
        NonZeroU64,
        NonZeroU8,
        NonZeroUsize,
    },
};

/// A value represented as an index.
///
/// # Valid indices
///
/// Valid indices are defined by the type `T`. In order for an index
/// to be valid, they must be valid to be passed into
/// [`FromIndex::from_index`].
///
/// Created by either [`IntoIndex::into_index`] or [`Idx::try_new`].
#[must_use]
#[derive(Eq, PartialEq, Debug)]
pub struct Idx<T: ?Sized> {
    v: NonZeroUsize,
    _phantom: PhantomData<T>,
}

impl<T: ?Sized> Clone for Idx<T> {
    fn clone(&self) -> Self {
        Self {
            v: self.v,
            _phantom: PhantomData,
        }
    }
}

impl<T: ?Sized> fmt::Display for Idx<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.v, f)
    }
}

impl<T: ?Sized + NewIndex> Idx<T> {
    /// Create a new index with the specified value if the type allows
    /// it.
    pub fn try_new(v: NonZeroUsize) -> Option<Self> {
        if <T as NewIndex>::new_index_allowed(v) {
            // SAFETY: New indices with that value are allowed.
            Some(unsafe { Self::new(v) })
        } else {
            None
        }
    }

    /// Create a new index with the specified value if the type allows
    /// it.
    crate fn try_new_usize(v: usize) -> Option<Self> {
        NonZeroUsize::new(v).and_then(Self::try_new)
    }
}

impl<T: ?Sized> Idx<T> {
    /// Create a new index with the specific value.
    ///
    /// # Safety
    ///
    /// The value must be a [valid index][idx].
    ///
    /// [idx]: #valid-indices
    pub const unsafe fn new(v: NonZeroUsize) -> Self {
        Self {
            v,
            _phantom: PhantomData,
        }
    }

    /// Same as [`Self::new`], except that `v` can be zero, and
    /// `None` will be returned.
    ///
    /// # Safety
    ///
    /// The value must either be a [valid index][idx] or zero.
    ///
    /// [idx]: #valid-indices
    pub const unsafe fn from_usize(v: usize) -> Option<Self> {
        if let Some(v) = NonZeroUsize::new(v) {
            Some(Self {
                v,
                _phantom: PhantomData,
            })
        } else {
            None
        }
    }

    pub const fn get(&self) -> NonZeroUsize {
        self.v
    }

    /// This reinterprets the index as a different type of index;
    /// essentially `Idx::<U>::new(self.get())`.
    ///
    /// # Safety
    ///
    /// The index must be a [valid index][idx] for type `U`.
    ///
    /// [idx]: #valid-indices
    pub const unsafe fn cast<U: ?Sized>(self) -> Idx<U> {
        unsafe { Idx::new(self.v) }
    }

    crate const unsafe fn new_unchecked(v: usize) -> Self {
        Self {
            v: unsafe { NonZeroUsize::new_unchecked(v) },
            _phantom: PhantomData,
        }
    }
}

impl<T: ?Sized> Idx<T> {
    /// This reinterprets the index as a different type of index;
    /// essentially `Idx::<U>::new(self.get())`.
    ///
    /// This is restricted by Borrow, meaning that it is type-safe.
    pub fn cast_safe<U: Borrow<T>>(self) -> Idx<U> {
        unsafe { Idx::new(self.v) }
    }
}

impl<T: ?Sized + FromIndex> Idx<T> {
    /// Convert this index into a value.
    ///
    /// A shorthand for [`<T as FromIndex>::from_index(self)`][fi].
    ///
    /// [fi]: FromIndex::from_index
    pub fn into_value(self) -> T {
        <T as FromIndex>::from_index(self)
    }
}

/// Whether a new index can be created out of thin air for the value.
pub unsafe trait NewIndex: FromIndex + IntoIndex {
    /// Whether the specified value is allowed to be used to make an
    /// index out of thin air.
    fn new_index_allowed(v: NonZeroUsize) -> bool;
}

/// An attempted conversion into an [`Idx`].
///
/// This is used when converting a value into an appropriate index. Therefore,
/// only types that are integer-like should return `Some` here.
///
/// Example:
///
/// ```rust
/// # use core::convert::{TryFrom, TryInto}; // If not edition-2021
/// use core::num::NonZeroUsize;
///
/// use hash_arr_map::{FromIndex, Idx, IntoIndex};
///
/// struct CouldBeAnIdx(i32);
///
/// impl IntoIndex for CouldBeAnIdx {
///     fn into_index(&self) -> Option<Idx<Self>> {
///         let nzu: NonZeroUsize = usize::try_from(self.0).ok()?.try_into().ok()?;
///         Some(unsafe { Idx::new(nzu) })
///     }
/// }
///
/// impl FromIndex for CouldBeAnIdx {
///     fn from_index(idx: Idx<Self>) -> Self {
///         Self(idx.get().get() as i32)
///     }
/// }
/// ```
pub trait IntoIndex {
    /// Try to convert `self` into an [`Idx`].
    ///
    /// ```rust
    /// use core::num::NonZeroUsize;
    ///
    /// use hash_arr_map::{Idx, IntoIndex};
    ///
    /// let a: i32 = 5;
    ///
    /// assert_eq!(
    ///     a.into_index(),
    ///     Some(unsafe { Idx::new(NonZeroUsize::new(5).unwrap()) })
    /// );
    /// ```
    #[allow(clippy::wrong_self_convention)]
    fn into_index(&self) -> Option<Idx<Self>>;
}

/// Conversion from an index.
///
/// This trait implements conversion from an index into `Self`.
pub trait FromIndex: Sized + IntoIndex {
    /// Convert it.
    ///
    /// # Implementors
    ///
    /// The only guarantees about the index value is that it has either
    /// come from `Self::into_index`, `Idx::try_new` or that is has
    /// come from a borrowed form of `Self`.
    ///
    /// By implementing `Borrow<T>` for your type, this loosens the
    /// guarantees given here, since this index could also come from
    /// `T`.
    fn from_index(idx: Idx<Self>) -> Self;
}

macro_rules! impl_test_index {
    ($($t:ty,)+) => {
        $(
            impl IntoIndex for $t {
                fn into_index(&self) -> Option<Idx<Self>> {
                    unsafe { Idx::from_usize(usize::try_from(*self).ok()?) }
                }
            }

            impl FromIndex for $t {
                fn from_index(idx: Idx<Self>) -> Self {
                    idx.get().get() as $t
                }
            }

            unsafe impl NewIndex for $t {
                fn new_index_allowed(idx: NonZeroUsize) -> bool {
                    idx.get() <= (<$t>::MAX as usize)
                }
            }
        )+
    }
}

impl_test_index! {
    i8,    u8,
    i16,   u16,
    i32,   u32,
    i64,   u64,
    i128,  u128,
    isize, usize,
}

macro_rules! impl_test_index_nonzero {
    ($($t:ty, $b:ty,)+) => {
        $(
            impl IntoIndex for $t {
                fn into_index(&self) -> Option<Idx<Self>> {
                    Some(unsafe { Idx::new((*self).try_into().ok()?) })
                }
            }

            impl FromIndex for $t {
                fn from_index(idx: Idx<Self>) -> Self {
                    unsafe { Self::new_unchecked(idx.get().get() as _) }
                }
            }

            unsafe impl NewIndex for $t {
                fn new_index_allowed(idx: NonZeroUsize) -> bool {
                    <$b>::try_from(idx.get()).is_ok()
                }
            }
        )+
    }
}

impl_test_index_nonzero! {
    NonZeroI8,    i8,    NonZeroU8,   u8,
    NonZeroI16,   i16,   NonZeroU16,  u16,
    NonZeroI32,   i32,   NonZeroU32,  u32,
    NonZeroI64,   i64,   NonZeroU64,  u64,
    NonZeroI128,  i128,  NonZeroU128, u128,
    NonZeroIsize, isize,
}

impl IntoIndex for NonZeroUsize {
    fn into_index(&self) -> Option<Idx<Self>> {
        Some(unsafe { Idx::new(*self) })
    }
}

impl FromIndex for NonZeroUsize {
    fn from_index(idx: Idx<Self>) -> Self {
        idx.get()
    }
}

unsafe impl NewIndex for NonZeroUsize {
    fn new_index_allowed(_: NonZeroUsize) -> bool {
        true
    }
}

impl IntoIndex for char {
    fn into_index(&self) -> Option<Idx<Self>> {
        Some(unsafe { u32::from(*self).into_index()?.cast() })
    }
}

impl FromIndex for char {
    fn from_index(idx: Idx<Self>) -> Self {
        unsafe { Self::from_u32_unchecked(idx.get().get() as u32) }
    }
}

unsafe impl NewIndex for char {
    fn new_index_allowed(idx: NonZeroUsize) -> bool {
        u32::try_from(idx.get())
            .ok()
            .and_then(Self::from_u32)
            .is_some()
    }
}

// Note: There is no matching FromIndex.
impl<T: IntoIndex> IntoIndex for &T {
    fn into_index(&self) -> Option<Idx<Self>> {
        Some((**self).into_index()?.cast_safe())
    }
}

impl<T: IntoIndex> IntoIndex for Box<T> {
    fn into_index(&self) -> Option<Idx<Self>> {
        Some((**self).into_index()?.cast_safe())
    }
}

impl<T: FromIndex> FromIndex for Box<T> {
    fn from_index(idx: Idx<Self>) -> Self {
        Self::new(T::from_index(unsafe { idx.cast() }))
    }
}

unsafe impl<T: NewIndex> NewIndex for Box<T> {
    fn new_index_allowed(idx: NonZeroUsize) -> bool {
        T::new_index_allowed(idx)
    }
}

impl<T: IntoIndex> IntoIndex for Option<T> {
    fn into_index(&self) -> Option<Idx<Self>> {
        Some(unsafe { self.as_ref().and_then(T::into_index)?.cast() })
    }
}

impl<T: FromIndex> FromIndex for Option<T> {
    fn from_index(idx: Idx<Self>) -> Self {
        Some(T::from_index(unsafe { idx.cast() }))
    }
}

unsafe impl<T: NewIndex> NewIndex for Option<T> {
    fn new_index_allowed(idx: NonZeroUsize) -> bool {
        T::new_index_allowed(idx)
    }
}

impl<T: IntoIndex, E> IntoIndex for Result<T, E> {
    fn into_index(&self) -> Option<Idx<Self>> {
        Some(unsafe { self.as_ref().ok()?.into_index()?.cast() })
    }
}

impl<T: FromIndex, E> FromIndex for Result<T, E> {
    fn from_index(idx: Idx<Self>) -> Self {
        Ok(T::from_index(unsafe { idx.cast() }))
    }
}

unsafe impl<T: NewIndex, E> NewIndex for Result<T, E> {
    fn new_index_allowed(idx: NonZeroUsize) -> bool {
        T::new_index_allowed(idx)
    }
}

impl<T: ?Sized + IntoIndex + ToOwned> IntoIndex for Cow<'_, T> {
    fn into_index(&self) -> Option<Idx<Self>> {
        Some((**self).into_index()?.cast_safe())
    }
}

impl<T: ?Sized + IntoIndex + ToOwned> FromIndex for Cow<'static, T>
where
    <T as ToOwned>::Owned: FromIndex,
{
    fn from_index(idx: Idx<Self>) -> Self {
        Self::Owned(FromIndex::from_index(unsafe { idx.cast() }))
    }
}

unsafe impl<T: ?Sized + IntoIndex + ToOwned> NewIndex for Cow<'static, T>
where
    <T as ToOwned>::Owned: NewIndex,
{
    fn new_index_allowed(idx: NonZeroUsize) -> bool {
        <T as ToOwned>::Owned::new_index_allowed(idx)
    }
}

impl IntoIndex for str {
    fn into_index(&self) -> Option<Idx<Self>> {
        if self.starts_with('0') {
            None
        } else {
            let u = self.bytes().try_fold(0, |acc, c| -> Option<usize> {
                acc.checked_mul(10)?
                    .checked_add(matches!(c, b'0'..=b'9').then(|| c - b'0')? as usize)
            })?;
            unsafe { Idx::from_usize(u) }
        }
    }
}

impl IntoIndex for String {
    fn into_index(&self) -> Option<Idx<Self>> {
        Some((**self).into_index()?.cast_safe())
    }
}

impl FromIndex for String {
    fn from_index(idx: Idx<Self>) -> Self {
        idx.to_string()
    }
}

unsafe impl NewIndex for String {
    fn new_index_allowed(_: NonZeroUsize) -> bool {
        true
    }
}