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.
15 use core::default::Default;
21 use {Collection, Mutable};
24 use str::{CharRange, StrAllocating};
27 /// A growable string stored as a UTF-8 encoded buffer.
28 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)]
34 /// Creates a new string buffer initialized with the empty string.
36 pub fn new() -> String {
42 /// Creates a new string buffer with the given capacity.
44 pub fn with_capacity(capacity: uint) -> String {
46 vec: Vec::with_capacity(capacity),
50 /// Creates a new string buffer from length, capacity, and a pointer.
52 pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
54 vec: Vec::from_raw_parts(length, capacity, ptr),
58 /// Creates a new string buffer from the given string.
60 pub fn from_str(string: &str) -> String {
62 vec: Vec::from_slice(string.as_bytes())
67 #[deprecated = "obsoleted by the removal of ~str"]
69 pub fn from_owned_str(string: String) -> String {
73 /// Returns the vector as a string buffer, if possible, taking care not to
76 /// Returns `Err` with the original vector if the vector contains invalid
79 pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
80 if str::is_utf8(vec.as_slice()) {
81 Ok(String { vec: vec })
87 /// Return the underlying byte buffer, encoded as UTF-8.
89 pub fn into_bytes(self) -> Vec<u8> {
93 /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
96 pub fn append(mut self, second: &str) -> String {
97 self.push_str(second);
101 /// Creates a string buffer by repeating a character `length` times.
103 pub fn from_char(length: uint, ch: char) -> String {
108 let mut buf = String::new();
110 let size = buf.len() * length;
112 for _ in range(1, length) {
118 /// Pushes the given string onto this string buffer.
120 pub fn push_str(&mut self, string: &str) {
121 self.vec.push_all(string.as_bytes())
124 /// Push `ch` onto the given string `count` times.
126 pub fn grow(&mut self, count: uint, ch: char) {
127 for _ in range(0, count) {
132 /// Returns the number of bytes that this string buffer can hold without reallocating.
134 pub fn byte_capacity(&self) -> uint {
138 /// Reserves capacity for at least `extra` additional bytes in this string buffer.
140 pub fn reserve_additional(&mut self, extra: uint) {
141 self.vec.reserve_additional(extra)
144 /// Reserves capacity for at least `capacity` bytes in this string buffer.
146 pub fn reserve(&mut self, capacity: uint) {
147 self.vec.reserve(capacity)
150 /// Reserves capacity for exactly `capacity` bytes in this string buffer.
152 pub fn reserve_exact(&mut self, capacity: uint) {
153 self.vec.reserve_exact(capacity)
156 /// Shrinks the capacity of this string buffer to match its length.
158 pub fn shrink_to_fit(&mut self) {
159 self.vec.shrink_to_fit()
162 /// Adds the given character to the end of the string.
164 pub fn push_char(&mut self, ch: char) {
165 let cur_len = self.len();
166 // This may use up to 4 bytes.
167 self.vec.reserve_additional(4);
170 // Attempt to not use an intermediate buffer by just pushing bytes
171 // directly onto this string.
173 data: self.vec.as_ptr().offset(cur_len as int),
176 let used = ch.encode_utf8(mem::transmute(slice));
177 self.vec.set_len(cur_len + used);
181 /// Pushes the given bytes onto this string buffer. This is unsafe because it does not check
182 /// to ensure that the resulting string will be valid UTF-8.
184 pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
185 self.vec.push_all(bytes)
188 /// Works with the underlying buffer as a byte slice.
190 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
194 /// Works with the underlying buffer as a mutable byte slice. Unsafe
195 /// because this can be used to violate the UTF-8 property.
197 pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
198 self.vec.as_mut_slice()
201 /// Shorten a string to the specified length (which must be <= the current length)
203 pub fn truncate(&mut self, len: uint) {
204 assert!(self.as_slice().is_char_boundary(len));
205 self.vec.truncate(len)
208 /// Appends a byte to this string buffer. The caller must preserve the valid UTF-8 property.
210 pub unsafe fn push_byte(&mut self, byte: u8) {
211 self.push_bytes([byte])
214 /// Removes the last byte from the string buffer and returns it. Returns `None` if this string
217 /// The caller must preserve the valid UTF-8 property.
219 pub unsafe fn pop_byte(&mut self) -> Option<u8> {
220 let len = self.len();
225 let byte = self.as_bytes()[len - 1];
226 self.vec.set_len(len - 1);
230 /// Removes the last character from the string buffer and returns it. Returns `None` if this
231 /// string buffer is empty.
233 pub fn pop_char(&mut self) -> Option<char> {
234 let len = self.len();
239 let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
241 self.vec.set_len(next);
246 /// Removes the first byte from the string buffer and returns it. Returns `None` if this string
249 /// The caller must preserve the valid UTF-8 property.
250 pub unsafe fn shift_byte(&mut self) -> Option<u8> {
254 /// Removes the first character from the string buffer and returns it. Returns `None` if this
255 /// string buffer is empty.
259 /// This is a O(n) operation as it requires copying every element in the buffer.
260 pub fn shift_char (&mut self) -> Option<char> {
261 let len = self.len();
266 let CharRange {ch, next} = self.as_slice().char_range_at(0);
267 let new_len = len - next;
269 ptr::copy_memory(self.vec.as_mut_ptr(), self.vec.as_ptr().offset(next as int), new_len);
270 self.vec.set_len(new_len);
275 /// Views the string buffer as a mutable sequence of bytes.
277 /// Callers must preserve the valid UTF-8 property.
278 pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
283 impl Collection for String {
285 fn len(&self) -> uint {
290 impl Mutable for String {
292 fn clear(&mut self) {
297 impl FromIterator<char> for String {
298 fn from_iter<I:Iterator<char>>(iterator: I) -> String {
299 let mut buf = String::new();
300 buf.extend(iterator);
305 impl Extendable<char> for String {
306 fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
313 impl Str for String {
315 fn as_slice<'a>(&'a self) -> &'a str {
317 mem::transmute(self.vec.as_slice())
322 impl StrAllocating for String {
324 fn into_string(self) -> String {
329 impl Default for String {
330 fn default() -> String {
335 impl fmt::Show for String {
336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
337 self.as_slice().fmt(f)
341 impl<H: hash::Writer> hash::Hash<H> for String {
343 fn hash(&self, hasher: &mut H) {
344 self.as_slice().hash(hasher)
348 impl<'a, S: Str> Equiv<S> for String {
350 fn equiv(&self, other: &S) -> bool {
351 self.as_slice() == other.as_slice()
355 impl<S: Str> Add<S, String> for String {
356 fn add(&self, other: &S) -> String {
357 let mut s = self.to_string();
358 s.push_str(other.as_slice());
369 use str::{Str, StrSlice};
373 fn bench_with_capacity(b: &mut Bencher) {
375 String::with_capacity(100)
380 fn bench_push_str(b: &mut Bencher) {
381 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
383 let mut r = String::new();
389 fn test_push_bytes() {
390 let mut s = String::from_str("ABC");
392 s.push_bytes([ 'D' as u8 ]);
394 assert_eq!(s.as_slice(), "ABCD");
399 let mut s = String::new();
401 assert_eq!(s.as_slice().slice_from(0), "");
403 assert_eq!(s.as_slice().slice_from(0), "abc");
404 s.push_str("ประเทศไทย中华Việt Nam");
405 assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
409 fn test_push_char() {
410 let mut data = String::from_str("ประเทศไทย中");
412 data.push_char('b'); // 1 byte
413 data.push_char('¢'); // 2 byte
414 data.push_char('€'); // 3 byte
415 data.push_char('𤭢'); // 4 byte
416 assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
421 let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
422 assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
423 assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
424 assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
425 assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
426 assert_eq!(data.pop_char().unwrap(), '华');
427 assert_eq!(data.as_slice(), "ประเทศไทย中");
431 fn test_shift_char() {
432 let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
433 assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
434 assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
435 assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
436 assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
437 assert_eq!(data.shift_char().unwrap(), '华');
438 assert_eq!(data.as_slice(), "ประเทศไทย中");
442 fn test_str_truncate() {
443 let mut s = String::from_str("12345");
445 assert_eq!(s.as_slice(), "12345");
447 assert_eq!(s.as_slice(), "123");
449 assert_eq!(s.as_slice(), "");
451 let mut s = String::from_str("12345");
452 let p = s.as_slice().as_ptr();
455 let p_ = s.as_slice().as_ptr();
461 fn test_str_truncate_invalid_len() {
462 let mut s = String::from_str("12345");
468 fn test_str_truncate_split_codepoint() {
469 let mut s = String::from_str("\u00FC"); // ü
474 fn test_str_clear() {
475 let mut s = String::from_str("12345");
477 assert_eq!(s.len(), 0);
478 assert_eq!(s.as_slice(), "");
483 let a = String::from_str("12345");
485 let b = b + String::from_str("2");
486 assert_eq!(b.len(), 7);
487 assert_eq!(b.as_slice(), "1234522");