This commit is contained in:
nora 2023-09-30 12:18:47 +02:00
parent 5673cf51db
commit ae189e8b18
3 changed files with 79 additions and 1 deletions

View file

@ -1,3 +1,5 @@
pub mod stream;
use core::ffi::c_char; use core::ffi::c_char;
use crate::sys::syscall; use crate::sys::syscall;

50
libuwuc/src/io/stream.rs Normal file
View file

@ -0,0 +1,50 @@
use core::ffi::c_int;
use super::EOF;
/// A `FILE`.
#[repr(C)]
pub struct FileStream {
fd: c_int,
}
impl FileStream {
pub const fn from_raw_fd(fd: c_int) -> Self {
Self { fd }
}
fn write_byte(&self, c: u8) -> Result<(), i32> {
unsafe { super::write_all(self.fd, &[c]).map_err(|e| e as _) }
}
}
pub fn fputc(c: u8, stream: &FileStream) -> i32 {
match stream.write_byte(c) {
Ok(_) => c as _,
Err(_) => EOF,
}
}
pub unsafe fn fwrite(ptr: *const u8, size: usize, nitems: usize, stream: &FileStream) -> usize {
if nitems == 0 {
return 0;
}
for i in 0..nitems {
unsafe {
let ptr = ptr.add(i * size);
for j in 0..size {
let ptr = ptr.add(j);
let result = stream.write_byte(ptr.read());
match result {
Ok(()) => {}
Err(_) => {
return i;
}
}
}
}
}
nitems
}

View file

@ -1,6 +1,32 @@
use core::ffi::c_char; use core::ffi::{c_char, c_int};
use libuwuc::io::{stream::FileStream, STDERR, STDIN, STDOUT};
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn puts(s: *const c_char) -> i32 { pub unsafe extern "C" fn puts(s: *const c_char) -> i32 {
libuwuc::io::puts(s) libuwuc::io::puts(s)
} }
// STREAMS:
#[no_mangle]
pub static stdin: &FileStream = &FileStream::from_raw_fd(STDIN);
#[no_mangle]
pub static stdout: &FileStream = &FileStream::from_raw_fd(STDOUT);
#[no_mangle]
pub static stderr: &FileStream = &FileStream::from_raw_fd(STDERR);
#[no_mangle]
pub unsafe extern "C" fn fputc(c: c_int, stream: *mut FileStream) -> c_int {
libuwuc::io::stream::fputc(c as u8, &*stream)
}
#[no_mangle]
pub unsafe extern "C" fn fwrite(
ptr: *const u8,
size: usize,
nitems: usize,
stream: &FileStream,
) -> usize {
libuwuc::io::stream::fwrite(ptr, size, nitems, stream)
}