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