From 735013cc4634e2cd05c096db08f0405b0432e286 Mon Sep 17 00:00:00 2001 From: Yury Vostrikov Date: Sun, 21 Jun 2020 12:12:50 +0200 Subject: [PATCH] Fix overly cautious assert in Index> and IndexMut> It is perfectly legal to have std::ops::Range with a start equal an end. The length of such range is zero. Example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3ccc1c83e2e26352a6b0cdc815f23ad4 While empty slice might be looking useless, it helps to avoid special-casing in code like this: for x in &vec[start..end] { ... } --- src/trait_impls.rs | 4 ++-- test/test_staticvec.rs | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/trait_impls.rs b/src/trait_impls.rs index f951327..b1663c9 100644 --- a/src/trait_impls.rs +++ b/src/trait_impls.rs @@ -516,7 +516,7 @@ impl Index> for StaticVec { /// and if so returns a constant reference to a slice of elements `index.start..index.end`. #[inline(always)] fn index(&self, index: Range) -> &Self::Output { - assert!(index.start < index.end && index.end <= self.length); + assert!(index.start <= index.end && index.end <= self.length); slice_from_raw_parts( unsafe { self.ptr_at_unchecked(index.start) }, index.end - index.start, @@ -530,7 +530,7 @@ impl IndexMut> for StaticVec { /// and if so returns a mutable reference to a slice of elements `index.start..index.end`. #[inline(always)] fn index_mut(&mut self, index: Range) -> &mut Self::Output { - assert!(index.start < index.end && index.end <= self.length); + assert!(index.start <= index.end && index.end <= self.length); slice_from_raw_parts_mut( unsafe { self.mut_ptr_at_unchecked(index.start) }, index.end - index.start, diff --git a/test/test_staticvec.rs b/test/test_staticvec.rs index f75b4f1..bd482c9 100644 --- a/test/test_staticvec.rs +++ b/test/test_staticvec.rs @@ -2052,6 +2052,15 @@ fn try_push() { assert_eq!(vec2, [1, 2, 3, 3]); } +#[test] +fn empty_slice() { + let mut vec = staticvec![1, 2, 3, 4, 5]; + let s = &vec[0..0]; + assert_eq!(0, s.len()); + let s = &mut vec[0..0]; + assert_eq!(0, s.len()); +} + /* #[test] fn union() {