• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 *******************************************************************************
5 *
6 *   Copyright (C) 2013-2016, International Business Machines
7 *   Corporation and others.  All Rights Reserved.
8 *
9 *******************************************************************************
10 *   file name:  listformatter.cpp
11 *   encoding:   US-ASCII
12 *   tab size:   8 (not used)
13 *   indentation:4
14 *
15 *   created on: 2012aug27
16 *   created by: Umesh P. Nair
17 */
18 
19 #include "unicode/listformatter.h"
20 #include "unicode/simpleformatter.h"
21 #include "mutex.h"
22 #include "hash.h"
23 #include "cstring.h"
24 #include "ulocimp.h"
25 #include "charstr.h"
26 #include "ucln_cmn.h"
27 #include "uresimp.h"
28 #include "resource.h"
29 
30 U_NAMESPACE_BEGIN
31 
32 struct ListFormatInternal : public UMemory {
33     SimpleFormatter twoPattern;
34     SimpleFormatter startPattern;
35     SimpleFormatter middlePattern;
36     SimpleFormatter endPattern;
37 
ListFormatInternalListFormatInternal38 ListFormatInternal(
39         const UnicodeString& two,
40         const UnicodeString& start,
41         const UnicodeString& middle,
42         const UnicodeString& end,
43         UErrorCode &errorCode) :
44         twoPattern(two, 2, 2, errorCode),
45         startPattern(start, 2, 2, errorCode),
46         middlePattern(middle, 2, 2, errorCode),
47         endPattern(end, 2, 2, errorCode) {}
48 
ListFormatInternalListFormatInternal49 ListFormatInternal(const ListFormatData &data, UErrorCode &errorCode) :
50         twoPattern(data.twoPattern, errorCode),
51         startPattern(data.startPattern, errorCode),
52         middlePattern(data.middlePattern, errorCode),
53         endPattern(data.endPattern, errorCode) { }
54 
ListFormatInternalListFormatInternal55 ListFormatInternal(const ListFormatInternal &other) :
56     twoPattern(other.twoPattern),
57     startPattern(other.startPattern),
58     middlePattern(other.middlePattern),
59     endPattern(other.endPattern) { }
60 };
61 
62 
63 
64 static Hashtable* listPatternHash = NULL;
65 static UMutex listFormatterMutex = U_MUTEX_INITIALIZER;
66 static const char *STANDARD_STYLE = "standard";
67 
68 U_CDECL_BEGIN
uprv_listformatter_cleanup()69 static UBool U_CALLCONV uprv_listformatter_cleanup() {
70     delete listPatternHash;
71     listPatternHash = NULL;
72     return TRUE;
73 }
74 
75 static void U_CALLCONV
uprv_deleteListFormatInternal(void * obj)76 uprv_deleteListFormatInternal(void *obj) {
77     delete static_cast<ListFormatInternal *>(obj);
78 }
79 
80 U_CDECL_END
81 
ListFormatter(const ListFormatter & other)82 ListFormatter::ListFormatter(const ListFormatter& other) :
83         owned(other.owned), data(other.data) {
84     if (other.owned != NULL) {
85         owned = new ListFormatInternal(*other.owned);
86         data = owned;
87     }
88 }
89 
operator =(const ListFormatter & other)90 ListFormatter& ListFormatter::operator=(const ListFormatter& other) {
91     if (this == &other) {
92         return *this;
93     }
94     delete owned;
95     if (other.owned) {
96         owned = new ListFormatInternal(*other.owned);
97         data = owned;
98     } else {
99         owned = NULL;
100         data = other.data;
101     }
102     return *this;
103 }
104 
initializeHash(UErrorCode & errorCode)105 void ListFormatter::initializeHash(UErrorCode& errorCode) {
106     if (U_FAILURE(errorCode)) {
107         return;
108     }
109 
110     listPatternHash = new Hashtable();
111     if (listPatternHash == NULL) {
112         errorCode = U_MEMORY_ALLOCATION_ERROR;
113         return;
114     }
115 
116     listPatternHash->setValueDeleter(uprv_deleteListFormatInternal);
117     ucln_common_registerCleanup(UCLN_COMMON_LIST_FORMATTER, uprv_listformatter_cleanup);
118 
119 }
120 
getListFormatInternal(const Locale & locale,const char * style,UErrorCode & errorCode)121 const ListFormatInternal* ListFormatter::getListFormatInternal(
122         const Locale& locale, const char *style, UErrorCode& errorCode) {
123     if (U_FAILURE(errorCode)) {
124         return NULL;
125     }
126     CharString keyBuffer(locale.getName(), errorCode);
127     keyBuffer.append(':', errorCode).append(style, errorCode);
128     UnicodeString key(keyBuffer.data(), -1, US_INV);
129     ListFormatInternal* result = NULL;
130     {
131         Mutex m(&listFormatterMutex);
132         if (listPatternHash == NULL) {
133             initializeHash(errorCode);
134             if (U_FAILURE(errorCode)) {
135                 return NULL;
136             }
137         }
138         result = static_cast<ListFormatInternal*>(listPatternHash->get(key));
139     }
140     if (result != NULL) {
141         return result;
142     }
143     result = loadListFormatInternal(locale, style, errorCode);
144     if (U_FAILURE(errorCode)) {
145         return NULL;
146     }
147 
148     {
149         Mutex m(&listFormatterMutex);
150         ListFormatInternal* temp = static_cast<ListFormatInternal*>(listPatternHash->get(key));
151         if (temp != NULL) {
152             delete result;
153             result = temp;
154         } else {
155             listPatternHash->put(key, result, errorCode);
156             if (U_FAILURE(errorCode)) {
157                 return NULL;
158             }
159         }
160     }
161     return result;
162 }
163 
164 static const UChar solidus = 0x2F;
165 static const UChar aliasPrefix[] = { 0x6C,0x69,0x73,0x74,0x50,0x61,0x74,0x74,0x65,0x72,0x6E,0x2F }; // "listPattern/"
166 enum {
167     kAliasPrefixLen = UPRV_LENGTHOF(aliasPrefix),
168     kStyleLenMax = 24 // longest currently is 14
169 };
170 
171 struct ListFormatter::ListPatternsSink : public ResourceSink {
172     UnicodeString two, start, middle, end;
173     char aliasedStyle[kStyleLenMax+1] = {0};
174 
ListPatternsSinkListFormatter::ListPatternsSink175     ListPatternsSink() {}
176     virtual ~ListPatternsSink();
177 
setAliasedStyleListFormatter::ListPatternsSink178     void setAliasedStyle(UnicodeString alias) {
179         int32_t startIndex = alias.indexOf(aliasPrefix, kAliasPrefixLen, 0);
180         if (startIndex < 0) {
181             return;
182         }
183         startIndex += kAliasPrefixLen;
184         int32_t endIndex = alias.indexOf(solidus, startIndex);
185         if (endIndex < 0) {
186             endIndex = alias.length();
187         }
188         alias.extract(startIndex, endIndex-startIndex, aliasedStyle, kStyleLenMax+1, US_INV);
189         aliasedStyle[kStyleLenMax] = 0;
190     }
191 
handleValueForPatternListFormatter::ListPatternsSink192     void handleValueForPattern(ResourceValue &value, UnicodeString &pattern, UErrorCode &errorCode) {
193         if (pattern.isEmpty()) {
194             if (value.getType() == URES_ALIAS) {
195                 if (aliasedStyle[0] == 0) {
196                     setAliasedStyle(value.getAliasUnicodeString(errorCode));
197                 }
198             } else {
199                 pattern = value.getUnicodeString(errorCode);
200             }
201         }
202     }
203 
putListFormatter::ListPatternsSink204     virtual void put(const char *key, ResourceValue &value, UBool /*noFallback*/,
205             UErrorCode &errorCode) {
206         aliasedStyle[0] = 0;
207         if (value.getType() == URES_ALIAS) {
208             setAliasedStyle(value.getAliasUnicodeString(errorCode));
209             return;
210         }
211         ResourceTable listPatterns = value.getTable(errorCode);
212         for (int i = 0; U_SUCCESS(errorCode) && listPatterns.getKeyAndValue(i, key, value); ++i) {
213             if (uprv_strcmp(key, "2") == 0) {
214                 handleValueForPattern(value, two, errorCode);
215             } else if (uprv_strcmp(key, "end") == 0) {
216                 handleValueForPattern(value, end, errorCode);
217             } else if (uprv_strcmp(key, "middle") == 0) {
218                 handleValueForPattern(value, middle, errorCode);
219             } else if (uprv_strcmp(key, "start") == 0) {
220                 handleValueForPattern(value, start, errorCode);
221             }
222         }
223     }
224 };
225 
226 // Virtual destructors must be defined out of line.
~ListPatternsSink()227 ListFormatter::ListPatternsSink::~ListPatternsSink() {}
228 
loadListFormatInternal(const Locale & locale,const char * style,UErrorCode & errorCode)229 ListFormatInternal* ListFormatter::loadListFormatInternal(
230         const Locale& locale, const char * style, UErrorCode& errorCode) {
231     UResourceBundle* rb = ures_open(NULL, locale.getName(), &errorCode);
232     rb = ures_getByKeyWithFallback(rb, "listPattern", rb, &errorCode);
233     if (U_FAILURE(errorCode)) {
234         ures_close(rb);
235         return NULL;
236     }
237     ListFormatter::ListPatternsSink sink;
238     char currentStyle[kStyleLenMax+1];
239     uprv_strncpy(currentStyle, style, kStyleLenMax);
240     currentStyle[kStyleLenMax] = 0;
241 
242     for (;;) {
243         ures_getAllItemsWithFallback(rb, currentStyle, sink, errorCode);
244         if (U_FAILURE(errorCode) || sink.aliasedStyle[0] == 0 || uprv_strcmp(currentStyle, sink.aliasedStyle) == 0) {
245             break;
246         }
247         uprv_strcpy(currentStyle, sink.aliasedStyle);
248     }
249     ures_close(rb);
250     if (U_FAILURE(errorCode)) {
251         return NULL;
252     }
253     if (sink.two.isEmpty() || sink.start.isEmpty() || sink.middle.isEmpty() || sink.end.isEmpty()) {
254         errorCode = U_MISSING_RESOURCE_ERROR;
255         return NULL;
256     }
257     ListFormatInternal* result = new ListFormatInternal(sink.two, sink.start, sink.middle, sink.end, errorCode);
258     if (result == NULL) {
259         errorCode = U_MEMORY_ALLOCATION_ERROR;
260         return NULL;
261     }
262     if (U_FAILURE(errorCode)) {
263         delete result;
264         return NULL;
265     }
266     return result;
267 }
268 
createInstance(UErrorCode & errorCode)269 ListFormatter* ListFormatter::createInstance(UErrorCode& errorCode) {
270     Locale locale;  // The default locale.
271     return createInstance(locale, errorCode);
272 }
273 
createInstance(const Locale & locale,UErrorCode & errorCode)274 ListFormatter* ListFormatter::createInstance(const Locale& locale, UErrorCode& errorCode) {
275     return createInstance(locale, STANDARD_STYLE, errorCode);
276 }
277 
createInstance(const Locale & locale,const char * style,UErrorCode & errorCode)278 ListFormatter* ListFormatter::createInstance(const Locale& locale, const char *style, UErrorCode& errorCode) {
279     Locale tempLocale = locale;
280     const ListFormatInternal* listFormatInternal = getListFormatInternal(tempLocale, style, errorCode);
281     if (U_FAILURE(errorCode)) {
282         return NULL;
283     }
284     ListFormatter* p = new ListFormatter(listFormatInternal);
285     if (p == NULL) {
286         errorCode = U_MEMORY_ALLOCATION_ERROR;
287         return NULL;
288     }
289     return p;
290 }
291 
ListFormatter(const ListFormatData & listFormatData,UErrorCode & errorCode)292 ListFormatter::ListFormatter(const ListFormatData& listFormatData, UErrorCode &errorCode) {
293     owned = new ListFormatInternal(listFormatData, errorCode);
294     data = owned;
295 }
296 
ListFormatter(const ListFormatInternal * listFormatterInternal)297 ListFormatter::ListFormatter(const ListFormatInternal* listFormatterInternal) : owned(NULL), data(listFormatterInternal) {
298 }
299 
~ListFormatter()300 ListFormatter::~ListFormatter() {
301     delete owned;
302 }
303 
304 /**
305  * Joins first and second using the pattern pat.
306  * On entry offset is an offset into first or -1 if offset unspecified.
307  * On exit offset is offset of second in result if recordOffset was set
308  * Otherwise if it was >=0 it is set to point into result where it used
309  * to point into first. On exit, result is the join of first and second
310  * according to pat. Any previous value of result gets replaced.
311  */
joinStringsAndReplace(const SimpleFormatter & pat,const UnicodeString & first,const UnicodeString & second,UnicodeString & result,UBool recordOffset,int32_t & offset,UErrorCode & errorCode)312 static void joinStringsAndReplace(
313         const SimpleFormatter& pat,
314         const UnicodeString& first,
315         const UnicodeString& second,
316         UnicodeString &result,
317         UBool recordOffset,
318         int32_t &offset,
319         UErrorCode& errorCode) {
320     if (U_FAILURE(errorCode)) {
321         return;
322     }
323     const UnicodeString *params[2] = {&first, &second};
324     int32_t offsets[2];
325     pat.formatAndReplace(
326             params,
327             UPRV_LENGTHOF(params),
328             result,
329             offsets,
330             UPRV_LENGTHOF(offsets),
331             errorCode);
332     if (U_FAILURE(errorCode)) {
333         return;
334     }
335     if (offsets[0] == -1 || offsets[1] == -1) {
336         errorCode = U_INVALID_FORMAT_ERROR;
337         return;
338     }
339     if (recordOffset) {
340         offset = offsets[1];
341     } else if (offset >= 0) {
342         offset += offsets[0];
343     }
344 }
345 
format(const UnicodeString items[],int32_t nItems,UnicodeString & appendTo,UErrorCode & errorCode) const346 UnicodeString& ListFormatter::format(
347         const UnicodeString items[],
348         int32_t nItems,
349         UnicodeString& appendTo,
350         UErrorCode& errorCode) const {
351     int32_t offset;
352     return format(items, nItems, appendTo, -1, offset, errorCode);
353 }
354 
format(const UnicodeString items[],int32_t nItems,UnicodeString & appendTo,int32_t index,int32_t & offset,UErrorCode & errorCode) const355 UnicodeString& ListFormatter::format(
356         const UnicodeString items[],
357         int32_t nItems,
358         UnicodeString& appendTo,
359         int32_t index,
360         int32_t &offset,
361         UErrorCode& errorCode) const {
362     offset = -1;
363     if (U_FAILURE(errorCode)) {
364         return appendTo;
365     }
366     if (data == NULL) {
367         errorCode = U_INVALID_STATE_ERROR;
368         return appendTo;
369     }
370 
371     if (nItems <= 0) {
372         return appendTo;
373     }
374     if (nItems == 1) {
375         if (index == 0) {
376             offset = appendTo.length();
377         }
378         appendTo.append(items[0]);
379         return appendTo;
380     }
381     UnicodeString result(items[0]);
382     if (index == 0) {
383         offset = 0;
384     }
385     joinStringsAndReplace(
386             nItems == 2 ? data->twoPattern : data->startPattern,
387             result,
388             items[1],
389             result,
390             index == 1,
391             offset,
392             errorCode);
393     if (nItems > 2) {
394         for (int32_t i = 2; i < nItems - 1; ++i) {
395              joinStringsAndReplace(
396                      data->middlePattern,
397                      result,
398                      items[i],
399                      result,
400                      index == i,
401                      offset,
402                      errorCode);
403         }
404         joinStringsAndReplace(
405                 data->endPattern,
406                 result,
407                 items[nItems - 1],
408                 result,
409                 index == nItems - 1,
410                 offset,
411                 errorCode);
412     }
413     if (U_SUCCESS(errorCode)) {
414         if (offset >= 0) {
415             offset += appendTo.length();
416         }
417         appendTo += result;
418     }
419     return appendTo;
420 }
421 
422 U_NAMESPACE_END
423