optimize increment

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-06-25 01:31:52 +00:00
parent 3480074f61
commit c1712d4d8b
3 changed files with 48 additions and 12 deletions

View file

@ -6,6 +6,7 @@ pub mod html;
pub mod json; pub mod json;
pub mod mutex_map; pub mod mutex_map;
pub mod sys; pub mod sys;
mod tests;
use std::{ use std::{
cmp::{self, Ordering}, cmp::{self, Ordering},
@ -34,16 +35,14 @@ pub fn millis_since_unix_epoch() -> u64 {
.as_millis() as u64 .as_millis() as u64
} }
pub fn increment(old: Option<&[u8]>) -> Vec<u8> { #[inline]
let number = match old.map(TryInto::try_into) { #[must_use]
Some(Ok(bytes)) => { pub fn increment(old: Option<&[u8]>) -> [u8; 8] {
let number = u64::from_be_bytes(bytes); const ZERO: u64 = 0;
number + 1 old.map(TryInto::try_into)
}, .map_or(ZERO, |val| val.map_or(ZERO, u64::from_be_bytes))
_ => 1, // Start at one. since 0 should return the first event in the db .wrapping_add(1)
}; .to_be_bytes()
number.to_be_bytes().to_vec()
} }
#[must_use] #[must_use]

37
src/core/utils/tests.rs Normal file
View file

@ -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);
}

View file

@ -155,13 +155,13 @@ impl KvTree for RocksDbEngineTree<'_> {
let new = utils::increment(old.as_deref()); let new = utils::increment(old.as_deref());
self.db self.db
.rocks .rocks
.put_cf_opt(&self.cf(), key, &new, &writeoptions)?; .put_cf_opt(&self.cf(), key, new, &writeoptions)?;
if !self.db.corked() { if !self.db.corked() {
self.db.flush()?; self.db.flush()?;
} }
Ok(new) Ok(new.to_vec())
} }
fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> { fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {