contains_key guarding an insert instead of the entry API
ID |
rust.maintainability.map_entry |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Inefficient Api Usage |
Language |
Rust |
Description
Reports a map lookup with contains_key that only decides whether to insert the same key, which is what the entry API expresses in a single call.
Rationale
The pair hashes and probes the map twice for one logical operation. It also splits the invariant across two statements, so the key used to test and the key used to insert can drift apart in a later edit without the compiler noticing. entry binds the two together and hands back the slot it has already found.
The following code illustrates the pattern detected by this rule:
use std::collections::HashMap;
pub fn register(sessions: &mut HashMap<String, u32>, key: String, ttl: u32) {
// FLAGGED: contains_key guarding an insert instead of the entry API
if !sessions.contains_key(&key) {
sessions.insert(key, ttl);
}
}