85 lines
2.2 KiB
Rust
85 lines
2.2 KiB
Rust
use std::fmt;
|
|
|
|
use crate::sharry;
|
|
|
|
pub struct Chunk<'t> {
|
|
file_id: sharry::FileID,
|
|
offset: u64,
|
|
data: &'t [u8],
|
|
}
|
|
|
|
impl fmt::Debug for Chunk<'_> {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.debug_struct("Chunk")
|
|
.field("file_id", &self.file_id)
|
|
.field("offset", &self.offset)
|
|
.field("data.len()", &self.data.len())
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
impl<'t> Chunk<'t> {
|
|
pub(super) fn new_direct(file_id: sharry::FileID, offset: u64, data: &'t [u8]) -> Self {
|
|
Self {
|
|
file_id,
|
|
offset,
|
|
data,
|
|
}
|
|
}
|
|
|
|
/// get a reference to the associated `file_id`
|
|
pub fn get_file_id(&self) -> &sharry::FileID {
|
|
&self.file_id
|
|
}
|
|
|
|
/// get the chunk's offset
|
|
pub fn get_offset(&self) -> u64 {
|
|
self.offset
|
|
}
|
|
|
|
/// get a reference to the associated data
|
|
pub fn get_data(&self) -> &[u8] {
|
|
self.data
|
|
}
|
|
|
|
/// get the chunk's length
|
|
pub fn get_length(&self) -> u64 {
|
|
let len = self.data.len();
|
|
|
|
// BOOKMARK this might **panic** on platforms where `usize` has more than 64 bit.
|
|
// Also, you've allocated more than 2 EiB ... in ONE chunk.
|
|
// Whoa! Maybe just chill?
|
|
u64::try_from(len).unwrap_or_else(|e| panic!("usize={len} did not fit into u64: {e}"))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use crate::test_util::{
|
|
check_trait,
|
|
data::{DATA_LENGTHS_BAD, cases_with},
|
|
};
|
|
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn basic_tests() {
|
|
for (data, len, mock_offset) in cases_with(DATA_LENGTHS_BAD) {
|
|
let fid = sharry::FileID::default();
|
|
let chunk = Chunk::new_direct(fid, mock_offset, data);
|
|
|
|
let repr_expect = format!(
|
|
"Chunk {{ file_id: {:?}, offset: {:?}, data.len(): {:?}, .. }}",
|
|
chunk.file_id,
|
|
chunk.offset,
|
|
chunk.data.len()
|
|
);
|
|
check_trait(format!("{chunk:?}"), repr_expect, "Debug", "Chunk");
|
|
|
|
assert_eq!(chunk.get_file_id().to_string(), "fid");
|
|
assert_eq!(chunk.get_offset(), mock_offset);
|
|
assert_eq!(chunk.get_data(), data);
|
|
assert_eq!(chunk.get_length(), len);
|
|
}
|
|
}
|
|
}
|