bpo-34222: Lib/email: Fix infinite loop when folding by Xiami2012 · Pull Request #8990 · python/cpython

@Xiami2012

Currently when folding headers with length > maxlen, _fold_as_ew tries
to split the to_encode into multiple parts to fulfill the maxlen limit,
in an inapropriate way.

If a long header has non-ascii characters, in some situations (e.g. a
Subject: with full of CJK chars), it will split the to_encode into
["", to_encode], entering an infinite loop.

This commit fixes this by introducing a smarter way to split.
Besides, when an header needs to be folded now, every non-last line will
try its best to reach the maxlen, in O(log N) time.
Also, apply missing charset= parameter for _ew.encode.

The bug is introduced in commit 85d5c18