Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Enforce additional Rust lints across the workspace

Manav Rathiede40dfe7896
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index ba5507bb7e..b3f22281e7 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -117,6 +117,29 @@ unsafe_code = "deny"
[workspace.lints.clippy]
allow_attributes = "deny"
allow_attributes_without_reason = "deny"
+collection_is_never_read = "deny"
+dbg_macro = "deny"
+debug_assert_with_mut_call = "deny"
+derive_partial_eq_without_eq = "deny"
+empty_drop = "deny"
+fallible_impl_from = "deny"
+implicit_clone = "deny"
+inefficient_to_string = "deny"
+large_stack_arrays = "deny"
+large_types_passed_by_value = "deny"
+manual_let_else = "deny"
+needless_collect = "deny"
+path_buf_push_overwrite = "deny"
+rc_mutex = "deny"
+read_zero_byte_vec = "deny"
+redundant_clone = "deny"
+redundant_closure_for_method_calls = "deny"
+suspicious_operation_groupings = "deny"
+trivially_copy_pass_by_ref = "deny"
+uninlined_format_args = "deny"
+unused_async = "deny"
+unused_peekable = "deny"
+unused_rounding = "deny"
# Unoptimized Argon2 makes production-strength derivations dominate test runtime.
[profile.dev.package.argon2]
diff --git a/rust/apps/cli/src/commands/account.rs b/rust/apps/cli/src/commands/account.rs
index 7e5d6b9734..3ea8fa97c6 100644
--- a/rust/apps/cli/src/commands/account.rs
+++ b/rust/apps/cli/src/commands/account.rs
@@ -21,13 +21,13 @@ use zeroize::Zeroizing;
pub async fn handle_account_command(cmd: AccountCommand, storage: &Storage) -> Result<()> {
match cmd.command {
- AccountSubcommands::List => list_accounts(storage).await,
+ AccountSubcommands::List => list_accounts(storage),
AccountSubcommands::Add(args) => add_account(storage, args).await,
AccountSubcommands::Create(args) => create_account(storage, args).await,
AccountSubcommands::Update { email, dir, app } => {
- update_account(storage, &email, &dir, &app).await
+ update_account(storage, &email, &dir, &app)
}
- AccountSubcommands::GetToken { email, app } => get_token(storage, &email, &app).await,
+ AccountSubcommands::GetToken { email, app } => get_token(storage, &email, &app),
AccountSubcommands::TwoFactor {
email,
app,
@@ -169,7 +169,7 @@ impl AuthFlowUi for DialoguerAuthFlowUi {
}
}
-async fn list_accounts(storage: &Storage) -> Result<()> {
+fn list_accounts(storage: &Storage) -> Result<()> {
let accounts = storage.accounts().list()?;
if accounts.is_empty() {
@@ -399,13 +399,12 @@ async fn enable_two_factor(
Ok(())
}
-async fn update_account(storage: &Storage, email: &str, dir: &str, app_str: &str) -> Result<()> {
+fn update_account(storage: &Storage, email: &str, dir: &str, app_str: &str) -> Result<()> {
let app = resolve_app(app_str)?;
if storage.accounts().get(email, app)?.is_none() {
return Err(Error::NotFound(format!(
- "Account not found: {} (app: {})",
- email, app
+ "Account not found: {email} (app: {app})"
)));
}
@@ -420,7 +419,7 @@ async fn update_account(storage: &Storage, email: &str, dir: &str, app_str: &str
Ok(())
}
-async fn get_token(storage: &Storage, email: &str, app_str: &str) -> Result<()> {
+fn get_token(storage: &Storage, email: &str, app_str: &str) -> Result<()> {
let app = resolve_app(app_str)?;
let account = storage
diff --git a/rust/apps/cli/src/commands/export.rs b/rust/apps/cli/src/commands/export.rs
index d7a8e8a678..3a96031666 100644
--- a/rust/apps/cli/src/commands/export.rs
+++ b/rust/apps/cli/src/commands/export.rs
@@ -37,7 +37,7 @@ async fn load_album_metadata(
let mut entries = match fs::read_dir(&meta_dir).await {
Ok(entries) => entries,
Err(e) => {
- log::warn!("Failed to read metadata directory {:?}: {}", meta_dir, e);
+ log::warn!("Failed to read metadata directory {meta_dir:?}: {e}");
return Ok(existing_files);
}
};
@@ -59,7 +59,7 @@ async fn load_album_metadata(
let json_content = match fs::read_to_string(&meta_path).await {
Ok(content) => content,
Err(e) => {
- log::warn!("Failed to read metadata file {:?}: {}", meta_path, e);
+ log::warn!("Failed to read metadata file {meta_path:?}: {e}");
continue;
}
};
@@ -67,7 +67,7 @@ async fn load_album_metadata(
let disk_metadata: DiskFileMetadata = match serde_json::from_str(&json_content) {
Ok(metadata) => metadata,
Err(e) => {
- log::warn!("Failed to parse metadata file {:?}: {}", meta_path, e);
+ log::warn!("Failed to parse metadata file {meta_path:?}: {e}");
continue;
}
};
@@ -312,7 +312,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
}
};
- if collection.name.as_ref().is_none_or(|n| n.is_empty())
+ if collection.name.as_ref().is_none_or(String::is_empty)
&& let Some(ref encrypted_name) = collection.encrypted_name
&& let Some(ref nonce) = collection.name_decryption_nonce
{
@@ -370,16 +370,13 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
total_files += 1;
- let collection_info = match collection_map.get(&file.collection_id) {
- Some(info) => info,
- None => {
- log::debug!(
- "File {} belongs to unknown/deleted collection {}",
- file.id,
- file.collection_id
- );
- continue;
- }
+ let Some(collection_info) = collection_map.get(&file.collection_id) else {
+ log::debug!(
+ "File {} belongs to unknown/deleted collection {}",
+ file.id,
+ file.collection_id
+ );
+ continue;
};
let (collection, collection_key) = collection_info;
@@ -401,7 +398,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
);
if !filter.should_include_collection(collection_name, is_shared, is_hidden) {
- log::debug!("Skipping file in filtered collection: {}", collection_name);
+ log::debug!("Skipping file in filtered collection: {collection_name}");
continue;
}
@@ -519,21 +516,20 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
let is_live_photo = metadata
.as_ref()
- .map(|m| m.is_live_photo())
+ .map(FileMetadata::is_live_photo)
.unwrap_or(false);
if is_live_photo {
let old_mov_path = existing.file_path.with_extension("MOV");
if old_mov_path.exists() {
- log::debug!("Removing old live photo MOV component: {:?}", old_mov_path);
+ log::debug!("Removing old live photo MOV component: {old_mov_path:?}");
fs::remove_file(&old_mov_path).await.ok();
}
let old_mov_path_lower = existing.file_path.with_extension("mov");
if old_mov_path_lower.exists() && old_mov_path_lower != old_mov_path {
log::debug!(
- "Removing old live photo mov component: {:?}",
- old_mov_path_lower
+ "Removing old live photo mov component: {old_mov_path_lower:?}"
);
fs::remove_file(&old_mov_path_lower).await.ok();
}
@@ -571,7 +567,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
let is_live_photo = metadata
.as_ref()
- .map(|m| m.is_live_photo())
+ .map(FileMetadata::is_live_photo)
.unwrap_or(false);
if is_live_photo {
@@ -579,9 +575,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
let new_mov = file_path.with_extension("MOV");
if existing_mov.exists() {
log::debug!(
- "Copying live photo MOV component from {:?} to {:?}",
- existing_mov,
- new_mov
+ "Copying live photo MOV component from {existing_mov:?} to {new_mov:?}"
);
fs::copy(&existing_mov, &new_mov).await.ok();
} else {
@@ -589,9 +583,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
let new_mov_lower = file_path.with_extension("mov");
if existing_mov_lower.exists() {
log::debug!(
- "Copying live photo mov component from {:?} to {:?}",
- existing_mov_lower,
- new_mov_lower
+ "Copying live photo mov component from {existing_mov_lower:?} to {new_mov_lower:?}"
);
fs::copy(&existing_mov_lower, &new_mov_lower).await.ok();
}
@@ -643,7 +635,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
let is_live_photo = metadata
.as_ref()
- .map(|m| m.is_live_photo())
+ .map(FileMetadata::is_live_photo)
.unwrap_or(false);
if is_live_photo {
@@ -676,7 +668,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
let filename = file_path
.file_name()
.and_then(|n| n.to_str())
- .ok_or_else(|| crate::Error::Generic(format!("Invalid file path: {:?}", file_path)))?;
+ .ok_or_else(|| crate::Error::Generic(format!("Invalid file path: {file_path:?}")))?;
write_file_metadata(
export_path,
&album_folder,
@@ -690,7 +682,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
*file_index += 1;
if exported_files % 10 == 0 || exported_files == 1 {
- println!(" [{}/{}] Exported files...", exported_files, total_files);
+ println!(" [{exported_files}/{total_files}] Exported files...");
}
}
@@ -718,13 +710,13 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
let mov_path = existing_file.file_path.with_extension("MOV");
if mov_path.exists() {
- log::debug!("Removing live photo MOV component: {:?}", mov_path);
+ log::debug!("Removing live photo MOV component: {mov_path:?}");
fs::remove_file(&mov_path).await.ok();
}
let mov_path_lower = existing_file.file_path.with_extension("mov");
if mov_path_lower.exists() && mov_path_lower != mov_path {
- log::debug!("Removing live photo mov component: {:?}", mov_path_lower);
+ log::debug!("Removing live photo mov component: {mov_path_lower:?}");
fs::remove_file(&mov_path_lower).await.ok();
}
@@ -745,7 +737,7 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
}
if removed_files > 0 {
- log::info!("Removed {} deleted files from disk", removed_files);
+ log::info!("Removed {removed_files} deleted files from disk");
}
println!("\n{}", "=".repeat(50));
@@ -875,7 +867,7 @@ fn decrypt_collection_name(
)?;
String::from_utf8(decrypted)
- .map_err(|e| crate::Error::Generic(format!("Invalid UTF-8 in collection name: {}", e)))
+ .map_err(|e| crate::Error::Generic(format!("Invalid UTF-8 in collection name: {e}")))
}
fn decrypt_file_key(encrypted_key: &str, nonce: &str, collection_key: &[u8]) -> Result<Vec<u8>> {
@@ -985,7 +977,9 @@ fn check_collection_visibility(
) -> bool {
if let Some(ref magic_metadata) = collection.magic_metadata
&& let Ok(Some(decrypted_json)) = decrypt_magic_metadata(magic_metadata, collection_key)
- && let Some(visibility) = decrypted_json.get("visibility").and_then(|v| v.as_i64())
+ && let Some(visibility) = decrypted_json
+ .get("visibility")
+ .and_then(serde_json::Value::as_i64)
{
log::debug!(
"Collection {} has visibility: {} (hidden={})",
@@ -1045,7 +1039,7 @@ async fn write_file_metadata(
.and_then(|s| s.to_str())
.unwrap_or("");
- let meta_filename = format!("{}_{}.{}.json", base_name, file_index, extension);
+ let meta_filename = format!("{base_name}_{file_index}.{extension}.json");
let mut disk_metadata = DiskFileMetadata::from_file(file, metadata, filename.to_string());
disk_metadata.meta_file_name = meta_filename.clone();
diff --git a/rust/apps/cli/src/models/export_metadata.rs b/rust/apps/cli/src/models/export_metadata.rs
index 74c961f04c..10069862cd 100644
--- a/rust/apps/cli/src/models/export_metadata.rs
+++ b/rust/apps/cli/src/models/export_metadata.rs
@@ -1,6 +1,10 @@
use chrono::{DateTime, Local, TimeZone};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
+#[expect(
+ clippy::trivially_copy_pass_by_ref,
+ reason = "Serde serialize_with functions receive references"
+)]
fn serialize_timestamp_as_iso8601<S>(
timestamp_micros: &i64,
serializer: S,
@@ -38,7 +42,7 @@ where
TimestampFormat::Microseconds(micros) => Ok(micros),
TimestampFormat::IsoString(s) => DateTime::parse_from_rfc3339(&s)
.map(|dt| dt.timestamp_micros())
- .map_err(|e| Error::custom(format!("Invalid ISO timestamp: {}", e))),
+ .map_err(|e| Error::custom(format!("Invalid ISO timestamp: {e}"))),
}
}
diff --git a/rust/apps/cli/src/storage/account.rs b/rust/apps/cli/src/storage/account.rs
index 336d173e88..ad84e407ae 100644
--- a/rust/apps/cli/src/storage/account.rs
+++ b/rust/apps/cli/src/storage/account.rs
@@ -73,8 +73,7 @@ impl<'a> AccountStore<'a> {
if rows_affected == 0 {
return Err(crate::Error::NotFound(format!(
- "Account not found: {} (app: {:?})",
- email, app
+ "Account not found: {email} (app: {app:?})"
)));
}
@@ -89,8 +88,7 @@ impl<'a> AccountStore<'a> {
if rows_affected == 0 {
return Err(crate::Error::NotFound(format!(
- "Account not found: user_id={} (app: {:?})",
- user_id, app
+ "Account not found: user_id={user_id} (app: {app:?})"
)));
}
diff --git a/rust/apps/cli/src/storage/sync.rs b/rust/apps/cli/src/storage/sync.rs
index 2b0e6d20ec..491b147d4d 100644
--- a/rust/apps/cli/src/storage/sync.rs
+++ b/rust/apps/cli/src/storage/sync.rs
@@ -171,7 +171,7 @@ impl<'a> SyncStore<'a> {
.and_then(|s| s.strip_suffix("_files"))
.and_then(|s| s.parse::<i64>().ok())
.ok_or_else(|| {
- crate::Error::InvalidInput(format!("Invalid sync type: {}", sync_type))
+ crate::Error::InvalidInput(format!("Invalid sync type: {sync_type}"))
})?;
let now = chrono::Utc::now().timestamp_micros();
@@ -208,7 +208,7 @@ impl<'a> SyncStore<'a> {
.and_then(|s| s.strip_suffix("_files"))
.and_then(|s| s.parse::<i64>().ok())
.ok_or_else(|| {
- crate::Error::InvalidInput(format!("Invalid sync type: {}", sync_type))
+ crate::Error::InvalidInput(format!("Invalid sync type: {sync_type}"))
})?;
let timestamp = self
diff --git a/rust/apps/cli/src/sync/engine.rs b/rust/apps/cli/src/sync/engine.rs
index 3a53ef9c2a..2ff6cf6a18 100644
--- a/rust/apps/cli/src/sync/engine.rs
+++ b/rust/apps/cli/src/sync/engine.rs
@@ -249,7 +249,7 @@ impl SyncEngine {
Ok(result)
}
- pub async fn get_pending_downloads(&self) -> Result<Vec<RemoteFile>> {
+ pub fn get_pending_downloads(&self) -> Result<Vec<RemoteFile>> {
let sync_store = self.storage.sync();
let collections = sync_store.get_collections(self.account.user_id)?;
@@ -266,7 +266,7 @@ impl SyncEngine {
Ok(pending)
}
- pub async fn get_collections(&self) -> Result<Vec<crate::models::collection::Collection>> {
+ pub fn get_collections(&self) -> Result<Vec<crate::models::collection::Collection>> {
let sync_store = self.storage.sync();
sync_store.get_collections(self.account.user_id)
}
diff --git a/rust/apps/ensu/src-tauri/src/commands/llm.rs b/rust/apps/ensu/src-tauri/src/commands/llm.rs
index b682f751b5..8c8209c2f2 100644
--- a/rust/apps/ensu/src-tauri/src/commands/llm.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/llm.rs
@@ -1,3 +1,4 @@
+use std::num::NonZeroUsize;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
@@ -165,7 +166,7 @@ pub(crate) fn replace_state(
fn default_threads() -> i32 {
let available = std::thread::available_parallelism()
- .map(|count| count.get())
+ .map(NonZeroUsize::get)
.unwrap_or(2);
let half = available / 2;
let threads = if half == 0 { 1 } else { half };
diff --git a/rust/apps/ensu/src-tauri/src/commands/notes/watcher.rs b/rust/apps/ensu/src-tauri/src/commands/notes/watcher.rs
index 127f08e6cd..91ec2c13d5 100644
--- a/rust/apps/ensu/src-tauri/src/commands/notes/watcher.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/notes/watcher.rs
@@ -605,7 +605,7 @@ fn classify_watch_paths(
}
continue;
}
- if metadata.as_ref().is_some_and(|metadata| metadata.is_dir())
+ if metadata.as_ref().is_some_and(fs::Metadata::is_dir)
|| (metadata.is_none() && overflow_or_ambiguity)
{
change.force_full_hash = true;
@@ -743,7 +743,7 @@ mod tests {
let directories = watch_directories(&root).unwrap();
- assert_eq!(directories, BTreeSet::from([root.clone(), nested]));
+ assert_eq!(directories, BTreeSet::from([root, nested]));
assert!(!directories.contains(&outside));
}
diff --git a/rust/apps/ensu/src-tauri/src/logging.rs b/rust/apps/ensu/src-tauri/src/logging.rs
index 06f010f318..9e9abbc971 100644
--- a/rust/apps/ensu/src-tauri/src/logging.rs
+++ b/rust/apps/ensu/src-tauri/src/logging.rs
@@ -75,7 +75,7 @@ pub fn install_panic_hook() {
let thread = std::thread::current()
.name()
- .map(|name| name.to_string())
+ .map(ToString::to_string)
.unwrap_or_else(|| "unnamed".to_string());
log(
diff --git a/rust/bindings/frb/photos/src/api/vecdb_api.rs b/rust/bindings/frb/photos/src/api/vecdb_api.rs
index f1c81698ff..17363b18fa 100644
--- a/rust/bindings/frb/photos/src/api/vecdb_api.rs
+++ b/rust/bindings/frb/photos/src/api/vecdb_api.rs
@@ -565,7 +565,7 @@ mod tests {
)
.unwrap();
assert_eq!(empty_allowed.len(), 3);
- assert!(empty_allowed.iter().all(|matches| matches.is_empty()));
+ assert!(empty_allowed.iter().all(Vec::is_empty));
for degenerate_distance in [f32::NAN, f32::INFINITY, -0.5] {
let degenerate = db
.bulk_approx_filtered_search_vectors_within_distance(
@@ -576,7 +576,7 @@ mod tests {
)
.unwrap();
assert_eq!(degenerate.len(), 3);
- assert!(degenerate.iter().all(|matches| matches.is_empty()));
+ assert!(degenerate.iter().all(Vec::is_empty));
}
let unfiltered = db.search(basis(0), Some(3), None, false, None).unwrap();
assert_eq!(unfiltered.len(), 3);
@@ -646,8 +646,7 @@ mod tests {
value: VecDbAttrValue::F64(0.75),
},
];
- db.add_vector_with_attrs(key("a"), basis(0), attrs.clone())
- .unwrap();
+ db.add_vector_with_attrs(key("a"), basis(0), attrs).unwrap();
let fetched = db.get_attrs(key("a")).unwrap();
assert_eq!(fetched.len(), 4);
assert!(matches!(
diff --git a/rust/bindings/napi/photos/src/lib.rs b/rust/bindings/napi/photos/src/lib.rs
index 87bdec5d29..30026c08c7 100644
--- a/rust/bindings/napi/photos/src/lib.rs
+++ b/rust/bindings/napi/photos/src/lib.rs
@@ -205,7 +205,7 @@ impl Task for AnalyzeImageTask {
fn resolve(&mut self, env: Env, output: Self::Output) -> Result<Self::JsValue> {
match output {
Ok(output) => Ok(to_napi_analyze_image_result(output)),
- Err(error) => Err(ml_error_to_napi(&env, error)?),
+ Err(error) => Err(ml_error_to_napi(env, error)?),
}
}
}
@@ -277,7 +277,7 @@ pub fn tokenize_clip_text(text: String, vocab_path: String) -> Result<Vec<i32>>
.map_err(|error| Error::from_reason(error.to_string()))
}
-fn ml_error_to_napi(env: &Env, error: MlError) -> Result<Error> {
+fn ml_error_to_napi(env: Env, error: MlError) -> Result<Error> {
let name = match &error {
MlError::CorruptModel(_) => "ml_init",
MlError::Decode(_) => "ml_decode",
@@ -286,7 +286,7 @@ fn ml_error_to_napi(env: &Env, error: MlError) -> Result<Error> {
};
let mut value = env.create_error(Error::from_reason(error.to_string()))?;
value.set_named_property("name", name)?;
- Ok(Error::from(value.into_unknown(env)?))
+ Ok(Error::from(value.into_unknown(&env)?))
}
fn asset_error_to_napi(error: ente_assets::download::Error) -> Error {
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rs
index 6f3e53d8f0..b18942c889 100644
--- a/rust/bindings/wasm/space/src/space.rs
+++ b/rust/bindings/wasm/space/src/space.rs
@@ -503,7 +503,7 @@ fn link_post_to_js(post: PostResponse, decrypted: DecryptedPost) -> Result<PostJ
})
}
-async fn account_message_to_js(
+fn account_message_to_js(
mut message: MessageResponse,
decrypted: DecryptedMessage,
) -> Result<MessageJs, Error> {
@@ -557,7 +557,7 @@ async fn account_message_response_to_js(
}
if message.kind != "post_like" && message.kind != "friend_added" {
let decrypted = ctx.decrypt_message(viewer_space_id, &message).await?;
- return account_message_to_js(message, decrypted).await;
+ return account_message_to_js(message, decrypted);
}
let text = message.text.clone();
@@ -683,7 +683,7 @@ async fn resilient_message_conversation_activity_to_js(
}
#[wasm_bindgen(js_name = spaceOpenAccountCtx)]
-pub async fn space_open_account_ctx(input: JsValue) -> Result<SpaceAccountCtxHandle, Error> {
+pub fn space_open_account_ctx(input: JsValue) -> Result<SpaceAccountCtxHandle, Error> {
let input: OpenAccountSpaceCtxJsInput = swb::from_value(input)?;
let space_root_key = decode_b64_field(&input.space_root_key_b64)?;
let ctx = AccountSpaceCtx::open(OpenAccountSpaceCtxInput {
@@ -1110,7 +1110,7 @@ impl SpaceAccountCtxHandle {
.create_post(
&space_id,
&[object],
- caption.as_ref().map(|value| value.as_bytes()),
+ caption.as_ref().map(String::as_bytes),
Some(&post_key),
)
.await?;
@@ -1225,7 +1225,7 @@ impl SpaceAccountCtxHandle {
.inner
.decrypt_message(&sender_space_id, &message)
.await?;
- swb::to_value(&account_message_to_js(message, decrypted).await?).map_err(Into::into)
+ swb::to_value(&account_message_to_js(message, decrypted)?).map_err(Into::into)
}
#[wasm_bindgen(js_name = sendPoke)]
@@ -1239,7 +1239,7 @@ impl SpaceAccountCtxHandle {
.inner
.decrypt_message(&sender_space_id, &message)
.await?;
- swb::to_value(&account_message_to_js(message, decrypted).await?).map_err(Into::into)
+ swb::to_value(&account_message_to_js(message, decrypted)?).map_err(Into::into)
}
#[wasm_bindgen(js_name = replyToMessage)]
@@ -1258,7 +1258,7 @@ impl SpaceAccountCtxHandle {
.inner
.decrypt_message(&sender_space_id, &message)
.await?;
- swb::to_value(&account_message_to_js(message, decrypted).await?).map_err(Into::into)
+ swb::to_value(&account_message_to_js(message, decrypted)?).map_err(Into::into)
}
#[wasm_bindgen(js_name = replyToPost)]
@@ -1277,7 +1277,7 @@ impl SpaceAccountCtxHandle {
.inner
.decrypt_message(&sender_space_id, &message)
.await?;
- swb::to_value(&account_message_to_js(message, decrypted).await?).map_err(Into::into)
+ swb::to_value(&account_message_to_js(message, decrypted)?).map_err(Into::into)
}
#[wasm_bindgen(js_name = likeMessage)]
@@ -1403,7 +1403,7 @@ impl SpaceAccountCtxHandle {
&space_id,
post_id,
&decrypted_post.post_key,
- caption.as_ref().map(|value| value.as_bytes()),
+ caption.as_ref().map(String::as_bytes),
)
.await
.map_err(Into::into)
diff --git a/rust/crates/accounts/src/auth/api.rs b/rust/crates/accounts/src/auth/api.rs
index 2af33e5c75..de50a94c7e 100644
--- a/rust/crates/accounts/src/auth/api.rs
+++ b/rust/crates/accounts/src/auth/api.rs
@@ -74,7 +74,7 @@ impl fmt::Debug for GeneratedSrpSetup {
pub fn derive_srp_credentials(password: &str, srp_attrs: &SrpAttributes) -> Result<SrpCredentials> {
let kek_salt =
- b64::decode(&srp_attrs.kek_salt).map_err(|e| Error::Decode(format!("kek_salt: {}", e)))?;
+ b64::decode(&srp_attrs.kek_salt).map_err(|e| Error::Decode(format!("kek_salt: {e}")))?;
let salt = crypto::Salt::try_from_slice(&kek_salt)?;
let kek = argon::derive_key(
@@ -100,8 +100,7 @@ pub fn derive_kek(
mem_limit: u32,
ops_limit: u32,
) -> Result<SecretVec> {
- let salt_bytes =
- b64::decode(kek_salt).map_err(|e| Error::Decode(format!("kek_salt: {}", e)))?;
+ let salt_bytes = b64::decode(kek_salt).map_err(|e| Error::Decode(format!("kek_salt: {e}")))?;
let salt = crypto::Salt::try_from_slice(&salt_bytes)?;
let key = argon::derive_key(
@@ -172,9 +171,9 @@ pub fn generate_srp_setup_with_login_key(
pub fn decrypt_keys_only(kek: &[u8], key_attrs: &KeyAttributes) -> Result<(Key, SecretKey)> {
let encrypted_key = b64::decode(&key_attrs.encrypted_key)
- .map_err(|e| Error::Decode(format!("encrypted_key: {}", e)))?;
+ .map_err(|e| Error::Decode(format!("encrypted_key: {e}")))?;
let key_nonce = b64::decode(&key_attrs.key_decryption_nonce)
- .map_err(|e| Error::Decode(format!("key_decryption_nonce: {}", e)))?;
+ .map_err(|e| Error::Decode(format!("key_decryption_nonce: {e}")))?;
let master_key = secretbox::decrypt(
&encrypted_key,
@@ -185,11 +184,11 @@ pub fn decrypt_keys_only(kek: &[u8], key_attrs: &KeyAttributes) -> Result<(Key,
let master_key = Key::try_from_slice(&master_key)?;
let encrypted_secret_key = b64::decode(&key_attrs.encrypted_secret_key)
- .map_err(|e| Error::Decode(format!("encrypted_secret_key: {}", e)))?;
+ .map_err(|e| Error::Decode(format!("encrypted_secret_key: {e}")))?;
let secret_key_nonce = b64::decode(&key_attrs.secret_key_decryption_nonce)
- .map_err(|e| Error::Decode(format!("secret_key_decryption_nonce: {}", e)))?;
+ .map_err(|e| Error::Decode(format!("secret_key_decryption_nonce: {e}")))?;
let public_key = b64::decode(&key_attrs.public_key)
- .map_err(|e| Error::Decode(format!("public_key: {}", e)))?;
+ .map_err(|e| Error::Decode(format!("public_key: {e}")))?;
let public_key = crypto::PublicKey::try_from_slice(&public_key)?;
let secret_key = SecretKey::open(
&secretbox::EncryptedBox {
@@ -211,8 +210,8 @@ pub fn decrypt_secrets(
) -> Result<DecryptedSecrets> {
let (master_key, secret_key) = decrypt_keys_only(kek, key_attrs)?;
- let sealed_token = b64::decode(encrypted_token)
- .map_err(|e| Error::Decode(format!("encrypted_token: {}", e)))?;
+ let sealed_token =
+ b64::decode(encrypted_token).map_err(|e| Error::Decode(format!("encrypted_token: {e}")))?;
let token = sealed::open(&sealed_token, &secret_key.public_key(), &secret_key)
.map_err(|_| Error::InvalidKeyAttributes)?;
diff --git a/rust/crates/accounts/src/auth/recovery.rs b/rust/crates/accounts/src/auth/recovery.rs
index 1e256338e8..0065d41ecb 100644
--- a/rust/crates/accounts/src/auth/recovery.rs
+++ b/rust/crates/accounts/src/auth/recovery.rs
@@ -20,9 +20,9 @@ pub fn get_recovery_key(master_key: &Key, attributes: &KeyAttributes) -> Result<
.ok_or(Error::MissingField("recovery_key_decryption_nonce"))?;
let encrypted_bytes = b64::decode(encrypted_recovery_key)
- .map_err(|e| Error::Decode(format!("recovery_key_encrypted_with_master_key: {}", e)))?;
+ .map_err(|e| Error::Decode(format!("recovery_key_encrypted_with_master_key: {e}")))?;
let nonce_bytes = b64::decode(nonce)
- .map_err(|e| Error::Decode(format!("recovery_key_decryption_nonce: {}", e)))?;
+ .map_err(|e| Error::Decode(format!("recovery_key_decryption_nonce: {e}")))?;
let recovery_key = SecretVec::new(
secretbox::decrypt(
@@ -66,7 +66,7 @@ pub fn recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex: &str) ->
pub fn recovery_key_to_mnemonic(recovery_key_b64: &str) -> Result<String> {
let recovery_key = SecretVec::new(
- b64::decode(recovery_key_b64).map_err(|e| Error::Decode(format!("recovery_key: {}", e)))?,
+ b64::decode(recovery_key_b64).map_err(|e| Error::Decode(format!("recovery_key: {e}")))?,
);
if recovery_key.len() != 32 {
@@ -75,7 +75,7 @@ pub fn recovery_key_to_mnemonic(recovery_key_b64: &str) -> Result<String> {
Mnemonic::from_entropy_in(Language::English, &recovery_key)
.map(|mnemonic| mnemonic.to_string())
- .map_err(|e| Error::InvalidKey(format!("recovery_key: {}", e)))
+ .map_err(|e| Error::InvalidKey(format!("recovery_key: {e}")))
}
#[cfg(test)]
diff --git a/rust/crates/accounts/src/auth/srp.rs b/rust/crates/accounts/src/auth/srp.rs
index f63b40279b..abb5429c77 100644
--- a/rust/crates/accounts/src/auth/srp.rs
+++ b/rust/crates/accounts/src/auth/srp.rs
@@ -42,7 +42,7 @@ impl SrpSession {
let mut a_private = vec![0u8; 64];
getrandom::fill(&mut a_private)
- .map_err(|e| Error::Srp(format!("Failed to generate random bytes: {}", e)))?;
+ .map_err(|e| Error::Srp(format!("Failed to generate random bytes: {e}")))?;
let a_public = client.compute_public_ephemeral(&a_private);
@@ -76,7 +76,7 @@ impl SrpSession {
&self.salt,
server_b,
)
- .map_err(|e| Error::Srp(format!("Failed to process server response: {:?}", e)))?;
+ .map_err(|e| Error::Srp(format!("Failed to process server response: {e:?}")))?;
// The srp crate uses S directly for M2, but our server uses K = H(S).
let s = verifier.key();
diff --git a/rust/crates/accounts/src/models.rs b/rust/crates/accounts/src/models.rs
index 3ed777d4ed..a5e42ef9e3 100644
--- a/rust/crates/accounts/src/models.rs
+++ b/rust/crates/accounts/src/models.rs
@@ -54,10 +54,7 @@ impl TryFrom<AuthResponseWire> for AuthResponse {
.passkey_session_id
.as_ref()
.is_some_and(|session_id| !session_id.is_empty())
- && value
- .accounts_url
- .as_ref()
- .is_none_or(|accounts_url| accounts_url.is_empty())
+ && value.accounts_url.as_ref().is_none_or(String::is_empty)
{
return Err("accountsUrl is required when passkeySessionID is present".into());
}
diff --git a/rust/crates/assets/src/store.rs b/rust/crates/assets/src/store.rs
index 0842732ce5..95fa5d1656 100644
--- a/rust/crates/assets/src/store.rs
+++ b/rust/crates/assets/src/store.rs
@@ -863,10 +863,7 @@ mod tests {
}
fn key(components: &[&str]) -> Vec<String> {
- components
- .iter()
- .map(|component| component.to_string())
- .collect()
+ components.iter().map(ToString::to_string).collect()
}
fn file(name: &str, bytes: &[u8]) -> AssetFile {
diff --git a/rust/crates/contacts/tests/contacts.rs b/rust/crates/contacts/tests/contacts.rs
index a23c69a7d3..3bb3b899c9 100644
--- a/rust/crates/contacts/tests/contacts.rs
+++ b/rust/crates/contacts/tests/contacts.rs
@@ -600,12 +600,11 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
.iter()
.all(|kit| kit.id != waiting_kit.kit.id)
);
- let inactive_error = match recovery_client
+ let Err(inactive_error) = recovery_client
.open_from_shares(&waiting_kit.shares[0..2], None)
.await
- {
- Ok(_) => panic!("deleted legacy kit recovery unexpectedly opened"),
- Err(error) => error,
+ else {
+ panic!("deleted legacy kit recovery unexpectedly opened")
};
assert!(matches!(
inactive_error,
diff --git a/rust/crates/core/src/crypto/argon.rs b/rust/crates/core/src/crypto/argon.rs
index a9a6e62419..67dce5679c 100644
--- a/rust/crates/core/src/crypto/argon.rs
+++ b/rust/crates/core/src/crypto/argon.rs
@@ -148,8 +148,7 @@ fn derive_sensitive_adaptive(password: &[u8], salt: &Salt) -> Result<DerivedKey>
if u64::from(mem_limit) * u64::from(ops_limit) != desired_strength {
return Err(Error::InvalidKeyDerivationParams(format!(
- "Unexpected mem/ops limits: mem_limit {}, ops_limit {}",
- mem_limit, ops_limit
+ "Unexpected mem/ops limits: mem_limit {mem_limit}, ops_limit {ops_limit}"
)));
}
diff --git a/rust/crates/core/src/crypto/blob.rs b/rust/crates/core/src/crypto/blob.rs
index 7ef2562384..62c56467af 100644
--- a/rust/crates/core/src/crypto/blob.rs
+++ b/rust/crates/core/src/crypto/blob.rs
@@ -78,20 +78,20 @@ pub fn decrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
pub fn encrypt_json<T: serde::Serialize>(value: &T, key: &Key) -> Result<EncryptedBlob> {
let json = serde_json::to_vec(value)
- .map_err(|e| Error::Json(format!("JSON serialization failed: {}", e)))?;
+ .map_err(|e| Error::Json(format!("JSON serialization failed: {e}")))?;
encrypt(&json, key)
}
pub fn encrypt_json_combined<T: serde::Serialize>(value: &T, key: &Key) -> Result<Vec<u8>> {
let json = serde_json::to_vec(value)
- .map_err(|e| Error::Json(format!("JSON serialization failed: {}", e)))?;
+ .map_err(|e| Error::Json(format!("JSON serialization failed: {e}")))?;
encrypt_combined(&json, key)
}
pub fn decrypt_json<T: serde::de::DeserializeOwned>(blob: &EncryptedBlob, key: &Key) -> Result<T> {
let plaintext = blob.decrypt(key)?;
serde_json::from_slice(&plaintext)
- .map_err(|e| Error::Json(format!("JSON deserialization failed: {}", e)))
+ .map_err(|e| Error::Json(format!("JSON deserialization failed: {e}")))
}
pub fn decrypt_json_combined<T: serde::de::DeserializeOwned>(
@@ -100,7 +100,7 @@ pub fn decrypt_json_combined<T: serde::de::DeserializeOwned>(
) -> Result<T> {
let plaintext = decrypt_combined(combined, key)?;
serde_json::from_slice(&plaintext)
- .map_err(|e| Error::Json(format!("JSON deserialization failed: {}", e)))
+ .map_err(|e| Error::Json(format!("JSON deserialization failed: {e}")))
}
#[cfg(test)]
@@ -226,8 +226,7 @@ mod tests {
let result: std::result::Result<u64, _> = decrypt_json(&encrypted, &key);
assert!(
matches!(result, Err(Error::Json(_))),
- "Expected Error::Json, got: {:?}",
- result
+ "Expected Error::Json, got: {result:?}"
);
}
diff --git a/rust/crates/core/src/crypto/sealed.rs b/rust/crates/core/src/crypto/sealed.rs
index 6231457450..9413f5b8a5 100644
--- a/rust/crates/core/src/crypto/sealed.rs
+++ b/rust/crates/core/src/crypto/sealed.rs
@@ -255,8 +255,7 @@ mod tests {
let result = seal(b"test", &zero_pk);
assert!(
matches!(result, Err(Error::InvalidPublicKey)),
- "seal() should reject small-order public key, got: {:?}",
- result
+ "seal() should reject small-order public key, got: {result:?}"
);
}
@@ -272,8 +271,7 @@ mod tests {
let result = open(&fake_ciphertext, &pk, &sk);
assert!(
matches!(result, Err(Error::InvalidPublicKey)),
- "open() should reject small-order ephemeral key, got: {:?}",
- result
+ "open() should reject small-order ephemeral key, got: {result:?}"
);
}
diff --git a/rust/crates/core/src/crypto/secret.rs b/rust/crates/core/src/crypto/secret.rs
index d6437053ac..9fe2173e8b 100644
--- a/rust/crates/core/src/crypto/secret.rs
+++ b/rust/crates/core/src/crypto/secret.rs
@@ -155,7 +155,7 @@ mod tests {
#[test]
fn test_secret_vec_debug_redacts() {
let secret = SecretVec::new(vec![42u8; 16]);
- let debug = format!("{:?}", secret);
+ let debug = format!("{secret:?}");
assert_eq!(debug, "[REDACTED]");
assert!(!debug.contains("42"));
}
diff --git a/rust/crates/core/src/crypto/secretbox.rs b/rust/crates/core/src/crypto/secretbox.rs
index fe95015842..def7cb07e9 100644
--- a/rust/crates/core/src/crypto/secretbox.rs
+++ b/rust/crates/core/src/crypto/secretbox.rs
@@ -7,7 +7,7 @@ use crate::crypto::{Error, Key, Nonce, Result};
// Same as libsodium's `crypto_secretbox_MACBYTES`.
pub const MAC_BYTES: usize = 16;
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptedBox {
pub encrypted_data: Vec<u8>,
pub nonce: Nonce,
diff --git a/rust/crates/core/src/crypto/stream.rs b/rust/crates/core/src/crypto/stream.rs
index 4b2ee3b8d4..def2e15bdf 100644
--- a/rust/crates/core/src/crypto/stream.rs
+++ b/rust/crates/core/src/crypto/stream.rs
@@ -115,18 +115,16 @@ pub fn estimate_encrypted_size(plaintext_len: usize) -> usize {
let full_chunks = plaintext_len / ENCRYPTION_CHUNK_SIZE;
let last_chunk_size = plaintext_len % ENCRYPTION_CHUNK_SIZE;
- let full_bytes = match full_chunks.checked_mul(DECRYPTION_CHUNK_SIZE) {
- Some(value) => value,
- None => return usize::MAX,
+ let Some(full_bytes) = full_chunks.checked_mul(DECRYPTION_CHUNK_SIZE) else {
+ return usize::MAX;
};
if last_chunk_size == 0 {
return full_bytes;
}
- let with_last = match full_bytes.checked_add(last_chunk_size) {
- Some(value) => value,
- None => return usize::MAX,
+ let Some(with_last) = full_bytes.checked_add(last_chunk_size) else {
+ return usize::MAX;
};
match with_last.checked_add(ABYTES) {
Some(value) => value,
@@ -507,8 +505,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamTruncated)),
- "Expected StreamTruncated error, got {:?}",
- result
+ "Expected StreamTruncated error, got {result:?}"
);
}
@@ -529,8 +526,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamTruncated)),
- "Expected StreamTruncated error, got {:?}",
- result
+ "Expected StreamTruncated error, got {result:?}"
);
}
@@ -641,11 +637,7 @@ mod tests {
}
}
- assert_eq!(
- plaintext, decrypted,
- "Mismatch with buffer size {}",
- buf_size
- );
+ assert_eq!(plaintext, decrypted, "Mismatch with buffer size {buf_size}");
}
}
@@ -704,7 +696,7 @@ mod tests {
assert_eq!(decrypted.len(), total_plaintext_size);
for (i, byte) in decrypted.iter().take(1000).enumerate() {
- assert_eq!(*byte, (i % 256) as u8, "Mismatch at small_data[{}]", i);
+ assert_eq!(*byte, (i % 256) as u8, "Mismatch at small_data[{i}]");
}
for (i, byte) in decrypted[1000..]
.iter()
@@ -714,8 +706,7 @@ mod tests {
assert_eq!(
*byte,
((i + 1000) % 256) as u8,
- "Mismatch at large_data[{}]",
- i
+ "Mismatch at large_data[{i}]"
);
}
}
@@ -803,8 +794,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamPullFailed)),
- "Expected StreamPullFailed error on tampered ciphertext, got {:?}",
- result
+ "Expected StreamPullFailed error on tampered ciphertext, got {result:?}"
);
}
@@ -824,8 +814,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamPullFailed)),
- "Expected StreamPullFailed error on tampered header, got {:?}",
- result
+ "Expected StreamPullFailed error on tampered header, got {result:?}"
);
}
@@ -846,8 +835,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamPullFailed)),
- "Expected StreamPullFailed error on tampered MAC, got {:?}",
- result
+ "Expected StreamPullFailed error on tampered MAC, got {result:?}"
);
}
@@ -866,8 +854,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamPullFailed)),
- "Expected StreamPullFailed error with wrong key, got {:?}",
- result
+ "Expected StreamPullFailed error with wrong key, got {result:?}"
);
}
@@ -913,8 +900,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamPullFailed)),
- "Expected StreamPullFailed for short ciphertext, got {:?}",
- result
+ "Expected StreamPullFailed for short ciphertext, got {result:?}"
);
}
@@ -1026,8 +1012,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamTruncated)),
- "Expected StreamTruncated for empty ciphertext, got {:?}",
- result
+ "Expected StreamTruncated for empty ciphertext, got {result:?}"
);
}
@@ -1046,8 +1031,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamTruncated)),
- "Expected StreamTruncated at chunk boundary, got {:?}",
- result
+ "Expected StreamTruncated at chunk boundary, got {result:?}"
);
}
@@ -1069,8 +1053,7 @@ mod tests {
assert!(
result.is_err(),
- "Expected error from truncated ciphertext, got {:?}",
- result
+ "Expected error from truncated ciphertext, got {result:?}"
);
}
@@ -1106,8 +1089,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamTrailingData)),
- "Expected StreamTrailingData for trailing bytes after FINAL, got {:?}",
- result
+ "Expected StreamTrailingData for trailing bytes after FINAL, got {result:?}"
);
}
@@ -1140,8 +1122,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamTruncated)),
- "Expected StreamTruncated from decrypt_file_data, got {:?}",
- result
+ "Expected StreamTruncated from decrypt_file_data, got {result:?}"
);
}
@@ -1159,8 +1140,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamTrailingData)),
- "Expected StreamTrailingData from decrypt_file_data, got {:?}",
- result
+ "Expected StreamTrailingData from decrypt_file_data, got {result:?}"
);
}
@@ -1182,8 +1162,7 @@ mod tests {
assert!(
matches!(result, Err(Error::StreamTrailingData)),
- "Expected StreamTrailingData from StreamingDecryptor, got {:?}",
- result
+ "Expected StreamTrailingData from StreamingDecryptor, got {result:?}"
);
}
@@ -1254,8 +1233,7 @@ mod tests {
assert_eq!(
stream_ciphertext_len, expected,
- "StreamingEncryptor: size={}, output {} != estimate {}",
- size, stream_ciphertext_len, expected
+ "StreamingEncryptor: size={size}, output {stream_ciphertext_len} != estimate {expected}"
);
}
}
@@ -1274,8 +1252,7 @@ mod tests {
assert!(
validate_sizes(plaintext.len(), encrypted.len()),
- "validate_sizes failed for size {}",
- size
+ "validate_sizes failed for size {size}"
);
}
}
diff --git a/rust/crates/ensu/src/config/knowledge.rs b/rust/crates/ensu/src/config/knowledge.rs
index ac4414378e..960e06bbaa 100644
--- a/rust/crates/ensu/src/config/knowledge.rs
+++ b/rust/crates/ensu/src/config/knowledge.rs
@@ -27,7 +27,7 @@ const MAX_HITS: u32 = 2;
const MAX_CONTEXT_UTF8_BYTES: u32 = 6_000;
const MODIFICATION_NOTICE: &str = "Adapted by Ente";
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KnowledgeEmbeddingConfig {
pub model_url: String,
pub model_size: u64,
@@ -43,7 +43,7 @@ pub struct KnowledgeEmbeddingConfig {
pub max_context_utf8_bytes: u32,
}
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttributionConfig {
pub credit: String,
pub license_label: String,
diff --git a/rust/crates/ensu/src/db/backend/mod.rs b/rust/crates/ensu/src/db/backend/mod.rs
index d522520f86..b2b8f3876b 100644
--- a/rust/crates/ensu/src/db/backend/mod.rs
+++ b/rust/crates/ensu/src/db/backend/mod.rs
@@ -3,7 +3,7 @@ use crate::db::{Error, Result};
#[cfg(feature = "sqlite")]
pub mod sqlite;
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
Null,
Integer(i64),
diff --git a/rust/crates/ensu/src/llm/generate.rs b/rust/crates/ensu/src/llm/generate.rs
index af06cb71ec..d1f80f2057 100644
--- a/rust/crates/ensu/src/llm/generate.rs
+++ b/rust/crates/ensu/src/llm/generate.rs
@@ -249,7 +249,7 @@ struct StreamDecoder {
impl StreamDecoder {
fn new(stop_sequences: &[String]) -> Self {
- let max_stop_len = stop_sequences.iter().map(|s| s.len()).max().unwrap_or(0);
+ let max_stop_len = stop_sequences.iter().map(String::len).max().unwrap_or(0);
Self {
generated_text: String::new(),
pending_bytes: Vec::new(),
diff --git a/rust/crates/ensu/src/model/migrations.rs b/rust/crates/ensu/src/model/migrations.rs
index d5d7bfb30d..e79eb93773 100644
--- a/rust/crates/ensu/src/model/migrations.rs
+++ b/rust/crates/ensu/src/model/migrations.rs
@@ -218,9 +218,8 @@ fn is_non_empty_file(path: &Path) -> bool {
}
fn looks_like_gguf(path: &Path) -> bool {
- let mut file = match File::open(path) {
- Ok(file) => file,
- Err(_) => return false,
+ let Ok(mut file) = File::open(path) else {
+ return false;
};
let mut header = [0u8; 4];
file.read_exact(&mut header).is_ok() && &header == b"GGUF"
diff --git a/rust/crates/ensu/src/retrieval/pack.rs b/rust/crates/ensu/src/retrieval/pack.rs
index 31ef7e850f..ab8228db29 100644
--- a/rust/crates/ensu/src/retrieval/pack.rs
+++ b/rust/crates/ensu/src/retrieval/pack.rs
@@ -71,13 +71,9 @@ pub fn reconcile_knowledge_pack(
let mut valid = Vec::<(String, PathBuf)>::new();
let mut invalid = Vec::<PathBuf>::new();
for entry in fs::read_dir(pack_root)? {
- let entry = match entry {
- Ok(entry) => entry,
- Err(_) => continue,
- };
- let file_type = match entry.file_type() {
- Ok(file_type) => file_type,
- Err(_) => continue,
+ let Ok(entry) = entry else { continue };
+ let Ok(file_type) = entry.file_type() else {
+ continue;
};
if !file_type.is_dir() {
continue;
diff --git a/rust/crates/ensu/src/transcription/text.rs b/rust/crates/ensu/src/transcription/text.rs
index 20d9d76f1b..e9ac5adffd 100644
--- a/rust/crates/ensu/src/transcription/text.rs
+++ b/rust/crates/ensu/src/transcription/text.rs
@@ -39,7 +39,7 @@ fn collapse_stutters(text: &str) -> String {
let word = words[i];
let word_lower = word.to_lowercase();
- if word_lower.len() <= 2 && word_lower.chars().all(|c| c.is_alphabetic()) {
+ if word_lower.len() <= 2 && word_lower.chars().all(char::is_alphabetic) {
let mut count = 1;
while i + count < words.len() && words[i + count].to_lowercase() == word_lower {
count += 1;
diff --git a/rust/crates/exif/src/motion.rs b/rust/crates/exif/src/motion.rs
index 19b44751ee..96131900f3 100644
--- a/rust/crates/exif/src/motion.rs
+++ b/rust/crates/exif/src/motion.rs
@@ -21,9 +21,9 @@ pub(crate) fn read<R: Read + Seek>(
}
let footer = reader.array::<8>(reader.len - 8)?;
let mut starts = Vec::new();
- let result = samsung(reader, state, &footer, &mut starts);
+ let result = samsung(reader, state, footer, &mut starts);
state.recover(reader.len - 8, result)?;
- let result = oplus(reader, state, &footer, &mut starts);
+ let result = oplus(reader, state, footer, &mut starts);
state.recover(reader.len - 8, result)?;
let result = xmp_starts(state, reader.len, &mut starts);
state.recover(0, result)?;
@@ -107,7 +107,7 @@ fn xmp_starts(state: &State, len: u64, starts: &mut Vec<u64>) -> Result<(), Erro
fn oplus<R: Read + Seek>(
reader: &mut Reader<'_, R>,
state: &mut State,
- footer: &[u8; 8],
+ footer: [u8; 8],
starts: &mut Vec<u64>,
) -> Result<(), Error> {
if &footer[..4] != b"jxrs" {
@@ -167,13 +167,13 @@ fn oplus<R: Read + Seek>(
fn samsung<R: Read + Seek>(
reader: &mut Reader<'_, R>,
state: &mut State,
- footer: &[u8; 8],
+ footer: [u8; 8],
starts: &mut Vec<u64>,
) -> Result<(), Error> {
if &footer[4..] != b"SEFT" {
return Ok(());
}
- let len = u64::from(le32(footer));
+ let len = u64::from(le32(&footer));
let start = reader
.len
.checked_sub(len + 8)
diff --git a/rust/crates/exif/tests/integration/common.rs b/rust/crates/exif/tests/integration/common.rs
index 989eaf412e..63c6d01e80 100644
--- a/rust/crates/exif/tests/integration/common.rs
+++ b/rust/crates/exif/tests/integration/common.rs
@@ -110,14 +110,14 @@ pub fn xmp(body: &str) -> String {
)
}
-pub fn box_bytes(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
+pub fn box_bytes(kind: [u8; 4], data: &[u8]) -> Vec<u8> {
let mut result = ((data.len() + 8) as u32).to_be_bytes().to_vec();
result.extend(kind);
result.extend(data);
result
}
-pub fn png_chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
+pub fn png_chunk(kind: [u8; 4], data: &[u8]) -> Vec<u8> {
let mut result = (data.len() as u32).to_be_bytes().to_vec();
result.extend(kind);
result.extend(data);
@@ -126,14 +126,14 @@ pub fn png_chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
}
pub fn heif(exif: &[u8], method: u16, split: bool) -> Vec<u8> {
- let ftyp = box_bytes(b"ftyp", b"heic\0\0\0\0mif1heic");
+ let ftyp = box_bytes(*b"ftyp", b"heic\0\0\0\0mif1heic");
let mut infe = vec![2, 0, 0, 0, 0, 2, 0, 0];
infe.extend(b"Exif\0");
let iinf = box_bytes(
- b"iinf",
- &[vec![0, 0, 0, 0, 0, 1], box_bytes(b"infe", &infe)].concat(),
+ *b"iinf",
+ &[vec![0, 0, 0, 0, 0, 1], box_bytes(*b"infe", &infe)].concat(),
);
- let pitm = box_bytes(b"pitm", &[0, 0, 0, 0, 0, 1]);
+ let pitm = box_bytes(*b"pitm", &[0, 0, 0, 0, 0, 1]);
let mut ispe = vec![0; 4];
ispe.extend(800u32.to_be_bytes());
ispe.extend(600u32.to_be_bytes());
@@ -142,16 +142,16 @@ pub fn heif(exif: &[u8], method: u16, split: bool) -> Vec<u8> {
.flat_map(u32::to_be_bytes)
.collect();
let ipco = box_bytes(
- b"ipco",
+ *b"ipco",
&[
- box_bytes(b"ispe", &ispe),
- box_bytes(b"irot", &[1]),
- box_bytes(b"clap", &clap),
+ box_bytes(*b"ispe", &ispe),
+ box_bytes(*b"irot", &[1]),
+ box_bytes(*b"clap", &clap),
]
.concat(),
);
- let ipma = box_bytes(b"ipma", &[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 3, 1, 0x82, 0x83]);
- let iprp = box_bytes(b"iprp", &[ipco, ipma].concat());
+ let ipma = box_bytes(*b"ipma", &[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 3, 1, 0x82, 0x83]);
+ let iprp = box_bytes(*b"iprp", &[ipco, ipma].concat());
let data = [vec![0; 4], exif.to_vec()].concat();
let extents = if split {
vec![(0, 10), (10, data.len() - 10)]
@@ -173,13 +173,13 @@ pub fn heif(exif: &[u8], method: u16, split: bool) -> Vec<u8> {
iloc[base_position..base_position + 4]
.copy_from_slice(&((ftyp.len() + meta_size + 8) as u32).to_be_bytes());
}
- let mut meta = [vec![0; 4], pitm, iinf, iprp, box_bytes(b"iloc", &iloc)].concat();
+ let mut meta = [vec![0; 4], pitm, iinf, iprp, box_bytes(*b"iloc", &iloc)].concat();
if method == 1 {
- meta.extend(box_bytes(b"idat", &data));
+ meta.extend(box_bytes(*b"idat", &data));
}
- let mut result = [ftyp, box_bytes(b"meta", &meta)].concat();
+ let mut result = [ftyp, box_bytes(*b"meta", &meta)].concat();
if method == 0 {
- result.extend(box_bytes(b"mdat", &data));
+ result.extend(box_bytes(*b"mdat", &data));
}
result
}
diff --git a/rust/crates/exif/tests/integration/dimensions.rs b/rust/crates/exif/tests/integration/dimensions.rs
index b0d57fc7a8..998cbee690 100644
--- a/rust/crates/exif/tests/integration/dimensions.rs
+++ b/rust/crates/exif/tests/integration/dimensions.rs
@@ -221,28 +221,28 @@ fn transformed_heif(order: &[u8]) -> Vec<u8> {
.flat_map(u32::to_be_bytes)
.collect();
let properties = [
- box_bytes(b"ispe", &ispe),
- box_bytes(b"clap", &clap),
- box_bytes(b"irot", &[1]),
- box_bytes(b"imir", &[0]),
- box_bytes(b"irot", &[2]),
+ box_bytes(*b"ispe", &ispe),
+ box_bytes(*b"clap", &clap),
+ box_bytes(*b"irot", &[1]),
+ box_bytes(*b"imir", &[0]),
+ box_bytes(*b"irot", &[2]),
]
.concat();
let mut associations = vec![0, 0, 0, 0, 0, 0, 0, 2, 0, 1, order.len() as u8];
associations.extend(order);
associations.extend([0, 2, 1, 5]);
[
- box_bytes(b"ftyp", b"heic\0\0\0\0mif1"),
+ box_bytes(*b"ftyp", b"heic\0\0\0\0mif1"),
box_bytes(
- b"meta",
+ *b"meta",
&[
vec![0; 4],
- box_bytes(b"pitm", &[0, 0, 0, 0, 0, 1]),
+ box_bytes(*b"pitm", &[0, 0, 0, 0, 0, 1]),
box_bytes(
- b"iprp",
+ *b"iprp",
&[
- box_bytes(b"ipco", &properties),
- box_bytes(b"ipma", &associations),
+ box_bytes(*b"ipco", &properties),
+ box_bytes(*b"ipma", &associations),
]
.concat(),
),
diff --git a/rust/crates/exif/tests/integration/formats.rs b/rust/crates/exif/tests/integration/formats.rs
index ef6e9521a1..7bc1bea9bf 100644
--- a/rust/crates/exif/tests/integration/formats.rs
+++ b/rust/crates/exif/tests/integration/formats.rs
@@ -256,21 +256,21 @@ fn heif_protected_metadata_preserves_image_dimensions() {
let mut location = vec![1, 0, 0, 0, 0x44, 0, 0, 1, 0, 2, 0, 1, 0, 0, 0, 1];
location.extend(0u32.to_be_bytes());
location.extend((data.len() as u32).to_be_bytes());
- let image_size = box_bytes(b"ispe", &[0u32, 640, 480].map(u32::to_be_bytes).concat());
- let mut properties = box_bytes(b"ipco", &image_size);
- properties.extend(box_bytes(b"ipma", &[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1]));
+ let image_size = box_bytes(*b"ispe", &[0u32, 640, 480].map(u32::to_be_bytes).concat());
+ let mut properties = box_bytes(*b"ipco", &image_size);
+ properties.extend(box_bytes(*b"ipma", &[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1]));
let mut meta = vec![0; 4];
- meta.extend(box_bytes(b"pitm", &[0, 0, 0, 0, 0, 1]));
+ meta.extend(box_bytes(*b"pitm", &[0, 0, 0, 0, 0, 1]));
meta.extend(box_bytes(
- b"iinf",
- &[vec![0, 0, 0, 0, 0, 1], box_bytes(b"infe", &info)].concat(),
+ *b"iinf",
+ &[vec![0, 0, 0, 0, 0, 1], box_bytes(*b"infe", &info)].concat(),
));
- meta.extend(box_bytes(b"iloc", &location));
- meta.extend(box_bytes(b"iprp", &properties));
- meta.extend(box_bytes(b"idat", data));
+ meta.extend(box_bytes(*b"iloc", &location));
+ meta.extend(box_bytes(*b"iprp", &properties));
+ meta.extend(box_bytes(*b"idat", data));
let bytes = [
- box_bytes(b"ftyp", b"heic\0\0\0\0mif1"),
- box_bytes(b"meta", &meta),
+ box_bytes(*b"ftyp", b"heic\0\0\0\0mif1"),
+ box_bytes(*b"meta", &meta),
]
.concat();
for mode in [Mode::Summary, Mode::Details] {
@@ -336,27 +336,27 @@ fn heif_metadata_prefers_primary_references() {
entry.extend(mime.as_bytes());
entry.extend([0, 0]);
}
- info.extend(box_bytes(b"infe", &entry));
+ info.extend(box_bytes(*b"infe", &entry));
locations.extend([id, 1, 0, 1].map(u16::to_be_bytes).concat());
locations.extend((data.len() as u32).to_be_bytes());
locations.extend((value.len() as u32).to_be_bytes());
data.extend(value);
if let Some(target) = target {
references.extend(box_bytes(
- b"cdsc",
+ *b"cdsc",
&[id, 1, target].map(u16::to_be_bytes).concat(),
));
}
}
let mut meta = vec![0; 4];
- meta.extend(box_bytes(b"pitm", &[0, 0, 0, 0, 0, 1]));
- meta.extend(box_bytes(b"iinf", &info));
- meta.extend(box_bytes(b"iloc", &locations));
- meta.extend(box_bytes(b"iref", &references));
- meta.extend(box_bytes(b"idat", &data));
+ meta.extend(box_bytes(*b"pitm", &[0, 0, 0, 0, 0, 1]));
+ meta.extend(box_bytes(*b"iinf", &info));
+ meta.extend(box_bytes(*b"iloc", &locations));
+ meta.extend(box_bytes(*b"iref", &references));
+ meta.extend(box_bytes(*b"idat", &data));
let bytes = [
- box_bytes(b"ftyp", b"heic\0\0\0\0mif1"),
- box_bytes(b"meta", &meta),
+ box_bytes(*b"ftyp", b"heic\0\0\0\0mif1"),
+ box_bytes(*b"meta", &meta),
]
.concat();
for mode in [Mode::Summary, Mode::Details] {
@@ -397,9 +397,9 @@ fn png_keywords_use_latin1_and_text_obeys_its_chunk_encoding() {
] {
let bytes = [
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]),
- png_chunk(kind, &value),
- png_chunk(b"IEND", &[]),
+ png_chunk(*b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]),
+ png_chunk(*kind, &value),
+ png_chunk(*b"IEND", &[]),
]
.concat();
let details = read(&bytes, Mode::Details);
@@ -468,13 +468,13 @@ fn png_summary_skips_text_within_a_small_read_budget() {
};
let bytes = [
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 2, 8, 2, 0, 0, 0]),
+ png_chunk(*b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 2, 8, 2, 0, 0, 0]),
png_chunk(
- kind,
+ *kind,
&[vec![b'C'; 79], vec![0], fields.to_vec(), text].concat(),
),
- png_chunk(b"eXIf", &tiff(&[(0x112, 3, 1, vec![6, 0])], false)),
- png_chunk(b"IEND", &[]),
+ png_chunk(*b"eXIf", &tiff(&[(0x112, 3, 1, vec![6, 0])], false)),
+ png_chunk(*b"IEND", &[]),
]
.concat();
let limits = ente_exif::Limits {
@@ -643,9 +643,9 @@ fn extended_xmp_reorders_fragments_and_rejects_overlap() {
#[test]
fn motion_requires_real_boxes_and_respects_explicit_disable() {
let video = [
- box_bytes(b"ftyp", b"isom\0\0\0\0isom"),
- box_bytes(b"moov", &[]),
- box_bytes(b"mdat", &[0; 256]),
+ box_bytes(*b"ftyp", b"isom\0\0\0\0isom"),
+ box_bytes(*b"moov", &[]),
+ box_bytes(*b"mdat", &[0; 256]),
]
.concat();
for flag in ["0", "1"] {
@@ -676,9 +676,9 @@ fn motion_requires_real_boxes_and_respects_explicit_disable() {
#[test]
fn motion_directory_accounts_for_primary_padding() {
let video = [
- box_bytes(b"ftyp", b"isom\0\0\0\0isom"),
- box_bytes(b"moov", &[]),
- box_bytes(b"mdat", &[0; 256]),
+ box_bytes(*b"ftyp", b"isom\0\0\0\0isom"),
+ box_bytes(*b"moov", &[]),
+ box_bytes(*b"mdat", &[0; 256]),
]
.concat();
let xml = xmp(&format!(
@@ -702,11 +702,11 @@ fn png_text_encoding_and_bad_compressed_block_recovery() {
let ihdr = [vec![0, 0, 0, 1, 0, 0, 0, 1], vec![8, 2, 0, 0, 0]].concat();
let bytes = [
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"IHDR", &ihdr),
- png_chunk(b"tEXt", b"Author\0Andr\xe9"),
- png_chunk(b"iTXt", "Description\0\0\0\0\0Snow β˜ƒ".as_bytes()),
- png_chunk(b"zTXt", b"Broken\0\0invalid zlib"),
- png_chunk(b"IEND", &[]),
+ png_chunk(*b"IHDR", &ihdr),
+ png_chunk(*b"tEXt", b"Author\0Andr\xe9"),
+ png_chunk(*b"iTXt", "Description\0\0\0\0\0Snow β˜ƒ".as_bytes()),
+ png_chunk(*b"zTXt", b"Broken\0\0invalid zlib"),
+ png_chunk(*b"IEND", &[]),
]
.concat();
let metadata = read(&bytes, Mode::Details);
@@ -728,9 +728,9 @@ fn motion_accepts_compatible_brands_but_not_the_minor_version() {
(b"newv\0\0\0\0iso".as_slice(), false, true),
] {
let video = [
- box_bytes(b"ftyp", brands),
- box_bytes(b"moov", &[]),
- box_bytes(b"mdat", &[0; 16]),
+ box_bytes(*b"ftyp", brands),
+ box_bytes(*b"moov", &[]),
+ box_bytes(*b"mdat", &[0; 16]),
]
.concat();
let packet = xmp(&format!(
@@ -755,7 +755,10 @@ fn motion_accepts_compatible_brands_but_not_the_minor_version() {
#[test]
fn png_itxt_preserves_languages_with_and_without_compression() {
let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec();
- bytes.extend(png_chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]));
+ bytes.extend(png_chunk(
+ *b"IHDR",
+ &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0],
+ ));
for (language, text, compressed) in [
("en", "Snow", false),
("fr", "Neige", true),
@@ -770,9 +773,9 @@ fn png_itxt_preserves_languages_with_and_without_compression() {
} else {
text.as_bytes().to_vec()
});
- bytes.extend(png_chunk(b"iTXt", &data));
+ bytes.extend(png_chunk(*b"iTXt", &data));
}
- bytes.extend(png_chunk(b"IEND", &[]));
+ bytes.extend(png_chunk(*b"IEND", &[]));
let metadata = read(&bytes, Mode::Details);
let values: Vec<_> = metadata
.properties("urn:png:text", "Description")
diff --git a/rust/crates/exif/tests/integration/jxl.rs b/rust/crates/exif/tests/integration/jxl.rs
index 33cd013056..5724b61c3a 100644
--- a/rust/crates/exif/tests/integration/jxl.rs
+++ b/rust/crates/exif/tests/integration/jxl.rs
@@ -67,10 +67,10 @@ fn codestream_wins_over_stale_exif_size_and_orientation() {
let exif = [2u32.to_be_bytes().as_slice(), b"--", &exif].concat();
for orientation in [None, Some(1), Some(6)] {
let bytes = container(&[
- box_bytes(b"Exif", &exif),
- box_bytes(b"jxlc", &header(false, 173, 211, 0, 0, orientation)),
+ box_bytes(*b"Exif", &exif),
+ box_bytes(*b"jxlc", &header(false, 173, 211, 0, 0, orientation)),
box_bytes(
- b"xml ",
+ *b"xml ",
xmp("<d:description>coast</d:description>").as_bytes(),
),
]);
@@ -105,7 +105,7 @@ fn split_headers_can_cross_every_byte_boundary() {
let bytes = container(&[
part(0, &stream[..split]),
box_bytes(
- b"xml ",
+ *b"xml ",
xmp("<d:description>between parts</d:description>").as_bytes(),
),
part(1, &[]),
@@ -155,9 +155,9 @@ fn invalid_box_sizes_and_codestream_sequences_fail() {
vec![part(0x8000_0001, &stream)],
vec![part(0, &stream), part(0x8000_0000, &[])],
vec![part(0x8000_0000, &stream), part(0x8000_0001, &[])],
- vec![part(0, &stream), box_bytes(b"jxlc", &stream)],
- vec![box_bytes(b"jxlc", &stream), box_bytes(b"jxlc", &stream)],
- vec![box_bytes(b"jxlp", &[0, 0, 0])],
+ vec![part(0, &stream), box_bytes(*b"jxlc", &stream)],
+ vec![box_bytes(*b"jxlc", &stream), box_bytes(*b"jxlc", &stream)],
+ vec![box_bytes(*b"jxlp", &[0, 0, 0])],
vec![b"\0\0\0\x07jxlc".to_vec()],
vec![b"\0\0\0\x01jxlc\0\0\0\0\0\0\0\x0f".to_vec()],
vec![b"\0\0\0\x01jxlc\xff\xff\xff\xff\xff\xff\xff\xff".to_vec()],
@@ -182,9 +182,9 @@ fn brotli_metadata_uses_the_same_exif_and_xmp_paths() {
.concat();
let xml = xmp("<d:description>星空</d:description>");
let bytes = container(&[
- box_bytes(b"jxlc", &header(true, 24, 40, 0, 0, None)),
- brob(b"Exif", &stored_brotli(&exif)),
- brob(b"xml ", &stored_brotli(xml.as_bytes())),
+ box_bytes(*b"jxlc", &header(true, 24, 40, 0, 0, None)),
+ brob(*b"Exif", &stored_brotli(&exif)),
+ brob(*b"xml ", &stored_brotli(xml.as_bytes())),
]);
for mode in [Mode::Summary, Mode::Details] {
let metadata = read(&bytes, mode);
@@ -206,8 +206,8 @@ fn compressed_output_grows_within_an_aggregate_budget() {
0x1b, 0x12, 0x14, 0xaa, 0x82, 0xeb, 0x4d, 0x5f, 0xad, 0xc1, 0x81, 0xe6, 0x74, 0x94, 0xa8,
0x8e, 0x46, 0x70, 0xec, 0xf3, 0x27, 0x01, 0x72, 0x4c, 0xa1, 0x20,
];
- let stream = box_bytes(b"jxlc", &header(true, 24, 40, 0, 0, None));
- let encoded = brob(b"xml ", COMPRESSED);
+ let stream = box_bytes(*b"jxlc", &header(true, 24, 40, 0, 0, None));
+ let encoded = brob(*b"xml ", COMPRESSED);
let plain = br#"<r:RDF xmlns:r="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><r:Description xmlns:d="http://purl.org/dc/elements/1.1/"><d:description>woods</d:description></r:Description></r:RDF>"#;
let exact = plain.len() + 40000;
let mut limits = Limits {
@@ -223,7 +223,7 @@ fn compressed_output_grows_within_an_aggregate_budget() {
assert!(metadata.issues.is_empty());
assert_eq!(metadata.xmp_description(None), Some("woods"));
assert!(metadata.statistics.bytes_read < 300);
- let repeated = container(&[stream.clone(), encoded.clone(), encoded.clone()]);
+ let repeated = container(&[stream, encoded.clone(), encoded]);
assert!(matches!(
ente_exif::read(&mut Cursor::new(&repeated), Mode::Summary, limits),
Err(Error::Limit("Brotli output"))
@@ -249,9 +249,9 @@ fn malformed_compressed_metadata_recovers_but_limits_stop() {
] {
let metadata = read(
&container(&[
- box_bytes(b"jxlc", &header(true, 24, 40, 0, 0, None)),
- brob(b"xml ", &bad),
- box_bytes(b"xml ", xml.as_bytes()),
+ box_bytes(*b"jxlc", &header(true, 24, 40, 0, 0, None)),
+ brob(*b"xml ", &bad),
+ box_bytes(*b"xml ", xml.as_bytes()),
]),
Mode::Summary,
);
@@ -259,8 +259,8 @@ fn malformed_compressed_metadata_recovers_but_limits_stop() {
assert_eq!(metadata.xmp_description(None), Some("after"));
}
let bytes = container(&[
- box_bytes(b"jxlc", &header(true, 24, 40, 0, 0, None)),
- brob(b"xml ", &[0x0f]),
+ box_bytes(*b"jxlc", &header(true, 24, 40, 0, 0, None)),
+ brob(*b"xml ", &[0x0f]),
]);
assert!(matches!(
ente_exif::read(&mut Cursor::new(bytes), Mode::Summary, Limits::default()),
@@ -272,11 +272,11 @@ fn malformed_compressed_metadata_recovers_but_limits_stop() {
fn unknown_boxes_are_skipped_and_brob_cannot_wrap_codestreams() {
let metadata = read(
&container(&[
- box_bytes(b"jxlc", &header(true, 24, 40, 0, 0, None)),
- brob(b"jumb", &[0x11]),
- brob(b"brob", &[]),
- brob(b"jxlc", &[]),
- box_bytes(b"free", &vec![0; 10000]),
+ box_bytes(*b"jxlc", &header(true, 24, 40, 0, 0, None)),
+ brob(*b"jumb", &[0x11]),
+ brob(*b"brob", &[]),
+ brob(*b"jxlc", &[]),
+ box_bytes(*b"free", &vec![0; 10000]),
]),
Mode::Summary,
);
@@ -293,7 +293,7 @@ fn header_truncations_and_mutations_remain_bounded() {
&header(false, 400001, 500001, 0, 3, Some(7))[1..],
),
brob(
- b"xml ",
+ *b"xml ",
&stored_brotli(xmp("<d:description>green</d:description>").as_bytes()),
),
]);
@@ -319,18 +319,18 @@ fn header_truncations_and_mutations_remain_bounded() {
fn container(boxes: &[Vec<u8>]) -> Vec<u8> {
[
b"\0\0\0\x0cJXL \r\n\x87\n".to_vec(),
- box_bytes(b"ftyp", b"jxl \0\0\0\0jxl "),
+ box_bytes(*b"ftyp", b"jxl \0\0\0\0jxl "),
boxes.concat(),
]
.concat()
}
fn part(index: u32, bytes: &[u8]) -> Vec<u8> {
- box_bytes(b"jxlp", &[index.to_be_bytes().as_slice(), bytes].concat())
+ box_bytes(*b"jxlp", &[index.to_be_bytes().as_slice(), bytes].concat())
}
-fn brob(kind: &[u8; 4], bytes: &[u8]) -> Vec<u8> {
- box_bytes(b"brob", &[kind.as_slice(), bytes].concat())
+fn brob(kind: [u8; 4], bytes: &[u8]) -> Vec<u8> {
+ box_bytes(*b"brob", &[kind.as_slice(), bytes].concat())
}
fn header(
diff --git a/rust/crates/exif/tests/integration/limits.rs b/rust/crates/exif/tests/integration/limits.rs
index d52dc17e2d..dd3ac0b4d1 100644
--- a/rust/crates/exif/tests/integration/limits.rs
+++ b/rust/crates/exif/tests/integration/limits.rs
@@ -51,8 +51,11 @@ fn compressed_png_cannot_expand_beyond_budget() {
let text = miniz_oxide::deflate::compress_to_vec_zlib(&vec![b'a'; 100_000], 6);
let bytes = [
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"zTXt", &[b"XML:com.adobe.xmp\0\0".to_vec(), text].concat()),
- png_chunk(b"IEND", &[]),
+ png_chunk(
+ *b"zTXt",
+ &[b"XML:com.adobe.xmp\0\0".to_vec(), text].concat(),
+ ),
+ png_chunk(*b"IEND", &[]),
]
.concat();
assert!(matches!(
@@ -63,7 +66,7 @@ fn compressed_png_cannot_expand_beyond_budget() {
let packet = xmp(&" ".repeat(4000));
let compressed = miniz_oxide::deflate::compress_to_vec_zlib(packet.as_bytes(), 6);
let chunk = png_chunk(
- b"zTXt",
+ *b"zTXt",
&[b"XML:com.adobe.xmp\0\0".to_vec(), compressed].concat(),
);
let mut repeated = b"\x89PNG\r\n\x1a\n".to_vec();
@@ -162,9 +165,9 @@ fn png_text_limits_apply_to_utf8_output_before_conversion() {
] {
let bytes = [
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]),
- png_chunk(kind, &payload),
- png_chunk(b"IEND", &[]),
+ png_chunk(*b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]),
+ png_chunk(*kind, &payload),
+ png_chunk(*b"IEND", &[]),
]
.concat();
let result = ente_exif::read(&mut Cursor::new(&bytes), Mode::Details, limits);
@@ -202,7 +205,7 @@ fn undersized_jxrs_is_recoverable() {
fn png_language_obeys_value_and_retention_budgets() {
let bytes = [
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"iTXt", b"Note\0\0\0en-US\0\0x"),
+ png_chunk(*b"iTXt", b"Note\0\0\0en-US\0\0x"),
]
.concat();
for limits in [
diff --git a/rust/crates/exif/tests/integration/png_profiles.rs b/rust/crates/exif/tests/integration/png_profiles.rs
index 40244336f1..107b9f0c22 100644
--- a/rust/crates/exif/tests/integration/png_profiles.rs
+++ b/rust/crates/exif/tests/integration/png_profiles.rs
@@ -21,9 +21,9 @@ fn profiles_use_existing_exif_xmp_and_iptc_readers() {
.concat();
for kind in [b"tEXt", b"zTXt", b"iTXt"] {
let bytes = png(&[
- profile(kind, "exif", &[b"Exif\0\0".as_slice(), &exif].concat()),
- profile(kind, "iptc", &resource),
- profile(kind, "xmp", packet.as_bytes()),
+ profile(*kind, "exif", &[b"Exif\0\0".as_slice(), &exif].concat()),
+ profile(*kind, "iptc", &resource),
+ profile(*kind, "xmp", packet.as_bytes()),
]);
for mode in [Mode::Summary, Mode::Details] {
let metadata = read(&bytes, mode);
@@ -52,9 +52,9 @@ fn app1_profiles_and_direct_iim_are_supported() {
]
.concat();
let bytes = png(&[
- profile(b"zTXt", "APP1", &[b"Exif\0\0".as_slice(), &exif].concat()),
- profile(b"zTXt", "APP1", &xml),
- profile(b"tEXt", "iptc", b"\x1c\x02\x78\0\x04dawn"),
+ profile(*b"zTXt", "APP1", &[b"Exif\0\0".as_slice(), &exif].concat()),
+ profile(*b"zTXt", "APP1", &xml),
+ profile(*b"tEXt", "iptc", b"\x1c\x02\x78\0\x04dawn"),
]);
let metadata = read(&bytes, Mode::Summary);
assert!(metadata.issues.is_empty());
@@ -69,7 +69,7 @@ fn app1_profiles_and_direct_iim_are_supported() {
#[test]
fn malformed_profiles_do_not_hide_later_metadata() {
let good = profile(
- b"tEXt",
+ *b"tEXt",
"xmp",
xmp("<d:description>later</d:description>").as_bytes(),
);
@@ -82,7 +82,7 @@ fn malformed_profiles_do_not_hide_later_metadata() {
"\nexif\n184467440737095516160\n00",
] {
let bad = png_chunk(
- b"tEXt",
+ *b"tEXt",
&[b"Raw profile type exif\0".as_slice(), text.as_bytes()].concat(),
);
let metadata = read(&png(&[bad, good.clone()]), Mode::Summary);
@@ -100,7 +100,7 @@ fn decoded_profiles_share_the_expansion_budget() {
],
false,
);
- let bytes = png(&[profile(b"zTXt", "exif", &exif)]);
+ let bytes = png(&[profile(*b"zTXt", "exif", &exif)]);
let limits = Limits {
value_bytes: 32,
..Default::default()
@@ -120,7 +120,7 @@ fn decoded_profiles_share_the_expansion_budget() {
#[test]
fn raw_profiles_tolerate_hex_case_and_ascii_whitespace() {
let text = b"Raw profile type iptc\0\ngeneric profile\n 8\n1c 02 78 00 03 73\t65\r\n41\n";
- let metadata = read(&png(&[png_chunk(b"tEXt", text)]), Mode::Summary);
+ let metadata = read(&png(&[png_chunk(*b"tEXt", text)]), Mode::Summary);
assert!(metadata.issues.is_empty());
assert_eq!(
metadata.iptc_caption(TextEncoding::Ascii).as_deref(),
@@ -128,7 +128,7 @@ fn raw_profiles_tolerate_hex_case_and_ascii_whitespace() {
);
}
-fn profile(kind: &[u8; 4], name: &str, bytes: &[u8]) -> Vec<u8> {
+fn profile(kind: [u8; 4], name: &str, bytes: &[u8]) -> Vec<u8> {
use std::fmt::Write;
let mut text = format!("\n{name}\n{:8}\n", bytes.len());
for (index, byte) in bytes.iter().enumerate() {
@@ -139,14 +139,14 @@ fn profile(kind: &[u8; 4], name: &str, bytes: &[u8]) -> Vec<u8> {
}
text.push('\n');
let mut data = format!("Raw profile type {name}\0").into_bytes();
- if kind == b"zTXt" {
+ if kind == *b"zTXt" {
data.push(0);
data.extend(miniz_oxide::deflate::compress_to_vec_zlib(
text.as_bytes(),
6,
));
} else {
- if kind == b"iTXt" {
+ if kind == *b"iTXt" {
data.extend([0; 4]);
}
data.extend(text.as_bytes());
@@ -163,9 +163,9 @@ fn png(chunks: &[Vec<u8>]) -> Vec<u8> {
.concat();
[
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"IHDR", &ihdr),
+ png_chunk(*b"IHDR", &ihdr),
chunks.concat(),
- png_chunk(b"IEND", &[]),
+ png_chunk(*b"IEND", &[]),
]
.concat()
}
diff --git a/rust/crates/exif/tests/integration/reader.rs b/rust/crates/exif/tests/integration/reader.rs
index 1901ceb992..40d8d68ed6 100644
--- a/rust/crates/exif/tests/integration/reader.rs
+++ b/rust/crates/exif/tests/integration/reader.rs
@@ -132,10 +132,10 @@ fn png_metadata_after_image_data_and_compressed_xmp() {
ihdr.extend([8, 2, 0, 0, 0]);
let data = [
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"IHDR", &ihdr),
- png_chunk(b"IDAT", &vec![0; 1_000_000]),
- png_chunk(b"iTXt", &text),
- png_chunk(b"IEND", &[]),
+ png_chunk(*b"IHDR", &ihdr),
+ png_chunk(*b"IDAT", &vec![0; 1_000_000]),
+ png_chunk(*b"iTXt", &text),
+ png_chunk(*b"IEND", &[]),
]
.concat();
let metadata = read(&data, Mode::Summary);
@@ -198,9 +198,9 @@ fn truncations_and_header_mutations_never_panic() {
let packet = xmp("<d:subject><r:Bag><r:li>cafΓ©</r:li></r:Bag></d:subject>");
let png = [
b"\x89PNG\r\n\x1a\n".to_vec(),
- png_chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]),
- png_chunk(b"tEXt", b"Caf\xe9\0Caption"),
- png_chunk(b"IEND", &[]),
+ png_chunk(*b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]),
+ png_chunk(*b"tEXt", b"Caf\xe9\0Caption"),
+ png_chunk(*b"IEND", &[]),
]
.concat();
let seeds = [
diff --git a/rust/crates/image/src/color_management.rs b/rust/crates/image/src/color_management.rs
index 25f52ce58a..2634978a2b 100644
--- a/rust/crates/image/src/color_management.rs
+++ b/rust/crates/image/src/color_management.rs
@@ -5,7 +5,7 @@ use moxcms::{
};
use std::{
collections::VecDeque,
- sync::{Arc, Mutex, OnceLock},
+ sync::{Arc, Mutex, OnceLock, PoisonError},
};
static SRGB_PROFILE: OnceLock<ColorProfile> = OnceLock::new();
@@ -326,7 +326,7 @@ fn lock_profile_cache() -> std::sync::MutexGuard<'static, VecDeque<CachedIccProf
ICC_PROFILE_CACHE
.get_or_init(|| Mutex::new(VecDeque::with_capacity(ICC_PROFILE_CACHE_CAPACITY)))
.lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .unwrap_or_else(PoisonError::into_inner)
}
fn transform_options() -> TransformOptions {
diff --git a/rust/crates/image/src/decode.rs b/rust/crates/image/src/decode.rs
index 21b1adc75d..4ded16a57b 100644
--- a/rust/crates/image/src/decode.rs
+++ b/rust/crates/image/src/decode.rs
@@ -90,8 +90,7 @@ fn decode_with_image_crate(image_path: &str) -> ImageResult<DecodedDynamicImage>
Ok(decoded) => Ok(decoded),
Err(primary_error) if should_attempt_tiff_fallback(guessed_format) => {
eprintln!(
- "[ml][decode] image crate TIFF decode failed for '{}': {}. Retrying with tiff crate fallback",
- image_path, primary_error
+ "[ml][decode] image crate TIFF decode failed for '{image_path}': {primary_error}. Retrying with tiff crate fallback"
);
match decode_with_tiff_crate(image_path) {
@@ -539,7 +538,7 @@ mod tests {
#[test]
fn decode_applies_embedded_png_display_p3_profile() {
let display_p3_icc = ColorProfile::new_display_p3().encode().unwrap();
- let png = encode_rgb8_png_with_icc(&[128, 0, 0], display_p3_icc);
+ let png = encode_rgb8_png_with_icc([128, 0, 0], display_p3_icc);
let decoded = decode_image_from_bytes(&png).unwrap();
@@ -556,7 +555,7 @@ mod tests {
#[test]
fn decode_leaves_embedded_png_srgb_profile_unchanged() {
let srgb_icc = ColorProfile::new_srgb().encode().unwrap();
- let png = encode_rgb8_png_with_icc(&[128, 64, 32], srgb_icc);
+ let png = encode_rgb8_png_with_icc([128, 64, 32], srgb_icc);
let decoded = decode_image_from_bytes(&png).unwrap();
@@ -588,12 +587,12 @@ mod tests {
assert_eq!(decoded.rgb, vec![255, 0, 0, 0, 255, 0]);
}
- fn encode_rgb8_png_with_icc(pixel: &[u8; 3], icc_profile: Vec<u8>) -> Vec<u8> {
+ fn encode_rgb8_png_with_icc(pixel: [u8; 3], icc_profile: Vec<u8>) -> Vec<u8> {
let mut encoded = Vec::new();
let mut encoder = PngEncoder::new(&mut encoded);
encoder.set_icc_profile(icc_profile).unwrap();
encoder
- .write_image(pixel, 1, 1, ColorType::Rgb8.into())
+ .write_image(&pixel, 1, 1, ColorType::Rgb8.into())
.unwrap();
encoded
}
diff --git a/rust/crates/image/src/types.rs b/rust/crates/image/src/types.rs
index 9ea07bac27..b03fb43375 100644
--- a/rust/crates/image/src/types.rs
+++ b/rust/crates/image/src/types.rs
@@ -1,4 +1,4 @@
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Dimensions {
pub width: u32,
pub height: u32,
diff --git a/rust/crates/location/src/city.rs b/rust/crates/location/src/city.rs
index b7b4d77a2a..b15a07eb7d 100644
--- a/rust/crates/location/src/city.rs
+++ b/rust/crates/location/src/city.rs
@@ -883,6 +883,10 @@ fn invalid(reason: &'static str) -> Error {
Error::invalid(SECTION, reason)
}
+#[expect(
+ clippy::trivially_copy_pass_by_ref,
+ reason = "Iterator::min_by passes references to borrowed candidates"
+)]
fn compare_candidates(left: &&Candidate, right: &&Candidate) -> Ordering {
right
.rank
diff --git a/rust/crates/ml/examples/vecdb_bench.rs b/rust/crates/ml/examples/vecdb_bench.rs
index 93cc90fcaa..53a08e76a2 100644
--- a/rust/crates/ml/examples/vecdb_bench.rs
+++ b/rust/crates/ml/examples/vecdb_bench.rs
@@ -69,7 +69,7 @@ fn main() {
config
.scales
.iter()
- .map(|scale| scale.to_string())
+ .map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
);
@@ -409,10 +409,7 @@ fn search_phase(db: &VecDb, data: &BenchData, scale: usize) -> SearchTimings {
};
warm(db, &data.queries, &threshold_params);
let (threshold_total, threshold_results) = timed_searches(db, &data.queries, &threshold_params);
- let threshold_avg_hits = threshold_results
- .iter()
- .map(|found| found.len())
- .sum::<usize>() as f64
+ let threshold_avg_hits = threshold_results.iter().map(Vec::len).sum::<usize>() as f64
/ threshold_results.len().max(1) as f64;
let filtered_params = SearchParams {
limit: Some(SEARCH_K),
diff --git a/rust/crates/ml/src/clip/mod.rs b/rust/crates/ml/src/clip/mod.rs
index 6ef411754e..8d06a00545 100644
--- a/rust/crates/ml/src/clip/mod.rs
+++ b/rust/crates/ml/src/clip/mod.rs
@@ -23,8 +23,7 @@ pub(super) fn finish_embedding(
let mut embedding = if shape.len() == 2 {
if shape[0] != 1 {
return Err(MlError::Postprocess(format!(
- "unexpected {name} batch size in shape {:?}",
- shape
+ "unexpected {name} batch size in shape {shape:?}"
)));
}
output
@@ -32,8 +31,7 @@ pub(super) fn finish_embedding(
output
} else {
return Err(MlError::Postprocess(format!(
- "unsupported {name} output shape {:?}",
- shape
+ "unsupported {name} output shape {shape:?}"
)));
};
diff --git a/rust/crates/ml/src/clip/tokenizer.rs b/rust/crates/ml/src/clip/tokenizer.rs
index 3533259415..c80db25959 100644
--- a/rust/crates/ml/src/clip/tokenizer.rs
+++ b/rust/crates/ml/src/clip/tokenizer.rs
@@ -371,9 +371,8 @@ mod tests {
#[test]
fn rejects_incomplete_bpe_vocabulary_file() {
let truncated_vocab = "#version: 0.2\na b";
- let err = match ClipTextTokenizer::from_vocabulary(truncated_vocab) {
- Ok(_) => panic!("expected incomplete vocab to fail"),
- Err(err) => err,
+ let Err(err) = ClipTextTokenizer::from_vocabulary(truncated_vocab) else {
+ panic!("expected incomplete vocab to fail")
};
assert!(
err.to_string().contains("invalid clip vocab"),
diff --git a/rust/crates/ml/src/diagnostics.rs b/rust/crates/ml/src/diagnostics.rs
index ac6d49dc0e..fa8a38fe6d 100644
--- a/rust/crates/ml/src/diagnostics.rs
+++ b/rust/crates/ml/src/diagnostics.rs
@@ -1,7 +1,7 @@
use std::{
collections::HashMap,
sync::{
- Arc, Condvar, Mutex, MutexGuard,
+ Arc, Condvar, Mutex, MutexGuard, PoisonError,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant},
@@ -278,9 +278,7 @@ impl AnalysisMonitor {
}
fn lock_state(&self) -> MutexGuard<'_, MonitorState> {
- self.state
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}
diff --git a/rust/crates/ml/src/ocr/recognize.rs b/rust/crates/ml/src/ocr/recognize.rs
index 33ff2ae47d..979484329f 100644
--- a/rust/crates/ml/src/ocr/recognize.rs
+++ b/rust/crates/ml/src/ocr/recognize.rs
@@ -530,7 +530,7 @@ mod tests {
assert_eq!(batches, [vec![10, 20, 30, 40, 50, 60], vec![70, 80]]);
let texts: Vec<String> = results.into_iter().map(|r| r.text).collect();
- let expected: Vec<String> = widths.iter().map(|w| w.to_string()).collect();
+ let expected: Vec<String> = widths.iter().map(ToString::to_string).collect();
assert_eq!(texts, expected);
}
diff --git a/rust/crates/ml/src/onnx/webgpu.rs b/rust/crates/ml/src/onnx/webgpu.rs
index 67c46cfe88..ae685780c5 100644
--- a/rust/crates/ml/src/onnx/webgpu.rs
+++ b/rust/crates/ml/src/onnx/webgpu.rs
@@ -212,9 +212,8 @@ fn model_dir(model_path: &str) -> Option<PathBuf> {
test
))]
fn quarantined(dir: &Path) -> bool {
- let entries = match fs::read_dir(dir) {
- Ok(entries) => entries,
- Err(_) => return true,
+ let Ok(entries) = fs::read_dir(dir) else {
+ return true;
};
for entry in entries {
let Ok(entry) = entry else {
diff --git a/rust/crates/ml/src/pet/detect.rs b/rust/crates/ml/src/pet/detect.rs
index a053fdcdd0..ffe00fbafd 100644
--- a/rust/crates/ml/src/pet/detect.rs
+++ b/rust/crates/ml/src/pet/detect.rs
@@ -93,8 +93,7 @@ fn postprocess_pet_face_tensor<T: onnx::FloatTensorData>(
11
} else {
return Err(MlError::Postprocess(format!(
- "unexpected pet face detector output size: {} (shape: {:?})",
- total, output_shape
+ "unexpected pet face detector output size: {total} (shape: {output_shape:?})"
)));
}
} else {
diff --git a/rust/crates/ml/src/vecdb/log.rs b/rust/crates/ml/src/vecdb/log.rs
index 06a58c1425..e0ba968df7 100644
--- a/rust/crates/ml/src/vecdb/log.rs
+++ b/rust/crates/ml/src/vecdb/log.rs
@@ -2250,7 +2250,7 @@ mod tests {
*crc_flipped_tombstone.last_mut().unwrap() ^= 0x01;
let mut oversized_key_payload = payload.clone();
oversized_key_payload.push(0);
- let mut over_counted_attrs = payload.clone();
+ let mut over_counted_attrs = payload;
over_counted_attrs.push(17);
let mut truncated = good.clone();
truncated.pop();
diff --git a/rust/crates/ml/src/vecdb/store.rs b/rust/crates/ml/src/vecdb/store.rs
index f1ecc1f1e4..b694adf368 100644
--- a/rust/crates/ml/src/vecdb/store.rs
+++ b/rust/crates/ml/src/vecdb/store.rs
@@ -912,9 +912,8 @@ fn registry_holds_live(key: &Path) -> bool {
}
fn open_cost_from_files(path: &Path) -> OpenCost {
- let mut file = match File::open(path) {
- Ok(file) => file,
- Err(_) => return OpenCost::Absent,
+ let Ok(mut file) = File::open(path) else {
+ return OpenCost::Absent;
};
let log_len = match file.metadata() {
Ok(meta) => meta.len(),
@@ -2618,6 +2617,10 @@ mod tests {
let key = registry_key_for(&stalled_path).unwrap();
let slot = path_slot(&key);
let build_in_progress = lock_slot(&slot);
+ #[expect(
+ clippy::needless_collect,
+ reason = "Start both worker threads before releasing the slot lock"
+ )]
let stalled_openers: Vec<_> = (0..2)
.map(|_| {
let path = stalled_path.clone();
@@ -3249,7 +3252,7 @@ mod tests {
assert_eq!(
db.bulk_search(std::slice::from_ref(&query), &approx)
.unwrap(),
- vec![expected.clone()]
+ vec![expected]
);
assert_eq!(
db.bulk_search_stored(&stored_keys, 5, None, false, false)
@@ -4778,7 +4781,7 @@ mod tests {
db.add("seed", &vector).unwrap();
let log_bytes = db.stats().unwrap().log_bytes;
let keys = vec!["x".to_string(), "y".to_string()];
- let vectors = vec![vector.clone(), vector.clone()];
+ let vectors = vec![vector.clone(), vector];
assert!(matches!(
db.bulk_add_with_attrs(&keys, &vectors, &[None]),
Err(VecDbError::LengthMismatch {
diff --git a/rust/crates/photos/src/ml_db/queries/clip.rs b/rust/crates/photos/src/ml_db/queries/clip.rs
index 00aeffc16e..f170f37a68 100644
--- a/rust/crates/photos/src/ml_db/queries/clip.rs
+++ b/rust/crates/photos/src/ml_db/queries/clip.rs
@@ -23,7 +23,7 @@ pub struct EmbeddingVector {
pub embedding: Vec<f32>,
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClipRow {
pub file_id: i64,
pub embedding: Vec<u8>,
diff --git a/rust/crates/photos/src/ml_db/queries/pets.rs b/rust/crates/photos/src/ml_db/queries/pets.rs
index 54ed4eb595..5136fa9d95 100644
--- a/rust/crates/photos/src/ml_db/queries/pets.rs
+++ b/rust/crates/photos/src/ml_db/queries/pets.rs
@@ -34,21 +34,21 @@ pub struct PetBodyRow {
pub ml_version: i64,
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PetFaceVectorRow {
pub pet_face_id: String,
pub face_vector_id: Option<i64>,
pub species: i64,
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PetBodyVectorRow {
pub pet_body_id: String,
pub body_vector_id: Option<i64>,
pub species: i64,
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PetRowsForFiles {
pub faces: Vec<PetFaceVectorRow>,
pub bodies: Vec<PetBodyVectorRow>,
diff --git a/rust/crates/photos/src/ml_db/vector_encoding.rs b/rust/crates/photos/src/ml_db/vector_encoding.rs
index fa3b012ea9..c09db144eb 100644
--- a/rust/crates/photos/src/ml_db/vector_encoding.rs
+++ b/rust/crates/photos/src/ml_db/vector_encoding.rs
@@ -45,10 +45,7 @@ pub fn decode_evector(bytes: &[u8]) -> Result<Vec<f64>> {
}
pub fn encode_f32(values: impl IntoIterator<Item = f32>) -> Vec<u8> {
- values
- .into_iter()
- .flat_map(|value| value.to_le_bytes())
- .collect()
+ values.into_iter().flat_map(f32::to_le_bytes).collect()
}
pub fn decode_f32(bytes: &[u8]) -> Vec<f32> {
diff --git a/rust/crates/photos/src/motion_photo/mod.rs b/rust/crates/photos/src/motion_photo/mod.rs
index cd7419ab0b..81bc3d11d8 100644
--- a/rust/crates/photos/src/motion_photo/mod.rs
+++ b/rust/crates/photos/src/motion_photo/mod.rs
@@ -75,9 +75,8 @@ fn extract_motion_video(
index: Option<VideoIndex>,
) -> Result<Vec<u8>, MotionPhotoError> {
let video_index = index.or_else(|| get_motion_video_index(bytes));
- let video_index = match video_index {
- Some(value) => value,
- None => return Err(MotionPhotoError::VideoNotFound),
+ let Some(video_index) = video_index else {
+ return Err(MotionPhotoError::VideoNotFound);
};
if video_index.start >= video_index.end || video_index.end > bytes.len() {
@@ -95,9 +94,8 @@ pub fn extract_motion_video_file_from_path<P: AsRef<Path>, Q: AsRef<Path>>(
) -> Result<Option<PathBuf>, MotionPhotoError> {
validate_output_file_name(file_name)?;
- let video = match extract_motion_video_from_path(file_path, index)? {
- Some(data) => data,
- None => return Ok(None),
+ let Some(video) = extract_motion_video_from_path(file_path, index)? else {
+ return Ok(None);
};
fs::create_dir_all(destination_directory.as_ref())?;
let output = destination_directory.as_ref().join(file_name);
@@ -173,11 +171,11 @@ mod tests {
use std::fs;
use tempfile::tempdir;
- fn make_ftyp_box(brand: &[u8; 4]) -> Vec<u8> {
+ fn make_ftyp_box(brand: [u8; 4]) -> Vec<u8> {
let mut buf = Vec::with_capacity(16);
buf.extend_from_slice(&16u32.to_be_bytes());
buf.extend_from_slice(b"ftyp");
- buf.extend_from_slice(brand);
+ buf.extend_from_slice(&brand);
buf.extend_from_slice(&0u32.to_be_bytes());
buf
}
@@ -202,7 +200,7 @@ mod tests {
#[test]
fn finds_ftyp_box_in_jpeg_like_file() {
let mut bytes = b"jpeg-prefix".to_vec();
- bytes.extend_from_slice(&make_ftyp_box(b"mp42"));
+ bytes.extend_from_slice(&make_ftyp_box(*b"mp42"));
bytes.extend_from_slice(&[1, 2, 3, 4]);
let index = get_motion_video_index(&bytes).expect("video index should exist");
@@ -214,10 +212,10 @@ mod tests {
fn picks_largest_segment_when_multiple_ftyp_exist() {
let mut bytes = b"jpeg-prefix".to_vec();
let first_start = bytes.len();
- bytes.extend_from_slice(&make_ftyp_box(b"mp42"));
+ bytes.extend_from_slice(&make_ftyp_box(*b"mp42"));
bytes.extend_from_slice(&[0xAA; 500]);
let second_start = bytes.len();
- bytes.extend_from_slice(&make_ftyp_box(b"isom"));
+ bytes.extend_from_slice(&make_ftyp_box(*b"isom"));
bytes.extend_from_slice(&[0xBB; 50]);
let index = get_motion_video_index(&bytes).expect("video index should exist");
@@ -228,10 +226,10 @@ mod tests {
assert_eq!(extracted.len(), second_start - first_start);
let mut bytes2 = b"jpeg-prefix".to_vec();
- bytes2.extend_from_slice(&make_ftyp_box(b"mp42"));
+ bytes2.extend_from_slice(&make_ftyp_box(*b"mp42"));
bytes2.extend_from_slice(&[0xCC; 50]);
let second_start = bytes2.len();
- bytes2.extend_from_slice(&make_ftyp_box(b"isom"));
+ bytes2.extend_from_slice(&make_ftyp_box(*b"isom"));
bytes2.extend_from_slice(&[0xDD; 500]);
let index2 = get_motion_video_index(&bytes2).expect("video index should exist");
@@ -245,7 +243,7 @@ mod tests {
b"isom", b"mp41", b"mp42", b"avc1", b"iso2", b"M4V ", b"qt ",
] {
let mut bytes = b"jpeg-prefix-data".to_vec();
- bytes.extend_from_slice(&make_ftyp_box(brand));
+ bytes.extend_from_slice(&make_ftyp_box(*brand));
bytes.extend_from_slice(&[0xDE, 0xAD]);
let index = get_motion_video_index(&bytes)
.unwrap_or_else(|| panic!("should detect brand {:?}", std::str::from_utf8(brand)));
@@ -257,7 +255,7 @@ mod tests {
fn rejects_non_video_ftyp_brands() {
for brand in [b"heic", b"heif", b"mif1", b"avif"] {
let mut bytes = b"jpeg-prefix-data".to_vec();
- bytes.extend_from_slice(&make_ftyp_box(brand));
+ bytes.extend_from_slice(&make_ftyp_box(*brand));
bytes.extend_from_slice(&[0xDE, 0xAD]);
assert_eq!(
get_motion_video_index(&bytes),
@@ -285,7 +283,7 @@ mod tests {
#[test]
fn rejects_ftyp_at_file_start() {
- let mut bytes = make_ftyp_box(b"mp42");
+ let mut bytes = make_ftyp_box(*b"mp42");
bytes.extend_from_slice(b"moov-data-here");
assert_eq!(get_motion_video_index(&bytes), None);
}
diff --git a/rust/crates/space/src/client/keys.rs b/rust/crates/space/src/client/keys.rs
index 839562a03e..765f9c67e3 100644
--- a/rust/crates/space/src/client/keys.rs
+++ b/rust/crates/space/src/client/keys.rs
@@ -96,7 +96,7 @@ impl AccountSpaceCtx {
.ok_or_else(|| Error::InvalidInput("missing current profile".into()))?,
};
let next_space_key = generate_key();
- let space_root_key = self.get_or_create_space_root_key().await?;
+ let space_root_key = self.get_or_create_space_root_key()?;
let link_rotation = self.active_link_wrapper(space_id, &next_space_key).await?;
let request = RotateSpaceKeyRequest {
key_version: current.key_version,
diff --git a/rust/crates/space/src/client/mod.rs b/rust/crates/space/src/client/mod.rs
index 5db4dd60a1..c3a25b246b 100644
--- a/rust/crates/space/src/client/mod.rs
+++ b/rust/crates/space/src/client/mod.rs
@@ -139,11 +139,11 @@ impl AccountSpaceCtx {
&self.space_root_key
}
- pub async fn get_space_root_key(&self) -> Result<Option<Vec<u8>>> {
+ pub fn get_space_root_key(&self) -> Result<Option<Vec<u8>>> {
Ok(Some(self.space_root_key.to_vec()))
}
- pub async fn get_or_create_space_root_key(&self) -> Result<Vec<u8>> {
+ pub fn get_or_create_space_root_key(&self) -> Result<Vec<u8>> {
Ok(self.space_root_key.to_vec())
}
@@ -243,8 +243,7 @@ impl AccountSpaceCtx {
space_id: &str,
) -> Result<(SpaceKeyResponse, Vec<u8>)> {
let space_root_key = self
- .get_space_root_key()
- .await?
+ .get_space_root_key()?
.ok_or_else(|| Error::InvalidInput("space root key is missing".into()))?;
let space_id = space_id.trim();
if space_id.is_empty() {
@@ -315,7 +314,7 @@ impl AccountSpaceCtx {
profile: &[u8],
referred_by_space_id: Option<&str>,
) -> Result<CreatedSpace> {
- let space_root_key = self.get_or_create_space_root_key().await?;
+ let space_root_key = self.get_or_create_space_root_key()?;
let root_wrapped_space_key =
b64::encode(&encrypt_secretbox_payload(&space_root_key, space_key)?);
let (public_key, secret_key) = generate_keypair()?;
@@ -423,9 +422,8 @@ impl AccountSpaceCtx {
&self,
space_id: &str,
) -> Result<Option<ResolvedOwnedSpaceAccess>> {
- let space_root_key = match self.get_space_root_key().await? {
- Some(value) => value,
- None => return Ok(None),
+ let Some(space_root_key) = self.get_space_root_key()? else {
+ return Ok(None);
};
let spaces = self.list_owned_spaces_cached().await?;
let Some(record) = spaces.into_iter().find(|value| value.space_id == space_id) else {
@@ -497,9 +495,8 @@ impl AccountSpaceCtx {
space_id: &str,
version: Option<i32>,
) -> Result<Option<Vec<u8>>> {
- let mut access = match self.resolve_space_access(space_id).await? {
- Some(value) => value,
- None => return Ok(None),
+ let Some(mut access) = self.resolve_space_access(space_id).await? else {
+ return Ok(None);
};
let target_version = version.unwrap_or(access.key_version);
access = self
@@ -525,9 +522,8 @@ impl AccountSpaceCtx {
}
None => self.resolve_space_access(space_id).await?,
};
- let mut access = match access {
- Some(value) => value,
- None => return Ok(None),
+ let Some(mut access) = access else {
+ return Ok(None);
};
let target_version = version.unwrap_or(access.key_version);
access = self
diff --git a/rust/crates/space/src/client/posts.rs b/rust/crates/space/src/client/posts.rs
index 3f1c9ec323..fb49b500d7 100644
--- a/rust/crates/space/src/client/posts.rs
+++ b/rust/crates/space/src/client/posts.rs
@@ -234,7 +234,7 @@ impl AccountSpaceCtx {
}
pub async fn hydrate_space_keys(&self) -> Result<HydratedKeys> {
- let space_root_key = self.get_space_root_key().await?;
+ let space_root_key = self.get_space_root_key()?;
let owned_records = self.list_owned_spaces().await?;
let mut owned = Vec::with_capacity(owned_records.len());
if let Some(space_root_key) = space_root_key {
diff --git a/rust/crates/space/src/client/tests.rs b/rust/crates/space/src/client/tests.rs
index 0b548f155a..ebce393019 100644
--- a/rust/crates/space/src/client/tests.rs
+++ b/rust/crates/space/src/client/tests.rs
@@ -49,7 +49,6 @@ async fn get_space_root_key_returns_context_space_root_key() {
let space_root = ctx
.get_space_root_key()
- .await
.expect("space root key should load")
.expect("space root key should exist");
@@ -64,7 +63,6 @@ async fn get_or_create_space_root_key_returns_context_space_root_key() {
let space_root = ctx
.get_or_create_space_root_key()
- .await
.expect("space root key should load");
assert_eq!(space_root, expected_space_root);
@@ -647,12 +645,11 @@ async fn create_space_maps_owner_limit_error() {
.create_async()
.await;
- let error = match ctx
+ let Err(error) = ctx
.create_space_with_key("owner-main", &generate_key(), b"profile-json")
.await
- {
- Ok(_) => panic!("space creation should fail"),
- Err(error) => error,
+ else {
+ panic!("space creation should fail")
};
assert!(matches!(error, Error::SpaceLimitReached));
diff --git a/rust/crates/space/src/transport.rs b/rust/crates/space/src/transport.rs
index 5ea905cb23..61f4c8db7d 100644
--- a/rust/crates/space/src/transport.rs
+++ b/rust/crates/space/src/transport.rs
@@ -1,5 +1,9 @@
use serde::{Deserialize, Serialize};
+#[expect(
+ clippy::trivially_copy_pass_by_ref,
+ reason = "Serde skip_serializing_if predicates receive references"
+)]
fn is_false(value: &bool) -> bool {
!*value
}
diff --git a/rust/crates/test-support/src/server.rs b/rust/crates/test-support/src/server.rs
index bed3c537aa..adb130255f 100644
--- a/rust/crates/test-support/src/server.rs
+++ b/rust/crates/test-support/src/server.rs
@@ -104,9 +104,8 @@ fn wait_for_museum(process: &mut ChildProcess, port: u16) -> TestResult {
}
fn ping(port: u16) -> TestResult<bool> {
- let mut stream = match TcpStream::connect((LOCAL_HOST, port)) {
- Ok(stream) => stream,
- Err(_) => return Ok(false),
+ let Ok(mut stream) = TcpStream::connect((LOCAL_HOST, port)) else {
+ return Ok(false);
};
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
stream.write_all(b"GET /ping HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")?;