1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-03-20 14:31:15 +02:00

Make const slide less silly (#2557)

A constant named ZERO that does not contain zero seems pretty silly!

This also shows an example of a const fn.
This commit is contained in:
Dustin J. Mitchell 2025-01-16 04:18:29 -05:00 committed by GitHub
parent cb5409052a
commit 3291cb6c62
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -11,10 +11,18 @@ they are used:
```rust,editable
const DIGEST_SIZE: usize = 3;
const ZERO: Option<u8> = Some(42);
const FILL_VALUE: u8 = calculate_fill_value();
const fn calculate_fill_value() -> u8 {
if DIGEST_SIZE < 10 {
42
} else {
13
}
}
fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {
let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE];
let mut digest = [FILL_VALUE; DIGEST_SIZE];
for (idx, &b) in text.as_bytes().iter().enumerate() {
digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b);
}