1extern crate alloc;
2
3use core::{error::Error, fmt::Display};
4
5use crate::NonZeroChar;
6use alloc::{borrow::Cow, boxed::Box, string::String};
7
8macro_rules! impl_froms {
9 ($($ty:ty),+ $(,)?) => {
10 $(
11 impl From<NonZeroChar> for $ty {
12 fn from(value: NonZeroChar) -> Self {
13 value.get().into()
14 }
15 }
16 )+
17 };
18}
19macro_rules! impl_try_froms {
20 ($($ty:ty),+ $(,)?) => {
21 $(
22 impl TryFrom<NonZeroChar> for $ty {
23 type Error = <$ty as TryFrom<char>>::Error;
24
25 fn try_from(value: NonZeroChar) -> Result<Self, Self::Error> {
26 value.get().try_into()
27 }
28 }
29 )+
30 };
31}
32macro_rules! impl_fromiters {
33 ($($ty:ty),+ $(,)?) => {
34 $(
35 impl FromIterator<NonZeroChar> for $ty {
36 fn from_iter<T: IntoIterator<Item = NonZeroChar>>(iter: T) -> Self {
37 iter.into_iter()
38 .map(NonZeroChar::get)
39 .collect()
40 }
41 }
42 impl<'a> FromIterator<&'a NonZeroChar> for $ty {
43 fn from_iter<T: IntoIterator<Item = &'a NonZeroChar>>(iter: T) -> Self {
44 iter.into_iter()
45 .copied()
46 .map(NonZeroChar::get)
47 .collect()
48 }
49 }
50 )+
51 };
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct TryFromByteError(());
56#[allow(deprecated)]
57impl Display for TryFromByteError {
58 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
59 self.description().fmt(f)
60 }
61}
62impl Error for TryFromByteError {
63 fn description(&self) -> &str {
64 "converted integer out of range for `NonZeroChar`"
65 }
66}
67
68impl_froms! {
69 u32,
70 u64,
71 u128,
72 String,
73}
74impl_try_froms! {
75 u8,
76 u16,
77}
78impl_fromiters! {
79 String,
80 Box<str>,
81 Cow<'_, str>,
82}
83impl TryFrom<u8> for NonZeroChar {
84 type Error = TryFromByteError;
85
86 fn try_from(value: u8) -> Result<Self, Self::Error> {
87 NonZeroChar::new(value.into())
88 .ok_or(TryFromByteError(()))
89 }
90}
91impl TryFrom<u32> for NonZeroChar {
92 type Error = TryFromByteError;
93
94 fn try_from(value: u32) -> Result<Self, Self::Error> {
95 match value.try_into() {
96 Ok(ch) => {
97 NonZeroChar::new(ch)
98 .ok_or(TryFromByteError(()))
99 },
100 Err(_) => Err(TryFromByteError(())),
101 }
102 }
103}
104impl Extend<NonZeroChar> for String {
105 fn extend<T: IntoIterator<Item = NonZeroChar>>(&mut self, iter: T) {
106 self.extend(iter.into_iter().map(NonZeroChar::get));
107 }
108}
109impl<'a> Extend<&'a NonZeroChar> for String {
110 fn extend<T: IntoIterator<Item = &'a NonZeroChar>>(&mut self, iter: T) {
111 self.extend(iter.into_iter().copied().map(NonZeroChar::get));
112 }
113}