Skip to content

Commit

Permalink
Improve reader api [#14 #5]
Browse files Browse the repository at this point in the history
  • Loading branch information
cuichenli authored and marceloboeira committed May 31, 2019
1 parent 6be624e commit 554c51e
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
24 changes: 24 additions & 0 deletions commit_log/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
extern crate memmap;
mod segment;
mod position;
mod record;

use self::segment::Segment;
use position::Position;
use record::Record;

use std::fs;
use std::io::{Error, ErrorKind};
Expand Down Expand Up @@ -53,6 +57,9 @@ pub struct CommitLog {

/// List of segments
segments: Vec<Segment>, //TODO if too many Segments are created, and not "garbage collected", we have too many files opened

/// Current segment index
current_segment: usize
}

impl CommitLog {
Expand All @@ -68,6 +75,7 @@ impl CommitLog {
segments: segments,
segment_size: segment_size,
index_size: index_size,
current_segment: 0
})
}

Expand Down Expand Up @@ -95,6 +103,22 @@ impl CommitLog {
self.segments[segment_index].read_at(offset)
}

pub fn read_after(&mut self, position: Position, mut offset: usize) -> Result<Record, Error> {
let current_pos = match position {
Position::Horizontal => 1,
Position::Offset(offset) => offset
};
offset += current_pos;

return Record::new(&mut self.segments[self.current_segment], offset);
}


pub fn read(&mut self, position: Position) -> Result<Record, Error> {
return self.read_after(position, 0);
}


fn rotate_segment(&mut self) -> Result<(), Error> {
let next_offset = self.segments.len();

Expand Down
4 changes: 4 additions & 0 deletions commit_log/src/position.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub enum Position {
Horizontal,
Offset(usize)
}
38 changes: 38 additions & 0 deletions commit_log/src/record.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@

use super::segment::Segment;
use super::position::Position;
use std::io::Error;

pub struct Record<'a> {
current_offset: usize,

segment: &'a mut Segment,
}

impl<'a> Record<'a> {
pub fn new(segment: &'a mut Segment, offset: usize) -> Result<Self, Error>{
Ok(Self {
current_offset: offset,
segment: segment
})
}

pub fn record(&mut self) -> Result<&[u8], Error> {
self.segment.read_at(self.current_offset)
}

pub fn position(&self) -> Position {
Position::Offset(self.current_offset)
}

pub fn record_after(&'a mut self, offset: usize) -> Self {
Self {
segment: self.segment,
current_offset: self.current_offset + offset
}
}

pub fn next(&'a mut self) -> Self {
self.record_after(1)
}
}

0 comments on commit 554c51e

Please sign in to comment.