Skip to content

Commit

Permalink
Don't go out of bounds when slicing
Browse files Browse the repository at this point in the history
  • Loading branch information
Manishearth committed Nov 21, 2016
1 parent 1be1b3b commit 6efdb97
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
17 changes: 15 additions & 2 deletions src/slicing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ impl Index<RangeFrom<Position>> for Url {
impl Index<RangeTo<Position>> for Url {
type Output = str;
fn index(&self, range: RangeTo<Position>) -> &str {
&self.serialization[..self.index(range.end)]
&self.serialization[..self.clamp(self.index(range.end))]
}
}

impl Index<Range<Position>> for Url {
type Output = str;
fn index(&self, range: Range<Position>) -> &str {
&self.serialization[self.index(range.start)..self.index(range.end)]
&self.serialization[self.index(range.start)..self.clamp(self.index(range.end))]
}
}

Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 6efdb97

Please sign in to comment.