Skip to content

Commit 5fa459d

Browse files
committed
Fix test and add docs
1 parent a2afdf3 commit 5fa459d

File tree

1 file changed

+16
-9
lines changed
  • crates/bitwarden-crypto/src/store

1 file changed

+16
-9
lines changed

crates/bitwarden-crypto/src/store/mod.rs

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ pub use context::KeyStoreContext;
3838
/// }
3939
///
4040
/// // Initialize the store and insert a test key
41-
/// let store: KeyStore<Ids> = KeyStore::new();
41+
/// let store: KeyStore<Ids> = KeyStore::default();
4242
///
4343
/// #[allow(deprecated)]
4444
/// store.context_mut().set_symmetric_key(SymmKeyId::User, SymmetricCryptoKey::generate(rand::thread_rng()));
@@ -231,13 +231,20 @@ impl<Ids: KeyIds> KeyStore<Ids> {
231231
}
232232
}
233233

234+
/// Calculate the optimal chunk size for parallelizing encryption/decryption operations.
234235
fn batch_chunk_size(len: usize) -> usize {
235-
// We want to split all the data between available threads, but at the
236-
// same time we don't want to split it too much if the amount of data is small.
237-
238-
// In this case, the minimum chunk size is 50. This was chosen pretty arbitrarily,
239-
// but it seems to work well in practice.
240-
usize::max(1 + len / rayon::current_num_threads(), 50)
236+
// In an optimal scenario with no overhead, we would split the data evenly between
237+
// all available threads, rounding up to the nearest integer.
238+
let items_per_thread = usize::div_ceil(len, rayon::current_num_threads());
239+
240+
// Because the addition of each chunk has some overhead (e.g. creating a new context, thread
241+
// synchronization), we want to split the data into chunks that are large enough to amortize
242+
// this overhead, but not too large that we get no benefit from multithreading. We've chosen
243+
// a value more or less arbitrarily, but it seems to work well in practice.
244+
const MINIMUM_CHUNK_SIZE: usize = 50;
245+
246+
// As a result, we pick whichever of the two values is larger.
247+
usize::max(items_per_thread, MINIMUM_CHUNK_SIZE)
241248
}
242249

243250
#[cfg(test)]
@@ -298,8 +305,8 @@ pub(crate) mod tests {
298305
}
299306

300307
// Create some test data
301-
let data: Vec<_> = (0..200)
302-
.map(|n| DataView(format!("Test {}", n), TestSymmKey::A(n % 15)))
308+
let data: Vec<_> = (0..300usize)
309+
.map(|n| DataView(format!("Test {}", n), TestSymmKey::A((n % 15) as u8)))
303310
.collect();
304311

305312
// Encrypt the data

0 commit comments

Comments
 (0)