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