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