# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+from .six import b, u, text_type, PY3, int2byte
class FolderNameError(ValueError):
pass
+PRINTABLE = set(range(0x20, 0x26)) | set(range(0x27, 0x7f))
def encode(s):
- if isinstance(s, str) and sum(n for n in (ord(c) for c in s) if n > 127):
- raise FolderNameError("%r contains characters not valid in a str folder name. "
- "Convert to unicode first?" % s)
+ """Encode a folder name using IMAP modified UTF-7 encoding
+
+ Input and output types:
+ Python 2 - str/unicode to str
+ Python 3 - str to bytes
+ """
+ # This is for Python 2 only. Under Python 3 the input will always be unicode.
+ if (not PY3 and isinstance(s, str) and
+ sum(n for n in (ord(c) for c in s) if n > 127)):
+ raise FolderNameError("%r contains characters not valid in a str "
+ "folder name. Convert to unicode first?" % s)
r = []
_in = []
+
+ def extend_result_if_chars_buffered():
+ if _in:
+ r.extend([b('&'), modified_base64(''.join(_in)), b('-')])
+ del _in[:]
+
for c in s:
- if ord(c) in (range(0x20, 0x26) + range(0x27, 0x7f)):
- if _in:
- r.extend(['&', modified_base64(''.join(_in)), '-'])
- del _in[:]
- r.append(str(c))
+ if ord(c) in PRINTABLE:
+ extend_result_if_chars_buffered()
+ r.append(int2byte(ord(c)))
elif c == '&':
- if _in:
- r.extend(['&', modified_base64(''.join(_in)), '-'])
- del _in[:]
- r.append('&-')
+ extend_result_if_chars_buffered()
+ r.append(b('&-'))
else:
_in.append(c)
- if _in:
- r.extend(['&', modified_base64(''.join(_in)), '-'])
- return ''.join(r)
+ extend_result_if_chars_buffered()
+
+ return b('').join(r[:])
def decode(s):
+ """Decode a folder name from IMAP modified UTF-7 encoding to unicode
+
+ Input and output types:
+ Python 2 - str to unicode
+ Python 3 - bytes to str
+ """
r = []
- decode = []
- for c in s:
- if c == '&' and not decode:
- decode.append('&')
- elif c == '-' and decode:
- if len(decode) == 1:
- r.append('&')
+ _in = []
+ for c in iter_as_bytes(s):
+ if c == b('&') and not _in:
+ _in.append(b('&'))
+ elif c == b('-') and _in:
+ if len(_in) == 1:
+ r.append(u('&'))
else:
- r.append(modified_unbase64(''.join(decode[1:])))
- decode = []
- elif decode:
- decode.append(c)
+ r.append(modified_unbase64(b('').join(_in[1:])))
+ _in = []
+ elif _in:
+ _in.append(c)
else:
r.append(c)
- if decode:
- r.append(modified_unbase64(''.join(decode[1:])))
- out = ''.join(r)
-
- if not isinstance(out, unicode):
- out = unicode(out, 'latin-1')
- return out
+ if _in:
+ r.append(modified_unbase64(b('').join(_in[1:])))
+ return u('').join(
+ x.decode('latin-1') if not isinstance(x, text_type) else x
+ for x in r[:])
def modified_base64(s):
s_utf7 = s.encode('utf-7')
- return s_utf7[1:-1].replace('/', ',')
-
+ return s_utf7[1:-1].replace(b('/'), b(','))
def modified_unbase64(s):
- s_utf7 = '+' + s.replace(',', '/') + '-'
+ s_utf7 = b('+') + s.replace(b(','), b('/')) + b('-')
return s_utf7.decode('utf-7')
+
+if PY3:
+ def iter_as_bytes(some_bytes):
+ for c in some_bytes[:]:
+ yield int2byte(c)
+else:
+ def iter_as_bytes(a_str):
+ return iter(a_str)
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses
-from imapclient.six import u
+from imapclient.six import b, u, binary_type, text_type, PY3
from imapclient.imap_utf7 import decode, encode, FolderNameError
from imapclient.test.util import unittest
class IMAP4UTF7TestCase(unittest.TestCase):
tests = [
- ['Foo', 'Foo'],
- ['Foo Bar', 'Foo Bar'],
- ['Stuff & Things', 'Stuff &- Things'],
- [u('Hello world'), 'Hello world'],
- [u('Hello & world'), 'Hello &- world'],
- [u('Hello\xffworld'), 'Hello&AP8-world'],
- [u('\xff\xfe\xfd\xfc'), '&AP8A,gD9APw-'],
+ ['Foo', b('Foo')],
+ ['Foo Bar', b('Foo Bar')],
+ ['Stuff & Things', b('Stuff &- Things')],
+ [u('Hello world'), b('Hello world')],
+ [u('Hello & world'), b('Hello &- world')],
+ [u('Hello\xffworld'), b('Hello&AP8-world')],
+ [u('\xff\xfe\xfd\xfc'), b('&AP8A,gD9APw-')],
[u('~peter/mail/\u65e5\u672c\u8a9e/\u53f0\u5317'),
- '~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060
- ['\x00foo', '&AAA-foo'],
+ b('~peter/mail/&ZeVnLIqe-/&U,BTFw-')], # example from RFC 2060
+ ['\x00foo', b('&AAA-foo')],
]
def test_encode(self):
for (input, output) in self.tests:
- self.assertEquals(encode(input), output)
+ encoded = encode(input)
+ self.assertIsInstance(encoded, binary_type)
+ self.assertEqual(encoded, output)
def test_decode(self):
for (input, output) in self.tests:
decoded = decode(output)
- self.assertEquals(input, decoded)
- self.assert_(isinstance(decoded, unicode))
+ self.assertIsInstance(decoded, text_type)
+ self.assertEqual(input, decoded)
+ @unittest.skipIf(PY3, "Only relevant for Python 2")
def test_illegal_chars(self):
not_valid_as_str = [
'blah' + chr(0x80) + 'sne',
unicode_names = [unicode(name, 'latin-1') for name in not_valid_as_str]
for name in unicode_names:
- assert isinstance(encode(name), str)
-
+ encoded = encode(name)
+ self.assertIsInstance(encoded, str)
def test_printableSingletons(self):
"""
characters which are in ASCII using the corresponding ASCII byte.
"""
# All printables represent themselves
- for o in range(0x20, 0x26) + range(0x27, 0x7f):
- self.failUnlessEqual(chr(o), encode(chr(o)))
- self.failUnlessEqual(chr(o), decode(chr(o)))
- self.failUnlessEqual(encode('&'), '&-')
- self.failUnlessEqual(decode('&-'), '&')
-
+ for o in list(range(0x20, 0x26)) + list(range(0x27, 0x7f)):
+ self.assertEqual(b(chr(o)), encode(chr(o)))
+ self.assertEqual(chr(o), decode(b(chr(o))))
+ self.assertEqual(encode('&'), b('&-'))
+ self.assertEqual(encode(u('&')), b('&-'))
+ self.assertEqual(decode(b('&-')), u('&'))
def test_FolderNameError_super(self):
- self.assert_(issubclass(FolderNameError, ValueError))
+ self.assertTrue(issubclass(FolderNameError, ValueError))
if __name__ == '__main__':