]> git.lizzy.rs Git - rust.git/blob - src/libcollections/str.rs
std: Fixup some missing stabilization on str
[rust.git] / src / libcollections / str.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //
11 // ignore-lexer-test FIXME #15679
12
13 //! Unicode string manipulation (`str` type)
14 //!
15 //! # Basic Usage
16 //!
17 //! Rust's string type is one of the core primitive types of the language. While
18 //! represented by the name `str`, the name `str` is not actually a valid type in
19 //! Rust. Each string must also be decorated with a pointer. `String` is used
20 //! for an owned string, so there is only one commonly-used `str` type in Rust:
21 //! `&str`.
22 //!
23 //! `&str` is the borrowed string type. This type of string can only be created
24 //! from other strings, unless it is a static string (see below). As the word
25 //! "borrowed" implies, this type of string is owned elsewhere, and this string
26 //! cannot be moved out of.
27 //!
28 //! As an example, here's some code that uses a string.
29 //!
30 //! ```rust
31 //! fn main() {
32 //!     let borrowed_string = "This string is borrowed with the 'static lifetime";
33 //! }
34 //! ```
35 //!
36 //! From the example above, you can guess that Rust's string literals have the
37 //! `'static` lifetime. This is akin to C's concept of a static string.
38 //! More precisely, string literals are immutable views with a 'static lifetime
39 //! (otherwise known as the lifetime of the entire program), and thus have the
40 //! type `&'static str`.
41 //!
42 //! # Representation
43 //!
44 //! Rust's string type, `str`, is a sequence of Unicode scalar values encoded as a
45 //! stream of UTF-8 bytes. All [strings](../../reference.html#literals) are
46 //! guaranteed to be validly encoded UTF-8 sequences. Additionally, strings are
47 //! not null-terminated and can thus contain null bytes.
48 //!
49 //! The actual representation of strings have direct mappings to slices: `&str`
50 //! is the same as `&[u8]`.
51
52 #![doc(primitive = "str")]
53 #![stable]
54
55 use self::RecompositionState::*;
56 use self::DecompositionType::*;
57
58 use core::borrow::{BorrowFrom, ToOwned};
59 use core::char::Char;
60 use core::clone::Clone;
61 use core::iter::AdditiveIterator;
62 use core::iter::{range, Iterator, IteratorExt};
63 use core::kinds::Sized;
64 use core::ops;
65 use core::option::Option::{self, Some, None};
66 use core::slice::AsSlice;
67 use core::str as core_str;
68 use unicode::str::{UnicodeStr, Utf16Encoder};
69
70 use ring_buf::RingBuf;
71 use slice::SliceExt;
72 use string::String;
73 use unicode;
74 use vec::Vec;
75 use slice::SliceConcatExt;
76
77 pub use core::str::{FromStr, Utf8Error, Str};
78 pub use core::str::{Lines, LinesAny, MatchIndices, SplitStr, CharRange};
79 pub use core::str::{Split, SplitTerminator};
80 pub use core::str::{SplitN, RSplitN};
81 pub use core::str::{from_utf8, CharEq, Chars, CharIndices, Bytes};
82 pub use core::str::{from_utf8_unchecked, from_c_str};
83 pub use unicode::str::{Words, Graphemes, GraphemeIndices};
84
85 /*
86 Section: Creating a string
87 */
88
89 impl<S: Str> SliceConcatExt<str, String> for [S] {
90     fn concat(&self) -> String {
91         let s = self.as_slice();
92
93         if s.is_empty() {
94             return String::new();
95         }
96
97         // `len` calculation may overflow but push_str will check boundaries
98         let len = s.iter().map(|s| s.as_slice().len()).sum();
99         let mut result = String::with_capacity(len);
100
101         for s in s.iter() {
102             result.push_str(s.as_slice())
103         }
104
105         result
106     }
107
108     fn connect(&self, sep: &str) -> String {
109         let s = self.as_slice();
110
111         if s.is_empty() {
112             return String::new();
113         }
114
115         // concat is faster
116         if sep.is_empty() {
117             return s.concat();
118         }
119
120         // this is wrong without the guarantee that `self` is non-empty
121         // `len` calculation may overflow but push_str but will check boundaries
122         let len = sep.len() * (s.len() - 1)
123             + s.iter().map(|s| s.as_slice().len()).sum();
124         let mut result = String::with_capacity(len);
125         let mut first = true;
126
127         for s in s.iter() {
128             if first {
129                 first = false;
130             } else {
131                 result.push_str(sep);
132             }
133             result.push_str(s.as_slice());
134         }
135         result
136     }
137 }
138
139 /*
140 Section: Iterators
141 */
142
143 // Helper functions used for Unicode normalization
144 fn canonical_sort(comb: &mut [(char, u8)]) {
145     let len = comb.len();
146     for i in range(0, len) {
147         let mut swapped = false;
148         for j in range(1, len-i) {
149             let class_a = comb[j-1].1;
150             let class_b = comb[j].1;
151             if class_a != 0 && class_b != 0 && class_a > class_b {
152                 comb.swap(j-1, j);
153                 swapped = true;
154             }
155         }
156         if !swapped { break; }
157     }
158 }
159
160 #[derive(Clone)]
161 enum DecompositionType {
162     Canonical,
163     Compatible
164 }
165
166 /// External iterator for a string's decomposition's characters.
167 /// Use with the `std::iter` module.
168 #[derive(Clone)]
169 pub struct Decompositions<'a> {
170     kind: DecompositionType,
171     iter: Chars<'a>,
172     buffer: Vec<(char, u8)>,
173     sorted: bool
174 }
175
176 impl<'a> Iterator for Decompositions<'a> {
177     type Item = char;
178
179     #[inline]
180     fn next(&mut self) -> Option<char> {
181         match self.buffer.first() {
182             Some(&(c, 0)) => {
183                 self.sorted = false;
184                 self.buffer.remove(0);
185                 return Some(c);
186             }
187             Some(&(c, _)) if self.sorted => {
188                 self.buffer.remove(0);
189                 return Some(c);
190             }
191             _ => self.sorted = false
192         }
193
194         if !self.sorted {
195             for ch in self.iter {
196                 let buffer = &mut self.buffer;
197                 let sorted = &mut self.sorted;
198                 {
199                     let callback = |&mut: d| {
200                         let class =
201                             unicode::char::canonical_combining_class(d);
202                         if class == 0 && !*sorted {
203                             canonical_sort(buffer.as_mut_slice());
204                             *sorted = true;
205                         }
206                         buffer.push((d, class));
207                     };
208                     match self.kind {
209                         Canonical => {
210                             unicode::char::decompose_canonical(ch, callback)
211                         }
212                         Compatible => {
213                             unicode::char::decompose_compatible(ch, callback)
214                         }
215                     }
216                 }
217                 if *sorted {
218                     break
219                 }
220             }
221         }
222
223         if !self.sorted {
224             canonical_sort(self.buffer.as_mut_slice());
225             self.sorted = true;
226         }
227
228         if self.buffer.is_empty() {
229             None
230         } else {
231             match self.buffer.remove(0) {
232                 (c, 0) => {
233                     self.sorted = false;
234                     Some(c)
235                 }
236                 (c, _) => Some(c),
237             }
238         }
239     }
240
241     fn size_hint(&self) -> (uint, Option<uint>) {
242         let (lower, _) = self.iter.size_hint();
243         (lower, None)
244     }
245 }
246
247 #[derive(Clone)]
248 enum RecompositionState {
249     Composing,
250     Purging,
251     Finished
252 }
253
254 /// External iterator for a string's recomposition's characters.
255 /// Use with the `std::iter` module.
256 #[derive(Clone)]
257 pub struct Recompositions<'a> {
258     iter: Decompositions<'a>,
259     state: RecompositionState,
260     buffer: RingBuf<char>,
261     composee: Option<char>,
262     last_ccc: Option<u8>
263 }
264
265 impl<'a> Iterator for Recompositions<'a> {
266     type Item = char;
267
268     #[inline]
269     fn next(&mut self) -> Option<char> {
270         loop {
271             match self.state {
272                 Composing => {
273                     for ch in self.iter {
274                         let ch_class = unicode::char::canonical_combining_class(ch);
275                         if self.composee.is_none() {
276                             if ch_class != 0 {
277                                 return Some(ch);
278                             }
279                             self.composee = Some(ch);
280                             continue;
281                         }
282                         let k = self.composee.clone().unwrap();
283
284                         match self.last_ccc {
285                             None => {
286                                 match unicode::char::compose(k, ch) {
287                                     Some(r) => {
288                                         self.composee = Some(r);
289                                         continue;
290                                     }
291                                     None => {
292                                         if ch_class == 0 {
293                                             self.composee = Some(ch);
294                                             return Some(k);
295                                         }
296                                         self.buffer.push_back(ch);
297                                         self.last_ccc = Some(ch_class);
298                                     }
299                                 }
300                             }
301                             Some(l_class) => {
302                                 if l_class >= ch_class {
303                                     // `ch` is blocked from `composee`
304                                     if ch_class == 0 {
305                                         self.composee = Some(ch);
306                                         self.last_ccc = None;
307                                         self.state = Purging;
308                                         return Some(k);
309                                     }
310                                     self.buffer.push_back(ch);
311                                     self.last_ccc = Some(ch_class);
312                                     continue;
313                                 }
314                                 match unicode::char::compose(k, ch) {
315                                     Some(r) => {
316                                         self.composee = Some(r);
317                                         continue;
318                                     }
319                                     None => {
320                                         self.buffer.push_back(ch);
321                                         self.last_ccc = Some(ch_class);
322                                     }
323                                 }
324                             }
325                         }
326                     }
327                     self.state = Finished;
328                     if self.composee.is_some() {
329                         return self.composee.take();
330                     }
331                 }
332                 Purging => {
333                     match self.buffer.pop_front() {
334                         None => self.state = Composing,
335                         s => return s
336                     }
337                 }
338                 Finished => {
339                     match self.buffer.pop_front() {
340                         None => return self.composee.take(),
341                         s => return s
342                     }
343                 }
344             }
345         }
346     }
347 }
348
349 /// External iterator for a string's UTF16 codeunits.
350 /// Use with the `std::iter` module.
351 #[derive(Clone)]
352 pub struct Utf16Units<'a> {
353     encoder: Utf16Encoder<Chars<'a>>
354 }
355
356 impl<'a> Iterator for Utf16Units<'a> {
357     type Item = u16;
358
359     #[inline]
360     fn next(&mut self) -> Option<u16> { self.encoder.next() }
361
362     #[inline]
363     fn size_hint(&self) -> (uint, Option<uint>) { self.encoder.size_hint() }
364 }
365
366 /*
367 Section: Misc
368 */
369
370 // Return the initial codepoint accumulator for the first byte.
371 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
372 // for width 3, and 3 bits for width 4
373 macro_rules! utf8_first_byte {
374     ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as u32)
375 }
376
377 // return the value of $ch updated with continuation byte $byte
378 macro_rules! utf8_acc_cont_byte {
379     ($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63u8) as u32)
380 }
381
382 #[unstable = "trait is unstable"]
383 impl BorrowFrom<String> for str {
384     fn borrow_from(owned: &String) -> &str { owned[] }
385 }
386
387 #[unstable = "trait is unstable"]
388 impl ToOwned<String> for str {
389     fn to_owned(&self) -> String {
390         unsafe {
391             String::from_utf8_unchecked(self.as_bytes().to_owned())
392         }
393     }
394 }
395
396 /*
397 Section: CowString
398 */
399
400 /*
401 Section: Trait implementations
402 */
403
404 /// Any string that can be represented as a slice.
405 #[stable]
406 pub trait StrExt for Sized?: ops::Slice<uint, str> {
407     /// Escapes each char in `s` with `char::escape_default`.
408     #[unstable = "return type may change to be an iterator"]
409     fn escape_default(&self) -> String {
410         self.chars().flat_map(|c| c.escape_default()).collect()
411     }
412
413     /// Escapes each char in `s` with `char::escape_unicode`.
414     #[unstable = "return type may change to be an iterator"]
415     fn escape_unicode(&self) -> String {
416         self.chars().flat_map(|c| c.escape_unicode()).collect()
417     }
418
419     /// Replaces all occurrences of one string with another.
420     ///
421     /// # Arguments
422     ///
423     /// * `from` - The string to replace
424     /// * `to` - The replacement string
425     ///
426     /// # Return value
427     ///
428     /// The original string with all occurrences of `from` replaced with `to`.
429     ///
430     /// # Examples
431     ///
432     /// ```rust
433     /// let s = "Do you know the muffin man,
434     /// The muffin man, the muffin man, ...".to_string();
435     ///
436     /// assert_eq!(s.replace("muffin man", "little lamb"),
437     ///            "Do you know the little lamb,
438     /// The little lamb, the little lamb, ...".to_string());
439     ///
440     /// // not found, so no change.
441     /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
442     /// ```
443     #[stable]
444     fn replace(&self, from: &str, to: &str) -> String {
445         let mut result = String::new();
446         let mut last_end = 0;
447         for (start, end) in self.match_indices(from) {
448             result.push_str(unsafe { self.slice_unchecked(last_end, start) });
449             result.push_str(to);
450             last_end = end;
451         }
452         result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
453         result
454     }
455
456     /// Returns an iterator over the string in Unicode Normalization Form D
457     /// (canonical decomposition).
458     #[inline]
459     #[unstable = "this functionality may be moved to libunicode"]
460     fn nfd_chars<'a>(&'a self) -> Decompositions<'a> {
461         Decompositions {
462             iter: self[].chars(),
463             buffer: Vec::new(),
464             sorted: false,
465             kind: Canonical
466         }
467     }
468
469     /// Returns an iterator over the string in Unicode Normalization Form KD
470     /// (compatibility decomposition).
471     #[inline]
472     #[unstable = "this functionality may be moved to libunicode"]
473     fn nfkd_chars<'a>(&'a self) -> Decompositions<'a> {
474         Decompositions {
475             iter: self[].chars(),
476             buffer: Vec::new(),
477             sorted: false,
478             kind: Compatible
479         }
480     }
481
482     /// An Iterator over the string in Unicode Normalization Form C
483     /// (canonical decomposition followed by canonical composition).
484     #[inline]
485     #[unstable = "this functionality may be moved to libunicode"]
486     fn nfc_chars<'a>(&'a self) -> Recompositions<'a> {
487         Recompositions {
488             iter: self.nfd_chars(),
489             state: Composing,
490             buffer: RingBuf::new(),
491             composee: None,
492             last_ccc: None
493         }
494     }
495
496     /// An Iterator over the string in Unicode Normalization Form KC
497     /// (compatibility decomposition followed by canonical composition).
498     #[inline]
499     #[unstable = "this functionality may be moved to libunicode"]
500     fn nfkc_chars<'a>(&'a self) -> Recompositions<'a> {
501         Recompositions {
502             iter: self.nfkd_chars(),
503             state: Composing,
504             buffer: RingBuf::new(),
505             composee: None,
506             last_ccc: None
507         }
508     }
509
510     /// Returns true if a string contains a string pattern.
511     ///
512     /// # Arguments
513     ///
514     /// - pat - The string pattern to look for
515     ///
516     /// # Example
517     ///
518     /// ```rust
519     /// assert!("bananas".contains("nana"));
520     /// ```
521     #[stable]
522     fn contains(&self, pat: &str) -> bool {
523         core_str::StrExt::contains(self[], pat)
524     }
525
526     /// Returns true if a string contains a char pattern.
527     ///
528     /// # Arguments
529     ///
530     /// - pat - The char pattern to look for
531     ///
532     /// # Example
533     ///
534     /// ```rust
535     /// assert!("hello".contains_char('e'));
536     /// ```
537     #[unstable = "might get removed in favour of a more generic contains()"]
538     fn contains_char<P: CharEq>(&self, pat: P) -> bool {
539         core_str::StrExt::contains_char(self[], pat)
540     }
541
542     /// An iterator over the characters of `self`. Note, this iterates
543     /// over Unicode code-points, not Unicode graphemes.
544     ///
545     /// # Example
546     ///
547     /// ```rust
548     /// let v: Vec<char> = "abc åäö".chars().collect();
549     /// assert_eq!(v, vec!['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
550     /// ```
551     #[stable]
552     fn chars(&self) -> Chars {
553         core_str::StrExt::chars(self[])
554     }
555
556     /// An iterator over the bytes of `self`
557     ///
558     /// # Example
559     ///
560     /// ```rust
561     /// let v: Vec<u8> = "bors".bytes().collect();
562     /// assert_eq!(v, b"bors".to_vec());
563     /// ```
564     #[stable]
565     fn bytes(&self) -> Bytes {
566         core_str::StrExt::bytes(self[])
567     }
568
569     /// An iterator over the characters of `self` and their byte offsets.
570     #[stable]
571     fn char_indices(&self) -> CharIndices {
572         core_str::StrExt::char_indices(self[])
573     }
574
575     /// An iterator over substrings of `self`, separated by characters
576     /// matched by the pattern `pat`.
577     ///
578     /// # Example
579     ///
580     /// ```rust
581     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
582     /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
583     ///
584     /// let v: Vec<&str> = "abc1def2ghi".split(|&: c: char| c.is_numeric()).collect();
585     /// assert_eq!(v, vec!["abc", "def", "ghi"]);
586     ///
587     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
588     /// assert_eq!(v, vec!["lion", "", "tiger", "leopard"]);
589     ///
590     /// let v: Vec<&str> = "".split('X').collect();
591     /// assert_eq!(v, vec![""]);
592     /// ```
593     #[stable]
594     fn split<P: CharEq>(&self, pat: P) -> Split<P> {
595         core_str::StrExt::split(self[], pat)
596     }
597
598     /// An iterator over substrings of `self`, separated by characters
599     /// matched by the pattern `pat`, restricted to splitting at most `count`
600     /// times.
601     ///
602     /// # Example
603     ///
604     /// ```rust
605     /// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
606     /// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
607     ///
608     /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |&: c: char| c.is_numeric()).collect();
609     /// assert_eq!(v, vec!["abc", "def2ghi"]);
610     ///
611     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
612     /// assert_eq!(v, vec!["lion", "", "tigerXleopard"]);
613     ///
614     /// let v: Vec<&str> = "abcXdef".splitn(0, 'X').collect();
615     /// assert_eq!(v, vec!["abcXdef"]);
616     ///
617     /// let v: Vec<&str> = "".splitn(1, 'X').collect();
618     /// assert_eq!(v, vec![""]);
619     /// ```
620     #[stable]
621     fn splitn<P: CharEq>(&self, count: uint, pat: P) -> SplitN<P> {
622         core_str::StrExt::splitn(self[], count, pat)
623     }
624
625     /// An iterator over substrings of `self`, separated by characters
626     /// matched by the pattern `pat`.
627     ///
628     /// Equivalent to `split`, except that the trailing substring
629     /// is skipped if empty (terminator semantics).
630     ///
631     /// # Example
632     ///
633     /// ```rust
634     /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
635     /// assert_eq!(v, vec!["A", "B"]);
636     ///
637     /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
638     /// assert_eq!(v, vec!["A", "", "B", ""]);
639     ///
640     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
641     /// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
642     ///
643     /// let v: Vec<&str> = "abc1def2ghi".split(|&: c: char| c.is_numeric()).rev().collect();
644     /// assert_eq!(v, vec!["ghi", "def", "abc"]);
645     ///
646     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
647     /// assert_eq!(v, vec!["leopard", "tiger", "", "lion"]);
648     /// ```
649     #[unstable = "might get removed"]
650     fn split_terminator<P: CharEq>(&self, pat: P) -> SplitTerminator<P> {
651         core_str::StrExt::split_terminator(self[], pat)
652     }
653
654     /// An iterator over substrings of `self`, separated by characters
655     /// matched by the pattern `pat`, starting from the end of the string.
656     /// Restricted to splitting at most `count` times.
657     ///
658     /// # Example
659     ///
660     /// ```rust
661     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
662     /// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
663     ///
664     /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |&: c: char| c.is_numeric()).collect();
665     /// assert_eq!(v, vec!["ghi", "abc1def"]);
666     ///
667     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
668     /// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
669     /// ```
670     #[stable]
671     fn rsplitn<P: CharEq>(&self, count: uint, pat: P) -> RSplitN<P> {
672         core_str::StrExt::rsplitn(self[], count, pat)
673     }
674
675     /// An iterator over the start and end indices of the disjoint
676     /// matches of the pattern `pat` within `self`.
677     ///
678     /// That is, each returned value `(start, end)` satisfies
679     /// `self.slice(start, end) == sep`. For matches of `sep` within
680     /// `self` that overlap, only the indices corresponding to the
681     /// first match are returned.
682     ///
683     /// # Example
684     ///
685     /// ```rust
686     /// let v: Vec<(uint, uint)> = "abcXXXabcYYYabc".match_indices("abc").collect();
687     /// assert_eq!(v, vec![(0,3), (6,9), (12,15)]);
688     ///
689     /// let v: Vec<(uint, uint)> = "1abcabc2".match_indices("abc").collect();
690     /// assert_eq!(v, vec![(1,4), (4,7)]);
691     ///
692     /// let v: Vec<(uint, uint)> = "ababa".match_indices("aba").collect();
693     /// assert_eq!(v, vec![(0, 3)]); // only the first `aba`
694     /// ```
695     #[unstable = "might have its iterator type changed"]
696     fn match_indices<'a>(&'a self, pat: &'a str) -> MatchIndices<'a> {
697         core_str::StrExt::match_indices(self[], pat)
698     }
699
700     /// An iterator over the substrings of `self` separated by the pattern `sep`.
701     ///
702     /// # Example
703     ///
704     /// ```rust
705     /// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
706     /// assert_eq!(v, vec!["", "XXX", "YYY", ""]);
707     ///
708     /// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
709     /// assert_eq!(v, vec!["1", "", "2"]);
710     /// ```
711     #[unstable = "might get removed in the future in favor of a more generic split()"]
712     fn split_str<'a>(&'a self, pat: &'a str) -> SplitStr<'a> {
713         core_str::StrExt::split_str(self[], pat)
714     }
715
716     /// An iterator over the lines of a string (subsequences separated
717     /// by `\n`). This does not include the empty string after a
718     /// trailing `\n`.
719     ///
720     /// # Example
721     ///
722     /// ```rust
723     /// let four_lines = "foo\nbar\n\nbaz\n";
724     /// let v: Vec<&str> = four_lines.lines().collect();
725     /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
726     /// ```
727     #[stable]
728     fn lines(&self) -> Lines {
729         core_str::StrExt::lines(self[])
730     }
731
732     /// An iterator over the lines of a string, separated by either
733     /// `\n` or `\r\n`. As with `.lines()`, this does not include an
734     /// empty trailing line.
735     ///
736     /// # Example
737     ///
738     /// ```rust
739     /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
740     /// let v: Vec<&str> = four_lines.lines_any().collect();
741     /// assert_eq!(v, vec!["foo", "bar", "", "baz"]);
742     /// ```
743     #[stable]
744     fn lines_any(&self) -> LinesAny {
745         core_str::StrExt::lines_any(self[])
746     }
747
748     /// Returns a slice of the given string from the byte range
749     /// [`begin`..`end`).
750     ///
751     /// This operation is `O(1)`.
752     ///
753     /// Panics when `begin` and `end` do not point to valid characters
754     /// or point beyond the last character of the string.
755     ///
756     /// See also `slice_to` and `slice_from` for slicing prefixes and
757     /// suffixes of strings, and `slice_chars` for slicing based on
758     /// code point counts.
759     ///
760     /// # Example
761     ///
762     /// ```rust
763     /// let s = "Löwe 老虎 Léopard";
764     /// assert_eq!(s.slice(0, 1), "L");
765     ///
766     /// assert_eq!(s.slice(1, 9), "öwe 老");
767     ///
768     /// // these will panic:
769     /// // byte 2 lies within `ö`:
770     /// // s.slice(2, 3);
771     ///
772     /// // byte 8 lies within `老`
773     /// // s.slice(1, 8);
774     ///
775     /// // byte 100 is outside the string
776     /// // s.slice(3, 100);
777     /// ```
778     #[unstable = "use slice notation [a..b] instead"]
779     fn slice(&self, begin: uint, end: uint) -> &str {
780         core_str::StrExt::slice(self[], begin, end)
781     }
782
783     /// Returns a slice of the string from `begin` to its end.
784     ///
785     /// Equivalent to `self.slice(begin, self.len())`.
786     ///
787     /// Panics when `begin` does not point to a valid character, or is
788     /// out of bounds.
789     ///
790     /// See also `slice`, `slice_to` and `slice_chars`.
791     #[unstable = "use slice notation [a..] instead"]
792     fn slice_from(&self, begin: uint) -> &str {
793         core_str::StrExt::slice_from(self[], begin)
794     }
795
796     /// Returns a slice of the string from the beginning to byte
797     /// `end`.
798     ///
799     /// Equivalent to `self.slice(0, end)`.
800     ///
801     /// Panics when `end` does not point to a valid character, or is
802     /// out of bounds.
803     ///
804     /// See also `slice`, `slice_from` and `slice_chars`.
805     #[unstable = "use slice notation [0..a] instead"]
806     fn slice_to(&self, end: uint) -> &str {
807         core_str::StrExt::slice_to(self[], end)
808     }
809
810     /// Returns a slice of the string from the character range
811     /// [`begin`..`end`).
812     ///
813     /// That is, start at the `begin`-th code point of the string and
814     /// continue to the `end`-th code point. This does not detect or
815     /// handle edge cases such as leaving a combining character as the
816     /// first code point of the string.
817     ///
818     /// Due to the design of UTF-8, this operation is `O(end)`.
819     /// See `slice`, `slice_to` and `slice_from` for `O(1)`
820     /// variants that use byte indices rather than code point
821     /// indices.
822     ///
823     /// Panics if `begin` > `end` or the either `begin` or `end` are
824     /// beyond the last character of the string.
825     ///
826     /// # Example
827     ///
828     /// ```rust
829     /// let s = "Löwe 老虎 Léopard";
830     /// assert_eq!(s.slice_chars(0, 4), "Löwe");
831     /// assert_eq!(s.slice_chars(5, 7), "老虎");
832     /// ```
833     #[unstable = "may have yet to prove its worth"]
834     fn slice_chars(&self, begin: uint, end: uint) -> &str {
835         core_str::StrExt::slice_chars(self[], begin, end)
836     }
837
838     /// Takes a bytewise (not UTF-8) slice from a string.
839     ///
840     /// Returns the substring from [`begin`..`end`).
841     ///
842     /// Caller must check both UTF-8 character boundaries and the boundaries of
843     /// the entire slice as well.
844     #[stable]
845     unsafe fn slice_unchecked(&self, begin: uint, end: uint) -> &str {
846         core_str::StrExt::slice_unchecked(self[], begin, end)
847     }
848
849     /// Returns true if the pattern `pat` is a prefix of the string.
850     ///
851     /// # Example
852     ///
853     /// ```rust
854     /// assert!("banana".starts_with("ba"));
855     /// ```
856     #[stable]
857     fn starts_with(&self, pat: &str) -> bool {
858         core_str::StrExt::starts_with(self[], pat)
859     }
860
861     /// Returns true if the pattern `pat` is a suffix of the string.
862     ///
863     /// # Example
864     ///
865     /// ```rust
866     /// assert!("banana".ends_with("nana"));
867     /// ```
868     #[stable]
869     fn ends_with(&self, pat: &str) -> bool {
870         core_str::StrExt::ends_with(self[], pat)
871     }
872
873     /// Returns a string with all pre- and suffixes that match
874     /// the pattern `pat` repeatedly removed.
875     ///
876     /// # Arguments
877     ///
878     /// * pat - a string pattern
879     ///
880     /// # Example
881     ///
882     /// ```rust
883     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
884     /// let x: &[_] = &['1', '2'];
885     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
886     /// assert_eq!("123foo1bar123".trim_matches(|&: c: char| c.is_numeric()), "foo1bar");
887     /// ```
888     #[stable]
889     fn trim_matches<P: CharEq>(&self, pat: P) -> &str {
890         core_str::StrExt::trim_matches(self[], pat)
891     }
892
893     /// Returns a string with all prefixes that match
894     /// the pattern `pat` repeatedly removed.
895     ///
896     /// # Arguments
897     ///
898     /// * pat - a string pattern
899     ///
900     /// # Example
901     ///
902     /// ```rust
903     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
904     /// let x: &[_] = &['1', '2'];
905     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
906     /// assert_eq!("123foo1bar123".trim_left_matches(|&: c: char| c.is_numeric()), "foo1bar123");
907     /// ```
908     #[stable]
909     fn trim_left_matches<P: CharEq>(&self, pat: P) -> &str {
910         core_str::StrExt::trim_left_matches(self[], pat)
911     }
912
913     /// Returns a string with all suffixes that match
914     /// the pattern `pat` repeatedly removed.
915     ///
916     /// # Arguments
917     ///
918     /// * pat - a string pattern
919     ///
920     /// # Example
921     ///
922     /// ```rust
923     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
924     /// let x: &[_] = &['1', '2'];
925     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
926     /// assert_eq!("123foo1bar123".trim_right_matches(|&: c: char| c.is_numeric()), "123foo1bar");
927     /// ```
928     #[stable]
929     fn trim_right_matches<P: CharEq>(&self, pat: P) -> &str {
930         core_str::StrExt::trim_right_matches(self[], pat)
931     }
932
933     /// Check that `index`-th byte lies at the start and/or end of a
934     /// UTF-8 code point sequence.
935     ///
936     /// The start and end of the string (when `index == self.len()`)
937     /// are considered to be boundaries.
938     ///
939     /// Panics if `index` is greater than `self.len()`.
940     ///
941     /// # Example
942     ///
943     /// ```rust
944     /// let s = "Löwe 老虎 Léopard";
945     /// assert!(s.is_char_boundary(0));
946     /// // start of `老`
947     /// assert!(s.is_char_boundary(6));
948     /// assert!(s.is_char_boundary(s.len()));
949     ///
950     /// // second byte of `ö`
951     /// assert!(!s.is_char_boundary(2));
952     ///
953     /// // third byte of `老`
954     /// assert!(!s.is_char_boundary(8));
955     /// ```
956     #[unstable = "naming is uncertain with container conventions"]
957     fn is_char_boundary(&self, index: uint) -> bool {
958         core_str::StrExt::is_char_boundary(self[], index)
959     }
960
961     /// Pluck a character out of a string and return the index of the next
962     /// character.
963     ///
964     /// This function can be used to iterate over the Unicode characters of a
965     /// string.
966     ///
967     /// # Example
968     ///
969     /// This example manually iterates through the characters of a
970     /// string; this should normally be done by `.chars()` or
971     /// `.char_indices`.
972     ///
973     /// ```rust
974     /// use std::str::CharRange;
975     ///
976     /// let s = "中华Việt Nam";
977     /// let mut i = 0u;
978     /// while i < s.len() {
979     ///     let CharRange {ch, next} = s.char_range_at(i);
980     ///     println!("{}: {}", i, ch);
981     ///     i = next;
982     /// }
983     /// ```
984     ///
985     /// This outputs:
986     ///
987     /// ```text
988     /// 0: 中
989     /// 3: 华
990     /// 6: V
991     /// 7: i
992     /// 8: ệ
993     /// 11: t
994     /// 12:
995     /// 13: N
996     /// 14: a
997     /// 15: m
998     /// ```
999     ///
1000     /// # Arguments
1001     ///
1002     /// * s - The string
1003     /// * i - The byte offset of the char to extract
1004     ///
1005     /// # Return value
1006     ///
1007     /// A record {ch: char, next: uint} containing the char value and the byte
1008     /// index of the next Unicode character.
1009     ///
1010     /// # Panics
1011     ///
1012     /// If `i` is greater than or equal to the length of the string.
1013     /// If `i` is not the index of the beginning of a valid UTF-8 character.
1014     #[unstable = "naming is uncertain with container conventions"]
1015     fn char_range_at(&self, start: uint) -> CharRange {
1016         core_str::StrExt::char_range_at(self[], start)
1017     }
1018
1019     /// Given a byte position and a str, return the previous char and its position.
1020     ///
1021     /// This function can be used to iterate over a Unicode string in reverse.
1022     ///
1023     /// Returns 0 for next index if called on start index 0.
1024     ///
1025     /// # Panics
1026     ///
1027     /// If `i` is greater than the length of the string.
1028     /// If `i` is not an index following a valid UTF-8 character.
1029     #[unstable = "naming is uncertain with container conventions"]
1030     fn char_range_at_reverse(&self, start: uint) -> CharRange {
1031         core_str::StrExt::char_range_at_reverse(self[], start)
1032     }
1033
1034     /// Plucks the character starting at the `i`th byte of a string.
1035     ///
1036     /// # Example
1037     ///
1038     /// ```rust
1039     /// let s = "abπc";
1040     /// assert_eq!(s.char_at(1), 'b');
1041     /// assert_eq!(s.char_at(2), 'π');
1042     /// assert_eq!(s.char_at(4), 'c');
1043     /// ```
1044     ///
1045     /// # Panics
1046     ///
1047     /// If `i` is greater than or equal to the length of the string.
1048     /// If `i` is not the index of the beginning of a valid UTF-8 character.
1049     #[unstable = "naming is uncertain with container conventions"]
1050     fn char_at(&self, i: uint) -> char {
1051         core_str::StrExt::char_at(self[], i)
1052     }
1053
1054     /// Plucks the character ending at the `i`th byte of a string.
1055     ///
1056     /// # Panics
1057     ///
1058     /// If `i` is greater than the length of the string.
1059     /// If `i` is not an index following a valid UTF-8 character.
1060     #[unstable = "naming is uncertain with container conventions"]
1061     fn char_at_reverse(&self, i: uint) -> char {
1062         core_str::StrExt::char_at_reverse(self[], i)
1063     }
1064
1065     /// Work with the byte buffer of a string as a byte slice.
1066     ///
1067     /// # Example
1068     ///
1069     /// ```rust
1070     /// assert_eq!("bors".as_bytes(), b"bors");
1071     /// ```
1072     #[stable]
1073     fn as_bytes(&self) -> &[u8] {
1074         core_str::StrExt::as_bytes(self[])
1075     }
1076
1077     /// Returns the byte index of the first character of `self` that
1078     /// matches the pattern `pat`.
1079     ///
1080     /// # Return value
1081     ///
1082     /// `Some` containing the byte index of the last matching character
1083     /// or `None` if there is no match
1084     ///
1085     /// # Example
1086     ///
1087     /// ```rust
1088     /// let s = "Löwe 老虎 Léopard";
1089     ///
1090     /// assert_eq!(s.find('L'), Some(0));
1091     /// assert_eq!(s.find('é'), Some(14));
1092     ///
1093     /// // the first space
1094     /// assert_eq!(s.find(|&: c: char| c.is_whitespace()), Some(5));
1095     ///
1096     /// // neither are found
1097     /// let x: &[_] = &['1', '2'];
1098     /// assert_eq!(s.find(x), None);
1099     /// ```
1100     #[stable]
1101     fn find<P: CharEq>(&self, pat: P) -> Option<uint> {
1102         core_str::StrExt::find(self[], pat)
1103     }
1104
1105     /// Returns the byte index of the last character of `self` that
1106     /// matches the pattern `pat`.
1107     ///
1108     /// # Return value
1109     ///
1110     /// `Some` containing the byte index of the last matching character
1111     /// or `None` if there is no match.
1112     ///
1113     /// # Example
1114     ///
1115     /// ```rust
1116     /// let s = "Löwe 老虎 Léopard";
1117     ///
1118     /// assert_eq!(s.rfind('L'), Some(13));
1119     /// assert_eq!(s.rfind('é'), Some(14));
1120     ///
1121     /// // the second space
1122     /// assert_eq!(s.rfind(|&: c: char| c.is_whitespace()), Some(12));
1123     ///
1124     /// // searches for an occurrence of either `1` or `2`, but neither are found
1125     /// let x: &[_] = &['1', '2'];
1126     /// assert_eq!(s.rfind(x), None);
1127     /// ```
1128     #[stable]
1129     fn rfind<P: CharEq>(&self, pat: P) -> Option<uint> {
1130         core_str::StrExt::rfind(self[], pat)
1131     }
1132
1133     /// Returns the byte index of the first matching substring
1134     ///
1135     /// # Arguments
1136     ///
1137     /// * `needle` - The string to search for
1138     ///
1139     /// # Return value
1140     ///
1141     /// `Some` containing the byte index of the first matching substring
1142     /// or `None` if there is no match.
1143     ///
1144     /// # Example
1145     ///
1146     /// ```rust
1147     /// let s = "Löwe 老虎 Léopard";
1148     ///
1149     /// assert_eq!(s.find_str("老虎 L"), Some(6));
1150     /// assert_eq!(s.find_str("muffin man"), None);
1151     /// ```
1152     #[unstable = "might get removed in favor of a more generic find in the future"]
1153     fn find_str(&self, needle: &str) -> Option<uint> {
1154         core_str::StrExt::find_str(self[], needle)
1155     }
1156
1157     /// Retrieves the first character from a string slice and returns
1158     /// it. This does not allocate a new string; instead, it returns a
1159     /// slice that point one character beyond the character that was
1160     /// shifted. If the string does not contain any characters,
1161     /// None is returned instead.
1162     ///
1163     /// # Example
1164     ///
1165     /// ```rust
1166     /// let s = "Löwe 老虎 Léopard";
1167     /// let (c, s1) = s.slice_shift_char().unwrap();
1168     /// assert_eq!(c, 'L');
1169     /// assert_eq!(s1, "öwe 老虎 Léopard");
1170     ///
1171     /// let (c, s2) = s1.slice_shift_char().unwrap();
1172     /// assert_eq!(c, 'ö');
1173     /// assert_eq!(s2, "we 老虎 Léopard");
1174     /// ```
1175     #[unstable = "awaiting conventions about shifting and slices"]
1176     fn slice_shift_char(&self) -> Option<(char, &str)> {
1177         core_str::StrExt::slice_shift_char(self[])
1178     }
1179
1180     /// Returns the byte offset of an inner slice relative to an enclosing outer slice.
1181     ///
1182     /// Panics if `inner` is not a direct slice contained within self.
1183     ///
1184     /// # Example
1185     ///
1186     /// ```rust
1187     /// let string = "a\nb\nc";
1188     /// let lines: Vec<&str> = string.lines().collect();
1189     ///
1190     /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
1191     /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
1192     /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
1193     /// ```
1194     #[unstable = "awaiting convention about comparability of arbitrary slices"]
1195     fn subslice_offset(&self, inner: &str) -> uint {
1196         core_str::StrExt::subslice_offset(self[], inner)
1197     }
1198
1199     /// Return an unsafe pointer to the strings buffer.
1200     ///
1201     /// The caller must ensure that the string outlives this pointer,
1202     /// and that it is not reallocated (e.g. by pushing to the
1203     /// string).
1204     #[stable]
1205     #[inline]
1206     fn as_ptr(&self) -> *const u8 {
1207         core_str::StrExt::as_ptr(self[])
1208     }
1209
1210     /// Return an iterator of `u16` over the string encoded as UTF-16.
1211     #[unstable = "this functionality may only be provided by libunicode"]
1212     fn utf16_units(&self) -> Utf16Units {
1213         Utf16Units { encoder: Utf16Encoder::new(self[].chars()) }
1214     }
1215
1216     /// Return the number of bytes in this string
1217     ///
1218     /// # Example
1219     ///
1220     /// ```
1221     /// assert_eq!("foo".len(), 3);
1222     /// assert_eq!("ƒoo".len(), 4);
1223     /// ```
1224     #[stable]
1225     #[inline]
1226     fn len(&self) -> uint {
1227         core_str::StrExt::len(self[])
1228     }
1229
1230     /// Returns true if this slice contains no bytes
1231     ///
1232     /// # Example
1233     ///
1234     /// ```
1235     /// assert!("".is_empty());
1236     /// ```
1237     #[inline]
1238     #[stable]
1239     fn is_empty(&self) -> bool {
1240         core_str::StrExt::is_empty(self[])
1241     }
1242
1243     /// Parse this string into the specified type.
1244     ///
1245     /// # Example
1246     ///
1247     /// ```
1248     /// assert_eq!("4".parse::<u32>(), Some(4));
1249     /// assert_eq!("j".parse::<u32>(), None);
1250     /// ```
1251     #[inline]
1252     #[unstable = "this method was just created"]
1253     fn parse<F: FromStr>(&self) -> Option<F> {
1254         core_str::StrExt::parse(self[])
1255     }
1256
1257     /// Returns an iterator over the
1258     /// [grapheme clusters](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
1259     /// of the string.
1260     ///
1261     /// If `is_extended` is true, the iterator is over the *extended grapheme clusters*;
1262     /// otherwise, the iterator is over the *legacy grapheme clusters*.
1263     /// [UAX#29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
1264     /// recommends extended grapheme cluster boundaries for general processing.
1265     ///
1266     /// # Example
1267     ///
1268     /// ```rust
1269     /// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
1270     /// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
1271     /// assert_eq!(gr1.as_slice(), b);
1272     /// let gr2 = "a\r\nb🇷🇺🇸🇹".graphemes(true).collect::<Vec<&str>>();
1273     /// let b: &[_] = &["a", "\r\n", "b", "🇷🇺🇸🇹"];
1274     /// assert_eq!(gr2.as_slice(), b);
1275     /// ```
1276     #[unstable = "this functionality may only be provided by libunicode"]
1277     fn graphemes(&self, is_extended: bool) -> Graphemes {
1278         UnicodeStr::graphemes(self[], is_extended)
1279     }
1280
1281     /// Returns an iterator over the grapheme clusters of self and their byte offsets.
1282     /// See `graphemes()` method for more information.
1283     ///
1284     /// # Example
1285     ///
1286     /// ```rust
1287     /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(uint, &str)>>();
1288     /// let b: &[_] = &[(0u, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
1289     /// assert_eq!(gr_inds.as_slice(), b);
1290     /// ```
1291     #[unstable = "this functionality may only be provided by libunicode"]
1292     fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices {
1293         UnicodeStr::grapheme_indices(self[], is_extended)
1294     }
1295
1296     /// An iterator over the words of a string (subsequences separated
1297     /// by any sequence of whitespace). Sequences of whitespace are
1298     /// collapsed, so empty "words" are not included.
1299     ///
1300     /// # Example
1301     ///
1302     /// ```rust
1303     /// let some_words = " Mary   had\ta little  \n\t lamb";
1304     /// let v: Vec<&str> = some_words.words().collect();
1305     /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
1306     /// ```
1307     #[stable]
1308     fn words(&self) -> Words {
1309         UnicodeStr::words(self[])
1310     }
1311
1312     /// Returns a string's displayed width in columns, treating control
1313     /// characters as zero-width.
1314     ///
1315     /// `is_cjk` determines behavior for characters in the Ambiguous category:
1316     /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1.
1317     /// In CJK locales, `is_cjk` should be `true`, else it should be `false`.
1318     /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
1319     /// recommends that these characters be treated as 1 column (i.e.,
1320     /// `is_cjk` = `false`) if the locale is unknown.
1321     #[unstable = "this functionality may only be provided by libunicode"]
1322     fn width(&self, is_cjk: bool) -> uint {
1323         UnicodeStr::width(self[], is_cjk)
1324     }
1325
1326     /// Returns a string with leading and trailing whitespace removed.
1327     #[stable]
1328     fn trim(&self) -> &str {
1329         UnicodeStr::trim(self[])
1330     }
1331
1332     /// Returns a string with leading whitespace removed.
1333     #[stable]
1334     fn trim_left(&self) -> &str {
1335         UnicodeStr::trim_left(self[])
1336     }
1337
1338     /// Returns a string with trailing whitespace removed.
1339     #[stable]
1340     fn trim_right(&self) -> &str {
1341         UnicodeStr::trim_right(self[])
1342     }
1343 }
1344
1345 #[stable]
1346 impl StrExt for str {}
1347
1348 #[cfg(test)]
1349 mod tests {
1350     use prelude::*;
1351
1352     use core::iter::AdditiveIterator;
1353     use super::from_utf8;
1354     use super::Utf8Error;
1355
1356     #[test]
1357     fn test_le() {
1358         assert!("" <= "");
1359         assert!("" <= "foo");
1360         assert!("foo" <= "foo");
1361         assert!("foo" != "bar");
1362     }
1363
1364     #[test]
1365     fn test_len() {
1366         assert_eq!("".len(), 0u);
1367         assert_eq!("hello world".len(), 11u);
1368         assert_eq!("\x63".len(), 1u);
1369         assert_eq!("\u{a2}".len(), 2u);
1370         assert_eq!("\u{3c0}".len(), 2u);
1371         assert_eq!("\u{2620}".len(), 3u);
1372         assert_eq!("\u{1d11e}".len(), 4u);
1373
1374         assert_eq!("".chars().count(), 0u);
1375         assert_eq!("hello world".chars().count(), 11u);
1376         assert_eq!("\x63".chars().count(), 1u);
1377         assert_eq!("\u{a2}".chars().count(), 1u);
1378         assert_eq!("\u{3c0}".chars().count(), 1u);
1379         assert_eq!("\u{2620}".chars().count(), 1u);
1380         assert_eq!("\u{1d11e}".chars().count(), 1u);
1381         assert_eq!("ประเทศไทย中华Việt Nam".chars().count(), 19u);
1382
1383         assert_eq!("hello".width(false), 10u);
1384         assert_eq!("hello".width(true), 10u);
1385         assert_eq!("\0\0\0\0\0".width(false), 0u);
1386         assert_eq!("\0\0\0\0\0".width(true), 0u);
1387         assert_eq!("".width(false), 0u);
1388         assert_eq!("".width(true), 0u);
1389         assert_eq!("\u{2081}\u{2082}\u{2083}\u{2084}".width(false), 4u);
1390         assert_eq!("\u{2081}\u{2082}\u{2083}\u{2084}".width(true), 8u);
1391     }
1392
1393     #[test]
1394     fn test_find() {
1395         assert_eq!("hello".find('l'), Some(2u));
1396         assert_eq!("hello".find(|&: c:char| c == 'o'), Some(4u));
1397         assert!("hello".find('x').is_none());
1398         assert!("hello".find(|&: c:char| c == 'x').is_none());
1399         assert_eq!("ประเทศไทย中华Việt Nam".find('华'), Some(30u));
1400         assert_eq!("ประเทศไทย中华Việt Nam".find(|&: c: char| c == '华'), Some(30u));
1401     }
1402
1403     #[test]
1404     fn test_rfind() {
1405         assert_eq!("hello".rfind('l'), Some(3u));
1406         assert_eq!("hello".rfind(|&: c:char| c == 'o'), Some(4u));
1407         assert!("hello".rfind('x').is_none());
1408         assert!("hello".rfind(|&: c:char| c == 'x').is_none());
1409         assert_eq!("ประเทศไทย中华Việt Nam".rfind('华'), Some(30u));
1410         assert_eq!("ประเทศไทย中华Việt Nam".rfind(|&: c: char| c == '华'), Some(30u));
1411     }
1412
1413     #[test]
1414     fn test_collect() {
1415         let empty = String::from_str("");
1416         let s: String = empty.chars().collect();
1417         assert_eq!(empty, s);
1418         let data = String::from_str("ประเทศไทย中");
1419         let s: String = data.chars().collect();
1420         assert_eq!(data, s);
1421     }
1422
1423     #[test]
1424     fn test_into_bytes() {
1425         let data = String::from_str("asdf");
1426         let buf = data.into_bytes();
1427         assert_eq!(b"asdf", buf);
1428     }
1429
1430     #[test]
1431     fn test_find_str() {
1432         // byte positions
1433         assert_eq!("".find_str(""), Some(0u));
1434         assert!("banana".find_str("apple pie").is_none());
1435
1436         let data = "abcabc";
1437         assert_eq!(data.slice(0u, 6u).find_str("ab"), Some(0u));
1438         assert_eq!(data.slice(2u, 6u).find_str("ab"), Some(3u - 2u));
1439         assert!(data.slice(2u, 4u).find_str("ab").is_none());
1440
1441         let string = "ประเทศไทย中华Việt Nam";
1442         let mut data = String::from_str(string);
1443         data.push_str(string);
1444         assert!(data.find_str("ไท华").is_none());
1445         assert_eq!(data.slice(0u, 43u).find_str(""), Some(0u));
1446         assert_eq!(data.slice(6u, 43u).find_str(""), Some(6u - 6u));
1447
1448         assert_eq!(data.slice(0u, 43u).find_str("ประ"), Some( 0u));
1449         assert_eq!(data.slice(0u, 43u).find_str("ทศไ"), Some(12u));
1450         assert_eq!(data.slice(0u, 43u).find_str("ย中"), Some(24u));
1451         assert_eq!(data.slice(0u, 43u).find_str("iệt"), Some(34u));
1452         assert_eq!(data.slice(0u, 43u).find_str("Nam"), Some(40u));
1453
1454         assert_eq!(data.slice(43u, 86u).find_str("ประ"), Some(43u - 43u));
1455         assert_eq!(data.slice(43u, 86u).find_str("ทศไ"), Some(55u - 43u));
1456         assert_eq!(data.slice(43u, 86u).find_str("ย中"), Some(67u - 43u));
1457         assert_eq!(data.slice(43u, 86u).find_str("iệt"), Some(77u - 43u));
1458         assert_eq!(data.slice(43u, 86u).find_str("Nam"), Some(83u - 43u));
1459     }
1460
1461     #[test]
1462     fn test_slice_chars() {
1463         fn t(a: &str, b: &str, start: uint) {
1464             assert_eq!(a.slice_chars(start, start + b.chars().count()), b);
1465         }
1466         t("", "", 0);
1467         t("hello", "llo", 2);
1468         t("hello", "el", 1);
1469         t("αβλ", "β", 1);
1470         t("αβλ", "", 3);
1471         assert_eq!("ะเทศไท", "ประเทศไทย中华Việt Nam".slice_chars(2, 8));
1472     }
1473
1474     fn s(x: &str) -> String { x.to_string() }
1475
1476     macro_rules! test_concat {
1477         ($expected: expr, $string: expr) => {
1478             {
1479                 let s: String = $string.concat();
1480                 assert_eq!($expected, s);
1481             }
1482         }
1483     }
1484
1485     #[test]
1486     fn test_concat_for_different_types() {
1487         test_concat!("ab", vec![s("a"), s("b")]);
1488         test_concat!("ab", vec!["a", "b"]);
1489         test_concat!("ab", vec!["a", "b"].as_slice());
1490         test_concat!("ab", vec![s("a"), s("b")]);
1491     }
1492
1493     #[test]
1494     fn test_concat_for_different_lengths() {
1495         let empty: &[&str] = &[];
1496         test_concat!("", empty);
1497         test_concat!("a", ["a"]);
1498         test_concat!("ab", ["a", "b"]);
1499         test_concat!("abc", ["", "a", "bc"]);
1500     }
1501
1502     macro_rules! test_connect {
1503         ($expected: expr, $string: expr, $delim: expr) => {
1504             {
1505                 let s = $string.connect($delim);
1506                 assert_eq!($expected, s);
1507             }
1508         }
1509     }
1510
1511     #[test]
1512     fn test_connect_for_different_types() {
1513         test_connect!("a-b", ["a", "b"], "-");
1514         let hyphen = "-".to_string();
1515         test_connect!("a-b", [s("a"), s("b")], hyphen.as_slice());
1516         test_connect!("a-b", vec!["a", "b"], hyphen.as_slice());
1517         test_connect!("a-b", vec!["a", "b"].as_slice(), "-");
1518         test_connect!("a-b", vec![s("a"), s("b")], "-");
1519     }
1520
1521     #[test]
1522     fn test_connect_for_different_lengths() {
1523         let empty: &[&str] = &[];
1524         test_connect!("", empty, "-");
1525         test_connect!("a", ["a"], "-");
1526         test_connect!("a-b", ["a", "b"], "-");
1527         test_connect!("-a-bc", ["", "a", "bc"], "-");
1528     }
1529
1530     #[test]
1531     fn test_unsafe_slice() {
1532         assert_eq!("ab", unsafe {"abc".slice_unchecked(0, 2)});
1533         assert_eq!("bc", unsafe {"abc".slice_unchecked(1, 3)});
1534         assert_eq!("", unsafe {"abc".slice_unchecked(1, 1)});
1535         fn a_million_letter_a() -> String {
1536             let mut i = 0u;
1537             let mut rs = String::new();
1538             while i < 100000 {
1539                 rs.push_str("aaaaaaaaaa");
1540                 i += 1;
1541             }
1542             rs
1543         }
1544         fn half_a_million_letter_a() -> String {
1545             let mut i = 0u;
1546             let mut rs = String::new();
1547             while i < 100000 {
1548                 rs.push_str("aaaaa");
1549                 i += 1;
1550             }
1551             rs
1552         }
1553         let letters = a_million_letter_a();
1554         assert!(half_a_million_letter_a() ==
1555             unsafe {String::from_str(letters.slice_unchecked(
1556                                      0u,
1557                                      500000))});
1558     }
1559
1560     #[test]
1561     fn test_starts_with() {
1562         assert!(("".starts_with("")));
1563         assert!(("abc".starts_with("")));
1564         assert!(("abc".starts_with("a")));
1565         assert!((!"a".starts_with("abc")));
1566         assert!((!"".starts_with("abc")));
1567         assert!((!"ödd".starts_with("-")));
1568         assert!(("ödd".starts_with("öd")));
1569     }
1570
1571     #[test]
1572     fn test_ends_with() {
1573         assert!(("".ends_with("")));
1574         assert!(("abc".ends_with("")));
1575         assert!(("abc".ends_with("c")));
1576         assert!((!"a".ends_with("abc")));
1577         assert!((!"".ends_with("abc")));
1578         assert!((!"ddö".ends_with("-")));
1579         assert!(("ddö".ends_with("dö")));
1580     }
1581
1582     #[test]
1583     fn test_is_empty() {
1584         assert!("".is_empty());
1585         assert!(!"a".is_empty());
1586     }
1587
1588     #[test]
1589     fn test_replace() {
1590         let a = "a";
1591         assert_eq!("".replace(a, "b"), String::from_str(""));
1592         assert_eq!("a".replace(a, "b"), String::from_str("b"));
1593         assert_eq!("ab".replace(a, "b"), String::from_str("bb"));
1594         let test = "test";
1595         assert!(" test test ".replace(test, "toast") ==
1596             String::from_str(" toast toast "));
1597         assert_eq!(" test test ".replace(test, ""), String::from_str("   "));
1598     }
1599
1600     #[test]
1601     fn test_replace_2a() {
1602         let data = "ประเทศไทย中华";
1603         let repl = "دولة الكويت";
1604
1605         let a = "ประเ";
1606         let a2 = "دولة الكويتทศไทย中华";
1607         assert_eq!(data.replace(a, repl), a2);
1608     }
1609
1610     #[test]
1611     fn test_replace_2b() {
1612         let data = "ประเทศไทย中华";
1613         let repl = "دولة الكويت";
1614
1615         let b = "ะเ";
1616         let b2 = "ปรدولة الكويتทศไทย中华";
1617         assert_eq!(data.replace(b, repl), b2);
1618     }
1619
1620     #[test]
1621     fn test_replace_2c() {
1622         let data = "ประเทศไทย中华";
1623         let repl = "دولة الكويت";
1624
1625         let c = "中华";
1626         let c2 = "ประเทศไทยدولة الكويت";
1627         assert_eq!(data.replace(c, repl), c2);
1628     }
1629
1630     #[test]
1631     fn test_replace_2d() {
1632         let data = "ประเทศไทย中华";
1633         let repl = "دولة الكويت";
1634
1635         let d = "ไท华";
1636         assert_eq!(data.replace(d, repl), data);
1637     }
1638
1639     #[test]
1640     fn test_slice() {
1641         assert_eq!("ab", "abc".slice(0, 2));
1642         assert_eq!("bc", "abc".slice(1, 3));
1643         assert_eq!("", "abc".slice(1, 1));
1644         assert_eq!("\u{65e5}", "\u{65e5}\u{672c}".slice(0, 3));
1645
1646         let data = "ประเทศไทย中华";
1647         assert_eq!("ป", data.slice(0, 3));
1648         assert_eq!("ร", data.slice(3, 6));
1649         assert_eq!("", data.slice(3, 3));
1650         assert_eq!("华", data.slice(30, 33));
1651
1652         fn a_million_letter_x() -> String {
1653             let mut i = 0u;
1654             let mut rs = String::new();
1655             while i < 100000 {
1656                 rs.push_str("华华华华华华华华华华");
1657                 i += 1;
1658             }
1659             rs
1660         }
1661         fn half_a_million_letter_x() -> String {
1662             let mut i = 0u;
1663             let mut rs = String::new();
1664             while i < 100000 {
1665                 rs.push_str("华华华华华");
1666                 i += 1;
1667             }
1668             rs
1669         }
1670         let letters = a_million_letter_x();
1671         assert!(half_a_million_letter_x() ==
1672             String::from_str(letters.slice(0u, 3u * 500000u)));
1673     }
1674
1675     #[test]
1676     fn test_slice_2() {
1677         let ss = "中华Việt Nam";
1678
1679         assert_eq!("华", ss.slice(3u, 6u));
1680         assert_eq!("Việt Nam", ss.slice(6u, 16u));
1681
1682         assert_eq!("ab", "abc".slice(0u, 2u));
1683         assert_eq!("bc", "abc".slice(1u, 3u));
1684         assert_eq!("", "abc".slice(1u, 1u));
1685
1686         assert_eq!("中", ss.slice(0u, 3u));
1687         assert_eq!("华V", ss.slice(3u, 7u));
1688         assert_eq!("", ss.slice(3u, 3u));
1689         /*0: 中
1690           3: 华
1691           6: V
1692           7: i
1693           8: ệ
1694          11: t
1695          12:
1696          13: N
1697          14: a
1698          15: m */
1699     }
1700
1701     #[test]
1702     #[should_fail]
1703     fn test_slice_fail() {
1704         "中华Việt Nam".slice(0u, 2u);
1705     }
1706
1707     #[test]
1708     fn test_slice_from() {
1709         assert_eq!("abcd".slice_from(0), "abcd");
1710         assert_eq!("abcd".slice_from(2), "cd");
1711         assert_eq!("abcd".slice_from(4), "");
1712     }
1713     #[test]
1714     fn test_slice_to() {
1715         assert_eq!("abcd".slice_to(0), "");
1716         assert_eq!("abcd".slice_to(2), "ab");
1717         assert_eq!("abcd".slice_to(4), "abcd");
1718     }
1719
1720     #[test]
1721     fn test_trim_left_matches() {
1722         let v: &[char] = &[];
1723         assert_eq!(" *** foo *** ".trim_left_matches(v), " *** foo *** ");
1724         let chars: &[char] = &['*', ' '];
1725         assert_eq!(" *** foo *** ".trim_left_matches(chars), "foo *** ");
1726         assert_eq!(" ***  *** ".trim_left_matches(chars), "");
1727         assert_eq!("foo *** ".trim_left_matches(chars), "foo *** ");
1728
1729         assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
1730         let chars: &[char] = &['1', '2'];
1731         assert_eq!("12foo1bar12".trim_left_matches(chars), "foo1bar12");
1732         assert_eq!("123foo1bar123".trim_left_matches(|&: c: char| c.is_numeric()), "foo1bar123");
1733     }
1734
1735     #[test]
1736     fn test_trim_right_matches() {
1737         let v: &[char] = &[];
1738         assert_eq!(" *** foo *** ".trim_right_matches(v), " *** foo *** ");
1739         let chars: &[char] = &['*', ' '];
1740         assert_eq!(" *** foo *** ".trim_right_matches(chars), " *** foo");
1741         assert_eq!(" ***  *** ".trim_right_matches(chars), "");
1742         assert_eq!(" *** foo".trim_right_matches(chars), " *** foo");
1743
1744         assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
1745         let chars: &[char] = &['1', '2'];
1746         assert_eq!("12foo1bar12".trim_right_matches(chars), "12foo1bar");
1747         assert_eq!("123foo1bar123".trim_right_matches(|&: c: char| c.is_numeric()), "123foo1bar");
1748     }
1749
1750     #[test]
1751     fn test_trim_matches() {
1752         let v: &[char] = &[];
1753         assert_eq!(" *** foo *** ".trim_matches(v), " *** foo *** ");
1754         let chars: &[char] = &['*', ' '];
1755         assert_eq!(" *** foo *** ".trim_matches(chars), "foo");
1756         assert_eq!(" ***  *** ".trim_matches(chars), "");
1757         assert_eq!("foo".trim_matches(chars), "foo");
1758
1759         assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1760         let chars: &[char] = &['1', '2'];
1761         assert_eq!("12foo1bar12".trim_matches(chars), "foo1bar");
1762         assert_eq!("123foo1bar123".trim_matches(|&: c: char| c.is_numeric()), "foo1bar");
1763     }
1764
1765     #[test]
1766     fn test_trim_left() {
1767         assert_eq!("".trim_left(), "");
1768         assert_eq!("a".trim_left(), "a");
1769         assert_eq!("    ".trim_left(), "");
1770         assert_eq!("     blah".trim_left(), "blah");
1771         assert_eq!("   \u{3000}  wut".trim_left(), "wut");
1772         assert_eq!("hey ".trim_left(), "hey ");
1773     }
1774
1775     #[test]
1776     fn test_trim_right() {
1777         assert_eq!("".trim_right(), "");
1778         assert_eq!("a".trim_right(), "a");
1779         assert_eq!("    ".trim_right(), "");
1780         assert_eq!("blah     ".trim_right(), "blah");
1781         assert_eq!("wut   \u{3000}  ".trim_right(), "wut");
1782         assert_eq!(" hey".trim_right(), " hey");
1783     }
1784
1785     #[test]
1786     fn test_trim() {
1787         assert_eq!("".trim(), "");
1788         assert_eq!("a".trim(), "a");
1789         assert_eq!("    ".trim(), "");
1790         assert_eq!("    blah     ".trim(), "blah");
1791         assert_eq!("\nwut   \u{3000}  ".trim(), "wut");
1792         assert_eq!(" hey dude ".trim(), "hey dude");
1793     }
1794
1795     #[test]
1796     fn test_is_whitespace() {
1797         assert!("".chars().all(|c| c.is_whitespace()));
1798         assert!(" ".chars().all(|c| c.is_whitespace()));
1799         assert!("\u{2009}".chars().all(|c| c.is_whitespace())); // Thin space
1800         assert!("  \n\t   ".chars().all(|c| c.is_whitespace()));
1801         assert!(!"   _   ".chars().all(|c| c.is_whitespace()));
1802     }
1803
1804     #[test]
1805     fn test_slice_shift_char() {
1806         let data = "ประเทศไทย中";
1807         assert_eq!(data.slice_shift_char(), Some(('ป', "ระเทศไทย中")));
1808     }
1809
1810     #[test]
1811     fn test_slice_shift_char_2() {
1812         let empty = "";
1813         assert_eq!(empty.slice_shift_char(), None);
1814     }
1815
1816     #[test]
1817     fn test_is_utf8() {
1818         // deny overlong encodings
1819         assert!(from_utf8(&[0xc0, 0x80]).is_err());
1820         assert!(from_utf8(&[0xc0, 0xae]).is_err());
1821         assert!(from_utf8(&[0xe0, 0x80, 0x80]).is_err());
1822         assert!(from_utf8(&[0xe0, 0x80, 0xaf]).is_err());
1823         assert!(from_utf8(&[0xe0, 0x81, 0x81]).is_err());
1824         assert!(from_utf8(&[0xf0, 0x82, 0x82, 0xac]).is_err());
1825         assert!(from_utf8(&[0xf4, 0x90, 0x80, 0x80]).is_err());
1826
1827         // deny surrogates
1828         assert!(from_utf8(&[0xED, 0xA0, 0x80]).is_err());
1829         assert!(from_utf8(&[0xED, 0xBF, 0xBF]).is_err());
1830
1831         assert!(from_utf8(&[0xC2, 0x80]).is_ok());
1832         assert!(from_utf8(&[0xDF, 0xBF]).is_ok());
1833         assert!(from_utf8(&[0xE0, 0xA0, 0x80]).is_ok());
1834         assert!(from_utf8(&[0xED, 0x9F, 0xBF]).is_ok());
1835         assert!(from_utf8(&[0xEE, 0x80, 0x80]).is_ok());
1836         assert!(from_utf8(&[0xEF, 0xBF, 0xBF]).is_ok());
1837         assert!(from_utf8(&[0xF0, 0x90, 0x80, 0x80]).is_ok());
1838         assert!(from_utf8(&[0xF4, 0x8F, 0xBF, 0xBF]).is_ok());
1839     }
1840
1841     #[test]
1842     fn test_is_utf16() {
1843         use unicode::str::is_utf16;
1844         macro_rules! pos ( ($($e:expr),*) => { { $(assert!(is_utf16($e));)* } });
1845
1846         // non-surrogates
1847         pos!(&[0x0000],
1848              &[0x0001, 0x0002],
1849              &[0xD7FF],
1850              &[0xE000]);
1851
1852         // surrogate pairs (randomly generated with Python 3's
1853         // .encode('utf-16be'))
1854         pos!(&[0xdb54, 0xdf16, 0xd880, 0xdee0, 0xdb6a, 0xdd45],
1855              &[0xd91f, 0xdeb1, 0xdb31, 0xdd84, 0xd8e2, 0xde14],
1856              &[0xdb9f, 0xdc26, 0xdb6f, 0xde58, 0xd850, 0xdfae]);
1857
1858         // mixtures (also random)
1859         pos!(&[0xd921, 0xdcc2, 0x002d, 0x004d, 0xdb32, 0xdf65],
1860              &[0xdb45, 0xdd2d, 0x006a, 0xdacd, 0xddfe, 0x0006],
1861              &[0x0067, 0xd8ff, 0xddb7, 0x000f, 0xd900, 0xdc80]);
1862
1863         // negative tests
1864         macro_rules! neg ( ($($e:expr),*) => { { $(assert!(!is_utf16($e));)* } });
1865
1866         neg!(
1867             // surrogate + regular unit
1868             &[0xdb45, 0x0000],
1869             // surrogate + lead surrogate
1870             &[0xd900, 0xd900],
1871             // unterminated surrogate
1872             &[0xd8ff],
1873             // trail surrogate without a lead
1874             &[0xddb7]);
1875
1876         // random byte sequences that Python 3's .decode('utf-16be')
1877         // failed on
1878         neg!(&[0x5b3d, 0x0141, 0xde9e, 0x8fdc, 0xc6e7],
1879              &[0xdf5a, 0x82a5, 0x62b9, 0xb447, 0x92f3],
1880              &[0xda4e, 0x42bc, 0x4462, 0xee98, 0xc2ca],
1881              &[0xbe00, 0xb04a, 0x6ecb, 0xdd89, 0xe278],
1882              &[0x0465, 0xab56, 0xdbb6, 0xa893, 0x665e],
1883              &[0x6b7f, 0x0a19, 0x40f4, 0xa657, 0xdcc5],
1884              &[0x9b50, 0xda5e, 0x24ec, 0x03ad, 0x6dee],
1885              &[0x8d17, 0xcaa7, 0xf4ae, 0xdf6e, 0xbed7],
1886              &[0xdaee, 0x2584, 0x7d30, 0xa626, 0x121a],
1887              &[0xd956, 0x4b43, 0x7570, 0xccd6, 0x4f4a],
1888              &[0x9dcf, 0x1b49, 0x4ba5, 0xfce9, 0xdffe],
1889              &[0x6572, 0xce53, 0xb05a, 0xf6af, 0xdacf],
1890              &[0x1b90, 0x728c, 0x9906, 0xdb68, 0xf46e],
1891              &[0x1606, 0xbeca, 0xbe76, 0x860f, 0xdfa5],
1892              &[0x8b4f, 0xde7a, 0xd220, 0x9fac, 0x2b6f],
1893              &[0xb8fe, 0xebbe, 0xda32, 0x1a5f, 0x8b8b],
1894              &[0x934b, 0x8956, 0xc434, 0x1881, 0xddf7],
1895              &[0x5a95, 0x13fc, 0xf116, 0xd89b, 0x93f9],
1896              &[0xd640, 0x71f1, 0xdd7d, 0x77eb, 0x1cd8],
1897              &[0x348b, 0xaef0, 0xdb2c, 0xebf1, 0x1282],
1898              &[0x50d7, 0xd824, 0x5010, 0xb369, 0x22ea]);
1899     }
1900
1901     #[test]
1902     fn test_as_bytes() {
1903         // no null
1904         let v = [
1905             224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228,
1906             184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97,
1907             109
1908         ];
1909         let b: &[u8] = &[];
1910         assert_eq!("".as_bytes(), b);
1911         assert_eq!("abc".as_bytes(), b"abc");
1912         assert_eq!("ศไทย中华Việt Nam".as_bytes(), v);
1913     }
1914
1915     #[test]
1916     #[should_fail]
1917     fn test_as_bytes_fail() {
1918         // Don't double free. (I'm not sure if this exercises the
1919         // original problem code path anymore.)
1920         let s = String::from_str("");
1921         let _bytes = s.as_bytes();
1922         panic!();
1923     }
1924
1925     #[test]
1926     fn test_as_ptr() {
1927         let buf = "hello".as_ptr();
1928         unsafe {
1929             assert_eq!(*buf.offset(0), b'h');
1930             assert_eq!(*buf.offset(1), b'e');
1931             assert_eq!(*buf.offset(2), b'l');
1932             assert_eq!(*buf.offset(3), b'l');
1933             assert_eq!(*buf.offset(4), b'o');
1934         }
1935     }
1936
1937     #[test]
1938     fn test_subslice_offset() {
1939         let a = "kernelsprite";
1940         let b = a.slice(7, a.len());
1941         let c = a.slice(0, a.len() - 6);
1942         assert_eq!(a.subslice_offset(b), 7);
1943         assert_eq!(a.subslice_offset(c), 0);
1944
1945         let string = "a\nb\nc";
1946         let lines: Vec<&str> = string.lines().collect();
1947         assert_eq!(string.subslice_offset(lines[0]), 0);
1948         assert_eq!(string.subslice_offset(lines[1]), 2);
1949         assert_eq!(string.subslice_offset(lines[2]), 4);
1950     }
1951
1952     #[test]
1953     #[should_fail]
1954     fn test_subslice_offset_2() {
1955         let a = "alchemiter";
1956         let b = "cruxtruder";
1957         a.subslice_offset(b);
1958     }
1959
1960     #[test]
1961     fn vec_str_conversions() {
1962         let s1: String = String::from_str("All mimsy were the borogoves");
1963
1964         let v: Vec<u8> = s1.as_bytes().to_vec();
1965         let s2: String = String::from_str(from_utf8(v.as_slice()).unwrap());
1966         let mut i: uint = 0u;
1967         let n1: uint = s1.len();
1968         let n2: uint = v.len();
1969         assert_eq!(n1, n2);
1970         while i < n1 {
1971             let a: u8 = s1.as_bytes()[i];
1972             let b: u8 = s2.as_bytes()[i];
1973             debug!("{}", a);
1974             debug!("{}", b);
1975             assert_eq!(a, b);
1976             i += 1u;
1977         }
1978     }
1979
1980     #[test]
1981     fn test_contains() {
1982         assert!("abcde".contains("bcd"));
1983         assert!("abcde".contains("abcd"));
1984         assert!("abcde".contains("bcde"));
1985         assert!("abcde".contains(""));
1986         assert!("".contains(""));
1987         assert!(!"abcde".contains("def"));
1988         assert!(!"".contains("a"));
1989
1990         let data = "ประเทศไทย中华Việt Nam";
1991         assert!(data.contains("ประเ"));
1992         assert!(data.contains("ะเ"));
1993         assert!(data.contains("中华"));
1994         assert!(!data.contains("ไท华"));
1995     }
1996
1997     #[test]
1998     fn test_contains_char() {
1999         assert!("abc".contains_char('b'));
2000         assert!("a".contains_char('a'));
2001         assert!(!"abc".contains_char('d'));
2002         assert!(!"".contains_char('a'));
2003     }
2004
2005     #[test]
2006     fn test_char_at() {
2007         let s = "ศไทย中华Việt Nam";
2008         let v = vec!['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
2009         let mut pos = 0;
2010         for ch in v.iter() {
2011             assert!(s.char_at(pos) == *ch);
2012             pos += ch.to_string().len();
2013         }
2014     }
2015
2016     #[test]
2017     fn test_char_at_reverse() {
2018         let s = "ศไทย中华Việt Nam";
2019         let v = vec!['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
2020         let mut pos = s.len();
2021         for ch in v.iter().rev() {
2022             assert!(s.char_at_reverse(pos) == *ch);
2023             pos -= ch.to_string().len();
2024         }
2025     }
2026
2027     #[test]
2028     fn test_escape_unicode() {
2029         assert_eq!("abc".escape_unicode(),
2030                    String::from_str("\\u{61}\\u{62}\\u{63}"));
2031         assert_eq!("a c".escape_unicode(),
2032                    String::from_str("\\u{61}\\u{20}\\u{63}"));
2033         assert_eq!("\r\n\t".escape_unicode(),
2034                    String::from_str("\\u{d}\\u{a}\\u{9}"));
2035         assert_eq!("'\"\\".escape_unicode(),
2036                    String::from_str("\\u{27}\\u{22}\\u{5c}"));
2037         assert_eq!("\x00\x01\u{fe}\u{ff}".escape_unicode(),
2038                    String::from_str("\\u{0}\\u{1}\\u{fe}\\u{ff}"));
2039         assert_eq!("\u{100}\u{ffff}".escape_unicode(),
2040                    String::from_str("\\u{100}\\u{ffff}"));
2041         assert_eq!("\u{10000}\u{10ffff}".escape_unicode(),
2042                    String::from_str("\\u{10000}\\u{10ffff}"));
2043         assert_eq!("ab\u{fb00}".escape_unicode(),
2044                    String::from_str("\\u{61}\\u{62}\\u{fb00}"));
2045         assert_eq!("\u{1d4ea}\r".escape_unicode(),
2046                    String::from_str("\\u{1d4ea}\\u{d}"));
2047     }
2048
2049     #[test]
2050     fn test_escape_default() {
2051         assert_eq!("abc".escape_default(), String::from_str("abc"));
2052         assert_eq!("a c".escape_default(), String::from_str("a c"));
2053         assert_eq!("\r\n\t".escape_default(), String::from_str("\\r\\n\\t"));
2054         assert_eq!("'\"\\".escape_default(), String::from_str("\\'\\\"\\\\"));
2055         assert_eq!("\u{100}\u{ffff}".escape_default(),
2056                    String::from_str("\\u{100}\\u{ffff}"));
2057         assert_eq!("\u{10000}\u{10ffff}".escape_default(),
2058                    String::from_str("\\u{10000}\\u{10ffff}"));
2059         assert_eq!("ab\u{fb00}".escape_default(),
2060                    String::from_str("ab\\u{fb00}"));
2061         assert_eq!("\u{1d4ea}\r".escape_default(),
2062                    String::from_str("\\u{1d4ea}\\r"));
2063     }
2064
2065     #[test]
2066     fn test_total_ord() {
2067         "1234".cmp("123") == Greater;
2068         "123".cmp("1234") == Less;
2069         "1234".cmp("1234") == Equal;
2070         "12345555".cmp("123456") == Less;
2071         "22".cmp("1234") == Greater;
2072     }
2073
2074     #[test]
2075     fn test_char_range_at() {
2076         let data = "b¢€𤭢𤭢€¢b";
2077         assert_eq!('b', data.char_range_at(0).ch);
2078         assert_eq!('¢', data.char_range_at(1).ch);
2079         assert_eq!('€', data.char_range_at(3).ch);
2080         assert_eq!('𤭢', data.char_range_at(6).ch);
2081         assert_eq!('𤭢', data.char_range_at(10).ch);
2082         assert_eq!('€', data.char_range_at(14).ch);
2083         assert_eq!('¢', data.char_range_at(17).ch);
2084         assert_eq!('b', data.char_range_at(19).ch);
2085     }
2086
2087     #[test]
2088     fn test_char_range_at_reverse_underflow() {
2089         assert_eq!("abc".char_range_at_reverse(0).next, 0);
2090     }
2091
2092     #[test]
2093     fn test_iterator() {
2094         let s = "ศไทย中华Việt Nam";
2095         let v = ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
2096
2097         let mut pos = 0;
2098         let mut it = s.chars();
2099
2100         for c in it {
2101             assert_eq!(c, v[pos]);
2102             pos += 1;
2103         }
2104         assert_eq!(pos, v.len());
2105     }
2106
2107     #[test]
2108     fn test_rev_iterator() {
2109         let s = "ศไทย中华Việt Nam";
2110         let v = ['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ'];
2111
2112         let mut pos = 0;
2113         let mut it = s.chars().rev();
2114
2115         for c in it {
2116             assert_eq!(c, v[pos]);
2117             pos += 1;
2118         }
2119         assert_eq!(pos, v.len());
2120     }
2121
2122     #[test]
2123     fn test_chars_decoding() {
2124         let mut bytes = [0u8; 4];
2125         for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) {
2126             let len = c.encode_utf8(&mut bytes).unwrap_or(0);
2127             let s = ::core::str::from_utf8(bytes[..len]).unwrap();
2128             if Some(c) != s.chars().next() {
2129                 panic!("character {:x}={} does not decode correctly", c as u32, c);
2130             }
2131         }
2132     }
2133
2134     #[test]
2135     fn test_chars_rev_decoding() {
2136         let mut bytes = [0u8; 4];
2137         for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) {
2138             let len = c.encode_utf8(&mut bytes).unwrap_or(0);
2139             let s = ::core::str::from_utf8(bytes[..len]).unwrap();
2140             if Some(c) != s.chars().rev().next() {
2141                 panic!("character {:x}={} does not decode correctly", c as u32, c);
2142             }
2143         }
2144     }
2145
2146     #[test]
2147     fn test_iterator_clone() {
2148         let s = "ศไทย中华Việt Nam";
2149         let mut it = s.chars();
2150         it.next();
2151         assert!(it.zip(it.clone()).all(|(x,y)| x == y));
2152     }
2153
2154     #[test]
2155     fn test_bytesator() {
2156         let s = "ศไทย中华Việt Nam";
2157         let v = [
2158             224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228,
2159             184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97,
2160             109
2161         ];
2162         let mut pos = 0;
2163
2164         for b in s.bytes() {
2165             assert_eq!(b, v[pos]);
2166             pos += 1;
2167         }
2168     }
2169
2170     #[test]
2171     fn test_bytes_revator() {
2172         let s = "ศไทย中华Việt Nam";
2173         let v = [
2174             224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228,
2175             184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97,
2176             109
2177         ];
2178         let mut pos = v.len();
2179
2180         for b in s.bytes().rev() {
2181             pos -= 1;
2182             assert_eq!(b, v[pos]);
2183         }
2184     }
2185
2186     #[test]
2187     fn test_char_indicesator() {
2188         let s = "ศไทย中华Việt Nam";
2189         let p = [0, 3, 6, 9, 12, 15, 18, 19, 20, 23, 24, 25, 26, 27];
2190         let v = ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
2191
2192         let mut pos = 0;
2193         let mut it = s.char_indices();
2194
2195         for c in it {
2196             assert_eq!(c, (p[pos], v[pos]));
2197             pos += 1;
2198         }
2199         assert_eq!(pos, v.len());
2200         assert_eq!(pos, p.len());
2201     }
2202
2203     #[test]
2204     fn test_char_indices_revator() {
2205         let s = "ศไทย中华Việt Nam";
2206         let p = [27, 26, 25, 24, 23, 20, 19, 18, 15, 12, 9, 6, 3, 0];
2207         let v = ['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ'];
2208
2209         let mut pos = 0;
2210         let mut it = s.char_indices().rev();
2211
2212         for c in it {
2213             assert_eq!(c, (p[pos], v[pos]));
2214             pos += 1;
2215         }
2216         assert_eq!(pos, v.len());
2217         assert_eq!(pos, p.len());
2218     }
2219
2220     #[test]
2221     fn test_splitn_char_iterator() {
2222         let data = "\nMäry häd ä little lämb\nLittle lämb\n";
2223
2224         let split: Vec<&str> = data.splitn(3, ' ').collect();
2225         assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
2226
2227         let split: Vec<&str> = data.splitn(3, |&: c: char| c == ' ').collect();
2228         assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
2229
2230         // Unicode
2231         let split: Vec<&str> = data.splitn(3, 'ä').collect();
2232         assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
2233
2234         let split: Vec<&str> = data.splitn(3, |&: c: char| c == 'ä').collect();
2235         assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
2236     }
2237
2238     #[test]
2239     fn test_split_char_iterator_no_trailing() {
2240         let data = "\nMäry häd ä little lämb\nLittle lämb\n";
2241
2242         let split: Vec<&str> = data.split('\n').collect();
2243         assert_eq!(split, vec!["", "Märy häd ä little lämb", "Little lämb", ""]);
2244
2245         let split: Vec<&str> = data.split_terminator('\n').collect();
2246         assert_eq!(split, vec!["", "Märy häd ä little lämb", "Little lämb"]);
2247     }
2248
2249     #[test]
2250     fn test_words() {
2251         let data = "\n \tMäry   häd\tä  little lämb\nLittle lämb\n";
2252         let words: Vec<&str> = data.words().collect();
2253         assert_eq!(words, vec!["Märy", "häd", "ä", "little", "lämb", "Little", "lämb"])
2254     }
2255
2256     #[test]
2257     fn test_nfd_chars() {
2258         macro_rules! t {
2259             ($input: expr, $expected: expr) => {
2260                 assert_eq!($input.nfd_chars().collect::<String>(), $expected);
2261             }
2262         }
2263         t!("abc", "abc");
2264         t!("\u{1e0b}\u{1c4}", "d\u{307}\u{1c4}");
2265         t!("\u{2026}", "\u{2026}");
2266         t!("\u{2126}", "\u{3a9}");
2267         t!("\u{1e0b}\u{323}", "d\u{323}\u{307}");
2268         t!("\u{1e0d}\u{307}", "d\u{323}\u{307}");
2269         t!("a\u{301}", "a\u{301}");
2270         t!("\u{301}a", "\u{301}a");
2271         t!("\u{d4db}", "\u{1111}\u{1171}\u{11b6}");
2272         t!("\u{ac1c}", "\u{1100}\u{1162}");
2273     }
2274
2275     #[test]
2276     fn test_nfkd_chars() {
2277         macro_rules! t {
2278             ($input: expr, $expected: expr) => {
2279                 assert_eq!($input.nfkd_chars().collect::<String>(), $expected);
2280             }
2281         }
2282         t!("abc", "abc");
2283         t!("\u{1e0b}\u{1c4}", "d\u{307}DZ\u{30c}");
2284         t!("\u{2026}", "...");
2285         t!("\u{2126}", "\u{3a9}");
2286         t!("\u{1e0b}\u{323}", "d\u{323}\u{307}");
2287         t!("\u{1e0d}\u{307}", "d\u{323}\u{307}");
2288         t!("a\u{301}", "a\u{301}");
2289         t!("\u{301}a", "\u{301}a");
2290         t!("\u{d4db}", "\u{1111}\u{1171}\u{11b6}");
2291         t!("\u{ac1c}", "\u{1100}\u{1162}");
2292     }
2293
2294     #[test]
2295     fn test_nfc_chars() {
2296         macro_rules! t {
2297             ($input: expr, $expected: expr) => {
2298                 assert_eq!($input.nfc_chars().collect::<String>(), $expected);
2299             }
2300         }
2301         t!("abc", "abc");
2302         t!("\u{1e0b}\u{1c4}", "\u{1e0b}\u{1c4}");
2303         t!("\u{2026}", "\u{2026}");
2304         t!("\u{2126}", "\u{3a9}");
2305         t!("\u{1e0b}\u{323}", "\u{1e0d}\u{307}");
2306         t!("\u{1e0d}\u{307}", "\u{1e0d}\u{307}");
2307         t!("a\u{301}", "\u{e1}");
2308         t!("\u{301}a", "\u{301}a");
2309         t!("\u{d4db}", "\u{d4db}");
2310         t!("\u{ac1c}", "\u{ac1c}");
2311         t!("a\u{300}\u{305}\u{315}\u{5ae}b", "\u{e0}\u{5ae}\u{305}\u{315}b");
2312     }
2313
2314     #[test]
2315     fn test_nfkc_chars() {
2316         macro_rules! t {
2317             ($input: expr, $expected: expr) => {
2318                 assert_eq!($input.nfkc_chars().collect::<String>(), $expected);
2319             }
2320         }
2321         t!("abc", "abc");
2322         t!("\u{1e0b}\u{1c4}", "\u{1e0b}D\u{17d}");
2323         t!("\u{2026}", "...");
2324         t!("\u{2126}", "\u{3a9}");
2325         t!("\u{1e0b}\u{323}", "\u{1e0d}\u{307}");
2326         t!("\u{1e0d}\u{307}", "\u{1e0d}\u{307}");
2327         t!("a\u{301}", "\u{e1}");
2328         t!("\u{301}a", "\u{301}a");
2329         t!("\u{d4db}", "\u{d4db}");
2330         t!("\u{ac1c}", "\u{ac1c}");
2331         t!("a\u{300}\u{305}\u{315}\u{5ae}b", "\u{e0}\u{5ae}\u{305}\u{315}b");
2332     }
2333
2334     #[test]
2335     fn test_lines() {
2336         let data = "\nMäry häd ä little lämb\n\nLittle lämb\n";
2337         let lines: Vec<&str> = data.lines().collect();
2338         assert_eq!(lines, vec!["", "Märy häd ä little lämb", "", "Little lämb"]);
2339
2340         let data = "\nMäry häd ä little lämb\n\nLittle lämb"; // no trailing \n
2341         let lines: Vec<&str> = data.lines().collect();
2342         assert_eq!(lines, vec!["", "Märy häd ä little lämb", "", "Little lämb"]);
2343     }
2344
2345     #[test]
2346     fn test_graphemes() {
2347         use core::iter::order;
2348         // official Unicode test data
2349         // from http://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakTest.txt
2350         let test_same: [(_, &[_]); 325] = [
2351             ("\u{20}\u{20}", &["\u{20}", "\u{20}"]),
2352             ("\u{20}\u{308}\u{20}", &["\u{20}\u{308}", "\u{20}"]),
2353             ("\u{20}\u{D}", &["\u{20}", "\u{D}"]),
2354             ("\u{20}\u{308}\u{D}", &["\u{20}\u{308}", "\u{D}"]),
2355             ("\u{20}\u{A}", &["\u{20}", "\u{A}"]),
2356             ("\u{20}\u{308}\u{A}", &["\u{20}\u{308}", "\u{A}"]),
2357             ("\u{20}\u{1}", &["\u{20}", "\u{1}"]),
2358             ("\u{20}\u{308}\u{1}", &["\u{20}\u{308}", "\u{1}"]),
2359             ("\u{20}\u{300}", &["\u{20}\u{300}"]),
2360             ("\u{20}\u{308}\u{300}", &["\u{20}\u{308}\u{300}"]),
2361             ("\u{20}\u{1100}", &["\u{20}", "\u{1100}"]),
2362             ("\u{20}\u{308}\u{1100}", &["\u{20}\u{308}", "\u{1100}"]),
2363             ("\u{20}\u{1160}", &["\u{20}", "\u{1160}"]),
2364             ("\u{20}\u{308}\u{1160}", &["\u{20}\u{308}", "\u{1160}"]),
2365             ("\u{20}\u{11A8}", &["\u{20}", "\u{11A8}"]),
2366             ("\u{20}\u{308}\u{11A8}", &["\u{20}\u{308}", "\u{11A8}"]),
2367             ("\u{20}\u{AC00}", &["\u{20}", "\u{AC00}"]),
2368             ("\u{20}\u{308}\u{AC00}", &["\u{20}\u{308}", "\u{AC00}"]),
2369             ("\u{20}\u{AC01}", &["\u{20}", "\u{AC01}"]),
2370             ("\u{20}\u{308}\u{AC01}", &["\u{20}\u{308}", "\u{AC01}"]),
2371             ("\u{20}\u{1F1E6}", &["\u{20}", "\u{1F1E6}"]),
2372             ("\u{20}\u{308}\u{1F1E6}", &["\u{20}\u{308}", "\u{1F1E6}"]),
2373             ("\u{20}\u{378}", &["\u{20}", "\u{378}"]),
2374             ("\u{20}\u{308}\u{378}", &["\u{20}\u{308}", "\u{378}"]),
2375             ("\u{D}\u{20}", &["\u{D}", "\u{20}"]),
2376             ("\u{D}\u{308}\u{20}", &["\u{D}", "\u{308}", "\u{20}"]),
2377             ("\u{D}\u{D}", &["\u{D}", "\u{D}"]),
2378             ("\u{D}\u{308}\u{D}", &["\u{D}", "\u{308}", "\u{D}"]),
2379             ("\u{D}\u{A}", &["\u{D}\u{A}"]),
2380             ("\u{D}\u{308}\u{A}", &["\u{D}", "\u{308}", "\u{A}"]),
2381             ("\u{D}\u{1}", &["\u{D}", "\u{1}"]),
2382             ("\u{D}\u{308}\u{1}", &["\u{D}", "\u{308}", "\u{1}"]),
2383             ("\u{D}\u{300}", &["\u{D}", "\u{300}"]),
2384             ("\u{D}\u{308}\u{300}", &["\u{D}", "\u{308}\u{300}"]),
2385             ("\u{D}\u{903}", &["\u{D}", "\u{903}"]),
2386             ("\u{D}\u{1100}", &["\u{D}", "\u{1100}"]),
2387             ("\u{D}\u{308}\u{1100}", &["\u{D}", "\u{308}", "\u{1100}"]),
2388             ("\u{D}\u{1160}", &["\u{D}", "\u{1160}"]),
2389             ("\u{D}\u{308}\u{1160}", &["\u{D}", "\u{308}", "\u{1160}"]),
2390             ("\u{D}\u{11A8}", &["\u{D}", "\u{11A8}"]),
2391             ("\u{D}\u{308}\u{11A8}", &["\u{D}", "\u{308}", "\u{11A8}"]),
2392             ("\u{D}\u{AC00}", &["\u{D}", "\u{AC00}"]),
2393             ("\u{D}\u{308}\u{AC00}", &["\u{D}", "\u{308}", "\u{AC00}"]),
2394             ("\u{D}\u{AC01}", &["\u{D}", "\u{AC01}"]),
2395             ("\u{D}\u{308}\u{AC01}", &["\u{D}", "\u{308}", "\u{AC01}"]),
2396             ("\u{D}\u{1F1E6}", &["\u{D}", "\u{1F1E6}"]),
2397             ("\u{D}\u{308}\u{1F1E6}", &["\u{D}", "\u{308}", "\u{1F1E6}"]),
2398             ("\u{D}\u{378}", &["\u{D}", "\u{378}"]),
2399             ("\u{D}\u{308}\u{378}", &["\u{D}", "\u{308}", "\u{378}"]),
2400             ("\u{A}\u{20}", &["\u{A}", "\u{20}"]),
2401             ("\u{A}\u{308}\u{20}", &["\u{A}", "\u{308}", "\u{20}"]),
2402             ("\u{A}\u{D}", &["\u{A}", "\u{D}"]),
2403             ("\u{A}\u{308}\u{D}", &["\u{A}", "\u{308}", "\u{D}"]),
2404             ("\u{A}\u{A}", &["\u{A}", "\u{A}"]),
2405             ("\u{A}\u{308}\u{A}", &["\u{A}", "\u{308}", "\u{A}"]),
2406             ("\u{A}\u{1}", &["\u{A}", "\u{1}"]),
2407             ("\u{A}\u{308}\u{1}", &["\u{A}", "\u{308}", "\u{1}"]),
2408             ("\u{A}\u{300}", &["\u{A}", "\u{300}"]),
2409             ("\u{A}\u{308}\u{300}", &["\u{A}", "\u{308}\u{300}"]),
2410             ("\u{A}\u{903}", &["\u{A}", "\u{903}"]),
2411             ("\u{A}\u{1100}", &["\u{A}", "\u{1100}"]),
2412             ("\u{A}\u{308}\u{1100}", &["\u{A}", "\u{308}", "\u{1100}"]),
2413             ("\u{A}\u{1160}", &["\u{A}", "\u{1160}"]),
2414             ("\u{A}\u{308}\u{1160}", &["\u{A}", "\u{308}", "\u{1160}"]),
2415             ("\u{A}\u{11A8}", &["\u{A}", "\u{11A8}"]),
2416             ("\u{A}\u{308}\u{11A8}", &["\u{A}", "\u{308}", "\u{11A8}"]),
2417             ("\u{A}\u{AC00}", &["\u{A}", "\u{AC00}"]),
2418             ("\u{A}\u{308}\u{AC00}", &["\u{A}", "\u{308}", "\u{AC00}"]),
2419             ("\u{A}\u{AC01}", &["\u{A}", "\u{AC01}"]),
2420             ("\u{A}\u{308}\u{AC01}", &["\u{A}", "\u{308}", "\u{AC01}"]),
2421             ("\u{A}\u{1F1E6}", &["\u{A}", "\u{1F1E6}"]),
2422             ("\u{A}\u{308}\u{1F1E6}", &["\u{A}", "\u{308}", "\u{1F1E6}"]),
2423             ("\u{A}\u{378}", &["\u{A}", "\u{378}"]),
2424             ("\u{A}\u{308}\u{378}", &["\u{A}", "\u{308}", "\u{378}"]),
2425             ("\u{1}\u{20}", &["\u{1}", "\u{20}"]),
2426             ("\u{1}\u{308}\u{20}", &["\u{1}", "\u{308}", "\u{20}"]),
2427             ("\u{1}\u{D}", &["\u{1}", "\u{D}"]),
2428             ("\u{1}\u{308}\u{D}", &["\u{1}", "\u{308}", "\u{D}"]),
2429             ("\u{1}\u{A}", &["\u{1}", "\u{A}"]),
2430             ("\u{1}\u{308}\u{A}", &["\u{1}", "\u{308}", "\u{A}"]),
2431             ("\u{1}\u{1}", &["\u{1}", "\u{1}"]),
2432             ("\u{1}\u{308}\u{1}", &["\u{1}", "\u{308}", "\u{1}"]),
2433             ("\u{1}\u{300}", &["\u{1}", "\u{300}"]),
2434             ("\u{1}\u{308}\u{300}", &["\u{1}", "\u{308}\u{300}"]),
2435             ("\u{1}\u{903}", &["\u{1}", "\u{903}"]),
2436             ("\u{1}\u{1100}", &["\u{1}", "\u{1100}"]),
2437             ("\u{1}\u{308}\u{1100}", &["\u{1}", "\u{308}", "\u{1100}"]),
2438             ("\u{1}\u{1160}", &["\u{1}", "\u{1160}"]),
2439             ("\u{1}\u{308}\u{1160}", &["\u{1}", "\u{308}", "\u{1160}"]),
2440             ("\u{1}\u{11A8}", &["\u{1}", "\u{11A8}"]),
2441             ("\u{1}\u{308}\u{11A8}", &["\u{1}", "\u{308}", "\u{11A8}"]),
2442             ("\u{1}\u{AC00}", &["\u{1}", "\u{AC00}"]),
2443             ("\u{1}\u{308}\u{AC00}", &["\u{1}", "\u{308}", "\u{AC00}"]),
2444             ("\u{1}\u{AC01}", &["\u{1}", "\u{AC01}"]),
2445             ("\u{1}\u{308}\u{AC01}", &["\u{1}", "\u{308}", "\u{AC01}"]),
2446             ("\u{1}\u{1F1E6}", &["\u{1}", "\u{1F1E6}"]),
2447             ("\u{1}\u{308}\u{1F1E6}", &["\u{1}", "\u{308}", "\u{1F1E6}"]),
2448             ("\u{1}\u{378}", &["\u{1}", "\u{378}"]),
2449             ("\u{1}\u{308}\u{378}", &["\u{1}", "\u{308}", "\u{378}"]),
2450             ("\u{300}\u{20}", &["\u{300}", "\u{20}"]),
2451             ("\u{300}\u{308}\u{20}", &["\u{300}\u{308}", "\u{20}"]),
2452             ("\u{300}\u{D}", &["\u{300}", "\u{D}"]),
2453             ("\u{300}\u{308}\u{D}", &["\u{300}\u{308}", "\u{D}"]),
2454             ("\u{300}\u{A}", &["\u{300}", "\u{A}"]),
2455             ("\u{300}\u{308}\u{A}", &["\u{300}\u{308}", "\u{A}"]),
2456             ("\u{300}\u{1}", &["\u{300}", "\u{1}"]),
2457             ("\u{300}\u{308}\u{1}", &["\u{300}\u{308}", "\u{1}"]),
2458             ("\u{300}\u{300}", &["\u{300}\u{300}"]),
2459             ("\u{300}\u{308}\u{300}", &["\u{300}\u{308}\u{300}"]),
2460             ("\u{300}\u{1100}", &["\u{300}", "\u{1100}"]),
2461             ("\u{300}\u{308}\u{1100}", &["\u{300}\u{308}", "\u{1100}"]),
2462             ("\u{300}\u{1160}", &["\u{300}", "\u{1160}"]),
2463             ("\u{300}\u{308}\u{1160}", &["\u{300}\u{308}", "\u{1160}"]),
2464             ("\u{300}\u{11A8}", &["\u{300}", "\u{11A8}"]),
2465             ("\u{300}\u{308}\u{11A8}", &["\u{300}\u{308}", "\u{11A8}"]),
2466             ("\u{300}\u{AC00}", &["\u{300}", "\u{AC00}"]),
2467             ("\u{300}\u{308}\u{AC00}", &["\u{300}\u{308}", "\u{AC00}"]),
2468             ("\u{300}\u{AC01}", &["\u{300}", "\u{AC01}"]),
2469             ("\u{300}\u{308}\u{AC01}", &["\u{300}\u{308}", "\u{AC01}"]),
2470             ("\u{300}\u{1F1E6}", &["\u{300}", "\u{1F1E6}"]),
2471             ("\u{300}\u{308}\u{1F1E6}", &["\u{300}\u{308}", "\u{1F1E6}"]),
2472             ("\u{300}\u{378}", &["\u{300}", "\u{378}"]),
2473             ("\u{300}\u{308}\u{378}", &["\u{300}\u{308}", "\u{378}"]),
2474             ("\u{903}\u{20}", &["\u{903}", "\u{20}"]),
2475             ("\u{903}\u{308}\u{20}", &["\u{903}\u{308}", "\u{20}"]),
2476             ("\u{903}\u{D}", &["\u{903}", "\u{D}"]),
2477             ("\u{903}\u{308}\u{D}", &["\u{903}\u{308}", "\u{D}"]),
2478             ("\u{903}\u{A}", &["\u{903}", "\u{A}"]),
2479             ("\u{903}\u{308}\u{A}", &["\u{903}\u{308}", "\u{A}"]),
2480             ("\u{903}\u{1}", &["\u{903}", "\u{1}"]),
2481             ("\u{903}\u{308}\u{1}", &["\u{903}\u{308}", "\u{1}"]),
2482             ("\u{903}\u{300}", &["\u{903}\u{300}"]),
2483             ("\u{903}\u{308}\u{300}", &["\u{903}\u{308}\u{300}"]),
2484             ("\u{903}\u{1100}", &["\u{903}", "\u{1100}"]),
2485             ("\u{903}\u{308}\u{1100}", &["\u{903}\u{308}", "\u{1100}"]),
2486             ("\u{903}\u{1160}", &["\u{903}", "\u{1160}"]),
2487             ("\u{903}\u{308}\u{1160}", &["\u{903}\u{308}", "\u{1160}"]),
2488             ("\u{903}\u{11A8}", &["\u{903}", "\u{11A8}"]),
2489             ("\u{903}\u{308}\u{11A8}", &["\u{903}\u{308}", "\u{11A8}"]),
2490             ("\u{903}\u{AC00}", &["\u{903}", "\u{AC00}"]),
2491             ("\u{903}\u{308}\u{AC00}", &["\u{903}\u{308}", "\u{AC00}"]),
2492             ("\u{903}\u{AC01}", &["\u{903}", "\u{AC01}"]),
2493             ("\u{903}\u{308}\u{AC01}", &["\u{903}\u{308}", "\u{AC01}"]),
2494             ("\u{903}\u{1F1E6}", &["\u{903}", "\u{1F1E6}"]),
2495             ("\u{903}\u{308}\u{1F1E6}", &["\u{903}\u{308}", "\u{1F1E6}"]),
2496             ("\u{903}\u{378}", &["\u{903}", "\u{378}"]),
2497             ("\u{903}\u{308}\u{378}", &["\u{903}\u{308}", "\u{378}"]),
2498             ("\u{1100}\u{20}", &["\u{1100}", "\u{20}"]),
2499             ("\u{1100}\u{308}\u{20}", &["\u{1100}\u{308}", "\u{20}"]),
2500             ("\u{1100}\u{D}", &["\u{1100}", "\u{D}"]),
2501             ("\u{1100}\u{308}\u{D}", &["\u{1100}\u{308}", "\u{D}"]),
2502             ("\u{1100}\u{A}", &["\u{1100}", "\u{A}"]),
2503             ("\u{1100}\u{308}\u{A}", &["\u{1100}\u{308}", "\u{A}"]),
2504             ("\u{1100}\u{1}", &["\u{1100}", "\u{1}"]),
2505             ("\u{1100}\u{308}\u{1}", &["\u{1100}\u{308}", "\u{1}"]),
2506             ("\u{1100}\u{300}", &["\u{1100}\u{300}"]),
2507             ("\u{1100}\u{308}\u{300}", &["\u{1100}\u{308}\u{300}"]),
2508             ("\u{1100}\u{1100}", &["\u{1100}\u{1100}"]),
2509             ("\u{1100}\u{308}\u{1100}", &["\u{1100}\u{308}", "\u{1100}"]),
2510             ("\u{1100}\u{1160}", &["\u{1100}\u{1160}"]),
2511             ("\u{1100}\u{308}\u{1160}", &["\u{1100}\u{308}", "\u{1160}"]),
2512             ("\u{1100}\u{11A8}", &["\u{1100}", "\u{11A8}"]),
2513             ("\u{1100}\u{308}\u{11A8}", &["\u{1100}\u{308}", "\u{11A8}"]),
2514             ("\u{1100}\u{AC00}", &["\u{1100}\u{AC00}"]),
2515             ("\u{1100}\u{308}\u{AC00}", &["\u{1100}\u{308}", "\u{AC00}"]),
2516             ("\u{1100}\u{AC01}", &["\u{1100}\u{AC01}"]),
2517             ("\u{1100}\u{308}\u{AC01}", &["\u{1100}\u{308}", "\u{AC01}"]),
2518             ("\u{1100}\u{1F1E6}", &["\u{1100}", "\u{1F1E6}"]),
2519             ("\u{1100}\u{308}\u{1F1E6}", &["\u{1100}\u{308}", "\u{1F1E6}"]),
2520             ("\u{1100}\u{378}", &["\u{1100}", "\u{378}"]),
2521             ("\u{1100}\u{308}\u{378}", &["\u{1100}\u{308}", "\u{378}"]),
2522             ("\u{1160}\u{20}", &["\u{1160}", "\u{20}"]),
2523             ("\u{1160}\u{308}\u{20}", &["\u{1160}\u{308}", "\u{20}"]),
2524             ("\u{1160}\u{D}", &["\u{1160}", "\u{D}"]),
2525             ("\u{1160}\u{308}\u{D}", &["\u{1160}\u{308}", "\u{D}"]),
2526             ("\u{1160}\u{A}", &["\u{1160}", "\u{A}"]),
2527             ("\u{1160}\u{308}\u{A}", &["\u{1160}\u{308}", "\u{A}"]),
2528             ("\u{1160}\u{1}", &["\u{1160}", "\u{1}"]),
2529             ("\u{1160}\u{308}\u{1}", &["\u{1160}\u{308}", "\u{1}"]),
2530             ("\u{1160}\u{300}", &["\u{1160}\u{300}"]),
2531             ("\u{1160}\u{308}\u{300}", &["\u{1160}\u{308}\u{300}"]),
2532             ("\u{1160}\u{1100}", &["\u{1160}", "\u{1100}"]),
2533             ("\u{1160}\u{308}\u{1100}", &["\u{1160}\u{308}", "\u{1100}"]),
2534             ("\u{1160}\u{1160}", &["\u{1160}\u{1160}"]),
2535             ("\u{1160}\u{308}\u{1160}", &["\u{1160}\u{308}", "\u{1160}"]),
2536             ("\u{1160}\u{11A8}", &["\u{1160}\u{11A8}"]),
2537             ("\u{1160}\u{308}\u{11A8}", &["\u{1160}\u{308}", "\u{11A8}"]),
2538             ("\u{1160}\u{AC00}", &["\u{1160}", "\u{AC00}"]),
2539             ("\u{1160}\u{308}\u{AC00}", &["\u{1160}\u{308}", "\u{AC00}"]),
2540             ("\u{1160}\u{AC01}", &["\u{1160}", "\u{AC01}"]),
2541             ("\u{1160}\u{308}\u{AC01}", &["\u{1160}\u{308}", "\u{AC01}"]),
2542             ("\u{1160}\u{1F1E6}", &["\u{1160}", "\u{1F1E6}"]),
2543             ("\u{1160}\u{308}\u{1F1E6}", &["\u{1160}\u{308}", "\u{1F1E6}"]),
2544             ("\u{1160}\u{378}", &["\u{1160}", "\u{378}"]),
2545             ("\u{1160}\u{308}\u{378}", &["\u{1160}\u{308}", "\u{378}"]),
2546             ("\u{11A8}\u{20}", &["\u{11A8}", "\u{20}"]),
2547             ("\u{11A8}\u{308}\u{20}", &["\u{11A8}\u{308}", "\u{20}"]),
2548             ("\u{11A8}\u{D}", &["\u{11A8}", "\u{D}"]),
2549             ("\u{11A8}\u{308}\u{D}", &["\u{11A8}\u{308}", "\u{D}"]),
2550             ("\u{11A8}\u{A}", &["\u{11A8}", "\u{A}"]),
2551             ("\u{11A8}\u{308}\u{A}", &["\u{11A8}\u{308}", "\u{A}"]),
2552             ("\u{11A8}\u{1}", &["\u{11A8}", "\u{1}"]),
2553             ("\u{11A8}\u{308}\u{1}", &["\u{11A8}\u{308}", "\u{1}"]),
2554             ("\u{11A8}\u{300}", &["\u{11A8}\u{300}"]),
2555             ("\u{11A8}\u{308}\u{300}", &["\u{11A8}\u{308}\u{300}"]),
2556             ("\u{11A8}\u{1100}", &["\u{11A8}", "\u{1100}"]),
2557             ("\u{11A8}\u{308}\u{1100}", &["\u{11A8}\u{308}", "\u{1100}"]),
2558             ("\u{11A8}\u{1160}", &["\u{11A8}", "\u{1160}"]),
2559             ("\u{11A8}\u{308}\u{1160}", &["\u{11A8}\u{308}", "\u{1160}"]),
2560             ("\u{11A8}\u{11A8}", &["\u{11A8}\u{11A8}"]),
2561             ("\u{11A8}\u{308}\u{11A8}", &["\u{11A8}\u{308}", "\u{11A8}"]),
2562             ("\u{11A8}\u{AC00}", &["\u{11A8}", "\u{AC00}"]),
2563             ("\u{11A8}\u{308}\u{AC00}", &["\u{11A8}\u{308}", "\u{AC00}"]),
2564             ("\u{11A8}\u{AC01}", &["\u{11A8}", "\u{AC01}"]),
2565             ("\u{11A8}\u{308}\u{AC01}", &["\u{11A8}\u{308}", "\u{AC01}"]),
2566             ("\u{11A8}\u{1F1E6}", &["\u{11A8}", "\u{1F1E6}"]),
2567             ("\u{11A8}\u{308}\u{1F1E6}", &["\u{11A8}\u{308}", "\u{1F1E6}"]),
2568             ("\u{11A8}\u{378}", &["\u{11A8}", "\u{378}"]),
2569             ("\u{11A8}\u{308}\u{378}", &["\u{11A8}\u{308}", "\u{378}"]),
2570             ("\u{AC00}\u{20}", &["\u{AC00}", "\u{20}"]),
2571             ("\u{AC00}\u{308}\u{20}", &["\u{AC00}\u{308}", "\u{20}"]),
2572             ("\u{AC00}\u{D}", &["\u{AC00}", "\u{D}"]),
2573             ("\u{AC00}\u{308}\u{D}", &["\u{AC00}\u{308}", "\u{D}"]),
2574             ("\u{AC00}\u{A}", &["\u{AC00}", "\u{A}"]),
2575             ("\u{AC00}\u{308}\u{A}", &["\u{AC00}\u{308}", "\u{A}"]),
2576             ("\u{AC00}\u{1}", &["\u{AC00}", "\u{1}"]),
2577             ("\u{AC00}\u{308}\u{1}", &["\u{AC00}\u{308}", "\u{1}"]),
2578             ("\u{AC00}\u{300}", &["\u{AC00}\u{300}"]),
2579             ("\u{AC00}\u{308}\u{300}", &["\u{AC00}\u{308}\u{300}"]),
2580             ("\u{AC00}\u{1100}", &["\u{AC00}", "\u{1100}"]),
2581             ("\u{AC00}\u{308}\u{1100}", &["\u{AC00}\u{308}", "\u{1100}"]),
2582             ("\u{AC00}\u{1160}", &["\u{AC00}\u{1160}"]),
2583             ("\u{AC00}\u{308}\u{1160}", &["\u{AC00}\u{308}", "\u{1160}"]),
2584             ("\u{AC00}\u{11A8}", &["\u{AC00}\u{11A8}"]),
2585             ("\u{AC00}\u{308}\u{11A8}", &["\u{AC00}\u{308}", "\u{11A8}"]),
2586             ("\u{AC00}\u{AC00}", &["\u{AC00}", "\u{AC00}"]),
2587             ("\u{AC00}\u{308}\u{AC00}", &["\u{AC00}\u{308}", "\u{AC00}"]),
2588             ("\u{AC00}\u{AC01}", &["\u{AC00}", "\u{AC01}"]),
2589             ("\u{AC00}\u{308}\u{AC01}", &["\u{AC00}\u{308}", "\u{AC01}"]),
2590             ("\u{AC00}\u{1F1E6}", &["\u{AC00}", "\u{1F1E6}"]),
2591             ("\u{AC00}\u{308}\u{1F1E6}", &["\u{AC00}\u{308}", "\u{1F1E6}"]),
2592             ("\u{AC00}\u{378}", &["\u{AC00}", "\u{378}"]),
2593             ("\u{AC00}\u{308}\u{378}", &["\u{AC00}\u{308}", "\u{378}"]),
2594             ("\u{AC01}\u{20}", &["\u{AC01}", "\u{20}"]),
2595             ("\u{AC01}\u{308}\u{20}", &["\u{AC01}\u{308}", "\u{20}"]),
2596             ("\u{AC01}\u{D}", &["\u{AC01}", "\u{D}"]),
2597             ("\u{AC01}\u{308}\u{D}", &["\u{AC01}\u{308}", "\u{D}"]),
2598             ("\u{AC01}\u{A}", &["\u{AC01}", "\u{A}"]),
2599             ("\u{AC01}\u{308}\u{A}", &["\u{AC01}\u{308}", "\u{A}"]),
2600             ("\u{AC01}\u{1}", &["\u{AC01}", "\u{1}"]),
2601             ("\u{AC01}\u{308}\u{1}", &["\u{AC01}\u{308}", "\u{1}"]),
2602             ("\u{AC01}\u{300}", &["\u{AC01}\u{300}"]),
2603             ("\u{AC01}\u{308}\u{300}", &["\u{AC01}\u{308}\u{300}"]),
2604             ("\u{AC01}\u{1100}", &["\u{AC01}", "\u{1100}"]),
2605             ("\u{AC01}\u{308}\u{1100}", &["\u{AC01}\u{308}", "\u{1100}"]),
2606             ("\u{AC01}\u{1160}", &["\u{AC01}", "\u{1160}"]),
2607             ("\u{AC01}\u{308}\u{1160}", &["\u{AC01}\u{308}", "\u{1160}"]),
2608             ("\u{AC01}\u{11A8}", &["\u{AC01}\u{11A8}"]),
2609             ("\u{AC01}\u{308}\u{11A8}", &["\u{AC01}\u{308}", "\u{11A8}"]),
2610             ("\u{AC01}\u{AC00}", &["\u{AC01}", "\u{AC00}"]),
2611             ("\u{AC01}\u{308}\u{AC00}", &["\u{AC01}\u{308}", "\u{AC00}"]),
2612             ("\u{AC01}\u{AC01}", &["\u{AC01}", "\u{AC01}"]),
2613             ("\u{AC01}\u{308}\u{AC01}", &["\u{AC01}\u{308}", "\u{AC01}"]),
2614             ("\u{AC01}\u{1F1E6}", &["\u{AC01}", "\u{1F1E6}"]),
2615             ("\u{AC01}\u{308}\u{1F1E6}", &["\u{AC01}\u{308}", "\u{1F1E6}"]),
2616             ("\u{AC01}\u{378}", &["\u{AC01}", "\u{378}"]),
2617             ("\u{AC01}\u{308}\u{378}", &["\u{AC01}\u{308}", "\u{378}"]),
2618             ("\u{1F1E6}\u{20}", &["\u{1F1E6}", "\u{20}"]),
2619             ("\u{1F1E6}\u{308}\u{20}", &["\u{1F1E6}\u{308}", "\u{20}"]),
2620             ("\u{1F1E6}\u{D}", &["\u{1F1E6}", "\u{D}"]),
2621             ("\u{1F1E6}\u{308}\u{D}", &["\u{1F1E6}\u{308}", "\u{D}"]),
2622             ("\u{1F1E6}\u{A}", &["\u{1F1E6}", "\u{A}"]),
2623             ("\u{1F1E6}\u{308}\u{A}", &["\u{1F1E6}\u{308}", "\u{A}"]),
2624             ("\u{1F1E6}\u{1}", &["\u{1F1E6}", "\u{1}"]),
2625             ("\u{1F1E6}\u{308}\u{1}", &["\u{1F1E6}\u{308}", "\u{1}"]),
2626             ("\u{1F1E6}\u{300}", &["\u{1F1E6}\u{300}"]),
2627             ("\u{1F1E6}\u{308}\u{300}", &["\u{1F1E6}\u{308}\u{300}"]),
2628             ("\u{1F1E6}\u{1100}", &["\u{1F1E6}", "\u{1100}"]),
2629             ("\u{1F1E6}\u{308}\u{1100}", &["\u{1F1E6}\u{308}", "\u{1100}"]),
2630             ("\u{1F1E6}\u{1160}", &["\u{1F1E6}", "\u{1160}"]),
2631             ("\u{1F1E6}\u{308}\u{1160}", &["\u{1F1E6}\u{308}", "\u{1160}"]),
2632             ("\u{1F1E6}\u{11A8}", &["\u{1F1E6}", "\u{11A8}"]),
2633             ("\u{1F1E6}\u{308}\u{11A8}", &["\u{1F1E6}\u{308}", "\u{11A8}"]),
2634             ("\u{1F1E6}\u{AC00}", &["\u{1F1E6}", "\u{AC00}"]),
2635             ("\u{1F1E6}\u{308}\u{AC00}", &["\u{1F1E6}\u{308}", "\u{AC00}"]),
2636             ("\u{1F1E6}\u{AC01}", &["\u{1F1E6}", "\u{AC01}"]),
2637             ("\u{1F1E6}\u{308}\u{AC01}", &["\u{1F1E6}\u{308}", "\u{AC01}"]),
2638             ("\u{1F1E6}\u{1F1E6}", &["\u{1F1E6}\u{1F1E6}"]),
2639             ("\u{1F1E6}\u{308}\u{1F1E6}", &["\u{1F1E6}\u{308}", "\u{1F1E6}"]),
2640             ("\u{1F1E6}\u{378}", &["\u{1F1E6}", "\u{378}"]),
2641             ("\u{1F1E6}\u{308}\u{378}", &["\u{1F1E6}\u{308}", "\u{378}"]),
2642             ("\u{378}\u{20}", &["\u{378}", "\u{20}"]),
2643             ("\u{378}\u{308}\u{20}", &["\u{378}\u{308}", "\u{20}"]),
2644             ("\u{378}\u{D}", &["\u{378}", "\u{D}"]),
2645             ("\u{378}\u{308}\u{D}", &["\u{378}\u{308}", "\u{D}"]),
2646             ("\u{378}\u{A}", &["\u{378}", "\u{A}"]),
2647             ("\u{378}\u{308}\u{A}", &["\u{378}\u{308}", "\u{A}"]),
2648             ("\u{378}\u{1}", &["\u{378}", "\u{1}"]),
2649             ("\u{378}\u{308}\u{1}", &["\u{378}\u{308}", "\u{1}"]),
2650             ("\u{378}\u{300}", &["\u{378}\u{300}"]),
2651             ("\u{378}\u{308}\u{300}", &["\u{378}\u{308}\u{300}"]),
2652             ("\u{378}\u{1100}", &["\u{378}", "\u{1100}"]),
2653             ("\u{378}\u{308}\u{1100}", &["\u{378}\u{308}", "\u{1100}"]),
2654             ("\u{378}\u{1160}", &["\u{378}", "\u{1160}"]),
2655             ("\u{378}\u{308}\u{1160}", &["\u{378}\u{308}", "\u{1160}"]),
2656             ("\u{378}\u{11A8}", &["\u{378}", "\u{11A8}"]),
2657             ("\u{378}\u{308}\u{11A8}", &["\u{378}\u{308}", "\u{11A8}"]),
2658             ("\u{378}\u{AC00}", &["\u{378}", "\u{AC00}"]),
2659             ("\u{378}\u{308}\u{AC00}", &["\u{378}\u{308}", "\u{AC00}"]),
2660             ("\u{378}\u{AC01}", &["\u{378}", "\u{AC01}"]),
2661             ("\u{378}\u{308}\u{AC01}", &["\u{378}\u{308}", "\u{AC01}"]),
2662             ("\u{378}\u{1F1E6}", &["\u{378}", "\u{1F1E6}"]),
2663             ("\u{378}\u{308}\u{1F1E6}", &["\u{378}\u{308}", "\u{1F1E6}"]),
2664             ("\u{378}\u{378}", &["\u{378}", "\u{378}"]),
2665             ("\u{378}\u{308}\u{378}", &["\u{378}\u{308}", "\u{378}"]),
2666             ("\u{61}\u{1F1E6}\u{62}", &["\u{61}", "\u{1F1E6}", "\u{62}"]),
2667             ("\u{1F1F7}\u{1F1FA}", &["\u{1F1F7}\u{1F1FA}"]),
2668             ("\u{1F1F7}\u{1F1FA}\u{1F1F8}", &["\u{1F1F7}\u{1F1FA}\u{1F1F8}"]),
2669             ("\u{1F1F7}\u{1F1FA}\u{1F1F8}\u{1F1EA}",
2670             &["\u{1F1F7}\u{1F1FA}\u{1F1F8}\u{1F1EA}"]),
2671             ("\u{1F1F7}\u{1F1FA}\u{200B}\u{1F1F8}\u{1F1EA}",
2672              &["\u{1F1F7}\u{1F1FA}", "\u{200B}", "\u{1F1F8}\u{1F1EA}"]),
2673             ("\u{1F1E6}\u{1F1E7}\u{1F1E8}", &["\u{1F1E6}\u{1F1E7}\u{1F1E8}"]),
2674             ("\u{1F1E6}\u{200D}\u{1F1E7}\u{1F1E8}", &["\u{1F1E6}\u{200D}",
2675              "\u{1F1E7}\u{1F1E8}"]),
2676             ("\u{1F1E6}\u{1F1E7}\u{200D}\u{1F1E8}",
2677              &["\u{1F1E6}\u{1F1E7}\u{200D}", "\u{1F1E8}"]),
2678             ("\u{20}\u{200D}\u{646}", &["\u{20}\u{200D}", "\u{646}"]),
2679             ("\u{646}\u{200D}\u{20}", &["\u{646}\u{200D}", "\u{20}"]),
2680         ];
2681
2682         let test_diff: [(_, &[_], &[_]); 23] = [
2683             ("\u{20}\u{903}", &["\u{20}\u{903}"], &["\u{20}", "\u{903}"]), ("\u{20}\u{308}\u{903}",
2684             &["\u{20}\u{308}\u{903}"], &["\u{20}\u{308}", "\u{903}"]), ("\u{D}\u{308}\u{903}",
2685             &["\u{D}", "\u{308}\u{903}"], &["\u{D}", "\u{308}", "\u{903}"]), ("\u{A}\u{308}\u{903}",
2686             &["\u{A}", "\u{308}\u{903}"], &["\u{A}", "\u{308}", "\u{903}"]), ("\u{1}\u{308}\u{903}",
2687             &["\u{1}", "\u{308}\u{903}"], &["\u{1}", "\u{308}", "\u{903}"]), ("\u{300}\u{903}",
2688             &["\u{300}\u{903}"], &["\u{300}", "\u{903}"]), ("\u{300}\u{308}\u{903}",
2689             &["\u{300}\u{308}\u{903}"], &["\u{300}\u{308}", "\u{903}"]), ("\u{903}\u{903}",
2690             &["\u{903}\u{903}"], &["\u{903}", "\u{903}"]), ("\u{903}\u{308}\u{903}",
2691             &["\u{903}\u{308}\u{903}"], &["\u{903}\u{308}", "\u{903}"]), ("\u{1100}\u{903}",
2692             &["\u{1100}\u{903}"], &["\u{1100}", "\u{903}"]), ("\u{1100}\u{308}\u{903}",
2693             &["\u{1100}\u{308}\u{903}"], &["\u{1100}\u{308}", "\u{903}"]), ("\u{1160}\u{903}",
2694             &["\u{1160}\u{903}"], &["\u{1160}", "\u{903}"]), ("\u{1160}\u{308}\u{903}",
2695             &["\u{1160}\u{308}\u{903}"], &["\u{1160}\u{308}", "\u{903}"]), ("\u{11A8}\u{903}",
2696             &["\u{11A8}\u{903}"], &["\u{11A8}", "\u{903}"]), ("\u{11A8}\u{308}\u{903}",
2697             &["\u{11A8}\u{308}\u{903}"], &["\u{11A8}\u{308}", "\u{903}"]), ("\u{AC00}\u{903}",
2698             &["\u{AC00}\u{903}"], &["\u{AC00}", "\u{903}"]), ("\u{AC00}\u{308}\u{903}",
2699             &["\u{AC00}\u{308}\u{903}"], &["\u{AC00}\u{308}", "\u{903}"]), ("\u{AC01}\u{903}",
2700             &["\u{AC01}\u{903}"], &["\u{AC01}", "\u{903}"]), ("\u{AC01}\u{308}\u{903}",
2701             &["\u{AC01}\u{308}\u{903}"], &["\u{AC01}\u{308}", "\u{903}"]), ("\u{1F1E6}\u{903}",
2702             &["\u{1F1E6}\u{903}"], &["\u{1F1E6}", "\u{903}"]), ("\u{1F1E6}\u{308}\u{903}",
2703             &["\u{1F1E6}\u{308}\u{903}"], &["\u{1F1E6}\u{308}", "\u{903}"]), ("\u{378}\u{903}",
2704             &["\u{378}\u{903}"], &["\u{378}", "\u{903}"]), ("\u{378}\u{308}\u{903}",
2705             &["\u{378}\u{308}\u{903}"], &["\u{378}\u{308}", "\u{903}"]),
2706         ];
2707
2708         for &(s, g) in test_same.iter() {
2709             // test forward iterator
2710             assert!(order::equals(s.graphemes(true), g.iter().map(|&x| x)));
2711             assert!(order::equals(s.graphemes(false), g.iter().map(|&x| x)));
2712
2713             // test reverse iterator
2714             assert!(order::equals(s.graphemes(true).rev(), g.iter().rev().map(|&x| x)));
2715             assert!(order::equals(s.graphemes(false).rev(), g.iter().rev().map(|&x| x)));
2716         }
2717
2718         for &(s, gt, gf) in test_diff.iter() {
2719             // test forward iterator
2720             assert!(order::equals(s.graphemes(true), gt.iter().map(|&x| x)));
2721             assert!(order::equals(s.graphemes(false), gf.iter().map(|&x| x)));
2722
2723             // test reverse iterator
2724             assert!(order::equals(s.graphemes(true).rev(), gt.iter().rev().map(|&x| x)));
2725             assert!(order::equals(s.graphemes(false).rev(), gf.iter().rev().map(|&x| x)));
2726         }
2727
2728         // test the indices iterators
2729         let s = "a̐éö̲\r\n";
2730         let gr_inds = s.grapheme_indices(true).collect::<Vec<(uint, &str)>>();
2731         let b: &[_] = &[(0u, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
2732         assert_eq!(gr_inds, b);
2733         let gr_inds = s.grapheme_indices(true).rev().collect::<Vec<(uint, &str)>>();
2734         let b: &[_] = &[(11, "\r\n"), (6, "ö̲"), (3, "é"), (0u, "a̐")];
2735         assert_eq!(gr_inds, b);
2736         let mut gr_inds_iter = s.grapheme_indices(true);
2737         {
2738             let gr_inds = gr_inds_iter.by_ref();
2739             let e1 = gr_inds.size_hint();
2740             assert_eq!(e1, (1, Some(13)));
2741             let c = gr_inds.count();
2742             assert_eq!(c, 4);
2743         }
2744         let e2 = gr_inds_iter.size_hint();
2745         assert_eq!(e2, (0, Some(0)));
2746
2747         // make sure the reverse iterator does the right thing with "\n" at beginning of string
2748         let s = "\n\r\n\r";
2749         let gr = s.graphemes(true).rev().collect::<Vec<&str>>();
2750         let b: &[_] = &["\r", "\r\n", "\n"];
2751         assert_eq!(gr, b);
2752     }
2753
2754     #[test]
2755     fn test_split_strator() {
2756         fn t(s: &str, sep: &str, u: &[&str]) {
2757             let v: Vec<&str> = s.split_str(sep).collect();
2758             assert_eq!(v, u);
2759         }
2760         t("--1233345--", "12345", &["--1233345--"]);
2761         t("abc::hello::there", "::", &["abc", "hello", "there"]);
2762         t("::hello::there", "::", &["", "hello", "there"]);
2763         t("hello::there::", "::", &["hello", "there", ""]);
2764         t("::hello::there::", "::", &["", "hello", "there", ""]);
2765         t("ประเทศไทย中华Việt Nam", "中华", &["ประเทศไทย", "Việt Nam"]);
2766         t("zzXXXzzYYYzz", "zz", &["", "XXX", "YYY", ""]);
2767         t("zzXXXzYYYz", "XXX", &["zz", "zYYYz"]);
2768         t(".XXX.YYY.", ".", &["", "XXX", "YYY", ""]);
2769         t("", ".", &[""]);
2770         t("zz", "zz", &["",""]);
2771         t("ok", "z", &["ok"]);
2772         t("zzz", "zz", &["","z"]);
2773         t("zzzzz", "zz", &["","","z"]);
2774     }
2775
2776     #[test]
2777     fn test_str_default() {
2778         use core::default::Default;
2779         fn t<S: Default + Str>() {
2780             let s: S = Default::default();
2781             assert_eq!(s.as_slice(), "");
2782         }
2783
2784         t::<&str>();
2785         t::<String>();
2786     }
2787
2788     #[test]
2789     fn test_str_container() {
2790         fn sum_len(v: &[&str]) -> uint {
2791             v.iter().map(|x| x.len()).sum()
2792         }
2793
2794         let s = String::from_str("01234");
2795         assert_eq!(5, sum_len(&["012", "", "34"]));
2796         assert_eq!(5, sum_len(&[String::from_str("01").as_slice(),
2797                                 String::from_str("2").as_slice(),
2798                                 String::from_str("34").as_slice(),
2799                                 String::from_str("").as_slice()]));
2800         assert_eq!(5, sum_len(&[s.as_slice()]));
2801     }
2802
2803     #[test]
2804     fn test_str_from_utf8() {
2805         let xs = b"hello";
2806         assert_eq!(from_utf8(xs), Ok("hello"));
2807
2808         let xs = "ศไทย中华Việt Nam".as_bytes();
2809         assert_eq!(from_utf8(xs), Ok("ศไทย中华Việt Nam"));
2810
2811         let xs = b"hello\xFF";
2812         assert_eq!(from_utf8(xs), Err(Utf8Error::TooShort));
2813     }
2814 }
2815
2816 #[cfg(test)]
2817 mod bench {
2818     use super::*;
2819     use prelude::{SliceExt, IteratorExt, SliceConcatExt};
2820     use test::Bencher;
2821     use test::black_box;
2822
2823     #[bench]
2824     fn char_iterator(b: &mut Bencher) {
2825         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
2826
2827         b.iter(|| s.chars().count());
2828     }
2829
2830     #[bench]
2831     fn char_iterator_for(b: &mut Bencher) {
2832         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
2833
2834         b.iter(|| {
2835             for ch in s.chars() { black_box(ch) }
2836         });
2837     }
2838
2839     #[bench]
2840     fn char_iterator_ascii(b: &mut Bencher) {
2841         let s = "Mary had a little lamb, Little lamb
2842         Mary had a little lamb, Little lamb
2843         Mary had a little lamb, Little lamb
2844         Mary had a little lamb, Little lamb
2845         Mary had a little lamb, Little lamb
2846         Mary had a little lamb, Little lamb";
2847
2848         b.iter(|| s.chars().count());
2849     }
2850
2851     #[bench]
2852     fn char_iterator_rev(b: &mut Bencher) {
2853         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
2854
2855         b.iter(|| s.chars().rev().count());
2856     }
2857
2858     #[bench]
2859     fn char_iterator_rev_for(b: &mut Bencher) {
2860         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
2861
2862         b.iter(|| {
2863             for ch in s.chars().rev() { black_box(ch) }
2864         });
2865     }
2866
2867     #[bench]
2868     fn char_indicesator(b: &mut Bencher) {
2869         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
2870         let len = s.chars().count();
2871
2872         b.iter(|| assert_eq!(s.char_indices().count(), len));
2873     }
2874
2875     #[bench]
2876     fn char_indicesator_rev(b: &mut Bencher) {
2877         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
2878         let len = s.chars().count();
2879
2880         b.iter(|| assert_eq!(s.char_indices().rev().count(), len));
2881     }
2882
2883     #[bench]
2884     fn split_unicode_ascii(b: &mut Bencher) {
2885         let s = "ประเทศไทย中华Việt Namประเทศไทย中华Việt Nam";
2886
2887         b.iter(|| assert_eq!(s.split('V').count(), 3));
2888     }
2889
2890     #[bench]
2891     fn split_unicode_not_ascii(b: &mut Bencher) {
2892         struct NotAscii(char);
2893         impl CharEq for NotAscii {
2894             fn matches(&mut self, c: char) -> bool {
2895                 let NotAscii(cc) = *self;
2896                 cc == c
2897             }
2898             fn only_ascii(&self) -> bool { false }
2899         }
2900         let s = "ประเทศไทย中华Việt Namประเทศไทย中华Việt Nam";
2901
2902         b.iter(|| assert_eq!(s.split(NotAscii('V')).count(), 3));
2903     }
2904
2905
2906     #[bench]
2907     fn split_ascii(b: &mut Bencher) {
2908         let s = "Mary had a little lamb, Little lamb, little-lamb.";
2909         let len = s.split(' ').count();
2910
2911         b.iter(|| assert_eq!(s.split(' ').count(), len));
2912     }
2913
2914     #[bench]
2915     fn split_not_ascii(b: &mut Bencher) {
2916         struct NotAscii(char);
2917         impl CharEq for NotAscii {
2918             #[inline]
2919             fn matches(&mut self, c: char) -> bool {
2920                 let NotAscii(cc) = *self;
2921                 cc == c
2922             }
2923             fn only_ascii(&self) -> bool { false }
2924         }
2925         let s = "Mary had a little lamb, Little lamb, little-lamb.";
2926         let len = s.split(' ').count();
2927
2928         b.iter(|| assert_eq!(s.split(NotAscii(' ')).count(), len));
2929     }
2930
2931     #[bench]
2932     fn split_extern_fn(b: &mut Bencher) {
2933         let s = "Mary had a little lamb, Little lamb, little-lamb.";
2934         let len = s.split(' ').count();
2935         fn pred(c: char) -> bool { c == ' ' }
2936
2937         b.iter(|| assert_eq!(s.split(pred).count(), len));
2938     }
2939
2940     #[bench]
2941     fn split_closure(b: &mut Bencher) {
2942         let s = "Mary had a little lamb, Little lamb, little-lamb.";
2943         let len = s.split(' ').count();
2944
2945         b.iter(|| assert_eq!(s.split(|&: c: char| c == ' ').count(), len));
2946     }
2947
2948     #[bench]
2949     fn split_slice(b: &mut Bencher) {
2950         let s = "Mary had a little lamb, Little lamb, little-lamb.";
2951         let len = s.split(' ').count();
2952
2953         let c: &[char] = &[' '];
2954         b.iter(|| assert_eq!(s.split(c).count(), len));
2955     }
2956
2957     #[bench]
2958     fn bench_connect(b: &mut Bencher) {
2959         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
2960         let sep = "→";
2961         let v = vec![s, s, s, s, s, s, s, s, s, s];
2962         b.iter(|| {
2963             assert_eq!(v.connect(sep).len(), s.len() * 10 + sep.len() * 9);
2964         })
2965     }
2966
2967     #[bench]
2968     fn bench_contains_short_short(b: &mut Bencher) {
2969         let haystack = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
2970         let needle = "sit";
2971
2972         b.iter(|| {
2973             assert!(haystack.contains(needle));
2974         })
2975     }
2976
2977     #[bench]
2978     fn bench_contains_short_long(b: &mut Bencher) {
2979         let haystack = "\
2980 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis lorem sit amet dolor \
2981 ultricies condimentum. Praesent iaculis purus elit, ac malesuada quam malesuada in. Duis sed orci \
2982 eros. Suspendisse sit amet magna mollis, mollis nunc luctus, imperdiet mi. Integer fringilla non \
2983 sem ut lacinia. Fusce varius tortor a risus porttitor hendrerit. Morbi mauris dui, ultricies nec \
2984 tempus vel, gravida nec quam.
2985
2986 In est dui, tincidunt sed tempus interdum, adipiscing laoreet ante. Etiam tempor, tellus quis \
2987 sagittis interdum, nulla purus mattis sem, quis auctor erat odio ac tellus. In nec nunc sit amet \
2988 diam volutpat molestie at sed ipsum. Vestibulum laoreet consequat vulputate. Integer accumsan \
2989 lorem ac dignissim placerat. Suspendisse convallis faucibus lorem. Aliquam erat volutpat. In vel \
2990 eleifend felis. Sed suscipit nulla lorem, sed mollis est sollicitudin et. Nam fermentum egestas \
2991 interdum. Curabitur ut nisi justo.
2992
2993 Sed sollicitudin ipsum tellus, ut condimentum leo eleifend nec. Cras ut velit ante. Phasellus nec \
2994 mollis odio. Mauris molestie erat in arcu mattis, at aliquet dolor vehicula. Quisque malesuada \
2995 lectus sit amet nisi pretium, a condimentum ipsum porta. Morbi at dapibus diam. Praesent egestas \
2996 est sed risus elementum, eu rutrum metus ultrices. Etiam fermentum consectetur magna, id rutrum \
2997 felis accumsan a. Aliquam ut pellentesque libero. Sed mi nulla, lobortis eu tortor id, suscipit \
2998 ultricies neque. Morbi iaculis sit amet risus at iaculis. Praesent eget ligula quis turpis \
2999 feugiat suscipit vel non arcu. Interdum et malesuada fames ac ante ipsum primis in faucibus. \
3000 Aliquam sit amet placerat lorem.
3001
3002 Cras a lacus vel ante posuere elementum. Nunc est leo, bibendum ut facilisis vel, bibendum at \
3003 mauris. Nullam adipiscing diam vel odio ornare, luctus adipiscing mi luctus. Nulla facilisi. \
3004 Mauris adipiscing bibendum neque, quis adipiscing lectus tempus et. Sed feugiat erat et nisl \
3005 lobortis pharetra. Donec vitae erat enim. Nullam sit amet felis et quam lacinia tincidunt. Aliquam \
3006 suscipit dapibus urna. Sed volutpat urna in magna pulvinar volutpat. Phasellus nec tellus ac diam \
3007 cursus accumsan.
3008
3009 Nam lectus enim, dapibus non nisi tempor, consectetur convallis massa. Maecenas eleifend dictum \
3010 feugiat. Etiam quis mauris vel risus luctus mattis a a nunc. Nullam orci quam, imperdiet id \
3011 vehicula in, porttitor ut nibh. Duis sagittis adipiscing nisl vitae congue. Donec mollis risus eu \
3012 leo suscipit, varius porttitor nulla porta. Pellentesque ut sem nec nisi euismod vehicula. Nulla \
3013 malesuada sollicitudin quam eu fermentum.";
3014         let needle = "english";
3015
3016         b.iter(|| {
3017             assert!(!haystack.contains(needle));
3018         })
3019     }
3020
3021     #[bench]
3022     fn bench_contains_bad_naive(b: &mut Bencher) {
3023         let haystack = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
3024         let needle = "aaaaaaaab";
3025
3026         b.iter(|| {
3027             assert!(!haystack.contains(needle));
3028         })
3029     }
3030
3031     #[bench]
3032     fn bench_contains_equal(b: &mut Bencher) {
3033         let haystack = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
3034         let needle = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
3035
3036         b.iter(|| {
3037             assert!(haystack.contains(needle));
3038         })
3039     }
3040 }