Skip to content

armgit / ente

Public Imported from GitHub
0

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

Require explicit exceptions for expect calls

Manav Rathiea7364cd2bd2
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 9b9f0b2769..ba25a0a787 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -122,6 +122,7 @@ dbg_macro = "deny"
debug_assert_with_mut_call = "deny"
derive_partial_eq_without_eq = "deny"
empty_drop = "deny"
+expect_used = "deny"
fallible_impl_from = "deny"
implicit_clone = "deny"
inefficient_to_string = "deny"
diff --git a/rust/apps/cli/src/sync/download.rs b/rust/apps/cli/src/sync/download.rs
index 2f1947daba..6c440c44d8 100644
--- a/rust/apps/cli/src/sync/download.rs
+++ b/rust/apps/cli/src/sync/download.rs
@@ -132,6 +132,10 @@ impl DownloadManager {
let (_multi_progress, progress_bar) = if self.show_progress && total > 0 {
let mp = MultiProgress::new();
let pb = mp.add(ProgressBar::new(total as u64));
+ #[expect(
+ clippy::expect_used,
+ reason = "The progress template is a fixed literal"
+ )]
pb.set_style(
ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({percent}%) {msg}")
diff --git a/rust/apps/cli/tests/paste.rs b/rust/apps/cli/tests/paste.rs
index bd7fe54b66..1594e25c9e 100644
--- a/rust/apps/cli/tests/paste.rs
+++ b/rust/apps/cli/tests/paste.rs
@@ -1,3 +1,4 @@
+#![cfg(test)]
#![cfg(feature = "museum")]
mod support;
diff --git a/rust/apps/cli/tests/support/mod.rs b/rust/apps/cli/tests/support/mod.rs
index b95f4e4f56..f7aa2b7998 100644
--- a/rust/apps/cli/tests/support/mod.rs
+++ b/rust/apps/cli/tests/support/mod.rs
@@ -1,3 +1,5 @@
+#![cfg(test)]
+
mod cli;
pub use cli::Cli;
diff --git a/rust/apps/ensu/src-tauri/src/logging.rs b/rust/apps/ensu/src-tauri/src/logging.rs
index 9e9abbc971..bb267d8799 100644
--- a/rust/apps/ensu/src-tauri/src/logging.rs
+++ b/rust/apps/ensu/src-tauri/src/logging.rs
@@ -49,6 +49,10 @@ pub fn init_logging(app: &AppHandle) {
}
let _ = LOG_PATH.set(path.clone());
+ #[expect(
+ clippy::expect_used,
+ reason = "Initialization requires exclusive ownership of the process logger"
+ )]
log::set_logger(&LOGGER).expect("Rust logger already initialized");
log::set_max_level(log::LevelFilter::Info);
log(
diff --git a/rust/bindings/uniffi/ensu/src/assets.rs b/rust/bindings/uniffi/ensu/src/assets.rs
index a1cc61ae36..0f97a54c65 100644
--- a/rust/bindings/uniffi/ensu/src/assets.rs
+++ b/rust/bindings/uniffi/ensu/src/assets.rs
@@ -64,6 +64,10 @@ impl From<download::Error> for AssetDownloadError {
}
#[uniffi::export]
+#[expect(
+ clippy::expect_used,
+ reason = "Unknown model IDs fall back to the built-in catalog"
+)]
pub fn llm_asset(model_id: String) -> Arc<Asset> {
Asset::new(ente_ensu::model::mobile_llm_asset(&model_id).expect("valid mobile model catalog"))
}
diff --git a/rust/bindings/wasm/lib/src/logging.rs b/rust/bindings/wasm/lib/src/logging.rs
index 37b32530e9..92605fc40d 100644
--- a/rust/bindings/wasm/lib/src/logging.rs
+++ b/rust/bindings/wasm/lib/src/logging.rs
@@ -49,6 +49,10 @@ impl log::Log for WasmLogger {
#[wasm_bindgen(start)]
fn start() {
+ #[expect(
+ clippy::expect_used,
+ reason = "Initialization requires exclusive ownership of the process logger"
+ )]
log::set_logger(&LOGGER).expect("Rust logger already initialized");
log::set_max_level(log::LevelFilter::Info);
}
diff --git a/rust/clippy.toml b/rust/clippy.toml
index 154626ef4e..59cb72d114 100644
--- a/rust/clippy.toml
+++ b/rust/clippy.toml
@@ -1 +1,2 @@
+allow-expect-in-tests = true
allow-unwrap-in-tests = true
diff --git a/rust/crates/accounts/src/flow.rs b/rust/crates/accounts/src/flow.rs
index 7b8a707ec7..ce38d02cc4 100644
--- a/rust/crates/accounts/src/flow.rs
+++ b/rust/crates/accounts/src/flow.rs
@@ -717,6 +717,10 @@ where
.filter(|session_id| !session_id.is_empty())
.ok_or_else(|| Error::Protocol("No passkey session ID".into()))?;
+ #[expect(
+ clippy::expect_used,
+ reason = "AuthResponse validation requires accountsUrl for passkey sessions"
+ )]
let accounts_url = auth_response
.accounts_url
.as_deref()
diff --git a/rust/crates/assets/src/download.rs b/rust/crates/assets/src/download.rs
index 301ee2f3a5..24ed7606c0 100644
--- a/rust/crates/assets/src/download.rs
+++ b/rust/crates/assets/src/download.rs
@@ -755,6 +755,10 @@ async fn download_file_ranged(
let mut downloads = Vec::new();
{
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let metadata = range_metadata.lock().expect("range metadata lock");
for (part_index, range) in metadata.ranges.iter().copied().enumerate() {
if range.complete {
@@ -791,6 +795,10 @@ async fn download_file_ranged(
});
}
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let states = range_states.lock().expect("range state lock");
let network_downloaded_bytes = states
.iter()
@@ -824,6 +832,10 @@ impl RangeDownloadContext<'_, '_> {
}
{
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let mut states = self.range_states.lock().expect("range state lock");
if let Some(state) = states.get_mut(part_index) {
state.downloaded_bytes = 0;
@@ -901,6 +913,10 @@ impl RangeDownloadContext<'_, '_> {
downloaded_in_range += chunk_len;
{
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let mut states = self.range_states.lock().expect("range state lock");
if let Some(state) = states.get_mut(part_index) {
state.downloaded_bytes = downloaded_in_range;
@@ -933,6 +949,10 @@ impl RangeDownloadContext<'_, '_> {
}
{
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let mut states = self.range_states.lock().expect("range state lock");
if let Some(state) = states.get_mut(part_index) {
state.downloaded_bytes = range_len;
@@ -947,6 +967,10 @@ impl RangeDownloadContext<'_, '_> {
}
fn emit_progress(&self) {
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let states = self.range_states.lock().expect("range state lock");
let downloaded_bytes = states
.iter()
@@ -963,6 +987,10 @@ impl RangeDownloadContext<'_, '_> {
.fold(0u32, u32::saturating_add);
drop(states);
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let mut callback = self.on_progress.lock().expect("progress lock");
(**callback)(FileProgress {
downloaded_bytes,
@@ -974,6 +1002,10 @@ impl RangeDownloadContext<'_, '_> {
}
fn increment_retry(&self, part_index: usize) {
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let mut states = self.range_states.lock().expect("range state lock");
if let Some(state) = states.get_mut(part_index) {
state.retry_count = state.retry_count.saturating_add(1);
@@ -981,6 +1013,10 @@ impl RangeDownloadContext<'_, '_> {
}
fn mark_complete(&self, part_index: usize) -> Result<(), Error> {
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
let mut metadata = self.range_metadata.lock().expect("range metadata lock");
if let Some(range) = metadata.ranges.get_mut(part_index) {
range.complete = true;
diff --git a/rust/crates/assets/src/store.rs b/rust/crates/assets/src/store.rs
index 95fa5d1656..274bbaa01f 100644
--- a/rust/crates/assets/src/store.rs
+++ b/rust/crates/assets/src/store.rs
@@ -223,9 +223,17 @@ impl AssetStore {
_ = cancellation.cancelled() => return Err(Error::Cancelled),
};
if self.is_downloaded(asset) {
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
progress.lock().expect("progress lock").skip(asset_index);
return Ok(());
}
+ #[expect(
+ clippy::expect_used,
+ reason = "The private asset semaphore is never closed"
+ )]
let _slot = tokio::select! {
slot = self.asset_slots.acquire() => slot.expect("asset semaphore closed"),
_ = cancellation.cancelled() => return Err(Error::Cancelled),
@@ -235,6 +243,10 @@ impl AssetStore {
.download(
self.download_targets(asset),
|update| {
+ #[expect(
+ clippy::expect_used,
+ reason = "A panic unwinds the download; its local state is not reused"
+ )]
progress
.lock()
.expect("progress lock")
@@ -255,6 +267,10 @@ impl AssetStore {
}
fn key_lock(&self, components: &[String]) -> Result<Arc<Mutex<()>>, Error> {
+ #[expect(
+ clippy::expect_used,
+ reason = "The registry critical section invokes no caller code"
+ )]
let mut locks = self.asset_locks.lock().expect("asset lock registry");
if let Some((key, lock)) = locks.iter().find(|(key, _)| keys_overlap(key, components)) {
if key == components {
diff --git a/rust/crates/core/examples/ping.rs b/rust/crates/core/examples/ping.rs
index d9635a4c7f..57673fc393 100644
--- a/rust/crates/core/examples/ping.rs
+++ b/rust/crates/core/examples/ping.rs
@@ -1,5 +1,9 @@
use ente_core::http::{Api, ApiConfig, Http};
+#[expect(
+ clippy::expect_used,
+ reason = "The example requires a URL argument and an initialized HTTP client"
+)]
#[tokio::main]
async fn main() {
let origin = std::env::args().nth(1).expect("Usage: ping <origin>");
diff --git a/rust/crates/core/src/crypto/hpke.rs b/rust/crates/core/src/crypto/hpke.rs
index dc85d195a1..d86e8cf04a 100644
--- a/rust/crates/core/src/crypto/hpke.rs
+++ b/rust/crates/core/src/crypto/hpke.rs
@@ -29,6 +29,10 @@ impl PublicKey {
&self.0
}
+ #[expect(
+ clippy::expect_used,
+ reason = "PublicKey construction validates these bytes"
+ )]
fn hpke_key(&self) -> <Kem as HpkeKem>::PublicKey {
<Kem as HpkeKem>::PublicKey::from_bytes(&self.0)
.expect("PublicKey is validated when constructed")
@@ -62,13 +66,17 @@ impl SecretKey {
pub fn public_key(&self) -> PublicKey {
let bytes = Kem::sk_to_pk(&self.hpke_key()).to_bytes();
- PublicKey(bytes.as_slice().try_into().expect("X-Wing public key size"))
+ PublicKey(bytes.into())
}
pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
&self.0
}
+ #[expect(
+ clippy::expect_used,
+ reason = "X-Wing accepts every 32-byte private key"
+ )]
fn hpke_key(&self) -> <Kem as HpkeKem>::PrivateKey {
<Kem as HpkeKem>::PrivateKey::from_bytes(&self.0)
.expect("X-Wing accepts every 32-byte private key")
diff --git a/rust/crates/core/src/crypto/kdf.rs b/rust/crates/core/src/crypto/kdf.rs
index dee676acf3..06b00632de 100644
--- a/rust/crates/core/src/crypto/kdf.rs
+++ b/rust/crates/core/src/crypto/kdf.rs
@@ -49,6 +49,10 @@ pub fn derive_subkey(
}
pub fn derive_login_key(kek: &Key) -> SecretVec {
+ #[expect(
+ clippy::expect_used,
+ reason = "The login subkey length, ID and context are fixed valid constants"
+ )]
let subkey = derive_subkey(kek, LOGIN_SUBKEY_LEN, LOGIN_SUBKEY_ID, LOGIN_SUBKEY_CONTEXT)
.expect("login subkey parameters are statically valid");
SecretVec::new(subkey[..16].to_vec())
diff --git a/rust/crates/core/src/crypto/secretbox.rs b/rust/crates/core/src/crypto/secretbox.rs
index def7cb07e9..49d4ef146c 100644
--- a/rust/crates/core/src/crypto/secretbox.rs
+++ b/rust/crates/core/src/crypto/secretbox.rs
@@ -33,8 +33,10 @@ fn encrypt_with_nonce(data: &[u8], nonce: &Nonce, key: &Key) -> Vec<u8> {
let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(key.as_bytes()));
let nonce_ga = GenericArray::from_slice(nonce.as_bytes());
- // The underlying AEAD encrypt only fails on plaintexts exceeding the
- // cipher's size bounds, which cannot be reached with in-memory slices.
+ #[expect(
+ clippy::expect_used,
+ reason = "The cipher size limit cannot be reached by an in-memory slice"
+ )]
cipher
.encrypt(nonce_ga, data)
.expect("XSalsa20-Poly1305 encryption cannot fail for in-memory plaintexts")
diff --git a/rust/crates/core/src/crypto/types.rs b/rust/crates/core/src/crypto/types.rs
index ab7398e1d8..f81db62ef1 100644
--- a/rust/crates/core/src/crypto/types.rs
+++ b/rust/crates/core/src/crypto/types.rs
@@ -220,6 +220,10 @@ pub fn random_bytes(len: usize) -> Vec<u8> {
}
pub(crate) fn fill_random(buf: &mut [u8]) {
+ #[expect(
+ clippy::expect_used,
+ reason = "Stop if the OS cannot supply cryptographic randomness"
+ )]
getrandom::fill(buf).expect("failed to generate random bytes");
}
diff --git a/rust/crates/ensu/src/config.rs b/rust/crates/ensu/src/config.rs
index ff9f0eafb0..e1928bf157 100644
--- a/rust/crates/ensu/src/config.rs
+++ b/rust/crates/ensu/src/config.rs
@@ -255,6 +255,10 @@ pub fn resolve_effective_model(
.unwrap_or(policy.default_model)
}
+#[expect(
+ clippy::expect_used,
+ reason = "Built-in defaults refer to IDs defined in the same catalog"
+)]
fn catalog_preset(catalog: &[ModelPreset], id: &str) -> ModelPreset {
catalog
.iter()
diff --git a/rust/crates/ensu/src/config/knowledge.rs b/rust/crates/ensu/src/config/knowledge.rs
index 960e06bbaa..d4956cba95 100644
--- a/rust/crates/ensu/src/config/knowledge.rs
+++ b/rust/crates/ensu/src/config/knowledge.rs
@@ -96,6 +96,10 @@ pub(crate) fn knowledge_index_contract() -> KnowledgeIndexContract {
}
}
+#[expect(
+ clippy::expect_used,
+ reason = "The fixed prompt contains both placeholders"
+)]
pub(crate) fn format_knowledge_document_prompt(title: &str, text: &str) -> String {
let (prefix, remainder) = DOCUMENT_PROMPT
.split_once("{title}")
diff --git a/rust/crates/ensu/src/llm/generate.rs b/rust/crates/ensu/src/llm/generate.rs
index d1f80f2057..a9d330e2fa 100644
--- a/rust/crates/ensu/src/llm/generate.rs
+++ b/rust/crates/ensu/src/llm/generate.rs
@@ -93,6 +93,10 @@ pub struct ChatRequest {
pub grammar: Option<String>,
}
+#[expect(
+ clippy::expect_used,
+ reason = "llama.cpp reports insufficient buffer capacity as a negative byte count"
+)]
fn token_piece_bytes(model: &LlamaModel, token: LlamaToken) -> Result<Vec<u8>, TokenToStringError> {
match model.token_to_piece_bytes(token, 8, true, None) {
Err(TokenToStringError::InsufficientBufferSpace(required)) => model.token_to_piece_bytes(
@@ -214,6 +218,7 @@ fn drain_utf8(pending: &mut Vec<u8>) -> String {
Err(err) => {
let valid_up_to = err.valid_up_to();
if valid_up_to > 0 {
+ #[expect(clippy::expect_used, reason = "Utf8Error identifies a valid prefix")]
let valid =
std::str::from_utf8(&pending[..valid_up_to]).expect("valid UTF-8 prefix");
output.push_str(valid);
diff --git a/rust/crates/ensu/src/model/mod.rs b/rust/crates/ensu/src/model/mod.rs
index e2ae165755..4a82db3332 100644
--- a/rust/crates/ensu/src/model/mod.rs
+++ b/rust/crates/ensu/src/model/mod.rs
@@ -69,6 +69,10 @@ pub fn desktop_llm_asset(model_id: &str) -> Result<Asset, InvalidPreset> {
llm_asset(&preset)
}
+#[expect(
+ clippy::expect_used,
+ reason = "The built-in model preset has a valid asset key and checksum"
+)]
pub fn transcription_model_asset() -> Asset {
let preset = config::defaults().transcription_model;
Asset::tar_gz(
@@ -80,6 +84,10 @@ pub fn transcription_model_asset() -> Asset {
.expect("transcription asset config")
}
+#[expect(
+ clippy::expect_used,
+ reason = "The built-in model preset has a valid asset key and checksum"
+)]
pub fn voice_activity_model_asset() -> Asset {
let preset = config::defaults().voice_activity_model;
Asset::files(
@@ -94,6 +102,10 @@ pub fn voice_activity_model_asset() -> Asset {
.expect("voice activity asset config")
}
+#[expect(
+ clippy::expect_used,
+ reason = "The built-in model preset has a valid asset key and checksum"
+)]
pub fn knowledge_embedding_model_asset() -> Asset {
let embedding = config::knowledge_embedding_config();
Asset::files(
diff --git a/rust/crates/ensu/src/transcription/text.rs b/rust/crates/ensu/src/transcription/text.rs
index 7e15baf3ed..40596026a4 100644
--- a/rust/crates/ensu/src/transcription/text.rs
+++ b/rust/crates/ensu/src/transcription/text.rs
@@ -6,8 +6,16 @@ const FILLER_WORDS: &[&str] = &[
"ehh",
];
+#[expect(
+ clippy::expect_used,
+ reason = "The whitespace regex is a fixed valid literal"
+)]
static MULTI_SPACE_PATTERN: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\s{2,}").expect("valid whitespace regex"));
+#[expect(
+ clippy::expect_used,
+ reason = "Filler words are escaped before insertion into the fixed regex"
+)]
static FILLER_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
FILLER_WORDS
.iter()
diff --git a/rust/crates/exif/src/boxes.rs b/rust/crates/exif/src/boxes.rs
index db35696fdd..98cc1859b3 100644
--- a/rust/crates/exif/src/boxes.rs
+++ b/rust/crates/exif/src/boxes.rs
@@ -19,6 +19,7 @@ pub(crate) fn box_at<R: Read + Seek>(
) -> Result<BoxRange, Error> {
range(0, end, offset, 8)?;
let header = reader.array::<8>(offset)?;
+ let [_, _, _, _, kind @ ..] = header;
let mut size = u64::from(be32(&header));
let mut header_size = 8;
if size == 1 {
@@ -33,7 +34,7 @@ pub(crate) fn box_at<R: Read + Seek>(
}
range(0, end, offset, size)?;
Ok(BoxRange {
- kind: header[4..8].try_into().expect("box type is four bytes"),
+ kind,
start: offset + header_size,
len: size - header_size,
})
diff --git a/rust/crates/exif/src/isobmff.rs b/rust/crates/exif/src/isobmff.rs
index 0f6e3d1930..4fb4e93610 100644
--- a/rust/crates/exif/src/isobmff.rs
+++ b/rust/crates/exif/src/isobmff.rs
@@ -289,6 +289,10 @@ fn item_info<R: Read + Seek>(
}
let id = c.number(if version == 2 { 2 } else { 4 })? as u32;
let protection = c.number(2)?;
+ #[expect(
+ clippy::expect_used,
+ reason = "take returns exactly the requested four bytes"
+ )]
let kind: [u8; 4] = c.take(4)?.try_into().expect("item type is four bytes");
c.string()?;
let mime = if &kind == b"mime" {
diff --git a/rust/crates/image/src/color_management.rs b/rust/crates/image/src/color_management.rs
index 2634978a2b..7c07870db4 100644
--- a/rust/crates/image/src/color_management.rs
+++ b/rust/crates/image/src/color_management.rs
@@ -110,6 +110,10 @@ fn apply_profile_to_image(
}
}
+#[expect(
+ clippy::expect_used,
+ reason = "Color transforms preserve the source buffer length and dimensions"
+)]
fn transform_buffer<P>(
mut buffer: ImageBuffer<P, Vec<P::Subpixel>>,
source_profile: &ColorProfile,
@@ -216,6 +220,10 @@ fn cached_color_profile(encoded: &[u8]) -> Result<Arc<ColorProfile>, String> {
.iter()
.position(|entry| entry.encoded.as_ref() == encoded)
{
+ #[expect(
+ clippy::expect_used,
+ reason = "The index comes from this cache while its lock is held"
+ )]
let entry = cache
.remove(index)
.expect("cache index came from iteration");
diff --git a/rust/crates/legacy/tests/sheet_format.rs b/rust/crates/legacy/tests/sheet_format.rs
index 8e199491e7..19d72643e4 100644
--- a/rust/crates/legacy/tests/sheet_format.rs
+++ b/rust/crates/legacy/tests/sheet_format.rs
@@ -1,3 +1,5 @@
+#![cfg(test)]
+
use ente_core::b64;
use ente_legacy::{Error, LegacyKitRecoveryClient, LegacyKitShare, validate_share_pair};
use serde::Deserialize;
diff --git a/rust/crates/location/src/binary.rs b/rust/crates/location/src/binary.rs
index 090eb6bb61..da0b28ffe6 100644
--- a/rust/crates/location/src/binary.rs
+++ b/rust/crates/location/src/binary.rs
@@ -13,6 +13,10 @@ impl<'a> ByteReader<'a> {
}
fn array<const N: usize>(&mut self) -> [u8; N] {
+ #[expect(
+ clippy::expect_used,
+ reason = "Index validators check field ranges before ByteReader is used"
+ )]
let (value, rest) = self
.bytes
.split_first_chunk::<N>()
diff --git a/rust/crates/location/src/city.rs b/rust/crates/location/src/city.rs
index a3add7a541..acfd4f6d3f 100644
--- a/rust/crates/location/src/city.rs
+++ b/rust/crates/location/src/city.rs
@@ -278,6 +278,10 @@ impl CityIndex {
continue;
};
let prominence_window = (0.5 + nearest * 0.25).min(2.0);
+ #[expect(
+ clippy::expect_used,
+ reason = "The nearest candidate is included in the prominence window"
+ )]
let best = eligible
.iter()
.filter(|candidate| candidate.distance_km <= nearest + prominence_window)
@@ -857,6 +861,10 @@ fn string_offset(bytes: &[u8], offset: usize, length: usize) -> crate::Result<us
}
}
+#[expect(
+ clippy::expect_used,
+ reason = "Index construction validates the string table as UTF-8"
+)]
fn table_entry_u24(bytes: &[u8], offsets: usize, blob: usize, index: usize) -> &str {
let mut reader = ByteReader::at(bytes, offsets + index * NAME_OFFSET_LEN);
let start = reader.u24() as usize;
@@ -864,6 +872,10 @@ fn table_entry_u24(bytes: &[u8], offsets: usize, blob: usize, index: usize) -> &
std::str::from_utf8(&bytes[blob + start..blob + end]).expect("validated UTF-8")
}
+#[expect(
+ clippy::expect_used,
+ reason = "Index construction validates the string table as UTF-8"
+)]
fn table_entry_u32(bytes: &[u8], offsets: usize, blob: usize, index: usize) -> &str {
let mut reader = ByteReader::at(bytes, offsets + index * 4);
let start = reader.u32() as usize;
diff --git a/rust/crates/location/src/dispute.rs b/rust/crates/location/src/dispute.rs
index 54d19d78a3..e41941e055 100644
--- a/rust/crates/location/src/dispute.rs
+++ b/rust/crates/location/src/dispute.rs
@@ -93,6 +93,10 @@ impl DisputeIndex {
})
}
+ #[expect(
+ clippy::expect_used,
+ reason = "Index construction checks every geometry code against the territory catalog"
+ )]
pub(crate) fn lookup_prepared(
&self,
location: PreparedCell,
@@ -189,6 +193,10 @@ impl<'a> DisputeMatch<'a> {
self.index.layout.territories + self.territory * TERRITORY_LEN
}
+ #[expect(
+ clippy::expect_used,
+ reason = "Index construction validates the string table as UTF-8"
+ )]
fn string(self, start: u16, length: usize) -> &'a str {
let start = self.index.layout.strings + usize::from(start);
str::from_utf8(&self.index.bytes[start..start + length]).expect("validated UTF-8")
diff --git a/rust/crates/location/src/lib.rs b/rust/crates/location/src/lib.rs
index 3451bbb5eb..eda22c90ba 100644
--- a/rust/crates/location/src/lib.rs
+++ b/rust/crates/location/src/lib.rs
@@ -60,6 +60,10 @@ impl CountryCode {
self.0
}
+ #[expect(
+ clippy::expect_used,
+ reason = "CountryCode construction restricts bytes to ASCII"
+ )]
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0).expect("country code is ASCII")
}
diff --git a/rust/crates/location/src/urban.rs b/rust/crates/location/src/urban.rs
index 9c2025e1a2..b22ad30eb0 100644
--- a/rust/crates/location/src/urban.rs
+++ b/rust/crates/location/src/urban.rs
@@ -168,6 +168,10 @@ impl UrbanCenterIndex {
&self.bytes[feature.geometry_start..feature.geometry_end],
SECTION,
);
+ #[expect(
+ clippy::expect_used,
+ reason = "Index construction validates all polygon and ring records"
+ )]
for _ in 0..reader.u16().expect("validated polygon count") {
let ring_count = reader.u16().expect("validated ring count");
let mut inside = reader.ring_contains(point).expect("validated ring");
@@ -214,6 +218,10 @@ impl UrbanCenterIndex {
}
}
+ #[expect(
+ clippy::expect_used,
+ reason = "Index construction validates terminated UTF-8 names"
+ )]
fn name(&self, offset: usize) -> &str {
let end = self.bytes[offset..self.layout.geometry]
.iter()
@@ -223,6 +231,10 @@ impl UrbanCenterIndex {
std::str::from_utf8(&self.bytes[offset..end]).expect("validated name")
}
+ #[expect(
+ clippy::expect_used,
+ reason = "Index construction validates the country string table as UTF-8"
+ )]
fn country(&self, index: usize) -> &str {
let mut reader = ByteReader::at(&self.bytes, self.layout.country_offsets + index * 4);
let start = reader.u32() as usize;
diff --git a/rust/crates/ml/examples/vecdb_bench.rs b/rust/crates/ml/examples/vecdb_bench.rs
index 77340364bf..e5834058a2 100644
--- a/rust/crates/ml/examples/vecdb_bench.rs
+++ b/rust/crates/ml/examples/vecdb_bench.rs
@@ -1,3 +1,8 @@
+#![expect(
+ clippy::expect_used,
+ reason = "Benchmark failures should abort the run"
+)]
+
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
diff --git a/rust/crates/ml/src/assets.rs b/rust/crates/ml/src/assets.rs
index faf35f4c7d..41fecc49e7 100644
--- a/rust/crates/ml/src/assets.rs
+++ b/rust/crates/ml/src/assets.rs
@@ -27,6 +27,10 @@ pub struct ClipTextPaths {
pub vocab: PathBuf,
}
+#[expect(
+ clippy::expect_used,
+ reason = "The built-in model catalog has valid asset keys and checksums"
+)]
fn model_asset(model: Model) -> Asset {
let spec = model_asset_spec(model);
Asset::files(
@@ -63,6 +67,10 @@ pub fn indexing_model_paths(
model_paths
}
+#[expect(
+ clippy::expect_used,
+ reason = "The filenames and asset come from the same CLIP catalog entry"
+)]
pub fn clip_text_paths(store: &AssetStore) -> ClipTextPaths {
let asset = clip_text_asset();
let files = model_asset_spec(Model::ClipText).files;
@@ -212,6 +220,10 @@ struct ModelAssetFile {
sha256: &'static str,
}
+#[expect(
+ clippy::expect_used,
+ reason = "The filename and asset come from the same model catalog entry"
+)]
fn model_path(store: &AssetStore, model: Model) -> String {
let asset = model_asset(model);
store
diff --git a/rust/crates/ml/src/clip/tokenizer.rs b/rust/crates/ml/src/clip/tokenizer.rs
index c80db25959..ab340d2bcb 100644
--- a/rust/crates/ml/src/clip/tokenizer.rs
+++ b/rust/crates/ml/src/clip/tokenizer.rs
@@ -15,6 +15,10 @@ use super::CLIP_TEXT_TOKEN_COUNT;
const BPE_MERGES_END_EXCLUSIVE: usize = 49152 - 256 - 2 + 1;
+#[expect(
+ clippy::expect_used,
+ reason = "The tokenizer regex is a fixed valid literal"
+)]
static TOKEN_PATTERN: Lazy<Regex> = Lazy::new(|| {
Regex::new(
// Keep this aligned with MobileCLIP's Python tokenizer path
@@ -24,6 +28,10 @@ static TOKEN_PATTERN: Lazy<Regex> = Lazy::new(|| {
.expect("valid clip tokenizer regex")
});
+#[expect(
+ clippy::expect_used,
+ reason = "The whitespace regex is a fixed valid literal"
+)]
static WHITESPACE_PATTERN: Lazy<Regex> =
Lazy::new(|| Regex::new(r"\s+").expect("valid whitespace regex"));
diff --git a/rust/crates/ml/src/face/align.rs b/rust/crates/ml/src/face/align.rs
index 8e002ced64..05f91ef331 100644
--- a/rust/crates/ml/src/face/align.rs
+++ b/rust/crates/ml/src/face/align.rs
@@ -72,6 +72,10 @@ pub(crate) fn run_face_alignment(
result
}
+#[expect(
+ clippy::expect_used,
+ reason = "RGB dimensions and exact buffer length are checked before conversion"
+)]
fn take_rgb_image(decoded: &mut DecodedImage) -> MlResult<RgbImage> {
let expected_len = (decoded.dimensions.width as usize)
.checked_mul(decoded.dimensions.height as usize)
diff --git a/rust/crates/ml/src/ocr/assets.rs b/rust/crates/ml/src/ocr/assets.rs
index dd065a46be..e8f86be5d1 100644
--- a/rust/crates/ml/src/ocr/assets.rs
+++ b/rust/crates/ml/src/ocr/assets.rs
@@ -51,6 +51,10 @@ impl OcrModelFile {
format!("{MODEL_BASE_URL}/{}", self.name)
}
+ #[expect(
+ clippy::expect_used,
+ reason = "The built-in OCR catalog has valid asset keys and checksums"
+ )]
fn asset(&self) -> Asset {
Asset::file(
vec![MODELS.to_string(), self.key.to_string()],
@@ -64,6 +68,10 @@ impl OcrModelFile {
.expect("valid OCR model catalog")
}
+ #[expect(
+ clippy::expect_used,
+ reason = "The filename and asset come from the same OCR catalog entry"
+ )]
fn path(&self, store: &AssetStore) -> String {
store
.file_path(&self.asset(), self.name)
diff --git a/rust/crates/ml/src/ocr/mod.rs b/rust/crates/ml/src/ocr/mod.rs
index 04e7534416..4021d58980 100644
--- a/rust/crates/ml/src/ocr/mod.rs
+++ b/rust/crates/ml/src/ocr/mod.rs
@@ -397,6 +397,10 @@ fn crop_candidates(
"OCR crop source buffer mismatch".to_string(),
));
}
+ #[expect(
+ clippy::expect_used,
+ reason = "RGB dimensions and exact buffer length are checked before conversion"
+ )]
let source = image::RgbImage::from_raw(
working.width as u32,
working.height as u32,
diff --git a/rust/crates/ml/src/onnx/providers.rs b/rust/crates/ml/src/onnx/providers.rs
index 2e5a6cdd8e..86b4559c7e 100644
--- a/rust/crates/ml/src/onnx/providers.rs
+++ b/rust/crates/ml/src/onnx/providers.rs
@@ -339,6 +339,7 @@ fn webgpu_attempt_providers() -> Vec<ExecutionProviderDispatch> {
}
#[cfg(target_os = "android")]
+#[expect(clippy::expect_used, reason = "The fixed thread count is nonzero")]
fn xnnpack_provider() -> ExecutionProviderDispatch {
XNNPACK::default()
.with_intra_op_num_threads(NonZeroUsize::new(4).expect("four is non-zero"))
diff --git a/rust/crates/ml/src/pet/preprocess.rs b/rust/crates/ml/src/pet/preprocess.rs
index 4bfde7ee54..bc0aa70148 100644
--- a/rust/crates/ml/src/pet/preprocess.rs
+++ b/rust/crates/ml/src/pet/preprocess.rs
@@ -125,6 +125,10 @@ pub(super) struct RgbCropResizer {
impl RgbCropResizer {
pub(super) fn new(output_size: u32) -> Self {
assert!(output_size > 0);
+ #[expect(
+ clippy::expect_used,
+ reason = "An unrepresentable crop buffer size is a programming error"
+ )]
let output_len = (output_size as usize)
.checked_mul(output_size as usize)
.and_then(|pixels| pixels.checked_mul(3))
diff --git a/rust/crates/ml/src/vecdb/log.rs b/rust/crates/ml/src/vecdb/log.rs
index 8a42ee38e8..92fa55ab7e 100644
--- a/rust/crates/ml/src/vecdb/log.rs
+++ b/rust/crates/ml/src/vecdb/log.rs
@@ -425,6 +425,10 @@ impl LogScanner<'_> {
}
fn read_attr_bytes(&mut self, body_budget: u64) -> Result<bool, VecDbError> {
+ #[expect(
+ clippy::expect_used,
+ reason = "The add-record header includes an attribute count byte"
+ )]
let attr_count = *self
.scratch
.last()
@@ -437,6 +441,10 @@ impl LogScanner<'_> {
if !self.extend_within(body_budget, 1)? {
return Ok(false);
}
+ #[expect(
+ clippy::expect_used,
+ reason = "extend_within just appended the name length byte"
+ )]
let name_len = *self.scratch.last().expect("attribute name length was read") as usize;
if name_len == 0 || name_len > MAX_ATTR_NAME_BYTES {
return Ok(false);
@@ -444,6 +452,10 @@ impl LogScanner<'_> {
if !self.extend_within(body_budget, name_len + 1)? {
return Ok(false);
}
+ #[expect(
+ clippy::expect_used,
+ reason = "extend_within just appended the value tag byte"
+ )]
let value_len = match *self.scratch.last().expect("attribute value tag was read") {
ATTR_TAG_STR => {
if !self.extend_within(body_budget, 2)? {
diff --git a/rust/crates/ml/tests/support/ml_indexing.rs b/rust/crates/ml/tests/support/ml_indexing.rs
index 4aef96cb7f..8beed80870 100644
--- a/rust/crates/ml/tests/support/ml_indexing.rs
+++ b/rust/crates/ml/tests/support/ml_indexing.rs
@@ -351,6 +351,10 @@ impl MlIndexingTestContext {
let mut model_paths = self.model_paths.clone();
model_paths.face_detection = model_path.clone();
+ #[expect(
+ clippy::expect_used,
+ reason = "The invalid-model fixture must fail analysis"
+ )]
let error = analyze_image(AnalyzeImageRequest {
file_id: -1,
source: ImageSource::Path(image_path.to_string_lossy().into_owned()),
diff --git a/rust/crates/photos/src/db.rs b/rust/crates/photos/src/db.rs
index a39d6fcd04..f3e26d6e8d 100644
--- a/rust/crates/photos/src/db.rs
+++ b/rust/crates/photos/src/db.rs
@@ -301,6 +301,10 @@ impl Pool {
}
}
+ #[expect(
+ clippy::expect_used,
+ reason = "acquire_reader returns a guard owning a connection"
+ )]
fn read<T>(&self, query: impl FnOnce(&mut Connection) -> Result<T>) -> Result<T> {
let mut reader = self.acquire_reader();
query(
diff --git a/rust/tools/location-dataset/src/city.rs b/rust/tools/location-dataset/src/city.rs
index 1229695cd2..fe5e093f8e 100644
--- a/rust/tools/location-dataset/src/city.rs
+++ b/rust/tools/location-dataset/src/city.rs
@@ -464,6 +464,10 @@ fn build_tree(cities: &[SourceCity], mut points: Vec<usize>) -> Vec<usize> {
let point = points[median];
nodes.push(point);
let (left, right_with_median) = points.split_at_mut(median);
+ #[expect(
+ clippy::expect_used,
+ reason = "The nonempty input slice contains its median element"
+ )]
let (_, right) = right_with_median
.split_first_mut()
.expect("nonempty median slice");
diff --git a/rust/tools/location-dataset/src/lib.rs b/rust/tools/location-dataset/src/lib.rs
index c3b6f3cf97..d3e29593f7 100644
--- a/rust/tools/location-dataset/src/lib.rs
+++ b/rust/tools/location-dataset/src/lib.rs
@@ -121,6 +121,7 @@ fn invalid(message: impl Into<String>) -> Error {
fn hex(bytes: impl AsRef<[u8]>) -> String {
let mut output = String::with_capacity(bytes.as_ref().len() * 2);
for byte in bytes.as_ref() {
+ #[expect(clippy::expect_used, reason = "Formatting into a String cannot fail")]
write!(output, "{byte:02x}").expect("writing to a string is infallible");
}
output
diff --git a/rust/tools/location-dataset/src/urban.rs b/rust/tools/location-dataset/src/urban.rs
index 1d0922bd43..7304a28fa5 100644
--- a/rust/tools/location-dataset/src/urban.rs
+++ b/rust/tools/location-dataset/src/urban.rs
@@ -392,6 +392,10 @@ fn decode_geopackage_geometry(bytes: &[u8]) -> Result<MultiPolygon<f64>> {
if flags & 1 == 0 || flags & 0x10 != 0 {
return Err(invalid("unsupported GHSL GeoPackage geometry flags"));
}
+ #[expect(
+ clippy::expect_used,
+ reason = "The header length is checked before taking its four-byte SRS field"
+ )]
let srs = i32::from_le_bytes(bytes[4..8].try_into().expect("eight-byte header"));
if srs != 54_009 {
return Err(invalid(format!("unexpected GHSL spatial reference {srs}")));
@@ -510,6 +514,7 @@ impl<'a> WkbReader<'a> {
.position
.checked_add(N)
.ok_or_else(|| invalid("truncated GHSL WKB geometry"))?;
+ #[expect(clippy::expect_used, reason = "The checked slice has exactly N bytes")]
let bytes = self
.bytes
.get(self.position..end)