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