Skip to content

Implement Index and IndexMut for Vec #15652

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 17, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/compiletest/compiletest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,9 @@ pub fn parse_config(args: Vec<String> ) -> Config {
optflag("h", "help", "show this message"));

assert!(!args.is_empty());
let argv0 = (*args.get(0)).clone();
let argv0 = args[0].clone();
let args_ = args.tail();
if args.get(1).as_slice() == "-h" || args.get(1).as_slice() == "--help" {
if args[1].as_slice() == "-h" || args[1].as_slice() == "--help" {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
println!("");
Expand All @@ -116,7 +116,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
}

let filter = if !matches.free.is_empty() {
let s = matches.free.get(0).as_slice();
let s = matches.free[0].as_slice();
match regex::Regex::new(s) {
Ok(re) => Some(re),
Err(e) => {
Expand Down
24 changes: 12 additions & 12 deletions src/compiletest/runtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
let proc_res = print_source(config,
props,
testfile,
(*srcs.get(round)).to_string(),
srcs[round].to_string(),
"normal");

if !proc_res.status.success() {
Expand All @@ -187,9 +187,9 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
let s = File::open(&filepath).read_to_end().unwrap();
String::from_utf8(s).unwrap()
}
None => { (*srcs.get(srcs.len() - 2u)).clone() }
None => { srcs[srcs.len() - 2u].clone() }
};
let mut actual = (*srcs.get(srcs.len() - 1u)).clone();
let mut actual = srcs[srcs.len() - 1u].clone();

if props.pp_exact.is_some() {
// Now we have to care about line endings
Expand All @@ -209,7 +209,7 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
if props.no_pretty_expanded { return }

// additionally, run `--pretty expanded` and try to build it.
let proc_res = print_source(config, props, testfile, (*srcs.get(round)).clone(), "expanded");
let proc_res = print_source(config, props, testfile, srcs[round].clone(), "expanded");
if !proc_res.status.success() {
fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
}
Expand Down Expand Up @@ -702,7 +702,7 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String])
let mut rest = line.trim();
let mut first = true;
let mut failed = false;
for frag in check_fragments.get(i).iter() {
for frag in check_fragments[i].iter() {
let found = if first {
if rest.starts_with(frag.as_slice()) {
Some(0)
Expand Down Expand Up @@ -752,7 +752,7 @@ fn check_error_patterns(props: &TestProps,
}

let mut next_err_idx = 0u;
let mut next_err_pat = props.error_patterns.get(next_err_idx);
let mut next_err_pat = &props.error_patterns[next_err_idx];
let mut done = false;
let output_to_check = if props.check_stdout {
format!("{}{}", proc_res.stdout, proc_res.stderr)
Expand All @@ -761,14 +761,14 @@ fn check_error_patterns(props: &TestProps,
};
for line in output_to_check.as_slice().lines() {
if line.contains(next_err_pat.as_slice()) {
debug!("found error pattern {}", *next_err_pat);
debug!("found error pattern {}", next_err_pat);
next_err_idx += 1u;
if next_err_idx == props.error_patterns.len() {
debug!("found all error patterns");
done = true;
break;
}
next_err_pat = props.error_patterns.get(next_err_idx);
next_err_pat = &props.error_patterns[next_err_idx];
}
}
if done { return; }
Expand Down Expand Up @@ -847,13 +847,13 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
for line in proc_res.stderr.as_slice().lines() {
let mut was_expected = false;
for (i, ee) in expected_errors.iter().enumerate() {
if !*found_flags.get(i) {
if !found_flags[i] {
debug!("prefix={} ee.kind={} ee.msg={} line={}",
prefixes.get(i).as_slice(),
prefixes[i].as_slice(),
ee.kind,
ee.msg,
line);
if prefix_matches(line, prefixes.get(i).as_slice()) &&
if prefix_matches(line, prefixes[i].as_slice()) &&
line.contains(ee.kind.as_slice()) &&
line.contains(ee.msg.as_slice()) {
*found_flags.get_mut(i) = true;
Expand All @@ -877,7 +877,7 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,

for (i, &flag) in found_flags.iter().enumerate() {
if !flag {
let ee = expected_errors.get(i);
let ee = &expected_errors[i];
fatal_proc_rec(format!("expected {} on line {} not found: {}",
ee.kind, ee.line, ee.msg).as_slice(),
proc_res);
Expand Down
14 changes: 7 additions & 7 deletions src/doc/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ fn main() {

spawn(proc() {
let numbers = rx.recv();
println!("{}", *numbers.get(0));
println!("{}", numbers[0]);
})
}
```
Expand Down Expand Up @@ -244,19 +244,19 @@ fn main() {

spawn(proc() {
let numbers = rx.recv();
println!("{}", numbers.get(0));
println!("{}", numbers[0]);
});

// Try to print a number from the original task
println!("{}", *numbers.get(0));
println!("{}", numbers[0]);
}
```

The compiler will produce an error indicating that the value is no longer in scope:

```text
concurrency.rs:12:20: 12:27 error: use of moved value: 'numbers'
concurrency.rs:12 println!("{}", numbers.get(0));
concurrency.rs:12 println!("{}", numbers[0]);
^~~~~~~
```

Expand All @@ -276,7 +276,7 @@ fn main() {

spawn(proc() {
let numbers = rx.recv();
println!("{:d}", *numbers.get(num as uint));
println!("{:d}", numbers[num as uint]);
})
}
}
Expand Down Expand Up @@ -309,7 +309,7 @@ fn main() {

spawn(proc() {
let numbers = rx.recv();
println!("{:d}", *numbers.get(num as uint));
println!("{:d}", (*numbers)[num as uint]);
})
}
}
Expand Down Expand Up @@ -364,7 +364,7 @@ fn main() {
// See: https://github.com/rust-lang/rust/issues/6515
*numbers.get_mut(num as uint) = *numbers.get_mut(num as uint) + 1;

println!("{}", *numbers.get(num as uint));
println!("{}", (*numbers)[num as uint]);

// When `numbers` goes out of scope the lock is dropped
})
Expand Down
2 changes: 1 addition & 1 deletion src/doc/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -2427,7 +2427,7 @@ as in this version of `print_all` that copies elements.
fn print_all<T: Printable + Clone>(printable_things: Vec<T>) {
let mut i = 0;
while i < printable_things.len() {
let copy_of_thing = printable_things.get(i).clone();
let copy_of_thing = printable_things[i].clone();
copy_of_thing.print();
i += 1;
}
Expand Down
33 changes: 32 additions & 1 deletion src/libcollections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub static PTR_MARKER: u8 = 0;
/// vec.push(2i);
///
/// assert_eq!(vec.len(), 2);
/// assert_eq!(vec.get(0), &1);
/// assert_eq!(vec[0], 1);
///
/// assert_eq!(vec.pop(), Some(2));
/// assert_eq!(vec.len(), 1);
Expand Down Expand Up @@ -363,6 +363,21 @@ impl<T:Clone> Clone for Vec<T> {
}
}

impl<T> Index<uint,T> for Vec<T> {
#[inline]
fn index<'a>(&'a self, index: &uint) -> &'a T {
self.get(*index)
}
}

// FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
/*impl<T> IndexMut<uint,T> for Vec<T> {
#[inline]
fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
self.get_mut(*index)
}
}*/

impl<T> FromIterator<T> for Vec<T> {
#[inline]
fn from_iter<I:Iterator<T>>(mut iterator: I) -> Vec<T> {
Expand Down Expand Up @@ -731,9 +746,12 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// #![allow(deprecated)]
///
/// let vec = vec!(1i, 2, 3);
/// assert!(vec.get(1) == &2);
/// ```
#[deprecated="prefer using indexing, e.g., vec[0]"]
#[inline]
pub fn get<'a>(&'a self, index: uint) -> &'a T {
&self.as_slice()[index]
Expand Down Expand Up @@ -1847,6 +1865,19 @@ mod tests {
v.truncate(0);
}

#[test]
fn test_index() {
let vec = vec!(1i, 2, 3);
assert!(vec[1] == 2);
}

#[test]
#[should_fail]
fn test_index_out_of_bounds() {
let vec = vec!(1i, 2, 3);
let _ = vec[3];
}

#[bench]
fn bench_new(b: &mut Bencher) {
b.iter(|| {
Expand Down
4 changes: 2 additions & 2 deletions src/libdebug/repr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> {
_offset: uint,
inner: *const TyDesc)
-> bool {
match *self.var_stk.get(self.var_stk.len() - 1) {
match self.var_stk[self.var_stk.len() - 1] {
Matched => {
if i != 0 {
try!(self, self.writer.write(", ".as_bytes()));
Expand All @@ -484,7 +484,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> {
_disr_val: Disr,
n_fields: uint,
_name: &str) -> bool {
match *self.var_stk.get(self.var_stk.len() - 1) {
match self.var_stk[self.var_stk.len() - 1] {
Matched => {
if n_fields > 0 {
try!(self, self.writer.write([')' as u8]));
Expand Down
34 changes: 17 additions & 17 deletions src/libgetopts/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
//! fn main() {
//! let args: Vec<String> = os::args();
//!
//! let program = args.get(0).clone();
//! let program = args[0].clone();
//!
//! let opts = [
//! optopt("o", "", "set output file name", "NAME"),
Expand All @@ -67,7 +67,7 @@
//! }
//! let output = matches.opt_str("o");
//! let input = if !matches.free.is_empty() {
//! (*matches.free.get(0)).clone()
//! matches.free[0].clone()
//! } else {
//! print_usage(program.as_slice(), opts);
//! return;
Expand Down Expand Up @@ -275,7 +275,7 @@ impl OptGroup {
impl Matches {
fn opt_vals(&self, nm: &str) -> Vec<Optval> {
match find_opt(self.opts.as_slice(), Name::from_str(nm)) {
Some(id) => (*self.vals.get(id)).clone(),
Some(id) => self.vals[id].clone(),
None => fail!("No option '{}' defined", nm)
}
}
Expand All @@ -285,7 +285,7 @@ impl Matches {
if vals.is_empty() {
None
} else {
Some((*vals.get(0)).clone())
Some(vals[0].clone())
}
}

Expand All @@ -304,7 +304,7 @@ impl Matches {
for nm in names.iter() {
match find_opt(self.opts.as_slice(),
Name::from_str(nm.as_slice())) {
Some(id) if !self.vals.get(id).is_empty() => return true,
Some(id) if !self.vals[id].is_empty() => return true,
_ => (),
};
}
Expand Down Expand Up @@ -344,8 +344,8 @@ impl Matches {
if vals.is_empty() {
return None::<String>;
}
match vals.get(0) {
&Val(ref s) => Some((*s).clone()),
match vals[0] {
Val(ref s) => Some((*s).clone()),
_ => None
}
}
Expand All @@ -361,8 +361,8 @@ impl Matches {
if vals.is_empty() {
return None;
}
match vals.get(0) {
&Val(ref s) => Some((*s).clone()),
match vals[0] {
Val(ref s) => Some((*s).clone()),
_ => Some(def.to_string())
}
}
Expand Down Expand Up @@ -560,8 +560,8 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
names = vec!(Long(tail.to_string()));
} else {
names =
vec!(Long((*tail_eq.get(0)).to_string()));
i_arg = Some((*tail_eq.get(1)).to_string());
vec!(Long(tail_eq[0].to_string()));
i_arg = Some(tail_eq[1].to_string());
}
} else {
let mut j = 1;
Expand All @@ -583,7 +583,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
None => {
let arg_follows =
last_valid_opt_id.is_some() &&
match opts.get(last_valid_opt_id.unwrap())
match opts[last_valid_opt_id.unwrap()]
.hasarg {

Yes | Maybe => true,
Expand All @@ -609,7 +609,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
Some(id) => id,
None => return Err(UnrecognizedOption(nm.to_string()))
};
match opts.get(optid).hasarg {
match opts[optid].hasarg {
No => {
if !i_arg.is_none() {
return Err(UnexpectedArgument(nm.to_string()));
Expand Down Expand Up @@ -646,16 +646,16 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
}
i = 0u;
while i < n_opts {
let n = vals.get(i).len();
let occ = opts.get(i).occur;
let n = vals[i].len();
let occ = opts[i].occur;
if occ == Req {
if n == 0 {
return Err(OptionMissing(opts.get(i).name.to_string()));
return Err(OptionMissing(opts[i].name.to_string()));
}
}
if occ != Multi {
if n > 1 {
return Err(OptionDuplicated(opts.get(i).name.to_string()));
return Err(OptionDuplicated(opts[i].name.to_string()));
}
}
i += 1;
Expand Down
Loading