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
extern crate alloc;

use alloc::boxed::Box;
use spinning_top::{Spinlock, SpinlockGuard};

pub use crate::error::{Error, ErrorKind};

pub type Result<T> = core::result::Result<T, Error>;

pub trait Device {
    fn initialize(&mut self) -> Result<()>;
    fn initialized(&self) -> bool;
}

pub trait Write {
    fn write_all(&mut self, buf: &[u8]) -> Result<()>;
}

pub trait ConsoleWriter: Device + Write + Send {}

pub struct Stdout {
    device: Option<Box<dyn ConsoleWriter>>,
}

impl Stdout {
    pub const fn new() -> Self {
        Self { device: None }
    }
    pub fn attach(&mut self, mut device: Box<dyn ConsoleWriter>) -> Result<()> {
        if !device.initialized() {
            device.initialize()?;
        }
        self.device.replace(device);
        Ok(())
    }
}

impl Write for Stdout {
    fn write_all(&mut self, buf: &[u8]) -> Result<()> {
        self.device
            .as_mut()
            .map(|dev| dev.write_all(buf))
            .unwrap_or(Err(Error::new(ErrorKind::NotConnected)))
    }
}

pub fn stdout() -> SpinlockGuard<'static, Stdout> {
    static STDOUT: Spinlock<Stdout> = Spinlock::new(Stdout::new());
    STDOUT.lock()
}

#[cfg(test)]
pub mod test {
    extern crate alloc;
    use crate::io::{ConsoleWriter, Device, Result, Stdout, Write};
    use alloc::boxed::Box;
    use alloc::string::String;
    use alloc::vec::Vec;
    use core::cell::RefCell;

    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()
        }

        pub fn clear(&mut self) {
            self.buffer.borrow_mut().clear()
        }
    }

    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 attach_and_ready() {
        let mock = Box::new(MockDevice::new());
        let mock_ptr = mock.as_ref() as *const MockDevice;
        let mut stdout = Stdout::new();

        assert!(!mock.initialized());

        stdout.attach(mock).ok().unwrap();

        assert!(unsafe { (*mock_ptr).initialized() });
    }

    #[test]
    fn write() {
        let mock = Box::new(MockDevice::new());
        let mock_ptr = mock.as_ref() as *const MockDevice;
        let mut stdout = Stdout::new();

        stdout.attach(mock).ok().unwrap();

        stdout.write_all("Hello ".as_bytes()).ok().unwrap();
        stdout.write_all("World!".as_bytes()).ok().unwrap();
        assert_eq!(unsafe { (*mock_ptr).output() }, "Hello World!");
    }
}