]> git.lizzy.rs Git - rust.git/blob - src/libstd/string.rs
core: rename strbuf::StrBuf to string::String
[rust.git] / src / libstd / 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 //! An owned, growable string that enforces that its contents are valid UTF-8.
12
13 use c_vec::CVec;
14 use char::Char;
15 use cmp::Equiv;
16 use container::{Container, Mutable};
17 use default::Default;
18 use fmt;
19 use from_str::FromStr;
20 use io::Writer;
21 use iter::{Extendable, FromIterator, Iterator, range};
22 use mem;
23 use option::{None, Option, Some};
24 use ptr::RawPtr;
25 use ptr;
26 use result::{Result, Ok, Err};
27 use slice::Vector;
28 use str::{CharRange, Str, StrSlice, StrAllocating};
29 use str;
30 use vec::Vec;
31
32 /// A growable string stored as a UTF-8 encoded buffer.
33 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
34 pub struct String {
35     vec: Vec<u8>,
36 }
37
38 impl String {
39     /// Creates a new string buffer initialized with the empty string.
40     #[inline]
41     pub fn new() -> String {
42         String {
43             vec: Vec::new(),
44         }
45     }
46
47     /// Creates a new string buffer with the given capacity.
48     #[inline]
49     pub fn with_capacity(capacity: uint) -> String {
50         String {
51             vec: Vec::with_capacity(capacity),
52         }
53     }
54
55     /// Creates a new string buffer from length, capacity, and a pointer.
56     #[inline]
57     pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
58         String {
59             vec: Vec::from_raw_parts(length, capacity, ptr),
60         }
61     }
62
63     /// Creates a new string buffer from the given string.
64     #[inline]
65     pub fn from_str(string: &str) -> String {
66         String {
67             vec: Vec::from_slice(string.as_bytes())
68         }
69     }
70
71     /// Creates a new string buffer from the given owned string, taking care not to copy it.
72     #[inline]
73     pub fn from_owned_str(string: String) -> String {
74         string
75     }
76
77     /// Returns the vector as a string buffer, if possible, taking care not to
78     /// copy it.
79     ///
80     /// Returns `Err` with the original vector if the vector contains invalid
81     /// UTF-8.
82     #[inline]
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 })
86         } else {
87             Err(vec)
88         }
89     }
90
91     /// Return the underlying byte buffer, encoded as UTF-8.
92     #[inline]
93     pub fn into_bytes(self) -> Vec<u8> {
94         self.vec
95     }
96
97     /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
98     /// again.
99     #[inline]
100     pub fn append(mut self, second: &str) -> String {
101         self.push_str(second);
102         self
103     }
104
105     /// Creates a string buffer by repeating a character `length` times.
106     #[inline]
107     pub fn from_char(length: uint, ch: char) -> String {
108         if length == 0 {
109             return String::new()
110         }
111
112         let mut buf = String::new();
113         buf.push_char(ch);
114         let size = buf.len() * length;
115         buf.reserve(size);
116         for _ in range(1, length) {
117             buf.push_char(ch)
118         }
119         buf
120     }
121
122     /// Pushes the given string onto this string buffer.
123     #[inline]
124     pub fn push_str(&mut self, string: &str) {
125         self.vec.push_all(string.as_bytes())
126     }
127
128     /// Push `ch` onto the given string `count` times.
129     #[inline]
130     pub fn grow(&mut self, count: uint, ch: char) {
131         for _ in range(0, count) {
132             self.push_char(ch)
133         }
134     }
135
136     /// Returns the number of bytes that this string buffer can hold without reallocating.
137     #[inline]
138     pub fn byte_capacity(&self) -> uint {
139         self.vec.capacity()
140     }
141
142     /// Reserves capacity for at least `extra` additional bytes in this string buffer.
143     #[inline]
144     pub fn reserve_additional(&mut self, extra: uint) {
145         self.vec.reserve_additional(extra)
146     }
147
148     /// Reserves capacity for at least `capacity` bytes in this string buffer.
149     #[inline]
150     pub fn reserve(&mut self, capacity: uint) {
151         self.vec.reserve(capacity)
152     }
153
154     /// Reserves capacity for exactly `capacity` bytes in this string buffer.
155     #[inline]
156     pub fn reserve_exact(&mut self, capacity: uint) {
157         self.vec.reserve_exact(capacity)
158     }
159
160     /// Shrinks the capacity of this string buffer to match its length.
161     #[inline]
162     pub fn shrink_to_fit(&mut self) {
163         self.vec.shrink_to_fit()
164     }
165
166     /// Adds the given character to the end of the string.
167     #[inline]
168     pub fn push_char(&mut self, ch: char) {
169         let cur_len = self.len();
170         unsafe {
171             // This may use up to 4 bytes.
172             self.vec.reserve_additional(4);
173
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);
179         }
180     }
181
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.
184     #[inline]
185     pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
186         self.vec.push_all(bytes)
187     }
188
189     /// Works with the underlying buffer as a byte slice.
190     #[inline]
191     pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
192         self.vec.as_slice()
193     }
194
195     /// Works with the underlying buffer as a mutable byte slice. Unsafe
196     /// because this can be used to violate the UTF-8 property.
197     #[inline]
198     pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
199         self.vec.as_mut_slice()
200     }
201
202     /// Shorten a string to the specified length (which must be <= the current length)
203     #[inline]
204     pub fn truncate(&mut self, len: uint) {
205         assert!(self.as_slice().is_char_boundary(len));
206         self.vec.truncate(len)
207     }
208
209     /// Appends a byte to this string buffer. The caller must preserve the valid UTF-8 property.
210     #[inline]
211     pub unsafe fn push_byte(&mut self, byte: u8) {
212         self.push_bytes([byte])
213     }
214
215     /// Removes the last byte from the string buffer and returns it. Returns `None` if this string
216     /// buffer is empty.
217     ///
218     /// The caller must preserve the valid UTF-8 property.
219     #[inline]
220     pub unsafe fn pop_byte(&mut self) -> Option<u8> {
221         let len = self.len();
222         if len == 0 {
223             return None
224         }
225
226         let byte = self.as_slice()[len - 1];
227         self.vec.set_len(len - 1);
228         Some(byte)
229     }
230
231     /// Removes the last character from the string buffer and returns it. Returns `None` if this
232     /// string buffer is empty.
233     #[inline]
234     pub fn pop_char(&mut self) -> Option<char> {
235         let len = self.len();
236         if len == 0 {
237             return None
238         }
239
240         let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
241         unsafe {
242             self.vec.set_len(next);
243         }
244         Some(ch)
245     }
246
247     /// Removes the first byte from the string buffer and returns it. Returns `None` if this string
248     /// buffer is empty.
249     ///
250     /// The caller must preserve the valid UTF-8 property.
251     pub unsafe fn shift_byte(&mut self) -> Option<u8> {
252         self.vec.shift()
253     }
254
255     /// Removes the first character from the string buffer and returns it. Returns `None` if this
256     /// string buffer is empty.
257     ///
258     /// # Warning
259     ///
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();
263         if len == 0 {
264             return None
265         }
266
267         let CharRange {ch, next} = self.as_slice().char_range_at(0);
268         let new_len = len - next;
269         unsafe {
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);
272         }
273         Some(ch)
274     }
275
276     /// Views the string buffer as a mutable sequence of bytes.
277     ///
278     /// Callers must preserve the valid UTF-8 property.
279     pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
280         &mut self.vec
281     }
282 }
283
284 impl Container for String {
285     #[inline]
286     fn len(&self) -> uint {
287         self.vec.len()
288     }
289 }
290
291 impl Mutable for String {
292     #[inline]
293     fn clear(&mut self) {
294         self.vec.clear()
295     }
296 }
297
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);
302         buf
303     }
304 }
305
306 impl Extendable<char> for String {
307     fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
308         for ch in iterator {
309             self.push_char(ch)
310         }
311     }
312 }
313
314 impl Str for String {
315     #[inline]
316     fn as_slice<'a>(&'a self) -> &'a str {
317         unsafe {
318             mem::transmute(self.vec.as_slice())
319         }
320     }
321 }
322
323 impl StrAllocating for String {
324     #[inline]
325     fn into_owned(self) -> String {
326         self
327     }
328
329     #[inline]
330     fn into_strbuf(self) -> String {
331         self
332     }
333 }
334
335 impl Default for String {
336     fn default() -> String {
337         String::new()
338     }
339 }
340
341 impl fmt::Show for String {
342     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
343         self.as_slice().fmt(f)
344     }
345 }
346
347 impl<H:Writer> ::hash::Hash<H> for String {
348     #[inline]
349     fn hash(&self, hasher: &mut H) {
350         self.as_slice().hash(hasher)
351     }
352 }
353
354 impl<'a, S: Str> Equiv<S> for String {
355     #[inline]
356     fn equiv(&self, other: &S) -> bool {
357         self.as_slice() == other.as_slice()
358     }
359 }
360
361 impl FromStr for String {
362     #[inline]
363     fn from_str(s: &str) -> Option<String> {
364         Some(s.to_strbuf())
365     }
366 }
367
368 #[cfg(test)]
369 mod tests {
370     extern crate test;
371     use container::{Container, Mutable};
372     use self::test::Bencher;
373     use str::{Str, StrSlice};
374     use super::String;
375
376     #[bench]
377     fn bench_with_capacity(b: &mut Bencher) {
378         b.iter(|| {
379             String::with_capacity(100)
380         });
381     }
382
383     #[bench]
384     fn bench_push_str(b: &mut Bencher) {
385         let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
386         b.iter(|| {
387             let mut r = String::new();
388             r.push_str(s);
389         });
390     }
391
392     #[test]
393     fn test_push_bytes() {
394         let mut s = String::from_str("ABC");
395         unsafe {
396             s.push_bytes([ 'D' as u8 ]);
397         }
398         assert_eq!(s.as_slice(), "ABCD");
399     }
400
401     #[test]
402     fn test_push_str() {
403         let mut s = String::new();
404         s.push_str("");
405         assert_eq!(s.as_slice().slice_from(0), "");
406         s.push_str("abc");
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");
410     }
411
412     #[test]
413     fn test_push_char() {
414         let mut data = String::from_str("ประเทศไทย中");
415         data.push_char('华');
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¢€𤭢");
421     }
422
423     #[test]
424     fn test_pop_char() {
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(), "ประเทศไทย中");
432     }
433
434     #[test]
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(), "ประเทศไทย中");
443     }
444
445     #[test]
446     fn test_str_truncate() {
447         let mut s = String::from_str("12345");
448         s.truncate(5);
449         assert_eq!(s.as_slice(), "12345");
450         s.truncate(3);
451         assert_eq!(s.as_slice(), "123");
452         s.truncate(0);
453         assert_eq!(s.as_slice(), "");
454
455         let mut s = String::from_str("12345");
456         let p = s.as_slice().as_ptr();
457         s.truncate(3);
458         s.push_str("6");
459         let p_ = s.as_slice().as_ptr();
460         assert_eq!(p_, p);
461     }
462
463     #[test]
464     #[should_fail]
465     fn test_str_truncate_invalid_len() {
466         let mut s = String::from_str("12345");
467         s.truncate(6);
468     }
469
470     #[test]
471     #[should_fail]
472     fn test_str_truncate_split_codepoint() {
473         let mut s = String::from_str("\u00FC"); // ü
474         s.truncate(1);
475     }
476
477     #[test]
478     fn test_str_clear() {
479         let mut s = String::from_str("12345");
480         s.clear();
481         assert_eq!(s.len(), 0);
482         assert_eq!(s.as_slice(), "");
483     }
484 }