1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2009 Index Data
3 * See the file LICENSE for details.
8 * \brief UTF-8 string utilities for ICU
16 #include <yaz/xmalloc.h>
18 #include <yaz/icu_I18N.h>
26 #include <unicode/ustring.h> /* some more string fcns*/
27 #include <unicode/uchar.h> /* char names */
29 struct icu_buf_utf8 *icu_buf_utf8_create(size_t capacity)
31 struct icu_buf_utf8 * buf8
32 = (struct icu_buf_utf8 *) xmalloc(sizeof(struct icu_buf_utf8));
40 buf8->utf8 = (uint8_t *) xmalloc(sizeof(uint8_t) * capacity);
41 buf8->utf8[0] = (uint8_t) 0;
42 buf8->utf8_cap = capacity;
47 struct icu_buf_utf8 * icu_buf_utf8_clear(struct icu_buf_utf8 * buf8)
52 buf8->utf8[0] = (uint8_t) 0;
58 struct icu_buf_utf8 * icu_buf_utf8_resize(struct icu_buf_utf8 * buf8,
66 buf8->utf8 = (uint8_t *) xmalloc(sizeof(uint8_t) * capacity);
69 = (uint8_t *) xrealloc(buf8->utf8, sizeof(uint8_t) * capacity);
71 buf8->utf8_cap = capacity;
83 const char *icu_buf_utf8_to_cstr(struct icu_buf_utf8 *src8)
85 if (!src8 || src8->utf8_len == 0)
88 if (src8->utf8_len == src8->utf8_cap)
89 src8 = icu_buf_utf8_resize(src8, src8->utf8_len * 2 + 1);
91 src8->utf8[src8->utf8_len] = '\0';
93 return (const char *) src8->utf8;
96 void icu_buf_utf8_destroy(struct icu_buf_utf8 * buf8)
103 UErrorCode icu_utf16_from_utf8_cstr(struct icu_buf_utf16 * dest16,
104 const char * src8cstr,
107 size_t src8cstr_len = 0;
108 int32_t utf16_len = 0;
110 *status = U_ZERO_ERROR;
111 src8cstr_len = strlen(src8cstr);
113 u_strFromUTF8(dest16->utf16, dest16->utf16_cap,
115 src8cstr, src8cstr_len, status);
117 /* check for buffer overflow, resize and retry */
118 if (*status == U_BUFFER_OVERFLOW_ERROR)
120 icu_buf_utf16_resize(dest16, utf16_len * 2);
121 *status = U_ZERO_ERROR;
122 u_strFromUTF8(dest16->utf16, dest16->utf16_cap,
124 src8cstr, src8cstr_len, status);
127 if (U_SUCCESS(*status)
128 && utf16_len <= dest16->utf16_cap)
129 dest16->utf16_len = utf16_len;
131 icu_buf_utf16_clear(dest16);
136 UErrorCode icu_utf16_to_utf8(struct icu_buf_utf8 * dest8,
137 struct icu_buf_utf16 * src16,
140 int32_t utf8_len = 0;
142 u_strToUTF8((char *) dest8->utf8, dest8->utf8_cap,
144 src16->utf16, src16->utf16_len, status);
146 /* check for buffer overflow, resize and retry */
147 if (*status == U_BUFFER_OVERFLOW_ERROR)
149 icu_buf_utf8_resize(dest8, utf8_len * 2);
150 *status = U_ZERO_ERROR;
151 u_strToUTF8((char *) dest8->utf8, dest8->utf8_cap,
153 src16->utf16, src16->utf16_len, status);
156 if (U_SUCCESS(*status)
157 && utf8_len <= dest8->utf8_cap)
158 dest8->utf8_len = utf8_len;
160 icu_buf_utf8_clear(dest8);
165 #endif /* YAZ_HAVE_ICU */
170 * c-file-style: "Stroustrup"
171 * indent-tabs-mode: nil
173 * vim: shiftwidth=4 tabstop=8 expandtab