/
str.rs
2479 lines (2200 loc) · 92.3 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-2014 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.
//
// ignore-lexer-test FIXME #15679
//! Unicode string manipulation (`str` type)
//!
//! # Basic Usage
//!
//! Rust's string type is one of the core primitive types of the language. While
//! represented by the name `str`, the name `str` is not actually a valid type in
//! Rust. Each string must also be decorated with a pointer. `String` is used
//! for an owned string, so there is only one commonly-used `str` type in Rust:
//! `&str`.
//!
//! `&str` is the borrowed string type. This type of string can only be created
//! from other strings, unless it is a static string (see below). As the word
//! "borrowed" implies, this type of string is owned elsewhere, and this string
//! cannot be moved out of.
//!
//! As an example, here's some code that uses a string.
//!
//! ```rust
//! fn main() {
//! let borrowed_string = "This string is borrowed with the 'static lifetime";
//! }
//! ```
//!
//! From the example above, you can guess that Rust's string literals have the
//! `'static` lifetime. This is akin to C's concept of a static string.
//! More precisely, string literals are immutable views with a 'static lifetime
//! (otherwise known as the lifetime of the entire program), and thus have the
//! type `&'static str`.
//!
//! # Representation
//!
//! Rust's string type, `str`, is a sequence of Unicode scalar values encoded as a
//! stream of UTF-8 bytes. All strings are guaranteed to be validly encoded UTF-8
//! sequences. Additionally, strings are not null-terminated and can thus contain
//! null bytes.
//!
//! The actual representation of strings have direct mappings to slices: `&str`
//! is the same as `&[u8]`.
#![doc(primitive = "str")]
use core::default::Default;
use core::fmt;
use core::cmp;
use core::iter::AdditiveIterator;
use core::kinds::Sized;
use core::prelude::{Char, Clone, Eq, Equiv};
use core::prelude::{Iterator, SlicePrelude, None, Option, Ord, Ordering};
use core::prelude::{PartialEq, PartialOrd, Result, AsSlice, Some, Tuple2};
use core::prelude::{range};
use hash;
use ring_buf::RingBuf;
use string::String;
use unicode;
use vec::Vec;
pub use core::str::{from_utf8, CharEq, Chars, CharOffsets};
pub use core::str::{Bytes, CharSplits};
pub use core::str::{CharSplitsN, AnyLines, MatchIndices, StrSplits};
pub use core::str::{Utf16CodeUnits, eq_slice, is_utf8, is_utf16, Utf16Items};
pub use core::str::{Utf16Item, ScalarValue, LoneSurrogate, utf16_items};
pub use core::str::{truncate_utf16_at_nul, utf8_char_width, CharRange};
pub use core::str::{Str, StrPrelude};
pub use unicode::str::{UnicodeStrPrelude, Words, Graphemes, GraphemeIndices};
// FIXME(conventions): ensure bit/char conventions are followed by str's API
/*
Section: Creating a string
*/
/// Methods for vectors of strings.
pub trait StrVector for Sized? {
/// Concatenates a vector of strings.
///
/// # Example
///
/// ```rust
/// let first = "Restaurant at the End of the".to_string();
/// let second = " Universe".to_string();
/// let string_vec = vec![first, second];
/// assert_eq!(string_vec.concat(), "Restaurant at the End of the Universe".to_string());
/// ```
fn concat(&self) -> String;
/// Concatenates a vector of strings, placing a given separator between each.
///
/// # Example
///
/// ```rust
/// let first = "Roast".to_string();
/// let second = "Sirloin Steak".to_string();
/// let string_vec = vec![first, second];
/// assert_eq!(string_vec.connect(", "), "Roast, Sirloin Steak".to_string());
/// ```
fn connect(&self, sep: &str) -> String;
}
impl<S: Str> StrVector for [S] {
fn concat(&self) -> String {
if self.is_empty() {
return String::new();
}
// `len` calculation may overflow but push_str will check boundaries
let len = self.iter().map(|s| s.as_slice().len()).sum();
let mut result = String::with_capacity(len);
for s in self.iter() {
result.push_str(s.as_slice())
}
result
}
fn connect(&self, sep: &str) -> String {
if self.is_empty() {
return String::new();
}
// concat is faster
if sep.is_empty() {
return self.concat();
}
// this is wrong without the guarantee that `self` is non-empty
// `len` calculation may overflow but push_str but will check boundaries
let len = sep.len() * (self.len() - 1)
+ self.iter().map(|s| s.as_slice().len()).sum();
let mut result = String::with_capacity(len);
let mut first = true;
for s in self.iter() {
if first {
first = false;
} else {
result.push_str(sep);
}
result.push_str(s.as_slice());
}
result
}
}
impl<S: Str> StrVector for Vec<S> {
#[inline]
fn concat(&self) -> String {
self.as_slice().concat()
}
#[inline]
fn connect(&self, sep: &str) -> String {
self.as_slice().connect(sep)
}
}
/*
Section: Iterators
*/
// Helper functions used for Unicode normalization
fn canonical_sort(comb: &mut [(char, u8)]) {
let len = comb.len();
for i in range(0, len) {
let mut swapped = false;
for j in range(1, len-i) {
let class_a = *comb[j-1].ref1();
let class_b = *comb[j].ref1();
if class_a != 0 && class_b != 0 && class_a > class_b {
comb.swap(j-1, j);
swapped = true;
}
}
if !swapped { break; }
}
}
#[deriving(Clone)]
enum DecompositionType {
Canonical,
Compatible
}
/// External iterator for a string's decomposition's characters.
/// Use with the `std::iter` module.
#[deriving(Clone)]
pub struct Decompositions<'a> {
kind: DecompositionType,
iter: Chars<'a>,
buffer: Vec<(char, u8)>,
sorted: bool
}
impl<'a> Iterator<char> for Decompositions<'a> {
#[inline]
fn next(&mut self) -> Option<char> {
match self.buffer.as_slice().head() {
Some(&(c, 0)) => {
self.sorted = false;
self.buffer.remove(0);
return Some(c);
}
Some(&(c, _)) if self.sorted => {
self.buffer.remove(0);
return Some(c);
}
_ => self.sorted = false
}
let decomposer = match self.kind {
Canonical => unicode::char::decompose_canonical,
Compatible => unicode::char::decompose_compatible
};
if !self.sorted {
for ch in self.iter {
let buffer = &mut self.buffer;
let sorted = &mut self.sorted;
decomposer(ch, |d| {
let class = unicode::char::canonical_combining_class(d);
if class == 0 && !*sorted {
canonical_sort(buffer.as_mut_slice());
*sorted = true;
}
buffer.push((d, class));
});
if *sorted { break }
}
}
if !self.sorted {
canonical_sort(self.buffer.as_mut_slice());
self.sorted = true;
}
match self.buffer.remove(0) {
Some((c, 0)) => {
self.sorted = false;
Some(c)
}
Some((c, _)) => Some(c),
None => None
}
}
fn size_hint(&self) -> (uint, Option<uint>) {
let (lower, _) = self.iter.size_hint();
(lower, None)
}
}
#[deriving(Clone)]
enum RecompositionState {
Composing,
Purging,
Finished
}
/// External iterator for a string's recomposition's characters.
/// Use with the `std::iter` module.
#[deriving(Clone)]
pub struct Recompositions<'a> {
iter: Decompositions<'a>,
state: RecompositionState,
buffer: RingBuf<char>,
composee: Option<char>,
last_ccc: Option<u8>
}
impl<'a> Iterator<char> for Recompositions<'a> {
#[inline]
fn next(&mut self) -> Option<char> {
loop {
match self.state {
Composing => {
for ch in self.iter {
let ch_class = unicode::char::canonical_combining_class(ch);
if self.composee.is_none() {
if ch_class != 0 {
return Some(ch);
}
self.composee = Some(ch);
continue;
}
let k = self.composee.clone().unwrap();
match self.last_ccc {
None => {
match unicode::char::compose(k, ch) {
Some(r) => {
self.composee = Some(r);
continue;
}
None => {
if ch_class == 0 {
self.composee = Some(ch);
return Some(k);
}
self.buffer.push_back(ch);
self.last_ccc = Some(ch_class);
}
}
}
Some(l_class) => {
if l_class >= ch_class {
// `ch` is blocked from `composee`
if ch_class == 0 {
self.composee = Some(ch);
self.last_ccc = None;
self.state = Purging;
return Some(k);
}
self.buffer.push_back(ch);
self.last_ccc = Some(ch_class);
continue;
}
match unicode::char::compose(k, ch) {
Some(r) => {
self.composee = Some(r);
continue;
}
None => {
self.buffer.push_back(ch);
self.last_ccc = Some(ch_class);
}
}
}
}
}
self.state = Finished;
if self.composee.is_some() {
return self.composee.take();
}
}
Purging => {
match self.buffer.pop_front() {
None => self.state = Composing,
s => return s
}
}
Finished => {
match self.buffer.pop_front() {
None => return self.composee.take(),
s => return s
}
}
}
}
}
}
/// Replaces 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 occurrences of `from` replaced with `to`.
///
/// # Example
///
/// ```rust
/// use std::str;
/// let string = "orange";
/// let new_string = str::replace(string, "or", "str");
/// assert_eq!(new_string.as_slice(), "strange");
/// ```
pub fn replace(s: &str, from: &str, to: &str) -> String {
let mut result = String::new();
let mut last_end = 0;
for (start, end) in s.match_indices(from) {
result.push_str(unsafe{raw::slice_bytes(s, last_end, start)});
result.push_str(to);
last_end = end;
}
result.push_str(unsafe{raw::slice_bytes(s, last_end, s.len())});
result
}
/*
Section: Misc
*/
// Return the initial codepoint accumulator for the first byte.
// The first byte is special, only want bottom 5 bits for width 2, 4 bits
// for width 3, and 3 bits for width 4
macro_rules! utf8_first_byte(
($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
)
// return the value of $ch updated with continuation byte $byte
macro_rules! utf8_acc_cont_byte(
($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63u8) as u32)
)
/*
Section: MaybeOwned
*/
/// A string type that can hold either a `String` or a `&str`.
/// This can be useful as an optimization when an allocation is sometimes
/// needed but not always.
pub enum MaybeOwned<'a> {
/// A borrowed string.
Slice(&'a str),
/// An owned string.
Owned(String)
}
/// A specialization of `MaybeOwned` to be sendable.
pub type SendStr = MaybeOwned<'static>;
impl<'a> MaybeOwned<'a> {
/// Returns `true` if this `MaybeOwned` wraps an owned string.
///
/// # Example
///
/// ```rust
/// let string = String::from_str("orange");
/// let maybe_owned_string = string.into_maybe_owned();
/// assert_eq!(true, maybe_owned_string.is_owned());
/// ```
#[inline]
pub fn is_owned(&self) -> bool {
match *self {
Slice(_) => false,
Owned(_) => true
}
}
/// Returns `true` if this `MaybeOwned` wraps a borrowed string.
///
/// # Example
///
/// ```rust
/// let string = "orange";
/// let maybe_owned_string = string.as_slice().into_maybe_owned();
/// assert_eq!(true, maybe_owned_string.is_slice());
/// ```
#[inline]
pub fn is_slice(&self) -> bool {
match *self {
Slice(_) => true,
Owned(_) => false
}
}
/// Return the number of bytes in this string.
#[inline]
pub fn len(&self) -> uint { self.as_slice().len() }
/// Returns true if the string contains no bytes
#[inline]
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
/// Trait for moving into a `MaybeOwned`.
pub trait IntoMaybeOwned<'a> {
/// Moves `self` into a `MaybeOwned`.
fn into_maybe_owned(self) -> MaybeOwned<'a>;
}
impl<'a> IntoMaybeOwned<'a> for String {
/// # Example
///
/// ```rust
/// let owned_string = String::from_str("orange");
/// let maybe_owned_string = owned_string.into_maybe_owned();
/// assert_eq!(true, maybe_owned_string.is_owned());
/// ```
#[inline]
fn into_maybe_owned(self) -> MaybeOwned<'a> {
Owned(self)
}
}
impl<'a> IntoMaybeOwned<'a> for &'a str {
/// # Example
///
/// ```rust
/// let string = "orange";
/// let maybe_owned_str = string.as_slice().into_maybe_owned();
/// assert_eq!(false, maybe_owned_str.is_owned());
/// ```
#[inline]
fn into_maybe_owned(self) -> MaybeOwned<'a> { Slice(self) }
}
impl<'a> IntoMaybeOwned<'a> for MaybeOwned<'a> {
/// # Example
///
/// ```rust
/// let str = "orange";
/// let maybe_owned_str = str.as_slice().into_maybe_owned();
/// let maybe_maybe_owned_str = maybe_owned_str.into_maybe_owned();
/// assert_eq!(false, maybe_maybe_owned_str.is_owned());
/// ```
#[inline]
fn into_maybe_owned(self) -> MaybeOwned<'a> { self }
}
impl<'a> PartialEq for MaybeOwned<'a> {
#[inline]
fn eq(&self, other: &MaybeOwned) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<'a> Eq for MaybeOwned<'a> {}
impl<'a> PartialOrd for MaybeOwned<'a> {
#[inline]
fn partial_cmp(&self, other: &MaybeOwned) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Ord for MaybeOwned<'a> {
#[inline]
fn cmp(&self, other: &MaybeOwned) -> Ordering {
self.as_slice().cmp(other.as_slice())
}
}
impl<'a, S: Str> Equiv<S> for MaybeOwned<'a> {
#[inline]
fn equiv(&self, other: &S) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<'a> Str for MaybeOwned<'a> {
#[inline]
fn as_slice<'b>(&'b self) -> &'b str {
match *self {
Slice(s) => s,
Owned(ref s) => s.as_slice()
}
}
}
impl<'a> StrAllocating for MaybeOwned<'a> {
#[inline]
fn into_string(self) -> String {
match self {
Slice(s) => String::from_str(s),
Owned(s) => s
}
}
}
impl<'a> Clone for MaybeOwned<'a> {
#[inline]
fn clone(&self) -> MaybeOwned<'a> {
match *self {
Slice(s) => Slice(s),
Owned(ref s) => Owned(String::from_str(s.as_slice()))
}
}
}
impl<'a> Default for MaybeOwned<'a> {
#[inline]
fn default() -> MaybeOwned<'a> { Slice("") }
}
impl<'a, H: hash::Writer> hash::Hash<H> for MaybeOwned<'a> {
#[inline]
fn hash(&self, hasher: &mut H) {
self.as_slice().hash(hasher)
}
}
impl<'a> fmt::Show for MaybeOwned<'a> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Slice(ref s) => s.fmt(f),
Owned(ref s) => s.fmt(f)
}
}
}
/// Unsafe string operations.
pub mod raw {
pub use core::str::raw::{from_utf8, c_str_to_static_slice, slice_bytes};
pub use core::str::raw::{slice_unchecked};
}
/*
Section: Trait implementations
*/
/// Any string that can be represented as a slice.
pub trait StrAllocating: Str {
/// Converts `self` into a `String`, not making a copy if possible.
fn into_string(self) -> String;
/// Escapes each char in `s` with `char::escape_default`.
fn escape_default(&self) -> String {
let me = self.as_slice();
let mut out = String::with_capacity(me.len());
for c in me.chars() {
c.escape_default(|c| out.push(c));
}
out
}
/// Escapes each char in `s` with `char::escape_unicode`.
fn escape_unicode(&self) -> String {
let me = self.as_slice();
let mut out = String::with_capacity(me.len());
for c in me.chars() {
c.escape_unicode(|c| out.push(c));
}
out
}
/// Replaces all occurrences of one string with another.
///
/// # Arguments
///
/// * `from` - The string to replace
/// * `to` - The replacement string
///
/// # Return value
///
/// The original string with all occurrences of `from` replaced with `to`.
///
/// # Example
///
/// ```rust
/// let s = "Do you know the muffin man,
/// The muffin man, the muffin man, ...".to_string();
///
/// assert_eq!(s.replace("muffin man", "little lamb"),
/// "Do you know the little lamb,
/// The little lamb, the little lamb, ...".to_string());
///
/// // not found, so no change.
/// assert_eq!(s.replace("cookie monster", "little lamb"), s);
/// ```
fn replace(&self, from: &str, to: &str) -> String {
let me = self.as_slice();
let mut result = String::new();
let mut last_end = 0;
for (start, end) in me.match_indices(from) {
result.push_str(unsafe{raw::slice_bytes(me, last_end, start)});
result.push_str(to);
last_end = end;
}
result.push_str(unsafe{raw::slice_bytes(me, last_end, me.len())});
result
}
/// Given a string, makes a new string with repeated copies of it.
fn repeat(&self, nn: uint) -> String {
let me = self.as_slice();
let mut ret = String::with_capacity(nn * me.len());
for _ in range(0, nn) {
ret.push_str(me);
}
ret
}
/// Returns the Levenshtein Distance between two strings.
fn lev_distance(&self, t: &str) -> uint {
let me = self.as_slice();
if me.is_empty() { return t.char_len(); }
if t.is_empty() { return me.char_len(); }
let mut dcol = Vec::from_fn(t.len() + 1, |x| x);
let mut t_last = 0;
for (i, sc) in me.chars().enumerate() {
let mut current = i;
dcol[0] = current + 1;
for (j, tc) in t.chars().enumerate() {
let next = dcol[j + 1];
if sc == tc {
dcol[j + 1] = current;
} else {
dcol[j + 1] = cmp::min(current, next);
dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
}
current = next;
t_last = j;
}
}
dcol[t_last + 1]
}
/// Returns an iterator over the string in Unicode Normalization Form D
/// (canonical decomposition).
#[inline]
fn nfd_chars<'a>(&'a self) -> Decompositions<'a> {
Decompositions {
iter: self.as_slice().chars(),
buffer: Vec::new(),
sorted: false,
kind: Canonical
}
}
/// Returns an iterator over the string in Unicode Normalization Form KD
/// (compatibility decomposition).
#[inline]
fn nfkd_chars<'a>(&'a self) -> Decompositions<'a> {
Decompositions {
iter: self.as_slice().chars(),
buffer: Vec::new(),
sorted: false,
kind: Compatible
}
}
/// An Iterator over the string in Unicode Normalization Form C
/// (canonical decomposition followed by canonical composition).
#[inline]
fn nfc_chars<'a>(&'a self) -> Recompositions<'a> {
Recompositions {
iter: self.nfd_chars(),
state: Composing,
buffer: RingBuf::new(),
composee: None,
last_ccc: None
}
}
/// An Iterator over the string in Unicode Normalization Form KC
/// (compatibility decomposition followed by canonical composition).
#[inline]
fn nfkc_chars<'a>(&'a self) -> Recompositions<'a> {
Recompositions {
iter: self.nfkd_chars(),
state: Composing,
buffer: RingBuf::new(),
composee: None,
last_ccc: None
}
}
}
impl<'a> StrAllocating for &'a str {
#[inline]
fn into_string(self) -> String {
String::from_str(self)
}
}
#[cfg(test)]
mod tests {
use std::iter::AdditiveIterator;
use std::iter::range;
use std::default::Default;
use std::char::Char;
use std::clone::Clone;
use std::cmp::{Equal, Greater, Less, Ord, PartialOrd, Equiv};
use std::option::{Some, None};
use std::ptr::RawPtr;
use std::iter::{Iterator, DoubleEndedIterator};
use super::*;
use std::slice::{AsSlice, SlicePrelude};
use string::String;
use vec::Vec;
use slice::CloneSliceAllocPrelude;
use unicode::char::UnicodeChar;
#[test]
fn test_eq_slice() {
assert!((eq_slice("foobar".slice(0, 3), "foo")));
assert!((eq_slice("barfoo".slice(3, 6), "foo")));
assert!((!eq_slice("foo1", "foo2")));
}
#[test]
fn test_le() {
assert!("" <= "");
assert!("" <= "foo");
assert!("foo" <= "foo");
assert!("foo" != "bar");
}
#[test]
fn test_len() {
assert_eq!("".len(), 0u);
assert_eq!("hello world".len(), 11u);
assert_eq!("\x63".len(), 1u);
assert_eq!("\u00a2".len(), 2u);
assert_eq!("\u03c0".len(), 2u);
assert_eq!("\u2620".len(), 3u);
assert_eq!("\U0001d11e".len(), 4u);
assert_eq!("".char_len(), 0u);
assert_eq!("hello world".char_len(), 11u);
assert_eq!("\x63".char_len(), 1u);
assert_eq!("\u00a2".char_len(), 1u);
assert_eq!("\u03c0".char_len(), 1u);
assert_eq!("\u2620".char_len(), 1u);
assert_eq!("\U0001d11e".char_len(), 1u);
assert_eq!("ประเทศไทย中华Việt Nam".char_len(), 19u);
assert_eq!("hello".width(false), 10u);
assert_eq!("hello".width(true), 10u);
assert_eq!("\0\0\0\0\0".width(false), 0u);
assert_eq!("\0\0\0\0\0".width(true), 0u);
assert_eq!("".width(false), 0u);
assert_eq!("".width(true), 0u);
assert_eq!("\u2081\u2082\u2083\u2084".width(false), 4u);
assert_eq!("\u2081\u2082\u2083\u2084".width(true), 8u);
}
#[test]
fn test_find() {
assert_eq!("hello".find('l'), Some(2u));
assert_eq!("hello".find(|c:char| c == 'o'), Some(4u));
assert!("hello".find('x').is_none());
assert!("hello".find(|c:char| c == 'x').is_none());
assert_eq!("ประเทศไทย中华Việt Nam".find('华'), Some(30u));
assert_eq!("ประเทศไทย中华Việt Nam".find(|c: char| c == '华'), Some(30u));
}
#[test]
fn test_rfind() {
assert_eq!("hello".rfind('l'), Some(3u));
assert_eq!("hello".rfind(|c:char| c == 'o'), Some(4u));
assert!("hello".rfind('x').is_none());
assert!("hello".rfind(|c:char| c == 'x').is_none());
assert_eq!("ประเทศไทย中华Việt Nam".rfind('华'), Some(30u));
assert_eq!("ประเทศไทย中华Việt Nam".rfind(|c: char| c == '华'), Some(30u));
}
#[test]
fn test_collect() {
let empty = String::from_str("");
let s: String = empty.as_slice().chars().collect();
assert_eq!(empty, s);
let data = String::from_str("ประเทศไทย中");
let s: String = data.as_slice().chars().collect();
assert_eq!(data, s);
}
#[test]
fn test_into_bytes() {
let data = String::from_str("asdf");
let buf = data.into_bytes();
assert_eq!(b"asdf", buf.as_slice());
}
#[test]
fn test_find_str() {
// byte positions
assert_eq!("".find_str(""), Some(0u));
assert!("banana".find_str("apple pie").is_none());
let data = "abcabc";
assert_eq!(data.slice(0u, 6u).find_str("ab"), Some(0u));
assert_eq!(data.slice(2u, 6u).find_str("ab"), Some(3u - 2u));
assert!(data.slice(2u, 4u).find_str("ab").is_none());
let string = "ประเทศไทย中华Việt Nam";
let mut data = String::from_str(string);
data.push_str(string);
assert!(data.as_slice().find_str("ไท华").is_none());
assert_eq!(data.as_slice().slice(0u, 43u).find_str(""), Some(0u));
assert_eq!(data.as_slice().slice(6u, 43u).find_str(""), Some(6u - 6u));
assert_eq!(data.as_slice().slice(0u, 43u).find_str("ประ"), Some( 0u));
assert_eq!(data.as_slice().slice(0u, 43u).find_str("ทศไ"), Some(12u));
assert_eq!(data.as_slice().slice(0u, 43u).find_str("ย中"), Some(24u));
assert_eq!(data.as_slice().slice(0u, 43u).find_str("iệt"), Some(34u));
assert_eq!(data.as_slice().slice(0u, 43u).find_str("Nam"), Some(40u));
assert_eq!(data.as_slice().slice(43u, 86u).find_str("ประ"), Some(43u - 43u));
assert_eq!(data.as_slice().slice(43u, 86u).find_str("ทศไ"), Some(55u - 43u));
assert_eq!(data.as_slice().slice(43u, 86u).find_str("ย中"), Some(67u - 43u));
assert_eq!(data.as_slice().slice(43u, 86u).find_str("iệt"), Some(77u - 43u));
assert_eq!(data.as_slice().slice(43u, 86u).find_str("Nam"), Some(83u - 43u));
}
#[test]
fn test_slice_chars() {
fn t(a: &str, b: &str, start: uint) {
assert_eq!(a.slice_chars(start, start + b.char_len()), b);
}
t("", "", 0);
t("hello", "llo", 2);
t("hello", "el", 1);
t("αβλ", "β", 1);
t("αβλ", "", 3);
assert_eq!("ะเทศไท", "ประเทศไทย中华Việt Nam".slice_chars(2, 8));
}
#[test]
fn test_concat() {
fn t(v: &[String], s: &str) {
assert_eq!(v.concat().as_slice(), s);
}
t([String::from_str("you"), String::from_str("know"),
String::from_str("I'm"),
String::from_str("no"), String::from_str("good")],
"youknowI'mnogood");
let v: &[String] = [];
t(v, "");
t([String::from_str("hi")], "hi");
}
#[test]
fn test_connect() {
fn t(v: &[String], sep: &str, s: &str) {
assert_eq!(v.connect(sep).as_slice(), s);
}
t([String::from_str("you"), String::from_str("know"),
String::from_str("I'm"),
String::from_str("no"), String::from_str("good")],
" ", "you know I'm no good");
let v: &[String] = [];
t(v, " ", "");
t([String::from_str("hi")], " ", "hi");
}
#[test]
fn test_concat_slices() {
fn t(v: &[&str], s: &str) {
assert_eq!(v.concat().as_slice(), s);
}
t(["you", "know", "I'm", "no", "good"], "youknowI'mnogood");
let v: &[&str] = [];
t(v, "");
t(["hi"], "hi");
}
#[test]
fn test_connect_slices() {
fn t(v: &[&str], sep: &str, s: &str) {
assert_eq!(v.connect(sep).as_slice(), s);
}
t(["you", "know", "I'm", "no", "good"],
" ", "you know I'm no good");
t([], " ", "");
t(["hi"], " ", "hi");
}
#[test]
fn test_repeat() {
assert_eq!("x".repeat(4), String::from_str("xxxx"));
assert_eq!("hi".repeat(4), String::from_str("hihihihi"));
assert_eq!("ไท华".repeat(3), String::from_str("ไท华ไท华ไท华"));
assert_eq!("".repeat(4), String::from_str(""));
assert_eq!("hi".repeat(0), String::from_str(""));
}
#[test]
fn test_unsafe_slice() {
assert_eq!("ab", unsafe {raw::slice_bytes("abc", 0, 2)});
assert_eq!("bc", unsafe {raw::slice_bytes("abc", 1, 3)});
assert_eq!("", unsafe {raw::slice_bytes("abc", 1, 1)});
fn a_million_letter_a() -> String {
let mut i = 0u;
let mut rs = String::new();
while i < 100000 {
rs.push_str("aaaaaaaaaa");
i += 1;
}
rs
}
fn half_a_million_letter_a() -> String {
let mut i = 0u;
let mut rs = String::new();
while i < 100000 {
rs.push_str("aaaaa");
i += 1;
}
rs