appender: fix max_files integer underflow when set to zero (#3348)

## Motivation

When `max_files` set to zero,
[rolling.rs:695](c01d4fd9de/tracing-appender/src/rolling.rs (L695))
will cause integer underflow and panicking in debug build. In my
opinion the API should prevent this from happening as "zero" is a
valid `usize` value to pass in.

## Solution

Currently, in release builds, if `max_files` is set to zero, it
behaves just like `u64::MAX` on `x86_64` platforms. Therefore, I
decided to simply make `zero == None`, which should align with the
existing behavior but without the panicking. I believe this can be
considered as "non-breaking".
This commit is contained in:
Sola 2025-11-22 17:12:49 +08:00 committed by GitHub
parent 2a8b0404c9
commit adbd8a41f9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -195,7 +195,7 @@ impl Builder {
/// the maximum, so if you need to retain `m` log files, specify a max of
/// `m + 1`.
///
/// If no value is supplied, the `RollingAppender` will not remove any files.
/// If `0` is supplied, the `RollingAppender` will not remove any files.
///
/// Files are considered candidates for deletion based on the following
/// criteria:
@ -232,7 +232,8 @@ impl Builder {
#[must_use]
pub fn max_log_files(self, n: usize) -> Self {
Self {
max_files: Some(n),
// Setting `n` to 0 will disable the max files (effectively make it infinite).
max_files: Some(n).filter(|&n| n > 0),
..self
}
}