From cab34baeeb77dc0075efaf294b30985ef74af081 Mon Sep 17 00:00:00 2001 From: Mark Date: Fri, 1 Jun 2018 23:32:33 +0200 Subject: [PATCH] Fix and add tests for negative slices #52 --- src/mango/util/strslice/slice.rs | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/mango/util/strslice/slice.rs b/src/mango/util/strslice/slice.rs index 97bb04e7..88eea284 100644 --- a/src/mango/util/strslice/slice.rs +++ b/src/mango/util/strslice/slice.rs @@ -5,25 +5,28 @@ pub fn charslice>(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)" @@ -36,12 +39,13 @@ pub fn charslice>(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>(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) } @@ -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)); } }