`SizeHint` addition overflows (panics in debug builds, wraps in release)

未关闭 适合新手
#183 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
78/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
rust

调研方向

Issue 指向 src/size_hint.rs,其中 Add for SizeHint 在合并边界时会溢出。先阅读该实现及其附近的测试,然后检查建议的饱和下界和经过检查的上界如何符合现有行为。完成标准是溢出的加法不再触发 panic 或回绕,并且测试覆盖所得边界。

由索引模型根据 Issue 内容生成。

描述

impl Add for SizeHint adds the lower and upper bounds with plain +, so it panics with "attempt to add with overflow" in debug builds when a sum exceeds u64::MAX. In release builds it wraps, and the result can be a hint whose bounds are smaller than either input.

// Cargo.toml: http-body = { git = "https://github.com/hyperium/http-body" }
use http_body::SizeHint;

fn main() {
    let s = SizeHint::with_exact(u64::MAX) + SizeHint::with_exact(1);
    println!("{:?} {:?}", s.lower(), s.upper());
}

Debug build:

thread 'main' panicked at http-body/src/size_hint.rs:95:20:
attempt to add with overflow

Release build: prints 0 Some(0).

I expected the sum to saturate at u64::MAX (a size hint that cannot be represented exactly is still a valid lower bound when saturated), or the overflow to be documented. Checked on master at c6ca645.

fn add(self, rhs: Self) -> Self::Output {
    SizeHint {
        lower: self.lower() + rhs.lower(),                                   // overflows
        upper: self.upper().and_then(|this| rhs.upper().map(|rhs| this + rhs)), // overflows
    }
}

Suggested fix: self.lower().saturating_add(rhs.lower()), and for the upper bound checked_add, giving None (no upper bound) when the sum does not fit.

Kani harness that fails on master (cargo kani --harness add_does_not_overflow, appended to src/size_hint.rs):

#[cfg(kani)]
mod kani_proofs {
    use super::SizeHint;

    #[kani::proof]
    fn add_does_not_overflow() {
        let a = SizeHint::with_exact(kani::any());
        let b = SizeHint::with_exact(kani::any());
        let _ = a + b;
    }
}
Failed Checks: attempt to add with overflow
 File: "src/size_hint.rs", line 95, in <size_hint::SizeHint as std::ops::Add>::add
VERIFICATION:- FAILED

It takes about 1.6 s and under 200 MB.


This was found with Kani 0.68.0 in an experiment where AI agents verified popular crates using the Kani agent plugin (model-checking/kani#5059). The text was written with AI assistance; the reproducer and the Kani harness were re-run by hand on the commit named above.

主要语言
Rust
星标
173
派生
71
平均合并
1 天 12 小时
30 天内合并 PR
1

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

hyperium/http-body 的其他 Issue

查看 hyperium/http-body 的全部 Issue

相似的 Issue

更多 Rust Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。