Skip to content

Commit cccf9e5

Browse files
killerswanbrson
authored andcommitted
Copy str::slice -> str::unsafe::slice (and unsafe_slice)
1 parent 5a19baf commit cccf9e5

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

src/libcore/str.rs

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ Failure:
425425
If `begin` + `len` is is greater than the byte length of the string
426426
*/
427427
fn substr(s: str, begin: uint, len: uint) -> str {
428-
ret slice(s, begin, begin + len);
428+
ret unsafe::slice(s, begin, begin + len);
429429
}
430430

431431
/*
@@ -712,7 +712,7 @@ fn replace(s: str, from: str, to: str) : is_not_empty(from) -> str {
712712
if byte_len(s) == 0u {
713713
ret "";
714714
} else if starts_with(s, from) {
715-
ret to + replace(slice(s, byte_len(from), byte_len(s)), from, to);
715+
ret to + replace(unsafe::slice(s, byte_len(from), byte_len(s)), from, to);
716716
} else {
717717
let idx = find(s, from);
718718
if idx == -1 {
@@ -1346,7 +1346,9 @@ mod unsafe {
13461346
export
13471347
// UNSAFE
13481348
from_bytes,
1349-
from_byte;
1349+
from_byte,
1350+
slice,
1351+
safe_slice;
13501352

13511353
// Function: unsafe::from_bytes
13521354
//
@@ -1364,6 +1366,47 @@ mod unsafe {
13641366
// Converts a byte to a string. Does not verify that the byte is
13651367
// valid UTF-8.
13661368
unsafe fn from_byte(u: u8) -> str { unsafe::from_bytes([u]) }
1369+
1370+
/*
1371+
Function: slice
1372+
1373+
Takes a bytewise slice from a string. Returns the substring from
1374+
[`begin`..`end`).
1375+
1376+
This function is not unicode-safe.
1377+
1378+
Failure:
1379+
1380+
- If begin is greater than end.
1381+
- If end is greater than the length of the string.
1382+
1383+
FIXME: rename to byte_slice
1384+
*/
1385+
unsafe fn slice(s: str, begin: uint, end: uint) -> str unsafe {
1386+
// FIXME: Typestate precondition
1387+
assert (begin <= end);
1388+
assert (end <= byte_len(s));
1389+
1390+
let v: [u8] = ::unsafe::reinterpret_cast(s);
1391+
let v2 = vec::slice(v, begin, end);
1392+
::unsafe::leak(v);
1393+
v2 += [0u8];
1394+
let s2: str = ::unsafe::reinterpret_cast(v2);
1395+
::unsafe::leak(v2);
1396+
ret s2;
1397+
}
1398+
1399+
/*
1400+
Function: safe_slice
1401+
1402+
FIXME: rename to safe_range_byte_slice
1403+
*/
1404+
unsafe fn safe_slice(s: str, begin: uint, end: uint) : uint::le(begin, end) -> str {
1405+
// would need some magic to make this a precondition
1406+
assert (end <= byte_len(s));
1407+
ret slice(s, begin, end);
1408+
}
1409+
13671410
}
13681411

13691412

0 commit comments

Comments
 (0)