Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[storage] Add indexed access to StorageVec #165 #166

Merged
merged 3 commits into from
Sep 8, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/storage/storage_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ impl<T: Serialize, S: Storage> StorageVec<T, S> {
Ok(())
}

pub(crate) fn value(&mut self, index: u64) -> Result<T, DbError> {
if self.size <= index {
return Err(DbError::Storage("index out of bounds".to_string()));
}

self.storage
.borrow_mut()
.value_at::<T>(self.index, Self::value_offset(index))
}

fn reallocate(&mut self, new_capacity: u64) -> Result<(), DbError> {
self.capacity = new_capacity;
self.storage
Expand Down Expand Up @@ -81,4 +91,36 @@ mod tests {
Ok(vec![1_i64, 3_i64, 5_i64])
);
}

#[test]
fn value() {
let test_file = TestFile::from("./storage_vec-value.agdb");
let storage = std::rc::Rc::new(std::cell::RefCell::new(
FileStorage::try_from(test_file.file_name().clone()).unwrap(),
));

let mut vec = StorageVec::<i64>::try_from(storage).unwrap();
vec.push(&1).unwrap();
vec.push(&3).unwrap();
vec.push(&5).unwrap();

assert_eq!(vec.value(0), Ok(1));
assert_eq!(vec.value(1), Ok(3));
assert_eq!(vec.value(2), Ok(5));
}

#[test]
fn value_out_of_bounds() {
let test_file = TestFile::from("./storage_vec-value_out_of_bounds.agdb");
let storage = std::rc::Rc::new(std::cell::RefCell::new(
FileStorage::try_from(test_file.file_name().clone()).unwrap(),
));

let mut vec = StorageVec::<i64>::try_from(storage).unwrap();

assert_eq!(
vec.value(0),
Err(DbError::Storage("index out of bounds".to_string()))
);
}
}