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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! This crate creates the abstraction of `stdio`. They are essentially ring buffer of bytes.
//! It also creates the queue for `KeyEvent`, which allows applications to have direct access
//! to keyboard events.
#![no_std]

extern crate alloc;
extern crate spin;
extern crate core2;
extern crate keycodes_ascii;

use alloc::collections::VecDeque;
use alloc::sync::Arc;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use spin::{Mutex, MutexGuard};
use core2::io::{Read, Write};
use keycodes_ascii::KeyEvent;
use core::ops::Deref;

/// A ring buffer with an EOF mark.
pub struct RingBufferEof<T> {
    /// The ring buffer.
    queue: VecDeque<T>,
    /// The EOF mark. We meet EOF when it equals `true`.
    end: bool
}

/// A reference to a ring buffer with an EOF mark with mutex protection.
pub type RingBufferEofRef<T> = Arc<Mutex<RingBufferEof<T>>>;

/// A ring buffer containing bytes. It forms `stdin`, `stdout` and `stderr`.
/// The two `Arc`s actually point to the same ring buffer. It is designed to prevent
/// interleaved reading but at the same time allow writing to the ring buffer while
/// the reader is holding its lock, and vice versa.
pub struct Stdio {
    /// This prevents interleaved reading.
    read_access: Arc<Mutex<RingBufferEofRef<u8>>>,
    /// This prevents interleaved writing.
    write_access: Arc<Mutex<RingBufferEofRef<u8>>>
}

/// A reader to stdio buffers.
#[derive(Clone)]
pub struct StdioReader {
    /// Inner buffer to support buffered read.
    inner_buf: Box<[u8]>,
    /// The length of actual buffered bytes.
    inner_content_len: usize,
    /// Points to the ring buffer.
    read_access: Arc<Mutex<RingBufferEofRef<u8>>>
}

/// A writer to stdio buffers.
#[derive(Clone)]
pub struct StdioWriter {
    /// Points to the ring buffer.
    write_access: Arc<Mutex<RingBufferEofRef<u8>>>
}

/// `StdioReadGuard` acts like `MutexGuard`, it locks the underlying ring buffer during its
/// lifetime, and provides reading methods to the ring buffer. The lock will be automatically
/// released on dropping of this structure.
pub struct StdioReadGuard<'a> {
    guard: MutexGuard<'a, RingBufferEofRef<u8>>
}

/// `StdioReadGuard` acts like `MutexGuard`, it locks the underlying ring buffer during its
/// lifetime, and provides writing methods to the ring buffer. The lock will be automatically
/// released on dropping of this structure.
pub struct StdioWriteGuard<'a> {
    guard: MutexGuard<'a, RingBufferEofRef<u8>>
}

impl<T> RingBufferEof<T> {
    /// Create a new ring buffer.
    fn new() -> RingBufferEof<T> {
        RingBufferEof {
            queue: VecDeque::new(),
            end: false
        }
    }
}

impl Stdio {
    /// Create a new stdio buffer.
    pub fn new() -> Stdio {
        let ring_buffer = Arc::new(Mutex::new(RingBufferEof::new()));
        Stdio {
            read_access: Arc::new(Mutex::new(Arc::clone(&ring_buffer))),
            write_access: Arc::new(Mutex::new(ring_buffer))
        }
    }

    /// Get a reader to the stdio buffer. Note that each reader has its own
    /// inner buffer. The buffer size is set to be 256 bytes. Resort to
    /// `get_reader_with_buf_capacity` if one needs a different buffer size.
    pub fn get_reader(&self) -> StdioReader {
        StdioReader {
            inner_buf: Box::new([0u8; 256]),
            inner_content_len: 0,
            read_access: Arc::clone(&self.read_access)
        }
    }

    /// Get a reader to the stdio buffer with a customized buffer size.
    /// Note that each reader has its own inner buffer.
    pub fn get_reader_with_buf_capacity(&self, capacity: usize) -> StdioReader {
        let mut inner_buf = Vec::with_capacity(capacity);
        inner_buf.resize(capacity, 0u8);
        StdioReader {
            inner_buf: inner_buf.into_boxed_slice(),
            inner_content_len: 0,
            read_access: Arc::clone(&self.read_access)
        }
    }

    /// Get a writer to the stdio buffer.
    pub fn get_writer(&self) -> StdioWriter {
        StdioWriter {
            write_access: Arc::clone(&self.write_access)
        }
    }
}

impl StdioReader {
    /// Lock the reader and return a guard that can perform reading operation to that buffer.
    /// Note that this lock does not lock the underlying ring buffer. It only excludes other
    /// readr from performing simultaneous read, but does *not* prevent a writer to perform
    /// writing to the underlying ring buffer.
    pub fn lock(&self) -> StdioReadGuard {
        StdioReadGuard {
            guard: self.read_access.lock()
        }
    }

    /// Read a line from the ring buffer and return. Remaining bytes are stored in the inner
    /// buffer. Do NOT use this function alternatively with `read()` method defined in
    /// `StdioReadGuard`. This function returns the number of bytes read. It will return
    /// zero only upon EOF.
    pub fn read_line(&mut self, buf: &mut String) -> Result<usize, core2::io::Error> {
        let mut total_cnt = 0usize;    // total number of bytes read this time
        let mut new_cnt;               // number of bytes returned from a `read()` invocation
        let mut tmp_buf = Vec::new();  // temporary buffer
        let mut line_finished = false; // mark if we have finished a line

        // Copy from the inner buffer. Process the remaining characters from last read first.
        tmp_buf.resize(self.inner_buf.len(), 0);
        tmp_buf[0..self.inner_content_len].clone_from_slice(&self.inner_buf[0..self.inner_content_len]);
        new_cnt = self.inner_content_len;
        self.inner_content_len = 0;

        loop {
            // Try to find an '\n' character.
            let mut cnt_before_new_line = new_cnt;
            for (idx, c) in tmp_buf[0..new_cnt].iter().enumerate() {
                if *c as char == '\n' {
                    cnt_before_new_line = idx + 1;
                    line_finished = true;
                    break;
                }
            }

            // Append new characters to output buffer (until '\n').
            total_cnt += cnt_before_new_line;
            let new_str = String::from_utf8_lossy(&tmp_buf[0..cnt_before_new_line]);
            buf.push_str(&new_str);

            // If we have read a whole line, copy any byte left to inner buffer, and then return.
            if line_finished {
                self.inner_buf[0..new_cnt-cnt_before_new_line].clone_from_slice(&tmp_buf[cnt_before_new_line..new_cnt]);
                self.inner_content_len = new_cnt - cnt_before_new_line;
                return Ok(total_cnt);
            }

            // We have not finished a whole line. Try to read more from the ring buffer, until
            // we hit EOF.
            let mut locked = self.lock();
            new_cnt = locked.read(&mut tmp_buf[..])?;
            if new_cnt == 0 && locked.is_eof() { return Ok(total_cnt); }
        }
    }
}

impl StdioWriter {
    /// Lock the writer and return a guard that can perform writing operation to that buffer.
    /// Note that this lock does not lock the underlying ring buffer. It only excludes other
    /// writer from performing simultaneous write, but does *not* prevent a reader to perform
    /// reading to the underlying ring buffer.
    pub fn lock(&self) -> StdioWriteGuard {
        StdioWriteGuard {
            guard: self.write_access.lock()
        }
    }
}

impl<'a> Read for StdioReadGuard<'a> {
    /// Read from the ring buffer. Returns the number of bytes read. 
    /// 
    /// Currently it is not possible to return an error, 
    /// but one should *not* assume that because it is subject to change in the future.
    /// 
    /// Note that this method will block until at least one byte is available to be read.
    /// It will only return zero under one of two scenarios:
    /// 1. The EOF flag has been set.
    /// 2. The buffer specified was 0 bytes in length.
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, core2::io::Error> {

        // Deal with the edge case that the buffer specified was 0 bytes in length.
        if buf.len() == 0 { return Ok(0); }

        let mut cnt: usize = 0;
        loop {
            let end; // EOF flag
            {
                let mut locked_ring_buf = self.guard.lock();
                let mut buf_iter = buf[cnt..].iter_mut();

                // Keep reading if we have empty space in the output buffer
                // and available byte in the ring buffer.
                while let Some(buf_entry) = buf_iter.next() {
                    if let Some(queue_elem) = locked_ring_buf.queue.pop_front() {
                        *buf_entry = queue_elem;
                        cnt += 1;
                    } else {
                        break;
                    }
                }

                end = locked_ring_buf.end;
            } // the lock on the ring buffer is guaranteed to be dropped here

            // Break if we have read something or we encounter EOF.
            if cnt > 0 || end { break; }
        }
        return Ok(cnt);
    }
}

impl<'a> StdioReadGuard<'a> {
    /// Same as `read()`, but is non-blocking.
    /// 
    /// Returns `Ok(0)` when the underlying buffer is empty.
    pub fn try_read(&mut self, buf: &mut [u8]) -> Result<usize, core2::io::Error> {

        // Deal with the edge case that the buffer specified was 0 bytes in length.
        if buf.len() == 0 { return Ok(0); }

        let mut buf_iter = buf.iter_mut();
        let mut cnt: usize = 0;
        let mut locked_ring_buf = self.guard.lock();

        // Keep reading if we have empty space in the output buffer
        // and available byte(s) in the ring buffer.
        while let Some(buf_entry) = buf_iter.next() {
            if let Some(queue_elem) = locked_ring_buf.queue.pop_front() {
                *buf_entry = queue_elem;
                cnt += 1;
            } else {
                break;
            }
        }

        return Ok(cnt);
    }

    /// Returns the number of bytes still in the read buffer.
    pub fn remaining_bytes(&self) -> usize {
        return self.guard.lock().queue.len();
    }
}

impl<'a> Write for StdioWriteGuard<'a> {
    /// Write to the ring buffer, returniong the number of bytes written.
    /// 
    /// When this method is called after setting the EOF flag, it returns error with `ErrorKind`
    /// set to `UnexpectedEof`.
    /// 
    /// Also note that this method does *not* guarantee to write all given bytes, although it currently
    /// does so. Always check the return value when using this method. Otherwise, use `write_all` to
    /// ensure that all given bytes are written.
    fn write(&mut self, buf: &[u8]) -> Result<usize, core2::io::Error> {
        if self.guard.lock().end {
            return Err(core2::io::Error::new(core2::io::ErrorKind::UnexpectedEof,
                                           "cannot write to a stream with EOF set"));
        }
        let mut locked_ring_buf = self.guard.lock();
        for byte in buf {
            locked_ring_buf.queue.push_back(*byte)
        }
        Ok(buf.len())
    }
    /// The function required by `Write` trait. Currently it performs nothing,
    /// since everything is write directly to the ring buffer in `write` method.
    fn flush(&mut self) -> Result<(), core2::io::Error> {
        Ok(())
    }
}

impl<'a> StdioReadGuard<'a> {
    /// Check if the EOF flag of the queue has been set.
    pub fn is_eof(&self) -> bool {
        self.guard.lock().end
    }
}

impl<'a> StdioWriteGuard<'a> {
    /// Set the EOF flag of the queue to true.
    pub fn set_eof(&mut self) {
        self.guard.lock().end = true;
    }
}

pub struct KeyEventQueue {
    /// A ring buffer storing `KeyEvent`.
    key_event_queue: RingBufferEofRef<KeyEvent>
}

/// A reader to keyevent ring buffer.
#[derive(Clone)]
pub struct KeyEventQueueReader {
    /// Points to the ring buffer storing `KeyEvent`.
    key_event_queue: RingBufferEofRef<KeyEvent>
}

/// A writer to keyevent ring buffer.
#[derive(Clone)]
pub struct KeyEventQueueWriter {
    /// Points to the ring buffer storing `KeyEvent`.
    key_event_queue: RingBufferEofRef<KeyEvent>
}

impl KeyEventQueue {
    /// Create a new ring buffer storing `KeyEvent`.
    pub fn new() -> KeyEventQueue {
        KeyEventQueue {
            key_event_queue: Arc::new(Mutex::new(RingBufferEof::new()))
        }
    }

    /// Get a reader to the ring buffer.
    pub fn get_reader(&self) -> KeyEventQueueReader {
        KeyEventQueueReader {
            key_event_queue: self.key_event_queue.clone()
        }
    }

    /// Get a writer to the ring buffer.
    pub fn get_writer(&self) -> KeyEventQueueWriter {
        KeyEventQueueWriter {
            key_event_queue: self.key_event_queue.clone()
        }
    }
}

impl KeyEventQueueReader {
    /// Try to read a keyevent from the ring buffer. It returns `None` if currently
    /// the ring buffer is empty.
    pub fn read_one(&self) -> Option<KeyEvent> {
        let mut locked_queue = self.key_event_queue.lock();
        locked_queue.queue.pop_front()
    }
}

impl KeyEventQueueWriter {
    /// Push a keyevent into the ring buffer.
    pub fn write_one(&self, key_event: KeyEvent) {
        let mut locked_queue = self.key_event_queue.lock();
        locked_queue.queue.push_back(key_event);
    }
}

/// A structure that allows applications to access keyboard events directly. 
/// When it gets instantiated, it `take`s the reader of the `KeyEventQueue` away from the `shell`, 
/// or whichever entity previously owned the queue.
/// When it goes out of the scope, the taken reader will be automatically returned
/// back to the `shell` or the original owner in its `Drop` routine.
pub struct KeyEventReadGuard {
    /// The taken reader of the `KeyEventQueue`.
    reader: Option<KeyEventQueueReader>,
    /// The closure to be excuted on dropping.
    closure: Box<dyn Fn(&mut Option<KeyEventQueueReader>)>
}

impl KeyEventReadGuard {
    /// Create a new `KeyEventReadGuard`. This function *takes* a reader
    /// to `KeyEventQueue`. Thus, the `reader` will never be `None` until the
    /// `drop()` method.
    pub fn new(
        reader: KeyEventQueueReader,
        closure: Box<dyn Fn(&mut Option<KeyEventQueueReader>)>
    ) -> KeyEventReadGuard {
        KeyEventReadGuard {
            reader: Some(reader),
            closure
        }
    }
}

impl Drop for KeyEventReadGuard {
    /// Returns the reader of `KeyEventQueue` back to the previous owner by executing the closure.
    fn drop(&mut self) {
        (self.closure)(&mut self.reader);
    }
}

impl Deref for KeyEventReadGuard {
    type Target = Option<KeyEventQueueReader>;

    fn deref(&self) -> &Self::Target {
        &self.reader
    }
}