Exercise 18 / 24: Download Budget

// Iterators of Code 2026 — Day 18: Download Budget
// Challenge: Replace the accumulation loop while keeping early failure.
// Return the total bytes, or None as soon as adding a download would overflow.
// An empty download list has a total of zero bytes.

fn total_download_bytes(sizes: &[u64]) -> Option<u64> {
    let mut total = 0_u64;
    for size in sizes {
        match total.checked_add(*size) {
            Some(next) => total = next,
            None => return None,
        }
    }
    Some(total)
}

fn main() {
    assert_eq!(total_download_bytes(&[1200, 800, 4096]), Some(6096));
    assert_eq!(total_download_bytes(&[]), Some(0));
    assert_eq!(total_download_bytes(&[0, 0, 0]), Some(0));
    assert_eq!(total_download_bytes(&[u64::MAX]), Some(u64::MAX));
    assert_eq!(
        total_download_bytes(&[u64::MAX - 10, 10, 0]),
        Some(u64::MAX)
    );
    assert_eq!(total_download_bytes(&[u64::MAX, 1]), None);
    assert_eq!(total_download_bytes(&[1, u64::MAX, 0]), None);
    assert_eq!(total_download_bytes(&[u64::MAX - 10, 11, 42]), None);
}

Your solution

Standalone .rs / std only. Stored, not executed.

60 characters max. Not a login.

File overrides pasted code.

Maximum solution size: 64 KiB.

Editing access uses this browser's cookie. Clearing cookies loses access.