text
stringlengths
0
357
// NOTE: cannot convert UTF8 sequences longer than 4
utf8total = 4;
ucs4 = c & 0x03;
}
continue;
}
// loop to split ucs4 into two utf16 chars if necessary
utf8total = 0;
do {
if (ucs4 >= UTF16BASE) {
ucs4 -= UTF16BASE;
bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
+ UTF16HIGHSTART);
ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
utf16flag = 1;
} else {
bitbuf = (bitbuf << 16) | ucs4;
utf16flag = 0;
}
bitstogo += 16;
/* spew out base64 */
while (bitstogo >= 6) {
bitstogo -= 6;
*dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
: bitbuf)
& 0x3F];
}
} while (utf16flag);
}
// if in UTF-7 mode, finish in ASCII
if (utf7mode) {
if (bitstogo) {
*dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
}
*dst++ = '-';
}
*dst = '\0';
return res;
}
/**
* Convert an modified UTF-7 encoded string to an UTF-8 string.
* Modified UTF-7 strings are used eg. in IMAP mailbox names.
*
* @param to_decode Null-terminated, modified UTF-7 string to decode.
* @param change_spaces If set, the underscore character `_` is converted to
* a space.
* @return Null-terminated UTF-8 string. Must be free()'d after usage.
* Halts the program on memory allocation errors,
* for all other errors, an empty string is returned.
* NULL is never returned.
*/
char* dc_decode_modified_utf7(const char *to_decode, int change_spaces)
{
unsigned c = 0;
unsigned i = 0;
unsigned bitcount = 0;
unsigned long ucs4 = 0;
unsigned long utf16 = 0;
unsigned long bitbuf = 0;
unsigned char base64[256];
const char* src = NULL;
char* dst = NULL;
char* res = NULL;
if (to_decode==NULL) {
return dc_strdup("");
}
res = (char*)malloc(4*strlen(to_decode)+1);
dst = res;
src = to_decode;
if(!dst) {
exit(52);
}
memset(base64, UNDEFINED, sizeof (base64));
for (i = 0; i < sizeof (base64chars); ++i) {
base64[(unsigned)base64chars[i]] = i;
}
while (*src != '\0')
{
c = *src++;
// deal with literal characters and &-
if (c != '&' || *src=='-') {
// encode literally
if (change_spaces && c=='_') {
*dst++ = ' ';
}
else {
*dst++ = c;
}
// skip over the '-' if this is an &- sequence
if (c=='&') ++src;
}