This commit is contained in:
Jeremy Soller
2018-11-25 10:34:42 -07:00
parent a5279b648f
commit 0ac16556bc
24 changed files with 474 additions and 349 deletions
+1 -1
View File
@@ -6,8 +6,8 @@ use header::fcntl::*;
use header::string::strchr;
use io::LineWriter;
use mutex::Mutex;
use platform::types::*;
use platform;
use platform::types::*;
use super::constants::*;
use super::{Buffer, FILE};
+67 -55
View File
@@ -6,20 +6,20 @@ use alloc::vec::Vec;
use core::fmt;
use core::fmt::Write as WriteFmt;
use core::ops::{Deref, DerefMut};
use core::{ptr, str, slice};
use core::{ptr, slice, str};
use va_list::VaList as va_list;
use c_str::CStr;
use fs::File;
use header::errno::{self, STR_ERROR};
use header::{fcntl, stdlib, unistd};
use header::string::strlen;
use header::{fcntl, stdlib, unistd};
use io::{self, BufRead, LineWriter, Read, Write};
use mutex::Mutex;
use platform::types::*;
use platform::{Pal, Sys};
use platform::{errno, WriteByte};
use platform;
use platform::types::*;
use platform::{errno, WriteByte};
use platform::{Pal, Sys};
pub use self::constants::*;
mod constants;
@@ -34,7 +34,7 @@ mod scanf;
enum Buffer<'a> {
Borrowed(&'a mut [u8]),
Owned(Vec<u8>)
Owned(Vec<u8>),
}
impl<'a> Deref for Buffer<'a> {
type Target = [u8];
@@ -42,7 +42,7 @@ impl<'a> Deref for Buffer<'a> {
fn deref(&self) -> &Self::Target {
match self {
Buffer::Borrowed(inner) => inner,
Buffer::Owned(inner) => inner.borrow()
Buffer::Owned(inner) => inner.borrow(),
}
}
}
@@ -50,7 +50,7 @@ impl<'a> DerefMut for Buffer<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Buffer::Borrowed(inner) => inner,
Buffer::Owned(inner) => inner.borrow_mut()
Buffer::Owned(inner) => inner.borrow_mut(),
}
}
}
@@ -61,12 +61,12 @@ pub struct FILE {
lock: Mutex<()>,
file: File,
pub(crate) /* stdio_ext */ flags: c_int,
pub(crate) flags: c_int,
read_buf: Buffer<'static>,
read_pos: usize,
read_size: usize,
unget: Option<u8>,
pub(crate) /* stdio_ext */ writer: LineWriter<File>,
pub(crate) writer: LineWriter<File>,
// Optional pid for use with popen/pclose
pid: Option<c_int>,
@@ -99,7 +99,7 @@ impl BufRead for FILE {
Ok(0) => {
self.flags |= F_EOF;
0
},
}
Ok(n) => n,
Err(err) => {
self.flags |= F_ERR;
@@ -143,9 +143,7 @@ impl WriteFmt for FILE {
}
impl WriteByte for FILE {
fn write_u8(&mut self, c: u8) -> fmt::Result {
self.write_all(&[c])
.map(|_| ())
.map_err(|_| fmt::Error)
self.write_all(&[c]).map(|_| ()).map_err(|_| fmt::Error)
}
}
impl FILE {
@@ -202,7 +200,9 @@ pub extern "C" fn cuserid(_s: *mut c_char) -> *mut c_char {
#[no_mangle]
pub extern "C" fn fclose(stream: *mut FILE) -> c_int {
let stream = unsafe { &mut *stream };
unsafe { flockfile(stream); }
unsafe {
flockfile(stream);
}
let mut r = stream.flush().is_err();
let close = Sys::close(*stream.file) < 0;
@@ -214,7 +214,9 @@ pub extern "C" fn fclose(stream: *mut FILE) -> c_int {
// Reference files aren't closed on drop, so pretend to be a reference
stream.file.reference = true;
} else {
unsafe { funlockfile(stream); }
unsafe {
funlockfile(stream);
}
}
r as c_int
@@ -302,7 +304,7 @@ pub extern "C" fn fgets(original: *mut c_char, max: c_int, stream: *mut FILE) ->
let (read, exit) = {
let mut buf = match stream.fill_buf() {
Ok(buf) => buf,
Err(_) => return ptr::null_mut()
Err(_) => return ptr::null_mut(),
};
if buf.is_empty() {
break;
@@ -409,17 +411,19 @@ pub extern "C" fn fputs(s: *const c_char, stream: *mut FILE) -> c_int {
/// Read `nitems` of size `size` into `ptr` from `stream`
#[no_mangle]
pub extern "C" fn fread(ptr: *mut c_void, size: size_t, count: size_t, stream: *mut FILE) -> size_t {
pub extern "C" fn fread(
ptr: *mut c_void,
size: size_t,
count: size_t,
stream: *mut FILE,
) -> size_t {
let mut stream = unsafe { &mut *stream }.lock();
let buf = unsafe { slice::from_raw_parts_mut(
ptr as *mut u8,
size as usize * count as usize
) };
let buf = unsafe { slice::from_raw_parts_mut(ptr as *mut u8, size as usize * count as usize) };
let mut read = 0;
while read < buf.len() {
match stream.read(&mut buf[read..]) {
Ok(0) | Err(_) => break,
Ok(n) => read += n
Ok(n) => read += n,
}
}
(read / size as usize) as size_t
@@ -432,7 +436,9 @@ pub extern "C" fn freopen(
stream: &mut FILE,
) -> *mut FILE {
let mut flags = unsafe { helpers::parse_mode_flags(mode) };
unsafe { flockfile(stream); }
unsafe {
flockfile(stream);
}
let _ = stream.flush();
if filename.is_null() {
@@ -442,14 +448,18 @@ pub extern "C" fn freopen(
}
flags &= !(fcntl::O_CREAT | fcntl::O_EXCL | fcntl::O_CLOEXEC);
if fcntl::sys_fcntl(*stream.file, fcntl::F_SETFL, flags) < 0 {
unsafe { funlockfile(stream); }
unsafe {
funlockfile(stream);
}
fclose(stream);
return ptr::null_mut();
}
} else {
let new = fopen(filename, mode);
if new.is_null() {
unsafe { funlockfile(stream); }
unsafe {
funlockfile(stream);
}
fclose(stream);
return ptr::null_mut();
}
@@ -459,7 +469,9 @@ pub extern "C" fn freopen(
} else if Sys::dup2(*new.file, *stream.file) < 0
|| fcntl::sys_fcntl(*stream.file, fcntl::F_SETFL, flags & fcntl::O_CLOEXEC) < 0
{
unsafe { funlockfile(stream); }
unsafe {
funlockfile(stream);
}
fclose(new);
fclose(stream);
return ptr::null_mut();
@@ -467,7 +479,9 @@ pub extern "C" fn freopen(
stream.flags = (stream.flags & constants::F_PERM) | new.flags;
fclose(new);
}
unsafe { funlockfile(stream); }
unsafe {
funlockfile(stream);
}
stream
}
@@ -527,7 +541,11 @@ pub extern "C" fn ftello(stream: *mut FILE) -> off_t {
/// Try to lock the file. Returns 0 for success, 1 for failure
#[no_mangle]
pub unsafe extern "C" fn ftrylockfile(file: *mut FILE) -> c_int {
if (*file).lock.manual_try_lock().is_ok() { 0 } else { 1 }
if (*file).lock.manual_try_lock().is_ok() {
0
} else {
1
}
}
/// Unlock the file
@@ -538,17 +556,19 @@ pub unsafe extern "C" fn funlockfile(file: *mut FILE) {
/// Write `nitems` of size `size` from `ptr` to `stream`
#[no_mangle]
pub extern "C" fn fwrite(ptr: *const c_void, size: usize, count: usize, stream: *mut FILE) -> usize {
pub extern "C" fn fwrite(
ptr: *const c_void,
size: usize,
count: usize,
stream: *mut FILE,
) -> usize {
let mut stream = unsafe { &mut *stream }.lock();
let buf = unsafe { slice::from_raw_parts_mut(
ptr as *mut u8,
size as usize * count as usize
) };
let buf = unsafe { slice::from_raw_parts_mut(ptr as *mut u8, size as usize * count as usize) };
let mut written = 0;
while written < buf.len() {
match stream.write(&mut buf[written..]) {
Ok(0) | Err(_) => break,
Ok(n) => written += n
Ok(n) => written += n,
}
}
(written / size as usize) as size_t
@@ -574,7 +594,7 @@ pub extern "C" fn getc_unlocked(stream: *mut FILE) -> c_int {
match unsafe { &mut *stream }.read(&mut buf) {
Ok(0) | Err(_) => EOF,
Ok(_) => buf[0] as c_int
Ok(_) => buf[0] as c_int,
}
}
@@ -599,7 +619,7 @@ pub extern "C" fn getw(stream: *mut FILE) -> c_int {
&mut ret as *mut _ as *mut c_void,
mem::size_of_val(&ret),
1,
stream
stream,
) > 0
{
ret
@@ -717,18 +737,10 @@ pub unsafe extern "C" fn popen(command: *const c_char, mode: *const c_char) -> *
} else if child_pid > 0 {
let (fd, fd_mode) = if write {
unistd::close(pipes[0]);
(pipes[1], if cloexec {
c_str!("we")
} else {
c_str!("w")
})
(pipes[1], if cloexec { c_str!("we") } else { c_str!("w") })
} else {
unistd::close(pipes[1]);
(pipes[0], if cloexec {
c_str!("re")
} else {
c_str!("r")
})
(pipes[0], if cloexec { c_str!("re") } else { c_str!("r") })
};
if let Some(f) = helpers::_fdopen(fd, fd_mode.as_ptr()) {
@@ -827,7 +839,12 @@ pub extern "C" fn setbuf(stream: *mut FILE, buf: *mut c_char) {
/// Reset `stream` to use buffer `buf` of size `size`
/// If this isn't the meaning of unsafe, idk what is
#[no_mangle]
pub extern "C" fn setvbuf(stream: *mut FILE, buf: *mut c_char, mode: c_int, mut size: size_t) -> c_int {
pub extern "C" fn setvbuf(
stream: *mut FILE,
buf: *mut c_char,
mode: c_int,
mut size: size_t,
) -> c_int {
let mut stream = unsafe { &mut *stream }.lock();
// Set a buffer of size `size` if no buffer is given
stream.read_buf = if buf.is_null() || size == 0 {
@@ -838,14 +855,9 @@ pub extern "C" fn setvbuf(stream: *mut FILE, buf: *mut c_char, mode: c_int, mut
// if mode == _IONBF {
// } else {
Buffer::Owned(vec![0; size as usize])
// }
// }
} else {
unsafe {
Buffer::Borrowed(slice::from_raw_parts_mut(
buf as *mut u8,
size
))
}
unsafe { Buffer::Borrowed(slice::from_raw_parts_mut(buf as *mut u8, size)) }
};
stream.flags |= F_SVB;
0
+79 -54
View File
@@ -81,14 +81,14 @@ impl IntoUsize for f64 {
struct BufferedVaList {
list: VaList,
buf: Vec<usize>,
i: usize
i: usize,
}
impl BufferedVaList {
fn new(list: VaList) -> Self {
Self {
list,
buf: Vec::new(),
i: 0
i: 0,
}
}
unsafe fn get<T: VaPrimitive + IntoUsize>(&mut self, i: Option<usize>) -> T {
@@ -143,7 +143,7 @@ unsafe fn pop_int(format: &mut *const u8, ap: &mut BufferedVaList) -> Option<usi
if let Some(i) = pop_int_raw(&mut format2) {
if *format2 == b'$' {
*format = format2.offset(1);
return Some(ap.index::<usize>(i))
return Some(ap.index::<usize>(i));
}
}
@@ -153,17 +153,23 @@ unsafe fn pop_int(format: &mut *const u8, ap: &mut BufferedVaList) -> Option<usi
}
}
unsafe fn fmt_int<I>(fmt: u8, i: I) -> String
where I: fmt::Display + fmt::Octal + fmt::LowerHex + fmt::UpperHex
where
I: fmt::Display + fmt::Octal + fmt::LowerHex + fmt::UpperHex,
{
match fmt {
b'o' => format!("{:o}", i),
b'u' => i.to_string(),
b'x' => format!("{:x}", i),
b'X' => format!("{:X}", i),
_ => panic!("fmt_int should never be called with the fmt {}", fmt)
_ => panic!("fmt_int should never be called with the fmt {}", fmt),
}
}
fn pad<W: Write>(w: &mut W, current_side: bool, pad_char: u8, range: Range<usize>) -> io::Result<()> {
fn pad<W: Write>(
w: &mut W,
current_side: bool,
pad_char: u8,
range: Range<usize>,
) -> io::Result<()> {
if current_side {
for _ in range {
w.write_all(&[pad_char])?;
@@ -207,7 +213,10 @@ fn fmt_float_exp<W: Write>(
exp -= 1;
}
if range.map(|(start, end)| exp >= start && exp < end).unwrap_or(false) {
if range
.map(|(start, end)| exp >= start && exp < end)
.unwrap_or(false)
{
return Ok(false);
}
@@ -294,7 +303,7 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
b'-' => left = true,
b' ' => sign_reserve = true,
b'+' => sign_always = true,
_ => break
_ => break,
}
format = format.offset(1);
}
@@ -304,31 +313,35 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
let precision = if *format == b'.' {
format = format.offset(1);
match pop_int(&mut format, &mut ap) {
int@Some(_) => int,
None => return Ok(-1)
int @ Some(_) => int,
None => return Ok(-1),
}
} else {
None
};
let pad_space = if zero { 0 } else { min_width };
let pad_zero = if zero { min_width } else { 0 };
let pad_zero = if zero { min_width } else { 0 };
// Integer size:
let mut kind = IntKind::Int;
loop {
kind = match *format {
b'h' => if kind == IntKind::Short || kind == IntKind::Byte {
IntKind::Byte
} else {
IntKind::Short
},
b'h' => {
if kind == IntKind::Short || kind == IntKind::Byte {
IntKind::Byte
} else {
IntKind::Short
}
}
b'j' => IntKind::IntMax,
b'l' => if kind == IntKind::Long || kind == IntKind::LongLong {
IntKind::LongLong
} else {
IntKind::Long
},
b'l' => {
if kind == IntKind::Long || kind == IntKind::LongLong {
IntKind::LongLong
} else {
IntKind::Long
}
}
b'q' | b'L' => IntKind::LongLong,
b't' => IntKind::PtrDiff,
b'z' => IntKind::Size,
@@ -346,14 +359,14 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
// VaList does not seem to support these two:
// IntKind::Byte => ap.get::<c_char>(index).to_string(),
// IntKind::Short => ap.get::<c_short>(index).to_string(),
IntKind::Byte => (ap.get::<c_int>(index) as c_char).to_string(),
IntKind::Short => (ap.get::<c_int>(index) as c_short).to_string(),
IntKind::Int => ap.get::<c_int>(index).to_string(),
IntKind::Long => ap.get::<c_long>(index).to_string(),
IntKind::Byte => (ap.get::<c_int>(index) as c_char).to_string(),
IntKind::Short => (ap.get::<c_int>(index) as c_short).to_string(),
IntKind::Int => ap.get::<c_int>(index).to_string(),
IntKind::Long => ap.get::<c_long>(index).to_string(),
IntKind::LongLong => ap.get::<c_longlong>(index).to_string(),
IntKind::PtrDiff => ap.get::<ptrdiff_t>(index).to_string(),
IntKind::Size => ap.get::<ssize_t>(index).to_string(),
IntKind::IntMax => ap.get::<intmax_t>(index).to_string(),
IntKind::PtrDiff => ap.get::<ptrdiff_t>(index).to_string(),
IntKind::Size => ap.get::<ssize_t>(index).to_string(),
IntKind::IntMax => ap.get::<intmax_t>(index).to_string(),
};
let positive = !string.starts_with('-');
let zero = precision == Some(0) && string == "0";
@@ -388,21 +401,21 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
}
pad(w, left, b' ', final_len..pad_space)?;
},
}
b'o' | b'u' | b'x' | b'X' => {
let fmt = *format;
let string = match kind {
// VaList does not seem to support these two:
// IntKind::Byte => fmt_int(kind ap.get::<c_char>(index)),
// IntKind::Short => fmt_int(kind ap.get::<c_short>(index)),
IntKind::Byte => fmt_int(fmt, ap.get::<c_uint>(index) as c_uchar),
IntKind::Short => fmt_int(fmt, ap.get::<c_uint>(index) as c_ushort),
IntKind::Int => fmt_int(fmt, ap.get::<c_uint>(index)),
IntKind::Long => fmt_int(fmt, ap.get::<c_ulong>(index)),
IntKind::Byte => fmt_int(fmt, ap.get::<c_uint>(index) as c_uchar),
IntKind::Short => fmt_int(fmt, ap.get::<c_uint>(index) as c_ushort),
IntKind::Int => fmt_int(fmt, ap.get::<c_uint>(index)),
IntKind::Long => fmt_int(fmt, ap.get::<c_ulong>(index)),
IntKind::LongLong => fmt_int(fmt, ap.get::<c_ulonglong>(index)),
IntKind::PtrDiff => fmt_int(fmt, ap.get::<ptrdiff_t>(index)),
IntKind::Size => fmt_int(fmt, ap.get::<size_t>(index)),
IntKind::IntMax => fmt_int(fmt, ap.get::<uintmax_t>(index)),
IntKind::PtrDiff => fmt_int(fmt, ap.get::<ptrdiff_t>(index)),
IntKind::Size => fmt_int(fmt, ap.get::<size_t>(index)),
IntKind::IntMax => fmt_int(fmt, ap.get::<uintmax_t>(index)),
};
let zero = precision == Some(0) && string == "0";
@@ -411,15 +424,16 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
let no_precision = precision.map(|pad| pad < string.len()).unwrap_or(true);
let mut len = string.len();
let mut final_len = string.len().max(precision.unwrap_or(0)) +
if alternate && string != "0" {
let mut final_len = string.len().max(precision.unwrap_or(0))
+ if alternate && string != "0" {
match fmt {
b'o' if no_precision => 1,
b'x' |
b'X' => 2,
_ => 0
b'x' | b'X' => 2,
_ => 0,
}
} else { 0 };
} else {
0
};
if zero {
len = 0;
@@ -433,7 +447,7 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
b'o' if no_precision => w.write_all(&[b'0'])?,
b'x' => w.write_all(&[b'0', b'x'])?,
b'X' => w.write_all(&[b'0', b'X'])?,
_ => ()
_ => (),
}
}
pad(w, true, b'0', len..precision.unwrap_or(pad_zero))?;
@@ -443,27 +457,38 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
}
pad(w, left, b' ', final_len..pad_space)?;
},
}
b'e' | b'E' => {
let exp_fmt = *format;
let mut float = ap.get::<c_double>(index);
let precision = precision.unwrap_or(6);
fmt_float_exp(w, exp_fmt, None, false, precision, float, left, pad_space, pad_zero)?;
},
fmt_float_exp(
w, exp_fmt, None, false, precision, float, left, pad_space, pad_zero,
)?;
}
b'f' | b'F' => {
let mut float = ap.get::<c_double>(index);
let precision = precision.unwrap_or(6);
fmt_float_normal(w, false, precision, float, left, pad_space, pad_zero)?;
},
}
b'g' | b'G' => {
let exp_fmt = b'E' | (*format & 32);
let mut float = ap.get::<c_double>(index);
let precision = precision.unwrap_or(6);
if !fmt_float_exp(w, exp_fmt, Some((-4, precision as isize)), true,
precision, float, left, pad_space, pad_zero)? {
if !fmt_float_exp(
w,
exp_fmt,
Some((-4, precision as isize)),
true,
precision,
float,
left,
pad_space,
pad_zero,
)? {
fmt_float_normal(w, true, precision, float, left, pad_space, pad_zero)?;
}
}
@@ -486,7 +511,7 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
w.write_all(slice::from_raw_parts(ptr as *const u8, len))?;
pad(w, left, b' ', len..pad_space)?;
}
},
}
b'c' => {
// if kind == IntKind::Long || kind == IntKind::LongLong, handle wint_t
@@ -495,7 +520,7 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
pad(w, !left, b' ', 1..pad_space)?;
w.write_all(&[c as u8])?;
pad(w, left, b' ', 1..pad_space)?;
},
}
b'p' => {
let ptr = ap.get::<*const c_void>(index);
@@ -517,12 +542,12 @@ unsafe fn inner_printf<W: Write>(w: W, format: *const c_char, ap: VaList) -> io:
write!(w, "0x{:x}", ptr as usize)?;
}
pad(w, left, b' ', len..pad_space)?;
},
}
b'n' => {
let ptr = ap.get::<*mut c_int>(index);
*ptr = w.written as c_int;
},
_ => return Ok(-1)
}
_ => return Ok(-1),
}
}
format = format.offset(1);
+63 -45
View File
@@ -117,17 +117,21 @@ unsafe fn inner_scanf<R: Read>(
let mut kind = IntKind::Int;
loop {
kind = match c {
b'h' => if kind == IntKind::Short || kind == IntKind::Byte {
IntKind::Byte
} else {
IntKind::Short
},
b'h' => {
if kind == IntKind::Short || kind == IntKind::Byte {
IntKind::Byte
} else {
IntKind::Short
}
}
b'j' => IntKind::IntMax,
b'l' => if kind == IntKind::Long || kind == IntKind::LongLong {
IntKind::LongLong
} else {
IntKind::Long
},
b'l' => {
if kind == IntKind::Long || kind == IntKind::LongLong {
IntKind::LongLong
} else {
IntKind::Long
}
}
b'q' | b'L' => IntKind::LongLong,
b't' => IntKind::PtrDiff,
b'z' => IntKind::Size,
@@ -268,42 +272,56 @@ unsafe fn inner_scanf<R: Read>(
let unsigned = c == b'o' || c == b'u' || c == b'x' || c == b'X';
match kind {
IntKind::Byte => if unsigned {
parse_type!(c_uchar);
} else {
parse_type!(c_char);
},
IntKind::Short => if unsigned {
parse_type!(c_ushort)
} else {
parse_type!(c_short)
},
IntKind::Int => if unsigned {
parse_type!(c_uint)
} else {
parse_type!(c_int)
},
IntKind::Long => if unsigned {
parse_type!(c_ulong)
} else {
parse_type!(c_long)
},
IntKind::LongLong => if unsigned {
parse_type!(c_ulonglong)
} else {
parse_type!(c_longlong)
},
IntKind::IntMax => if unsigned {
parse_type!(uintmax_t)
} else {
parse_type!(intmax_t)
},
IntKind::Byte => {
if unsigned {
parse_type!(c_uchar);
} else {
parse_type!(c_char);
}
}
IntKind::Short => {
if unsigned {
parse_type!(c_ushort)
} else {
parse_type!(c_short)
}
}
IntKind::Int => {
if unsigned {
parse_type!(c_uint)
} else {
parse_type!(c_int)
}
}
IntKind::Long => {
if unsigned {
parse_type!(c_ulong)
} else {
parse_type!(c_long)
}
}
IntKind::LongLong => {
if unsigned {
parse_type!(c_ulonglong)
} else {
parse_type!(c_longlong)
}
}
IntKind::IntMax => {
if unsigned {
parse_type!(uintmax_t)
} else {
parse_type!(intmax_t)
}
}
IntKind::PtrDiff => parse_type!(ptrdiff_t),
IntKind::Size => if unsigned {
parse_type!(size_t)
} else {
parse_type!(ssize_t)
},
IntKind::Size => {
if unsigned {
parse_type!(size_t)
} else {
parse_type!(ssize_t)
}
}
}
}
}