array_of_base 0.1.0

An array of specified length `N` of u8 values from 0 to `B`-1
Documentation
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! An array of specified length `N` of u8 values from 0 to `B`-1
//!
//! See [`ArrayOfBase`]

use crate::ArrayOfHex;
use crate::Error;

#[cfg(feature = "serde")]
use serde::{
    ser::{Serialize, Serializer},
    Deserialize,
};

/// An array of specified length `N` of u8 values from 0 to `B`-1
///
/// # Example - Success
/// ```
/// # use array_of_base::ArrayOfBase;
/// // GIVEN
/// let array = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4];
///
/// // WHEN
/// let actual = ArrayOfBase::<10, 5>::try_new(array);
///
/// // THEN
/// assert!(actual.is_ok())
/// ```
///
/// # Example - Error
///
/// ```
/// # use array_of_base::ArrayOfBase;
/// // GIVEN
/// let array = [16];
///
/// // WHEN
/// let actual = ArrayOfBase::<1, 16>::try_new(array);
///
/// // THEN
/// assert!(actual.is_err())
/// ```
// #[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct ArrayOfBase<const N: usize, const B: u8> {
    value: [u8; N],
}

impl<const N: usize, const B: u8> ArrayOfBase<N, B> {
    /// Create from Array of u8 numbers of the same size
    ///
    /// See [`ArrayOfBase`] for Example
    ///
    /// # Errors
    ///
    /// Will error if:
    ///
    /// - Invalid value in supplied array [`Error::InvalidValue`]
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::{Error, ArrayOfBase};
    /// // GIVEN
    /// let valid_array     = [0u8, 1, 2, 3, 0];
    /// let invalid_array   = [0u8, 1, 2, 3, 4];
    ///
    /// // WHEN
    /// # let actual: Vec<Result<[u8; 5], Error>> =
    /// #     [valid_array, invalid_array]
    /// #         .into_iter()
    /// #         .map(|v| {
    /// ArrayOfBase::<5, 4>::try_new(v).map(|b| b.unwrap())
    /// // Ran on each
    /// #         })
    /// #         .collect();
    ///
    /// // THEN
    /// assert_eq!(
    ///     actual,
    ///     vec![
    ///         Ok([0u8, 1, 2, 3, 0]),      // valid_array
    ///         Err(Error::InvalidValue),   // invalid_array
    ///     ]
    /// );
    /// ```
    pub fn try_new(v: [u8; N]) -> Result<Self, Error> {
        if v.iter().copied().all(Self::valid_number) {
            Ok(Self { value: v })
        } else {
            Err(Error::InvalidValue)
        }
    }

    /// Create from Vec of u8 numbers
    ///
    /// # Errors
    ///
    /// Will error if:
    ///
    /// - Too many elements in the supplied vector [`Error::Oversized`]
    /// - Too few, but not 0, elements in the supplied vector [`Error::Undersized`]
    /// - Empty vector supplied [`Error::Empty`]
    /// - Invalid value in supplied array [`Error::InvalidValue`]
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::{Error, ArrayOfBase};
    /// // GIVEN
    /// let valid_vec: Vec<u8>      = vec![0, 0, 1, 2, 3];
    /// let undersized_vec: Vec<u8> = vec![1];
    /// let empty_vec: Vec<u8>      = Vec::new();
    /// let oversized_vec: Vec<u8>  = vec![1, 2, 3, 1, 2, 3];
    ///
    /// // WHEN
    /// # let actual: Vec<Result<[u8; 5], Error>> =
    /// #     [valid_vec, undersized_vec, empty_vec, oversized_vec]
    /// #         .iter()
    /// #         .map(|v| {
    /// ArrayOfBase::<5, 4>::try_from_vec_exact(v).map(|b| b.unwrap())
    /// // Ran on each
    /// #         })
    /// #         .collect();
    ///
    /// // THEN
    /// assert_eq!(
    ///     actual,
    ///     vec![
    ///         Ok([0u8, 0, 1, 2, 3]),  // valid_vec
    ///         Err(Error::Undersized), // undersized_vec
    ///         Err(Error::Empty),      // empty_vec
    ///         Err(Error::Oversized),  // oversized_vec
    ///     ]
    /// );
    /// ```
    pub fn try_from_vec_exact(v: &[u8]) -> Result<Self, Error> {
        use std::cmp::Ordering::{Equal, Greater, Less};
        match v.len().cmp(&N) {
            Greater => Err(Error::Oversized),
            Less if v.is_empty() => Err(Error::Empty),
            Less => Err(Error::Undersized),
            Equal => Self::try_new(v.try_into().expect(
                "1666898415 - Unreachable: Correct length already verified",
            )),
        }
    }

    /// Create from non-empty Vec of u8 numbers, pad `0`s to the left
    ///
    /// # Errors
    ///
    /// Will error if:
    ///
    /// - Too many elements in the supplied vector [`Error::Oversized`]
    /// - Empty vector supplied [`Error::Empty`]
    /// - Invalid value in supplied array [`Error::InvalidValue`]
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::{Error, ArrayOfBase};
    /// // GIVEN
    /// let valid_vec: Vec<u8>      = vec![1, 2, 3];
    /// let empty_vec: Vec<u8>      = Vec::new();
    /// let oversized_vec: Vec<u8>  = vec![1, 2, 3, 1, 2, 3];
    ///
    /// // WHEN
    /// # let actual: Vec<Result<[u8; 5], Error>> =
    /// #     [valid_vec, empty_vec, oversized_vec]
    /// #         .iter()
    /// #         .map(|v| {
    /// ArrayOfBase::<5, 4>::try_from_vec_pad(v).map(|b| b.unwrap())
    /// // Ran on each
    /// #         })
    /// #         .collect();
    ///
    /// // THEN
    /// assert_eq!(
    ///     actual,
    ///     vec![
    ///         Ok([0u8, 0, 1, 2, 3]),  // valid_vec
    ///         Err(Error::Empty),      // empty_vec
    ///         Err(Error::Oversized),  // oversized_vec
    ///     ]
    /// );
    /// ```
    pub fn try_from_vec_pad(v: &[u8]) -> Result<Self, Error> {
        use std::cmp::Ordering::{Greater, Less};
        match v.len().cmp(&N) {
            Greater => Err(Error::Oversized),
            Less if v.is_empty() => Err(Error::Empty),
            _ => Self::try_new(Self::pad_array(v)),
        }
    }

    /// Return the contained verified array
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::ArrayOfBase;
    /// // GIVEN
    /// # let valid_u8_array = [1, 2, 3];
    /// # let mut verified = ArrayOfBase::<3, 10>::default();
    /// verified = ArrayOfBase::try_new(valid_u8_array).unwrap();
    ///
    /// // WHEN
    /// let actual = verified.unwrap();
    ///
    /// // THEN
    /// assert_eq!(actual, valid_u8_array)
    /// ```
    #[must_use]
    pub fn unwrap(self) -> [u8; N] {
        self.value
    }

    /// Borrow the contained verified array
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::ArrayOfBase;
    /// // GIVEN
    /// # const VALID_U8_ARRAY: [u8; 3] = [1, 2, 3];
    /// # let mut verified = ArrayOfBase::<3, 10>::default();
    /// verified = ArrayOfBase::try_new(VALID_U8_ARRAY).unwrap();
    ///
    /// // WHEN
    /// let actual = verified.borrow_u8_array();
    ///
    /// // THEN
    /// assert_eq!(actual, &VALID_U8_ARRAY)
    /// ```
    #[must_use]
    pub fn borrow_u8_array(&self) -> &[u8; N] {
        &self.value
    }

    fn valid_number(u8: u8) -> bool {
        u8 < B
    }

    /// Prepend to array 0 values until `N` size reached
    ///
    /// # Panics
    ///
    /// Will Panic if an array that exceeds the desired length is passed
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::ArrayOfBase;
    /// // GIVEN
    /// let x = [1, 2, 3];
    ///
    /// // WHEN
    /// let actual = ArrayOfBase::<5, 10>::pad_array(&x);
    ///
    /// // THEN
    /// assert_eq!(actual, [0u8, 0, 1, 2, 3]);
    /// ```
    #[must_use]
    pub fn pad_array(v: &[u8]) -> [u8; N] {
        assert!(v.len() <= N);
        let mut vec = v.to_vec();
        while vec.len() < N {
            vec.insert(0, 0);
        }
        vec.try_into().expect("1666979421 - Unreachable")
    }

    /// Reduce the size of the array to the specified value
    ///
    /// # Panics
    ///
    /// If the specified size `L` is larger than the current array size `N` the
    /// function will panic
    ///
    /// # Example
    /// ```
    /// # use array_of_base::ArrayOfBase;
    /// // GIVEN
    /// let long_array =
    ///     ArrayOfBase::<5, 4>::try_new([0u8, 1, 2, 3, 0]).unwrap();
    ///
    /// // WHEN
    /// let actual: ArrayOfBase<3, 4> = long_array.trim();
    ///
    /// // THEN
    /// assert_eq!(actual.borrow_u8_array(), &[0u8, 1, 2]);
    /// ```
    #[must_use]
    pub fn trim<const L: usize>(&self) -> ArrayOfBase<L, B> {
        assert!(L <= N);

        ArrayOfBase {
            value: array_from_iter_unchecked(self.value.into_iter().take(L)),
        }
    }
}

impl<const N: usize, const B: u8> Default for ArrayOfBase<N, B> {
    fn default() -> Self {
        Self { value: [0u8; N] }
    }
}

impl<const N: usize> std::fmt::Display for ArrayOfBase<N, 16> {
    /// Output the contents of [`ArrayOfHex`] as a hexadecimal string
    ///
    /// # Restrictions
    ///
    /// This function only works if:
    ///
    /// - The base `B` of the [`ArrayOfBase`] is `16` or [`ArrayOfHex`] is used
    ///
    /// # Example
    /// ```
    /// # use array_of_base::ArrayOfHex;
    /// # const ALL_HEX_VALUES: fn() -> ArrayOfHex<16> = || {
    /// #     ArrayOfHex::try_new(core::array::from_fn(|i| i as u8)).unwrap()
    /// # };
    /// #
    /// // GIVEN
    /// let value: ArrayOfHex<16> = ALL_HEX_VALUES();
    ///
    /// // WHEN
    /// let actual: String = value.to_string();
    ///
    /// // THEN
    /// assert_eq!(actual, "0123456789abcdef");
    /// ```
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for v in self.borrow_u8_array().iter() {
            match v {
                10 => write!(f, "a")?,
                11 => write!(f, "b")?,
                12 => write!(f, "c")?,
                13 => write!(f, "d")?,
                14 => write!(f, "e")?,
                15 => write!(f, "f")?,
                v => write!(f, "{v}")?,
            }
        }
        Ok(())
    }
}

#[cfg(feature = "serde")]
impl<const N: usize> Serialize for ArrayOfBase<N, 16> {
    /// Allow using [`ArrayOfHex`] in structs that derive [`serde::Serialize`]
    ///
    /// # Restrictions
    ///
    /// This function only works if:
    ///
    /// - The crate feature `serde` is activated
    /// - The base `B` of the [`ArrayOfBase`] is `16` or [`ArrayOfHex`] is used
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::{ArrayOfHex};
    /// #
    /// # #[derive(serde::Serialize)]
    /// # struct DummyStruct {
    /// #     hex_value: ArrayOfHex<5>,
    /// # }
    /// #
    /// // GIVEN
    /// let example_struct = DummyStruct {
    ///     hex_value: ArrayOfHex::try_new([10u8, 1, 11, 2, 12])
    ///         .unwrap()
    ///         .into(),
    /// };
    ///
    /// // WHEN
    /// let string = serde_json::to_string(&example_struct);
    ///
    /// // THEN
    /// assert_eq!(string.unwrap(), r#"{"hex_value":"a1b2c"}"#);
    /// ```
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<const N: usize> std::str::FromStr for ArrayOfBase<N, 16> {
    type Err = String;

    /// Parse a hexadecimal string into [`ArrayOfHex`]
    ///
    /// # Restrictions
    ///
    /// This function only works if:
    ///
    /// - The base `B` of the [`ArrayOfBase`] is `16` or [`ArrayOfHex`] is used
    ///
    /// # Example
    /// ```
    /// # use array_of_base::ArrayOfHex;
    /// # const ALL_HEX_VALUES: fn() -> ArrayOfHex<16> = || {
    /// #     ArrayOfHex::try_new(core::array::from_fn(|i| i as u8)).unwrap()
    /// # };
    /// #
    /// // GIVEN
    /// let string = "0123456789AbCdEf";
    ///
    /// // WHEN
    /// let actual = string.parse::<ArrayOfHex<16>>();
    ///
    /// // THEN
    /// assert_eq!(
    ///     actual.ok().unwrap().borrow_u8_array(),
    ///     ALL_HEX_VALUES().borrow_u8_array()
    /// );
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.len() != N {
            return Err(format!(
                "1669744337 - String does not match expected length of {N}"
            ));
        }

        let mut array = [0; N];

        for (i, v) in s.chars().enumerate() {
            array[i] = match v {
                '0' => 0,
                '1' => 1,
                '2' => 2,
                '3' => 3,
                '4' => 4,
                '5' => 5,
                '6' => 6,
                '7' => 7,
                '8' => 8,
                '9' => 9,
                'a' | 'A' => 10,
                'b' | 'B' => 11,
                'c' | 'C' => 12,
                'd' | 'D' => 13,
                'e' | 'E' => 14,
                'f' | 'F' => 15,
                v => {
                    return Err(format!(
                        "1669744576 - Unrecognized char `{v}` at position {i}"
                    ));
                }
            };
        }

        ArrayOfHex::try_new(array).map_err(|_| {
            unreachable!("1669744870 - Input values already validated")
        })
    }
}

#[cfg(feature = "serde")]
impl<'de, const N: usize> Deserialize<'de> for ArrayOfBase<N, 16> {
    /// Allow using [`ArrayOfHex`] in structs that derive [`serde::Deserialize`]
    ///
    /// # Restrictions
    ///
    /// This function only works if:
    ///
    /// - The crate feature `serde` is activated
    /// - The base `B` of the [`ArrayOfBase`] is `16` or [`ArrayOfHex`] is used
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::ArrayOfHex;
    /// #
    /// # #[derive(serde::Deserialize)]
    /// # struct DummyStruct {
    /// #     hex_value: ArrayOfHex<5>,
    /// # }
    /// #
    /// // GIVEN
    /// let example_string = r#"{"hex_value":"A1b2C"}"#;
    ///
    /// // WHEN
    /// let parsed = serde_json::from_str::<DummyStruct>(example_string);
    ///
    /// // THEN
    /// assert_eq!(
    ///     parsed.ok().unwrap().hex_value.borrow_u8_array(),
    ///     &[10u8, 1, 11, 2, 12]
    /// );
    /// ```
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        std::str::FromStr::from_str(&s).map_err(serde::de::Error::custom)
    }
}

fn array_from_iter_unchecked<const N: usize, I: Iterator<Item = u8>>(
    mut i: I,
) -> [u8; N] {
    std::array::from_fn(|_| i.next().unwrap_or_default())
}

/// Convert u8 into 2 u4 encoded as u8
///
/// # Example
///
#[must_use]
fn u8_to_u4_as_u8(v: u8) -> [u8; 2] {
    [(v & 0xf0) >> 4, v & 0x0f]
}

impl<const N: usize> ArrayOfBase<N, 16> {
    /// Split [`u8`] values into `u4` values, construct into [`ArrayOfHex`]
    ///
    /// # Todo
    ///
    /// TODO: Replace with `from_u8_array(array: [u8; {N / 2}])` when `generic_const_exprs` feature stabilizes
    ///
    /// # Panics
    ///
    /// - If the `I` value is not half `N` the function will panic.
    /// - If `N` is not an even number, the function will panic.
    ///
    /// This will be resolved when `generic_const_exprs` feature stabilizes
    ///
    /// # Example
    ///
    /// ```
    /// # use array_of_base::ArrayOfHex;
    /// // GIVEN
    /// let u8_array = [0u8, 16, 255];
    ///
    /// // WHEN
    /// let actual = ArrayOfHex::<6>::from_u8_array(u8_array);
    /// //                     ^^^^^ - Required until `generic_const_exprs` feature stabilizes
    ///
    /// // THEN
    /// assert_eq!(actual.borrow_u8_array(), &[0u8, 0, 1, 0, 15, 15]);
    /// ```
    pub fn from_u8_array<const I: usize>(array: [u8; I]) -> ArrayOfHex<N> {
        assert!(N == I * 2);
        ArrayOfBase {
            value: array_from_iter_unchecked(
                array.into_iter().flat_map(u8_to_u4_as_u8),
            ),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test1669773971_u8_to_u4_as_u8() {
        // GIVEN
        let x = 0xab;

        // WHEN
        let actual = u8_to_u4_as_u8(x);

        // THEN
        assert_eq!(actual, [0xa, 0xb]);
    }
}