libnotcurses_sys/input/
received.rs

1//!
2
3use crate::NcKey;
4
5/// A received character or event.
6///
7/// # Default
8/// *[`NcReceived::NoInput`]
9#[derive(Clone, Copy, PartialEq, Eq)]
10pub enum NcReceived {
11    /// No input was received.
12    ///
13    /// A `0x00` (NUL) was received, meaning no input.
14    NoInput,
15
16    /// A synthesized event was received.
17    Key(NcKey),
18
19    /// A valid [`char`] was received.
20    Char(char),
21}
22
23mod core_impls {
24    use core::fmt;
25
26    #[cfg(not(feature = "std"))]
27    use alloc::{format, string::ToString};
28
29    use crate::{NcInput, NcKey, NcReceived};
30
31    impl Default for NcReceived {
32        fn default() -> Self {
33            Self::NoInput
34        }
35    }
36
37    impl fmt::Display for NcReceived {
38        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39            use NcReceived::*;
40            let string = match self {
41                Key(k) => format!["{k}"],
42                Char(c) => format!["{c:?}"],
43                NoInput => "NoInput".to_string(),
44            };
45            write!(f, "{}", string)
46        }
47    }
48    impl fmt::Debug for NcReceived {
49        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50            use NcReceived::*;
51            let string = match self {
52                Key(k) => format!["Key({k})"],
53                Char(c) => format!["Char({c:?})"],
54                NoInput => "NoInput".to_string(),
55            };
56            write!(f, "NcReceived::{}", string)
57        }
58    }
59
60    impl From<NcInput> for NcReceived {
61        fn from(i: NcInput) -> Self {
62            Self::from(i.id)
63        }
64    }
65    impl From<&NcInput> for NcReceived {
66        fn from(i: &NcInput) -> Self {
67            Self::from(i.id)
68        }
69    }
70    impl From<&mut NcInput> for NcReceived {
71        fn from(i: &mut NcInput) -> Self {
72            Self::from(i.id)
73        }
74    }
75
76    impl From<NcReceived> for u32 {
77        fn from(r: NcReceived) -> Self {
78            use NcReceived::*;
79            match r {
80                Char(c) => c.into(),
81                Key(k) => k.into(),
82                NoInput => 0,
83            }
84        }
85    }
86
87    impl From<u32> for NcReceived {
88        fn from(num: u32) -> Self {
89            use NcReceived::*;
90            if num == 0 {
91                NoInput
92            } else if NcKey::is(num) {
93                Key(NcKey::new(num).unwrap())
94            } else if let Some(c) = core::char::from_u32(num) {
95                Char(c)
96            } else {
97                unreachable!("NcReceived::from({}) not a char", num);
98            }
99        }
100    }
101}