This commit is contained in:
Matthias Schiffer 2019-08-09 21:13:19 +02:00
parent 0abdc827c9
commit 69c9e6031a
Signed by: neocturne
GPG key ID: 16EF3F64CB201D9C
4 changed files with 56 additions and 12 deletions

View file

@ -1,2 +1,3 @@
pub mod posix;
pub mod stdio;
pub mod string;

38
src/c/stdio.rs Normal file
View file

@ -0,0 +1,38 @@
use core::fmt;
use super::posix;
use super::string;
pub struct OStream {
file: *mut libc::FILE
}
pub fn stdout() -> OStream {
OStream { file: unsafe { posix::stdout } }
}
impl OStream {
pub fn write(&mut self, b: &[u8]) {
unsafe {
libc::fwrite(
b.as_ptr() as *const libc::c_void,
1,
b.len(),
self.file,
);
}
}
pub fn puts(&mut self, s: &string::CStr) {
unsafe {
libc::fputs(s.as_ptr(), self.file);
}
}
}
impl fmt::Write for OStream {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write(s.as_bytes());
Ok(())
}
}

View file

@ -11,15 +11,14 @@ fn must_succeed<T>(p: *mut T) -> *mut T {
p
}
unsafe fn malloc<T>() -> *mut T {
fn malloc<T>() -> *mut T {
let size = mem::size_of::<T>();
/*if size == 0 {
if size == 0 {
return SENTINEL as *mut T;
}*/
must_succeed(0 as *mut T)
/*must_succeed(
libc::memalign(mem::align_of::<T>() as libc::size_t, size as libc::size_t)
) as *mut T*/
}
must_succeed(
unsafe {libc::memalign(mem::align_of::<T>() as libc::size_t, size as libc::size_t) }
) as *mut T
}
pub struct CBox<T: ?Sized>(*mut T);
@ -46,8 +45,8 @@ impl<T: ?Sized> CBox<T> {
impl<T> CBox<T> {
pub fn new(value: T) -> CBox<T> {
let p = malloc();
unsafe {
let p = malloc();
ptr::write(p, value);
CBox::from_raw(p)
}
@ -56,6 +55,7 @@ impl<T> CBox<T> {
impl<T: ?Sized> Drop for CBox<T> {
fn drop(&mut self) {
unsafe { ptr::drop_in_place(self.0); }
let p = self.0 as *mut libc::c_void;
if p != SENTINEL {
unsafe { libc::free(p); }

View file

@ -5,11 +5,16 @@ extern crate libc;
mod c;
use core::fmt::Write;
#[no_mangle]
pub extern fn main(_nargs: libc::c_int, _args: *const *const libc::c_char) -> libc::c_int {
let foo = cstr!("Foo! %p\n");
let x = c::string::CBox::new(());
unsafe { libc::printf(foo.as_ptr(), &*x as *const ()); }
pub extern "C" fn main(_nargs: libc::c_int, _args: *const *const libc::c_char) -> libc::c_int {
let x = c::string::CString::from("foo");
let y = c::string::CBox::new(x);
//let foo = cstr!("Foo! %p\n");
//c::stdio::stdout().puts(foo);
let mut stdout = c::stdio::stdout();
writeln!(stdout, "Foo: {}", 42);
0
}