Skip to content

Commit

Permalink
fix: small rust review
Browse files Browse the repository at this point in the history
  • Loading branch information
Manuthor committed Jul 15, 2024
1 parent 0bef16a commit d6352d9
Show file tree
Hide file tree
Showing 12 changed files with 41 additions and 45 deletions.
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -118,20 +118,20 @@ repos:
args: [--skip-string-normalization]

- repo: https://github.com/Cosmian/git-hooks.git
rev: v1.0.16
rev: v1.0.26
hooks:
- id: stable-cargo-format
- id: cargo-upgrade
- id: cargo-update
- id: cargo-machete
- id: cargo-outdated
- id: cargo-udeps
- id: cargo-tests-all
- id: cargo-test-doc
- id: clippy-autofix-all
- id: clippy-autofix-pedantic
- id: clippy-autofix-others
- id: clippy-autofix-unreachable-pub
- id: clippy-autofix-nursery
- id: clippy-all-targets-all-features
- id: cargo-tests-all
- id: cargo-test-doc
- id: stable-cargo-format
- id: cargo-dry-publish
args: [--allow-dirty]
21 changes: 8 additions & 13 deletions benches/benches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn make_scale(start: usize, stop: usize, n: usize) -> Vec<f32> {
let step = ((stop - start) as f32) / n as f32;
let mut points = Vec::with_capacity(n);
for i in 0..=n {
points.push(start as f32 + i as f32 * step);
points.push((i as f32).mul_add(step, start as f32));
}
points
}
Expand Down Expand Up @@ -56,16 +56,11 @@ fn bench_search_multiple_bindings(c: &mut Criterion) {
let seed = Secret::random(&mut rng);
let stm = KvStore::default();
let index = build_benchmarking_bindings_index(&mut rng);
let findex = Findex::new(
seed.clone(),
stm,
dummy_encode::<WORD_LENGTH, _>,
dummy_decode,
);
let findex = Findex::new(seed, stm, dummy_encode::<WORD_LENGTH, _>, dummy_decode);
block_on(findex.insert(index.clone().into_iter())).unwrap();

let mut group = c.benchmark_group("Multiple bindings search (1 keyword)");
for (kw, vals) in index.clone().into_iter() {
for (kw, vals) in index {
group.bench_function(BenchmarkId::from_parameter(vals.len()), |b| {
b.iter_batched(
|| {
Expand Down Expand Up @@ -127,7 +122,7 @@ fn bench_search_multiple_keywords(c: &mut Criterion) {
findex.clear();
// Using .cloned() instead of .clone() reduces the overhead (maybe because it
// only clones what is needed)
index.iter().map(|(kw, _)| kw).take(n).cloned()
index.iter().map(|(kw, _)| kw).take(n).copied()
},
|kws| {
block_on(findex.search(kws)).expect("search failed");
Expand All @@ -149,7 +144,7 @@ fn bench_insert_multiple_bindings(c: &mut Criterion) {
// Reference: write one word per value inserted.
{
let mut group = c.benchmark_group("write n words to memory");
for (_, vals) in index.clone().into_iter() {
for (_, vals) in index.clone() {
let stm = KvStore::with_capacity(n_max + 1);
group
.bench_function(BenchmarkId::from_parameter(vals.len()), |b| {
Expand Down Expand Up @@ -177,7 +172,7 @@ fn bench_insert_multiple_bindings(c: &mut Criterion) {
// Bench it
{
let mut group = c.benchmark_group("Multiple bindings insert (same keyword)");
for (kw, vals) in index.clone().into_iter() {
for (kw, vals) in index {
let stm = KvStore::with_capacity(n_max + 1);
let findex = Findex::new(
seed.clone(),
Expand Down Expand Up @@ -329,7 +324,7 @@ fn bench_contention(c: &mut Criterion) {
runtime.block_on(async {
join_all(iterator.map(|(findex, binding)| {
tokio::spawn(async move {
findex.insert([binding].into_iter()).await
findex.insert(std::iter::once(binding)).await
})
}))
.await
Expand Down Expand Up @@ -381,7 +376,7 @@ fn bench_contention(c: &mut Criterion) {
runtime.block_on(async {
join_all(iterator.map(|(findex, binding)| {
tokio::spawn(async move {
findex.insert([binding].into_iter()).await
findex.insert(std::iter::once(binding)).await
})
}))
.await
Expand Down
4 changes: 2 additions & 2 deletions src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl<const LENGTH: usize> Address<LENGTH> {
}

impl<const LENGTH: usize> Add<u64> for Address<LENGTH> {
type Output = Address<LENGTH>;
type Output = Self;

/// Highly inefficient implementation of an add modulo 2^8^LENGTH in little endian.
fn add(mut self, mut adder: u64) -> Self::Output {
Expand All @@ -45,7 +45,7 @@ impl<const LENGTH: usize> Add<u64> for Address<LENGTH> {
// add bytes
let lhs = &mut self[pos % LENGTH];
let rhs = adder % 256;
let res = *lhs as i32 + rhs as i32 + carry;
let res = i32::from(*lhs) + rhs as i32 + carry;

// update states
*lhs = (res % 256) as u8;
Expand Down
12 changes: 6 additions & 6 deletions src/adt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub trait IndexADT<Keyword: Send + Sync + Hash, Value: Send + Sync + Hash> {
) -> impl Send + Sync + Future<Output = Result<(), Self::Error>>;
}

pub trait VectorADT: Send + Sync {
pub(crate) trait VectorADT: Send + Sync {
/// Vectors are homogeneous.
type Value: Send + Sync;

Expand Down Expand Up @@ -82,17 +82,17 @@ pub trait MemoryADT {
#[cfg(test)]
pub(crate) mod tests {

pub use vector::*;
pub(crate) use vector::*;

mod vector {
//! This module defines tests any implementation of the VectorADT interface must pass.
//! This module defines tests any implementation of the `VectorADT` interface must pass.

use crate::adt::VectorADT;
use futures::{executor::block_on, future::join_all};

/// Adding information from different copies of the same vector should be visible by all
/// copies.
pub async fn test_vector_sequential<const LENGTH: usize>(
pub(crate) async fn test_vector_sequential<const LENGTH: usize>(
v: &(impl Clone + VectorADT<Value = [u8; LENGTH]>),
) {
let mut v1 = v.clone();
Expand All @@ -109,7 +109,7 @@ pub(crate) mod tests {
}

/// Concurrently adding data to instances of the same vector should not introduce data loss.
pub async fn test_vector_concurrent<
pub(crate) async fn test_vector_concurrent<
const LENGTH: usize,
V: 'static + Clone + VectorADT<Value = [u8; LENGTH]>,
>(
Expand All @@ -135,7 +135,7 @@ pub(crate) mod tests {
}
let mut res = block_on(v.read()).unwrap();
let old = res.clone();
res.sort();
res.sort_unstable();
assert_ne!(old, res);
assert_eq!(res.len(), n * m);
assert_eq!(res, values);
Expand Down
8 changes: 4 additions & 4 deletions src/encoding.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! This module defines encoding operations that are used to serialize an operation.
//! Currently, the only supported operations are the insertion and deletion, but there is no
//! theorical restriction on the kind of operation that can be used.
//! theoretical restriction on the kind of operation that can be used.

#![allow(dead_code)]

Expand All @@ -12,7 +12,7 @@ pub enum Op {
Delete,
}

pub enum Mode {
pub(crate) enum Mode {
EqBlock(usize),
Offset(usize),
}
Expand Down Expand Up @@ -54,7 +54,7 @@ mod one_byte_metadata_uid_optimized {
//! - in the block mode, they designate the block-length (2 bits) of the values stored in this
//! word, and the number of such values stored in this word (3 bits).

use super::*;
use super::{HashSet, Op, Ordering};

/// Blocks are the smallest unit size in block mode, 16 bytes is optimized to store UUIDs.
const BLOCK_LENGTH: usize = 16;
Expand Down Expand Up @@ -98,7 +98,7 @@ pub fn dummy_encode<const WORD_LENGTH: usize, Value: AsRef<[u8]>>(
let bytes = v.as_ref();
if WORD_LENGTH - 2 < bytes.len() {
return Err(format!(
"unsufficient bytes in a word to fit a value of length {}",
"insufficient bytes in a word to fit a value of length {}",
bytes.len(),
));
}
Expand Down
2 changes: 1 addition & 1 deletion src/encryption_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,6 @@ mod tests {
val_addr_4
]))
.unwrap()
)
);
}
}
2 changes: 1 addition & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub enum Error<Address: Debug, MemoryError: std::error::Error> {

impl<Address: Debug, MemoryError: std::error::Error> Display for Error<Address, MemoryError> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
write!(f, "{self:?}")
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/findex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ where
let bindings = bindings
.map(|(kw, vals)| (self.encode)(op, vals).map(|words| (kw, words)))
.collect::<Result<Vec<_>, String>>()
.map_err(|e| Error::<_, Memory::Error>::Conversion(e.to_string()))?;
.map_err(Error::<_, Memory::Error>::Conversion)?;

let futures = bindings
.into_iter()
Expand Down Expand Up @@ -251,11 +251,11 @@ mod tests {
),
]);
block_on(findex.insert(bindings.clone().into_iter())).unwrap();
let res = block_on(findex.search(bindings.keys().cloned())).unwrap();
let res = block_on(findex.search(bindings.keys().copied())).unwrap();
assert_eq!(bindings, res);

block_on(findex.delete(bindings.clone().into_iter())).unwrap();
let res = block_on(findex.search(bindings.keys().cloned())).unwrap();
let res = block_on(findex.search(bindings.keys().copied())).unwrap();
assert_eq!(
HashMap::from_iter([("cat", HashSet::new()), ("dog", HashSet::new())]),
res
Expand Down
3 changes: 2 additions & 1 deletion src/kv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ impl<Address: Hash + Eq + Debug, Value: Clone + Eq + Debug> Default for KvStore<

impl<Address: Hash + Eq + Debug, Value: Clone + Eq + Debug> KvStore<Address, Value> {
#[cfg(feature = "bench")]
#[must_use]
pub fn with_capacity(c: usize) -> Self {
Self {
inner: Arc::new(Mutex::new(HashMap::with_capacity(c))),
Expand Down Expand Up @@ -123,6 +124,6 @@ mod tests {
assert_eq!(
vec![Some(1), Some(1), Some(3), Some(3)],
block_on(kv.batch_read(vec![1, 2, 3, 4])).unwrap(),
)
);
}
}
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@ pub use kv::KvStore;
/// mitigated by marking n bit of the addresses, allowing to statistically store up to 2^((64-n)/2)
/// keywords, and reducing the number of words that can be used to store associated values to
/// sqrt(2^64 - 2^n).
#[cfg(not(feature = "small"))]
pub const ADDRESS_LENGTH: usize = 16;
#[cfg(feature = "small")]
pub const ADDRESS_LENGTH: usize = 16;

/// Using 32-byte cryptographic keys allow achieving post-quantum resistance if the adequate
Expand Down
11 changes: 7 additions & 4 deletions src/ovec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
//! following invariant:
//!
//! > I_v: the value of the counter stored at the vector address is equal to the number of values
//! stored in this vector; these values are of homogeneous type and stored in contiguous
//! memory words.
//! > stored in this vector; these values are of homogeneous type and stored in contiguous
//! > memory words.
//!
//! This implementation is based on the assumption that an infinite array starting at the vector's
//! address has been allocated, and thus stores values after the header:
Expand Down Expand Up @@ -67,7 +67,10 @@ impl TryFrom<&[u8]> for Header {

/// Implementation of a vector in an infinite array.
#[derive(Debug)]
pub struct IVec<const WORD_LENGTH: usize, Memory: Clone + MemoryADT<Word = [u8; WORD_LENGTH]>> {
pub(crate) struct IVec<
const WORD_LENGTH: usize,
Memory: Clone + MemoryADT<Word = [u8; WORD_LENGTH]>,
> {
// backing array address
a: Memory::Address,
// cached header value
Expand Down Expand Up @@ -98,7 +101,7 @@ impl<
{
/// (Lazily) instantiates a new vector at this address in this memory: no value is written
/// before the first push.
pub fn new(a: Address, m: Memory) -> Self {
pub(crate) const fn new(a: Address, m: Memory) -> Self {
Self { a, h: None, m }
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl From<Vec<u8>> for Value {

impl From<&Value> for Vec<u8> {
fn from(value: &Value) -> Self {
value.0.to_vec()
value.0.clone()
}
}

Expand All @@ -48,7 +48,7 @@ impl TryFrom<Value> for String {
type Error = FromUtf8Error;

fn try_from(value: Value) -> Result<Self, Self::Error> {
String::from_utf8(value.0)
Self::from_utf8(value.0)
}
}

Expand Down

0 comments on commit d6352d9

Please sign in to comment.