@@ -425,7 +425,7 @@ Failure:
425
425
If `begin` + `len` is is greater than the byte length of the string
426
426
*/
427
427
fn substr ( s : str , begin : uint , len : uint ) -> str {
428
- ret slice ( s, begin, begin + len) ;
428
+ ret unsafe :: slice ( s, begin, begin + len) ;
429
429
}
430
430
431
431
/*
@@ -712,7 +712,7 @@ fn replace(s: str, from: str, to: str) : is_not_empty(from) -> str {
712
712
if byte_len ( s) == 0 u {
713
713
ret "" ;
714
714
} 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) ;
716
716
} else {
717
717
let idx = find ( s, from) ;
718
718
if idx == -1 {
@@ -1346,7 +1346,9 @@ mod unsafe {
1346
1346
export
1347
1347
// UNSAFE
1348
1348
from_bytes,
1349
- from_byte;
1349
+ from_byte,
1350
+ slice,
1351
+ safe_slice;
1350
1352
1351
1353
// Function: unsafe::from_bytes
1352
1354
//
@@ -1364,6 +1366,47 @@ mod unsafe {
1364
1366
// Converts a byte to a string. Does not verify that the byte is
1365
1367
// valid UTF-8.
1366
1368
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
+
1367
1410
}
1368
1411
1369
1412
0 commit comments