Merge pull request #4200 from ttaubert/issue-2649-rewrite-to_str_bytes
rewrite uint::to_str_bytes to avoid raw pointers
This commit is contained in:
commit
8311c94db4
|
@ -179,7 +179,7 @@ pub pure fn to_str_bytes<U>(neg: bool, num: T, radix: uint,
|
||||||
f: fn(v: &[u8]) -> U) -> U {
|
f: fn(v: &[u8]) -> U) -> U {
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn digit(n: T) -> u8 {
|
pure fn digit(n: T) -> u8 {
|
||||||
if n <= 9u as T {
|
if n <= 9u as T {
|
||||||
n as u8 + '0' as u8
|
n as u8 + '0' as u8
|
||||||
} else if n <= 15u as T {
|
} 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
|
// Worst case: 64-bit number, binary-radix, with
|
||||||
// a leading negative sign = 65 bytes.
|
// a leading negative sign = 65 bytes.
|
||||||
let buf : [mut u8 * 65] = [mut 0u8, ..65];
|
let buf : [mut u8 * 65] = [mut 0u8, ..65];
|
||||||
|
let len = buf.len();
|
||||||
|
|
||||||
// FIXME (#2649): post-snapshot, you can do this without the raw
|
let mut i = len;
|
||||||
// pointers and unsafe bits, and the codegen will prove it's all
|
let mut n = num;
|
||||||
// in-bounds, no extra cost.
|
let radix = radix as T;
|
||||||
|
loop {
|
||||||
unsafe {
|
i -= 1u;
|
||||||
do vec::as_imm_buf(buf) |p, len| {
|
assert 0u < i && i < len;
|
||||||
let mp = p as *mut u8;
|
buf[i] = digit(n % radix);
|
||||||
let mut i = len;
|
n /= radix;
|
||||||
let mut n = num;
|
if n == 0 as T { break; }
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
assert 0u < i && i < len;
|
||||||
|
|
||||||
|
if neg {
|
||||||
|
i -= 1u;
|
||||||
|
buf[i] = '-' as u8;
|
||||||
|
}
|
||||||
|
|
||||||
|
f(vec::view(buf, i, len))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert to a string
|
/// Convert to a string
|
||||||
|
|
Loading…
Reference in New Issue