Skip to content

Commit 918a731

Browse files
committed
auto merge of #11129 : SimonSapin/rust/foo-vs-foo_opt, r=alexcrichton
[On 2013-12-06, I wrote to the rust-dev mailing list](https://mail.mozilla.org/pipermail/rust-dev/2013-December/007263.html): > Subject: Let’s avoid having both foo() and foo_opt() > > We have some functions and methods such as [std::str::from_utf8](http://static.rust-lang.org/doc/master/std/str/fn.from_utf8.html) that may succeed and give a result, or fail when the input is invalid. > > 1. Sometimes we assume the input is valid and don’t want to deal with the error case. Task failure works nicely. > > 2. Sometimes we do want to do something different on invalid input, so returning an `Option<T>` works best. > > And so we end up with both `from_utf8` and `from_utf8`. This particular case is worse because we also have `from_utf8_owned` and `from_utf8_owned_opt`, to cover everything. > > Multiplying names like this is just not good design. I’d like to reduce this pattern. > > Getting behavior 1. when you have 2. is easy: just call `.unwrap()` on the Option. I think we should rename every `foo_opt()` function or method to just `foo`, remove the old `foo()` behavior, and tell people (through documentation) to use `foo().unwrap()` if they want it back? > > The downsides are that unwrap is more verbose and gives less helpful error messages on task failure. But I think it’s worth it. The email discussion has gone around long enough. Let’s discuss a concrete proposal. For the following functions or methods, I removed `foo` (that caused task failure) and renamed `foo_opt` (that returns `Option`) to just `foo`. Vector methods: * `get_opt` (rename only, `get` did not exist as it would have been just `[]`) * `head_opt` * `last_opt` * `pop_opt` * `shift_opt` * `remove_opt` `std::path::BytesContainer` method: * `container_as_str_opt` `std::str` functions: * `from_utf8_opt` * `from_utf8_owned_opt` (also remove the now unused `not_utf8` condition) Is there something else that should recieve the same treatement? I did not rename `recv_opt` on channels based on @brson’s [feedback](https://mail.mozilla.org/pipermail/rust-dev/2013-December/007270.html). Feel free to pick only some of these commits.
2 parents 505572b + ec422d7 commit 918a731

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

98 files changed

+398
-586
lines changed

src/compiletest/header.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,10 +159,10 @@ fn parse_exec_env(line: &str) -> Option<(~str, ~str)> {
159159
let mut strs: ~[~str] = nv.splitn('=', 1).map(|s| s.to_owned()).collect();
160160

161161
match strs.len() {
162-
1u => (strs.pop(), ~""),
162+
1u => (strs.pop().unwrap(), ~""),
163163
2u => {
164-
let end = strs.pop();
165-
(strs.pop(), end)
164+
let end = strs.pop().unwrap();
165+
(strs.pop().unwrap(), end)
166166
}
167167
n => fail!("Expected 1 or 2 strings, not {}", n)
168168
}

src/compiletest/procsrv.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ pub fn run(lib_path: &str,
6666

6767
Some(Result {
6868
status: status,
69-
out: str::from_utf8_owned(output),
70-
err: str::from_utf8_owned(error)
69+
out: str::from_utf8_owned(output).unwrap(),
70+
err: str::from_utf8_owned(error).unwrap()
7171
})
7272
},
7373
None => None

src/compiletest/runtest.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) {
154154
match props.pp_exact { Some(_) => 1, None => 2 };
155155

156156
let src = File::open(testfile).read_to_end();
157-
let src = str::from_utf8_owned(src);
157+
let src = str::from_utf8_owned(src).unwrap();
158158
let mut srcs = ~[src];
159159

160160
let mut round = 0;
@@ -176,7 +176,7 @@ fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) {
176176
Some(ref file) => {
177177
let filepath = testfile.dir_path().join(file);
178178
let s = File::open(&filepath).read_to_end();
179-
str::from_utf8_owned(s)
179+
str::from_utf8_owned(s).unwrap()
180180
}
181181
None => { srcs[srcs.len() - 2u].clone() }
182182
};
@@ -308,7 +308,7 @@ fn run_debuginfo_test(config: &config, props: &TestProps, testfile: &Path) {
308308

309309
let adb_arg = format!("export LD_LIBRARY_PATH={}; gdbserver :5039 {}/{}",
310310
config.adb_test_dir.clone(), config.adb_test_dir.clone(),
311-
str::from_utf8(exe_file.filename().unwrap()));
311+
str::from_utf8(exe_file.filename().unwrap()).unwrap());
312312

313313
let mut process = procsrv::run_background("", config.adb_path,
314314
[~"shell",adb_arg.clone()],
@@ -788,7 +788,7 @@ fn make_run_args(config: &config, _props: &TestProps, testfile: &Path) ->
788788
let exe_file = make_exe_name(config, testfile);
789789
// FIXME (#9639): This needs to handle non-utf8 paths
790790
args.push(exe_file.as_str().unwrap().to_owned());
791-
let prog = args.shift();
791+
let prog = args.shift().unwrap();
792792
return ProcArgs {prog: prog, args: args};
793793
}
794794
@@ -917,7 +917,7 @@ fn _arm_exec_compiled_test(config: &config, props: &TestProps,
917917

918918
// get bare program string
919919
let mut tvec: ~[~str] = args.prog.split('/').map(|ts| ts.to_owned()).collect();
920-
let prog_short = tvec.pop();
920+
let prog_short = tvec.pop().unwrap();
921921

922922
// copy to target
923923
let copy_result = procsrv::run("", config.adb_path,
@@ -1100,7 +1100,7 @@ fn disassemble_extract(config: &config, _props: &TestProps,
11001100

11011101
fn count_extracted_lines(p: &Path) -> uint {
11021102
let x = File::open(&p.with_extension("ll")).read_to_end();
1103-
let x = str::from_utf8_owned(x);
1103+
let x = str::from_utf8_owned(x).unwrap();
11041104
x.lines().len()
11051105
}
11061106

src/libextra/base64.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ impl<'a> FromBase64 for &'a str {
198198
* println!("base64 output: {}", hello_str);
199199
* let res = hello_str.from_base64();
200200
* if res.is_ok() {
201-
* let optBytes = str::from_utf8_owned_opt(res.unwrap());
201+
* let optBytes = str::from_utf8_owned(res.unwrap());
202202
* if optBytes.is_some() {
203203
* println!("decoded from base64: {}", optBytes.unwrap());
204204
* }

src/libextra/dlist.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,11 +1049,11 @@ mod tests {
10491049
match r % 6 {
10501050
0 => {
10511051
m.pop_back();
1052-
if v.len() > 0 { v.pop(); }
1052+
v.pop();
10531053
}
10541054
1 => {
10551055
m.pop_front();
1056-
if v.len() > 0 { v.shift(); }
1056+
v.shift();
10571057
}
10581058
2 | 4 => {
10591059
m.push_front(-i);

src/libextra/ebml.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ impl<'doc> Doc<'doc> {
3030
}
3131

3232
pub fn as_str_slice<'a>(&'a self) -> &'a str {
33-
str::from_utf8(self.data.slice(self.start, self.end))
33+
str::from_utf8(self.data.slice(self.start, self.end)).unwrap()
3434
}
3535

3636
pub fn as_str(&self) -> ~str {
@@ -651,7 +651,7 @@ pub mod writer {
651651
}
652652

653653
pub fn end_tag(&mut self) {
654-
let last_size_pos = self.size_positions.pop();
654+
let last_size_pos = self.size_positions.pop().unwrap();
655655
let cur_pos = self.writer.tell();
656656
self.writer.seek(last_size_pos as i64, io::SeekSet);
657657
let size = (cur_pos as uint - last_size_pos - 4);

src/libextra/glob.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ impl Iterator<Path> for Paths {
122122
return None;
123123
}
124124

125-
let (path,idx) = self.todo.pop();
125+
let (path,idx) = self.todo.pop().unwrap();
126126
let ref pattern = self.dir_patterns[idx];
127127

128128
if pattern.matches_with(match path.filename_str() {

src/libextra/hex.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ impl<'a> FromHex for &'a str {
9696
* println!("{}", hello_str);
9797
* let bytes = hello_str.from_hex().unwrap();
9898
* println!("{:?}", bytes);
99-
* let result_str = str::from_utf8_owned(bytes);
99+
* let result_str = str::from_utf8_owned(bytes).unwrap();
100100
* println!("{}", result_str);
101101
* }
102102
* ```

src/libextra/json.rs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ impl<'a> Encoder<'a> {
312312
/// Encode the specified struct into a json str
313313
pub fn str_encode<T:Encodable<Encoder<'a>>>(to_encode_object: &T) -> ~str {
314314
let buff:~[u8] = Encoder::buffer_encode(to_encode_object);
315-
str::from_utf8_owned(buff)
315+
str::from_utf8_owned(buff).unwrap()
316316
}
317317
}
318318

@@ -684,7 +684,7 @@ impl Json{
684684
pub fn to_pretty_str(&self) -> ~str {
685685
let mut s = MemWriter::new();
686686
self.to_pretty_writer(&mut s as &mut io::Writer);
687-
str::from_utf8_owned(s.unwrap())
687+
str::from_utf8_owned(s.unwrap()).unwrap()
688688
}
689689
}
690690

@@ -1028,7 +1028,7 @@ impl<T : Iterator<char>> Parser<T> {
10281028
while !self.eof() {
10291029
self.parse_whitespace();
10301030

1031-
if self.ch != '\"' {
1031+
if self.ch != '"' {
10321032
return self.error(~"key must be a string");
10331033
}
10341034

@@ -1067,7 +1067,7 @@ impl<T : Iterator<char>> Parser<T> {
10671067

10681068
/// Decodes a json value from an `&mut io::Reader`
10691069
pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, Error> {
1070-
let s = str::from_utf8_owned(rdr.read_to_end());
1070+
let s = str::from_utf8_owned(rdr.read_to_end()).unwrap();
10711071
let mut parser = Parser::new(s.chars());
10721072
parser.parse()
10731073
}
@@ -1117,7 +1117,7 @@ impl Decoder {
11171117
impl serialize::Decoder for Decoder {
11181118
fn read_nil(&mut self) -> () {
11191119
debug!("read_nil");
1120-
match self.stack.pop() {
1120+
match self.stack.pop().unwrap() {
11211121
Null => (),
11221122
value => self.expected("null", &value)
11231123
}
@@ -1137,15 +1137,15 @@ impl serialize::Decoder for Decoder {
11371137

11381138
fn read_bool(&mut self) -> bool {
11391139
debug!("read_bool");
1140-
match self.stack.pop() {
1140+
match self.stack.pop().unwrap() {
11411141
Boolean(b) => b,
11421142
value => self.expected("boolean", &value)
11431143
}
11441144
}
11451145

11461146
fn read_f64(&mut self) -> f64 {
11471147
debug!("read_f64");
1148-
match self.stack.pop() {
1148+
match self.stack.pop().unwrap() {
11491149
Number(f) => f,
11501150
value => self.expected("number", &value)
11511151
}
@@ -1168,7 +1168,7 @@ impl serialize::Decoder for Decoder {
11681168

11691169
fn read_str(&mut self) -> ~str {
11701170
debug!("read_str");
1171-
match self.stack.pop() {
1171+
match self.stack.pop().unwrap() {
11721172
String(s) => s,
11731173
value => self.expected("string", &value)
11741174
}
@@ -1184,7 +1184,7 @@ impl serialize::Decoder for Decoder {
11841184
f: |&mut Decoder, uint| -> T)
11851185
-> T {
11861186
debug!("read_enum_variant(names={:?})", names);
1187-
let name = match self.stack.pop() {
1187+
let name = match self.stack.pop().unwrap() {
11881188
String(s) => s,
11891189
Object(mut o) => {
11901190
let n = match o.pop(&~"variant") {
@@ -1249,7 +1249,7 @@ impl serialize::Decoder for Decoder {
12491249
-> T {
12501250
debug!("read_struct(name={}, len={})", name, len);
12511251
let value = f(self);
1252-
self.stack.pop();
1252+
self.stack.pop().unwrap();
12531253
value
12541254
}
12551255

@@ -1259,7 +1259,7 @@ impl serialize::Decoder for Decoder {
12591259
f: |&mut Decoder| -> T)
12601260
-> T {
12611261
debug!("read_struct_field(name={}, idx={})", name, idx);
1262-
match self.stack.pop() {
1262+
match self.stack.pop().unwrap() {
12631263
Object(mut obj) => {
12641264
let value = match obj.pop(&name.to_owned()) {
12651265
None => self.missing_field(name, obj),
@@ -1302,15 +1302,15 @@ impl serialize::Decoder for Decoder {
13021302
}
13031303

13041304
fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> T) -> T {
1305-
match self.stack.pop() {
1305+
match self.stack.pop().unwrap() {
13061306
Null => f(self, false),
13071307
value => { self.stack.push(value); f(self, true) }
13081308
}
13091309
}
13101310

13111311
fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> T) -> T {
13121312
debug!("read_seq()");
1313-
let len = match self.stack.pop() {
1313+
let len = match self.stack.pop().unwrap() {
13141314
List(list) => {
13151315
let len = list.len();
13161316
for v in list.move_rev_iter() {
@@ -1330,7 +1330,7 @@ impl serialize::Decoder for Decoder {
13301330

13311331
fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> T) -> T {
13321332
debug!("read_map()");
1333-
let len = match self.stack.pop() {
1333+
let len = match self.stack.pop().unwrap() {
13341334
Object(obj) => {
13351335
let len = obj.len();
13361336
for (key, value) in obj.move_iter() {
@@ -1541,7 +1541,7 @@ impl to_str::ToStr for Json {
15411541
fn to_str(&self) -> ~str {
15421542
let mut s = MemWriter::new();
15431543
self.to_writer(&mut s as &mut io::Writer);
1544-
str::from_utf8_owned(s.unwrap())
1544+
str::from_utf8_owned(s.unwrap()).unwrap()
15451545
}
15461546
}
15471547

@@ -1732,7 +1732,7 @@ mod tests {
17321732
17331733
let mut m = MemWriter::new();
17341734
f(&mut m as &mut io::Writer);
1735-
str::from_utf8_owned(m.unwrap())
1735+
str::from_utf8_owned(m.unwrap()).unwrap()
17361736
}
17371737
17381738
#[test]

src/libextra/num/bigint.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ impl Integer for BigUint {
385385
}
386386

387387
let mut shift = 0;
388-
let mut n = *other.data.last();
388+
let mut n = *other.data.last().unwrap();
389389
while n < (1 << BigDigit::bits - 2) {
390390
n <<= 1;
391391
shift += 1;
@@ -434,7 +434,7 @@ impl Integer for BigUint {
434434
}
435435

436436
let an = a.data.slice(a.data.len() - n, a.data.len());
437-
let bn = *b.data.last();
437+
let bn = *b.data.last().unwrap();
438438
let mut d = ~[];
439439
let mut carry = 0;
440440
for elt in an.rev_iter() {
@@ -798,7 +798,7 @@ impl BigUint {
798798
/// Determines the fewest bits necessary to express the `BigUint`.
799799
pub fn bits(&self) -> uint {
800800
if self.is_zero() { return 0; }
801-
let zeros = self.data.last().leading_zeros();
801+
let zeros = self.data.last().unwrap().leading_zeros();
802802
return self.data.len()*BigDigit::bits - (zeros as uint);
803803
}
804804
}

src/libextra/priority_queue.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ impl<T:Ord> PriorityQueue<T> {
5959

6060
/// Pop the greatest item from the queue - fails if empty
6161
pub fn pop(&mut self) -> T {
62-
let mut item = self.data.pop();
62+
let mut item = self.data.pop().unwrap();
6363
if !self.is_empty() {
6464
swap(&mut item, &mut self.data[0]);
6565
self.siftdown(0);
@@ -234,8 +234,8 @@ mod tests {
234234
sorted.sort();
235235
let mut heap = PriorityQueue::from_vec(data);
236236
while !heap.is_empty() {
237-
assert_eq!(heap.top(), sorted.last());
238-
assert_eq!(heap.pop(), sorted.pop());
237+
assert_eq!(heap.top(), sorted.last().unwrap());
238+
assert_eq!(heap.pop(), sorted.pop().unwrap());
239239
}
240240
}
241241

src/libextra/stats.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1001,7 +1001,7 @@ mod tests {
10011001
use std::io::MemWriter;
10021002
let mut m = MemWriter::new();
10031003
write_boxplot(&mut m as &mut io::Writer, s, 30);
1004-
let out = str::from_utf8_owned(m.unwrap());
1004+
let out = str::from_utf8_owned(m.unwrap()).unwrap();
10051005
assert_eq!(out, expected);
10061006
}
10071007

0 commit comments

Comments
 (0)