mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-27 17:24:06 +00:00
rewrite uint::to_str_bytes to avoid raw pointers
This commit is contained in:
parent
dbc52ce505
commit
2f3d4f6181
@ -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 {
|
||||
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user