]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
auto merge of #15999 : Kimundi/rust/fix_folder, r=nikomatsakis
[rust.git] / src / libcollections / string.rs
1 // Copyright 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 //! An owned, growable string that enforces that its contents are valid UTF-8.
14
15 use core::prelude::*;
16
17 use core::default::Default;
18 use core::fmt;
19 use core::mem;
20 use core::ptr;
21 use core::raw::Slice;
22
23 use {Collection, Mutable, MutableSeq};
24 use hash;
25 use str;
26 use str::{CharRange, StrAllocating, MaybeOwned, Owned, Slice};
27 use vec::Vec;
28
29 /// A growable string stored as a UTF-8 encoded buffer.
30 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)]
31 pub struct String {
32     vec: Vec<u8>,
33 }
34
35 impl String {
36     /// Creates a new string buffer initialized with the empty string.
37     ///
38     /// # Example
39     ///
40     /// ```
41     /// let mut s = String::new();
42     /// ```
43     #[inline]
44     pub fn new() -> String {
45         String {
46             vec: Vec::new(),
47         }
48     }
49
50     /// Creates a new string buffer with the given capacity.
51     /// The string will be able to hold exactly `capacity` bytes without
52     /// reallocating. If `capacity` is 0, the string will not allocate.
53     ///
54     /// # Example
55     ///
56     /// ```
57     /// let mut s = String::with_capacity(10);
58     /// ```
59     #[inline]
60     pub fn with_capacity(capacity: uint) -> String {
61         String {
62             vec: Vec::with_capacity(capacity),
63         }
64     }
65
66     /// Creates a new string buffer from the given string.
67     ///
68     /// # Example
69     ///
70     /// ```
71     /// let s = String::from_str("hello");
72     /// assert_eq!(s.as_slice(), "hello");
73     /// ```
74     #[inline]
75     pub fn from_str(string: &str) -> String {
76         String {
77             vec: Vec::from_slice(string.as_bytes())
78         }
79     }
80
81     /// Deprecated. Replaced by `string::raw::from_parts`
82     #[inline]
83     #[deprecated = "Replaced by string::raw::from_parts"]
84     pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
85         raw::from_parts(ptr, length, capacity)
86     }
87
88     /// Deprecated.
89     #[deprecated = "obsoleted by the removal of ~str"]
90     #[inline]
91     pub fn from_owned_str(string: String) -> String {
92         string
93     }
94
95     /// Returns the vector as a string buffer, if possible, taking care not to
96     /// copy it.
97     ///
98     /// Returns `Err` with the original vector if the vector contains invalid
99     /// UTF-8.
100     ///
101     /// # Example
102     ///
103     /// ```rust
104     /// let hello_vec = vec![104, 101, 108, 108, 111];
105     /// let s = String::from_utf8(hello_vec);
106     /// assert_eq!(s, Ok("hello".to_string()));
107     ///
108     /// let invalid_vec = vec![240, 144, 128];
109     /// let s = String::from_utf8(invalid_vec);
110     /// assert_eq!(s, Err(vec![240, 144, 128]));
111     /// ```
112     #[inline]
113     pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
114         if str::is_utf8(vec.as_slice()) {
115             Ok(String { vec: vec })
116         } else {
117             Err(vec)
118         }
119     }
120
121     /// Converts a vector of bytes to a new utf-8 string.
122     /// Any invalid utf-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
123     ///
124     /// # Example
125     ///
126     /// ```rust
127     /// let input = b"Hello \xF0\x90\x80World";
128     /// let output = String::from_utf8_lossy(input);
129     /// assert_eq!(output.as_slice(), "Hello \uFFFDWorld");
130     /// ```
131     pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> {
132         if str::is_utf8(v) {
133             return Slice(unsafe { mem::transmute(v) })
134         }
135
136         static TAG_CONT_U8: u8 = 128u8;
137         static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
138         let mut i = 0;
139         let total = v.len();
140         fn unsafe_get(xs: &[u8], i: uint) -> u8 {
141             unsafe { *xs.unsafe_ref(i) }
142         }
143         fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
144             if i >= total {
145                 0
146             } else {
147                 unsafe_get(xs, i)
148             }
149         }
150
151         let mut res = String::with_capacity(total);
152
153         if i > 0 {
154             unsafe {
155                 res.push_bytes(v.slice_to(i))
156             };
157         }
158
159         // subseqidx is the index of the first byte of the subsequence we're looking at.
160         // It's used to copy a bunch of contiguous good codepoints at once instead of copying
161         // them one by one.
162         let mut subseqidx = 0;
163
164         while i < total {
165             let i_ = i;
166             let byte = unsafe_get(v, i);
167             i += 1;
168
169             macro_rules! error(() => ({
170                 unsafe {
171                     if subseqidx != i_ {
172                         res.push_bytes(v.slice(subseqidx, i_));
173                     }
174                     subseqidx = i;
175                     res.push_bytes(REPLACEMENT);
176                 }
177             }))
178
179             if byte < 128u8 {
180                 // subseqidx handles this
181             } else {
182                 let w = str::utf8_char_width(byte);
183
184                 match w {
185                     2 => {
186                         if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
187                             error!();
188                             continue;
189                         }
190                         i += 1;
191                     }
192                     3 => {
193                         match (byte, safe_get(v, i, total)) {
194                             (0xE0        , 0xA0 .. 0xBF) => (),
195                             (0xE1 .. 0xEC, 0x80 .. 0xBF) => (),
196                             (0xED        , 0x80 .. 0x9F) => (),
197                             (0xEE .. 0xEF, 0x80 .. 0xBF) => (),
198                             _ => {
199                                 error!();
200                                 continue;
201                             }
202                         }
203                         i += 1;
204                         if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
205                             error!();
206                             continue;
207                         }
208                         i += 1;
209                     }
210                     4 => {
211                         match (byte, safe_get(v, i, total)) {
212                             (0xF0        , 0x90 .. 0xBF) => (),
213                             (0xF1 .. 0xF3, 0x80 .. 0xBF) => (),
214                             (0xF4        , 0x80 .. 0x8F) => (),
215                             _ => {
216                                 error!();
217                                 continue;
218                             }
219                         }
220                         i += 1;
221                         if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
222                             error!();
223                             continue;
224                         }
225                         i += 1;
226                         if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 {
227                             error!();
228                             continue;
229                         }
230                         i += 1;
231                     }
232                     _ => {
233                         error!();
234                         continue;
235                     }
236                 }
237             }
238         }
239         if subseqidx < total {
240             unsafe {
241                 res.push_bytes(v.slice(subseqidx, total))
242             };
243         }
244         Owned(res.into_string())
245     }
246
247     /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None`
248     /// if `v` contains any invalid data.
249     ///
250     /// # Example
251     ///
252     /// ```rust
253     /// // 𝄞music
254     /// let mut v = [0xD834, 0xDD1E, 0x006d, 0x0075,
255     ///              0x0073, 0x0069, 0x0063];
256     /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
257     ///
258     /// // 𝄞mu<invalid>ic
259     /// v[4] = 0xD800;
260     /// assert_eq!(String::from_utf16(v), None);
261     /// ```
262     pub fn from_utf16(v: &[u16]) -> Option<String> {
263         let mut s = String::with_capacity(v.len() / 2);
264         for c in str::utf16_items(v) {
265             match c {
266                 str::ScalarValue(c) => s.push_char(c),
267                 str::LoneSurrogate(_) => return None
268             }
269         }
270         Some(s)
271     }
272
273     /// Decode a UTF-16 encoded vector `v` into a string, replacing
274     /// invalid data with the replacement character (U+FFFD).
275     ///
276     /// # Example
277     /// ```rust
278     /// // 𝄞mus<invalid>ic<invalid>
279     /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
280     ///          0x0073, 0xDD1E, 0x0069, 0x0063,
281     ///          0xD834];
282     ///
283     /// assert_eq!(String::from_utf16_lossy(v),
284     ///            "𝄞mus\uFFFDic\uFFFD".to_string());
285     /// ```
286     pub fn from_utf16_lossy(v: &[u16]) -> String {
287         str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
288     }
289
290     /// Convert a vector of chars to a string.
291     ///
292     /// # Example
293     ///
294     /// ```rust
295     /// let chars = ['h', 'e', 'l', 'l', 'o'];
296     /// let s = String::from_chars(chars);
297     /// assert_eq!(s.as_slice(), "hello");
298     /// ```
299     #[inline]
300     pub fn from_chars(chs: &[char]) -> String {
301         chs.iter().map(|c| *c).collect()
302     }
303
304     /// Return the underlying byte buffer, encoded as UTF-8.
305     ///
306     /// # Example
307     ///
308     /// ```
309     /// let s = String::from_str("hello");
310     /// let bytes = s.into_bytes();
311     /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]);
312     /// ```
313     #[inline]
314     pub fn into_bytes(self) -> Vec<u8> {
315         self.vec
316     }
317
318     /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
319     /// again.
320     ///
321     /// # Example
322     ///
323     /// ```
324     /// let s = String::from_str("hello");
325     /// let big = s.append(" ").append("world").append("!");
326     /// // s has now been moved and cannot be used
327     ///
328     /// assert_eq!(big.as_slice(), "hello world!");
329     /// ```
330     #[inline]
331     pub fn append(mut self, second: &str) -> String {
332         self.push_str(second);
333         self
334     }
335
336     /// Creates a string buffer by repeating a character `length` times.
337     ///
338     /// # Example
339     ///
340     /// ```
341     /// let s = String::from_char(5, 'a');
342     /// assert_eq!(s.as_slice(), "aaaaa");
343     /// ```
344     #[inline]
345     pub fn from_char(length: uint, ch: char) -> String {
346         if length == 0 {
347             return String::new()
348         }
349
350         let mut buf = String::new();
351         buf.push_char(ch);
352         let size = buf.len() * length;
353         buf.reserve(size);
354         for _ in range(1, length) {
355             buf.push_char(ch)
356         }
357         buf
358     }
359
360     /// Convert a byte to a UTF-8 string.
361     ///
362     /// # Failure
363     ///
364     /// Fails if invalid UTF-8
365     ///
366     /// # Example
367     ///
368     /// ```rust
369     /// let s = String::from_byte(104);
370     /// assert_eq!(s.as_slice(), "h");
371     /// ```
372     pub fn from_byte(b: u8) -> String {
373         assert!(b < 128u8);
374         String::from_char(1, b as char)
375     }
376
377     /// Pushes the given string onto this string buffer.
378     ///
379     /// # Example
380     ///
381     /// ```
382     /// let mut s = String::from_str("foo");
383     /// s.push_str("bar");
384     /// assert_eq!(s.as_slice(), "foobar");
385     /// ```
386     #[inline]
387     pub fn push_str(&mut self, string: &str) {
388         self.vec.push_all(string.as_bytes())
389     }
390
391     /// Push `ch` onto the given string `count` times.
392     ///
393     /// # Example
394     ///
395     /// ```
396     /// let mut s = String::from_str("foo");
397     /// s.grow(5, 'Z');
398     /// assert_eq!(s.as_slice(), "fooZZZZZ");
399     /// ```
400     #[inline]
401     pub fn grow(&mut self, count: uint, ch: char) {
402         for _ in range(0, count) {
403             self.push_char(ch)
404         }
405     }
406
407     /// Returns the number of bytes that this string buffer can hold without reallocating.
408     ///
409     /// # Example
410     ///
411     /// ```
412     /// let s = String::with_capacity(10);
413     /// assert!(s.byte_capacity() >= 10);
414     /// ```
415     #[inline]
416     pub fn byte_capacity(&self) -> uint {
417         self.vec.capacity()
418     }
419
420     /// Reserves capacity for at least `extra` additional bytes in this string buffer.
421     ///
422     /// # Example
423     ///
424     /// ```
425     /// let mut s = String::with_capacity(10);
426     /// let before = s.byte_capacity();
427     /// s.reserve_additional(100);
428     /// assert!(s.byte_capacity() - before >= 100);
429     /// ```
430     #[inline]
431     pub fn reserve_additional(&mut self, extra: uint) {
432         self.vec.reserve_additional(extra)
433     }
434
435     /// Reserves capacity for at least `capacity` bytes in this string buffer.
436     ///
437     /// # Example
438     ///
439     /// ```
440     /// let mut s = String::new();
441     /// s.reserve(10);
442     /// assert!(s.byte_capacity() >= 10);
443     /// ```
444     #[inline]
445     pub fn reserve(&mut self, capacity: uint) {
446         self.vec.reserve(capacity)
447     }
448
449     /// Reserves capacity for exactly `capacity` bytes in this string buffer.
450     ///
451     /// # Example
452     ///
453     /// ```
454     /// let mut s = String::new();
455     /// s.reserve_exact(10);
456     /// assert_eq!(s.byte_capacity(), 10);
457     /// ```
458     #[inline]
459     pub fn reserve_exact(&mut self, capacity: uint) {
460         self.vec.reserve_exact(capacity)
461     }
462
463     /// Shrinks the capacity of this string buffer to match its length.
464     ///
465     /// # Example
466     ///
467     /// ```
468     /// let mut s = String::from_str("foo");
469     /// s.reserve(100);
470     /// assert!(s.byte_capacity() >= 100);
471     /// s.shrink_to_fit();
472     /// assert_eq!(s.byte_capacity(), 3);
473     /// ```
474     #[inline]
475     pub fn shrink_to_fit(&mut self) {
476         self.vec.shrink_to_fit()
477     }
478
479     /// Adds the given character to the end of the string.
480     ///
481     /// # Example
482     ///
483     /// ```
484     /// let mut s = String::from_str("abc");
485     /// s.push_char('1');
486     /// s.push_char('2');
487     /// s.push_char('3');
488     /// assert_eq!(s.as_slice(), "abc123");
489     /// ```
490     #[inline]
491     pub fn push_char(&mut self, ch: char) {
492         let cur_len = self.len();
493         // This may use up to 4 bytes.
494         self.vec.reserve_additional(4);
495
496         unsafe {
497             // Attempt to not use an intermediate buffer by just pushing bytes
498             // directly onto this string.
499             let slice = Slice {
500                 data: self.vec.as_ptr().offset(cur_len as int),
501                 len: 4,
502             };
503             let used = ch.encode_utf8(mem::transmute(slice));
504             self.vec.set_len(cur_len + used);
505         }
506     }
507
508     /// Pushes the given bytes onto this string buffer.
509     /// This is unsafe because it does not check
510     /// to ensure that the resulting string will be valid UTF-8.
511     ///
512     /// # Example
513     ///
514     /// ```
515     /// let mut s = String::new();
516     /// unsafe {
517     ///     s.push_bytes([104, 101, 108, 108, 111]);
518     /// }
519     /// assert_eq!(s.as_slice(), "hello");
520     /// ```
521     #[inline]
522     pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
523         self.vec.push_all(bytes)
524     }
525
526     /// Works with the underlying buffer as a byte slice.
527     ///
528     /// # Example
529     ///
530     /// ```
531     /// let s = String::from_str("hello");
532     /// assert_eq!(s.as_bytes(), &[104, 101, 108, 108, 111]);
533     /// ```
534     #[inline]
535     pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
536         self.vec.as_slice()
537     }
538
539     /// Works with the underlying buffer as a mutable byte slice.
540     ///
541     /// This is unsafe because it does not check
542     /// to ensure that the resulting string will be valid UTF-8.
543     ///
544     /// # Example
545     ///
546     /// ```
547     /// let mut s = String::from_str("hello");
548     /// unsafe {
549     ///     let bytes = s.as_mut_bytes();
550     ///     bytes[1] = 51;
551     ///     bytes[4] = 48;
552     /// }
553     /// assert_eq!(s.as_bytes(), &[104, 51, 108, 108, 48]);
554     /// assert_eq!(s.as_slice(), "h3ll0")
555     /// ```
556     #[inline]
557     pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
558         self.vec.as_mut_slice()
559     }
560
561     /// Shorten a string to the specified length.
562     ///
563     /// # Failure
564     ///
565     /// Fails if `len` > current length.
566     ///
567     /// # Example
568     ///
569     /// ```
570     /// let mut s = String::from_str("hello");
571     /// s.truncate(2);
572     /// assert_eq!(s.as_slice(), "he");
573     /// ```
574     #[inline]
575     pub fn truncate(&mut self, len: uint) {
576         assert!(self.as_slice().is_char_boundary(len));
577         self.vec.truncate(len)
578     }
579
580     /// Appends a byte to this string buffer.
581     ///
582     /// This is unsafe because it does not check
583     /// to ensure that the resulting string will be valid UTF-8.
584     ///
585     /// # Example
586     ///
587     /// ```
588     /// let mut s = String::from_str("hell");
589     /// unsafe {
590     ///     s.push_byte(111);
591     /// }
592     /// assert_eq!(s.as_slice(), "hello");
593     /// ```
594     #[inline]
595     pub unsafe fn push_byte(&mut self, byte: u8) {
596         self.vec.push(byte)
597     }
598
599     /// Removes the last byte from the string buffer and returns it.
600     /// Returns `None` if this string buffer is empty.
601     ///
602     /// This is unsafe because it does not check
603     /// to ensure that the resulting string will be valid UTF-8.
604     ///
605     /// # Example
606     ///
607     /// ```
608     /// let mut s = String::from_str("foo");
609     /// unsafe {
610     ///     assert_eq!(s.pop_byte(), Some(111));
611     ///     assert_eq!(s.pop_byte(), Some(111));
612     ///     assert_eq!(s.pop_byte(), Some(102));
613     ///     assert_eq!(s.pop_byte(), None);
614     /// }
615     /// ```
616     #[inline]
617     pub unsafe fn pop_byte(&mut self) -> Option<u8> {
618         let len = self.len();
619         if len == 0 {
620             return None
621         }
622
623         let byte = self.as_bytes()[len - 1];
624         self.vec.set_len(len - 1);
625         Some(byte)
626     }
627
628     /// Removes the last character from the string buffer and returns it.
629     /// Returns `None` if this string buffer is empty.
630     ///
631     /// # Example
632     ///
633     /// ```
634     /// let mut s = String::from_str("foo");
635     /// assert_eq!(s.pop_char(), Some('o'));
636     /// assert_eq!(s.pop_char(), Some('o'));
637     /// assert_eq!(s.pop_char(), Some('f'));
638     /// assert_eq!(s.pop_char(), None);
639     /// ```
640     #[inline]
641     pub fn pop_char(&mut self) -> Option<char> {
642         let len = self.len();
643         if len == 0 {
644             return None
645         }
646
647         let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
648         unsafe {
649             self.vec.set_len(next);
650         }
651         Some(ch)
652     }
653
654     /// Removes the first byte from the string buffer and returns it.
655     /// Returns `None` if this string buffer is empty.
656     ///
657     /// This is unsafe because it does not check
658     /// to ensure that the resulting string will be valid UTF-8.
659     ///
660     /// # Example
661     ///
662     /// ```
663     /// let mut s = String::from_str("foo");
664     /// unsafe {
665     ///     assert_eq!(s.shift_byte(), Some(102));
666     ///     assert_eq!(s.shift_byte(), Some(111));
667     ///     assert_eq!(s.shift_byte(), Some(111));
668     ///     assert_eq!(s.shift_byte(), None);
669     /// }
670     /// ```
671     pub unsafe fn shift_byte(&mut self) -> Option<u8> {
672         self.vec.shift()
673     }
674
675     /// Removes the first character from the string buffer and returns it.
676     /// Returns `None` if this string buffer is empty.
677     ///
678     /// # Warning
679     ///
680     /// This is a O(n) operation as it requires copying every element in the buffer.
681     ///
682     /// # Example
683     ///
684     /// ```
685     /// let mut s = String::from_str("foo");
686     /// assert_eq!(s.shift_char(), Some('f'));
687     /// assert_eq!(s.shift_char(), Some('o'));
688     /// assert_eq!(s.shift_char(), Some('o'));
689     /// assert_eq!(s.shift_char(), None);
690     /// ```
691     pub fn shift_char(&mut self) -> Option<char> {
692         let len = self.len();
693         if len == 0 {
694             return None
695         }
696
697         let CharRange {ch, next} = self.as_slice().char_range_at(0);
698         let new_len = len - next;
699         unsafe {
700             ptr::copy_memory(self.vec.as_mut_ptr(), self.vec.as_ptr().offset(next as int), new_len);
701             self.vec.set_len(new_len);
702         }
703         Some(ch)
704     }
705
706     /// Views the string buffer as a mutable sequence of bytes.
707     ///
708     /// This is unsafe because it does not check
709     /// to ensure that the resulting string will be valid UTF-8.
710     ///
711     /// # Example
712     ///
713     /// ```
714     /// let mut s = String::from_str("hello");
715     /// unsafe {
716     ///     let vec = s.as_mut_vec();
717     ///     assert!(vec == &mut vec![104, 101, 108, 108, 111]);
718     ///     vec.reverse();
719     /// }
720     /// assert_eq!(s.as_slice(), "olleh");
721     /// ```
722     pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
723         &mut self.vec
724     }
725 }
726
727 impl Collection for String {
728     #[inline]
729     fn len(&self) -> uint {
730         self.vec.len()
731     }
732 }
733
734 impl Mutable for String {
735     #[inline]
736     fn clear(&mut self) {
737         self.vec.clear()
738     }
739 }
740
741 impl FromIterator<char> for String {
742     fn from_iter<I:Iterator<char>>(iterator: I) -> String {
743         let mut buf = String::new();
744         buf.extend(iterator);
745         buf
746     }
747 }
748
749 impl Extendable<char> for String {
750     fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
751         for ch in iterator {
752             self.push_char(ch)
753         }
754     }
755 }
756
757 impl Str for String {
758     #[inline]
759     fn as_slice<'a>(&'a self) -> &'a str {
760         unsafe {
761             mem::transmute(self.vec.as_slice())
762         }
763     }
764 }
765
766 impl StrAllocating for String {
767     #[inline]
768     fn into_string(self) -> String {
769         self
770     }
771 }
772
773 impl Default for String {
774     fn default() -> String {
775         String::new()
776     }
777 }
778
779 impl fmt::Show for String {
780     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
781         self.as_slice().fmt(f)
782     }
783 }
784
785 impl<H: hash::Writer> hash::Hash<H> for String {
786     #[inline]
787     fn hash(&self, hasher: &mut H) {
788         self.as_slice().hash(hasher)
789     }
790 }
791
792 impl<'a, S: Str> Equiv<S> for String {
793     #[inline]
794     fn equiv(&self, other: &S) -> bool {
795         self.as_slice() == other.as_slice()
796     }
797 }
798
799 impl<S: Str> Add<S, String> for String {
800     fn add(&self, other: &S) -> String {
801         let mut s = String::from_str(self.as_slice());
802         s.push_str(other.as_slice());
803         return s;
804     }
805 }
806
807 /// Unsafe operations
808 pub mod raw {
809     use core::mem;
810     use core::ptr::RawPtr;
811     use core::raw::Slice;
812
813     use super::String;
814     use vec::Vec;
815
816     /// Creates a new `String` from length, capacity, and a pointer.
817     ///
818     /// This is unsafe because:
819     /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`
820     /// * We assume that the `Vec` contains valid UTF-8
821     #[inline]
822     pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
823         String {
824             vec: Vec::from_raw_parts(length, capacity, buf),
825         }
826     }
827
828     /// Create `String` from a *u8 buffer of the given length
829     ///
830     /// This function is unsafe because of two reasons:
831     /// * A raw pointer is dereferenced and transmuted to `&[u8]`
832     /// * The slice is not checked to see whether it contains valid UTF-8
833     pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
834         use slice::CloneableVector;
835         let slice: &[u8] = mem::transmute(Slice {
836             data: buf,
837             len: len,
838         });
839         self::from_utf8(slice.to_vec())
840     }
841
842     /// Create a `String` from a null-terminated *u8 buffer
843     ///
844     /// This function is unsafe because we dereference memory until we find the NUL character,
845     /// which is not guaranteed to be present. Additionaly, the slice is not checked to see
846     /// whether it contains valid UTF-8
847     pub unsafe fn from_buf(buf: *const u8) -> String {
848         let mut len = 0;
849         while *buf.offset(len) != 0 {
850             len += 1;
851         }
852         self::from_buf_len(buf, len as uint)
853     }
854
855     /// Converts a vector of bytes to a new `String` without checking if
856     /// it contains valid UTF-8. This is unsafe because it assumes that
857     /// the utf-8-ness of the vector has already been validated.
858     #[inline]
859     pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
860         String { vec: bytes }
861     }
862 }
863
864 #[cfg(test)]
865 mod tests {
866     use std::prelude::*;
867     use test::Bencher;
868
869     use {Mutable, MutableSeq};
870     use str;
871     use str::{Str, StrSlice, Owned, Slice};
872     use super::String;
873     use vec::Vec;
874
875     #[test]
876     fn test_from_str() {
877       let owned: Option<::std::string::String> = from_str("string");
878       assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
879     }
880
881     #[test]
882     fn test_from_utf8() {
883         let xs = Vec::from_slice(b"hello");
884         assert_eq!(String::from_utf8(xs), Ok(String::from_str("hello")));
885
886         let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
887         assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
888
889         let xs = Vec::from_slice(b"hello\xFF");
890         assert_eq!(String::from_utf8(xs),
891                    Err(Vec::from_slice(b"hello\xFF")));
892     }
893
894     #[test]
895     fn test_from_utf8_lossy() {
896         let xs = b"hello";
897         assert_eq!(String::from_utf8_lossy(xs), Slice("hello"));
898
899         let xs = "ศไทย中华Việt Nam".as_bytes();
900         assert_eq!(String::from_utf8_lossy(xs), Slice("ศไทย中华Việt Nam"));
901
902         let xs = b"Hello\xC2 There\xFF Goodbye";
903         assert_eq!(String::from_utf8_lossy(xs),
904                    Owned(String::from_str("Hello\uFFFD There\uFFFD Goodbye")));
905
906         let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
907         assert_eq!(String::from_utf8_lossy(xs),
908                    Owned(String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye")));
909
910         let xs = b"\xF5foo\xF5\x80bar";
911         assert_eq!(String::from_utf8_lossy(xs),
912                    Owned(String::from_str("\uFFFDfoo\uFFFD\uFFFDbar")));
913
914         let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
915         assert_eq!(String::from_utf8_lossy(xs),
916                    Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz")));
917
918         let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
919         assert_eq!(String::from_utf8_lossy(xs),
920                    Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz")));
921
922         let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
923         assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\
924                                                foo\U00010000bar")));
925
926         // surrogates
927         let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
928         assert_eq!(String::from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFDfoo\
929                                                \uFFFD\uFFFD\uFFFDbar")));
930     }
931
932     #[test]
933     fn test_from_utf16() {
934         let pairs =
935             [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
936               vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
937                 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
938                 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
939                 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
940
941              (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
942               vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
943                 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
944                 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
945                 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
946                 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
947                 0x000a_u16]),
948
949              (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
950               vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
951                 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
952                 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
953                 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
954                 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
955                 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
956                 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
957
958              (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
959               vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
960                 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
961                 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
962                 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
963                 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
964                 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
965                 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
966                 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
967                 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
968                 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
969                 0x000a_u16 ]),
970              // Issue #12318, even-numbered non-BMP planes
971              (String::from_str("\U00020000"),
972               vec![0xD840, 0xDC00])];
973
974         for p in pairs.iter() {
975             let (s, u) = (*p).clone();
976             let s_as_utf16 = s.as_slice().utf16_units().collect::<Vec<u16>>();
977             let u_as_string = String::from_utf16(u.as_slice()).unwrap();
978
979             assert!(str::is_utf16(u.as_slice()));
980             assert_eq!(s_as_utf16, u);
981
982             assert_eq!(u_as_string, s);
983             assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
984
985             assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
986             assert_eq!(u_as_string.as_slice().utf16_units().collect::<Vec<u16>>(), u);
987         }
988     }
989
990     #[test]
991     fn test_utf16_invalid() {
992         // completely positive cases tested above.
993         // lead + eof
994         assert_eq!(String::from_utf16([0xD800]), None);
995         // lead + lead
996         assert_eq!(String::from_utf16([0xD800, 0xD800]), None);
997
998         // isolated trail
999         assert_eq!(String::from_utf16([0x0061, 0xDC00]), None);
1000
1001         // general
1002         assert_eq!(String::from_utf16([0xD800, 0xd801, 0xdc8b, 0xD800]), None);
1003     }
1004
1005     #[test]
1006     fn test_from_utf16_lossy() {
1007         // completely positive cases tested above.
1008         // lead + eof
1009         assert_eq!(String::from_utf16_lossy([0xD800]), String::from_str("\uFFFD"));
1010         // lead + lead
1011         assert_eq!(String::from_utf16_lossy([0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD"));
1012
1013         // isolated trail
1014         assert_eq!(String::from_utf16_lossy([0x0061, 0xDC00]), String::from_str("a\uFFFD"));
1015
1016         // general
1017         assert_eq!(String::from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]),
1018                    String::from_str("\uFFFD𐒋\uFFFD"));
1019     }
1020
1021     #[test]
1022     fn test_from_buf_len() {
1023         unsafe {
1024             let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
1025             assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
1026         }
1027     }
1028
1029     #[test]
1030     fn test_from_buf() {
1031         unsafe {
1032             let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
1033             let b = a.as_ptr();
1034             let c = super::raw::from_buf(b);
1035             assert_eq!(c, String::from_str("AAAAAAA"));
1036         }
1037     }
1038
1039     #[test]
1040     fn test_push_bytes() {
1041         let mut s = String::from_str("ABC");
1042         unsafe {
1043             s.push_bytes([ 'D' as u8 ]);
1044         }
1045         assert_eq!(s.as_slice(), "ABCD");
1046     }
1047
1048     #[test]
1049     fn test_push_str() {
1050         let mut s = String::new();
1051         s.push_str("");
1052         assert_eq!(s.as_slice().slice_from(0), "");
1053         s.push_str("abc");
1054         assert_eq!(s.as_slice().slice_from(0), "abc");
1055         s.push_str("ประเทศไทย中华Việt Nam");
1056         assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
1057     }
1058
1059     #[test]
1060     fn test_push_char() {
1061         let mut data = String::from_str("ประเทศไทย中");
1062         data.push_char('华');
1063         data.push_char('b'); // 1 byte
1064         data.push_char('¢'); // 2 byte
1065         data.push_char('€'); // 3 byte
1066         data.push_char('𤭢'); // 4 byte
1067         assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
1068     }
1069
1070     #[test]
1071     fn test_pop_char() {
1072         let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1073         assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
1074         assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
1075         assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
1076         assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
1077         assert_eq!(data.pop_char().unwrap(), '华');
1078         assert_eq!(data.as_slice(), "ประเทศไทย中");
1079     }
1080
1081     #[test]
1082     fn test_shift_char() {
1083         let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
1084         assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
1085         assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
1086         assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
1087         assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
1088         assert_eq!(data.shift_char().unwrap(), '华');
1089         assert_eq!(data.as_slice(), "ประเทศไทย中");
1090     }
1091
1092     #[test]
1093     fn test_str_truncate() {
1094         let mut s = String::from_str("12345");
1095         s.truncate(5);
1096         assert_eq!(s.as_slice(), "12345");
1097         s.truncate(3);
1098         assert_eq!(s.as_slice(), "123");
1099         s.truncate(0);
1100         assert_eq!(s.as_slice(), "");
1101
1102         let mut s = String::from_str("12345");
1103         let p = s.as_slice().as_ptr();
1104         s.truncate(3);
1105         s.push_str("6");
1106         let p_ = s.as_slice().as_ptr();
1107         assert_eq!(p_, p);
1108     }
1109
1110     #[test]
1111     #[should_fail]
1112     fn test_str_truncate_invalid_len() {
1113         let mut s = String::from_str("12345");
1114         s.truncate(6);
1115     }
1116
1117     #[test]
1118     #[should_fail]
1119     fn test_str_truncate_split_codepoint() {
1120         let mut s = String::from_str("\u00FC"); // ü
1121         s.truncate(1);
1122     }
1123
1124     #[test]
1125     fn test_str_clear() {
1126         let mut s = String::from_str("12345");
1127         s.clear();
1128         assert_eq!(s.len(), 0);
1129         assert_eq!(s.as_slice(), "");
1130     }
1131
1132     #[test]
1133     fn test_str_add() {
1134         let a = String::from_str("12345");
1135         let b = a + "2";
1136         let b = b + String::from_str("2");
1137         assert_eq!(b.len(), 7);
1138         assert_eq!(b.as_slice(), "1234522");
1139     }
1140
1141     #[bench]
1142     fn bench_with_capacity(b: &mut Bencher) {
1143         b.iter(|| {
1144             String::with_capacity(100)
1145         });
1146     }
1147
1148     #[bench]
1149     fn bench_push_str(b: &mut Bencher) {
1150         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1151         b.iter(|| {
1152             let mut r = String::new();
1153             r.push_str(s);
1154         });
1155     }
1156
1157     #[bench]
1158     fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1159         let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1160                   Lorem ipsum dolor sit amet, consectetur. ";
1161
1162         assert_eq!(100, s.len());
1163         b.iter(|| {
1164             let _ = String::from_utf8_lossy(s);
1165         });
1166     }
1167
1168     #[bench]
1169     fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1170         let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1171         assert_eq!(100, s.len());
1172         b.iter(|| {
1173             let _ = String::from_utf8_lossy(s);
1174         });
1175     }
1176
1177     #[bench]
1178     fn from_utf8_lossy_invalid(b: &mut Bencher) {
1179         let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1180         b.iter(|| {
1181             let _ = String::from_utf8_lossy(s);
1182         });
1183     }
1184
1185     #[bench]
1186     fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1187         let s = Vec::from_elem(100, 0xF5u8);
1188         b.iter(|| {
1189             let _ = String::from_utf8_lossy(s.as_slice());
1190         });
1191     }
1192 }