-
Notifications
You must be signed in to change notification settings - Fork 37
Description
For use cases printing to an area with a maximum size, the width of a string is relevant for deciding if and where to truncate it. Currently, this crate can be used for such computations, but not well. Either one computes width per character, but that can't give correct results in all cases, if I understand the logic correctly. Alternatively, one could repeatedly pass prefixes of the string to the functions for computing string width until finding the maximal prefix which fits into the available area. While this would work, it's inefficient, both syntactically and performance-wise. Ideally, there would be functions like
pub fn longest_prefix_below_width(s: &str, width_limit: usize) -> (&str, usize);which return the longest prefix which results in a width below the width_limit.
Additional useful information to return is the width of the prefix, which might be shorter than the width_limit - 1 if the input string is not wide enough to fill to the limit, or of a width-2 character is at the width boundary, resulting in the prefix having width width_limit - 2.
It is also useful to know whether truncation occurred. For &str, that's easy to check based on their length. If an interface for iterators is implemented, which would be nice, it might be considered to add truncation information in some way.
I think implementing this might require reworking the width computation logic, as it currently seems to work in reverse. Doing so would also allow adding a regular width computation interface for non-double-ended iterators, but I don't know how much effort it would be to reverse the logic, or why the computation is currently done starting from the end of the string.