imagine/
ascii_array.rs

1use core::fmt::Write;
2
3/// An array of bytes expected to contain ascii data.
4///
5/// There's no actual enforced encoding! The `Debug` and `Display` impls will
6/// just `as` cast each byte into a character. This works just as expected for
7/// ascii data (`32..=126`), and is still safe for non-ascii data, but you just
8/// might get non-printing characters or multi-byte unicode characters.
9///
10/// This type really just exists to provide alternate `Debug` and `Display`
11/// impls for byte arrays. Image formats have magic byte sequences
12/// which are intended to match ascii sequences (such as PNG header tags), and
13/// so this is a useful newtype to use in other structures to give them a better
14/// `Debug` output.
15#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck::Zeroable, bytemuck::Pod)]
16#[repr(transparent)]
17pub struct AsciiArray<const N: usize>(pub [u8; N]);
18impl<const N: usize> Default for AsciiArray<N> {
19  #[inline]
20  #[must_use]
21  fn default() -> Self {
22    Self([0_u8; N])
23  }
24}
25impl<const N: usize> core::fmt::Debug for AsciiArray<N> {
26  #[inline]
27  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
28    f.write_char('\"')?;
29    for ch in self.0.iter().copied().map(|u| u as char) {
30      f.write_char(ch)?;
31    }
32    f.write_char('\"')?;
33    Ok(())
34  }
35}
36impl<const N: usize> core::fmt::Display for AsciiArray<N> {
37  #[inline]
38  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39    for ch in self.0.iter().copied().map(|u| u as char) {
40      f.write_char(ch)?;
41    }
42    Ok(())
43  }
44}
45impl<const N: usize> From<[u8; N]> for AsciiArray<N> {
46  #[inline]
47  #[must_use]
48  fn from(array: [u8; N]) -> Self {
49    Self(array)
50  }
51}
52impl<const N: usize> PartialEq<&str> for AsciiArray<N> {
53  #[inline]
54  #[must_use]
55  fn eq(&self, other: &&str) -> bool {
56    self.0.as_slice() == other.as_bytes()
57  }
58}