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
//! The `fs` module provides system calls to interact with the file system.

use core::str;

use log::error;

use crate::{
    executor::{yield_now, ControlFlow},
    mem::UserPtr,
    print,
    sbi,
    syscall::SystemCall,
};

const STDIN: usize = 0;
const STDOUT: usize = 1;

impl SystemCall<'_> {
    /// Reads the content from a file descriptor and writes them to a buffer.
    pub async fn sys_read(
        &self,
        fd: usize,
        mut buffer: UserPtr<u8>,
        _length: usize,
    ) -> (isize, ControlFlow) {
        match fd {
            STDIN => {
                let mut char;
                loop {
                    char = sbi::console_getchar();
                    if char == 0 {
                        yield_now().await;
                    } else {
                        break;
                    }
                }
                *buffer = char as u8;
                (1, ControlFlow::Continue)
            }
            _ => {
                error!("the file descriptor {} is not supported in 'sys_write'", fd);
                (-1, ControlFlow::Continue)
            }
        }
    }

    /// Writes the contents of a buffer to a file descriptor.
    pub fn sys_write(&self, fd: usize, buffer: UserPtr<u8>, length: usize) -> (isize, ControlFlow) {
        match fd {
            STDOUT => {
                for buffer in buffer.as_buffer(length) {
                    print!("{}", str::from_utf8(buffer).unwrap());
                }
                (length as isize, ControlFlow::Continue)
            }
            _ => {
                error!("the file descriptor {} is not supported in 'sys_write'", fd);
                (-1, ControlFlow::Continue)
            }
        }
    }
}