Skip to content

Commit 2f3d4f6

Browse files
committed
rewrite uint::to_str_bytes to avoid raw pointers
1 parent dbc52ce commit 2f3d4f6

File tree

1 file changed

+20
-28
lines changed

1 file changed

+20
-28
lines changed

src/libcore/uint-template.rs

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ pub pure fn to_str_bytes<U>(neg: bool, num: T, radix: uint,
179179
f: fn(v: &[u8]) -> U) -> U {
180180

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

199-
// FIXME (#2649): post-snapshot, you can do this without the raw
200-
// pointers and unsafe bits, and the codegen will prove it's all
201-
// in-bounds, no extra cost.
202-
203-
unsafe {
204-
do vec::as_imm_buf(buf) |p, len| {
205-
let mp = p as *mut u8;
206-
let mut i = len;
207-
let mut n = num;
208-
let radix = radix as T;
209-
loop {
210-
i -= 1u;
211-
assert 0u < i && i < len;
212-
*ptr::mut_offset(mp, i) = digit(n % radix);
213-
n /= radix;
214-
if n == 0 as T { break; }
215-
}
216-
217-
assert 0u < i && i < len;
218-
219-
if neg {
220-
i -= 1u;
221-
*ptr::mut_offset(mp, i) = '-' as u8;
222-
}
223-
224-
vec::raw::buf_as_slice(ptr::offset(p, i), len - i, f)
225-
}
200+
let mut i = len;
201+
let mut n = num;
202+
let radix = radix as T;
203+
loop {
204+
i -= 1u;
205+
assert 0u < i && i < len;
206+
buf[i] = digit(n % radix);
207+
n /= radix;
208+
if n == 0 as T { break; }
209+
}
210+
211+
assert 0u < i && i < len;
212+
213+
if neg {
214+
i -= 1u;
215+
buf[i] = '-' as u8;
226216
}
217+
218+
f(vec::view(buf, i, len))
227219
}
228220

229221
/// Convert to a string

0 commit comments

Comments
 (0)