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.
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.
11 //! An owned, growable string that enforces that its contents are valid UTF-8.
16 use container::{Container, Mutable};
19 use from_str::FromStr;
21 use iter::{Extendable, FromIterator, Iterator, range};
23 use option::{None, Option, Some};
26 use result::{Result, Ok, Err};
28 use str::{CharRange, Str, StrSlice, StrAllocating};
32 /// A growable string stored as a UTF-8 encoded buffer.
33 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
39 /// Creates a new string buffer initialized with the empty string.
41 pub fn new() -> String {
47 /// Creates a new string buffer with the given capacity.
49 pub fn with_capacity(capacity: uint) -> String {
51 vec: Vec::with_capacity(capacity),
55 /// Creates a new string buffer from length, capacity, and a pointer.
57 pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
59 vec: Vec::from_raw_parts(length, capacity, ptr),
63 /// Creates a new string buffer from the given string.
65 pub fn from_str(string: &str) -> String {
67 vec: Vec::from_slice(string.as_bytes())
71 /// Creates a new string buffer from the given owned string, taking care not to copy it.
73 pub fn from_owned_str(string: String) -> String {
77 /// Returns the vector as a string buffer, if possible, taking care not to
80 /// Returns `Err` with the original vector if the vector contains invalid
83 pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
84 if str::is_utf8(vec.as_slice()) {
85 Ok(String { vec: vec })
91 /// Return the underlying byte buffer, encoded as UTF-8.
93 pub fn into_bytes(self) -> Vec<u8> {
97 /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
100 pub fn append(mut self, second: &str) -> String {
101 self.push_str(second);
105 /// Creates a string buffer by repeating a character `length` times.
107 pub fn from_char(length: uint, ch: char) -> String {
112 let mut buf = String::new();
114 let size = buf.len() * length;
116 for _ in range(1, length) {
122 /// Pushes the given string onto this string buffer.
124 pub fn push_str(&mut self, string: &str) {
125 self.vec.push_all(string.as_bytes())
128 /// Push `ch` onto the given string `count` times.
130 pub fn grow(&mut self, count: uint, ch: char) {
131 for _ in range(0, count) {
136 /// Returns the number of bytes that this string buffer can hold without reallocating.
138 pub fn byte_capacity(&self) -> uint {
142 /// Reserves capacity for at least `extra` additional bytes in this string buffer.
144 pub fn reserve_additional(&mut self, extra: uint) {
145 self.vec.reserve_additional(extra)
148 /// Reserves capacity for at least `capacity` bytes in this string buffer.
150 pub fn reserve(&mut self, capacity: uint) {
151 self.vec.reserve(capacity)
154 /// Reserves capacity for exactly `capacity` bytes in this string buffer.
156 pub fn reserve_exact(&mut self, capacity: uint) {
157 self.vec.reserve_exact(capacity)
160 /// Shrinks the capacity of this string buffer to match its length.
162 pub fn shrink_to_fit(&mut self) {
163 self.vec.shrink_to_fit()
166 /// Adds the given character to the end of the string.
168 pub fn push_char(&mut self, ch: char) {
169 let cur_len = self.len();
171 // This may use up to 4 bytes.
172 self.vec.reserve_additional(4);
174 // Attempt to not use an intermediate buffer by just pushing bytes
175 // directly onto this string.
176 let mut c_vector = CVec::new(self.vec.as_mut_ptr().offset(cur_len as int), 4);
177 let used = ch.encode_utf8(c_vector.as_mut_slice());
178 self.vec.set_len(cur_len + used);
182 /// Pushes the given bytes onto this string buffer. This is unsafe because it does not check
183 /// to ensure that the resulting string will be valid UTF-8.
185 pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
186 self.vec.push_all(bytes)
189 /// Works with the underlying buffer as a byte slice.
191 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
195 /// Works with the underlying buffer as a mutable byte slice. Unsafe
196 /// because this can be used to violate the UTF-8 property.
198 pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
199 self.vec.as_mut_slice()
202 /// Shorten a string to the specified length (which must be <= the current length)
204 pub fn truncate(&mut self, len: uint) {
205 assert!(self.as_slice().is_char_boundary(len));
206 self.vec.truncate(len)
209 /// Appends a byte to this string buffer. The caller must preserve the valid UTF-8 property.
211 pub unsafe fn push_byte(&mut self, byte: u8) {
212 self.push_bytes([byte])
215 /// Removes the last byte from the string buffer and returns it. Returns `None` if this string
218 /// The caller must preserve the valid UTF-8 property.
220 pub unsafe fn pop_byte(&mut self) -> Option<u8> {
221 let len = self.len();
226 let byte = self.as_slice()[len - 1];
227 self.vec.set_len(len - 1);
231 /// Removes the last character from the string buffer and returns it. Returns `None` if this
232 /// string buffer is empty.
234 pub fn pop_char(&mut self) -> Option<char> {
235 let len = self.len();
240 let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
242 self.vec.set_len(next);
247 /// Removes the first byte from the string buffer and returns it. Returns `None` if this string
250 /// The caller must preserve the valid UTF-8 property.
251 pub unsafe fn shift_byte(&mut self) -> Option<u8> {
255 /// Removes the first character from the string buffer and returns it. Returns `None` if this
256 /// string buffer is empty.
260 /// This is a O(n) operation as it requires copying every element in the buffer.
261 pub fn shift_char (&mut self) -> Option<char> {
262 let len = self.len();
267 let CharRange {ch, next} = self.as_slice().char_range_at(0);
268 let new_len = len - next;
270 ptr::copy_memory(self.vec.as_mut_ptr(), self.vec.as_ptr().offset(next as int), new_len);
271 self.vec.set_len(new_len);
276 /// Views the string buffer as a mutable sequence of bytes.
278 /// Callers must preserve the valid UTF-8 property.
279 pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
284 impl Container for String {
286 fn len(&self) -> uint {
291 impl Mutable for String {
293 fn clear(&mut self) {
298 impl FromIterator<char> for String {
299 fn from_iter<I:Iterator<char>>(iterator: I) -> String {
300 let mut buf = String::new();
301 buf.extend(iterator);
306 impl Extendable<char> for String {
307 fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
314 impl Str for String {
316 fn as_slice<'a>(&'a self) -> &'a str {
318 mem::transmute(self.vec.as_slice())
323 impl StrAllocating for String {
325 fn into_owned(self) -> String {
330 fn into_strbuf(self) -> String {
335 impl Default for String {
336 fn default() -> String {
341 impl fmt::Show for String {
342 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
343 self.as_slice().fmt(f)
347 impl<H:Writer> ::hash::Hash<H> for String {
349 fn hash(&self, hasher: &mut H) {
350 self.as_slice().hash(hasher)
354 impl<'a, S: Str> Equiv<S> for String {
356 fn equiv(&self, other: &S) -> bool {
357 self.as_slice() == other.as_slice()
361 impl FromStr for String {
363 fn from_str(s: &str) -> Option<String> {
371 use container::{Container, Mutable};
372 use self::test::Bencher;
373 use str::{Str, StrSlice};
377 fn bench_with_capacity(b: &mut Bencher) {
379 String::with_capacity(100)
384 fn bench_push_str(b: &mut Bencher) {
385 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
387 let mut r = String::new();
393 fn test_push_bytes() {
394 let mut s = String::from_str("ABC");
396 s.push_bytes([ 'D' as u8 ]);
398 assert_eq!(s.as_slice(), "ABCD");
403 let mut s = String::new();
405 assert_eq!(s.as_slice().slice_from(0), "");
407 assert_eq!(s.as_slice().slice_from(0), "abc");
408 s.push_str("ประเทศไทย中华Việt Nam");
409 assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
413 fn test_push_char() {
414 let mut data = String::from_str("ประเทศไทย中");
416 data.push_char('b'); // 1 byte
417 data.push_char('¢'); // 2 byte
418 data.push_char('€'); // 3 byte
419 data.push_char('𤭢'); // 4 byte
420 assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
425 let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
426 assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
427 assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
428 assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
429 assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
430 assert_eq!(data.pop_char().unwrap(), '华');
431 assert_eq!(data.as_slice(), "ประเทศไทย中");
435 fn test_shift_char() {
436 let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
437 assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
438 assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
439 assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
440 assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
441 assert_eq!(data.shift_char().unwrap(), '华');
442 assert_eq!(data.as_slice(), "ประเทศไทย中");
446 fn test_str_truncate() {
447 let mut s = String::from_str("12345");
449 assert_eq!(s.as_slice(), "12345");
451 assert_eq!(s.as_slice(), "123");
453 assert_eq!(s.as_slice(), "");
455 let mut s = String::from_str("12345");
456 let p = s.as_slice().as_ptr();
459 let p_ = s.as_slice().as_ptr();
465 fn test_str_truncate_invalid_len() {
466 let mut s = String::from_str("12345");
472 fn test_str_truncate_split_codepoint() {
473 let mut s = String::from_str("\u00FC"); // ü
478 fn test_str_clear() {
479 let mut s = String::from_str("12345");
481 assert_eq!(s.len(), 0);
482 assert_eq!(s.as_slice(), "");