]> git.lizzy.rs Git - rust.git/blob - src/libcollections/string.rs
rollup merge of #19587: huonw/closure-feature-gate
[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, 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.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.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.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.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 impl PartialEq for String {
742     #[inline]
743     fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) }
744     #[inline]
745     fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) }
746 }
747
748 macro_rules! impl_eq {
749     ($lhs:ty, $rhs: ty) => {
750         impl<'a> PartialEq<$rhs> for $lhs {
751             #[inline]
752             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
753             #[inline]
754             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
755         }
756
757         impl<'a> PartialEq<$lhs> for $rhs {
758             #[inline]
759             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
760             #[inline]
761             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
762         }
763
764     }
765 }
766
767 impl_eq!(String, &'a str)
768 impl_eq!(CowString<'a>, String)
769
770 impl<'a, 'b> PartialEq<&'b str> for CowString<'a> {
771     #[inline]
772     fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) }
773     #[inline]
774     fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) }
775 }
776
777 impl<'a, 'b> PartialEq<CowString<'a>> for &'b str {
778     #[inline]
779     fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) }
780     #[inline]
781     fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) }
782 }
783
784 #[experimental = "waiting on Str stabilization"]
785 impl Str for String {
786     #[inline]
787     #[stable]
788     fn as_slice<'a>(&'a self) -> &'a str {
789         unsafe {
790             mem::transmute(self.vec.as_slice())
791         }
792     }
793 }
794
795 #[experimental = "waiting on StrAllocating stabilization"]
796 impl StrAllocating for String {
797     #[inline]
798     fn into_string(self) -> String {
799         self
800     }
801 }
802
803 #[stable]
804 impl Default for String {
805     fn default() -> String {
806         String::new()
807     }
808 }
809
810 #[experimental = "waiting on Show stabilization"]
811 impl fmt::Show for String {
812     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
813         self.as_slice().fmt(f)
814     }
815 }
816
817 #[experimental = "waiting on Hash stabilization"]
818 impl<H: hash::Writer> hash::Hash<H> for String {
819     #[inline]
820     fn hash(&self, hasher: &mut H) {
821         self.as_slice().hash(hasher)
822     }
823 }
824
825 #[allow(deprecated)]
826 #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
827 impl<'a, S: Str> Equiv<S> for String {
828     #[inline]
829     fn equiv(&self, other: &S) -> bool {
830         self.as_slice() == other.as_slice()
831     }
832 }
833
834 #[experimental = "waiting on Add stabilization"]
835 impl<S: Str> Add<S, String> for String {
836     fn add(&self, other: &S) -> String {
837         let mut s = String::from_str(self.as_slice());
838         s.push_str(other.as_slice());
839         return s;
840     }
841 }
842
843 impl ops::Slice<uint, str> for String {
844     #[inline]
845     fn as_slice_<'a>(&'a self) -> &'a str {
846         self.as_slice()
847     }
848
849     #[inline]
850     fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str {
851         self[][*from..]
852     }
853
854     #[inline]
855     fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str {
856         self[][..*to]
857     }
858
859     #[inline]
860     fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str {
861         self[][*from..*to]
862     }
863 }
864
865 #[experimental = "waiting on Deref stabilization"]
866 impl ops::Deref<str> for String {
867     fn deref<'a>(&'a self) -> &'a str { self.as_slice() }
868 }
869
870 /// Wrapper type providing a `&String` reference via `Deref`.
871 #[experimental]
872 pub struct DerefString<'a> {
873     x: DerefVec<'a, u8>
874 }
875
876 impl<'a> Deref<String> for DerefString<'a> {
877     fn deref<'b>(&'b self) -> &'b String {
878         unsafe { mem::transmute(&*self.x) }
879     }
880 }
881
882 /// Convert a string slice to a wrapper type providing a `&String` reference.
883 #[experimental]
884 pub fn as_string<'a>(x: &'a str) -> DerefString<'a> {
885     DerefString { x: as_vec(x.as_bytes()) }
886 }
887
888 impl FromStr for String {
889     #[inline]
890     fn from_str(s: &str) -> Option<String> {
891         Some(String::from_str(s))
892     }
893 }
894
895 /// Trait for converting a type to a string, consuming it in the process.
896 pub trait IntoString {
897     /// Consume and convert to a string.
898     fn into_string(self) -> String;
899 }
900
901 /// A generic trait for converting a value to a string
902 pub trait ToString {
903     /// Converts the value of `self` to an owned string
904     fn to_string(&self) -> String;
905 }
906
907 impl<T: fmt::Show> ToString for T {
908     fn to_string(&self) -> String {
909         let mut buf = Vec::<u8>::new();
910         let _ = format_args!(|args| fmt::write(&mut buf, args), "{}", self);
911         String::from_utf8(buf).unwrap()
912     }
913 }
914
915 impl IntoCow<'static, String, str> for String {
916     fn into_cow(self) -> CowString<'static> {
917         Cow::Owned(self)
918     }
919 }
920
921 impl<'a> IntoCow<'a, String, str> for &'a str {
922     fn into_cow(self) -> CowString<'a> {
923         Cow::Borrowed(self)
924     }
925 }
926
927 /// Unsafe operations
928 #[deprecated]
929 pub mod raw {
930     use super::String;
931     use vec::Vec;
932
933     /// Creates a new `String` from a length, capacity, and pointer.
934     ///
935     /// This is unsafe because:
936     /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
937     /// * We assume that the `Vec` contains valid UTF-8.
938     #[inline]
939     #[deprecated = "renamed to String::from_raw_parts"]
940     pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
941         String::from_raw_parts(buf, length, capacity)
942     }
943
944     /// Creates a `String` from a `*const u8` buffer of the given length.
945     ///
946     /// This function is unsafe because of two reasons:
947     ///
948     /// * A raw pointer is dereferenced and transmuted to `&[u8]`;
949     /// * The slice is not checked to see whether it contains valid UTF-8.
950     #[deprecated = "renamed to String::from_raw_buf_len"]
951     pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
952         String::from_raw_buf_len(buf, len)
953     }
954
955     /// Creates a `String` from a null-terminated `*const u8` buffer.
956     ///
957     /// This function is unsafe because we dereference memory until we find the NUL character,
958     /// which is not guaranteed to be present. Additionally, the slice is not checked to see
959     /// whether it contains valid UTF-8
960     #[deprecated = "renamed to String::from_raw_buf"]
961     pub unsafe fn from_buf(buf: *const u8) -> String {
962         String::from_raw_buf(buf)
963     }
964
965     /// Converts a vector of bytes to a new `String` without checking if
966     /// it contains valid UTF-8. This is unsafe because it assumes that
967     /// the UTF-8-ness of the vector has already been validated.
968     #[inline]
969     #[deprecated = "renamed to String::from_utf8_unchecked"]
970     pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
971         String::from_utf8_unchecked(bytes)
972     }
973 }
974
975 #[cfg(test)]
976 mod tests {
977     use std::prelude::*;
978     use test::Bencher;
979
980     use slice::CloneSliceAllocPrelude;
981     use str::{Str, StrPrelude};
982     use str;
983     use super::{as_string, String, ToString};
984     use vec::Vec;
985
986     #[test]
987     fn test_as_string() {
988         let x = "foo";
989         assert_eq!(x, as_string(x).as_slice());
990     }
991
992     #[test]
993     fn test_from_str() {
994       let owned: Option<::std::string::String> = from_str("string");
995       assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
996     }
997
998     #[test]
999     fn test_from_utf8() {
1000         let xs = b"hello".to_vec();
1001         assert_eq!(String::from_utf8(xs), Ok(String::from_str("hello")));
1002
1003         let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
1004         assert_eq!(String::from_utf8(xs), Ok(String::from_str("ศไทย中华Việt Nam")));
1005
1006         let xs = b"hello\xFF".to_vec();
1007         assert_eq!(String::from_utf8(xs),
1008                    Err(b"hello\xFF".to_vec()));
1009     }
1010
1011     #[test]
1012     fn test_from_utf8_lossy() {
1013         let xs = b"hello";
1014         let ys: str::CowString = "hello".into_cow();
1015         assert_eq!(String::from_utf8_lossy(xs), ys);
1016
1017         let xs = "ศไทย中华Việt Nam".as_bytes();
1018         let ys: str::CowString = "ศไทย中华Việt Nam".into_cow();
1019         assert_eq!(String::from_utf8_lossy(xs), ys);
1020
1021         let xs = b"Hello\xC2 There\xFF Goodbye";
1022         assert_eq!(String::from_utf8_lossy(xs),
1023                    String::from_str("Hello\uFFFD There\uFFFD Goodbye").into_cow());
1024
1025         let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1026         assert_eq!(String::from_utf8_lossy(xs),
1027                    String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye").into_cow());
1028
1029         let xs = b"\xF5foo\xF5\x80bar";
1030         assert_eq!(String::from_utf8_lossy(xs),
1031                    String::from_str("\uFFFDfoo\uFFFD\uFFFDbar").into_cow());
1032
1033         let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
1034         assert_eq!(String::from_utf8_lossy(xs),
1035                    String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz").into_cow());
1036
1037         let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
1038         assert_eq!(String::from_utf8_lossy(xs),
1039                    String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz").into_cow());
1040
1041         let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
1042         assert_eq!(String::from_utf8_lossy(xs), String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\
1043                                                foo\U00010000bar").into_cow());
1044
1045         // surrogates
1046         let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
1047         assert_eq!(String::from_utf8_lossy(xs), String::from_str("\uFFFD\uFFFD\uFFFDfoo\
1048                                                \uFFFD\uFFFD\uFFFDbar").into_cow());
1049     }
1050
1051     #[test]
1052     fn test_from_utf16() {
1053         let pairs =
1054             [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"),
1055               vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16,
1056                 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16,
1057                 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16,
1058                 0xd800_u16, 0xdf30_u16, 0x000a_u16]),
1059
1060              (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"),
1061               vec![0xd801_u16, 0xdc12_u16, 0xd801_u16,
1062                 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16,
1063                 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16,
1064                 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16,
1065                 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16,
1066                 0x000a_u16]),
1067
1068              (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"),
1069               vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16,
1070                 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16,
1071                 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16,
1072                 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16,
1073                 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16,
1074                 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16,
1075                 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]),
1076
1077              (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"),
1078               vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16,
1079                 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16,
1080                 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16,
1081                 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16,
1082                 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16,
1083                 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16,
1084                 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16,
1085                 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16,
1086                 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16,
1087                 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16,
1088                 0x000a_u16 ]),
1089              // Issue #12318, even-numbered non-BMP planes
1090              (String::from_str("\U00020000"),
1091               vec![0xD840, 0xDC00])];
1092
1093         for p in pairs.iter() {
1094             let (s, u) = (*p).clone();
1095             let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>();
1096             let u_as_string = String::from_utf16(u.as_slice()).unwrap();
1097
1098             assert!(str::is_utf16(u.as_slice()));
1099             assert_eq!(s_as_utf16, u);
1100
1101             assert_eq!(u_as_string, s);
1102             assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
1103
1104             assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
1105             assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u);
1106         }
1107     }
1108
1109     #[test]
1110     fn test_utf16_invalid() {
1111         // completely positive cases tested above.
1112         // lead + eof
1113         assert_eq!(String::from_utf16(&[0xD800]), None);
1114         // lead + lead
1115         assert_eq!(String::from_utf16(&[0xD800, 0xD800]), None);
1116
1117         // isolated trail
1118         assert_eq!(String::from_utf16(&[0x0061, 0xDC00]), None);
1119
1120         // general
1121         assert_eq!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]), None);
1122     }
1123
1124     #[test]
1125     fn test_from_utf16_lossy() {
1126         // completely positive cases tested above.
1127         // lead + eof
1128         assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\uFFFD"));
1129         // lead + lead
1130         assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD"));
1131
1132         // isolated trail
1133         assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\uFFFD"));
1134
1135         // general
1136         assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]),
1137                    String::from_str("\uFFFD𐒋\uFFFD"));
1138     }
1139
1140     #[test]
1141     fn test_from_buf_len() {
1142         unsafe {
1143             let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
1144             assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
1145         }
1146     }
1147
1148     #[test]
1149     fn test_from_buf() {
1150         unsafe {
1151             let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
1152             let b = a.as_ptr();
1153             let c = super::raw::from_buf(b);
1154             assert_eq!(c, String::from_str("AAAAAAA"));
1155         }
1156     }
1157
1158     #[test]
1159     fn test_push_bytes() {
1160         let mut s = String::from_str("ABC");
1161         unsafe {
1162             let mv = s.as_mut_vec();
1163             mv.push_all(&[b'D']);
1164         }
1165         assert_eq!(s, "ABCD");
1166     }
1167
1168     #[test]
1169     fn test_push_str() {
1170         let mut s = String::new();
1171         s.push_str("");
1172         assert_eq!(s.slice_from(0), "");
1173         s.push_str("abc");
1174         assert_eq!(s.slice_from(0), "abc");
1175         s.push_str("ประเทศไทย中华Việt Nam");
1176         assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam");
1177     }
1178
1179     #[test]
1180     fn test_push() {
1181         let mut data = String::from_str("ประเทศไทย中");
1182         data.push('华');
1183         data.push('b'); // 1 byte
1184         data.push('¢'); // 2 byte
1185         data.push('€'); // 3 byte
1186         data.push('𤭢'); // 4 byte
1187         assert_eq!(data, "ประเทศไทย中华b¢€𤭢");
1188     }
1189
1190     #[test]
1191     fn test_pop() {
1192         let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
1193         assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes
1194         assert_eq!(data.pop().unwrap(), '€'); // 3 bytes
1195         assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes
1196         assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes
1197         assert_eq!(data.pop().unwrap(), '华');
1198         assert_eq!(data, "ประเทศไทย中");
1199     }
1200
1201     #[test]
1202     fn test_str_truncate() {
1203         let mut s = String::from_str("12345");
1204         s.truncate(5);
1205         assert_eq!(s, "12345");
1206         s.truncate(3);
1207         assert_eq!(s, "123");
1208         s.truncate(0);
1209         assert_eq!(s, "");
1210
1211         let mut s = String::from_str("12345");
1212         let p = s.as_ptr();
1213         s.truncate(3);
1214         s.push_str("6");
1215         let p_ = s.as_ptr();
1216         assert_eq!(p_, p);
1217     }
1218
1219     #[test]
1220     #[should_fail]
1221     fn test_str_truncate_invalid_len() {
1222         let mut s = String::from_str("12345");
1223         s.truncate(6);
1224     }
1225
1226     #[test]
1227     #[should_fail]
1228     fn test_str_truncate_split_codepoint() {
1229         let mut s = String::from_str("\u00FC"); // ü
1230         s.truncate(1);
1231     }
1232
1233     #[test]
1234     fn test_str_clear() {
1235         let mut s = String::from_str("12345");
1236         s.clear();
1237         assert_eq!(s.len(), 0);
1238         assert_eq!(s, "");
1239     }
1240
1241     #[test]
1242     fn test_str_add() {
1243         let a = String::from_str("12345");
1244         let b = a + "2";
1245         let b = b + String::from_str("2");
1246         assert_eq!(b.len(), 7);
1247         assert_eq!(b, "1234522");
1248     }
1249
1250     #[test]
1251     fn remove() {
1252         let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
1253         assert_eq!(s.remove(0), Some('ศ'));
1254         assert_eq!(s.len(), 33);
1255         assert_eq!(s, "ไทย中华Việt Nam; foobar");
1256         assert_eq!(s.remove(33), None);
1257         assert_eq!(s.remove(300), None);
1258         assert_eq!(s.remove(17), Some('ệ'));
1259         assert_eq!(s, "ไทย中华Vit Nam; foobar");
1260     }
1261
1262     #[test] #[should_fail]
1263     fn remove_bad() {
1264         "ศ".to_string().remove(1);
1265     }
1266
1267     #[test]
1268     fn insert() {
1269         let mut s = "foobar".to_string();
1270         s.insert(0, 'ệ');
1271         assert_eq!(s, "ệfoobar");
1272         s.insert(6, 'ย');
1273         assert_eq!(s, "ệfooยbar");
1274     }
1275
1276     #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); }
1277     #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); }
1278
1279     #[test]
1280     fn test_slicing() {
1281         let s = "foobar".to_string();
1282         assert_eq!("foobar", s[]);
1283         assert_eq!("foo", s[..3]);
1284         assert_eq!("bar", s[3..]);
1285         assert_eq!("oob", s[1..4]);
1286     }
1287
1288     #[test]
1289     fn test_simple_types() {
1290         assert_eq!(1i.to_string(), "1");
1291         assert_eq!((-1i).to_string(), "-1");
1292         assert_eq!(200u.to_string(), "200");
1293         assert_eq!(2u8.to_string(), "2");
1294         assert_eq!(true.to_string(), "true");
1295         assert_eq!(false.to_string(), "false");
1296         assert_eq!(().to_string(), "()");
1297         assert_eq!(("hi".to_string()).to_string(), "hi");
1298     }
1299
1300     #[test]
1301     fn test_vectors() {
1302         let x: Vec<int> = vec![];
1303         assert_eq!(x.to_string(), "[]");
1304         assert_eq!((vec![1i]).to_string(), "[1]");
1305         assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]");
1306         assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() ==
1307                "[[], [1], [1, 1]]");
1308     }
1309
1310     #[bench]
1311     fn bench_with_capacity(b: &mut Bencher) {
1312         b.iter(|| {
1313             String::with_capacity(100)
1314         });
1315     }
1316
1317     #[bench]
1318     fn bench_push_str(b: &mut Bencher) {
1319         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
1320         b.iter(|| {
1321             let mut r = String::new();
1322             r.push_str(s);
1323         });
1324     }
1325
1326     #[bench]
1327     fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
1328         let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
1329                   Lorem ipsum dolor sit amet, consectetur. ";
1330
1331         assert_eq!(100, s.len());
1332         b.iter(|| {
1333             let _ = String::from_utf8_lossy(s);
1334         });
1335     }
1336
1337     #[bench]
1338     fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
1339         let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
1340         assert_eq!(100, s.len());
1341         b.iter(|| {
1342             let _ = String::from_utf8_lossy(s);
1343         });
1344     }
1345
1346     #[bench]
1347     fn from_utf8_lossy_invalid(b: &mut Bencher) {
1348         let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
1349         b.iter(|| {
1350             let _ = String::from_utf8_lossy(s);
1351         });
1352     }
1353
1354     #[bench]
1355     fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
1356         let s = Vec::from_elem(100, 0xF5u8);
1357         b.iter(|| {
1358             let _ = String::from_utf8_lossy(s.as_slice());
1359         });
1360     }
1361 }