Guest User

Untitled

a guest
Jul 17th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. #import "HUTF8MappedUTF16String.h"
  2. // example and a kind of a test
  3.  
  4. #define U16_IS_SINGLE(c) !(((c)&0xfffff800)==0xd800)
  5.  
  6. int main (int argc, const char * argv[]) {
  7. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  8.  
  9. // Our original Unicode test string
  10. unichar u16chars[] = {
  11. // Unicode characters:
  12. // h e j ♜ | ♞ | 𝄞 d å
  13. // Unicode (bits/char):
  14. // 8 8 8 8 16 8 16 8 32 8 8 16
  15. // UTF-8 widths (bytes/char):
  16. // 1 1 1 1 3 1 3 1 4 1 1 2
  17. 'h','e','j',' ',0x265c,'|',0x265e,'|',0xd834,0xdd1e,' ','d',0xe5 };
  18. NSString *str = [NSString stringWithCharacters:u16chars length:
  19. sizeof(u16chars)/sizeof(*u16chars)];
  20. HUTF8MappedUTF16String mappedString;
  21. mappedString.setNSString(str, NSMakeRange(0,str.length));
  22.  
  23. // UTF-8 buffer
  24. uint8_t *u8buf = new uint8_t[mappedString.maximumUTF8Size()+1];
  25.  
  26. // convert
  27. size_t u8len = mappedString.convert(u8buf);
  28.  
  29. u8buf[u8len] = '\0';
  30. fprintf(stderr, "utf8 value => '%s'\n", u8buf);
  31.  
  32. for (size_t i=0; i<u8len; i++) {
  33. size_t index = mappedString.UTF16IndexForUTF8Index(i);
  34. unichar c = mappedString[index];
  35.  
  36. if (U16_IS_SINGLE(c)) {
  37. NSLog(@"utf8[%zu] => utf16[%zu] -> '%C' \\u%x", i, index, c, c);
  38. } else {
  39. NSLog(@"utf8[%zu] => utf16[%zu..%zu] -> '%C%C' \\u%x \\u%x",
  40. i, index, index+1, c, mappedString[index+1],
  41. c, mappedString[index+1]);
  42. }
  43. }
  44.  
  45. NSRange u8range = NSMakeRange(2, u8len-4); // should be "j ♜|♞|𝄞 d"
  46. //u8range = NSMakeRange(12, 1); // should be "𝄞"
  47. NSString *u8substr = // temporary so we can use NSLog
  48. [[[NSString alloc] initWithBytesNoCopy:u8buf+u8range.location
  49. length:u8range.length
  50. encoding:NSUTF8StringEncoding
  51. freeWhenDone:NO] autorelease];
  52. NSLog(@"u8range: %@ -> '%@'", NSStringFromRange(u8range), u8substr);
  53. NSRange u16range = mappedString.UTF16RangeForUTF8Range(u8range);
  54. NSString *u16substr = [str substringWithRange:u16range];
  55. NSLog(@"u16range: %@ -> '%@'", NSStringFromRange(u16range), u16substr);
  56.  
  57. [pool drain];
  58. return 0;
  59. }
Add Comment
Please, Sign In to add comment