From 656834ca4cdf69df5be76fd2d1a33b78920affa3 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 21 Nov 2016 15:43:20 -0800 Subject: [PATCH] Don't go out of bounds when slicing (fixes #241) --- src/lib.rs | 2 +- src/slicing.rs | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5d9de6809..89e08c3c2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -498,7 +498,7 @@ impl Url { /// as is typically the case of `data:` and `mailto:` URLs. #[inline] pub fn cannot_be_a_base(&self) -> bool { - self.byte_at(self.path_start) != b'/' + !self.slice(self.path_start..).starts_with('/') } /// Return the username for this URL (typically the empty string) diff --git a/src/slicing.rs b/src/slicing.rs index 926f3c796..32b7a6f1c 100644 --- a/src/slicing.rs +++ b/src/slicing.rs @@ -26,14 +26,14 @@ impl Index> for Url { impl Index> for Url { type Output = str; fn index(&self, range: RangeTo) -> &str { - &self.serialization[..self.index(range.end)] + &self.serialization[..self.clamp(self.index(range.end))] } } impl Index> for Url { type Output = str; fn index(&self, range: Range) -> &str { - &self.serialization[self.index(range.start)..self.index(range.end)] + &self.serialization[self.index(range.start)..self.clamp(self.index(range.end))] } } @@ -98,6 +98,19 @@ pub enum Position { } impl Url { + #[inline] + fn clamp(&self, index: usize) -> usize { + if index >= self.serialization.len() { + if self.serialization.len() == 0 { + 0 + } else { + self.serialization.len() - 1 + } + } else { + index + } + } + #[inline] fn index(&self, position: Position) -> usize { match position {