]> git.saurik.com Git - apple/icu.git/blame - icuSources/samples/msgfmt/util.cpp
ICU-59180.0.1.tar.gz
[apple/icu.git] / icuSources / samples / msgfmt / util.cpp
CommitLineData
f3c0d7a5
A
1/**********************************************************************
2 * © 2016 and later: Unicode, Inc. and others.
3 * License & terms of use: http://www.unicode.org/copyright.html#License
4 ***********************************************************************
5 ***********************************************************************
b75a7d8f 6 * COPYRIGHT:
729e4ab9 7 * Copyright (c) 1999-2010, International Business Machines Corporation and
b75a7d8f 8 * others. All Rights Reserved.
f3c0d7a5 9 ***********************************************************************/
b75a7d8f
A
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
16void 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
25static 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
36UnicodeString 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
54void 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);
729e4ab9 66 delete [] buf;
b75a7d8f 67}