Skip to content

Commit

Permalink
chore: optimize the magic number to Option and extract common code
Browse files Browse the repository at this point in the history
  • Loading branch information
1996fanrui committed Aug 10, 2024
1 parent a2d0b27 commit a599e65
Showing 1 changed file with 9 additions and 19 deletions.
28 changes: 9 additions & 19 deletions src/append/rolling_file/rolling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ struct State {
current_date: OffsetDateTime,
current_count: usize,
current_filesize: usize,
next_date: usize,
next_date_timestamp: Option<usize>,
max_size: usize,
max_files: Option<usize>,
}
Expand All @@ -183,10 +183,7 @@ impl State {
) -> anyhow::Result<(Self, RwLock<File>)> {
let log_dir = dir.as_ref().to_path_buf();
let date_format = rotation.date_format();
let next_date = rotation
.next_date(&now)
.map(|date| date.unix_timestamp() as usize)
.unwrap_or(0);
let next_date_timestamp = rotation.next_date_timestamp(&now);

let current_date = now;
let current_count = 0;
Expand All @@ -200,7 +197,7 @@ impl State {
current_date,
current_count,
current_filesize,
next_date,
next_date_timestamp,
rotation,
max_size,
max_files,
Expand Down Expand Up @@ -320,12 +317,9 @@ impl State {
}

fn should_rollover_on_date(&self, date: OffsetDateTime) -> bool {
let next_date = self.next_date;
if next_date == 0 {
false
} else {
date.unix_timestamp() as usize >= next_date
}
self.next_date_timestamp
.map(|ts| date.unix_timestamp() as usize >= ts)
.unwrap_or(false)
}

fn should_rollover_on_size(&self) -> bool {
Expand All @@ -342,11 +336,7 @@ impl State {
self.current_date = now;
self.current_count = 0;
self.current_filesize = 0;
self.next_date = self
.rotation
.next_date(&now)
.map(|date| date.unix_timestamp() as usize)
.unwrap_or(0);
self.next_date_timestamp = self.rotation.next_date_timestamp(&now);
}
}

Expand All @@ -364,15 +354,15 @@ pub enum Rotation {
}

impl Rotation {
fn next_date(&self, current_date: &OffsetDateTime) -> Option<OffsetDateTime> {
fn next_date_timestamp(&self, current_date: &OffsetDateTime) -> Option<usize> {
let next_date = match *self {
Rotation::Minutely => *current_date + Duration::minutes(1),
Rotation::Hourly => *current_date + Duration::hours(1),
Rotation::Daily => *current_date + Duration::days(1),
Rotation::Never => return None,
};

Some(self.round_date(&next_date))
Some(self.round_date(&next_date).unix_timestamp() as usize)
}

fn round_date(&self, date: &OffsetDateTime) -> OffsetDateTime {
Expand Down

0 comments on commit a599e65

Please sign in to comment.