diff options
-rw-r--r-- | src/c/mod.rs | 1 | ||||
-rw-r--r-- | src/c/stdio.rs | 38 | ||||
-rw-r--r-- | src/c/string.rs | 16 | ||||
-rw-r--r-- | src/main.rs | 13 |
4 files changed, 56 insertions, 12 deletions
diff --git a/src/c/mod.rs b/src/c/mod.rs index 1b643c4..3694561 100644 --- a/src/c/mod.rs +++ b/src/c/mod.rs @@ -1,2 +1,3 @@ pub mod posix; +pub mod stdio; pub mod string; diff --git a/src/c/stdio.rs b/src/c/stdio.rs new file mode 100644 index 0000000..aa824ed --- /dev/null +++ b/src/c/stdio.rs @@ -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(()) + } +} diff --git a/src/c/string.rs b/src/c/string.rs index 8babef6..d0e620c 100644 --- a/src/c/string.rs +++ b/src/c/string.rs @@ -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); } diff --git a/src/main.rs b/src/main.rs index 7cdfb3f..15a2640 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 } |