Skip to content

Commit

Permalink
rewrite uint::to_str_bytes to avoid raw pointers
Browse files Browse the repository at this point in the history
  • Loading branch information
ttaubert committed Dec 15, 2012
1 parent dbc52ce commit 2f3d4f6
Showing 1 changed file with 20 additions and 28 deletions.
48 changes: 20 additions & 28 deletions src/libcore/uint-template.rs
Expand Up @@ -179,7 +179,7 @@ pub pure fn to_str_bytes<U>(neg: bool, num: T, radix: uint,
f: fn(v: &[u8]) -> U) -> U {

#[inline(always)]
fn digit(n: T) -> u8 {
pure fn digit(n: T) -> u8 {
if n <= 9u as T {
n as u8 + '0' as u8
} else if n <= 15u as T {
Expand All @@ -195,35 +195,27 @@ pub pure fn to_str_bytes<U>(neg: bool, num: T, radix: uint,
// Worst case: 64-bit number, binary-radix, with
// a leading negative sign = 65 bytes.
let buf : [mut u8 * 65] = [mut 0u8, ..65];
let len = buf.len();

// FIXME (#2649): post-snapshot, you can do this without the raw
// pointers and unsafe bits, and the codegen will prove it's all
// in-bounds, no extra cost.

unsafe {
do vec::as_imm_buf(buf) |p, len| {
let mp = p as *mut u8;
let mut i = len;
let mut n = num;
let radix = radix as T;
loop {
i -= 1u;
assert 0u < i && i < len;
*ptr::mut_offset(mp, i) = digit(n % radix);
n /= radix;
if n == 0 as T { break; }
}

assert 0u < i && i < len;

if neg {
i -= 1u;
*ptr::mut_offset(mp, i) = '-' as u8;
}

vec::raw::buf_as_slice(ptr::offset(p, i), len - i, f)
}
let mut i = len;
let mut n = num;
let radix = radix as T;
loop {
i -= 1u;
assert 0u < i && i < len;
buf[i] = digit(n % radix);
n /= radix;
if n == 0 as T { break; }
}

assert 0u < i && i < len;

if neg {
i -= 1u;
buf[i] = '-' as u8;
}

f(vec::view(buf, i, len))
}

/// Convert to a string
Expand Down

0 comments on commit 2f3d4f6

Please sign in to comment.