Skip to content

Commit

Permalink
Do not panic in Row::try_read
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanUkhov committed Apr 24, 2024
1 parent eab53c3 commit e2254c7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
28 changes: 15 additions & 13 deletions src/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub struct Row {
}

/// A type suitable for indexing columns in a row.
pub trait RowIndex: std::fmt::Debug {
pub trait RowIndex: std::fmt::Debug + std::fmt::Display {
/// Check if the index is present in a row.
fn contains(&self, row: &Row) -> bool;

Expand Down Expand Up @@ -181,6 +181,9 @@ impl Row {
T: TryFrom<&'l Value, Error = Error>,
U: RowIndex,
{
if !column.contains(self) {
raise!("the index is out of range ({column})");
}
T::try_from(&self.values[column.index(self)])
}
}
Expand All @@ -205,29 +208,28 @@ where

impl RowIndex for &str {
#[inline]
fn index(self, row: &Row) -> usize {
debug_assert!(
row.column_mapping.contains_key(self),
"the index is out of range",
);
row.column_mapping[self]
}

fn contains(&self, row: &Row) -> bool {
row.column_mapping.contains_key(*self)
}
}

impl RowIndex for usize {
#[inline]
fn index(self, row: &Row) -> usize {
debug_assert!(self < row.values.len(), "the index is out of range");
self
debug_assert!(RowIndex::contains(&self, row), "the index is out of range");
row.column_mapping[self]
}
}

impl RowIndex for usize {
#[inline]
fn contains(&self, row: &Row) -> bool {
self < &row.values.len()
}

#[inline]
fn index(self, row: &Row) -> usize {
debug_assert!(RowIndex::contains(&self, row), "the index is out of range");
self
}
}

pub fn new<'l, 'm>(statement: &'m mut Statement<'l>) -> Cursor<'l, 'm> {
Expand Down
10 changes: 10 additions & 0 deletions tests/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,16 @@ fn next_try_read_with_index() {
assert!(row.try_read::<&str, _>(4).is_err());
}

#[test]
fn next_try_read_with_index_out_of_range() {
let connection = setup_users(":memory:");
let query = "SELECT * FROM users";
let mut statement = ok!(connection.prepare(query));

let row = ok!(ok!(statement.iter().next()));
assert!(row.try_read::<&str, _>(5).is_err());
}

#[test]
fn next_try_read_with_index_and_option() {
let connection = setup_users(":memory:");
Expand Down

0 comments on commit e2254c7

Please sign in to comment.