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 {
|
||||
|
||||
#[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,21 +195,15 @@ 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);
|
||||
buf[i] = digit(n % radix);
|
||||
n /= radix;
|
||||
if n == 0 as T { break; }
|
||||
}
|
||||
|
@ -218,12 +212,10 @@ pub pure fn to_str_bytes<U>(neg: bool, num: T, radix: uint,
|
|||
|
||||
if neg {
|
||||
i -= 1u;
|
||||
*ptr::mut_offset(mp, i) = '-' as u8;
|
||||
buf[i] = '-' as u8;
|
||||
}
|
||||
|
||||
vec::raw::buf_as_slice(ptr::offset(p, i), len - i, f)
|
||||
}
|
||||
}
|
||||
f(vec::view(buf, i, len))
|
||||
}
|
||||
|
||||
/// Convert to a string
|
||||
|
|
Loading…
Reference in New Issue