Coverage Report

Created: 2026-09-28 06:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/icu/icu4c/source/common/uniset_closure.cpp
Line
Count
Source
1
// © 2016 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
/*
4
*******************************************************************************
5
*
6
*   Copyright (C) 2011, International Business Machines
7
*   Corporation and others.  All Rights Reserved.
8
*
9
*******************************************************************************
10
*   file name:  uniset_closure.cpp
11
*   encoding:   UTF-8
12
*   tab size:   8 (not used)
13
*   indentation:4
14
*
15
*   created on: 2011may30
16
*   created by: Markus W. Scherer
17
*
18
*   UnicodeSet::closeOver() and related methods moved here from uniset_props.cpp
19
*   to simplify dependencies.
20
*   In particular, this depends on the BreakIterator, but the BreakIterator
21
*   code also builds UnicodeSets from patterns and needs uniset_props.
22
*/
23
24
#include "unicode/brkiter.h"
25
#include "unicode/locid.h"
26
#include "unicode/parsepos.h"
27
#include "unicode/uniset.h"
28
#include "unicode/utf16.h"
29
#include "cmemory.h"
30
#include "ruleiter.h"
31
#include "ucase.h"
32
#include "uprops.h"
33
#include "util.h"
34
#include "uvector.h"
35
36
U_NAMESPACE_BEGIN
37
38
// TODO memory debugging provided inside uniset.cpp
39
// could be made available here but probably obsolete with use of modern
40
// memory leak checker tools
41
#define _dbgct(me)
42
43
//----------------------------------------------------------------
44
// Constructors &c
45
//----------------------------------------------------------------
46
47
UnicodeSet::UnicodeSet(const UnicodeString& pattern,
48
                       uint32_t options,
49
                       const SymbolTable* symbols,
50
80.8k
                       UErrorCode& status) {
51
80.8k
    applyPattern(pattern, options, symbols, status);
52
80.8k
    _dbgct(this);
53
80.8k
}
54
55
UnicodeSet::UnicodeSet(const UnicodeString& pattern, ParsePosition& pos,
56
                       uint32_t options,
57
                       const SymbolTable* symbols,
58
0
                       UErrorCode& status) {
59
0
    applyPattern(pattern, pos, options, symbols, status);
60
0
    _dbgct(this);
61
0
}
62
63
//----------------------------------------------------------------
64
// Public API
65
//----------------------------------------------------------------
66
67
UnicodeSet& UnicodeSet::applyPattern(const UnicodeString& pattern,
68
                                     uint32_t options,
69
                                     const SymbolTable* symbols,
70
80.8k
                                     UErrorCode& status) U_LIFETIME_BOUND {
71
80.8k
    ParsePosition pos(0);
72
80.8k
    applyPattern(pattern, pos, options, symbols, status);
73
80.8k
    if (U_FAILURE(status)) return *this;
74
75
64.3k
    int32_t i = pos.getIndex();
76
77
64.3k
    if (options & USET_IGNORE_SPACE) {
78
        // Skip over trailing whitespace
79
0
        ICU_Utility::skipWhitespace(pattern, i, true);
80
0
    }
81
82
64.3k
    if (i != pattern.length()) {
83
73
        status = U_ILLEGAL_ARGUMENT_ERROR;
84
73
    }
85
64.3k
    return *this;
86
80.8k
}
87
88
UnicodeSet& UnicodeSet::applyPattern(const UnicodeString& pattern,
89
                                     ParsePosition& pos,
90
                                     uint32_t options,
91
                                     const SymbolTable* symbols,
92
80.8k
                                     UErrorCode& status) U_LIFETIME_BOUND {
93
80.8k
    if (U_FAILURE(status)) {
94
0
        return *this;
95
0
    }
96
80.8k
    if (isFrozen()) {
97
0
        status = U_NO_WRITE_PERMISSION;
98
0
        return *this;
99
0
    }
100
    // Need to build the pattern in a temporary string because
101
    // _applyPattern calls add() etc., which set pat to empty.
102
80.8k
    UnicodeString rebuiltPat;
103
80.8k
    RuleCharacterIterator chars(pattern, symbols, pos);
104
80.8k
    applyPattern(pattern, pos, chars, symbols, rebuiltPat, options, &UnicodeSet::closeOver, status);
105
80.8k
    if (U_FAILURE(status)) return *this;
106
64.3k
    if (chars.inVariable()) {
107
        // syntaxError(chars, "Extra chars in variable value");
108
0
        status = U_MALFORMED_SET;
109
0
        return *this;
110
0
    }
111
64.3k
    setPattern(rebuiltPat);
112
64.3k
    return *this;
113
64.3k
}
114
115
// USetAdder implementation
116
// Does not use uset.h to reduce code dependencies
117
static void U_CALLCONV
118
161M
_set_add(USet *set, UChar32 c) {
119
161M
    reinterpret_cast<UnicodeSet*>(set)->add(c);
120
161M
}
121
122
static void U_CALLCONV
123
0
_set_addRange(USet *set, UChar32 start, UChar32 end) {
124
0
    reinterpret_cast<UnicodeSet*>(set)->add(start, end);
125
0
}
126
127
static void U_CALLCONV
128
6.69M
_set_addString(USet *set, const char16_t *str, int32_t length) {
129
6.69M
    reinterpret_cast<UnicodeSet*>(set)->add(UnicodeString(static_cast<UBool>(length < 0), str, length));
130
6.69M
}
131
132
//----------------------------------------------------------------
133
// Case folding API
134
//----------------------------------------------------------------
135
136
// add the result of a full case mapping to the set
137
// use str as a temporary string to avoid constructing one
138
static inline void
139
0
addCaseMapping(UnicodeSet &set, int32_t result, const char16_t *full, UnicodeString &str) {
140
0
    if(result >= 0) {
141
0
        if(result > UCASE_MAX_STRING_LENGTH) {
142
            // add a single-code point case mapping
143
0
            set.add(result);
144
0
        } else {
145
            // add a string case mapping from full with length result
146
0
            str.setTo(static_cast<UBool>(false), full, result);
147
0
            set.add(str);
148
0
        }
149
0
    }
150
    // result < 0: the code point mapped to itself, no need to add it
151
    // see ucase.h
152
0
}
153
154
namespace {
155
156
/** For case closure on a large set, look only at code points with relevant properties. */
157
const UnicodeSet &maybeOnlyCaseSensitive(const UnicodeSet &src U_LIFETIME_BOUND,
158
463k
                                         UnicodeSet &subset U_LIFETIME_BOUND) {
159
    // The subset must have been constructed with all code points,
160
    // so that the retainAll() intersection effectively copies all single code points from src.
161
463k
    U_ASSERT(subset.contains(0, 0x10ffff));
162
463k
    if (src.size() < 30) {
163
331k
        return src;
164
331k
    }
165
    // Return the intersection of the src code points with Case_Sensitive ones.
166
132k
    UErrorCode errorCode = U_ZERO_ERROR;
167
132k
    const UnicodeSet *sensitive =
168
132k
        CharacterProperties::getBinaryPropertySet(UCHAR_CASE_SENSITIVE, errorCode);
169
132k
    if (U_FAILURE(errorCode)) {
170
0
        return src;
171
0
    }
172
    // Start by copying the "smaller" set.
173
    // (We "copy" by intersecting all Unicode *code points* with the first set,
174
    // which omits any strings.)
175
132k
    if (src.getRangeCount() > sensitive->getRangeCount()) {
176
62.5k
        subset.retainAll(*sensitive);
177
62.5k
        subset.retainAll(src);
178
70.0k
    } else {
179
70.0k
        subset.retainAll(src);
180
70.0k
        subset.retainAll(*sensitive);
181
70.0k
    }
182
132k
    return subset;
183
132k
}
184
185
// Per-character scf = Simple_Case_Folding of a string.
186
// (Normally when we case-fold a string we use full case foldings.)
187
0
bool scfString(const UnicodeString &s, UnicodeString &scf) {
188
    // Iterate over the raw buffer for best performance.
189
0
    const char16_t *p = s.getBuffer();
190
0
    int32_t length = s.length();
191
    // Loop while not needing modification.
192
0
    for (int32_t i = 0; i < length;) {
193
0
        UChar32 c;
194
0
        U16_NEXT(p, i, length, c);  // post-increments i
195
0
        UChar32 scfChar = u_foldCase(c, U_FOLD_CASE_DEFAULT);
196
0
        if (scfChar != c) {
197
            // Copy the characters before c.
198
0
            scf.setTo(p, i - U16_LENGTH(c));
199
            // Loop over the rest of the string and keep case-folding.
200
0
            for (;;) {
201
0
                scf.append(scfChar);
202
0
                if (i == length) {
203
0
                    return true;
204
0
                }
205
0
                U16_NEXT(p, i, length, c);  // post-increments i
206
0
                scfChar = u_foldCase(c, U_FOLD_CASE_DEFAULT);
207
0
            }
208
0
        }
209
0
    }
210
0
    return false;
211
0
}
212
213
}  // namespace
214
215
463k
UnicodeSet& UnicodeSet::closeOver(int32_t attribute) U_LIFETIME_BOUND {
216
463k
    if (isFrozen() || isBogus()) {
217
0
        return *this;
218
0
    }
219
463k
    switch (attribute & USET_CASE_MASK) {
220
0
    case 0:
221
0
        break;
222
463k
    case USET_CASE_INSENSITIVE:
223
463k
        closeOverCaseInsensitive(/* simple= */ false);
224
463k
        break;
225
0
    case USET_ADD_CASE_MAPPINGS:
226
0
        closeOverAddCaseMappings();
227
0
        break;
228
0
    case USET_SIMPLE_CASE_INSENSITIVE:
229
0
        closeOverCaseInsensitive(/* simple= */ true);
230
0
        break;
231
0
    default:
232
        // bad option (unreachable)
233
0
        break;
234
463k
    }
235
463k
    return *this;
236
463k
}
237
238
463k
void UnicodeSet::closeOverCaseInsensitive(bool simple) {
239
    // Start with input set to guarantee inclusion.
240
463k
    UnicodeSet foldSet(*this);
241
    // Full case mappings closure:
242
    // Remove strings because the strings will actually be reduced (folded);
243
    // therefore, start with no strings and add only those needed.
244
    // Do this before processing code points, because they may add strings.
245
463k
    if (!simple && foldSet.hasStrings()) {
246
15.7k
        foldSet.strings_->removeAllElements();
247
15.7k
    }
248
249
463k
    USetAdder sa = {
250
463k
        foldSet.toUSet(),
251
463k
        _set_add,
252
463k
        _set_addRange,
253
463k
        _set_addString,
254
463k
        nullptr, // don't need remove()
255
463k
        nullptr // don't need removeRange()
256
463k
    };
257
258
463k
    UnicodeSet subset(0, 0x10ffff);
259
463k
    const UnicodeSet &codePoints = maybeOnlyCaseSensitive(*this, subset);
260
261
    // Iterate over the ranges of single code points. Nested loop for each code point.
262
463k
    int32_t n = codePoints.getRangeCount();
263
264
8.62M
    for (int32_t i=0; i<n; ++i) {
265
8.16M
        UChar32 start = codePoints.getRangeStart(i);
266
8.16M
        UChar32 end   = codePoints.getRangeEnd(i);
267
268
8.16M
        if (simple) {
269
0
            for (UChar32 cp=start; cp<=end; ++cp) {
270
0
                ucase_addSimpleCaseClosure(cp, &sa);
271
0
            }
272
8.16M
        } else {
273
158M
            for (UChar32 cp=start; cp<=end; ++cp) {
274
149M
                ucase_addCaseClosure(cp, &sa);
275
149M
            }
276
8.16M
        }
277
8.16M
    }
278
463k
    if (hasStrings()) {
279
15.7k
        UnicodeString str;
280
699k
        for (int32_t j=0; j<strings_->size(); ++j) {
281
683k
            const UnicodeString* pStr = static_cast<const UnicodeString*>(strings_->elementAt(j));
282
683k
            if (simple) {
283
0
                if (scfString(*pStr, str)) {
284
0
                    foldSet.remove(*pStr).add(str);
285
0
                }
286
683k
            } else {
287
683k
                str = *pStr;
288
683k
                str.foldCase();
289
683k
                if(!ucase_addStringCaseClosure(str.getBuffer(), str.length(), &sa)) {
290
18.4k
                    foldSet.add(str); // does not map to code points: add the folded string itself
291
18.4k
                }
292
683k
            }
293
683k
        }
294
15.7k
    }
295
463k
    *this = foldSet;
296
463k
}
297
298
0
void UnicodeSet::closeOverAddCaseMappings() {
299
    // Start with input set to guarantee inclusion.
300
0
    UnicodeSet foldSet(*this);
301
302
0
    UnicodeSet subset(0, 0x10ffff);
303
0
    const UnicodeSet &codePoints = maybeOnlyCaseSensitive(*this, subset);
304
305
    // Iterate over the ranges of single code points. Nested loop for each code point.
306
0
    int32_t n = codePoints.getRangeCount();
307
0
    UChar32 result;
308
0
    const char16_t *full;
309
0
    UnicodeString str;
310
311
0
    for (int32_t i=0; i<n; ++i) {
312
0
        UChar32 start = codePoints.getRangeStart(i);
313
0
        UChar32 end   = codePoints.getRangeEnd(i);
314
315
        // add case mappings
316
        // (does not add long s for regular s, or Kelvin for k, for example)
317
0
        for (UChar32 cp=start; cp<=end; ++cp) {
318
0
            result = ucase_toFullLower(cp, nullptr, nullptr, &full, UCASE_LOC_ROOT);
319
0
            addCaseMapping(foldSet, result, full, str);
320
321
0
            result = ucase_toFullTitle(cp, nullptr, nullptr, &full, UCASE_LOC_ROOT);
322
0
            addCaseMapping(foldSet, result, full, str);
323
324
0
            result = ucase_toFullUpper(cp, nullptr, nullptr, &full, UCASE_LOC_ROOT);
325
0
            addCaseMapping(foldSet, result, full, str);
326
327
0
            result = ucase_toFullFolding(cp, &full, 0);
328
0
            addCaseMapping(foldSet, result, full, str);
329
0
        }
330
0
    }
331
0
    if (hasStrings()) {
332
0
        Locale root("");
333
0
#if !UCONFIG_NO_BREAK_ITERATION
334
0
        UErrorCode status = U_ZERO_ERROR;
335
0
        BreakIterator *bi = BreakIterator::createWordInstance(root, status);
336
0
        if (U_SUCCESS(status)) {
337
0
#endif
338
0
            for (int32_t j=0; j<strings_->size(); ++j) {
339
0
                const UnicodeString* pStr = static_cast<const UnicodeString*>(strings_->elementAt(j));
340
0
                (str = *pStr).toLower(root);
341
0
                foldSet.add(str);
342
0
#if !UCONFIG_NO_BREAK_ITERATION
343
0
                (str = *pStr).toTitle(bi, root);
344
0
                foldSet.add(str);
345
0
#endif
346
0
                (str = *pStr).toUpper(root);
347
0
                foldSet.add(str);
348
0
                (str = *pStr).foldCase();
349
0
                foldSet.add(str);
350
0
            }
351
0
#if !UCONFIG_NO_BREAK_ITERATION
352
0
        }
353
0
        delete bi;
354
0
#endif
355
0
    }
356
0
    *this = foldSet;
357
0
}
358
359
U_NAMESPACE_END