Skip to content

Commit

Permalink
Fix and add tests for negative slices #52
Browse files Browse the repository at this point in the history
  • Loading branch information
mverleg committed Jun 1, 2018
1 parent a60d144 commit cab34ba
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/mango/util/strslice/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,28 @@ pub fn charslice<S: Into<String>>(text: S, start: isize, end: isize) -> String {
let stext = text.into();
let from: usize;
let length: usize;
let charcount = stext.chars().count();
if start < 0 {
// LATER: may remove this check and just default to 0 in the future.
assert!(
-start as usize <= stext.len(),
-start as usize <= charcount,
"charslice: if 'start' is negative, the magnitude may not exceed the length"
);
// TODO: off by one?
from = (stext.len() as isize + start) as usize;
println!(
">> charcount as isize + start = {} + {}",
charcount as isize, start
);
from = (charcount as isize + start) as usize;
} else {
from = start as usize;
}
if end < 0 {
// LATER: may remove this check and just default to 0 in the future.
assert!(
-end as usize <= stext.len(),
-end as usize <= charcount,
"charslice: if 'end' is negative, the magnitude may not exceed the length"
);
// TODO: off by one?
let new_end = (stext.len() as isize + end) as usize;
let new_end = (charcount as isize + end) as usize;
assert!(
new_end >= from,
"charslice: 'start' may not be before 'end' (end was positive)"
Expand All @@ -36,12 +39,13 @@ pub fn charslice<S: Into<String>>(text: S, start: isize, end: isize) -> String {
);
length = end as usize - from;
}
println!("from: {}, length: {}", from, length);
stext.chars().skip(from).take(length).collect()
}

pub fn charslicefrom<S: Into<String>>(text: S, start: isize) -> String {
let stext = text.into();
let len = stext.len() as isize;
let len = stext.chars().count() as isize;
charslice(stext, start, len)
}

Expand All @@ -59,6 +63,9 @@ mod tests {
assert_eq!("你好", charslice("你好!", 0, 2));
assert_eq!("!", charslicefrom("你好!", 2));
assert_eq!("你好", charsliceto("你好!", 2));
// TODO: test negative values
// Negative indices should match Python 3 behaviour:
assert_eq!("你好", charslice("你好!", -3, -1));
assert_eq!("!", charslicefrom("你好!", -1));
assert_eq!("你好", charsliceto("你好!", -1));
}
}

0 comments on commit cab34ba

Please sign in to comment.