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
//!

use crate::NcKey;

/// A received character or event.
///
/// # Default
/// *[`NcReceived::NoInput`]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum NcReceived {
    /// No input was received.
    ///
    /// A `0x00` (NUL) was received, meaning no input.
    NoInput,

    /// A synthesized event was received.
    Key(NcKey),

    /// A valid [`char`] was received.
    Char(char),
}

mod std_impls {
    use crate::{NcInput, NcKey, NcReceived};
    use std::fmt;

    impl Default for NcReceived {
        fn default() -> Self {
            Self::NoInput
        }
    }

    impl fmt::Display for NcReceived {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            use NcReceived::*;
            let string = match self {
                Key(k) => format!["{k}"],
                Char(c) => format!["{c:?}"],
                NoInput => "NoInput".to_string(),
            };
            write!(f, "{}", string)
        }
    }
    impl fmt::Debug for NcReceived {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            use NcReceived::*;
            let string = match self {
                Key(k) => format!["Key({k})"],
                Char(c) => format!["Char({c:?})"],
                NoInput => "NoInput".to_string(),
            };
            write!(f, "NcReceived::{}", string)
        }
    }

    impl From<NcInput> for NcReceived {
        fn from(i: NcInput) -> Self {
            Self::from(i.id)
        }
    }
    impl From<&NcInput> for NcReceived {
        fn from(i: &NcInput) -> Self {
            Self::from(i.id)
        }
    }
    impl From<&mut NcInput> for NcReceived {
        fn from(i: &mut NcInput) -> Self {
            Self::from(i.id)
        }
    }

    impl From<NcReceived> for u32 {
        fn from(r: NcReceived) -> Self {
            use NcReceived::*;
            match r {
                Char(c) => c.into(),
                Key(k) => k.into(),
                NoInput => 0,
            }
        }
    }

    impl From<u32> for NcReceived {
        fn from(num: u32) -> Self {
            use NcReceived::*;
            if num == 0 {
                NoInput
            } else if NcKey::is(num) {
                Key(NcKey::new(num).unwrap())
            } else if let Some(c) = core::char::from_u32(num) {
                Char(c)
            } else {
                unreachable!("NcReceived::from({}) not a char", num);
            }
        }
    }
}