Skip to content

Commit

Permalink
[storage] Add value() to FileStorage #79 (#80)
Browse files Browse the repository at this point in the history
* Update file_record.rs

* Update file_storage.rs

* Update file_storage.rs
  • Loading branch information
michaelvlach authored Aug 23, 2022
1 parent 7483d53 commit 434c64a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/storage/file_record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ pub(crate) struct FileRecord {
pub(crate) size: u64,
}

#[allow(dead_code)]
impl FileRecord {
pub(crate) const fn size() -> usize {
size_of::<i64>() + size_of::<u64>()
}
}

impl Serialize for FileRecord {
fn deserialize(bytes: &[u8]) -> Self {
const SIZE_OFFSET: usize = size_of::<i64>();
Expand Down Expand Up @@ -65,4 +72,9 @@ mod tests {

assert_eq!(record, actual_record);
}

#[test]
fn size() {
assert_eq!(FileRecord::size(), size_of::<i64>() + size_of::<u64>());
}
}
32 changes: 32 additions & 0 deletions src/storage/file_storage.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use super::file_record::FileRecord;
use super::file_records::FileRecords;
use super::serialize::Serialize;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Write;
use std::io::{Seek, SeekFrom};

Expand All @@ -22,6 +24,19 @@ impl FileStorage {
self.file.write_all(&bytes).unwrap();
record.index
}

pub(crate) fn value<T: Serialize>(&mut self, index: i64) -> Option<T> {
if let Some(record) = self.records.get(index) {
self.file
.seek(SeekFrom::Start(record.position + FileRecord::size() as u64))
.unwrap();
let mut bytes: Vec<u8> = vec![0; record.size as usize];
self.file.read_exact(&mut bytes).unwrap();
return Some(T::deserialize(&bytes));
}

None
}
}

impl From<&str> for FileStorage {
Expand Down Expand Up @@ -77,4 +92,21 @@ mod tests {

assert_eq!(index, 0);
}

#[test]
fn value() {
let test_file = TestFile::from("./file_storage_test03.agdb");
let mut storage = FileStorage::from(test_file.file_name().clone());

let index = storage.insert(&10_i64);

assert_eq!(storage.value::<i64>(index), Some(10_i64));
}

#[test]
fn value_of_missing_index() {
let test_file = TestFile::from("./file_storage_test03.agdb");
let mut storage = FileStorage::from(test_file.file_name().clone());
assert_eq!(storage.value::<i64>(0), None);
}
}

0 comments on commit 434c64a

Please sign in to comment.