Last active
August 29, 2015 14:00
-
-
Save hisui/11373047 to your computer and use it in GitHub Desktop.
[iOS] iconv+NSString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iconv.h> | |
static NSString *decode(const char *encoding, char *src, size_t len, double capacityRatio=2) | |
{ | |
if (len == 0) { | |
return @""; | |
} | |
auto size = size_t(len * capacityRatio); | |
auto dest = (char*) malloc(size); | |
size_t pos = 0; | |
auto ic = iconv_open("UTF-16", encoding); | |
for (;;) { | |
auto rem = size - pos; | |
auto tmp = dest + pos; | |
auto ret = iconv(ic, &src, &len, &tmp, &rem); | |
pos = size - rem; | |
if (ret != size_t(-1)) { | |
break; | |
} | |
switch (errno) { | |
case EILSEQ: | |
case EINVAL: | |
NSLog(@"[warn] Invalid byte sequence found."); | |
len --; | |
src ++; | |
break; | |
case E2BIG: | |
NSLog(@"[info] Output buffer is too small"); | |
dest = (char*) realloc(dest, size * 2); | |
break; | |
} | |
} | |
iconv_close(ic); | |
return [NSString.alloc initWithBytesNoCopy:dest | |
length:pos | |
encoding:NSUTF16StringEncoding | |
freeWhenDone:YES]; | |
} | |
static NSString *sjis(NSData *data) | |
{ | |
return decode("SJIS", (char*) data.bytes, data.length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment