From c1712d4d8b57407493651ca10aa8f65624036b23 Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Tue, 25 Jun 2024 01:31:52 +0000 Subject: [PATCH] optimize increment Signed-off-by: Jason Volk --- src/core/utils/mod.rs | 19 +++++++++-------- src/core/utils/tests.rs | 37 ++++++++++++++++++++++++++++++++++ src/database/rocksdb/kvtree.rs | 4 ++-- 3 files changed, 48 insertions(+), 12 deletions(-) create mode 100644 src/core/utils/tests.rs diff --git a/src/core/utils/mod.rs b/src/core/utils/mod.rs index 27d47fa5..1e0e01c0 100644 --- a/src/core/utils/mod.rs +++ b/src/core/utils/mod.rs @@ -6,6 +6,7 @@ pub mod html; pub mod json; pub mod mutex_map; pub mod sys; +mod tests; use std::{ cmp::{self, Ordering}, @@ -34,16 +35,14 @@ pub fn millis_since_unix_epoch() -> u64 { .as_millis() as u64 } -pub fn increment(old: Option<&[u8]>) -> Vec { - let number = match old.map(TryInto::try_into) { - Some(Ok(bytes)) => { - let number = u64::from_be_bytes(bytes); - number + 1 - }, - _ => 1, // Start at one. since 0 should return the first event in the db - }; - - number.to_be_bytes().to_vec() +#[inline] +#[must_use] +pub fn increment(old: Option<&[u8]>) -> [u8; 8] { + const ZERO: u64 = 0; + old.map(TryInto::try_into) + .map_or(ZERO, |val| val.map_or(ZERO, u64::from_be_bytes)) + .wrapping_add(1) + .to_be_bytes() } #[must_use] diff --git a/src/core/utils/tests.rs b/src/core/utils/tests.rs new file mode 100644 index 00000000..b226bd41 --- /dev/null +++ b/src/core/utils/tests.rs @@ -0,0 +1,37 @@ +#![cfg(test)] + +use crate::utils; + +#[test] +fn increment_none() { + let bytes: [u8; 8] = utils::increment(None); + let res = u64::from_be_bytes(bytes); + assert_eq!(res, 1); +} + +#[test] +fn increment_fault() { + let start: u8 = 127; + let bytes: [u8; 1] = start.to_be_bytes(); + let bytes: [u8; 8] = utils::increment(Some(&bytes)); + let res = u64::from_be_bytes(bytes); + assert_eq!(res, 1); +} + +#[test] +fn increment_norm() { + let start: u64 = 1_234_567; + let bytes: [u8; 8] = start.to_be_bytes(); + let bytes: [u8; 8] = utils::increment(Some(&bytes)); + let res = u64::from_be_bytes(bytes); + assert_eq!(res, 1_234_568); +} + +#[test] +fn increment_wrap() { + let start = u64::MAX; + let bytes: [u8; 8] = start.to_be_bytes(); + let bytes: [u8; 8] = utils::increment(Some(&bytes)); + let res = u64::from_be_bytes(bytes); + assert_eq!(res, 0); +} diff --git a/src/database/rocksdb/kvtree.rs b/src/database/rocksdb/kvtree.rs index 00d01f8e..253b10c6 100644 --- a/src/database/rocksdb/kvtree.rs +++ b/src/database/rocksdb/kvtree.rs @@ -155,13 +155,13 @@ impl KvTree for RocksDbEngineTree<'_> { let new = utils::increment(old.as_deref()); self.db .rocks - .put_cf_opt(&self.cf(), key, &new, &writeoptions)?; + .put_cf_opt(&self.cf(), key, new, &writeoptions)?; if !self.db.corked() { self.db.flush()?; } - Ok(new) + Ok(new.to_vec()) } fn increment_batch(&self, iter: &mut dyn Iterator>) -> Result<()> {