Skip to content

Commit

Permalink
clippy: Deny str::len
Browse files Browse the repository at this point in the history
When I was working on some column printing code
with Unicode I got bit by using `str::len`...and
digging in I found that clippy actually just
merged a lint to go the *other* way; more in
the link in the code.

Turning on a lint showed one place that should
have been using `chars().count()` and one that
should have been validating ASCII. Fix those.

Signed-off-by: Colin Walters <[email protected]>
  • Loading branch information
cgwalters committed Nov 19, 2024
1 parent 3604dbb commit dfa2c79
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ missing_debug_implementations = "deny"
dead_code = "deny"

[workspace.lints.clippy]
disallowed_methods = "deny"
# These should only be in local code
dbg_macro = "deny"
todo = "deny"
Expand Down
4 changes: 4 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
disallowed-methods = [
# https://github.com/rust-lang/rust-clippy/issues/13434#issuecomment-2484292914
{ path = "str::len", reason = "use <str>.as_bytes().len() instead" }
]
2 changes: 1 addition & 1 deletion ostree-ext/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -900,7 +900,7 @@ async fn container_store(
}

fn print_column(s: &str, clen: u16, remaining: &mut terminal_size::Width) {
let l: u16 = s.len().try_into().unwrap();
let l: u16 = s.chars().count().try_into().unwrap();
let l = l.min(remaining.0);
print!("{}", &s[0..l as usize]);
if clen > 0 {
Expand Down
4 changes: 2 additions & 2 deletions ostree-ext/src/tar/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ fn parse_object_entry_path(path: &Utf8Path) -> Result<(&str, &Utf8Path, &str)> {
.parent()
.and_then(|p| p.file_name())
.ok_or_else(|| anyhow!("Invalid path (no parent) {}", path))?;
if parentname.len() != 2 {
if !(parentname.is_ascii() && parentname.as_bytes().len() == 2) {
return Err(anyhow!("Invalid checksum parent {}", parentname));
}
let name = path
Expand All @@ -146,7 +146,7 @@ fn parse_checksum(parent: &str, name: &Utf8Path) -> Result<String> {
// Also take care of the double extension on `.file.xattrs`.
let checksum_rest = checksum_rest.trim_end_matches(".file");

if checksum_rest.len() != 62 {
if !(checksum_rest.is_ascii() && checksum_rest.as_bytes().len() == 62) {
return Err(anyhow!("Invalid checksum part {}", checksum_rest));
}
let reassembled = format!("{}{}", parent, checksum_rest);
Expand Down

0 comments on commit dfa2c79

Please sign in to comment.