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