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 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<u8> {
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]

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());
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<Item = Vec<u8>>) -> Result<()> {