Add a buffered writer to stdlib _io module.

This commit is contained in:
Roy Frostig 2010-08-04 12:59:48 -07:00
parent b9075c23c0
commit 1a8d609e89
3 changed files with 50 additions and 7 deletions

View File

@ -2,6 +2,10 @@ type buf_reader = unsafe obj {
fn read() -> vec[u8];
};
type buf_writer = unsafe obj {
fn write(vec[u8] v);
};
fn default_bufsz() -> uint {
ret 4096u;
}
@ -10,7 +14,7 @@ fn new_buf() -> vec[u8] {
ret _vec.alloc[u8](default_bufsz());
}
fn new_buf_reader(str s) -> buf_reader {
fn new_buf_reader(str path) -> buf_reader {
unsafe obj fd_buf_reader(int fd, mutable vec[u8] buf) {
@ -39,11 +43,45 @@ fn new_buf_reader(str s) -> buf_reader {
}
}
auto fd = os.libc.open(_str.buf(s), 0);
auto fd = os.libc.open(_str.buf(path), 0);
if (fd < 0) {
log "error opening file";
log "error opening file for reading";
log sys.rustrt.last_os_error();
fail;
}
ret fd_buf_reader(fd, new_buf());
}
fn new_buf_writer(str path) -> buf_writer {
unsafe obj fd_buf_writer(int fd) {
fn write(vec[u8] v) {
auto len = _vec.len[u8](v);
auto count = 0u;
auto vbuf;
while (count < len) {
vbuf = _vec.buf_off[u8](v, count);
auto nout = os.libc.write(fd, vbuf, len);
if (nout < 0) {
log "error dumping buffer";
log sys.rustrt.last_os_error();
fail;
}
count += nout as uint;
}
}
drop {
os.libc.close(fd);
}
}
auto fd = os.libc.open(_str.buf(path), 0);
if (fd < 0) {
log "error opening file for writing";
log sys.rustrt.last_os_error();
fail;
}
ret fd_buf_writer(fd);
}

View File

@ -3,7 +3,7 @@ import op = util.operator;
native "rust" mod rustrt {
type vbuf;
fn vec_buf[T](vec[T] v) -> vbuf;
fn vec_buf[T](vec[T] v, uint offset) -> vbuf;
fn vec_len[T](vec[T] v) -> uint;
/* The T in vec_alloc[T, U] is the type of the vec to allocate. The
* U is the type of an element in the vec. So to allocate a vec[U] we
@ -50,7 +50,12 @@ fn len[T](vec[T] v) -> uint {
}
fn buf[T](vec[T] v) -> vbuf {
ret rustrt.vec_buf[T](v);
ret rustrt.vec_buf[T](v, 0u);
}
fn buf_off[T](vec[T] v, uint offset) -> vbuf {
check (offset < len[T](v));
ret rustrt.vec_buf[T](v, offset);
}
// Returns elements from [start..end) from v.

View File

@ -116,9 +116,9 @@ str_buf(rust_task *task, rust_str *s)
}
extern "C" CDECL void *
vec_buf(rust_task *task, type_desc *ty, rust_vec *v)
vec_buf(rust_task *task, type_desc *ty, rust_vec *v, size_t offset)
{
return (void *)&v->data[0];
return (void *)&v->data[ty->size * offset];
}
extern "C" CDECL size_t