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};
18 use from_str::FromStr;
20 use iter::{Extendable, FromIterator, Iterator, range};
22 use option::{None, Option, Some};
25 use result::{Result, Ok, Err};
27 use str::{CharRange, Str, StrSlice, StrAllocating};
31 /// A growable string stored as a UTF-8 encoded buffer.
32 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
38 /// Creates a new string buffer initialized with the empty string.
40 pub fn new() -> StrBuf {
46 /// Creates a new string buffer with the given capacity.
48 pub fn with_capacity(capacity: uint) -> StrBuf {
50 vec: Vec::with_capacity(capacity),
54 /// Creates a new string buffer from length, capacity, and a pointer.
56 pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> StrBuf {
58 vec: Vec::from_raw_parts(length, capacity, ptr),
62 /// Creates a new string buffer from the given string.
64 pub fn from_str(string: &str) -> StrBuf {
66 vec: Vec::from_slice(string.as_bytes())
70 /// Creates a new string buffer from the given owned string, taking care not to copy it.
72 pub fn from_owned_str(string: StrBuf) -> StrBuf {
76 /// Returns the vector as a string buffer, if possible, taking care not to
79 /// Returns `Err` with the original vector if the vector contains invalid
82 pub fn from_utf8(vec: Vec<u8>) -> Result<StrBuf, Vec<u8>> {
83 if str::is_utf8(vec.as_slice()) {
84 Ok(StrBuf { vec: vec })
90 /// Return the underlying byte buffer, encoded as UTF-8.
92 pub fn into_bytes(self) -> Vec<u8> {
96 /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
99 pub fn append(mut self, second: &str) -> StrBuf {
100 self.push_str(second);
104 /// Creates a string buffer by repeating a character `length` times.
106 pub fn from_char(length: uint, ch: char) -> StrBuf {
111 let mut buf = StrBuf::new();
113 let size = buf.len() * length;
115 for _ in range(1, length) {
121 /// Pushes the given string onto this string buffer.
123 pub fn push_str(&mut self, string: &str) {
124 self.vec.push_all(string.as_bytes())
127 /// Push `ch` onto the given string `count` times.
129 pub fn grow(&mut self, count: uint, ch: char) {
130 for _ in range(0, count) {
135 /// Returns the number of bytes that this string buffer can hold without reallocating.
137 pub fn byte_capacity(&self) -> uint {
141 /// Reserves capacity for at least `extra` additional bytes in this string buffer.
143 pub fn reserve_additional(&mut self, extra: uint) {
144 self.vec.reserve_additional(extra)
147 /// Reserves capacity for at least `capacity` bytes in this string buffer.
149 pub fn reserve(&mut self, capacity: uint) {
150 self.vec.reserve(capacity)
153 /// Reserves capacity for exactly `capacity` bytes in this string buffer.
155 pub fn reserve_exact(&mut self, capacity: uint) {
156 self.vec.reserve_exact(capacity)
159 /// Shrinks the capacity of this string buffer to match its length.
161 pub fn shrink_to_fit(&mut self) {
162 self.vec.shrink_to_fit()
165 /// Adds the given character to the end of the string.
167 pub fn push_char(&mut self, ch: char) {
168 let cur_len = self.len();
170 // This may use up to 4 bytes.
171 self.vec.reserve_additional(4);
173 // Attempt to not use an intermediate buffer by just pushing bytes
174 // directly onto this string.
175 let mut c_vector = CVec::new(self.vec.as_mut_ptr().offset(cur_len as int), 4);
176 let used = ch.encode_utf8(c_vector.as_mut_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_slice()[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 Container for StrBuf {
285 fn len(&self) -> uint {
290 impl Mutable for StrBuf {
292 fn clear(&mut self) {
297 impl FromIterator<char> for StrBuf {
298 fn from_iter<I:Iterator<char>>(iterator: I) -> StrBuf {
299 let mut buf = StrBuf::new();
300 buf.extend(iterator);
305 impl Extendable<char> for StrBuf {
306 fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
313 impl Str for StrBuf {
315 fn as_slice<'a>(&'a self) -> &'a str {
317 mem::transmute(self.vec.as_slice())
322 impl StrAllocating for StrBuf {
324 fn into_owned(self) -> StrBuf {
329 fn into_strbuf(self) -> StrBuf {
334 impl fmt::Show for StrBuf {
335 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
336 self.as_slice().fmt(f)
340 impl<H:Writer> ::hash::Hash<H> for StrBuf {
342 fn hash(&self, hasher: &mut H) {
343 self.as_slice().hash(hasher)
347 impl<'a, S: Str> Equiv<S> for StrBuf {
349 fn equiv(&self, other: &S) -> bool {
350 self.as_slice() == other.as_slice()
354 impl FromStr for StrBuf {
356 fn from_str(s: &str) -> Option<StrBuf> {
364 use container::{Container, Mutable};
365 use self::test::Bencher;
366 use str::{Str, StrSlice};
370 fn bench_with_capacity(b: &mut Bencher) {
372 StrBuf::with_capacity(100)
377 fn bench_push_str(b: &mut Bencher) {
378 let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
380 let mut r = StrBuf::new();
386 fn test_push_bytes() {
387 let mut s = StrBuf::from_str("ABC");
389 s.push_bytes([ 'D' as u8 ]);
391 assert_eq!(s.as_slice(), "ABCD");
396 let mut s = StrBuf::new();
398 assert_eq!(s.as_slice().slice_from(0), "");
400 assert_eq!(s.as_slice().slice_from(0), "abc");
401 s.push_str("ประเทศไทย中华Việt Nam");
402 assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
406 fn test_push_char() {
407 let mut data = StrBuf::from_str("ประเทศไทย中");
409 data.push_char('b'); // 1 byte
410 data.push_char('¢'); // 2 byte
411 data.push_char('€'); // 3 byte
412 data.push_char('𤭢'); // 4 byte
413 assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
418 let mut data = StrBuf::from_str("ประเทศไทย中华b¢€𤭢");
419 assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
420 assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
421 assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
422 assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
423 assert_eq!(data.pop_char().unwrap(), '华');
424 assert_eq!(data.as_slice(), "ประเทศไทย中");
428 fn test_shift_char() {
429 let mut data = StrBuf::from_str("𤭢€¢b华ประเทศไทย中");
430 assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
431 assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
432 assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
433 assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
434 assert_eq!(data.shift_char().unwrap(), '华');
435 assert_eq!(data.as_slice(), "ประเทศไทย中");
439 fn test_str_truncate() {
440 let mut s = StrBuf::from_str("12345");
442 assert_eq!(s.as_slice(), "12345");
444 assert_eq!(s.as_slice(), "123");
446 assert_eq!(s.as_slice(), "");
448 let mut s = StrBuf::from_str("12345");
449 let p = s.as_slice().as_ptr();
452 let p_ = s.as_slice().as_ptr();
458 fn test_str_truncate_invalid_len() {
459 let mut s = StrBuf::from_str("12345");
465 fn test_str_truncate_split_codepoint() {
466 let mut s = StrBuf::from_str("\u00FC"); // ü
471 fn test_str_clear() {
472 let mut s = StrBuf::from_str("12345");
474 assert_eq!(s.len(), 0);
475 assert_eq!(s.as_slice(), "");