Skip to content

Commit

Permalink
Redo yesterday's buf_writer-wrapper in a less silly and convoluted wa…
Browse files Browse the repository at this point in the history
…y. Add integer stringifying functions to _int module.
  • Loading branch information
froystig committed Aug 6, 2010
1 parent 514fb4b commit 80a1cd3
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 43 deletions.
44 changes: 44 additions & 0 deletions src/lib/_int.rs
Expand Up @@ -44,3 +44,47 @@ fn next_power_of_two(uint n) -> uint {
}
ret tmp + 1u;
}

fn uto_string(mutable uint n, uint radix) -> str
{
check (0u < radix && radix <= 16u);
fn digit(uint n) -> str {
alt (n) {
case (0u) { ret "0"; }
case (1u) { ret "1"; }
case (2u) { ret "2"; }
case (3u) { ret "3"; }
case (4u) { ret "4"; }
case (5u) { ret "5"; }
case (6u) { ret "6"; }
case (7u) { ret "7"; }
case (8u) { ret "8"; }
case (9u) { ret "9"; }
case (10u) { ret "A"; }
case (11u) { ret "B"; }
case (12u) { ret "C"; }
case (13u) { ret "D"; }
case (14u) { ret "E"; }
case (15u) { ret "F"; }
}
}

if (n == 0u) { ret "0"; }

let str s = "";
while (n > 0u) {
s = digit(n % radix) + s;
n /= radix;
}
ret s;
}

fn to_string(mutable int n, uint radix) -> str
{
check (0u < radix && radix <= 16u);
if (n < 0) {
ret "-" + uto_string((-n) as uint, radix);
} else {
ret uto_string(n as uint, radix);
}
}
58 changes: 15 additions & 43 deletions src/lib/_io.rs
Expand Up @@ -112,49 +112,21 @@ fn new_buf_writer(str path, vec[fileflag] flags) -> buf_writer {
ret fd_buf_writer(fd);
}

type formatter[T] = fn(&T x) -> vec[u8];

type writer[T] = unsafe obj { fn write(&T x); };

fn mk_writer[T](str path,
vec[fileflag] flags,
&formatter[T] fmt)
-> writer[T]
{
unsafe obj w[T](buf_writer out, formatter[T] fmt) {
fn write(&T x) {
out.write(fmt(x));
}
}
ret w[T](new_buf_writer(path, flags), fmt);
}

/* TODO: int_writer, uint_writer, ... */

fn str_writer(str path, vec[fileflag] flags) -> writer[str] {
auto fmt = _str.bytes; // FIXME (issue #90)
ret mk_writer[str](path, flags, fmt);
}

fn vec_writer[T](str path,
vec[fileflag] flags,
&formatter[T] inner)
-> writer[vec[T]]
type writer =
unsafe obj {
fn write_str(str s);
fn write_int(int n);
fn write_uint(uint n);
};

fn file_writer(str path,
vec[fileflag] flags)
-> writer
{
fn fmt[T](&vec[T] v, &formatter[T] inner) -> vec[u8] {
let vec[u8] res = _str.bytes("vec(");
auto first = true;
for (T x in v) {
if (!first) {
res += _str.bytes(", ");
} else {
first = false;
}
res += inner(x);
}
res += _str.bytes(")\n");
ret res;
unsafe obj fw(buf_writer out) {
fn write_str(str s) { out.write(_str.bytes(s)); }
fn write_int(int n) { out.write(_str.bytes(_int.to_string(n, 10u))); }
fn write_uint(uint n) { out.write(_str.bytes(_int.uto_string(n, 10u))); }
}

ret mk_writer[vec[T]](path, flags, bind fmt[T](_, inner));
ret fw(new_buf_writer(path, flags));
}

0 comments on commit 80a1cd3

Please sign in to comment.