Protect TTF_MeasureString() from overlong input. #550
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When the string to be measured seems likely to be significantly longer than the maximum width, use font metrics to estimate a prefix of the string to measure first. Since harfbuzz has to shape the entire string before any of it can be measured, a good first estimate reduces useless work, and avoids quadratic performance from common use cases.
More details:
Harfbuzz shaping is done over the entire input string before any of it can be measured. In the case of a string that is much longer than the maximum width, most of the produced shaping data is not relevant.
A common use case for TTF_MeasureString() is to identify a line's worth of text from a string, and then call the function again with the remainder of the string, repeating this process until the string is fully consumed. But if the entire string is shaped on each call, this results in quadratic performance.
Absent new functionality in harfbuzz, one solution is for TTF_MeasureString() to use font metrics to quickly estimate a likely prefix that will still meet or exceed the caller's maximum width, and process that prefix instead. (If this prefix proves to be shorter than the maximum width, then the code will retry with longer prefixes until a correct return value is found, but this will almost never happen.)
Since this estimation is potentially redundant work, it is only done for strings that appear likely to be significantly longer than the maximum width. All other strings are processed normally, as before this change.