Skip to content

Commit

Permalink
refactor: make segment trailer serializing less error prone
Browse files Browse the repository at this point in the history
  • Loading branch information
marvin-j97 committed Jun 9, 2024
1 parent 4a7368b commit 5fe6a5c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
26 changes: 25 additions & 1 deletion src/segment/file_offsets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::{Read, Write};

#[derive(Debug)]
#[derive(Debug, Default)]
pub struct FileOffsets {
pub index_block_ptr: u64,
pub tli_ptr: u64,
Expand All @@ -14,6 +14,14 @@ pub struct FileOffsets {
pub metadata_ptr: u64,
}

impl FileOffsets {
/// Returns the on-disk size
#[must_use]
pub const fn serialized_len() -> usize {
5 * std::mem::size_of::<u64>()
}
}

impl Serializable for FileOffsets {
fn serialize<W: Write>(&self, writer: &mut W) -> Result<(), SerializeError> {
writer.write_u64::<BigEndian>(self.index_block_ptr)?;
Expand Down Expand Up @@ -42,3 +50,19 @@ impl Deserializable for FileOffsets {
})
}
}

#[cfg(test)]
mod tests {
use super::*;
use test_log::test;

#[test]
fn file_offsets_serialized_len() -> crate::Result<()> {
let mut buf = vec![];
FileOffsets::default().serialize(&mut buf)?;

assert_eq!(FileOffsets::serialized_len(), buf.len());

Ok(())
}
}
3 changes: 1 addition & 2 deletions src/segment/trailer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ impl SegmentFileTrailer {
// Parse pointers
let offsets = FileOffsets::deserialize(&mut reader)?;

// IMPORTANT: sizeof(offsets) ---------v
let remaining_padding = TRAILER_SIZE - 5 * std::mem::size_of::<u64>() - TRAILER_MAGIC.len();
let remaining_padding = TRAILER_SIZE - FileOffsets::serialized_len() - TRAILER_MAGIC.len();
reader.seek_relative(remaining_padding as i64)?;

// Check trailer magic
Expand Down

0 comments on commit 5fe6a5c

Please sign in to comment.