-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
Copy pathstr.rs
3319 lines (2986 loc) · 94.4 KB
/
str.rs
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 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.
*/
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use at_vec;
use cast;
use char;
use cmp::{Eq, Ord};
use libc;
use libc::size_t;
use io::WriterUtil;
use option::{None, Option, Some};
use ptr;
use str;
use to_str::ToStr;
use u8;
use uint;
use vec;
/*
Section: Creating a string
*/
/**
* Convert a vector of bytes to a UTF-8 string
*
* # Failure
*
* Fails if invalid UTF-8
*/
pub pure fn from_bytes(vv: &[const u8]) -> ~str {
assert is_utf8(vv);
return unsafe { raw::from_bytes(vv) };
}
/// Copy a slice into a new unique str
pub pure fn from_slice(s: &str) -> ~str {
unsafe { raw::slice_bytes(s, 0, len(s)) }
}
/**
* Convert a byte to a UTF-8 string
*
* # Failure
*
* Fails if invalid UTF-8
*/
pub pure fn from_byte(b: u8) -> ~str {
assert b < 128u8;
unsafe { ::cast::transmute(~[b, 0u8]) }
}
/// Appends a character at the end of a string
pub fn push_char(s: &mut ~str, ch: char) {
unsafe {
let code = ch as uint;
let nb = if code < max_one_b { 1u }
else if code < max_two_b { 2u }
else if code < max_three_b { 3u }
else if code < max_four_b { 4u }
else if code < max_five_b { 5u }
else { 6u };
let len = len(*s);
let new_len = len + nb;
reserve_at_least(s, new_len);
let off = len;
do as_buf(*s) |buf, _len| {
let buf: *mut u8 = ::cast::reinterpret_cast(&buf);
if nb == 1u {
*ptr::mut_offset(buf, off) =
code as u8;
} else if nb == 2u {
*ptr::mut_offset(buf, off) =
(code >> 6u & 31u | tag_two_b) as u8;
*ptr::mut_offset(buf, off + 1u) =
(code & 63u | tag_cont) as u8;
} else if nb == 3u {
*ptr::mut_offset(buf, off) =
(code >> 12u & 15u | tag_three_b) as u8;
*ptr::mut_offset(buf, off + 1u) =
(code >> 6u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 2u) =
(code & 63u | tag_cont) as u8;
} else if nb == 4u {
*ptr::mut_offset(buf, off) =
(code >> 18u & 7u | tag_four_b) as u8;
*ptr::mut_offset(buf, off + 1u) =
(code >> 12u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 2u) =
(code >> 6u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 3u) =
(code & 63u | tag_cont) as u8;
} else if nb == 5u {
*ptr::mut_offset(buf, off) =
(code >> 24u & 3u | tag_five_b) as u8;
*ptr::mut_offset(buf, off + 1u) =
(code >> 18u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 2u) =
(code >> 12u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 3u) =
(code >> 6u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 4u) =
(code & 63u | tag_cont) as u8;
} else if nb == 6u {
*ptr::mut_offset(buf, off) =
(code >> 30u & 1u | tag_six_b) as u8;
*ptr::mut_offset(buf, off + 1u) =
(code >> 24u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 2u) =
(code >> 18u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 3u) =
(code >> 12u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 4u) =
(code >> 6u & 63u | tag_cont) as u8;
*ptr::mut_offset(buf, off + 5u) =
(code & 63u | tag_cont) as u8;
}
}
raw::set_len(s, new_len);
}
}
/// Convert a char to a string
pub pure fn from_char(ch: char) -> ~str {
let mut buf = ~"";
unsafe { push_char(&mut buf, ch); }
buf
}
/// Convert a vector of chars to a string
pub pure fn from_chars(chs: &[char]) -> ~str {
let mut buf = ~"";
unsafe {
reserve(&mut buf, chs.len());
for vec::each(chs) |ch| {
push_char(&mut buf, *ch);
}
}
buf
}
/// Appends a string slice to the back of a string, without overallocating
#[inline(always)]
pub fn push_str_no_overallocate(lhs: &mut ~str, rhs: &str) {
unsafe {
let llen = lhs.len();
let rlen = rhs.len();
reserve(lhs, llen + rlen);
do as_buf(*lhs) |lbuf, _llen| {
do as_buf(rhs) |rbuf, _rlen| {
let dst = ptr::offset(lbuf, llen);
let dst = ::cast::transmute_mut_unsafe(dst);
ptr::copy_memory(dst, rbuf, rlen);
}
}
raw::set_len(lhs, llen + rlen);
}
}
/// Appends a string slice to the back of a string
#[inline(always)]
pub fn push_str(lhs: &mut ~str, rhs: &str) {
unsafe {
let llen = lhs.len();
let rlen = rhs.len();
reserve_at_least(lhs, llen + rlen);
do as_buf(*lhs) |lbuf, _llen| {
do as_buf(rhs) |rbuf, _rlen| {
let dst = ptr::offset(lbuf, llen);
let dst = ::cast::transmute_mut_unsafe(dst);
ptr::copy_memory(dst, rbuf, rlen);
}
}
raw::set_len(lhs, llen + rlen);
}
}
/// Concatenate two strings together
#[inline(always)]
pub pure fn append(lhs: ~str, rhs: &str) -> ~str {
let mut v = lhs;
unsafe {
push_str_no_overallocate(&mut v, rhs);
}
v
}
/// Concatenate a vector of strings
pub pure fn concat(v: &[~str]) -> ~str {
let mut s: ~str = ~"";
for vec::each(v) |ss| {
unsafe { push_str(&mut s, *ss) };
}
s
}
/// Concatenate a vector of strings, placing a given separator between each
pub pure fn connect(v: &[~str], sep: &str) -> ~str {
let mut s = ~"", first = true;
for vec::each(v) |ss| {
if first { first = false; } else { unsafe { push_str(&mut s, sep); } }
unsafe { push_str(&mut s, *ss) };
}
s
}
/// Given a string, make a new string with repeated copies of it
pub pure fn repeat(ss: &str, nn: uint) -> ~str {
let mut acc = ~"";
for nn.times { acc += ss; }
acc
}
/*
Section: Adding to and removing from a string
*/
/**
* Remove the final character from a string and return it
*
* # Failure
*
* If the string does not contain any characters
*/
pub fn pop_char(s: &mut ~str) -> char {
let end = len(*s);
assert end > 0u;
let CharRange {ch, next} = char_range_at_reverse(*s, end);
unsafe { raw::set_len(s, next); }
return ch;
}
/**
* Remove the first character from a string and return it
*
* # Failure
*
* If the string does not contain any characters
*/
pub fn shift_char(s: &mut ~str) -> char {
let CharRange {ch, next} = char_range_at(*s, 0u);
*s = unsafe { raw::slice_bytes(*s, next, len(*s)) };
return ch;
}
/**
* Removes the first character from a string slice and returns it. This does
* not allocate a new string; instead, it mutates a slice to point one
* character beyond the character that was shifted.
*
* # Failure
*
* If the string does not contain any characters
*/
#[inline]
pub fn view_shift_char(s: &a/str) -> (char, &a/str) {
let CharRange {ch, next} = char_range_at(s, 0u);
let next_s = unsafe { raw::view_bytes(s, next, len(s)) };
return (ch, next_s);
}
/// Prepend a char to a string
pub fn unshift_char(s: &mut ~str, ch: char) {
*s = from_char(ch) + *s;
}
/**
* Returns a string with leading `chars_to_trim` removed.
*
* # Arguments
*
* * s - A string
* * chars_to_trim - A vector of chars
*
*/
pub pure fn trim_left_chars(s: &str, chars_to_trim: &[char]) -> ~str {
if chars_to_trim.is_empty() { return from_slice(s); }
match find(s, |c| !chars_to_trim.contains(&c)) {
None => ~"",
Some(first) => unsafe { raw::slice_bytes(s, first, s.len()) }
}
}
/**
* Returns a string with trailing `chars_to_trim` removed.
*
* # Arguments
*
* * s - A string
* * chars_to_trim - A vector of chars
*
*/
pub pure fn trim_right_chars(s: &str, chars_to_trim: &[char]) -> ~str {
if chars_to_trim.is_empty() { return str::from_slice(s); }
match rfind(s, |c| !chars_to_trim.contains(&c)) {
None => ~"",
Some(last) => {
let next = char_range_at(s, last).next;
unsafe { raw::slice_bytes(s, 0u, next) }
}
}
}
/**
* Returns a string with leading and trailing `chars_to_trim` removed.
*
* # Arguments
*
* * s - A string
* * chars_to_trim - A vector of chars
*
*/
pub pure fn trim_chars(s: &str, chars_to_trim: &[char]) -> ~str {
trim_left_chars(trim_right_chars(s, chars_to_trim), chars_to_trim)
}
/// Returns a string with leading whitespace removed
pub pure fn trim_left(s: &str) -> ~str {
match find(s, |c| !char::is_whitespace(c)) {
None => ~"",
Some(first) => unsafe { raw::slice_bytes(s, first, len(s)) }
}
}
/// Returns a string with trailing whitespace removed
pub pure fn trim_right(s: &str) -> ~str {
match rfind(s, |c| !char::is_whitespace(c)) {
None => ~"",
Some(last) => {
let next = char_range_at(s, last).next;
unsafe { raw::slice_bytes(s, 0u, next) }
}
}
}
/// Returns a string with leading and trailing whitespace removed
pub pure fn trim(s: &str) -> ~str { trim_left(trim_right(s)) }
/*
Section: Transforming strings
*/
/**
* Converts a string to a vector of bytes
*
* The result vector is not null-terminated.
*/
pub pure fn to_bytes(s: &str) -> ~[u8] unsafe {
let mut v: ~[u8] = ::cast::transmute(from_slice(s));
vec::raw::set_len(&mut v, len(s));
v
}
/// Work with the string as a byte slice, not including trailing null.
#[inline(always)]
pub pure fn byte_slice<T>(s: &str, f: fn(v: &[u8]) -> T) -> T {
do as_buf(s) |p,n| {
unsafe { vec::raw::buf_as_slice(p, n-1u, f) }
}
}
/// Convert a string to a vector of characters
pub pure fn chars(s: &str) -> ~[char] {
let mut buf = ~[], i = 0;
let len = len(s);
while i < len {
let CharRange {ch, next} = char_range_at(s, i);
unsafe { buf.push(ch); }
i = next;
}
buf
}
/**
* Take a substring of another.
*
* Returns a string containing `n` characters starting at byte offset
* `begin`.
*/
pub pure fn substr(s: &str, begin: uint, n: uint) -> ~str {
slice(s, begin, begin + count_bytes(s, begin, n))
}
/**
* Returns a slice of the given string from the byte range [`begin`..`end`)
*
* Fails when `begin` and `end` do not point to valid characters or
* beyond the last character of the string
*/
pub pure fn slice(s: &str, begin: uint, end: uint) -> ~str {
assert is_char_boundary(s, begin);
assert is_char_boundary(s, end);
unsafe { raw::slice_bytes(s, begin, end) }
}
/**
* Returns a view of the given string from the byte range [`begin`..`end`)
*
* Fails when `begin` and `end` do not point to valid characters or beyond
* the last character of the string
*/
pub pure fn view(s: &a/str, begin: uint, end: uint) -> &a/str {
assert is_char_boundary(s, begin);
assert is_char_boundary(s, end);
unsafe { raw::view_bytes(s, begin, end) }
}
/// Splits a string into substrings at each occurrence of a given character
pub pure fn split_char(s: &str, sep: char) -> ~[~str] {
split_char_inner(s, sep, len(s), true)
}
/**
* Splits a string into substrings at each occurrence of a given
* character up to 'count' times
*
* The byte must be a valid UTF-8/ASCII byte
*/
pub pure fn splitn_char(s: &str, sep: char, count: uint) -> ~[~str] {
split_char_inner(s, sep, count, true)
}
/// Like `split_char`, but omits empty strings from the returned vector
pub pure fn split_char_nonempty(s: &str, sep: char) -> ~[~str] {
split_char_inner(s, sep, len(s), false)
}
pure fn split_char_inner(s: &str, sep: char, count: uint, allow_empty: bool)
-> ~[~str] {
if sep < 128u as char {
let b = sep as u8, l = len(s);
let mut result = ~[], done = 0u;
let mut i = 0u, start = 0u;
while i < l && done < count {
if s[i] == b {
if allow_empty || start < i unsafe {
result.push(unsafe { raw::slice_bytes(s, start, i) });
}
start = i + 1u;
done += 1u;
}
i += 1u;
}
if allow_empty || start < l {
unsafe { result.push(raw::slice_bytes(s, start, l) ) };
}
result
} else {
splitn(s, |cur| cur == sep, count)
}
}
/// Splits a string into substrings using a character function
pub pure fn split(s: &str, sepfn: fn(char) -> bool) -> ~[~str] {
split_inner(s, sepfn, len(s), true)
}
/**
* Splits a string into substrings using a character function, cutting at
* most `count` times.
*/
pub pure fn splitn(s: &str, sepfn: fn(char) -> bool, count: uint) -> ~[~str] {
split_inner(s, sepfn, count, true)
}
/// Like `split`, but omits empty strings from the returned vector
pub pure fn split_nonempty(s: &str, sepfn: fn(char) -> bool) -> ~[~str] {
split_inner(s, sepfn, len(s), false)
}
pure fn split_inner(s: &str, sepfn: fn(cc: char) -> bool, count: uint,
allow_empty: bool) -> ~[~str] {
let l = len(s);
let mut result = ~[], i = 0u, start = 0u, done = 0u;
while i < l && done < count {
let CharRange {ch, next} = char_range_at(s, i);
if sepfn(ch) {
if allow_empty || start < i unsafe {
result.push(unsafe { raw::slice_bytes(s, start, i)});
}
start = next;
done += 1u;
}
i = next;
}
if allow_empty || start < l unsafe {
result.push(unsafe { raw::slice_bytes(s, start, l) });
}
result
}
// See Issue #1932 for why this is a naive search
pure fn iter_matches(s: &a/str, sep: &b/str, f: fn(uint, uint)) {
let sep_len = len(sep), l = len(s);
assert sep_len > 0u;
let mut i = 0u, match_start = 0u, match_i = 0u;
while i < l {
if s[i] == sep[match_i] {
if match_i == 0u { match_start = i; }
match_i += 1u;
// Found a match
if match_i == sep_len {
f(match_start, i + 1u);
match_i = 0u;
}
i += 1u;
} else {
// Failed match, backtrack
if match_i > 0u {
match_i = 0u;
i = match_start + 1u;
} else {
i += 1u;
}
}
}
}
pure fn iter_between_matches(s: &a/str, sep: &b/str, f: fn(uint, uint)) {
let mut last_end = 0u;
do iter_matches(s, sep) |from, to| {
f(last_end, from);
last_end = to;
}
f(last_end, len(s));
}
/**
* Splits a string into a vector of the substrings separated by a given string
*
* # Example
*
* ~~~
* assert ["", "XXX", "YYY", ""] == split_str(".XXX.YYY.", ".")
* ~~~
*/
pub pure fn split_str(s: &a/str, sep: &b/str) -> ~[~str] {
let mut result = ~[];
do iter_between_matches(s, sep) |from, to| {
unsafe { result.push(raw::slice_bytes(s, from, to)); }
}
result
}
pub pure fn split_str_nonempty(s: &a/str, sep: &b/str) -> ~[~str] {
let mut result = ~[];
do iter_between_matches(s, sep) |from, to| {
if to > from {
unsafe { result.push(raw::slice_bytes(s, from, to)); }
}
}
result
}
/**
* Splits a string into a vector of the substrings separated by LF ('\n')
*/
pub pure fn lines(s: &str) -> ~[~str] { split_char(s, '\n') }
/**
* Splits a string into a vector of the substrings separated by LF ('\n')
* and/or CR LF ("\r\n")
*/
pub pure fn lines_any(s: &str) -> ~[~str] {
vec::map(lines(s), |s| {
let l = len(*s);
let mut cp = copy *s;
if l > 0u && s[l - 1u] == '\r' as u8 {
unsafe { raw::set_len(&mut cp, l - 1u); }
}
cp
})
}
/// Splits a string into a vector of the substrings separated by whitespace
pub pure fn words(s: &str) -> ~[~str] {
split_nonempty(s, |c| char::is_whitespace(c))
}
/** Split a string into a vector of substrings,
* each of which is less than a limit
*/
pub fn split_within(ss: &str, lim: uint) -> ~[~str] {
let words = str::words(ss);
// empty?
if words == ~[] { return ~[]; }
let mut rows : ~[~str] = ~[];
let mut row : ~str = ~"";
for words.each |wptr| {
let word = copy *wptr;
// if adding this word to the row would go over the limit,
// then start a new row
if row.len() + word.len() + 1 > lim {
rows.push(copy row); // save previous row
row = word; // start a new one
} else {
if row.len() > 0 { row += ~" " } // separate words
row += word; // append to this row
}
}
// save the last row
if row != ~"" { rows.push(row); }
rows
}
/// Convert a string to lowercase. ASCII only
pub pure fn to_lower(s: &str) -> ~str {
map(s,
|c| unsafe{(libc::tolower(c as libc::c_char)) as char}
)
}
/// Convert a string to uppercase. ASCII only
pub pure fn to_upper(s: &str) -> ~str {
map(s,
|c| unsafe{(libc::toupper(c as libc::c_char)) as char}
)
}
/**
* Replace all occurrences of one string with another
*
* # Arguments
*
* * s - The string containing substrings to replace
* * from - The string to replace
* * to - The replacement string
*
* # Return value
*
* The original string with all occurances of `from` replaced with `to`
*/
pub pure fn replace(s: &str, from: &str, to: &str) -> ~str {
let mut result = ~"", first = true;
do iter_between_matches(s, from) |start, end| {
if first {
first = false;
} else {
unsafe { push_str(&mut result, to); }
}
unsafe { push_str(&mut result, raw::slice_bytes(s, start, end)); }
}
result
}
/*
Section: Comparing strings
*/
/// Bytewise slice equality
#[cfg(notest)]
#[lang="str_eq"]
pub pure 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)]
pub pure 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(notest)]
#[lang="uniq_str_eq"]
pub pure fn eq(a: &~str, b: &~str) -> bool {
eq_slice(*a, *b)
}
#[cfg(test)]
pub pure fn eq(a: &~str, b: &~str) -> bool {
eq_slice(*a, *b)
}
/// Bytewise slice less than
pure fn lt(a: &str, b: &str) -> bool {
let (a_len, b_len) = (a.len(), b.len());
let mut end = uint::min(a_len, b_len);
let mut i = 0;
while i < end {
let (c_a, c_b) = (a[i], b[i]);
if c_a < c_b { return true; }
if c_a > c_b { return false; }
i += 1;
}
return a_len < b_len;
}
/// Bytewise less than or equal
pub pure fn le(a: &str, b: &str) -> bool {
!lt(b, a)
}
/// Bytewise greater than or equal
pure fn ge(a: &str, b: &str) -> bool {
!lt(a, b)
}
/// Bytewise greater than
pure fn gt(a: &str, b: &str) -> bool {
!le(a, b)
}
#[cfg(notest)]
impl &str : Eq {
#[inline(always)]
pure fn eq(&self, other: & &self/str) -> bool {
eq_slice((*self), (*other))
}
#[inline(always)]
pure fn ne(&self, other: & &self/str) -> bool { !(*self).eq(other) }
}
#[cfg(notest)]
impl ~str : Eq {
#[inline(always)]
pure fn eq(&self, other: &~str) -> bool {
eq_slice((*self), (*other))
}
#[inline(always)]
pure fn ne(&self, other: &~str) -> bool { !(*self).eq(other) }
}
#[cfg(notest)]
impl @str : Eq {
#[inline(always)]
pure fn eq(&self, other: &@str) -> bool {
eq_slice((*self), (*other))
}
#[inline(always)]
pure fn ne(&self, other: &@str) -> bool { !(*self).eq(other) }
}
#[cfg(notest)]
impl ~str : Ord {
#[inline(always)]
pure fn lt(&self, other: &~str) -> bool { lt((*self), (*other)) }
#[inline(always)]
pure fn le(&self, other: &~str) -> bool { le((*self), (*other)) }
#[inline(always)]
pure fn ge(&self, other: &~str) -> bool { ge((*self), (*other)) }
#[inline(always)]
pure fn gt(&self, other: &~str) -> bool { gt((*self), (*other)) }
}
#[cfg(notest)]
impl &str : Ord {
#[inline(always)]
pure fn lt(&self, other: & &self/str) -> bool { lt((*self), (*other)) }
#[inline(always)]
pure fn le(&self, other: & &self/str) -> bool { le((*self), (*other)) }
#[inline(always)]
pure fn ge(&self, other: & &self/str) -> bool { ge((*self), (*other)) }
#[inline(always)]
pure fn gt(&self, other: & &self/str) -> bool { gt((*self), (*other)) }
}
#[cfg(notest)]
impl @str : Ord {
#[inline(always)]
pure fn lt(&self, other: &@str) -> bool { lt((*self), (*other)) }
#[inline(always)]
pure fn le(&self, other: &@str) -> bool { le((*self), (*other)) }
#[inline(always)]
pure fn ge(&self, other: &@str) -> bool { ge((*self), (*other)) }
#[inline(always)]
pure fn gt(&self, other: &@str) -> bool { gt((*self), (*other)) }
}
/*
Section: Iterating through strings
*/
/**
* Return true if a predicate matches all characters or if the string
* contains no characters
*/
pub pure fn all(s: &str, it: fn(char) -> bool) -> bool {
all_between(s, 0u, len(s), it)
}
/**
* Return true if a predicate matches any character (and false if it
* matches none or there are no characters)
*/
pub pure fn any(ss: &str, pred: fn(char) -> bool) -> bool {
!all(ss, |cc| !pred(cc))
}
/// Apply a function to each character
pub pure fn map(ss: &str, ff: fn(char) -> char) -> ~str {
let mut result = ~"";
unsafe {
reserve(&mut result, len(ss));
for chars_each(ss) |cc| {
str::push_char(&mut result, ff(cc));
}
}
result
}
/// Iterate over the bytes in a string
pub pure fn bytes_each(ss: &str, it: fn(u8) -> bool) {
let mut pos = 0u;
let len = len(ss);
while (pos < len) {
if !it(ss[pos]) { return; }
pos += 1u;
}
}
/// Iterate over the bytes in a string
#[inline(always)]
pub pure fn each(s: &str, it: fn(u8) -> bool) {
eachi(s, |_i, b| it(b) )
}
/// Iterate over the bytes in a string, with indices
#[inline(always)]
pub pure fn eachi(s: &str, it: fn(uint, u8) -> bool) {
let mut i = 0u, l = len(s);
while (i < l) {
if !it(i, s[i]) { break; }
i += 1u;
}
}
/// Iterates over the chars in a string
#[inline(always)]
pub pure fn each_char(s: &str, it: fn(char) -> bool) {
each_chari(s, |_i, c| it(c))
}
/// Iterates over the chars in a string, with indices
#[inline(always)]
pub pure fn each_chari(s: &str, it: fn(uint, char) -> bool) {
let mut pos = 0u, ch_pos = 0u;
let len = len(s);
while pos < len {
let CharRange {ch, next} = char_range_at(s, pos);
pos = next;
if !it(ch_pos, ch) { break; }
ch_pos += 1u;
}
}
/// Iterate over the characters in a string
pub pure fn chars_each(s: &str, it: fn(char) -> bool) {
let mut pos = 0u;
let len = len(s);
while (pos < len) {
let CharRange {ch, next} = char_range_at(s, pos);
pos = next;
if !it(ch) { return; }
}
}
/// Apply a function to each substring after splitting by character
pub pure fn split_char_each(ss: &str, cc: char, ff: fn(v: &str) -> bool) {
vec::each(split_char(ss, cc), |s| ff(*s))
}
/**
* Apply a function to each substring after splitting by character, up to
* `count` times
*/
pub pure fn splitn_char_each(ss: &str, sep: char, count: uint,
ff: fn(v: &str) -> bool) {
vec::each(splitn_char(ss, sep, count), |s| ff(*s))
}
/// Apply a function to each word
pub pure fn words_each(ss: &str, ff: fn(v: &str) -> bool) {
vec::each(words(ss), |s| ff(*s))
}
/**
* Apply a function to each line (by '\n')
*/
pub pure fn lines_each(ss: &str, ff: fn(v: &str) -> bool) {
vec::each(lines(ss), |s| ff(*s))
}
/*
Section: Searching
*/
/**
* Returns the byte index of the first matching character
*
* # Arguments
*
* * `s` - The string to search
* * `c` - The character to search for
*
* # Return value
*
* An `option` containing the byte index of the first matching character
* or `none` if there is no match
*/
pub pure fn find_char(s: &str, c: char) -> Option<uint> {
find_char_between(s, c, 0u, len(s))
}
/**
* Returns the byte index of the first matching character beginning
* from a given byte offset
*
* # Arguments
*
* * `s` - The string to search
* * `c` - The character to search for
* * `start` - The byte index to begin searching at, inclusive
*
* # Return value
*
* An `option` containing the byte index of the first matching character
* or `none` if there is no match
*
* # Failure
*
* `start` must be less than or equal to `len(s)`. `start` must be the
* index of a character boundary, as defined by `is_char_boundary`.
*/
pub pure fn find_char_from(s: &str, c: char, start: uint) -> Option<uint> {
find_char_between(s, c, start, len(s))
}
/**
* Returns the byte index of the first matching character within a given range
*
* # Arguments
*
* * `s` - The string to search
* * `c` - The character to search for
* * `start` - The byte index to begin searching at, inclusive
* * `end` - The byte index to end searching at, exclusive
*
* # Return value
*
* An `option` containing the byte index of the first matching character
* or `none` if there is no match
*
* # Failure
*