function.imap-utf7-encode

function.imap-utf7-encode

[code=python] ¶
#zrbhimani(at)gmail(dot)com ¶
def modified_base64(s): ¶
s_utf7 = s.encode('utf-7') ¶
return s_utf7[1:-1].replace('/', ',') ¶

def modified_unbase64(s): ¶
s_utf7 = '+' + s.replace(',', '/') + '-' ¶
return s_utf7.decode('utf-7') ¶

def encode_imap4_utf7(s, errors=None): ¶
""" ¶
Encode the given C{unicode} string using the IMAP4 specific variation of ¶
UTF-7. ¶

@type s: C{unicode} ¶
@param s: The text to encode. ¶

@param errors: Policy for handling encoding errors. Currently ignored. ¶

@return: C{tuple} of a C{str} giving the encoded bytes and an C{int} ¶
giving the number of code units consumed from the input. ¶
""" ¶
r = [] ¶
_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)) ¶
elif c == '&': ¶
if _in: ¶
r.extend(['&', modified_base64(''.join(_in)), '-']) ¶
del _in[:] ¶
r.append('&-') ¶
else: ¶
_in.append(c) ¶
if _in: ¶
r.extend(['&', modified_base64(''.join(_in)), '-']) ¶
return (''.join(r), len(s))

[/code]