···11const segmenter = new Intl.Segmenter();
2233export const isWithinUtf8Bounds = (input: string, min = 0, max = Infinity): 'max' | 'min' | undefined => {
44- const maybeUtf8Len = input.length * 3;
44+ const utf16Len = input.length;
55+ const maybeUtf8Len = utf16Len * 3;
5666- // fail early if we're still less than minimum length
77+ // fail early if estimated upper bound is too small
78 if (maybeUtf8Len < min) {
89 return 'min';
910 }
10111111- // skip if we're still within maximum length
1212- if (maybeUtf8Len <= max) {
1212+ // skip if UTF-16 length already satisfies both constraints
1313+ if (utf16Len >= min && maybeUtf8Len <= max) {
1314 return undefined;
1415 }
1516···32333334 const utf16Len = input.length;
34353535- // fail early if UTF-16 length is less than grapheme length
3636+ // fail early if UTF-16 length is too small
3637 if (utf16Len < min) {
3738 return 'min';
3839 }
39404040- // skip if we're still within maximum constraint
4141- if (utf16Len <= max) {
4141+ // if there is no minimum bounds, we can safely skip when UTF-16 is
4242+ // within the maximum bounds.
4343+ if (min === 0 && utf16Len <= max) {
4244 return undefined;
4345 }
4446