From 936ae9b200514dadb23a35faeb50a388d6615ba9 Mon Sep 17 00:00:00 2001 From: Manuthor Date: Mon, 2 Dec 2024 09:41:11 +0100 Subject: [PATCH] fix: cargo deny + lints --- .github/workflows/benches.yml | 2 +- .pre-commit-config.yaml | 29 ++-- Cargo.toml | 23 ++- benches/benches.rs | 23 +-- benches/make_figures.tex | 16 +- deny.toml | 257 +++++++++++++++++++++++++++- docker-compose.yml | 6 + examples/insert.rs | 4 +- rust-toolchain.toml | 3 + src/address.rs | 7 +- src/adt.rs | 14 +- src/encoding.rs | 4 +- src/encryption_layer.rs | 2 +- src/error.rs | 2 +- src/findex.rs | 14 +- src/lib.rs | 2 - src/memory/db_stores/error.rs | 12 +- src/memory/db_stores/mod.rs | 2 +- src/memory/db_stores/redis_store.rs | 15 +- src/memory/mod.rs | 4 +- src/ovec.rs | 11 +- src/secret.rs | 5 +- src/symmetric_key.rs | 6 +- src/test/memory.rs | 13 +- src/test/mod.rs | 2 +- src/value.rs | 4 +- 26 files changed, 379 insertions(+), 103 deletions(-) create mode 100644 docker-compose.yml create mode 100644 rust-toolchain.toml diff --git a/.github/workflows/benches.yml b/.github/workflows/benches.yml index ccd97357..9283f448 100644 --- a/.github/workflows/benches.yml +++ b/.github/workflows/benches.yml @@ -1,7 +1,7 @@ --- name: Benches -on: [workflow_dispatch, pull_request, push] +on: [workflow_dispatch] jobs: bench: diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cb973a0e..ab8be692 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -7,7 +7,7 @@ # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks -exclude: datasets|tests_data|documentation/Findex.pdf|tests/first_names.txt +exclude: datasets|tests_data|documentation/Findex.pdf|tests/first_names.txt|benches/data repos: - repo: https://github.com/compilerla/conventional-pre-commit rev: v2.1.1 @@ -118,20 +118,27 @@ repos: args: [--skip-string-normalization] - repo: https://github.com/Cosmian/git-hooks.git - rev: v1.0.16 + rev: v1.0.32 hooks: - - id: stable-cargo-format - - id: cargo-upgrade - - id: cargo-update + - id: cargo-format + # - id: cargo-upgrade + # - id: cargo-update - id: cargo-machete - - id: cargo-outdated - - id: cargo-udeps + - id: docker-compose-up - 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-all-targets-all-features + - id: clippy-autofix-all-targets - id: clippy-all-targets-all-features - - id: stable-cargo-format + - id: clippy-all-targets + - id: cargo-format - id: cargo-dry-publish args: [--allow-dirty] + - id: docker-compose-down + + - repo: https://github.com/EmbarkStudios/cargo-deny + rev: 0.16.1 # choose your preferred tag + hooks: + - id: cargo-deny + args: [--all-features, check] diff --git a/Cargo.toml b/Cargo.toml index 0f7a1eaf..043817bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,23 @@ [package] -name = "findex" -version = "0.1.0" +name = "cosmian_findex" +version = "7.0.0" +authors = [ + "Chloé Hébant ", + "Bruno Grieder ", + "Célia Corsin ", + "Emmanuel Coste ", + "Théophile Brézot ", +] +categories = ["cosmian::crypto"] edition = "2021" +keywords = ["SSE"] +license = "BUSL-1.1" +repository = "https://github.com/Cosmian/findex/" +description = "Symmetric Searchable Encryption" + +[lib] +name = "cosmian_findex" +path = "src/lib.rs" [features] bench = [] @@ -23,12 +39,11 @@ redis = { version = "0.27.5", features = [ "tokio-comp", "connection-manager", ], optional = true } -cosmian_crypto_core = "9.6.1" [dev-dependencies] criterion = "0.5.1" serial_test = "3.2.0" -futures = "0.3.30" +futures = "0.3.31" lazy_static = "1.5.0" tokio = { version = "1.38.0", features = [ "rt", diff --git a/benches/benches.rs b/benches/benches.rs index eed0face..407858c0 100644 --- a/benches/benches.rs +++ b/benches/benches.rs @@ -1,9 +1,9 @@ use std::{collections::HashSet, time::Duration}; +use cosmian_findex::{Findex, InMemory, IndexADT, MemoryADT, Op, Secret, WORD_LENGTH}; +#[cfg(feature = "test-utils")] +use cosmian_findex::{dummy_decode, dummy_encode}; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; -use findex::{ - Findex, InMemory, IndexADT, MemoryADT, Op, Secret, WORD_LENGTH, dummy_decode, dummy_encode, -}; use futures::{executor::block_on, future::join_all}; use lazy_static::lazy_static; use rand_chacha::ChaChaRng; @@ -17,7 +17,7 @@ fn make_scale(start: usize, stop: usize, n: usize) -> Vec { 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 } @@ -58,16 +58,11 @@ fn bench_search_multiple_bindings(c: &mut Criterion) { let seed = Secret::random(&mut rng); let stm = InMemory::default(); let index = build_benchmarking_bindings_index(&mut rng); - let findex = Findex::new( - seed.clone(), - stm, - dummy_encode::, - dummy_decode, - ); + let findex = Findex::new(seed, stm, dummy_encode::, 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( || { @@ -129,7 +124,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"); @@ -151,7 +146,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 = InMemory::with_capacity(n_max + 1); group .bench_function(BenchmarkId::from_parameter(vals.len()), |b| { @@ -179,7 +174,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 = InMemory::with_capacity(n_max + 1); let findex = Findex::new( seed.clone(), diff --git a/benches/make_figures.tex b/benches/make_figures.tex index cffbd0c0..2cfe64ee 100644 --- a/benches/make_figures.tex +++ b/benches/make_figures.tex @@ -17,10 +17,10 @@ \addplot[color=red] table [y={create col/linear regression}] {./data/search.dat}; \addlegendentry{search-time(\#bindings)} \addlegendentry{ - $ y = - \pgfmathprintnumber{\pgfplotstableregressiona} - \cdot b - \pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$ + $ y = + \pgfmathprintnumber{\pgfplotstableregressiona} + \cdot b + \pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$ } \end{axis} \end{tikzpicture} @@ -36,10 +36,10 @@ \addplot[color=red] table [y={create col/linear regression}] {./data/insert.dat}; \addlegendentry{insertion-time(\#bindings)} \addlegendentry{ - $ y = - \pgfmathprintnumber{\pgfplotstableregressiona} - \cdot b - \pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$ + $ y = + \pgfmathprintnumber{\pgfplotstableregressiona} + \cdot b + \pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$ } \end{axis} \end{tikzpicture} diff --git a/deny.toml b/deny.toml index d42cb4f8..1dd1bc2d 100644 --- a/deny.toml +++ b/deny.toml @@ -1 +1,256 @@ -ignore = [{ id = "RUSTSEC-2023-0071", reason = "rsa" }] +# This template contains all of the possible sections and their default values + +# Note that all fields that take a lint level have these possible values: +# * deny - An error will be produced and the check will fail +# * warn - A warning will be produced, but the check will not fail +# * allow - No warning or error will be produced, though in some cases a note +# will be + +# The values provided in this template are the default values that will be used +# when any section or field is not specified in your own configuration + +# Root options + +# The graph table configures how the dependency graph is constructed and thus +# which crates the checks are performed against +[graph] +# If 1 or more target triples (and optionally, target_features) are specified, +# only the specified targets will be checked when running `cargo deny check`. +# This means, if a particular package is only ever used as a target specific +# dependency, such as, for example, the `nix` crate only being used via the +# `target_family = "unix"` configuration, that only having windows targets in +# this list would mean the nix crate, as well as any of its exclusive +# dependencies not shared by any other crates, would be ignored, as the target +# list here is effectively saying which targets you are building for. +targets = [ + + + # The triple can be any string, but only the target triples built in to + # rustc (as of 1.40) can be checked against actual config expressions + # "x86_64-unknown-linux-musl", + # You can also specify which target_features you promise are enabled for a + # particular target. target_features are currently not validated against + # the actual valid features supported by the target architecture. + # { triple = "wasm32-unknown-unknown", features = ["atomics"] }, +] +# When creating the dependency graph used as the source of truth when checks are +# executed, this field can be used to prune crates from the graph, removing them +# from the view of cargo-deny. This is an extremely heavy hammer, as if a crate +# is pruned from the graph, all of its dependencies will also be pruned unless +# they are connected to another crate in the graph that hasn't been pruned, +# so it should be used with care. The identifiers are [Package ID Specifications] +# (https://doc.rust-lang.org/cargo/reference/pkgid-spec.html) +# exclude = [] +# If true, metadata will be collected with `--all-features`. Note that this can't +# be toggled off if true, if you want to conditionally enable `--all-features` it +# is recommended to pass `--all-features` on the cmd line instead +all-features = true +# If true, metadata will be collected with `--no-default-features`. The same +# caveat with `all-features` applies +no-default-features = false +# If set, these feature will be enabled when collecting metadata. If `--features` +# is specified on the cmd line they will take precedence over this option. +# features = [] + +# The output table provides options for how/if diagnostics are outputted +[output] +# When outputting inclusion graphs in diagnostics that include features, this +# option can be used to specify the depth at which feature edges will be added. +# This option is included since the graphs can be quite large and the addition +# of features from the crate(s) to all of the graph roots can be far too verbose. +# This option can be overridden via `--feature-depth` on the cmd line +feature-depth = 1 + +# This section is considered when running `cargo deny check advisories` +# More documentation for the advisories section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html +[advisories] +# The path where the advisory databases are cloned/fetched into +# db-path = "$CARGO_HOME/advisory-dbs" +# The url(s) of the advisory databases to use +# db-urls = ["https://github.com/rustsec/advisory-db"] +# A list of advisory IDs to ignore. Note that ignored advisories will still +# output a note when they are encountered. +ignore = [ + # { id = "RUSTSEC-2023-0071", reason = "rsa" }, + # { id = "RUSTSEC-0000-0000", reason = "you can specify a reason the advisory is ignored" }, + # "a-crate-that-is-yanked@0.1.1", # you can also ignore yanked crate versions if you wish + # { crate = "a-crate-that-is-yanked@0.1.1", reason = "you can specify why you are ignoring the yanked crate" }, +] +# If this is true, then cargo deny will use the git executable to fetch advisory database. +# If this is false, then it uses a built-in git library. +# Setting this to true can be helpful if you have special authentication requirements that cargo-deny does not support. +# See Git Authentication for more information about setting up git authentication. +# git-fetch-with-cli = true + +# This section is considered when running `cargo deny check licenses` +# More documentation for the licenses section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/licenses/cfg.html +[licenses] +# List of explicitly allowed licenses +# See https://spdx.org/licenses/ for list of possible licenses +# [possible values: any SPDX 3.11 short identifier (+ optional exception)]. +allow = [ + "MIT", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "Zlib", + "BSD-2-Clause", + "BSD-3-Clause", + "Unicode-DFS-2016", + "BUSL-1.1", + "CC0-1.0", + "Unicode-3.0" +] +# The confidence threshold for detecting a license from license text. +# The higher the value, the more closely the license text must be to the +# canonical license text of a valid SPDX license file. +# [possible values: any between 0.0 and 1.0]. +confidence-threshold = 0.8 +# Allow 1 or more licenses on a per-crate basis, so that particular licenses +# aren't accepted for every possible crate as with the normal allow list +exceptions = [ + + + # Each entry is the crate and version constraint, and its specific allow + # list + # { allow = ["Zlib"], crate = "adler32" }, +] + +# Some crates don't have (easily) machine readable licensing information, +# adding a clarification entry for it allows you to manually specify the +# licensing information +[[licenses.clarify]] +# The package spec the clarification applies to +crate = "ring" +# The SPDX expression for the license requirements of the crate +expression = "MIT AND ISC AND OpenSSL" +# One or more files in the crate's source used as the "source of truth" for +# the license expression. If the contents match, the clarification will be used +# when running the license check, otherwise the clarification will be ignored +# and the crate will be checked normally, which may produce warnings or errors +# depending on the rest of your configuration +license-files = [ + # Each entry is a crate relative path, and the (opaque) hash of its contents + { path = "LICENSE", hash = 0xbd0eed23 }, +] + +[licenses.private] +# If true, ignores workspace crates that aren't published, or are only +# published to private registries. +# To see how to mark a crate as unpublished (to the official registry), +# visit https://doc.rust-lang.org/cargo/reference/manifest.html#the-publish-field. +ignore = false +# One or more private registries that you might publish crates to, if a crate +# is only published to private registries, and ignore is true, the crate will +# not have its license(s) checked +registries = [ + + + # "https://sekretz.com/registry +] + +# This section is considered when running `cargo deny check bans`. +# More documentation about the 'bans' section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html +[bans] +# Lint level for when multiple versions of the same crate are detected +multiple-versions = "warn" +# Lint level for when a crate version requirement is `*` +wildcards = "allow" +# The graph highlighting used when creating dotgraphs for crates +# with multiple versions +# * lowest-version - The path to the lowest versioned duplicate is highlighted +# * simplest-path - The path to the version with the fewest edges is highlighted +# * all - Both lowest-version and simplest-path are used +highlight = "all" +# The default lint level for `default` features for crates that are members of +# the workspace that is being checked. This can be overridden by allowing/denying +# `default` on a crate-by-crate basis if desired. +workspace-default-features = "allow" +# The default lint level for `default` features for external crates that are not +# members of the workspace. This can be overridden by allowing/denying `default` +# on a crate-by-crate basis if desired. +external-default-features = "allow" +# List of crates that are allowed. Use with care! +allow = [ + + + # "ansi_term@0.11.0", + # { crate = "ansi_term@0.11.0", reason = "you can specify a reason it is allowed" }, +] +# List of crates to deny +deny = [ + + + # "ansi_term@0.11.0", + # { crate = "ansi_term@0.11.0", reason = "you can specify a reason it is banned" }, + # Wrapper crates can optionally be specified to allow the crate when it + # is a direct dependency of the otherwise banned crate + # { crate = "ansi_term@0.11.0", wrappers = ["this-crate-directly-depends-on-ansi_term"] }, +] + +# List of features to allow/deny +# Each entry the name of a crate and a version range. If version is +# not specified, all versions will be matched. +# [[bans.features]] +# crate = "reqwest" +# Features to not allow +# deny = ["json"] +# Features to allow +# allow = [ +# "rustls", +# "__rustls", +# "__tls", +# "hyper-rustls", +# "rustls", +# "rustls-pemfile", +# "rustls-tls-webpki-roots", +# "tokio-rustls", +# "webpki-roots", +# ] +# If true, the allowed features must exactly match the enabled feature set. If +# this is set there is no point setting `deny` +# exact = true + +# Certain crates/versions that will be skipped when doing duplicate detection. +skip = [ + + + # "ansi_term@0.11.0", + # { crate = "ansi_term@0.11.0", reason = "you can specify a reason why it can't be updated/removed" }, +] +# Similarly to `skip` allows you to skip certain crates during duplicate +# detection. Unlike skip, it also includes the entire tree of transitive +# dependencies starting at the specified crate, up to a certain depth, which is +# by default infinite. +skip-tree = [ + + + # "ansi_term@0.11.0", # will be skipped along with _all_ of its direct and transitive dependencies + # { crate = "ansi_term@0.11.0", depth = 20 }, +] + +# This section is considered when running `cargo deny check sources`. +# More documentation about the 'sources' section can be found here: +# https://embarkstudios.github.io/cargo-deny/checks/sources/cfg.html +[sources] +# Lint level for what to happen when a crate from a crate registry that is not +# in the allow list is encountered +unknown-registry = "warn" +# Lint level for what to happen when a crate from a git repository that is not +# in the allow list is encountered +unknown-git = "warn" +# List of URLs for allowed crate registries. Defaults to the crates.io index +# if not specified. If it is specified but empty, no registries are allowed. +allow-registry = ["https://github.com/rust-lang/crates.io-index"] +# List of URLs for allowed Git repositories +allow-git = [] + +[sources.allow-org] +# # 1 or more github.com organizations to allow git sources for +# github = [""] +# # 1 or more gitlab.com organizations to allow git sources for +# gitlab = [""] +# # 1 or more bitbucket.org organizations to allow git sources for +# bitbucket = [""] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..cb24f9e8 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,6 @@ +--- +services: + redis: + image: redis:latest + ports: + - 6379:6379 diff --git a/examples/insert.rs b/examples/insert.rs index cb5fd993..ebb1b78d 100644 --- a/examples/insert.rs +++ b/examples/insert.rs @@ -1,6 +1,8 @@ use std::collections::HashSet; -use findex::{Findex, InMemory, IndexADT, Secret, Value, dummy_decode, dummy_encode}; +use cosmian_findex::{Findex, InMemory, IndexADT, Secret, Value}; +#[cfg(feature = "test-utils")] +use cosmian_findex::{dummy_decode, dummy_encode}; use futures::executor::block_on; use rand_chacha::ChaChaRng; use rand_core::{CryptoRngCore, SeedableRng}; diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 00000000..26baec7e --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.83.0" +components = ["rustfmt"] diff --git a/src/address.rs b/src/address.rs index 05d66693..93e2e854 100644 --- a/src/address.rs +++ b/src/address.rs @@ -47,7 +47,7 @@ impl Address { } impl Add for Address { - type Output = Address; + type Output = Self; /// Highly inefficient implementation of an add modulo 2^8^LENGTH in little /// endian. @@ -58,7 +58,7 @@ impl Add for Address { // 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; @@ -95,6 +95,7 @@ mod tests { assert_eq!(229 + 100 - 256, 73); // there will be a carry assert_eq!(Address([100, 10]) + 4325, Address([73, 27])); - assert_eq!(Address([0, 0]) + (1 << 16), Address([0, 0])); // 2^16 is the neutral element + // 2^16 is the neutral element + assert_eq!(Address([0, 0]) + (1 << 16), Address([0, 0])); } } diff --git a/src/adt.rs b/src/adt.rs index 8e83517e..931017ef 100644 --- a/src/adt.rs +++ b/src/adt.rs @@ -37,7 +37,7 @@ pub trait IndexADT { ) -> impl Send + Future>; } -pub trait VectorADT: Send + Sync { +pub(crate) trait VectorADT: Send + Sync { /// Vectors are homogeneous. type Value: Send + Sync; @@ -84,10 +84,10 @@ 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 + //! This module defines tests any implementation of the `VectorADT` //! interface must pass. use std::thread::spawn; @@ -98,7 +98,7 @@ pub(crate) mod tests { /// Adding information from different copies of the same vector should /// be visible by all copies. - pub async fn test_vector_sequential( + pub(crate) async fn test_vector_sequential( v: &(impl Clone + VectorADT), ) { let mut v1 = v.clone(); @@ -116,7 +116,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, >( @@ -138,10 +138,10 @@ pub(crate) mod tests { }) .collect::>(); for h in handles { - let _ = h.join().unwrap().await; + let () = h.join().unwrap().await; } let mut res = block_on(v.read()).unwrap(); - res.sort(); + res.sort_unstable(); assert_eq!(res.len(), n * m); assert_eq!(res, values); } diff --git a/src/encoding.rs b/src/encoding.rs index 5bc9403f..5b58bcd7 100644 --- a/src/encoding.rs +++ b/src/encoding.rs @@ -13,7 +13,7 @@ pub enum Op { Delete, } -pub enum Mode { +pub(crate) enum Mode { EqBlock(usize), Offset(usize), } @@ -32,7 +32,7 @@ pub fn dummy_encode>( vs: HashSet, ) -> Result, String> { if (u8::MAX as usize) < WORD_LENGTH { - return Err("WORD_LENGTH too big for this encoding".to_string()); + return Err("WORD_LENGTH too big for this encoding".to_owned()); } vs.into_iter() diff --git a/src/encryption_layer.rs b/src/encryption_layer.rs index ac083629..1aa695a6 100644 --- a/src/encryption_layer.rs +++ b/src/encryption_layer.rs @@ -239,6 +239,6 @@ mod tests { val_addr_4 ])) .unwrap() - ) + ); } } diff --git a/src/error.rs b/src/error.rs index ffc8abd8..34bd3a75 100644 --- a/src/error.rs +++ b/src/error.rs @@ -11,7 +11,7 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/src/findex.rs b/src/findex.rs index 47c85f40..a02719a7 100644 --- a/src/findex.rs +++ b/src/findex.rs @@ -1,3 +1,5 @@ +#![allow(clippy::type_complexity)] + use std::{ collections::{HashMap, HashSet}, hash::Hash, @@ -120,7 +122,7 @@ where let bindings = bindings .map(|(kw, vals)| (self.encode)(op, vals).map(|words| (kw, words))) .collect::, String>>() - .map_err(|e| Error::<_, Memory::Error>::Conversion(e.to_string()))?; + .map_err(Error::<_, Memory::Error>::Conversion)?; let futures = bindings .into_iter() @@ -251,11 +253,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 @@ -267,7 +269,7 @@ mod tests { if let Ok(var_env) = std::env::var("REDIS_HOST") { format!("redis://{var_env}:6379") } else { - "redis://localhost:6379".to_string() + "redis://localhost:6379".to_owned() } } @@ -296,11 +298,11 @@ mod tests { ), ]); findex.insert(bindings.clone().into_iter()).await.unwrap(); // using block_on here causes a never ending execution - let res = findex.search(bindings.keys().cloned()).await.unwrap(); + let res = findex.search(bindings.keys().copied()).await.unwrap(); assert_eq!(bindings, res); findex.delete(bindings.clone().into_iter()).await.unwrap(); - let res = findex.search(bindings.keys().cloned()).await.unwrap(); + let res = findex.search(bindings.keys().copied()).await.unwrap(); assert_eq!( HashMap::from_iter([("cat", HashSet::new()), ("dog", HashSet::new())]), res diff --git a/src/lib.rs b/src/lib.rs index 41a59d4a..dc3879c0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,3 @@ -#![allow(clippy::type_complexity)] - mod address; mod adt; mod encoding; diff --git a/src/memory/db_stores/error.rs b/src/memory/db_stores/error.rs index 5c805cab..3990d044 100644 --- a/src/memory/db_stores/error.rs +++ b/src/memory/db_stores/error.rs @@ -1,8 +1,6 @@ use core::fmt::Display; use std::num::TryFromIntError; -use cosmian_crypto_core::CryptoCoreError; - #[cfg(feature = "redis-store")] use super::redis_store::RedisStoreError; use crate::{Address, error::Error as FindexCoreError}; @@ -13,11 +11,10 @@ macro_rules! findex_core_error { }; } #[derive(Debug)] -pub enum DbStoreError { +pub(crate) enum DbStoreError { #[cfg(feature = "redis-store")] Redis(RedisStoreError), Findex(findex_core_error!()), - CryptoCore(CryptoCoreError), IntConversion(TryFromIntError), Io(std::io::Error), } @@ -27,7 +24,6 @@ impl Display for DbStoreError { match self { #[cfg(feature = "redis-store")] Self::Redis(err) => write!(f, "redis: {err}"), - Self::CryptoCore(err) => write!(f, "crypto_core: {err}"), Self::Findex(err) => write!(f, "findex: {err}"), Self::Io(err) => write!(f, "io: {err}"), Self::IntConversion(err) => write!(f, "conversion: {err}"), @@ -52,12 +48,6 @@ impl From for DbStoreError { } } -impl From for DbStoreError { - fn from(e: CryptoCoreError) -> Self { - Self::CryptoCore(e) - } -} - impl From for DbStoreError { fn from(e: findex_core_error!()) -> Self { Self::Findex(e) diff --git a/src/memory/db_stores/mod.rs b/src/memory/db_stores/mod.rs index fcb61be7..b77f0585 100644 --- a/src/memory/db_stores/mod.rs +++ b/src/memory/db_stores/mod.rs @@ -1,4 +1,4 @@ mod error; #[cfg(feature = "redis-store")] -pub mod redis_store; +pub(crate) mod redis_store; diff --git a/src/memory/db_stores/redis_store.rs b/src/memory/db_stores/redis_store.rs index a4ec9b1f..8f0ecf0e 100644 --- a/src/memory/db_stores/redis_store.rs +++ b/src/memory/db_stores/redis_store.rs @@ -22,7 +22,7 @@ pub struct RedisStore { // 2. Guard value. // 3. Vector length. // 4+. Vector elements (address, word). -const GUARDED_WRITE_LUA_SCRIPT: &str = r#" +const GUARDED_WRITE_LUA_SCRIPT: &str = r" local guard_address = ARGV[1] local guard_value = ARGV[2] local length = ARGV[3] @@ -38,7 +38,7 @@ if((value==false) or (not(value == false) and (guard_value == value))) then end end return value -"#; +"; impl Debug for RedisStore { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -117,8 +117,7 @@ impl< &self, addresses: Vec
, ) -> Result>, Self::Error> { - let refs: Vec<&[u8; ADDRESS_LENGTH]> = - addresses.iter().map(|address| address.deref()).collect(); + let refs: Vec<&[u8; ADDRESS_LENGTH]> = addresses.iter().map(|address| &**address).collect(); self.manager .clone() .mget::<_, Vec<_>>(&refs) @@ -140,14 +139,14 @@ impl< cmd = if let Some(byte_array) = guard_value { cmd.arg(&byte_array).arg(bindings.len()).clone() } else { - cmd.arg("false".to_string()).arg(bindings.len()).clone() + cmd.arg("false".to_owned()).arg(bindings.len()).clone() }; for (address, word) in bindings { cmd = cmd.arg(&*address).arg(&word).clone(); } cmd.query_async(&mut self.manager.clone()) .await - .map_err(|e| e.into()) + .map_err(std::convert::Into::into) } } @@ -165,11 +164,11 @@ mod tests { }, }; - pub fn get_redis_url() -> String { + pub(crate) fn get_redis_url() -> String { if let Ok(var_env) = std::env::var("REDIS_HOST") { format!("redis://{var_env}:6379") } else { - "redis://localhost:6379".to_string() + "redis://localhost:6379".to_owned() } } diff --git a/src/memory/mod.rs b/src/memory/mod.rs index a1d99bc1..c63481d8 100644 --- a/src/memory/mod.rs +++ b/src/memory/mod.rs @@ -1,5 +1,5 @@ // pub mod in_memory_store; -pub mod in_memory_store; +pub(crate) mod in_memory_store; #[cfg(feature = "redis-store")] -pub mod db_stores; +pub(crate) mod db_stores; diff --git a/src/ovec.rs b/src/ovec.rs index 2cc81ed4..7b4ad0e9 100644 --- a/src/ovec.rs +++ b/src/ovec.rs @@ -1,7 +1,7 @@ //! This module implements a simple vector, defined as a data-structure that //! preserves the following invariant: //! -//! I_v: the value of the counter stored at the vector address is equal to the +//! `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. //! @@ -32,7 +32,7 @@ impl TryFrom<&Header> for [u8; WORD_LENGTH] { fn try_from(header: &Header) -> Result { if WORD_LENGTH < 8 { - return Err("insufficient word length: should be at least 16 bytes".to_string()); + return Err("insufficient word length: should be at least 16 bytes".to_owned()); } let mut res = [0; WORD_LENGTH]; res[..8].copy_from_slice(&header.cnt.to_be_bytes()); @@ -68,7 +68,10 @@ impl TryFrom<&[u8]> for Header { /// Implementation of a vector in an infinite array. #[derive(Debug)] -pub struct IVec> { +pub(crate) struct IVec< + const WORD_LENGTH: usize, + Memory: Clone + MemoryADT, +> { // backing array address a: Memory::Address, // cached header value @@ -99,7 +102,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 } } } diff --git a/src/secret.rs b/src/secret.rs index 845d0b74..7b917e4f 100644 --- a/src/secret.rs +++ b/src/secret.rs @@ -17,6 +17,7 @@ impl Secret { /// /// All bytes are initially set to 0. #[inline(always)] + #[must_use] pub fn new() -> Self { Self(Box::pin([0; LENGTH])) } @@ -77,14 +78,14 @@ impl DerefMut for Secret { impl Zeroize for Secret { #[inline(always)] fn zeroize(&mut self) { - self.0.deref_mut().zeroize() + self.0.deref_mut().zeroize(); } } impl Drop for Secret { #[inline(always)] fn drop(&mut self) { - self.zeroize() + self.zeroize(); } } diff --git a/src/symmetric_key.rs b/src/symmetric_key.rs index 472a2118..df5a2fb0 100644 --- a/src/symmetric_key.rs +++ b/src/symmetric_key.rs @@ -33,7 +33,7 @@ impl Default for SymmetricKey { impl From> for Zeroizing> { fn from(value: SymmetricKey) -> Self { - Zeroizing::new(value.0.to_vec()) + Self::new(value.0.to_vec()) } } @@ -54,8 +54,8 @@ impl SymmetricKey { ) -> Result { if SECRET_LENGTH < KEY_LENGTH { return Err(format!( - "insufficient entropy to derive {}-byte key from a {}-byte secret", - KEY_LENGTH, SECRET_LENGTH, + "insufficient entropy to derive {KEY_LENGTH}-byte key from a {SECRET_LENGTH}-byte \ + secret", )); } let mut key = Self::default(); diff --git a/src/test/memory.rs b/src/test/memory.rs index 183e2012..001e0cee 100644 --- a/src/test/memory.rs +++ b/src/test/memory.rs @@ -30,9 +30,8 @@ where let expected_result = vec![None, None, None]; assert_eq!( empty_read_result, expected_result, - "Test batch_read of empty addresses failed.\nExpected result : {:?}. Got : {:?}. Seed : \ - {:?}", - expected_result, empty_read_result, seed + "Test batch_read of empty addresses failed.\nExpected result : {expected_result:?}. Got : \ + {empty_read_result:?}. Seed : {seed:?}" ); // Generate a random address and a random word that we save @@ -57,9 +56,8 @@ where let expected_result = vec![Some(T::Word::from(random_word))]; assert_eq!( read_result, expected_result, - "test_single_write_and_read failed.\nExpected result : {:?}, got : {:?}.\nDebug seed : \ - {:?}", - expected_result, read_result, seed + "test_single_write_and_read failed.\nExpected result : {expected_result:?}, got : \ + {read_result:?}.\nDebug seed : {seed:?}" ); } @@ -152,7 +150,8 @@ where if cur_cnt == old_cnt { return; // Successfully incremented, quit } else { - old_cnt = cur_cnt; // Guard failed, retry with the new value + // Guard failed, retry with the new value + old_cnt = cur_cnt; } } }) diff --git a/src/test/mod.rs b/src/test/mod.rs index 03fee246..acae6df4 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -1,2 +1,2 @@ #[cfg(any(test, feature = "test-utils"))] -pub mod memory; +pub(crate) mod memory; diff --git a/src/value.rs b/src/value.rs index 7d0c9996..c69e3364 100644 --- a/src/value.rs +++ b/src/value.rs @@ -28,7 +28,7 @@ impl From> for Value { impl From<&Value> for Vec { fn from(value: &Value) -> Self { - value.0.to_vec() + value.0.clone() } } @@ -48,7 +48,7 @@ impl TryFrom for String { type Error = FromUtf8Error; fn try_from(value: Value) -> Result { - String::from_utf8(value.0) + Self::from_utf8(value.0) } }