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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// TODO: Expands to cover args, ret
#[macro_export]
macro_rules! define_interface {
    (command {$($variant:ident = $val:expr),*,}) => {
        $(pub const $variant: usize = $val;)*
        pub fn to_str(code: usize) ->  alloc::string::String {
            use alloc::string::ToString;
            use alloc::format;
            match code {
                $($variant => stringify!($variant).to_string()),*,
                _ =>  format!("Undefined {}", code)
            }
        }
    };
}

#[macro_export]
macro_rules! print {
    ($($arg:tt)*) => {
        let buffer = alloc::format!($($arg)*);
        let _ = io::stdout().write_all(buffer.as_bytes());
    };
}

#[macro_export]
macro_rules! println {
    () => {crate::print!("\n")};
    ($fmt:expr) => {crate::print!(concat!($fmt, "\n"))};
    ($fmt:expr, $($arg:tt)*) => {crate::print!(concat!($fmt, "\n"), $($arg)*)};
}

#[macro_export]
macro_rules! eprint {
    ($fmt:expr) => {
        let buffer = concat!("\x1b[0;31m", $fmt, "\x1b[0m");
        let _ = io::stdout().write_all(buffer.as_bytes());
    };
    ($fmt:expr, $($arg:tt)*) => {{
        let buffer = alloc::format!(concat!("\x1b[0;31m", $fmt, "\x1b[0m"), $($arg)*);
        let _ = io::stdout().write_all(buffer.as_bytes());
    }};
}

#[macro_export]
macro_rules! eprintln {
    () => {crate::eprint!("\n")};
    ($fmt:expr) => {crate::eprint!(concat!($fmt, "\n"))};
    ($fmt:expr, $($arg:tt)*) => {crate::eprint!(concat!($fmt, "\n"), $($arg)*)};
}

#[macro_export]
macro_rules! const_assert {
    ($cond:expr) => {
        // Causes overflow if condition is false
        let _ = [(); 0 - (!($cond) as usize)];
    };
}

#[macro_export]
macro_rules! const_assert_eq {
    ($left:expr, $right:expr) => {
        const _: () = {
            crate::const_assert!($left == $right);
        };
    };
}

#[macro_export]
macro_rules! const_assert_size {
    ($struct:ty, $size:expr) => {
        crate::const_assert_eq!(core::mem::size_of::<$struct>(), ($size));
    };
}

#[cfg(test)]
mod test {
    extern crate alloc;

    use crate::{eprintln, println};
    use alloc::boxed::Box;
    use alloc::string::String;
    use alloc::vec::Vec;
    use core::cell::RefCell;
    use io::{stdout, Write as IoWrite};
    use io::{ConsoleWriter, Device, Result, Write};

    pub struct MockDevice {
        buffer: RefCell<Vec<u8>>,
        ready: bool,
    }

    impl MockDevice {
        pub const fn new() -> Self {
            MockDevice {
                buffer: RefCell::new(Vec::new()),
                ready: false,
            }
        }

        pub fn output(&self) -> String {
            String::from_utf8(self.buffer.borrow().to_vec()).unwrap()
        }
    }

    impl Device for MockDevice {
        fn initialize(&mut self) -> Result<()> {
            self.ready = true;
            Ok(())
        }

        fn initialized(&self) -> bool {
            self.ready
        }
    }

    impl Write for MockDevice {
        fn write_all(&mut self, buf: &[u8]) -> Result<()> {
            self.buffer.borrow_mut().extend_from_slice(buf);
            Ok(())
        }
    }

    impl ConsoleWriter for MockDevice {}

    #[test]
    fn println_without_arg() {
        let mock = Box::new(MockDevice::new());
        let mock_ptr = mock.as_ref() as *const MockDevice;
        stdout().attach(mock).ok().unwrap();

        println!();

        assert_eq!(unsafe { (*mock_ptr).output() }, "\n");
    }

    #[test]
    fn println_without_format() {
        let mock = Box::new(MockDevice::new());
        let mock_ptr = mock.as_ref() as *const MockDevice;
        stdout().attach(mock).ok().unwrap();

        println!("hello");
        assert_eq!(unsafe { (*mock_ptr).output() }, "hello\n");
    }

    #[test]
    fn println_with_format() {
        let mock = Box::new(MockDevice::new());
        let mock_ptr = mock.as_ref() as *const MockDevice;
        stdout().attach(mock).ok().unwrap();

        println!("number {}", 1234);
        assert_eq!(unsafe { (*mock_ptr).output() }, "number 1234\n");
    }

    #[test]
    fn eprintln_without_arg() {
        let mock = Box::new(MockDevice::new());
        let mock_ptr = mock.as_ref() as *const MockDevice;
        stdout().attach(mock).ok().unwrap();

        eprintln!();
        assert_eq!(unsafe { (*mock_ptr).output() }, "\x1b[0;31m\n\x1b[0m");
    }

    #[test]
    fn eprintln_without_format() {
        let mock = Box::new(MockDevice::new());
        let mock_ptr = mock.as_ref() as *const MockDevice;
        stdout().attach(mock).ok().unwrap();

        eprintln!("hello");
        assert_eq!(unsafe { (*mock_ptr).output() }, "\x1b[0;31mhello\n\x1b[0m");
    }

    #[test]
    fn eprintln_with_format() {
        let mock = Box::new(MockDevice::new());
        let mock_ptr = mock.as_ref() as *const MockDevice;
        stdout().attach(mock).ok().unwrap();

        eprintln!("number {}", 4321);
        assert_eq!(
            unsafe { (*mock_ptr).output() },
            "\x1b[0;31mnumber 4321\n\x1b[0m"
        );
    }

    #[test]
    fn set_of_const_assert() {
        const_assert!(1 != 2);
        const_assert!(true);

        const_assert_eq!(1, 1);
        const_assert_eq!(false, false);

        const_assert_size!(u32, 4);
        const_assert_size!(u64, 8);
    }
}