diff --git a/src/core/utils/mod.rs b/src/core/utils/mod.rs index 27d47fa54ae8b5c645df036af5509bf7a30f8f6b..1e0e01c090416b01bb4dbf4f5563730d4d0b2f31 100644 --- a/src/core/utils/mod.rs +++ b/src/core/utils/mod.rs @@ -6,6 +6,7 @@ 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] diff --git a/src/core/utils/tests.rs b/src/core/utils/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..b226bd411bee5605f501ad46a85b5ec03c6c7bec --- /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 00d01f8edac36a2fda6f6e4e1fe22afd5861ecc4..253b10c63147982f16659edbc6c85ed1c1c8744e 100644 --- a/src/database/rocksdb/kvtree.rs +++ b/src/database/rocksdb/kvtree.rs @@ -155,13 +155,13 @@ fn increment(&self, key: &[u8]) -> Result<Vec<u8>> { 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<()> {