Doesn't base64 have a simple closed-form formula for the expansion, which can be easily inverted for a single-step calculation of max source length?<p>Something like<p>encoded_length = 4 * ceil(length / 3) + len(prefix + suffix)<p>cut_at = floor((desired_length - len(prefix+suffix) / 4) * 3<p>Then, you should also try to at least cut on a utf8 code-point boundary and maybe handle the whole unicode grapheme something something.