mirror of
https://github.com/apple/swift-nio
synced 2026-11-22 04:30:41 +00:00
Saturate the `ByteCount` unit factories so large counts no longer trap on overflow. ### Motivation: `ByteCount` exposes unit factories such as `kilobytes`, `megabytes`, `gigabytes`, `kibibytes`, `mebibytes`, and `gibibytes`. Each one computed the byte total with a plain multiplication, for example `1024 * 1024 * 1024 * count` in `gibibytes`. When a caller passes a very large count, that multiplication overflows `Int64` and traps, crashing the process. This is exactly what issue #2877 reports: `ByteCount(contentsOf:maximumSizeAllowed: .gibibytes(.max))` crashes with an arithmetic overflow inside `gibibytes`, even though passing a huge value is a natural way to express "effectively no limit". ### Modifications: I added a small `fileprivate` saturating multiplication helper on `Int64` and routed every unit factory through it. The helper uses `multipliedReportingOverflow(by:)` and, on overflow, clamps to `Int64.max` for positive counts or `Int64.min` for negative counts. Counts that fit continue to produce the exact same value as before, so there is no behavior change for normal inputs. I extended `ByteCountTests` with positive and negative overflow cases, and applied the identical change to both copies of `ByteCount.swift` (`NIOFS` and `_NIOFileSystem`) to keep them in sync, matching the convention used by recent changes to those targets. ### Result: Passing extreme values such as `.gibibytes(.max)` saturates to `Int64.max` instead of trapping, so disabling a size limit via a large value no longer crashes. I verified this by running `swift test --filter ByteCountTests`, which passes after the change. To confirm the tests are load bearing I reverted the source fix and re-ran the new tests, which crashed with signal 5 (the overflow trap) exactly as the issue describes, and they pass again with the fix in place. `swift format lint --strict` reports no issues on the changed files. Fixes #2877