Skip to content

Commit def90f4

Browse files
committed
Fix tests. Add Vec<u8> conversion to StrBuf.
1 parent d8e45ea commit def90f4

File tree

8 files changed

+88
-60
lines changed

8 files changed

+88
-60
lines changed

src/libcollections/hashmap.rs

+10-2
Original file line numberDiff line numberDiff line change
@@ -1595,6 +1595,7 @@ pub type SetAlgebraItems<'a, T, H> =
15951595
mod test_map {
15961596
use super::HashMap;
15971597
use std::cmp::Equiv;
1598+
use std::hash::Hash;
15981599
use std::iter::{Iterator,range_inclusive,range_step_inclusive};
15991600
use std::local_data;
16001601
use std::vec;
@@ -1607,6 +1608,12 @@ mod test_map {
16071608
this == *other
16081609
}
16091610
}
1611+
impl<S: Writer> Hash<S> for KindaIntLike {
1612+
fn hash(&self, state: &mut S) {
1613+
let KindaIntLike(this) = *self;
1614+
this.hash(state)
1615+
}
1616+
}
16101617

16111618
#[test]
16121619
fn test_create_capacity_zero() {
@@ -1848,11 +1855,12 @@ mod test_map {
18481855
}
18491856

18501857
#[test]
1858+
#[allow(experimental)]
18511859
fn test_pop_equiv() {
18521860
let mut m = HashMap::new();
18531861
m.insert(1, 2);
1854-
assert_eq!(m.pop_equiv(&KindaIntLike(1), Some(2)));
1855-
assert_eq!(m.pop_equiv(&KindaIntLike(1), None));
1862+
assert_eq!(m.pop_equiv(&KindaIntLike(1)), Some(2));
1863+
assert_eq!(m.pop_equiv(&KindaIntLike(1)), None);
18561864
}
18571865

18581866
#[test]

src/libglob/lib.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -462,8 +462,8 @@ impl Pattern {
462462
fn fill_todo(todo: &mut Vec<(Path, uint)>, patterns: &[Pattern], idx: uint, path: &Path,
463463
options: MatchOptions) {
464464
// convert a pattern that's just many Char(_) to a string
465-
fn pattern_as_str(pattern: &Pattern) -> Option<~str> {
466-
let mut s = ~"";
465+
fn pattern_as_str(pattern: &Pattern) -> Option<StrBuf> {
466+
let mut s = StrBuf::new();
467467
for token in pattern.tokens.iter() {
468468
match *token {
469469
Char(c) => s.push_char(c),
@@ -493,8 +493,8 @@ fn fill_todo(todo: &mut Vec<(Path, uint)>, patterns: &[Pattern], idx: uint, path
493493
// continue. So instead of passing control back to the iterator,
494494
// we can just check for that one entry and potentially recurse
495495
// right away.
496-
let special = "." == s || ".." == s;
497-
let next_path = path.join(s);
496+
let special = "." == s.as_slice() || ".." == s.as_slice();
497+
let next_path = path.join(s.as_slice());
498498
if (special && path.is_dir()) || (!special && next_path.exists()) {
499499
add(todo, next_path);
500500
}

src/libnative/io/process.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ fn make_command_line(prog: &str, args: &[~str]) -> ~str {
402402
cmd.push_char(' ');
403403
append_arg(&mut cmd, *arg);
404404
}
405-
return cmd.to_owned_str();
405+
return cmd.into_owned();
406406

407407
fn append_arg(cmd: &mut StrBuf, arg: &str) {
408408
let quote = arg.chars().any(|c| c == ' ' || c == '\t');

src/libstd/hash/sip.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ mod tests {
291291
use iter::Iterator;
292292
use num::ToStrRadix;
293293
use option::{Some, None};
294-
use str::{Str, OwnedStr};
294+
use str::Str;
295295
use strbuf::StrBuf;
296296
use slice::{Vector, ImmutableVector, OwnedVector};
297297
use self::test::BenchHarness;

src/libstd/strbuf.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,11 @@ use iter::{Extendable, FromIterator, Iterator, range};
2020
use option::{None, Option, Some};
2121
use ptr::RawPtr;
2222
use slice::{OwnedVector, Vector};
23+
use str;
2324
use str::{OwnedStr, Str, StrSlice};
2425
use vec::Vec;
2526

27+
/// A growable string stored as a UTF-8 encoded buffer.
2628
#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
2729
pub struct StrBuf {
2830
vec: Vec<u8>,
@@ -69,6 +71,23 @@ impl StrBuf {
6971
}
7072
}
7173

74+
/// Tries to create a new string buffer from the given byte
75+
/// vector, validating that the vector is UTF-8 encoded.
76+
#[inline]
77+
pub fn from_utf8(vec: Vec<u8>) -> Option<StrBuf> {
78+
if str::is_utf8(vec.as_slice()) {
79+
Some(StrBuf { vec: vec })
80+
} else {
81+
None
82+
}
83+
}
84+
85+
/// Return the underlying byte buffer, encoded as UTF-8.
86+
#[inline]
87+
pub fn into_bytes(self) -> Vec<u8> {
88+
self.vec
89+
}
90+
7291
/// Pushes the given string onto this buffer; then, returns `self` so that it can be used
7392
/// again.
7493
#[inline]
@@ -100,6 +119,7 @@ impl StrBuf {
100119
self.vec.push_all(string.as_bytes())
101120
}
102121

122+
/// Push `ch` onto the given string `count` times.
103123
#[inline]
104124
pub fn grow(&mut self, count: uint, ch: char) {
105125
for _ in range(0, count) {
@@ -352,4 +372,3 @@ mod tests {
352372
s.truncate(1);
353373
}
354374
}
355-

src/test/bench/shootout-chameneos-redux.rs

+33-24
Original file line numberDiff line numberDiff line change
@@ -32,53 +32,62 @@ struct CreatureInfo {
3232
color: color
3333
}
3434

35-
fn show_color(cc: color) -> ~str {
35+
fn show_color(cc: color) -> &'static str {
3636
match cc {
37-
Red => {~"red"}
38-
Yellow => {~"yellow"}
39-
Blue => {~"blue"}
37+
Red => "red",
38+
Yellow => "yellow",
39+
Blue => "blue"
4040
}
4141
}
4242

43-
fn show_color_list(set: Vec<color>) -> ~str {
43+
fn show_color_list(set: Vec<color>) -> StrBuf {
4444
let mut out = StrBuf::new();
4545
for col in set.iter() {
4646
out.push_char(' ');
4747
out.push_str(show_color(*col));
4848
}
49-
return out.to_owned_str();
49+
out
5050
}
5151

52-
fn show_digit(nn: uint) -> ~str {
52+
fn show_digit(nn: uint) -> &'static str {
5353
match nn {
54-
0 => {~"zero"}
55-
1 => {~"one"}
56-
2 => {~"two"}
57-
3 => {~"three"}
58-
4 => {~"four"}
59-
5 => {~"five"}
60-
6 => {~"six"}
61-
7 => {~"seven"}
62-
8 => {~"eight"}
63-
9 => {~"nine"}
54+
0 => {"zero"}
55+
1 => {"one"}
56+
2 => {"two"}
57+
3 => {"three"}
58+
4 => {"four"}
59+
5 => {"five"}
60+
6 => {"six"}
61+
7 => {"seven"}
62+
8 => {"eight"}
63+
9 => {"nine"}
6464
_ => {fail!("expected digits from 0 to 9...")}
6565
}
6666
}
6767

68-
fn show_number(nn: uint) -> ~str {
69-
let mut out = ~"";
68+
fn show_number(nn: uint) -> StrBuf {
69+
let mut out = vec![];
7070
let mut num = nn;
7171
let mut dig;
72-
73-
if num == 0 { out = show_digit(0) };
72+
let mut len = 0;
73+
if num == 0 { out.push(show_digit(0)) };
7474

7575
while num != 0 {
7676
dig = num % 10;
7777
num = num / 10;
78-
out = show_digit(dig) + " " + out;
78+
out.push(" ");
79+
let s = show_digit(dig);
80+
out.push(s);
81+
len += 1 + s.len();
7982
}
83+
len += 1;
84+
out.push(" ");
8085

81-
return ~" " + out;
86+
let mut ret = StrBuf::with_capacity(len);
87+
for s in out.iter().rev() {
88+
ret.push_str(*s);
89+
}
90+
ret
8291
}
8392

8493
fn transform(aa: color, bb: color) -> color {
@@ -125,7 +134,7 @@ fn creature(
125134
option::None => {
126135
// log creatures met and evil clones of self
127136
let report = format!("{} {}",
128-
creatures_met, show_number(evil_clones_met));
137+
creatures_met, show_number(evil_clones_met).as_slice());
129138
to_rendezvous_log.send(report);
130139
break;
131140
}

src/test/bench/shootout-k-nucleotide-pipes.rs

+6-14
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,11 @@
1515

1616
extern crate collections;
1717

18-
use std::cmp::Ord;
19-
use std::comm;
2018
use collections::HashMap;
2119
use std::mem::replace;
2220
use std::option;
2321
use std::os;
24-
use std::io;
25-
use std::str;
2622
use std::strbuf::StrBuf;
27-
use std::task;
28-
use std::vec;
2923

3024
fn f64_cmp(x: f64, y: f64) -> Ordering {
3125
// arbitrarily decide that NaNs are larger than everything.
@@ -66,16 +60,14 @@ fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> ~str {
6660

6761
let mut buffer = StrBuf::new();
6862
for &(ref k, v) in pairs_sorted.iter() {
69-
unsafe {
70-
buffer.push_str(format!("{} {:0.3f}\n",
71-
k.as_slice()
72-
.to_ascii()
73-
.to_upper()
74-
.into_str(), v));
75-
}
63+
buffer.push_str(format!("{} {:0.3f}\n",
64+
k.as_slice()
65+
.to_ascii()
66+
.to_upper()
67+
.into_str(), v));
7668
}
7769

78-
return buffer.to_owned_str();
70+
return buffer.into_owned();
7971
}
8072

8173
// given a map, search for the frequency of a pattern

src/test/bench/shootout-k-nucleotide.rs

+13-13
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@
1111
// ignore-android see #10393 #13206
1212
// ignore-pretty
1313

14-
use std::ascii::OwnedStrAsciiExt;
15-
use std::str;
1614
use std::strbuf::StrBuf;
1715
use std::slice;
1816

@@ -50,8 +48,7 @@ impl Code {
5048
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
5149
}
5250

53-
// FIXME: Inefficient.
54-
fn unpack(&self, frame: uint) -> ~str {
51+
fn unpack(&self, frame: uint) -> StrBuf {
5552
let mut key = self.hash();
5653
let mut result = Vec::new();
5754
for _ in range(0, frame) {
@@ -60,7 +57,7 @@ impl Code {
6057
}
6158

6259
result.reverse();
63-
str::from_utf8_owned(result.move_iter().collect()).unwrap()
60+
StrBuf::from_utf8(result).unwrap()
6461
}
6562
}
6663

@@ -239,7 +236,7 @@ fn print_frequencies(frequencies: &Table, frame: uint) {
239236

240237
for &(count, key) in vector.iter().rev() {
241238
println!("{} {:.3f}",
242-
key.unpack(frame),
239+
key.unpack(frame).as_slice(),
243240
(count as f32 * 100.0) / (total_count as f32));
244241
}
245242
println!("");
@@ -249,14 +246,17 @@ fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
249246
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
250247
}
251248

252-
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> ~[u8] {
253-
let mut res = StrBuf::new();
249+
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
250+
let mut res = Vec::new();
254251
for l in r.lines().map(|l| l.ok().unwrap())
255252
.skip_while(|l| key != l.slice_to(key.len())).skip(1)
256253
{
257-
res.push_str(l.trim());
254+
res.push_all(l.trim().as_bytes());
258255
}
259-
res.to_owned_str().into_ascii_upper().into_bytes()
256+
for b in res.mut_iter() {
257+
*b = b.to_ascii().to_upper().to_byte();
258+
}
259+
res
260260
}
261261

262262
fn main() {
@@ -268,17 +268,17 @@ fn main() {
268268
};
269269

270270
let mut frequencies = Table::new();
271-
generate_frequencies(&mut frequencies, input, 1);
271+
generate_frequencies(&mut frequencies, input.as_slice(), 1);
272272
print_frequencies(&frequencies, 1);
273273

274274
frequencies = Table::new();
275-
generate_frequencies(&mut frequencies, input, 2);
275+
generate_frequencies(&mut frequencies, input.as_slice(), 2);
276276
print_frequencies(&frequencies, 2);
277277

278278
for occurrence in OCCURRENCES.iter() {
279279
frequencies = Table::new();
280280
generate_frequencies(&mut frequencies,
281-
input,
281+
input.as_slice(),
282282
occurrence.len());
283283
print_occurrences(&mut frequencies, *occurrence);
284284
}

0 commit comments

Comments
 (0)