1 /********************************************************************** 2 * © 2016 and later: Unicode, Inc. and others. 3 * License & terms of use: http://www.unicode.org/copyright.html#License 4 *********************************************************************** 5 *********************************************************************** 6 * COPYRIGHT: 7 * Copyright (c) 1999-2010, International Business Machines Corporation and 8 * others. All Rights Reserved. 9 ***********************************************************************/ 10 11 #include "unicode/unistr.h" 12 #include <stdio.h> 13 #include <stdlib.h> 14 15 // Verify that a UErrorCode is successful; exit(1) if not 16 void check(UErrorCode& status, const char* msg) { 17 if (U_FAILURE(status)) { 18 printf("ERROR: %s (%s)\n", u_errorName(status), msg); 19 exit(1); 20 } 21 // printf("Ok: %s\n", msg); 22 } 23 24 // Append a hex string to the target 25 static UnicodeString& appendHex(uint32_t number, 26 int8_t digits, 27 UnicodeString& target) { 28 static const UnicodeString DIGIT_STRING("0123456789ABCDEF"); 29 while (digits > 0) { 30 target += DIGIT_STRING[(number >> ((--digits) * 4)) & 0xF]; 31 } 32 return target; 33 } 34 35 // Replace nonprintable characters with unicode escapes 36 UnicodeString escape(const UnicodeString &source) { 37 int32_t i; 38 UnicodeString target; 39 target += "\""; 40 for (i=0; i<source.length(); ++i) { 41 UChar ch = source[i]; 42 if (ch < 0x09 || (ch > 0x0A && ch < 0x20) || ch > 0x7E) { 43 target += "\\u"; 44 appendHex(ch, 4, target); 45 } else { 46 target += ch; 47 } 48 } 49 target += "\""; 50 return target; 51 } 52 53 // Print the given string to stdout 54 void uprintf(const UnicodeString &str) { 55 char *buf = 0; 56 int32_t len = str.length(); 57 // int32_t bufLen = str.extract(0, len, buf); // Preflight 58 /* Preflighting seems to be broken now, so assume 1-1 conversion, 59 plus some slop. */ 60 int32_t bufLen = len + 16; 61 int32_t actualLen; 62 buf = new char[bufLen + 1]; 63 actualLen = str.extract(0, len, buf/*, bufLen*/); // Default codepage conversion 64 buf[actualLen] = 0; 65 printf("%s", buf); 66 delete [] buf; 67 } 68