mgeisler / textwrap

An efficient and powerful Rust library for word wrapping text.
MIT License
467 stars 45 forks source link

Prevent overflows by using `u32` instead of `usize` to represent the line width #420

Closed mgeisler closed 2 years ago

mgeisler commented 2 years ago

Before, we used usize for the line width, now we use an integer type with a fixed width of 32 bits.

Using an usize for the line width can make the optimal-fit wrapping algorithm overflow when it tries to compute the optimal wrapping cost. The problem is that the algorithm works with integer values formed by

(line_width - target_width)**2

and when line_width is near usize::max_value(), this computation can overflow an usize. By limiting the line width to an u32, we can do the internal computations with u128 and avoid the overflows.

The lack of overflows is checked by the new fuzz tests: wrap_first_fit.rs and wrap_optimal_fit.rs. These fuzz tests generate completely random segments with arbitrary widths and checks that they can be wrapped without overflow. The new fuzz tests find the original overflow bugs within a split second.


This is a continuation of #418, just with a better branch name.

mgeisler commented 2 years ago

Please also see #421 which solves this in a more flexible way.

mgeisler commented 2 years ago

Superseded by #421.