Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rewrite uint::to_str_bytes to avoid raw pointers #4200

Merged
merged 1 commit into from
Dec 17, 2012
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 20 additions & 28 deletions src/libcore/uint-template.rs
Original file line number Diff line number Diff line change
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