bouzuya.hatenablog.com

ぼうずやのにっき

clippy::format_collect

署名付き URL の続きを進める過程で、 clippy の警告を受けたのでメモ。

signature
    .into_iter()
    .map(|b| format!("{:02x}", b))
    .collect::<String>()

と書いたところ↓のように警告を受けた。

use of `format!` to build up a string from an iterator
this can be written more efficiently by appending to a `String` directly
for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#format_collect
`#[warn(clippy::format_collect)]` on by default
clippyClick for full compiler diagnostic
lib.rs(168, 14): call `fold` instead
lib.rs(168, 22): ... and use the `write!` macro here

clippy::format_collect に怒られた。効率が悪いのはまあわかる。説明どおり https://rust-lang.github.io/rust-clippy/master/index.html#format_collect を確認する。それによると。

fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02X}")).collect()
}

のかわりに

use std::fmt::Write;
fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().fold(String::new(), |mut output, b| {
        let _ = write!(output, "{b:02X}");
        output
    })
}

を使えとのこと。わかるけど面倒だ。

crates:hex があるのでそちらを使うのも良さそうだ。


お腹の調子が悪い。食べ過ぎか……。


今日のコミット。