forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstr.rs
More file actions
3338 lines (2988 loc) · 103 KB
/
str.rs
File metadata and controls
3338 lines (2988 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* String manipulation
*
* Strings are a packed UTF-8 representation of text, stored as null
* terminated buffers of u8 bytes. Strings should be indexed in bytes,
* for efficiency, but UTF-8 unsafe operations should be avoided. For
* some heavy-duty uses, try std::rope.
*/
use at_vec;
use cast::transmute;
use cast;
use char;
use char::Char;
use clone::Clone;
use container::Container;
use iter::Times;
use iterator::{Iterator, IteratorUtil, FilterIterator, AdditiveIterator, MapIterator};
use libc;
use num::Zero;
use option::{None, Option, Some};
use ptr;
use ptr::RawPtr;
use to_str::ToStr;
use uint;
use vec;
use vec::{OwnedVector, OwnedCopyableVector, ImmutableVector};
/*
Section: Conditions
*/
condition! {
not_utf8: (~str) -> ~str;
}
/*
Section: Creating a string
*/
/**
* Convert a vector of bytes to a new UTF-8 string
*
* # Failure
*
* Raises the `not_utf8` condition if invalid UTF-8
*/
pub fn from_bytes(vv: &[u8]) -> ~str {
use str::not_utf8::cond;
if !is_utf8(vv) {
let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).get();
cond.raise(fmt!("from_bytes: input is not UTF-8; first bad byte is %u",
first_bad_byte as uint))
}
else {
return unsafe { raw::from_bytes(vv) }
}
}
/**
* Convert a vector of bytes to a UTF-8 string.
* The vector needs to be one byte longer than the string, and end with a 0 byte.
*
* Compared to `from_bytes()`, this fn doesn't need to allocate a new owned str.
*
* # Failure
*
* Fails if invalid UTF-8
* Fails if not null terminated
*/
pub fn from_bytes_with_null<'a>(vv: &'a [u8]) -> &'a str {
assert_eq!(vv[vv.len() - 1], 0);
assert!(is_utf8(vv));
return unsafe { raw::from_bytes_with_null(vv) };
}
/**
* Converts a vector to a string slice without performing any allocations.
*
* Once the slice has been validated as utf-8, it is transmuted in-place and
* returned as a '&str' instead of a '&[u8]'
*
* # Failure
*
* Fails if invalid UTF-8
*/
pub fn from_bytes_slice<'a>(vector: &'a [u8]) -> &'a str {
unsafe {
assert!(is_utf8(vector));
let (ptr, len): (*u8, uint) = ::cast::transmute(vector);
let string: &'a str = ::cast::transmute((ptr, len + 1));
string
}
}
/// Copy a slice into a new unique str
#[inline]
pub fn to_owned(s: &str) -> ~str {
unsafe { raw::slice_bytes_owned(s, 0, s.len()) }
}
impl ToStr for ~str {
#[inline]
fn to_str(&self) -> ~str { to_owned(*self) }
}
impl<'self> ToStr for &'self str {
#[inline]
fn to_str(&self) -> ~str { to_owned(*self) }
}
impl ToStr for @str {
#[inline]
fn to_str(&self) -> ~str { to_owned(*self) }
}
/**
* Convert a byte to a UTF-8 string
*
* # Failure
*
* Fails if invalid UTF-8
*/
pub fn from_byte(b: u8) -> ~str {
assert!(b < 128u8);
unsafe { ::cast::transmute(~[b, 0u8]) }
}
/// Convert a char to a string
pub fn from_char(ch: char) -> ~str {
let mut buf = ~"";
buf.push_char(ch);
buf
}
/// Convert a vector of chars to a string
pub fn from_chars(chs: &[char]) -> ~str {
let mut buf = ~"";
buf.reserve(chs.len());
for chs.iter().advance |ch| {
buf.push_char(*ch)
}
buf
}
#[doc(hidden)]
pub fn push_str(lhs: &mut ~str, rhs: &str) {
lhs.push_str(rhs)
}
#[allow(missing_doc)]
pub trait StrVector {
pub fn concat(&self) -> ~str;
pub fn connect(&self, sep: &str) -> ~str;
}
impl<'self, S: Str> StrVector for &'self [S] {
/// Concatenate a vector of strings.
pub fn concat(&self) -> ~str {
if self.is_empty() { return ~""; }
let len = self.iter().transform(|s| s.as_slice().len()).sum();
let mut s = ~"";
s.reserve(len);
unsafe {
do as_buf(s) |buf, _| {
let mut buf = ::cast::transmute_mut_unsafe(buf);
for self.iter().advance |ss| {
do as_buf(ss.as_slice()) |ssbuf, sslen| {
let sslen = sslen - 1;
ptr::copy_memory(buf, ssbuf, sslen);
buf = buf.offset(sslen);
}
}
}
raw::set_len(&mut s, len);
}
s
}
/// Concatenate a vector of strings, placing a given separator between each.
pub fn connect(&self, sep: &str) -> ~str {
if self.is_empty() { return ~""; }
// concat is faster
if sep.is_empty() { return self.concat(); }
// this is wrong without the guarantee that `self` is non-empty
let len = sep.len() * (self.len() - 1)
+ self.iter().transform(|s| s.as_slice().len()).sum();
let mut s = ~"";
let mut first = true;
s.reserve(len);
unsafe {
do as_buf(s) |buf, _| {
do as_buf(sep) |sepbuf, seplen| {
let seplen = seplen - 1;
let mut buf = ::cast::transmute_mut_unsafe(buf);
for self.iter().advance |ss| {
do as_buf(ss.as_slice()) |ssbuf, sslen| {
let sslen = sslen - 1;
if first {
first = false;
} else {
ptr::copy_memory(buf, sepbuf, seplen);
buf = buf.offset(seplen);
}
ptr::copy_memory(buf, ssbuf, sslen);
buf = buf.offset(sslen);
}
}
}
}
raw::set_len(&mut s, len);
}
s
}
}
/// Something that can be used to compare against a character
pub trait CharEq {
/// Determine if the splitter should split at the given character
fn matches(&self, char) -> bool;
/// Indicate if this is only concerned about ASCII characters,
/// which can allow for a faster implementation.
fn only_ascii(&self) -> bool;
}
impl CharEq for char {
#[inline]
fn matches(&self, c: char) -> bool { *self == c }
fn only_ascii(&self) -> bool { (*self as uint) < 128 }
}
impl<'self> CharEq for &'self fn(char) -> bool {
#[inline]
fn matches(&self, c: char) -> bool { (*self)(c) }
fn only_ascii(&self) -> bool { false }
}
impl CharEq for extern "Rust" fn(char) -> bool {
#[inline]
fn matches(&self, c: char) -> bool { (*self)(c) }
fn only_ascii(&self) -> bool { false }
}
impl<'self, C: CharEq> CharEq for &'self [C] {
#[inline]
fn matches(&self, c: char) -> bool {
self.iter().any_(|m| m.matches(c))
}
fn only_ascii(&self) -> bool {
self.iter().all(|m| m.only_ascii())
}
}
/// An iterator over the substrings of a string, separated by `sep`.
pub struct StrCharSplitIterator<'self,Sep> {
priv string: &'self str,
priv position: uint,
priv sep: Sep,
/// The number of splits remaining
priv count: uint,
/// Whether an empty string at the end is allowed
priv allow_trailing_empty: bool,
priv finished: bool,
priv only_ascii: bool
}
/// An iterator over the words of a string, separated by an sequence of whitespace
pub type WordIterator<'self> =
FilterIterator<'self, &'self str,
StrCharSplitIterator<'self, extern "Rust" fn(char) -> bool>>;
/// An iterator over the lines of a string, separated by either `\n` or (`\r\n`).
pub type AnyLineIterator<'self> =
MapIterator<'self, &'self str, &'self str, StrCharSplitIterator<'self, char>>;
impl<'self, Sep: CharEq> Iterator<&'self str> for StrCharSplitIterator<'self, Sep> {
#[inline]
fn next(&mut self) -> Option<&'self str> {
if self.finished { return None }
let l = self.string.len();
let start = self.position;
if self.only_ascii {
// this gives a *huge* speed up for splitting on ASCII
// characters (e.g. '\n' or ' ')
while self.position < l && self.count > 0 {
let byte = self.string[self.position];
if self.sep.matches(byte as char) {
let slice = unsafe { raw::slice_bytes(self.string, start, self.position) };
self.position += 1;
self.count -= 1;
return Some(slice);
}
self.position += 1;
}
} else {
while self.position < l && self.count > 0 {
let CharRange {ch, next} = self.string.char_range_at(self.position);
if self.sep.matches(ch) {
let slice = unsafe { raw::slice_bytes(self.string, start, self.position) };
self.position = next;
self.count -= 1;
return Some(slice);
}
self.position = next;
}
}
self.finished = true;
if self.allow_trailing_empty || start < l {
Some(unsafe { raw::slice_bytes(self.string, start, l) })
} else {
None
}
}
}
/// An iterator over the start and end indicies of the matches of a
/// substring within a larger string
pub struct StrMatchesIndexIterator<'self> {
priv haystack: &'self str,
priv needle: &'self str,
priv position: uint,
}
/// An iterator over the substrings of a string separated by a given
/// search string
pub struct StrStrSplitIterator<'self> {
priv it: StrMatchesIndexIterator<'self>,
priv last_end: uint,
priv finished: bool
}
impl<'self> Iterator<(uint, uint)> for StrMatchesIndexIterator<'self> {
#[inline]
fn next(&mut self) -> Option<(uint, uint)> {
// See Issue #1932 for why this is a naive search
let (h_len, n_len) = (self.haystack.len(), self.needle.len());
let mut (match_start, match_i) = (0, 0);
while self.position < h_len {
if self.haystack[self.position] == self.needle[match_i] {
if match_i == 0 { match_start = self.position; }
match_i += 1;
self.position += 1;
if match_i == n_len {
// found a match!
return Some((match_start, self.position));
}
} else {
// failed match, backtrack
if match_i > 0 {
match_i = 0;
self.position = match_start;
}
self.position += 1;
}
}
None
}
}
impl<'self> Iterator<&'self str> for StrStrSplitIterator<'self> {
#[inline]
fn next(&mut self) -> Option<&'self str> {
if self.finished { return None; }
match self.it.next() {
Some((from, to)) => {
let ret = Some(self.it.haystack.slice(self.last_end, from));
self.last_end = to;
ret
}
None => {
self.finished = true;
Some(self.it.haystack.slice(self.last_end, self.it.haystack.len()))
}
}
}
}
/** Splits a string into substrings with possibly internal whitespace,
* each of them at most `lim` bytes long. The substrings have leading and trailing
* whitespace removed, and are only cut at whitespace boundaries.
*
* #Failure:
*
* Fails during iteration if the string contains a non-whitespace
* sequence longer than the limit.
*/
pub fn each_split_within<'a>(ss: &'a str,
lim: uint,
it: &fn(&'a str) -> bool) -> bool {
// Just for fun, let's write this as an state machine:
enum SplitWithinState {
A, // leading whitespace, initial state
B, // words
C, // internal and trailing whitespace
}
enum Whitespace {
Ws, // current char is whitespace
Cr // current char is not whitespace
}
enum LengthLimit {
UnderLim, // current char makes current substring still fit in limit
OverLim // current char makes current substring no longer fit in limit
}
let mut slice_start = 0;
let mut last_start = 0;
let mut last_end = 0;
let mut state = A;
let mut cont = true;
let slice: &fn() = || { cont = it(ss.slice(slice_start, last_end)) };
let machine: &fn((uint, char)) -> bool = |(i, c)| {
let whitespace = if char::is_whitespace(c) { Ws } else { Cr };
let limit = if (i - slice_start + 1) <= lim { UnderLim } else { OverLim };
state = match (state, whitespace, limit) {
(A, Ws, _) => { A }
(A, Cr, _) => { slice_start = i; last_start = i; B }
(B, Cr, UnderLim) => { B }
(B, Cr, OverLim) if (i - last_start + 1) > lim
=> fail!("word starting with %? longer than limit!",
ss.slice(last_start, i + 1)),
(B, Cr, OverLim) => { slice(); slice_start = last_start; B }
(B, Ws, UnderLim) => { last_end = i; C }
(B, Ws, OverLim) => { last_end = i; slice(); A }
(C, Cr, UnderLim) => { last_start = i; B }
(C, Cr, OverLim) => { slice(); slice_start = i; last_start = i; last_end = i; B }
(C, Ws, OverLim) => { slice(); A }
(C, Ws, UnderLim) => { C }
};
cont
};
ss.iter().enumerate().advance(machine);
// Let the automaton 'run out' by supplying trailing whitespace
let mut fake_i = ss.len();
while cont && match state { B | C => true, A => false } {
machine((fake_i, ' '));
fake_i += 1;
}
return cont;
}
/*
Section: Comparing strings
*/
/// Bytewise slice equality
#[cfg(not(test))]
#[lang="str_eq"]
#[inline]
pub fn eq_slice(a: &str, b: &str) -> bool {
do as_buf(a) |ap, alen| {
do as_buf(b) |bp, blen| {
if (alen != blen) { false }
else {
unsafe {
libc::memcmp(ap as *libc::c_void,
bp as *libc::c_void,
(alen - 1) as libc::size_t) == 0
}
}
}
}
}
#[cfg(test)]
#[inline]
pub fn eq_slice(a: &str, b: &str) -> bool {
do as_buf(a) |ap, alen| {
do as_buf(b) |bp, blen| {
if (alen != blen) { false }
else {
unsafe {
libc::memcmp(ap as *libc::c_void,
bp as *libc::c_void,
(alen - 1) as libc::size_t) == 0
}
}
}
}
}
/// Bytewise string equality
#[cfg(not(test))]
#[lang="uniq_str_eq"]
#[inline]
pub fn eq(a: &~str, b: &~str) -> bool {
eq_slice(*a, *b)
}
#[cfg(test)]
#[inline]
pub fn eq(a: &~str, b: &~str) -> bool {
eq_slice(*a, *b)
}
/*
Section: Searching
*/
// Utility used by various searching functions
fn match_at<'a,'b>(haystack: &'a str, needle: &'b str, at: uint) -> bool {
let mut i = at;
for needle.bytes_iter().advance |c| { if haystack[i] != c { return false; } i += 1u; }
return true;
}
/*
Section: Misc
*/
/// Determines if a vector of bytes contains valid UTF-8
pub fn is_utf8(v: &const [u8]) -> bool {
let mut i = 0u;
let total = v.len();
while i < total {
let mut chsize = utf8_char_width(v[i]);
if chsize == 0u { return false; }
if i + chsize > total { return false; }
i += 1u;
while chsize > 1u {
if v[i] & 192u8 != tag_cont_u8 { return false; }
i += 1u;
chsize -= 1u;
}
}
return true;
}
/// Determines if a vector of `u16` contains valid UTF-16
pub fn is_utf16(v: &[u16]) -> bool {
let len = v.len();
let mut i = 0u;
while (i < len) {
let u = v[i];
if u <= 0xD7FF_u16 || u >= 0xE000_u16 {
i += 1u;
} else {
if i+1u < len { return false; }
let u2 = v[i+1u];
if u < 0xD7FF_u16 || u > 0xDBFF_u16 { return false; }
if u2 < 0xDC00_u16 || u2 > 0xDFFF_u16 { return false; }
i += 2u;
}
}
return true;
}
/// Iterates over the utf-16 characters in the specified slice, yielding each
/// decoded unicode character to the function provided.
///
/// # Failures
///
/// * Fails on invalid utf-16 data
pub fn utf16_chars(v: &[u16], f: &fn(char)) {
let len = v.len();
let mut i = 0u;
while (i < len && v[i] != 0u16) {
let u = v[i];
if u <= 0xD7FF_u16 || u >= 0xE000_u16 {
f(u as char);
i += 1u;
} else {
let u2 = v[i+1u];
assert!(u >= 0xD800_u16 && u <= 0xDBFF_u16);
assert!(u2 >= 0xDC00_u16 && u2 <= 0xDFFF_u16);
let mut c = (u - 0xD800_u16) as char;
c = c << 10;
c |= (u2 - 0xDC00_u16) as char;
c |= 0x1_0000_u32 as char;
f(c);
i += 2u;
}
}
}
/**
* Allocates a new string from the utf-16 slice provided
*/
pub fn from_utf16(v: &[u16]) -> ~str {
let mut buf = ~"";
buf.reserve(v.len());
utf16_chars(v, |ch| buf.push_char(ch));
buf
}
/**
* Allocates a new string with the specified capacity. The string returned is
* the empty string, but has capacity for much more.
*/
pub fn with_capacity(capacity: uint) -> ~str {
let mut buf = ~"";
buf.reserve(capacity);
buf
}
/// Given a first byte, determine how many bytes are in this UTF-8 character
pub fn utf8_char_width(b: u8) -> uint {
let byte: uint = b as uint;
if byte < 128u { return 1u; }
// Not a valid start byte
if byte < 192u { return 0u; }
if byte < 224u { return 2u; }
if byte < 240u { return 3u; }
if byte < 248u { return 4u; }
if byte < 252u { return 5u; }
return 6u;
}
#[allow(missing_doc)]
pub struct CharRange {
ch: char,
next: uint
}
// UTF-8 tags and ranges
static tag_cont_u8: u8 = 128u8;
static tag_cont: uint = 128u;
static max_one_b: uint = 128u;
static tag_two_b: uint = 192u;
static max_two_b: uint = 2048u;
static tag_three_b: uint = 224u;
static max_three_b: uint = 65536u;
static tag_four_b: uint = 240u;
static max_four_b: uint = 2097152u;
static tag_five_b: uint = 248u;
static max_five_b: uint = 67108864u;
static tag_six_b: uint = 252u;
/**
* A dummy trait to hold all the utility methods that we implement on strings.
*/
pub trait StrUtil {
/**
* Work with the byte buffer of a string as a null-terminated C string.
*
* Allows for unsafe manipulation of strings, which is useful for foreign
* interop. This is similar to `str::as_buf`, but guarantees null-termination.
* If the given slice is not already null-terminated, this function will
* allocate a temporary, copy the slice, null terminate it, and pass
* that instead.
*
* # Example
*
* ~~~ {.rust}
* let s = "PATH".as_c_str(|path| libc::getenv(path));
* ~~~
*/
fn as_c_str<T>(self, f: &fn(*libc::c_char) -> T) -> T;
}
impl<'self> StrUtil for &'self str {
#[inline]
fn as_c_str<T>(self, f: &fn(*libc::c_char) -> T) -> T {
do as_buf(self) |buf, len| {
// NB: len includes the trailing null.
assert!(len > 0);
if unsafe { *(ptr::offset(buf,len-1)) != 0 } {
to_owned(self).as_c_str(f)
} else {
f(buf as *libc::c_char)
}
}
}
}
/**
* Deprecated. Use the `as_c_str` method on strings instead.
*/
#[inline]
pub fn as_c_str<T>(s: &str, f: &fn(*libc::c_char) -> T) -> T {
s.as_c_str(f)
}
/**
* Work with the byte buffer and length of a slice.
*
* The given length is one byte longer than the 'official' indexable
* length of the string. This is to permit probing the byte past the
* indexable area for a null byte, as is the case in slices pointing
* to full strings, or suffixes of them.
*/
#[inline]
pub fn as_buf<T>(s: &str, f: &fn(*u8, uint) -> T) -> T {
unsafe {
let v : *(*u8,uint) = transmute(&s);
let (buf,len) = *v;
f(buf, len)
}
}
/// Unsafe operations
pub mod raw {
use cast;
use libc;
use ptr;
use str::raw;
use str::{as_buf, is_utf8};
use vec;
/// Create a Rust string from a null-terminated *u8 buffer
pub unsafe fn from_buf(buf: *u8) -> ~str {
let mut (curr, i) = (buf, 0u);
while *curr != 0u8 {
i += 1u;
curr = ptr::offset(buf, i);
}
return from_buf_len(buf, i);
}
/// Create a Rust string from a *u8 buffer of the given length
pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> ~str {
let mut v: ~[u8] = vec::with_capacity(len + 1);
vec::as_mut_buf(v, |vbuf, _len| {
ptr::copy_memory(vbuf, buf as *u8, len)
});
vec::raw::set_len(&mut v, len);
v.push(0u8);
assert!(is_utf8(v));
return ::cast::transmute(v);
}
/// Create a Rust string from a null-terminated C string
pub unsafe fn from_c_str(c_str: *libc::c_char) -> ~str {
from_buf(::cast::transmute(c_str))
}
/// Create a Rust string from a `*c_char` buffer of the given length
pub unsafe fn from_c_str_len(c_str: *libc::c_char, len: uint) -> ~str {
from_buf_len(::cast::transmute(c_str), len)
}
/// Converts a vector of bytes to a new owned string.
pub unsafe fn from_bytes(v: &const [u8]) -> ~str {
do vec::as_const_buf(v) |buf, len| {
from_buf_len(buf, len)
}
}
/// Converts a vector of bytes to a string.
/// The byte slice needs to contain valid utf8 and needs to be one byte longer than
/// the string, if possible ending in a 0 byte.
pub unsafe fn from_bytes_with_null<'a>(v: &'a [u8]) -> &'a str {
cast::transmute(v)
}
/// Converts a byte to a string.
pub unsafe fn from_byte(u: u8) -> ~str { raw::from_bytes([u]) }
/// Form a slice from a C string. Unsafe because the caller must ensure the
/// C string has the static lifetime, or else the return value may be
/// invalidated later.
pub unsafe fn c_str_to_static_slice(s: *libc::c_char) -> &'static str {
let s = s as *u8;
let mut (curr, len) = (s, 0u);
while *curr != 0u8 {
len += 1u;
curr = ptr::offset(s, len);
}
let v = (s, len + 1);
assert!(is_utf8(::cast::transmute(v)));
::cast::transmute(v)
}
/**
* Takes a bytewise (not UTF-8) slice from a string.
*
* Returns the substring from [`begin`..`end`).
*
* # Failure
*
* If begin is greater than end.
* If end is greater than the length of the string.
*/
pub unsafe fn slice_bytes_owned(s: &str, begin: uint, end: uint) -> ~str {
do as_buf(s) |sbuf, n| {
assert!((begin <= end));
assert!((end <= n));
let mut v = vec::with_capacity(end - begin + 1u);
do vec::as_imm_buf(v) |vbuf, _vlen| {
let vbuf = ::cast::transmute_mut_unsafe(vbuf);
let src = ptr::offset(sbuf, begin);
ptr::copy_memory(vbuf, src, end - begin);
}
vec::raw::set_len(&mut v, end - begin);
v.push(0u8);
::cast::transmute(v)
}
}
/**
* Takes a bytewise (not UTF-8) slice from a string.
*
* Returns the substring from [`begin`..`end`).
*
* # Failure
*
* If begin is greater than end.
* If end is greater than the length of the string.
*/
#[inline]
pub unsafe fn slice_bytes(s: &str, begin: uint, end: uint) -> &str {
do as_buf(s) |sbuf, n| {
assert!((begin <= end));
assert!((end <= n));
let tuple = (ptr::offset(sbuf, begin), end - begin + 1);
::cast::transmute(tuple)
}
}
/// Appends a byte to a string. (Not UTF-8 safe).
pub unsafe fn push_byte(s: &mut ~str, b: u8) {
let new_len = s.len() + 1;
s.reserve_at_least(new_len);
do as_buf(*s) |buf, len| {
let buf: *mut u8 = ::cast::transmute(buf);
*ptr::mut_offset(buf, len) = b;
}
set_len(&mut *s, new_len);
}
/// Appends a vector of bytes to a string. (Not UTF-8 safe).
unsafe fn push_bytes(s: &mut ~str, bytes: &[u8]) {
let new_len = s.len() + bytes.len();
s.reserve_at_least(new_len);
for bytes.iter().advance |byte| { push_byte(&mut *s, *byte); }
}
/// Removes the last byte from a string and returns it. (Not UTF-8 safe).
pub unsafe fn pop_byte(s: &mut ~str) -> u8 {
let len = s.len();
assert!((len > 0u));
let b = s[len - 1u];
set_len(s, len - 1u);
return b;
}
/// Removes the first byte from a string and returns it. (Not UTF-8 safe).
pub unsafe fn shift_byte(s: &mut ~str) -> u8 {
let len = s.len();
assert!((len > 0u));
let b = s[0];
*s = raw::slice_bytes_owned(*s, 1u, len);
return b;
}
/// Sets the length of the string and adds the null terminator
#[inline]
pub unsafe fn set_len(v: &mut ~str, new_len: uint) {
let v: **mut vec::raw::VecRepr = cast::transmute(v);
let repr: *mut vec::raw::VecRepr = *v;
(*repr).unboxed.fill = new_len + 1u;
let null = ptr::mut_offset(cast::transmute(&((*repr).unboxed.data)),
new_len);
*null = 0u8;
}
#[test]
fn test_from_buf_len() {
unsafe {
let a = ~[65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8];
let b = vec::raw::to_ptr(a);
let c = from_buf_len(b, 3u);
assert_eq!(c, ~"AAA");
}
}
}
#[cfg(not(test))]
pub mod traits {
use ops::Add;
use cmp::{TotalOrd, Ordering, Less, Equal, Greater, Eq, Ord, Equiv, TotalEq};
use super::{Str, eq_slice};
impl<'self> Add<&'self str,~str> for &'self str {
#[inline]
fn add(&self, rhs: & &'self str) -> ~str {
let mut ret = self.to_owned();
ret.push_str(*rhs);
ret
}
}
impl<'self> TotalOrd for &'self str {
#[inline]
fn cmp(&self, other: & &'self str) -> Ordering {
for self.bytes_iter().zip(other.bytes_iter()).advance |(s_b, o_b)| {
match s_b.cmp(&o_b) {
Greater => return Greater,
Less => return Less,
Equal => ()
}
}
self.len().cmp(&other.len())
}
}
impl TotalOrd for ~str {
#[inline]
fn cmp(&self, other: &~str) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
}
impl TotalOrd for @str {
#[inline]
fn cmp(&self, other: &@str) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
}
impl<'self> Eq for &'self str {
#[inline]
fn eq(&self, other: & &'self str) -> bool {
eq_slice((*self), (*other))
}
#[inline]
fn ne(&self, other: & &'self str) -> bool { !(*self).eq(other) }
}
impl Eq for ~str {
#[inline]
fn eq(&self, other: &~str) -> bool {
eq_slice((*self), (*other))
}
#[inline]
fn ne(&self, other: &~str) -> bool { !(*self).eq(other) }
}
impl Eq for @str {
#[inline]
fn eq(&self, other: &@str) -> bool {
eq_slice((*self), (*other))
}
#[inline]
fn ne(&self, other: &@str) -> bool { !(*self).eq(other) }
}
impl<'self> TotalEq for &'self str {
#[inline]
fn equals(&self, other: & &'self str) -> bool {
eq_slice((*self), (*other))
}
}
impl TotalEq for ~str {
#[inline]
fn equals(&self, other: &~str) -> bool {
eq_slice((*self), (*other))
}
}
impl TotalEq for @str {
#[inline]
fn equals(&self, other: &@str) -> bool {
eq_slice((*self), (*other))
}
}
impl<'self> Ord for &'self str {
#[inline]
fn lt(&self, other: & &'self str) -> bool { self.cmp(other) == Less }