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/bytestriebuilder.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
*   Copyright (C) 2010-2012, International Business Machines
6
*   Corporation and others.  All Rights Reserved.
7
*******************************************************************************
8
*   file name:  bytestriebuilder.cpp
9
*   encoding:   UTF-8
10
*   tab size:   8 (not used)
11
*   indentation:4
12
*
13
*   created on: 2010sep25
14
*   created by: Markus W. Scherer
15
*/
16
17
#include "unicode/utypes.h"
18
#include "unicode/bytestrie.h"
19
#include "unicode/bytestriebuilder.h"
20
#include "unicode/stringpiece.h"
21
#include "charstr.h"
22
#include "cmemory.h"
23
#include "uhash.h"
24
#include "uarrsort.h"
25
#include "uassert.h"
26
#include "ustr_imp.h"
27
28
U_NAMESPACE_BEGIN
29
30
/*
31
 * Note: This builder implementation stores (bytes, value) pairs with full copies
32
 * of the byte sequences, until the BytesTrie is built.
33
 * It might(!) take less memory if we collected the data in a temporary, dynamic trie.
34
 */
35
36
class BytesTrieElement : public UMemory {
37
public:
38
    // Use compiler's default constructor, initializes nothing.
39
40
    void setTo(StringPiece s, int32_t val, CharString &strings, UErrorCode &errorCode);
41
42
0
    StringPiece getString(const CharString& strings U_LIFETIME_BOUND) const {
43
0
        int32_t offset=stringOffset;
44
0
        int32_t length;
45
0
        if(offset>=0) {
46
0
            length = static_cast<uint8_t>(strings[offset++]);
47
0
        } else {
48
0
            offset=~offset;
49
0
            length = (static_cast<int32_t>(static_cast<uint8_t>(strings[offset])) << 8) | static_cast<uint8_t>(strings[offset + 1]);
50
0
            offset+=2;
51
0
        }
52
0
        return StringPiece(strings.data()+offset, length);
53
0
    }
54
0
    int32_t getStringLength(const CharString &strings) const {
55
0
        int32_t offset=stringOffset;
56
0
        if(offset>=0) {
57
0
            return static_cast<uint8_t>(strings[offset]);
58
0
        } else {
59
0
            offset=~offset;
60
0
            return (static_cast<int32_t>(static_cast<uint8_t>(strings[offset])) << 8) | static_cast<uint8_t>(strings[offset + 1]);
61
0
        }
62
0
    }
63
64
0
    char charAt(int32_t index, const CharString &strings) const { return data(strings)[index]; }
65
66
0
    int32_t getValue() const { return value; }
67
68
    int32_t compareStringTo(const BytesTrieElement &o, const CharString &strings) const;
69
70
private:
71
0
    const char* data(const CharString& strings U_LIFETIME_BOUND) const {
72
0
        int32_t offset=stringOffset;
73
0
        if(offset>=0) {
74
0
            ++offset;
75
0
        } else {
76
0
            offset=~offset+2;
77
0
        }
78
0
        return strings.data()+offset;
79
0
    }
80
81
    // If the stringOffset is non-negative, then the first strings byte contains
82
    // the string length.
83
    // If the stringOffset is negative, then the first two strings bytes contain
84
    // the string length (big-endian), and the offset needs to be bit-inverted.
85
    // (Compared with a stringLength field here, this saves 3 bytes per string for most strings.)
86
    int32_t stringOffset;
87
    int32_t value;
88
};
89
90
void
91
BytesTrieElement::setTo(StringPiece s, int32_t val,
92
0
                        CharString &strings, UErrorCode &errorCode) {
93
0
    if(U_FAILURE(errorCode)) {
94
0
        return;
95
0
    }
96
0
    int32_t length=s.length();
97
0
    if(length>0xffff) {
98
        // Too long: We store the length in 1 or 2 bytes.
99
0
        errorCode=U_INDEX_OUTOFBOUNDS_ERROR;
100
0
        return;
101
0
    }
102
0
    int32_t offset=strings.length();
103
0
    if(length>0xff) {
104
0
        offset=~offset;
105
0
        strings.append(static_cast<char>(length >> 8), errorCode);
106
0
    }
107
0
    strings.append(static_cast<char>(length), errorCode);
108
0
    stringOffset=offset;
109
0
    value=val;
110
0
    strings.append(s, errorCode);
111
0
}
112
113
int32_t
114
0
BytesTrieElement::compareStringTo(const BytesTrieElement &other, const CharString &strings) const {
115
    // TODO: add StringPiece::compare(), see ticket #8187
116
0
    StringPiece thisString=getString(strings);
117
0
    StringPiece otherString=other.getString(strings);
118
0
    int32_t lengthDiff=thisString.length()-otherString.length();
119
0
    int32_t commonLength;
120
0
    if(lengthDiff<=0) {
121
0
        commonLength=thisString.length();
122
0
    } else {
123
0
        commonLength=otherString.length();
124
0
    }
125
0
    int32_t diff=uprv_memcmp(thisString.data(), otherString.data(), commonLength);
126
0
    return diff!=0 ? diff : lengthDiff;
127
0
}
128
129
BytesTrieBuilder::BytesTrieBuilder(UErrorCode &errorCode)
130
0
        : strings(nullptr), elements(nullptr), elementsCapacity(0), elementsLength(0),
131
0
          bytes(nullptr), bytesCapacity(0), bytesLength(0) {
132
0
    if(U_FAILURE(errorCode)) {
133
0
        return;
134
0
    }
135
0
    strings=new CharString();
136
0
    if(strings==nullptr) {
137
0
        errorCode=U_MEMORY_ALLOCATION_ERROR;
138
0
    }
139
0
}
140
141
0
BytesTrieBuilder::~BytesTrieBuilder() {
142
0
    delete strings;
143
0
    delete[] elements;
144
0
    uprv_free(bytes);
145
0
}
146
147
BytesTrieBuilder&
148
0
BytesTrieBuilder::add(StringPiece s, int32_t value, UErrorCode& errorCode) U_LIFETIME_BOUND {
149
0
    if(U_FAILURE(errorCode)) {
150
0
        return *this;
151
0
    }
152
0
    if(bytesLength>0) {
153
        // Cannot add elements after building.
154
0
        errorCode=U_NO_WRITE_PERMISSION;
155
0
        return *this;
156
0
    }
157
0
    if(elementsLength==elementsCapacity) {
158
0
        int32_t newCapacity;
159
0
        if(elementsCapacity==0) {
160
0
            newCapacity=1024;
161
0
        } else {
162
0
            newCapacity=4*elementsCapacity;
163
0
        }
164
0
        BytesTrieElement *newElements=new BytesTrieElement[newCapacity];
165
0
        if(newElements==nullptr) {
166
0
            errorCode=U_MEMORY_ALLOCATION_ERROR;
167
0
            return *this; // error instead of dereferencing null
168
0
        }
169
0
        if(elementsLength>0) {
170
0
            uprv_memcpy(newElements, elements, (size_t)elementsLength*sizeof(BytesTrieElement));
171
0
        }
172
0
        delete[] elements;
173
0
        elements=newElements;
174
0
        elementsCapacity=newCapacity;
175
0
    }
176
0
    elements[elementsLength++].setTo(s, value, *strings, errorCode);
177
0
    return *this;
178
0
}
179
180
U_CDECL_BEGIN
181
182
static int32_t U_CALLCONV
183
0
compareElementStrings(const void *context, const void *left, const void *right) {
184
0
    const CharString *strings=static_cast<const CharString *>(context);
185
0
    const BytesTrieElement *leftElement=static_cast<const BytesTrieElement *>(left);
186
0
    const BytesTrieElement *rightElement=static_cast<const BytesTrieElement *>(right);
187
0
    return leftElement->compareStringTo(*rightElement, *strings);
188
0
}
189
190
U_CDECL_END
191
192
BytesTrie *
193
0
BytesTrieBuilder::build(UStringTrieBuildOption buildOption, UErrorCode &errorCode) {
194
0
    buildBytes(buildOption, errorCode);
195
0
    BytesTrie *newTrie=nullptr;
196
0
    if(U_SUCCESS(errorCode)) {
197
0
        newTrie=new BytesTrie(bytes, bytes+(bytesCapacity-bytesLength));
198
0
        if(newTrie==nullptr) {
199
0
            errorCode=U_MEMORY_ALLOCATION_ERROR;
200
0
        } else {
201
0
            bytes=nullptr;  // The new trie now owns the array.
202
0
            bytesCapacity=0;
203
0
        }
204
0
    }
205
0
    return newTrie;
206
0
}
207
208
StringPiece
209
BytesTrieBuilder::buildStringPiece(UStringTrieBuildOption buildOption,
210
0
                                   UErrorCode& errorCode) U_LIFETIME_BOUND {
211
0
    buildBytes(buildOption, errorCode);
212
0
    StringPiece result;
213
0
    if(U_SUCCESS(errorCode)) {
214
0
        result.set(bytes+(bytesCapacity-bytesLength), bytesLength);
215
0
    }
216
0
    return result;
217
0
}
218
219
void
220
0
BytesTrieBuilder::buildBytes(UStringTrieBuildOption buildOption, UErrorCode &errorCode) {
221
0
    if(U_FAILURE(errorCode)) {
222
0
        return;
223
0
    }
224
0
    if(bytes!=nullptr && bytesLength>0) {
225
        // Already built.
226
0
        return;
227
0
    }
228
0
    if(bytesLength==0) {
229
0
        if(elementsLength==0) {
230
0
            errorCode=U_INDEX_OUTOFBOUNDS_ERROR;
231
0
            return;
232
0
        }
233
0
        uprv_sortArray(elements, elementsLength, static_cast<int32_t>(sizeof(BytesTrieElement)),
234
0
                      compareElementStrings, strings,
235
0
                      false,  // need not be a stable sort
236
0
                      &errorCode);
237
0
        if(U_FAILURE(errorCode)) {
238
0
            return;
239
0
        }
240
        // Duplicate strings are not allowed.
241
0
        StringPiece prev=elements[0].getString(*strings);
242
0
        for(int32_t i=1; i<elementsLength; ++i) {
243
0
            StringPiece current=elements[i].getString(*strings);
244
0
            if(prev==current) {
245
0
                errorCode=U_ILLEGAL_ARGUMENT_ERROR;
246
0
                return;
247
0
            }
248
0
            prev=current;
249
0
        }
250
0
    }
251
    // Create and byte-serialize the trie for the elements.
252
0
    bytesLength=0;
253
0
    int32_t capacity=strings->length();
254
0
    if(capacity<1024) {
255
0
        capacity=1024;
256
0
    }
257
0
    if(bytesCapacity<capacity) {
258
0
        uprv_free(bytes);
259
0
        bytes=static_cast<char *>(uprv_malloc(capacity));
260
0
        if(bytes==nullptr) {
261
0
            errorCode=U_MEMORY_ALLOCATION_ERROR;
262
0
            bytesCapacity=0;
263
0
            return;
264
0
        }
265
0
        bytesCapacity=capacity;
266
0
    }
267
0
    StringTrieBuilder::build(buildOption, elementsLength, errorCode);
268
0
    if(bytes==nullptr) {
269
0
        errorCode=U_MEMORY_ALLOCATION_ERROR;
270
0
    }
271
0
}
272
273
BytesTrieBuilder&
274
0
BytesTrieBuilder::clear() U_LIFETIME_BOUND {
275
0
    strings->clear();
276
0
    elementsLength=0;
277
0
    bytesLength=0;
278
0
    return *this;
279
0
}
280
281
int32_t
282
0
BytesTrieBuilder::getElementStringLength(int32_t i) const {
283
0
    return elements[i].getStringLength(*strings);
284
0
}
285
286
char16_t
287
0
BytesTrieBuilder::getElementUnit(int32_t i, int32_t byteIndex) const {
288
0
    return static_cast<uint8_t>(elements[i].charAt(byteIndex, *strings));
289
0
}
290
291
int32_t
292
0
BytesTrieBuilder::getElementValue(int32_t i) const {
293
0
    return elements[i].getValue();
294
0
}
295
296
int32_t
297
0
BytesTrieBuilder::getLimitOfLinearMatch(int32_t first, int32_t last, int32_t byteIndex) const {
298
0
    const BytesTrieElement &firstElement=elements[first];
299
0
    const BytesTrieElement &lastElement=elements[last];
300
0
    int32_t minStringLength=firstElement.getStringLength(*strings);
301
0
    while(++byteIndex<minStringLength &&
302
0
            firstElement.charAt(byteIndex, *strings)==
303
0
            lastElement.charAt(byteIndex, *strings)) {}
304
0
    return byteIndex;
305
0
}
306
307
int32_t
308
0
BytesTrieBuilder::countElementUnits(int32_t start, int32_t limit, int32_t byteIndex) const {
309
0
    int32_t length=0;  // Number of different bytes at byteIndex.
310
0
    int32_t i=start;
311
0
    do {
312
0
        char byte=elements[i++].charAt(byteIndex, *strings);
313
0
        while(i<limit && byte==elements[i].charAt(byteIndex, *strings)) {
314
0
            ++i;
315
0
        }
316
0
        ++length;
317
0
    } while(i<limit);
318
0
    return length;
319
0
}
320
321
int32_t
322
0
BytesTrieBuilder::skipElementsBySomeUnits(int32_t i, int32_t byteIndex, int32_t count) const {
323
0
    do {
324
0
        char byte=elements[i++].charAt(byteIndex, *strings);
325
0
        while(byte==elements[i].charAt(byteIndex, *strings)) {
326
0
            ++i;
327
0
        }
328
0
    } while(--count>0);
329
0
    return i;
330
0
}
331
332
int32_t
333
0
BytesTrieBuilder::indexOfElementWithNextUnit(int32_t i, int32_t byteIndex, char16_t byte) const {
334
0
    char b = static_cast<char>(byte);
335
0
    while(b==elements[i].charAt(byteIndex, *strings)) {
336
0
        ++i;
337
0
    }
338
0
    return i;
339
0
}
340
341
BytesTrieBuilder::BTLinearMatchNode::BTLinearMatchNode(const char *bytes, int32_t len, Node *nextNode)
342
0
        : LinearMatchNode(len, nextNode), s(bytes) {
343
0
    hash=static_cast<int32_t>(
344
0
        static_cast<uint32_t>(hash)*37u + static_cast<uint32_t>(ustr_hashCharsN(bytes, len)));
345
0
}
346
347
bool
348
0
BytesTrieBuilder::BTLinearMatchNode::operator==(const Node &other) const {
349
0
    if(this==&other) {
350
0
        return true;
351
0
    }
352
0
    if(!LinearMatchNode::operator==(other)) {
353
0
        return false;
354
0
    }
355
0
    const BTLinearMatchNode &o=static_cast<const BTLinearMatchNode &>(other);
356
0
    return 0==uprv_memcmp(s, o.s, length);
357
0
}
358
359
void
360
0
BytesTrieBuilder::BTLinearMatchNode::write(StringTrieBuilder &builder) {
361
0
    BytesTrieBuilder &b=static_cast<BytesTrieBuilder &>(builder);
362
0
    next->write(builder);
363
0
    b.write(s, length);
364
0
    offset=b.write(b.getMinLinearMatch()+length-1);
365
0
}
366
367
StringTrieBuilder::Node *
368
BytesTrieBuilder::createLinearMatchNode(int32_t i, int32_t byteIndex, int32_t length,
369
0
                                        Node *nextNode) const {
370
0
    return new BTLinearMatchNode(
371
0
            elements[i].getString(*strings).data()+byteIndex,
372
0
            length,
373
0
            nextNode);
374
0
}
375
376
UBool
377
0
BytesTrieBuilder::ensureCapacity(int32_t length) {
378
0
    if(bytes==nullptr) {
379
0
        return false;  // previous memory allocation had failed
380
0
    }
381
0
    if(length>bytesCapacity) {
382
0
        int32_t newCapacity=bytesCapacity;
383
0
        do {
384
0
            newCapacity*=2;
385
0
        } while(newCapacity<=length);
386
0
        char *newBytes=static_cast<char *>(uprv_malloc(newCapacity));
387
0
        if(newBytes==nullptr) {
388
            // unable to allocate memory
389
0
            uprv_free(bytes);
390
0
            bytes=nullptr;
391
0
            bytesCapacity=0;
392
0
            return false;
393
0
        }
394
0
        uprv_memcpy(newBytes+(newCapacity-bytesLength),
395
0
                    bytes+(bytesCapacity-bytesLength), bytesLength);
396
0
        uprv_free(bytes);
397
0
        bytes=newBytes;
398
0
        bytesCapacity=newCapacity;
399
0
    }
400
0
    return true;
401
0
}
402
403
int32_t
404
0
BytesTrieBuilder::write(int32_t byte) {
405
0
    int32_t newLength=bytesLength+1;
406
0
    if(ensureCapacity(newLength)) {
407
0
        bytesLength=newLength;
408
0
        bytes[bytesCapacity - bytesLength] = static_cast<char>(byte);
409
0
    }
410
0
    return bytesLength;
411
0
}
412
413
int32_t
414
0
BytesTrieBuilder::write(const char *b, int32_t length) {
415
0
    int32_t newLength=bytesLength+length;
416
0
    if(ensureCapacity(newLength)) {
417
0
        bytesLength=newLength;
418
0
        uprv_memcpy(bytes+(bytesCapacity-bytesLength), b, length);
419
0
    }
420
0
    return bytesLength;
421
0
}
422
423
int32_t
424
0
BytesTrieBuilder::writeElementUnits(int32_t i, int32_t byteIndex, int32_t length) {
425
0
    return write(elements[i].getString(*strings).data()+byteIndex, length);
426
0
}
427
428
int32_t
429
0
BytesTrieBuilder::writeValueAndFinal(int32_t i, UBool isFinal) {
430
0
    if(0<=i && i<=BytesTrie::kMaxOneByteValue) {
431
0
        return write(((BytesTrie::kMinOneByteValueLead+i)<<1)|isFinal);
432
0
    }
433
0
    char intBytes[5];
434
0
    int32_t length=1;
435
0
    if(i<0 || i>0xffffff) {
436
0
        intBytes[0] = static_cast<char>(BytesTrie::kFiveByteValueLead);
437
0
        intBytes[1] = static_cast<char>(static_cast<uint32_t>(i) >> 24);
438
0
        intBytes[2] = static_cast<char>(static_cast<uint32_t>(i) >> 16);
439
0
        intBytes[3] = static_cast<char>(static_cast<uint32_t>(i) >> 8);
440
0
        intBytes[4] = static_cast<char>(i);
441
0
        length=5;
442
    // } else if(i<=BytesTrie::kMaxOneByteValue) {
443
    //     intBytes[0]=(char)(BytesTrie::kMinOneByteValueLead+i);
444
0
    } else {
445
0
        if(i<=BytesTrie::kMaxTwoByteValue) {
446
0
            intBytes[0] = static_cast<char>(BytesTrie::kMinTwoByteValueLead + (i >> 8));
447
0
        } else {
448
0
            if(i<=BytesTrie::kMaxThreeByteValue) {
449
0
                intBytes[0] = static_cast<char>(BytesTrie::kMinThreeByteValueLead + (i >> 16));
450
0
            } else {
451
0
                intBytes[0] = static_cast<char>(BytesTrie::kFourByteValueLead);
452
0
                intBytes[1] = static_cast<char>(i >> 16);
453
0
                length=2;
454
0
            }
455
0
            intBytes[length++] = static_cast<char>(i >> 8);
456
0
        }
457
0
        intBytes[length++] = static_cast<char>(i);
458
0
    }
459
0
    intBytes[0] = static_cast<char>((intBytes[0] << 1) | isFinal);
460
0
    return write(intBytes, length);
461
0
}
462
463
int32_t
464
0
BytesTrieBuilder::writeValueAndType(UBool hasValue, int32_t value, int32_t node) {
465
0
    int32_t offset=write(node);
466
0
    if(hasValue) {
467
0
        offset=writeValueAndFinal(value, false);
468
0
    }
469
0
    return offset;
470
0
}
471
472
int32_t
473
0
BytesTrieBuilder::writeDeltaTo(int32_t jumpTarget) {
474
0
    int32_t i=bytesLength-jumpTarget;
475
0
    U_ASSERT(i>=0);
476
0
    if(i<=BytesTrie::kMaxOneByteDelta) {
477
0
        return write(i);
478
0
    } else {
479
0
        char intBytes[5];
480
0
        return write(intBytes, internalEncodeDelta(i, intBytes));
481
0
    }
482
0
}
483
484
int32_t
485
0
BytesTrieBuilder::internalEncodeDelta(int32_t i, char intBytes[]) {
486
0
    U_ASSERT(i>=0);
487
0
    if(i<=BytesTrie::kMaxOneByteDelta) {
488
0
        intBytes[0] = static_cast<char>(i);
489
0
        return 1;
490
0
    }
491
0
    int32_t length=1;
492
0
    if(i<=BytesTrie::kMaxTwoByteDelta) {
493
0
        intBytes[0] = static_cast<char>(BytesTrie::kMinTwoByteDeltaLead + (i >> 8));
494
0
    } else {
495
0
        if(i<=BytesTrie::kMaxThreeByteDelta) {
496
0
            intBytes[0] = static_cast<char>(BytesTrie::kMinThreeByteDeltaLead + (i >> 16));
497
0
        } else {
498
0
            if(i<=0xffffff) {
499
0
                intBytes[0] = static_cast<char>(BytesTrie::kFourByteDeltaLead);
500
0
            } else {
501
0
                intBytes[0] = static_cast<char>(BytesTrie::kFiveByteDeltaLead);
502
0
                intBytes[1] = static_cast<char>(i >> 24);
503
0
                length=2;
504
0
            }
505
0
            intBytes[length++] = static_cast<char>(i >> 16);
506
0
        }
507
0
        intBytes[length++] = static_cast<char>(i >> 8);
508
0
    }
509
0
    intBytes[length++] = static_cast<char>(i);
510
0
    return length;
511
0
}
512
513
U_NAMESPACE_END