| 1 | // Copyright 2024 Brian Smith. |
| 2 | // |
| 3 | // Permission to use, copy, modify, and/or distribute this software for any |
| 4 | // purpose with or without fee is hereby granted, provided that the above |
| 5 | // copyright notice and this permission notice appear in all copies. |
| 6 | // |
| 7 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES |
| 8 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 9 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY |
| 10 | // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 11 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION |
| 12 | // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN |
| 13 | // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 14 | |
| 15 | #![cfg_attr (not(test), allow(dead_code))] |
| 16 | |
| 17 | use super::Overlapping; |
| 18 | use crate::error::LenMismatchError; |
| 19 | use core::array::TryFromSliceError; |
| 20 | |
| 21 | pub struct Array<'o, T, const N: usize> { |
| 22 | // Invariant: N != 0. |
| 23 | // Invariant: `self.in_out.len() == N`. |
| 24 | in_out: Overlapping<'o, T>, |
| 25 | } |
| 26 | |
| 27 | impl<'o, T, const N: usize> Array<'o, T, N> { |
| 28 | pub(super) fn new(in_out: Overlapping<'o, T>) -> Result<Self, LenMismatchError> { |
| 29 | if N == 0 || in_out.len() != N { |
| 30 | return Err(LenMismatchError::new(N)); |
| 31 | } |
| 32 | Ok(Self { in_out }) |
| 33 | } |
| 34 | |
| 35 | pub fn into_unwritten_output(self) -> &'o mut [T; N] |
| 36 | where |
| 37 | &'o mut [T]: TryInto<&'o mut [T; N], Error = TryFromSliceError>, |
| 38 | { |
| 39 | self.in_out |
| 40 | .into_unwritten_output() |
| 41 | .try_into() |
| 42 | .unwrap_or_else(|TryFromSliceError { .. }| { |
| 43 | unreachable!() // Due to invariant |
| 44 | }) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | impl<T, const N: usize> Array<'_, T, N> { |
| 49 | pub fn input<'s>(&'s self) -> &'s [T; N] |
| 50 | where |
| 51 | &'s [T]: TryInto<&'s [T; N], Error = TryFromSliceError>, |
| 52 | { |
| 53 | self.in_out |
| 54 | .input() |
| 55 | .try_into() |
| 56 | .unwrap_or_else(|TryFromSliceError { .. }| { |
| 57 | unreachable!() // Due to invariant |
| 58 | }) |
| 59 | } |
| 60 | } |
| 61 | |