Coverage Report

Created: 2025-06-13 06:38

/src/icu/icu4c/source/common/utext.cpp
Line
Count
Source (jump to first uncovered line)
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) 2005-2016, International Business Machines
7
*   Corporation and others.  All Rights Reserved.
8
*
9
*******************************************************************************
10
*   file name:  utext.cpp
11
*   encoding:   UTF-8
12
*   tab size:   8 (not used)
13
*   indentation:4
14
*
15
*   created on: 2005apr12
16
*   created by: Markus W. Scherer
17
*/
18
19
#include <cstddef>
20
21
#include "unicode/utypes.h"
22
#include "unicode/ustring.h"
23
#include "unicode/unistr.h"
24
#include "unicode/chariter.h"
25
#include "unicode/utext.h"
26
#include "unicode/utf.h"
27
#include "unicode/utf8.h"
28
#include "unicode/utf16.h"
29
#include "ustr_imp.h"
30
#include "cmemory.h"
31
#include "cstring.h"
32
#include "uassert.h"
33
#include "putilimp.h"
34
35
U_NAMESPACE_USE
36
37
14.4M
#define I32_FLAG(bitIndex) ((int32_t)1<<(bitIndex))
38
39
40
static UBool
41
4.10k
utext_access(UText *ut, int64_t index, UBool forward) {
42
4.10k
    return ut->pFuncs->access(ut, index, forward);
43
4.10k
}
44
45
46
47
U_CAPI UBool U_EXPORT2
48
180k
utext_moveIndex32(UText *ut, int32_t delta) {
49
180k
    UChar32  c;
50
180k
    if (delta > 0) {
51
721k
        do {
52
721k
            if(ut->chunkOffset>=ut->chunkLength && !utext_access(ut, ut->chunkNativeLimit, true)) {
53
796
                return false;
54
796
            }
55
720k
            c = ut->chunkContents[ut->chunkOffset];
56
720k
            if (U16_IS_SURROGATE(c)) {
57
16.2k
                c = utext_next32(ut);
58
16.2k
                if (c == U_SENTINEL) {
59
0
                    return false;
60
0
                }
61
704k
            } else {
62
704k
                ut->chunkOffset++;
63
704k
            }
64
720k
        } while(--delta>0);
65
66
180k
    } else if (delta<0) {
67
0
        do {
68
0
            if(ut->chunkOffset<=0 && !utext_access(ut, ut->chunkNativeStart, false)) {
69
0
                return false;
70
0
            }
71
0
            c = ut->chunkContents[ut->chunkOffset-1];
72
0
            if (U16_IS_SURROGATE(c)) {
73
0
                c = utext_previous32(ut);
74
0
                if (c == U_SENTINEL) {
75
0
                    return false;
76
0
                }
77
0
            } else {
78
0
                ut->chunkOffset--;
79
0
            }
80
0
        } while(++delta<0);
81
0
    }
82
83
179k
    return true;
84
180k
}
85
86
87
U_CAPI int64_t U_EXPORT2
88
209k
utext_nativeLength(UText *ut) {
89
209k
    return ut->pFuncs->nativeLength(ut);
90
209k
}
91
92
93
U_CAPI UBool U_EXPORT2
94
0
utext_isLengthExpensive(const UText *ut) {
95
0
    UBool r = (ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE)) != 0;
96
0
    return r;
97
0
}
98
99
100
U_CAPI int64_t U_EXPORT2
101
1.83G
utext_getNativeIndex(const UText *ut) {
102
1.83G
    if(ut->chunkOffset <= ut->nativeIndexingLimit) {
103
1.75G
        return ut->chunkNativeStart+ut->chunkOffset;
104
1.75G
    } else {
105
80.3M
        return ut->pFuncs->mapOffsetToNative(ut);
106
80.3M
    }
107
1.83G
}
108
109
110
U_CAPI void U_EXPORT2
111
964M
utext_setNativeIndex(UText *ut, int64_t index) {
112
964M
    if(index<ut->chunkNativeStart || index>=ut->chunkNativeLimit) {
113
        // The desired position is outside of the current chunk.
114
        // Access the new position.  Assume a forward iteration from here,
115
        // which will also be optimimum for a single random access.
116
        // Reverse iterations may suffer slightly.
117
722k
        ut->pFuncs->access(ut, index, true);
118
964M
    } else if((int32_t)(index - ut->chunkNativeStart) <= ut->nativeIndexingLimit) {
119
        // utf-16 indexing.
120
936M
        ut->chunkOffset=(int32_t)(index-ut->chunkNativeStart);
121
936M
    } else {
122
27.6M
         ut->chunkOffset=ut->pFuncs->mapNativeIndexToUTF16(ut, index);
123
27.6M
    }
124
    // The convention is that the index must always be on a code point boundary.
125
    // Adjust the index position if it is in the middle of a surrogate pair.
126
964M
    if (ut->chunkOffset<ut->chunkLength) {
127
964M
        char16_t c= ut->chunkContents[ut->chunkOffset];
128
964M
        if (U16_IS_TRAIL(c)) {
129
27.7M
            if (ut->chunkOffset==0) {
130
1.32k
                ut->pFuncs->access(ut, ut->chunkNativeStart, false);
131
1.32k
            }
132
27.7M
            if (ut->chunkOffset>0) {
133
27.7M
                char16_t lead = ut->chunkContents[ut->chunkOffset-1];
134
27.7M
                if (U16_IS_LEAD(lead)) {
135
11.5k
                    ut->chunkOffset--;
136
11.5k
                }
137
27.7M
            }
138
27.7M
        }
139
964M
    }
140
964M
}
141
142
143
144
U_CAPI int64_t U_EXPORT2
145
5.94M
utext_getPreviousNativeIndex(UText *ut) {
146
    //
147
    //  Fast-path the common case.
148
    //     Common means current position is not at the beginning of a chunk
149
    //     and the preceding character is not supplementary.
150
    //
151
5.94M
    int32_t i = ut->chunkOffset - 1;
152
5.94M
    int64_t result;
153
5.94M
    if (i >= 0) {
154
5.94M
        char16_t c = ut->chunkContents[i];
155
5.94M
        if (U16_IS_TRAIL(c) == false) {
156
5.58M
            if (i <= ut->nativeIndexingLimit) {
157
5.58M
                result = ut->chunkNativeStart + i;
158
5.58M
            } else {
159
0
                ut->chunkOffset = i;
160
0
                result = ut->pFuncs->mapOffsetToNative(ut);
161
0
                ut->chunkOffset++;
162
0
            }
163
5.58M
            return result;
164
5.58M
        }
165
5.94M
    }
166
167
    // If at the start of text, simply return 0.
168
358k
    if (ut->chunkOffset==0 && ut->chunkNativeStart==0) {
169
0
        return 0;
170
0
    }
171
172
    // Harder, less common cases.  We are at a chunk boundary, or on a surrogate.
173
    //    Keep it simple, use other functions to handle the edges.
174
    //
175
358k
    utext_previous32(ut);
176
358k
    result = UTEXT_GETNATIVEINDEX(ut);
177
358k
    utext_next32(ut);
178
358k
    return result;
179
358k
}
180
181
182
//
183
//  utext_current32.  Get the UChar32 at the current position.
184
//                    UText iteration position is always on a code point boundary,
185
//                    never on the trail half of a surrogate pair.
186
//
187
U_CAPI UChar32 U_EXPORT2
188
210M
utext_current32(UText *ut) {
189
210M
    UChar32  c;
190
210M
    if (ut->chunkOffset==ut->chunkLength) {
191
        // Current position is just off the end of the chunk.
192
816k
        if (ut->pFuncs->access(ut, ut->chunkNativeLimit, true) == false) {
193
            // Off the end of the text.
194
93.7k
            return U_SENTINEL;
195
93.7k
        }
196
816k
    }
197
198
210M
    c = ut->chunkContents[ut->chunkOffset];
199
210M
    if (U16_IS_LEAD(c) == false) {
200
        // Normal, non-supplementary case.
201
205M
        return c;
202
205M
    }
203
204
    //
205
    //  Possible supplementary char.
206
    //
207
4.73M
    UChar32   trail = 0;
208
4.73M
    UChar32   supplementaryC = c;
209
4.73M
    if ((ut->chunkOffset+1) < ut->chunkLength) {
210
        // The trail surrogate is in the same chunk.
211
4.73M
        trail = ut->chunkContents[ut->chunkOffset+1];
212
4.73M
    } else {
213
        //  The trail surrogate is in a different chunk.
214
        //     Because we must maintain the iteration position, we need to switch forward
215
        //     into the new chunk, get the trail surrogate, then revert the chunk back to the
216
        //     original one.
217
        //     An edge case to be careful of:  the entire text may end with an unpaired
218
        //        leading surrogate.  The attempt to access the trail will fail, but
219
        //        the original position before the unpaired lead still needs to be restored.
220
860
        int64_t  nativePosition = ut->chunkNativeLimit;
221
860
        if (ut->pFuncs->access(ut, nativePosition, true)) {
222
0
            trail = ut->chunkContents[ut->chunkOffset];
223
0
        }
224
860
        UBool r = ut->pFuncs->access(ut, nativePosition, false);  // reverse iteration flag loads preceding chunk
225
860
        U_ASSERT(r);
226
        // Here we need to restore chunkOffset since the access functions were called with
227
        // chunkNativeLimit but that is not where we were (we were 1 code unit before the
228
        // limit). Restoring was originally added in ICU-4669 but did not support access
229
        // functions that changed the chunk size, the following does.
230
860
        ut->chunkOffset = ut->chunkLength - 1;
231
860
        if(!r) {
232
0
            return U_SENTINEL;
233
0
        }
234
860
    }
235
236
4.73M
    if (U16_IS_TRAIL(trail)) {
237
4.36M
        supplementaryC = U16_GET_SUPPLEMENTARY(c, trail);
238
4.36M
    }
239
4.73M
    return supplementaryC;
240
241
4.73M
}
242
243
244
U_CAPI UChar32 U_EXPORT2
245
4.71M
utext_char32At(UText *ut, int64_t nativeIndex) {
246
4.71M
    UChar32 c = U_SENTINEL;
247
248
    // Fast path the common case.
249
4.71M
    if (nativeIndex>=ut->chunkNativeStart && nativeIndex < ut->chunkNativeStart + ut->nativeIndexingLimit) {
250
4.52M
        ut->chunkOffset = (int32_t)(nativeIndex - ut->chunkNativeStart);
251
4.52M
        c = ut->chunkContents[ut->chunkOffset];
252
4.52M
        if (U16_IS_SURROGATE(c) == false) {
253
4.27M
            return c;
254
4.27M
        }
255
4.52M
    }
256
257
258
437k
    utext_setNativeIndex(ut, nativeIndex);
259
437k
    if (nativeIndex>=ut->chunkNativeStart && ut->chunkOffset<ut->chunkLength) {
260
401k
        c = ut->chunkContents[ut->chunkOffset];
261
401k
        if (U16_IS_SURROGATE(c)) {
262
            // For surrogates, let current32() deal with the complications
263
            //    of supplementaries that may span chunk boundaries.
264
250k
            c = utext_current32(ut);
265
250k
        }
266
401k
    }
267
437k
    return c;
268
4.71M
}
269
270
271
U_CAPI UChar32 U_EXPORT2
272
1.13G
utext_next32(UText *ut) {
273
1.13G
    UChar32       c;
274
275
1.13G
    if (ut->chunkOffset >= ut->chunkLength) {
276
4.95M
        if (ut->pFuncs->access(ut, ut->chunkNativeLimit, true) == false) {
277
1.99M
            return U_SENTINEL;
278
1.99M
        }
279
4.95M
    }
280
281
1.13G
    c = ut->chunkContents[ut->chunkOffset++];
282
1.13G
    if (U16_IS_LEAD(c) == false) {
283
        // Normal case, not supplementary.
284
        //   (A trail surrogate seen here is just returned as is, as a surrogate value.
285
        //    It cannot be part of a pair.)
286
1.10G
        return c;
287
1.10G
    }
288
289
26.7M
    if (ut->chunkOffset >= ut->chunkLength) {
290
12.5k
        if (ut->pFuncs->access(ut, ut->chunkNativeLimit, true) == false) {
291
            // c is an unpaired lead surrogate at the end of the text.
292
            // return it as it is.
293
12.5k
            return c;
294
12.5k
        }
295
12.5k
    }
296
26.7M
    UChar32 trail = ut->chunkContents[ut->chunkOffset];
297
26.7M
    if (U16_IS_TRAIL(trail) == false) {
298
        // c was an unpaired lead surrogate, not at the end of the text.
299
        // return it as it is (unpaired).  Iteration position is on the
300
        // following character, possibly in the next chunk, where the
301
        //  trail surrogate would have been if it had existed.
302
5.03M
        return c;
303
5.03M
    }
304
305
21.7M
    UChar32 supplementary = U16_GET_SUPPLEMENTARY(c, trail);
306
21.7M
    ut->chunkOffset++;   // move iteration position over the trail surrogate.
307
21.7M
    return supplementary;
308
26.7M
    }
309
310
311
U_CAPI UChar32 U_EXPORT2
312
8.57M
utext_previous32(UText *ut) {
313
8.57M
    UChar32       c;
314
315
8.57M
    if (ut->chunkOffset <= 0) {
316
64.4k
        if (ut->pFuncs->access(ut, ut->chunkNativeStart, false) == false) {
317
63.4k
            return U_SENTINEL;
318
63.4k
        }
319
64.4k
    }
320
8.51M
    ut->chunkOffset--;
321
8.51M
    c = ut->chunkContents[ut->chunkOffset];
322
8.51M
    if (U16_IS_TRAIL(c) == false) {
323
        // Normal case, not supplementary.
324
        //   (A lead surrogate seen here is just returned as is, as a surrogate value.
325
        //    It cannot be part of a pair.)
326
7.41M
        return c;
327
7.41M
    }
328
329
1.09M
    if (ut->chunkOffset <= 0) {
330
325
        if (ut->pFuncs->access(ut, ut->chunkNativeStart, false) == false) {
331
            // c is an unpaired trail surrogate at the start of the text.
332
            // return it as it is.
333
325
            return c;
334
325
        }
335
325
    }
336
337
1.09M
    UChar32 lead = ut->chunkContents[ut->chunkOffset-1];
338
1.09M
    if (U16_IS_LEAD(lead) == false) {
339
        // c was an unpaired trail surrogate, not at the end of the text.
340
        // return it as it is (unpaired).  Iteration position is at c
341
1.01M
        return c;
342
1.01M
    }
343
344
77.3k
    UChar32 supplementary = U16_GET_SUPPLEMENTARY(lead, c);
345
77.3k
    ut->chunkOffset--;   // move iteration position over the lead surrogate.
346
77.3k
    return supplementary;
347
1.09M
}
348
349
350
351
U_CAPI UChar32 U_EXPORT2
352
0
utext_next32From(UText *ut, int64_t index) {
353
0
    UChar32       c      = U_SENTINEL;
354
355
0
    if(index<ut->chunkNativeStart || index>=ut->chunkNativeLimit) {
356
        // Desired position is outside of the current chunk.
357
0
        if(!ut->pFuncs->access(ut, index, true)) {
358
            // no chunk available here
359
0
            return U_SENTINEL;
360
0
        }
361
0
    } else if (index - ut->chunkNativeStart  <= (int64_t)ut->nativeIndexingLimit) {
362
        // Desired position is in chunk, with direct 1:1 native to UTF16 indexing
363
0
        ut->chunkOffset = (int32_t)(index - ut->chunkNativeStart);
364
0
    } else {
365
        // Desired position is in chunk, with non-UTF16 indexing.
366
0
        ut->chunkOffset = ut->pFuncs->mapNativeIndexToUTF16(ut, index);
367
0
    }
368
369
0
    c = ut->chunkContents[ut->chunkOffset++];
370
0
    if (U16_IS_SURROGATE(c)) {
371
        // Surrogates.  Many edge cases.  Use other functions that already
372
        //              deal with the problems.
373
0
        utext_setNativeIndex(ut, index);
374
0
        c = utext_next32(ut);
375
0
    }
376
0
    return c;
377
0
}
378
379
380
U_CAPI UChar32 U_EXPORT2
381
0
utext_previous32From(UText *ut, int64_t index) {
382
    //
383
    //  Return the character preceding the specified index.
384
    //  Leave the iteration position at the start of the character that was returned.
385
    //
386
0
    UChar32     cPrev;    // The character preceding cCurr, which is what we will return.
387
388
    // Address the chunk containing the position preceding the incoming index
389
    // A tricky edge case:
390
    //   We try to test the requested native index against the chunkNativeStart to determine
391
    //    whether the character preceding the one at the index is in the current chunk.
392
    //    BUT, this test can fail with UTF-8 (or any other multibyte encoding), when the
393
    //    requested index is on something other than the first position of the first char.
394
    //
395
0
    if(index<=ut->chunkNativeStart || index>ut->chunkNativeLimit) {
396
        // Requested native index is outside of the current chunk.
397
0
        if(!ut->pFuncs->access(ut, index, false)) {
398
            // no chunk available here
399
0
            return U_SENTINEL;
400
0
        }
401
0
    } else if(index - ut->chunkNativeStart <= (int64_t)ut->nativeIndexingLimit) {
402
        // Direct UTF-16 indexing.
403
0
        ut->chunkOffset = (int32_t)(index - ut->chunkNativeStart);
404
0
    } else {
405
0
        ut->chunkOffset=ut->pFuncs->mapNativeIndexToUTF16(ut, index);
406
0
        if (ut->chunkOffset==0 && !ut->pFuncs->access(ut, index, false)) {
407
            // no chunk available here
408
0
            return U_SENTINEL;
409
0
        }
410
0
    }
411
412
    //
413
    // Simple case with no surrogates.
414
    //
415
0
    ut->chunkOffset--;
416
0
    cPrev = ut->chunkContents[ut->chunkOffset];
417
418
0
    if (U16_IS_SURROGATE(cPrev)) {
419
        // Possible supplementary.  Many edge cases.
420
        // Let other functions do the heavy lifting.
421
0
        utext_setNativeIndex(ut, index);
422
0
        cPrev = utext_previous32(ut);
423
0
    }
424
0
    return cPrev;
425
0
}
426
427
428
U_CAPI int32_t U_EXPORT2
429
utext_extract(UText *ut,
430
             int64_t start, int64_t limit,
431
             char16_t *dest, int32_t destCapacity,
432
16.7k
             UErrorCode *status) {
433
16.7k
                 return ut->pFuncs->extract(ut, start, limit, dest, destCapacity, status);
434
16.7k
             }
435
436
437
438
U_CAPI UBool U_EXPORT2
439
0
utext_equals(const UText *a, const UText *b) {
440
0
    if (a==nullptr || b==nullptr ||
441
0
        a->magic != UTEXT_MAGIC ||
442
0
        b->magic != UTEXT_MAGIC) {
443
            // Null or invalid arguments don't compare equal to anything.
444
0
            return false;
445
0
    }
446
447
0
    if (a->pFuncs != b->pFuncs) {
448
        // Different types of text providers.
449
0
        return false;
450
0
    }
451
452
0
    if (a->context != b->context) {
453
        // Different sources (different strings)
454
0
        return false;
455
0
    }
456
0
    if (utext_getNativeIndex(a) != utext_getNativeIndex(b)) {
457
        // Different current position in the string.
458
0
        return false;
459
0
    }
460
461
0
    return true;
462
0
}
463
464
U_CAPI UBool U_EXPORT2
465
utext_isWritable(const UText *ut)
466
0
{
467
0
    UBool b = (ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_WRITABLE)) != 0;
468
0
    return b;
469
0
}
470
471
472
U_CAPI void U_EXPORT2
473
56.7k
utext_freeze(UText *ut) {
474
    // Zero out the WRITABLE flag.
475
56.7k
    ut->providerProperties &= ~(I32_FLAG(UTEXT_PROVIDER_WRITABLE));
476
56.7k
}
477
478
479
U_CAPI UBool U_EXPORT2
480
utext_hasMetaData(const UText *ut)
481
0
{
482
0
    UBool b = (ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_HAS_META_DATA)) != 0;
483
0
    return b;
484
0
}
485
486
487
488
U_CAPI int32_t U_EXPORT2
489
utext_replace(UText *ut,
490
             int64_t nativeStart, int64_t nativeLimit,
491
             const char16_t *replacementText, int32_t replacementLength,
492
             UErrorCode *status)
493
0
{
494
0
    if (U_FAILURE(*status)) {
495
0
        return 0;
496
0
    }
497
0
    if ((ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_WRITABLE)) == 0) {
498
0
        *status = U_NO_WRITE_PERMISSION;
499
0
        return 0;
500
0
    }
501
0
    int32_t i = ut->pFuncs->replace(ut, nativeStart, nativeLimit, replacementText, replacementLength, status);
502
0
    return i;
503
0
}
504
505
U_CAPI void U_EXPORT2
506
utext_copy(UText *ut,
507
          int64_t nativeStart, int64_t nativeLimit,
508
          int64_t destIndex,
509
          UBool move,
510
          UErrorCode *status)
511
0
{
512
0
    if (U_FAILURE(*status)) {
513
0
        return;
514
0
    }
515
0
    if ((ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_WRITABLE)) == 0) {
516
0
        *status = U_NO_WRITE_PERMISSION;
517
0
        return;
518
0
    }
519
0
    ut->pFuncs->copy(ut, nativeStart, nativeLimit, destIndex, move, status);
520
0
}
521
522
523
524
U_CAPI UText * U_EXPORT2
525
56.7k
utext_clone(UText *dest, const UText *src, UBool deep, UBool readOnly, UErrorCode *status) {
526
56.7k
    if (U_FAILURE(*status)) {
527
0
        return dest;
528
0
    }
529
56.7k
    UText *result = src->pFuncs->clone(dest, src, deep, status);
530
56.7k
    if (U_FAILURE(*status)) {
531
0
        return result;
532
0
    }
533
56.7k
    if (result == nullptr) {
534
0
        *status = U_MEMORY_ALLOCATION_ERROR;
535
0
        return result;
536
0
    }
537
56.7k
    if (readOnly) {
538
56.7k
        utext_freeze(result);
539
56.7k
    }
540
56.7k
    return result;
541
56.7k
}
542
543
544
545
//------------------------------------------------------------------------------
546
//
547
//   UText common functions implementation
548
//
549
//------------------------------------------------------------------------------
550
551
//
552
//  UText.flags bit definitions
553
//
554
enum {
555
    UTEXT_HEAP_ALLOCATED  = 1,      //  1 if ICU has allocated this UText struct on the heap.
556
                                    //  0 if caller provided storage for the UText.
557
558
    UTEXT_EXTRA_HEAP_ALLOCATED = 2, //  1 if ICU has allocated extra storage as a separate
559
                                    //     heap block.
560
                                    //  0 if there is no separate allocation.  Either no extra
561
                                    //     storage was requested, or it is appended to the end
562
                                    //     of the main UText storage.
563
564
    UTEXT_OPEN = 4                  //  1 if this UText is currently open
565
                                    //  0 if this UText is not open.
566
};
567
568
569
//
570
//  Extended form of a UText.  The purpose is to aid in computing the total size required
571
//    when a provider asks for a UText to be allocated with extra storage.
572
573
struct ExtendedUText {
574
    UText               ut;
575
    std::max_align_t    extension;
576
};
577
578
static const UText emptyText = UTEXT_INITIALIZER;
579
580
U_CAPI UText * U_EXPORT2
581
4.84M
utext_setup(UText *ut, int32_t extraSpace, UErrorCode *status) {
582
4.84M
    if (U_FAILURE(*status)) {
583
0
        return ut;
584
0
    }
585
586
4.84M
    if (ut == nullptr) {
587
        // We need to heap-allocate storage for the new UText
588
47.3k
        int32_t spaceRequired = sizeof(UText);
589
47.3k
        if (extraSpace > 0) {
590
0
            spaceRequired = sizeof(ExtendedUText) + extraSpace - sizeof(std::max_align_t);
591
0
        }
592
47.3k
        ut = (UText *)uprv_malloc(spaceRequired);
593
47.3k
        if (ut == nullptr) {
594
0
            *status = U_MEMORY_ALLOCATION_ERROR;
595
0
            return nullptr;
596
47.3k
        } else {
597
47.3k
            *ut = emptyText;
598
47.3k
            ut->flags |= UTEXT_HEAP_ALLOCATED;
599
47.3k
            if (spaceRequired>0) {
600
47.3k
                ut->extraSize = extraSpace;
601
47.3k
                ut->pExtra    = &((ExtendedUText *)ut)->extension;
602
47.3k
            }
603
47.3k
        }
604
4.80M
    } else {
605
        // We have been supplied with an already existing UText.
606
        // Verify that it really appears to be a UText.
607
4.80M
        if (ut->magic != UTEXT_MAGIC) {
608
0
            *status = U_ILLEGAL_ARGUMENT_ERROR;
609
0
            return ut;
610
0
        }
611
        // If the ut is already open and there's a provider supplied close
612
        //   function, call it.
613
4.80M
        if ((ut->flags & UTEXT_OPEN) && ut->pFuncs->close != nullptr)  {
614
27.6k
            ut->pFuncs->close(ut);
615
27.6k
        }
616
4.80M
        ut->flags &= ~UTEXT_OPEN;
617
618
        // If extra space was requested by our caller, check whether
619
        //   sufficient already exists, and allocate new if needed.
620
4.80M
        if (extraSpace > ut->extraSize) {
621
            // Need more space.  If there is existing separately allocated space,
622
            //   delete it first, then allocate new space.
623
7.31k
            if (ut->flags & UTEXT_EXTRA_HEAP_ALLOCATED) {
624
0
                uprv_free(ut->pExtra);
625
0
                ut->extraSize = 0;
626
0
            }
627
7.31k
            ut->pExtra = uprv_malloc(extraSpace);
628
7.31k
            if (ut->pExtra == nullptr) {
629
0
                *status = U_MEMORY_ALLOCATION_ERROR;
630
7.31k
            } else {
631
7.31k
                ut->extraSize = extraSpace;
632
7.31k
                ut->flags |= UTEXT_EXTRA_HEAP_ALLOCATED;
633
7.31k
            }
634
7.31k
        }
635
4.80M
    }
636
4.84M
    if (U_SUCCESS(*status)) {
637
4.84M
        ut->flags |= UTEXT_OPEN;
638
639
        // Initialize all remaining fields of the UText.
640
        //
641
4.84M
        ut->context             = nullptr;
642
4.84M
        ut->chunkContents       = nullptr;
643
4.84M
        ut->p                   = nullptr;
644
4.84M
        ut->q                   = nullptr;
645
4.84M
        ut->r                   = nullptr;
646
4.84M
        ut->a                   = 0;
647
4.84M
        ut->b                   = 0;
648
4.84M
        ut->c                   = 0;
649
4.84M
        ut->chunkOffset         = 0;
650
4.84M
        ut->chunkLength         = 0;
651
4.84M
        ut->chunkNativeStart    = 0;
652
4.84M
        ut->chunkNativeLimit    = 0;
653
4.84M
        ut->nativeIndexingLimit = 0;
654
4.84M
        ut->providerProperties  = 0;
655
4.84M
        ut->privA               = 0;
656
4.84M
        ut->privB               = 0;
657
4.84M
        ut->privC               = 0;
658
4.84M
        ut->privP               = nullptr;
659
4.84M
        if (ut->pExtra!=nullptr && ut->extraSize>0)
660
4.84M
            uprv_memset(ut->pExtra, 0, ut->extraSize);
661
662
4.84M
    }
663
4.84M
    return ut;
664
4.84M
}
665
666
667
U_CAPI UText * U_EXPORT2
668
4.82M
utext_close(UText *ut) {
669
4.82M
    if (ut==nullptr ||
670
4.82M
        ut->magic != UTEXT_MAGIC ||
671
4.82M
        (ut->flags & UTEXT_OPEN) == 0)
672
0
    {
673
        // The supplied ut is not an open UText.
674
        // Do nothing.
675
0
        return ut;
676
0
    }
677
678
    // If the provider gave us a close function, call it now.
679
    // This will clean up anything allocated specifically by the provider.
680
4.82M
    if (ut->pFuncs->close != nullptr) {
681
4.82M
        ut->pFuncs->close(ut);
682
4.82M
    }
683
4.82M
    ut->flags &= ~UTEXT_OPEN;
684
685
    // If we (the framework) allocated the UText or subsidiary storage,
686
    //   delete it.
687
4.82M
    if (ut->flags & UTEXT_EXTRA_HEAP_ALLOCATED) {
688
7.31k
        uprv_free(ut->pExtra);
689
7.31k
        ut->pExtra = nullptr;
690
7.31k
        ut->flags &= ~UTEXT_EXTRA_HEAP_ALLOCATED;
691
7.31k
        ut->extraSize = 0;
692
7.31k
    }
693
694
    // Zero out function table of the closed UText.  This is a defensive move,
695
    //   intended to cause applications that inadvertently use a closed
696
    //   utext to crash with null pointer errors.
697
4.82M
    ut->pFuncs        = nullptr;
698
699
4.82M
    if (ut->flags & UTEXT_HEAP_ALLOCATED) {
700
        // This UText was allocated by UText setup.  We need to free it.
701
        // Clear magic, so we can detect if the user messes up and immediately
702
        //  tries to reopen another UText using the deleted storage.
703
47.3k
        ut->magic = 0;
704
47.3k
        uprv_free(ut);
705
47.3k
        ut = nullptr;
706
47.3k
    }
707
4.82M
    return ut;
708
4.82M
}
709
710
711
712
713
//
714
// invalidateChunk   Reset a chunk to have no contents, so that the next call
715
//                   to access will cause new data to load.
716
//                   This is needed when copy/move/replace operate directly on the
717
//                   backing text, potentially putting it out of sync with the
718
//                   contents in the chunk.
719
//
720
static void
721
0
invalidateChunk(UText *ut) {
722
0
    ut->chunkLength = 0;
723
0
    ut->chunkNativeLimit = 0;
724
0
    ut->chunkNativeStart = 0;
725
0
    ut->chunkOffset = 0;
726
0
    ut->nativeIndexingLimit = 0;
727
0
}
728
729
//
730
// pinIndex        Do range pinning on a native index parameter.
731
//                 64 bit pinning is done in place.
732
//                 32 bit truncated result is returned as a convenience for
733
//                        use in providers that don't need 64 bits.
734
static int32_t
735
2.28M
pinIndex(int64_t &index, int64_t limit) {
736
2.28M
    if (index<0) {
737
0
        index = 0;
738
2.28M
    } else if (index > limit) {
739
6.49k
        index = limit;
740
6.49k
    }
741
2.28M
    return static_cast<int32_t>(index);
742
2.28M
}
743
744
745
U_CDECL_BEGIN
746
747
//
748
// Pointer relocation function,
749
//   a utility used by shallow clone.
750
//   Adjust a pointer that refers to something within one UText (the source)
751
//   to refer to the same relative offset within a another UText (the target)
752
//
753
283k
static void adjustPointer(UText *dest, const void **destPtr, const UText *src) {
754
    // convert all pointers to (char *) so that byte address arithmetic will work.
755
283k
    char  *dptr = (char *)*destPtr;
756
283k
    char  *dUText = (char *)dest;
757
283k
    char  *sUText = (char *)src;
758
759
283k
    if (dptr >= (char *)src->pExtra && dptr < ((char*)src->pExtra)+src->extraSize) {
760
        // target ptr was to something within the src UText's pExtra storage.
761
        //   relocate it into the target UText's pExtra region.
762
7.23k
        *destPtr = ((char *)dest->pExtra) + (dptr - (char *)src->pExtra);
763
276k
    } else if (dptr>=sUText && dptr < sUText+src->sizeOfStruct) {
764
        // target ptr was pointing to somewhere within the source UText itself.
765
        //   Move it to the same offset within the target UText.
766
0
        *destPtr = dUText + (dptr-sUText);
767
0
    }
768
283k
}
769
770
771
//
772
//  Clone.  This is a generic copy-the-utext-by-value clone function that can be
773
//          used as-is with some utext types, and as a helper by other clones.
774
//
775
static UText * U_CALLCONV
776
56.7k
shallowTextClone(UText * dest, const UText * src, UErrorCode * status) {
777
56.7k
    if (U_FAILURE(*status)) {
778
0
        return nullptr;
779
0
    }
780
56.7k
    int32_t  srcExtraSize = src->extraSize;
781
782
    //
783
    // Use the generic text_setup to allocate storage if required.
784
    //
785
56.7k
    dest = utext_setup(dest, srcExtraSize, status);
786
56.7k
    if (U_FAILURE(*status)) {
787
0
        return dest;
788
0
    }
789
790
    //
791
    //  flags (how the UText was allocated) and the pointer to the
792
    //   extra storage must retain the values in the cloned utext that
793
    //   were set up by utext_setup.  Save them separately before
794
    //   copying the whole struct.
795
    //
796
56.7k
    void *destExtra = dest->pExtra;
797
56.7k
    int32_t flags   = dest->flags;
798
799
800
    //
801
    //  Copy the whole UText struct by value.
802
    //  Any "Extra" storage is copied also.
803
    //
804
56.7k
    int sizeToCopy = src->sizeOfStruct;
805
56.7k
    if (sizeToCopy > dest->sizeOfStruct) {
806
0
        sizeToCopy = dest->sizeOfStruct;
807
0
    }
808
56.7k
    uprv_memcpy(dest, src, sizeToCopy);
809
56.7k
    dest->pExtra = destExtra;
810
56.7k
    dest->flags  = flags;
811
56.7k
    if (srcExtraSize > 0) {
812
3.61k
        uprv_memcpy(dest->pExtra, src->pExtra, srcExtraSize);
813
3.61k
    }
814
815
    //
816
    // Relocate any pointers in the target that refer to the UText itself
817
    //   to point to the cloned copy rather than the original source.
818
    //
819
56.7k
    adjustPointer(dest, &dest->context, src);
820
56.7k
    adjustPointer(dest, &dest->p, src);
821
56.7k
    adjustPointer(dest, &dest->q, src);
822
56.7k
    adjustPointer(dest, &dest->r, src);
823
56.7k
    adjustPointer(dest, (const void **)&dest->chunkContents, src);
824
825
    // The newly shallow-cloned UText does _not_ own the underlying storage for the text.
826
    // (The source for the clone may or may not have owned the text.)
827
828
56.7k
    dest->providerProperties &= ~I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT);
829
830
56.7k
    return dest;
831
56.7k
}
832
833
834
U_CDECL_END
835
836
837
838
//------------------------------------------------------------------------------
839
//
840
//     UText implementation for UTF-8 char * strings (read-only)
841
//     Limitation:  string length must be <= 0x7fffffff in length.
842
//                  (length must for in an int32_t variable)
843
//
844
//         Use of UText data members:
845
//              context    pointer to UTF-8 string
846
//              utext.b    is the input string length (bytes).
847
//              utext.c    Length scanned so far in string
848
//                           (for optimizing finding length of zero terminated strings.)
849
//              utext.p    pointer to the current buffer
850
//              utext.q    pointer to the other buffer.
851
//
852
//------------------------------------------------------------------------------
853
854
// Chunk size.
855
//     Must be less than 85 (256/3), because of byte mapping from char16_t indexes to native indexes.
856
//     Worst case is three native bytes to one char16_t.  (Supplemenaries are 4 native bytes
857
//     to two UChars.)
858
//     The longest illegal byte sequence treated as a single error (and converted to U+FFFD)
859
//     is a three-byte sequence (truncated four-byte sequence).
860
//
861
enum { UTF8_TEXT_CHUNK_SIZE=32 };
862
863
//
864
// UTF8Buf  Two of these structs will be set up in the UText's extra allocated space.
865
//          Each contains the char16_t chunk buffer, the to and from native maps, and
866
//          header info.
867
//
868
//     because backwards iteration fills the buffers starting at the end and
869
//     working towards the front, the filled part of the buffers may not begin
870
//     at the start of the available storage for the buffers.
871
//
872
//     Buffer size is one bigger than the specified UTF8_TEXT_CHUNK_SIZE to allow for
873
//     the last character added being a supplementary, and thus requiring a surrogate
874
//     pair.  Doing this is simpler than checking for the edge case.
875
//
876
877
struct UTF8Buf {
878
    int32_t   bufNativeStart;                        // Native index of first char in char16_t buf
879
    int32_t   bufNativeLimit;                        // Native index following last char in buf.
880
    int32_t   bufStartIdx;                           // First filled position in buf.
881
    int32_t   bufLimitIdx;                           // Limit of filled range in buf.
882
    int32_t   bufNILimit;                            // Limit of native indexing part of buf
883
    int32_t   toUCharsMapStart;                      // Native index corresponding to
884
                                                     //   mapToUChars[0].
885
                                                     //   Set to bufNativeStart when filling forwards.
886
                                                     //   Set to computed value when filling backwards.
887
888
    char16_t  buf[UTF8_TEXT_CHUNK_SIZE+4];           // The char16_t buffer.  Requires one extra position beyond the
889
                                                     //   the chunk size, to allow for surrogate at the end.
890
                                                     //   Length must be identical to mapToNative array, below,
891
                                                     //   because of the way indexing works when the array is
892
                                                     //   filled backwards during a reverse iteration.  Thus,
893
                                                     //   the additional extra size.
894
    uint8_t   mapToNative[UTF8_TEXT_CHUNK_SIZE+4];   // map char16_t index in buf to
895
                                                     //  native offset from bufNativeStart.
896
                                                     //  Requires two extra slots,
897
                                                     //    one for a supplementary starting in the last normal position,
898
                                                     //    and one for an entry for the buffer limit position.
899
    uint8_t   mapToUChars[UTF8_TEXT_CHUNK_SIZE*3+6]; // Map native offset from bufNativeStart to
900
                                                     //   corresponding offset in filled part of buf.
901
    int32_t   align;
902
};
903
904
U_CDECL_BEGIN
905
906
//
907
//   utf8TextLength
908
//
909
//        Get the length of the string.  If we don't already know it,
910
//              we'll need to scan for the trailing  nul.
911
//
912
static int64_t U_CALLCONV
913
158k
utf8TextLength(UText *ut) {
914
158k
    if (ut->b < 0) {
915
        // Zero terminated string, and we haven't scanned to the end yet.
916
        // Scan it now.
917
0
        const char *r = (const char *)ut->context + ut->c;
918
0
        while (*r != 0) {
919
0
            r++;
920
0
        }
921
0
        if ((r - (const char *)ut->context) < 0x7fffffff) {
922
0
            ut->b = (int32_t)(r - (const char *)ut->context);
923
0
        } else {
924
            // Actual string was bigger (more than 2 gig) than we
925
            //   can handle.  Clip it to 2 GB.
926
0
            ut->b = 0x7fffffff;
927
0
        }
928
0
        ut->providerProperties &= ~I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE);
929
0
    }
930
158k
    return ut->b;
931
158k
}
932
933
934
935
936
937
938
static UBool U_CALLCONV
939
4.24M
utf8TextAccess(UText *ut, int64_t index, UBool forward) {
940
    //
941
    //  Apologies to those who are allergic to goto statements.
942
    //    Consider each goto to a labelled block to be the equivalent of
943
    //         call the named block as if it were a function();
944
    //         return;
945
    //
946
4.24M
    const uint8_t *s8=(const uint8_t *)ut->context;
947
4.24M
    UTF8Buf *u8b = nullptr;
948
4.24M
    int32_t  length = ut->b;         // Length of original utf-8
949
4.24M
    int32_t  ix= (int32_t)index;     // Requested index, trimmed to 32 bits.
950
4.24M
    int32_t  mapIndex = 0;
951
4.24M
    if (index<0) {
952
0
        ix=0;
953
4.24M
    } else if (index > 0x7fffffff) {
954
        // Strings with 64 bit lengths not supported by this UTF-8 provider.
955
0
        ix = 0x7fffffff;
956
0
    }
957
958
    // Pin requested index to the string length.
959
4.24M
    if (ix>length) {
960
0
        if (length>=0) {
961
0
            ix=length;
962
0
        } else if (ix>=ut->c) {
963
            // Zero terminated string, and requested index is beyond
964
            //   the region that has already been scanned.
965
            //   Scan up to either the end of the string or to the
966
            //   requested position, whichever comes first.
967
0
            while (ut->c<ix && s8[ut->c]!=0) {
968
0
                ut->c++;
969
0
            }
970
            //  TODO:  support for null terminated string length > 32 bits.
971
0
            if (s8[ut->c] == 0) {
972
                // We just found the actual length of the string.
973
                //  Trim the requested index back to that.
974
0
                ix     = ut->c;
975
0
                ut->b  = ut->c;
976
0
                length = ut->c;
977
0
                ut->providerProperties &= ~I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE);
978
0
            }
979
0
        }
980
0
    }
981
982
    //
983
    // Dispatch to the appropriate action for a forward iteration request.
984
    //
985
4.24M
    if (forward) {
986
4.24M
        if (ix==ut->chunkNativeLimit) {
987
            // Check for normal sequential iteration cases first.
988
3.79M
            if (ix==length) {
989
                // Just reached end of string
990
                // Don't swap buffers, but do set the
991
                //   current buffer position.
992
18.3k
                ut->chunkOffset = ut->chunkLength;
993
18.3k
                return false;
994
3.77M
            } else {
995
                // End of current buffer.
996
                //   check whether other buffer already has what we need.
997
3.77M
                UTF8Buf *altB = (UTF8Buf *)ut->q;
998
3.77M
                if (ix>=altB->bufNativeStart && ix<altB->bufNativeLimit) {
999
363k
                    goto swapBuffers;
1000
363k
                }
1001
3.77M
            }
1002
3.79M
        }
1003
1004
        // A random access.  Desired index could be in either or niether buf.
1005
        // For optimizing the order of testing, first check for the index
1006
        //    being in the other buffer.  This will be the case for uses that
1007
        //    move back and forth over a fairly limited range
1008
3.86M
        {
1009
3.86M
            u8b = (UTF8Buf *)ut->q;   // the alternate buffer
1010
3.86M
            if (ix>=u8b->bufNativeStart && ix<u8b->bufNativeLimit) {
1011
                // Requested index is in the other buffer.
1012
407k
                goto swapBuffers;
1013
407k
            }
1014
3.45M
            if (ix == length) {
1015
                // Requested index is end-of-string.
1016
                //   (this is the case of randomly seeking to the end.
1017
                //    The case of iterating off the end is handled earlier.)
1018
25
                if (ix == ut->chunkNativeLimit) {
1019
                    // Current buffer extends up to the end of the string.
1020
                    //   Leave it as the current buffer.
1021
0
                    ut->chunkOffset = ut->chunkLength;
1022
0
                    return false;
1023
0
                }
1024
25
                if (ix == u8b->bufNativeLimit) {
1025
                    // Alternate buffer extends to the end of string.
1026
                    //   Swap it in as the current buffer.
1027
25
                    goto swapBuffersAndFail;
1028
25
                }
1029
1030
                // Neither existing buffer extends to the end of the string.
1031
0
                goto makeStubBuffer;
1032
25
            }
1033
1034
3.45M
            if (ix<ut->chunkNativeStart || ix>=ut->chunkNativeLimit) {
1035
                // Requested index is in neither buffer.
1036
3.45M
                goto fillForward;
1037
3.45M
            }
1038
1039
            // Requested index is in this buffer.
1040
0
            u8b = (UTF8Buf *)ut->p;   // the current buffer
1041
0
            mapIndex = ix - u8b->toUCharsMapStart;
1042
0
            U_ASSERT(mapIndex < (int32_t)sizeof(UTF8Buf::mapToUChars));
1043
0
            ut->chunkOffset = u8b->mapToUChars[mapIndex] - u8b->bufStartIdx;
1044
0
            return true;
1045
1046
3.45M
        }
1047
3.45M
    }
1048
1049
1050
    //
1051
    // Dispatch to the appropriate action for a
1052
    //   Backwards Direction iteration request.
1053
    //
1054
1.05k
    if (ix==ut->chunkNativeStart) {
1055
        // Check for normal sequential iteration cases first.
1056
1.05k
        if (ix==0) {
1057
            // Just reached the start of string
1058
            // Don't swap buffers, but do set the
1059
            //   current buffer position.
1060
0
            ut->chunkOffset = 0;
1061
0
            return false;
1062
1.05k
        } else {
1063
            // Start of current buffer.
1064
            //   check whether other buffer already has what we need.
1065
1.05k
            UTF8Buf *altB = (UTF8Buf *)ut->q;
1066
1.05k
            if (ix>altB->bufNativeStart && ix<=altB->bufNativeLimit) {
1067
1.05k
                goto swapBuffers;
1068
1.05k
            }
1069
1.05k
        }
1070
1.05k
    }
1071
1072
    // A random access.  Desired index could be in either or niether buf.
1073
    // For optimizing the order of testing,
1074
    //    Most likely case:  in the other buffer.
1075
    //    Second most likely: in neither buffer.
1076
    //    Unlikely, but must work:  in the current buffer.
1077
0
    u8b = (UTF8Buf *)ut->q;   // the alternate buffer
1078
0
    if (ix>u8b->bufNativeStart && ix<=u8b->bufNativeLimit) {
1079
        // Requested index is in the other buffer.
1080
0
        goto swapBuffers;
1081
0
    }
1082
    // Requested index is start-of-string.
1083
    //   (this is the case of randomly seeking to the start.
1084
    //    The case of iterating off the start is handled earlier.)
1085
0
    if (ix==0) {
1086
0
        if (u8b->bufNativeStart==0) {
1087
            // Alternate buffer contains the data for the start string.
1088
            // Make it be the current buffer.
1089
0
            goto swapBuffersAndFail;
1090
0
        } else {
1091
            // Request for data before the start of string,
1092
            //   neither buffer is usable.
1093
            //   set up a zero-length buffer.
1094
0
            goto makeStubBuffer;
1095
0
        }
1096
0
    }
1097
1098
0
    if (ix<=ut->chunkNativeStart || ix>ut->chunkNativeLimit) {
1099
        // Requested index is in neither buffer.
1100
0
        goto fillReverse;
1101
0
    }
1102
1103
    // Requested index is in this buffer.
1104
    //   Set the utf16 buffer index.
1105
0
    u8b = (UTF8Buf *)ut->p;
1106
0
    mapIndex = ix - u8b->toUCharsMapStart;
1107
0
    ut->chunkOffset = u8b->mapToUChars[mapIndex] - u8b->bufStartIdx;
1108
0
    if (ut->chunkOffset==0) {
1109
        // This occurs when the first character in the text is
1110
        //   a multi-byte UTF-8 char, and the requested index is to
1111
        //   one of the trailing bytes.  Because there is no preceding ,
1112
        //   character, this access fails.  We can't pick up on the
1113
        //   situation sooner because the requested index is not zero.
1114
0
        return false;
1115
0
    } else {
1116
0
        return true;
1117
0
    }
1118
1119
1120
1121
771k
swapBuffers:
1122
    //  The alternate buffer (ut->q) has the string data that was requested.
1123
    //  Swap the primary and alternate buffers, and set the
1124
    //   chunk index into the new primary buffer.
1125
771k
    {
1126
771k
        u8b   = (UTF8Buf *)ut->q;
1127
771k
        ut->q = ut->p;
1128
771k
        ut->p = u8b;
1129
771k
        ut->chunkContents       = &u8b->buf[u8b->bufStartIdx];
1130
771k
        ut->chunkLength         = u8b->bufLimitIdx - u8b->bufStartIdx;
1131
771k
        ut->chunkNativeStart    = u8b->bufNativeStart;
1132
771k
        ut->chunkNativeLimit    = u8b->bufNativeLimit;
1133
771k
        ut->nativeIndexingLimit = u8b->bufNILimit;
1134
1135
        // Index into the (now current) chunk
1136
        // Use the map to set the chunk index.  It's more trouble than it's worth
1137
        //    to check whether native indexing can be used.
1138
771k
        U_ASSERT(ix>=u8b->bufNativeStart);
1139
771k
        U_ASSERT(ix<=u8b->bufNativeLimit);
1140
771k
        mapIndex = ix - u8b->toUCharsMapStart;
1141
771k
        U_ASSERT(mapIndex>=0);
1142
771k
        U_ASSERT(mapIndex<(int32_t)sizeof(u8b->mapToUChars));
1143
771k
        ut->chunkOffset = u8b->mapToUChars[mapIndex] - u8b->bufStartIdx;
1144
1145
771k
        return true;
1146
0
    }
1147
1148
1149
25
 swapBuffersAndFail:
1150
    // We got a request for either the start or end of the string,
1151
    //  with iteration continuing in the out-of-bounds direction.
1152
    // The alternate buffer already contains the data up to the
1153
    //  start/end.
1154
    // Swap the buffers, then return failure, indicating that we couldn't
1155
    //  make things correct for continuing the iteration in the requested
1156
    //  direction.  The position & buffer are correct should the
1157
    //  user decide to iterate in the opposite direction.
1158
25
    u8b   = (UTF8Buf *)ut->q;
1159
25
    ut->q = ut->p;
1160
25
    ut->p = u8b;
1161
25
    ut->chunkContents       = &u8b->buf[u8b->bufStartIdx];
1162
25
    ut->chunkLength         = u8b->bufLimitIdx - u8b->bufStartIdx;
1163
25
    ut->chunkNativeStart    = u8b->bufNativeStart;
1164
25
    ut->chunkNativeLimit    = u8b->bufNativeLimit;
1165
25
    ut->nativeIndexingLimit = u8b->bufNILimit;
1166
1167
    // Index into the (now current) chunk
1168
    //  For this function  (swapBuffersAndFail), the requested index
1169
    //    will always be at either the start or end of the chunk.
1170
25
    if (ix==u8b->bufNativeLimit) {
1171
25
        ut->chunkOffset = ut->chunkLength;
1172
25
    } else  {
1173
0
        ut->chunkOffset = 0;
1174
0
        U_ASSERT(ix == u8b->bufNativeStart);
1175
0
    }
1176
25
    return false;
1177
1178
0
makeStubBuffer:
1179
    //   The user has done a seek/access past the start or end
1180
    //   of the string.  Rather than loading data that is likely
1181
    //   to never be used, just set up a zero-length buffer at
1182
    //   the position.
1183
0
    u8b = (UTF8Buf *)ut->q;
1184
0
    u8b->bufNativeStart   = ix;
1185
0
    u8b->bufNativeLimit   = ix;
1186
0
    u8b->bufStartIdx      = 0;
1187
0
    u8b->bufLimitIdx      = 0;
1188
0
    u8b->bufNILimit       = 0;
1189
0
    u8b->toUCharsMapStart = ix;
1190
0
    u8b->mapToNative[0]   = 0;
1191
0
    u8b->mapToUChars[0]   = 0;
1192
0
    goto swapBuffersAndFail;
1193
1194
1195
1196
3.45M
fillForward:
1197
3.45M
    {
1198
        // Move the incoming index to a code point boundary.
1199
3.45M
        U8_SET_CP_START(s8, 0, ix);
1200
1201
        // Swap the UText buffers.
1202
        //  We want to fill what was previously the alternate buffer,
1203
        //  and make what was the current buffer be the new alternate.
1204
3.45M
        UTF8Buf *u8b_swap = (UTF8Buf *)ut->q;
1205
3.45M
        ut->q = ut->p;
1206
3.45M
        ut->p = u8b_swap;
1207
1208
3.45M
        int32_t strLen = ut->b;
1209
3.45M
        UBool   nulTerminated = false;
1210
3.45M
        if (strLen < 0) {
1211
0
            strLen = 0x7fffffff;
1212
0
            nulTerminated = true;
1213
0
        }
1214
1215
3.45M
        char16_t   *buf = u8b_swap->buf;
1216
3.45M
        uint8_t *mapToNative  = u8b_swap->mapToNative;
1217
3.45M
        uint8_t *mapToUChars  = u8b_swap->mapToUChars;
1218
3.45M
        int32_t  destIx       = 0;
1219
3.45M
        int32_t  srcIx        = ix;
1220
3.45M
        UBool    seenNonAscii = false;
1221
3.45M
        UChar32  c = 0;
1222
1223
        // Fill the chunk buffer and mapping arrays.
1224
100M
        while (destIx<UTF8_TEXT_CHUNK_SIZE) {
1225
96.7M
            c = s8[srcIx];
1226
96.7M
            if (c>0 && c<0x80) {
1227
                // Special case ASCII range for speed.
1228
                //   zero is excluded to simplify bounds checking.
1229
14.6M
                buf[destIx] = (char16_t)c;
1230
14.6M
                mapToNative[destIx]    = (uint8_t)(srcIx - ix);
1231
14.6M
                mapToUChars[srcIx-ix]  = (uint8_t)destIx;
1232
14.6M
                srcIx++;
1233
14.6M
                destIx++;
1234
82.1M
            } else {
1235
                // General case, handle everything.
1236
82.1M
                if (seenNonAscii == false) {
1237
3.26M
                    seenNonAscii = true;
1238
3.26M
                    u8b_swap->bufNILimit = destIx;
1239
3.26M
                }
1240
1241
82.1M
                int32_t  cIx      = srcIx;
1242
82.1M
                int32_t  dIx      = destIx;
1243
82.1M
                int32_t  dIxSaved = destIx;
1244
82.1M
                U8_NEXT_OR_FFFD(s8, srcIx, strLen, c);
1245
82.1M
                if (c==0 && nulTerminated) {
1246
0
                    srcIx--;
1247
0
                    break;
1248
0
                }
1249
1250
82.1M
                U16_APPEND_UNSAFE(buf, destIx, c);
1251
95.8M
                do {
1252
95.8M
                    mapToNative[dIx++] = (uint8_t)(cIx - ix);
1253
95.8M
                } while (dIx < destIx);
1254
1255
226M
                do {
1256
226M
                    mapToUChars[cIx++ - ix] = (uint8_t)dIxSaved;
1257
226M
                } while (cIx < srcIx);
1258
82.1M
            }
1259
96.7M
            if (srcIx>=strLen) {
1260
5.24k
                break;
1261
5.24k
            }
1262
1263
96.7M
        }
1264
1265
        //  store Native <--> Chunk Map entries for the end of the buffer.
1266
        //    There is no actual character here, but the index position is valid.
1267
3.45M
        mapToNative[destIx]     = (uint8_t)(srcIx - ix);
1268
3.45M
        mapToUChars[srcIx - ix] = (uint8_t)destIx;
1269
1270
        //  fill in Buffer descriptor
1271
3.45M
        u8b_swap->bufNativeStart     = ix;
1272
3.45M
        u8b_swap->bufNativeLimit     = srcIx;
1273
3.45M
        u8b_swap->bufStartIdx        = 0;
1274
3.45M
        u8b_swap->bufLimitIdx        = destIx;
1275
3.45M
        if (seenNonAscii == false) {
1276
191k
            u8b_swap->bufNILimit     = destIx;
1277
191k
        }
1278
3.45M
        u8b_swap->toUCharsMapStart   = u8b_swap->bufNativeStart;
1279
1280
        // Set UText chunk to refer to this buffer.
1281
3.45M
        ut->chunkContents       = buf;
1282
3.45M
        ut->chunkOffset         = 0;
1283
3.45M
        ut->chunkLength         = u8b_swap->bufLimitIdx;
1284
3.45M
        ut->chunkNativeStart    = u8b_swap->bufNativeStart;
1285
3.45M
        ut->chunkNativeLimit    = u8b_swap->bufNativeLimit;
1286
3.45M
        ut->nativeIndexingLimit = u8b_swap->bufNILimit;
1287
1288
        // For zero terminated strings, keep track of the maximum point
1289
        //   scanned so far.
1290
3.45M
        if (nulTerminated && srcIx>ut->c) {
1291
0
            ut->c = srcIx;
1292
0
            if (c==0) {
1293
                // We scanned to the end.
1294
                //   Remember the actual length.
1295
0
                ut->b = srcIx;
1296
0
                ut->providerProperties &= ~I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE);
1297
0
            }
1298
0
        }
1299
3.45M
        return true;
1300
0
    }
1301
1302
1303
0
fillReverse:
1304
0
    {
1305
        // Move the incoming index to a code point boundary.
1306
        // Can only do this if the incoming index is somewhere in the interior of the string.
1307
        //   If index is at the end, there is no character there to look at.
1308
0
        if (ix != ut->b) {
1309
            // Note: this function will only move the index back if it is on a trail byte
1310
            //       and there is a preceding lead byte and the sequence from the lead 
1311
            //       through this trail could be part of a valid UTF-8 sequence
1312
            //       Otherwise the index remains unchanged.
1313
0
            U8_SET_CP_START(s8, 0, ix);
1314
0
        }
1315
1316
        // Swap the UText buffers.
1317
        //  We want to fill what was previously the alternate buffer,
1318
        //  and make what was the current buffer be the new alternate.
1319
0
        UTF8Buf *u8b_swap = (UTF8Buf *)ut->q;
1320
0
        ut->q = ut->p;
1321
0
        ut->p = u8b_swap;
1322
1323
0
        char16_t   *buf = u8b_swap->buf;
1324
0
        uint8_t *mapToNative = u8b_swap->mapToNative;
1325
0
        uint8_t *mapToUChars = u8b_swap->mapToUChars;
1326
0
        int32_t  toUCharsMapStart = ix - sizeof(UTF8Buf::mapToUChars) + 1;
1327
        // Note that toUCharsMapStart can be negative. Happens when the remaining
1328
        // text from current position to the beginning is less than the buffer size.
1329
        // + 1 because mapToUChars must have a slot at the end for the bufNativeLimit entry.
1330
0
        int32_t  destIx = UTF8_TEXT_CHUNK_SIZE+2;   // Start in the overflow region
1331
                                                    //   at end of buffer to leave room
1332
                                                    //   for a surrogate pair at the
1333
                                                    //   buffer start.
1334
0
        int32_t  srcIx  = ix;
1335
0
        int32_t  bufNILimit = destIx;
1336
0
        UChar32   c;
1337
1338
        // Map to/from Native Indexes, fill in for the position at the end of
1339
        //   the buffer.
1340
        //
1341
0
        mapToNative[destIx] = (uint8_t)(srcIx - toUCharsMapStart);
1342
0
        mapToUChars[srcIx - toUCharsMapStart] = (uint8_t)destIx;
1343
1344
        // Fill the chunk buffer
1345
        // Work backwards, filling from the end of the buffer towards the front.
1346
        //
1347
0
        while (destIx>2 && (srcIx - toUCharsMapStart > 5) && (srcIx > 0)) {
1348
0
            srcIx--;
1349
0
            destIx--;
1350
1351
            // Get last byte of the UTF-8 character
1352
0
            c = s8[srcIx];
1353
0
            if (c<0x80) {
1354
                // Special case ASCII range for speed.
1355
0
                buf[destIx] = (char16_t)c;
1356
0
                U_ASSERT(toUCharsMapStart <= srcIx);
1357
0
                mapToUChars[srcIx - toUCharsMapStart] = (uint8_t)destIx;
1358
0
                mapToNative[destIx] = (uint8_t)(srcIx - toUCharsMapStart);
1359
0
            } else {
1360
                // General case, handle everything non-ASCII.
1361
1362
0
                int32_t  sIx      = srcIx;  // ix of last byte of multi-byte u8 char
1363
1364
                // Get the full character from the UTF8 string.
1365
                //   use code derived from the macros in utf8.h
1366
                //   Leaves srcIx pointing at the first byte of the UTF-8 char.
1367
                //
1368
0
                c=utf8_prevCharSafeBody(s8, 0, &srcIx, c, -3);
1369
                // leaves srcIx at first byte of the multi-byte char.
1370
1371
                // Store the character in UTF-16 buffer.
1372
0
                if (c<0x10000) {
1373
0
                    buf[destIx] = (char16_t)c;
1374
0
                    mapToNative[destIx] = (uint8_t)(srcIx - toUCharsMapStart);
1375
0
                } else {
1376
0
                    buf[destIx]         = U16_TRAIL(c);
1377
0
                    mapToNative[destIx] = (uint8_t)(srcIx - toUCharsMapStart);
1378
0
                    buf[--destIx]       = U16_LEAD(c);
1379
0
                    mapToNative[destIx] = (uint8_t)(srcIx - toUCharsMapStart);
1380
0
                }
1381
1382
                // Fill in the map from native indexes to UChars buf index.
1383
0
                do {
1384
0
                    mapToUChars[sIx-- - toUCharsMapStart] = (uint8_t)destIx;
1385
0
                } while (sIx >= srcIx);
1386
0
                U_ASSERT(toUCharsMapStart <= (srcIx+1));
1387
1388
                // Set native indexing limit to be the current position.
1389
                //   We are processing a non-ascii, non-native-indexing char now;
1390
                //     the limit will be here if the rest of the chars to be
1391
                //     added to this buffer are ascii.
1392
0
                bufNILimit = destIx;
1393
0
            }
1394
0
        }
1395
0
        u8b_swap->bufNativeStart     = srcIx;
1396
0
        u8b_swap->bufNativeLimit     = ix;
1397
0
        u8b_swap->bufStartIdx        = destIx;
1398
0
        u8b_swap->bufLimitIdx        = UTF8_TEXT_CHUNK_SIZE+2;
1399
0
        u8b_swap->bufNILimit         = bufNILimit - u8b_swap->bufStartIdx;
1400
0
        u8b_swap->toUCharsMapStart   = toUCharsMapStart;
1401
1402
0
        ut->chunkContents       = &buf[u8b_swap->bufStartIdx];
1403
0
        ut->chunkLength         = u8b_swap->bufLimitIdx - u8b_swap->bufStartIdx;
1404
0
        ut->chunkOffset         = ut->chunkLength;
1405
0
        ut->chunkNativeStart    = u8b_swap->bufNativeStart;
1406
0
        ut->chunkNativeLimit    = u8b_swap->bufNativeLimit;
1407
0
        ut->nativeIndexingLimit = u8b_swap->bufNILimit;
1408
0
        return true;
1409
0
    }
1410
1411
0
}
1412
1413
1414
1415
//
1416
//  This is a slightly modified copy of u_strFromUTF8,
1417
//     Inserts a Replacement Char rather than failing on invalid UTF-8
1418
//     Removes unnecessary features.
1419
//
1420
static char16_t*
1421
utext_strFromUTF8(char16_t *dest,
1422
              int32_t destCapacity,
1423
              int32_t *pDestLength,
1424
              const char* src,
1425
              int32_t srcLength,        // required.  NUL terminated not supported.
1426
              UErrorCode *pErrorCode
1427
              )
1428
0
{
1429
1430
0
    char16_t *pDest = dest;
1431
0
    char16_t *pDestLimit = (dest!=nullptr)?(dest+destCapacity):nullptr;
1432
0
    UChar32 ch=0;
1433
0
    int32_t index = 0;
1434
0
    int32_t reqLength = 0;
1435
0
    uint8_t* pSrc = (uint8_t*) src;
1436
1437
1438
0
    while((index < srcLength)&&(pDest<pDestLimit)){
1439
0
        ch = pSrc[index++];
1440
0
        if(ch <=0x7f){
1441
0
            *pDest++=(char16_t)ch;
1442
0
        }else{
1443
0
            ch=utf8_nextCharSafeBody(pSrc, &index, srcLength, ch, -3);
1444
0
            if(U_IS_BMP(ch)){
1445
0
                *(pDest++)=(char16_t)ch;
1446
0
            }else{
1447
0
                *(pDest++)=U16_LEAD(ch);
1448
0
                if(pDest<pDestLimit){
1449
0
                    *(pDest++)=U16_TRAIL(ch);
1450
0
                }else{
1451
0
                    reqLength++;
1452
0
                    break;
1453
0
                }
1454
0
            }
1455
0
        }
1456
0
    }
1457
    /* donot fill the dest buffer just count the UChars needed */
1458
0
    while(index < srcLength){
1459
0
        ch = pSrc[index++];
1460
0
        if(ch <= 0x7f){
1461
0
            reqLength++;
1462
0
        }else{
1463
0
            ch=utf8_nextCharSafeBody(pSrc, &index, srcLength, ch, -3);
1464
0
            reqLength+=U16_LENGTH(ch);
1465
0
        }
1466
0
    }
1467
1468
0
    reqLength+=(int32_t)(pDest - dest);
1469
1470
0
    if(pDestLength){
1471
0
        *pDestLength = reqLength;
1472
0
    }
1473
1474
    /* Terminate the buffer */
1475
0
    u_terminateUChars(dest,destCapacity,reqLength,pErrorCode);
1476
1477
0
    return dest;
1478
0
}
1479
1480
1481
1482
static int32_t U_CALLCONV
1483
utf8TextExtract(UText *ut,
1484
                int64_t start, int64_t limit,
1485
                char16_t *dest, int32_t destCapacity,
1486
0
                UErrorCode *pErrorCode) {
1487
0
    if(U_FAILURE(*pErrorCode)) {
1488
0
        return 0;
1489
0
    }
1490
0
    if(destCapacity<0 || (dest==nullptr && destCapacity>0)) {
1491
0
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
1492
0
        return 0;
1493
0
    }
1494
0
    int32_t  length  = ut->b;
1495
0
    int32_t  start32 = pinIndex(start, length);
1496
0
    int32_t  limit32 = pinIndex(limit, length);
1497
1498
0
    if(start32>limit32) {
1499
0
        *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
1500
0
        return 0;
1501
0
    }
1502
1503
1504
    // adjust the incoming indexes to land on code point boundaries if needed.
1505
    //    adjust by no more than three, because that is the largest number of trail bytes
1506
    //    in a well formed UTF8 character.
1507
0
    const uint8_t *buf = (const uint8_t *)ut->context;
1508
0
    int i;
1509
0
    if (start32 < ut->chunkNativeLimit) {
1510
0
        for (i=0; i<3; i++) {
1511
0
            if (U8_IS_SINGLE(buf[start32]) || U8_IS_LEAD(buf[start32]) || start32==0) {
1512
0
                break;
1513
0
            }
1514
0
            start32--;
1515
0
        }
1516
0
    }
1517
1518
0
    if (limit32 < ut->chunkNativeLimit) {
1519
0
        for (i=0; i<3; i++) {
1520
0
            if (U8_IS_SINGLE(buf[limit32]) || U8_IS_LEAD(buf[limit32]) || limit32==0) {
1521
0
                break;
1522
0
            }
1523
0
            limit32--;
1524
0
        }
1525
0
    }
1526
1527
    // Do the actual extract.
1528
0
    int32_t destLength=0;
1529
0
    utext_strFromUTF8(dest, destCapacity, &destLength,
1530
0
                    (const char *)ut->context+start32, limit32-start32,
1531
0
                    pErrorCode);
1532
0
    utf8TextAccess(ut, limit32, true);
1533
0
    return destLength;
1534
0
}
1535
1536
//
1537
// utf8TextMapOffsetToNative
1538
//
1539
// Map a chunk (UTF-16) offset to a native index.
1540
static int64_t U_CALLCONV
1541
139M
utf8TextMapOffsetToNative(const UText *ut) {
1542
    //
1543
139M
    UTF8Buf *u8b = (UTF8Buf *)ut->p;
1544
139M
    U_ASSERT(ut->chunkOffset>ut->nativeIndexingLimit && ut->chunkOffset<=ut->chunkLength);
1545
139M
    int32_t nativeOffset = u8b->mapToNative[ut->chunkOffset + u8b->bufStartIdx] + u8b->toUCharsMapStart;
1546
139M
    U_ASSERT(nativeOffset >= ut->chunkNativeStart && nativeOffset <= ut->chunkNativeLimit);
1547
139M
    return nativeOffset;
1548
139M
}
1549
1550
//
1551
// Map a native index to the corresponding chunk offset
1552
//
1553
static int32_t U_CALLCONV
1554
27.6M
utf8TextMapIndexToUTF16(const UText *ut, int64_t index64) {
1555
27.6M
    U_ASSERT(index64 <= 0x7fffffff);
1556
27.6M
    int32_t index = (int32_t)index64;
1557
27.6M
    UTF8Buf *u8b = (UTF8Buf *)ut->p;
1558
27.6M
    U_ASSERT(index>=ut->chunkNativeStart+ut->nativeIndexingLimit);
1559
27.6M
    U_ASSERT(index<=ut->chunkNativeLimit);
1560
27.6M
    int32_t mapIndex = index - u8b->toUCharsMapStart;
1561
27.6M
    U_ASSERT(mapIndex < (int32_t)sizeof(UTF8Buf::mapToUChars));
1562
27.6M
    int32_t offset = u8b->mapToUChars[mapIndex] - u8b->bufStartIdx;
1563
27.6M
    U_ASSERT(offset>=0 && offset<=ut->chunkLength);
1564
27.6M
    return offset;
1565
27.6M
}
1566
1567
static UText * U_CALLCONV
1568
utf8TextClone(UText *dest, const UText *src, UBool deep, UErrorCode *status)
1569
3.61k
{
1570
    // First do a generic shallow clone.  Does everything needed for the UText struct itself.
1571
3.61k
    dest = shallowTextClone(dest, src, status);
1572
1573
    // For deep clones, make a copy of the string.
1574
    //  The copied storage is owned by the newly created clone.
1575
    //
1576
    // TODO:  There is an issue with using utext_nativeLength().
1577
    //        That function is non-const in cases where the input was NUL terminated
1578
    //          and the length has not yet been determined.
1579
    //        This function (clone()) is const.
1580
    //        There potentially a thread safety issue lurking here.
1581
    //
1582
3.61k
    if (deep && U_SUCCESS(*status)) {
1583
0
        int32_t  len = (int32_t)utext_nativeLength((UText *)src);
1584
0
        char *copyStr = (char *)uprv_malloc(len+1);
1585
0
        if (copyStr == nullptr) {
1586
0
            *status = U_MEMORY_ALLOCATION_ERROR;
1587
0
        } else {
1588
0
            uprv_memcpy(copyStr, src->context, len+1);
1589
0
            dest->context = copyStr;
1590
0
            dest->providerProperties |= I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT);
1591
0
        }
1592
0
    }
1593
3.61k
    return dest;
1594
3.61k
}
1595
1596
1597
static void U_CALLCONV
1598
7.31k
utf8TextClose(UText *ut) {
1599
    // Most of the work of close is done by the generic UText framework close.
1600
    // All that needs to be done here is to delete the UTF8 string if the UText
1601
    //  owns it.  This occurs if the UText was created by cloning.
1602
7.31k
    if (ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT)) {
1603
0
        char *s = (char *)ut->context;
1604
0
        uprv_free(s);
1605
0
        ut->context = nullptr;
1606
0
    }
1607
7.31k
}
1608
1609
U_CDECL_END
1610
1611
1612
static const struct UTextFuncs utf8Funcs =
1613
{
1614
    sizeof(UTextFuncs),
1615
    0, 0, 0,             // Reserved alignment padding
1616
    utf8TextClone,
1617
    utf8TextLength,
1618
    utf8TextAccess,
1619
    utf8TextExtract,
1620
    nullptr,                /* replace*/
1621
    nullptr,                /* copy   */
1622
    utf8TextMapOffsetToNative,
1623
    utf8TextMapIndexToUTF16,
1624
    utf8TextClose,
1625
    nullptr,                // spare 1
1626
    nullptr,                // spare 2
1627
    nullptr                 // spare 3
1628
};
1629
1630
1631
static const char gEmptyString[] = {0};
1632
1633
U_CAPI UText * U_EXPORT2
1634
3.69k
utext_openUTF8(UText *ut, const char *s, int64_t length, UErrorCode *status) {
1635
3.69k
    if(U_FAILURE(*status)) {
1636
0
        return nullptr;
1637
0
    }
1638
3.69k
    if(s==nullptr && length==0) {
1639
0
        s = gEmptyString;
1640
0
    }
1641
1642
3.69k
    if(s==nullptr || length<-1 || length>INT32_MAX) {
1643
0
        *status=U_ILLEGAL_ARGUMENT_ERROR;
1644
0
        return nullptr;
1645
0
    }
1646
1647
3.69k
    ut = utext_setup(ut, sizeof(UTF8Buf) * 2, status);
1648
3.69k
    if (U_FAILURE(*status)) {
1649
0
        return ut;
1650
0
    }
1651
1652
3.69k
    ut->pFuncs  = &utf8Funcs;
1653
3.69k
    ut->context = s;
1654
3.69k
    ut->b       = (int32_t)length;
1655
3.69k
    ut->c       = (int32_t)length;
1656
3.69k
    if (ut->c < 0) {
1657
0
        ut->c = 0;
1658
0
        ut->providerProperties |= I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE);
1659
0
    }
1660
3.69k
    ut->p = ut->pExtra;
1661
3.69k
    ut->q = (char *)ut->pExtra + sizeof(UTF8Buf);
1662
3.69k
    return ut;
1663
1664
3.69k
}
1665
1666
1667
1668
1669
1670
1671
1672
1673
//------------------------------------------------------------------------------
1674
//
1675
//     UText implementation wrapper for Replaceable (read/write)
1676
//
1677
//         Use of UText data members:
1678
//            context    pointer to Replaceable.
1679
//            p          pointer to Replaceable if it is owned by the UText.
1680
//
1681
//------------------------------------------------------------------------------
1682
1683
1684
1685
// minimum chunk size for this implementation: 3
1686
// to allow for possible trimming for code point boundaries
1687
enum { REP_TEXT_CHUNK_SIZE=10 };
1688
1689
struct ReplExtra {
1690
    /*
1691
     * Chunk UChars.
1692
     * +1 to simplify filling with surrogate pair at the end.
1693
     */
1694
    char16_t s[REP_TEXT_CHUNK_SIZE+1];
1695
};
1696
1697
1698
U_CDECL_BEGIN
1699
1700
static UText * U_CALLCONV
1701
0
repTextClone(UText *dest, const UText *src, UBool deep, UErrorCode *status) {
1702
    // First do a generic shallow clone.  Does everything needed for the UText struct itself.
1703
0
    dest = shallowTextClone(dest, src, status);
1704
1705
    // For deep clones, make a copy of the Replaceable.
1706
    //  The copied Replaceable storage is owned by the newly created UText clone.
1707
    //  A non-nullptr pointer in UText.p is the signal to the close() function to delete
1708
    //    it.
1709
    //
1710
0
    if (deep && U_SUCCESS(*status)) {
1711
0
        const Replaceable *replSrc = (const Replaceable *)src->context;
1712
0
        dest->context = replSrc->clone();
1713
0
        dest->providerProperties |= I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT);
1714
1715
        // with deep clone, the copy is writable, even when the source is not.
1716
0
        dest->providerProperties |= I32_FLAG(UTEXT_PROVIDER_WRITABLE);
1717
0
    }
1718
0
    return dest;
1719
0
}
1720
1721
1722
static void U_CALLCONV
1723
0
repTextClose(UText *ut) {
1724
    // Most of the work of close is done by the generic UText framework close.
1725
    // All that needs to be done here is delete the Replaceable if the UText
1726
    //  owns it.  This occurs if the UText was created by cloning.
1727
0
    if (ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT)) {
1728
0
        Replaceable *rep = (Replaceable *)ut->context;
1729
0
        delete rep;
1730
0
        ut->context = nullptr;
1731
0
    }
1732
0
}
1733
1734
1735
static int64_t U_CALLCONV
1736
0
repTextLength(UText *ut) {
1737
0
    const Replaceable *replSrc = (const Replaceable *)ut->context;
1738
0
    int32_t  len = replSrc->length();
1739
0
    return len;
1740
0
}
1741
1742
1743
static UBool U_CALLCONV
1744
0
repTextAccess(UText *ut, int64_t index, UBool forward) {
1745
0
    const Replaceable *rep=(const Replaceable *)ut->context;
1746
0
    int32_t length=rep->length();   // Full length of the input text (bigger than a chunk)
1747
1748
    // clip the requested index to the limits of the text.
1749
0
    int32_t index32 = pinIndex(index, length);
1750
0
    U_ASSERT(index<=INT32_MAX);
1751
1752
1753
    /*
1754
     * Compute start/limit boundaries around index, for a segment of text
1755
     * to be extracted.
1756
     * To allow for the possibility that our user gave an index to the trailing
1757
     * half of a surrogate pair, we must request one extra preceding char16_t when
1758
     * going in the forward direction.  This will ensure that the buffer has the
1759
     * entire code point at the specified index.
1760
     */
1761
0
    if(forward) {
1762
1763
0
        if (index32>=ut->chunkNativeStart && index32<ut->chunkNativeLimit) {
1764
            // Buffer already contains the requested position.
1765
0
            ut->chunkOffset = (int32_t)(index - ut->chunkNativeStart);
1766
0
            return true;
1767
0
        }
1768
0
        if (index32>=length && ut->chunkNativeLimit==length) {
1769
            // Request for end of string, and buffer already extends up to it.
1770
            // Can't get the data, but don't change the buffer.
1771
0
            ut->chunkOffset = length - (int32_t)ut->chunkNativeStart;
1772
0
            return false;
1773
0
        }
1774
1775
0
        ut->chunkNativeLimit = index + REP_TEXT_CHUNK_SIZE - 1;
1776
        // Going forward, so we want to have the buffer with stuff at and beyond
1777
        //   the requested index.  The -1 gets us one code point before the
1778
        //   requested index also, to handle the case of the index being on
1779
        //   a trail surrogate of a surrogate pair.
1780
0
        if(ut->chunkNativeLimit > length) {
1781
0
            ut->chunkNativeLimit = length;
1782
0
        }
1783
        // unless buffer ran off end, start is index-1.
1784
0
        ut->chunkNativeStart = ut->chunkNativeLimit - REP_TEXT_CHUNK_SIZE;
1785
0
        if(ut->chunkNativeStart < 0) {
1786
0
            ut->chunkNativeStart = 0;
1787
0
        }
1788
0
    } else {
1789
        // Reverse iteration.  Fill buffer with data preceding the requested index.
1790
0
        if (index32>ut->chunkNativeStart && index32<=ut->chunkNativeLimit) {
1791
            // Requested position already in buffer.
1792
0
            ut->chunkOffset = index32 - (int32_t)ut->chunkNativeStart;
1793
0
            return true;
1794
0
        }
1795
0
        if (index32==0 && ut->chunkNativeStart==0) {
1796
            // Request for start, buffer already begins at start.
1797
            //  No data, but keep the buffer as is.
1798
0
            ut->chunkOffset = 0;
1799
0
            return false;
1800
0
        }
1801
1802
        // Figure out the bounds of the chunk to extract for reverse iteration.
1803
        // Need to worry about chunk not splitting surrogate pairs, and while still
1804
        // containing the data we need.
1805
        // Fix by requesting a chunk that includes an extra char16_t at the end.
1806
        // If this turns out to be a lead surrogate, we can lop it off and still have
1807
        //   the data we wanted.
1808
0
        ut->chunkNativeStart = index32 + 1 - REP_TEXT_CHUNK_SIZE;
1809
0
        if (ut->chunkNativeStart < 0) {
1810
0
            ut->chunkNativeStart = 0;
1811
0
        }
1812
1813
0
        ut->chunkNativeLimit = index32 + 1;
1814
0
        if (ut->chunkNativeLimit > length) {
1815
0
            ut->chunkNativeLimit = length;
1816
0
        }
1817
0
    }
1818
1819
    // Extract the new chunk of text from the Replaceable source.
1820
0
    ReplExtra *ex = (ReplExtra *)ut->pExtra;
1821
    // UnicodeString with its buffer a writable alias to the chunk buffer
1822
0
    UnicodeString buffer(ex->s, 0 /*buffer length*/, REP_TEXT_CHUNK_SIZE /*buffer capacity*/);
1823
0
    rep->extractBetween((int32_t)ut->chunkNativeStart, (int32_t)ut->chunkNativeLimit, buffer);
1824
1825
0
    ut->chunkContents  = ex->s;
1826
0
    ut->chunkLength    = (int32_t)(ut->chunkNativeLimit - ut->chunkNativeStart);
1827
0
    ut->chunkOffset    = (int32_t)(index32 - ut->chunkNativeStart);
1828
1829
    // Surrogate pairs from the input text must not span chunk boundaries.
1830
    // If end of chunk could be the start of a surrogate, trim it off.
1831
0
    if (ut->chunkNativeLimit < length &&
1832
0
        U16_IS_LEAD(ex->s[ut->chunkLength-1])) {
1833
0
            ut->chunkLength--;
1834
0
            ut->chunkNativeLimit--;
1835
0
            if (ut->chunkOffset > ut->chunkLength) {
1836
0
                ut->chunkOffset = ut->chunkLength;
1837
0
            }
1838
0
        }
1839
1840
    // if the first char16_t in the chunk could be the trailing half of a surrogate pair,
1841
    // trim it off.
1842
0
    if(ut->chunkNativeStart>0 && U16_IS_TRAIL(ex->s[0])) {
1843
0
        ++(ut->chunkContents);
1844
0
        ++(ut->chunkNativeStart);
1845
0
        --(ut->chunkLength);
1846
0
        --(ut->chunkOffset);
1847
0
    }
1848
1849
    // adjust the index/chunkOffset to a code point boundary
1850
0
    U16_SET_CP_START(ut->chunkContents, 0, ut->chunkOffset);
1851
1852
    // Use fast indexing for get/setNativeIndex()
1853
0
    ut->nativeIndexingLimit = ut->chunkLength;
1854
1855
0
    return true;
1856
0
}
1857
1858
1859
1860
static int32_t U_CALLCONV
1861
repTextExtract(UText *ut,
1862
               int64_t start, int64_t limit,
1863
               char16_t *dest, int32_t destCapacity,
1864
0
               UErrorCode *status) {
1865
0
    const Replaceable *rep=(const Replaceable *)ut->context;
1866
0
    int32_t  length=rep->length();
1867
1868
0
    if(U_FAILURE(*status)) {
1869
0
        return 0;
1870
0
    }
1871
0
    if(destCapacity<0 || (dest==nullptr && destCapacity>0)) {
1872
0
        *status=U_ILLEGAL_ARGUMENT_ERROR;
1873
0
    }
1874
0
    if(start>limit) {
1875
0
        *status=U_INDEX_OUTOFBOUNDS_ERROR;
1876
0
        return 0;
1877
0
    }
1878
1879
0
    int32_t  start32 = pinIndex(start, length);
1880
0
    int32_t  limit32 = pinIndex(limit, length);
1881
1882
    // adjust start, limit if they point to trail half of surrogates
1883
0
    if (start32<length && U16_IS_TRAIL(rep->charAt(start32)) &&
1884
0
        U_IS_SUPPLEMENTARY(rep->char32At(start32))){
1885
0
            start32--;
1886
0
    }
1887
0
    if (limit32<length && U16_IS_TRAIL(rep->charAt(limit32)) &&
1888
0
        U_IS_SUPPLEMENTARY(rep->char32At(limit32))){
1889
0
            limit32--;
1890
0
    }
1891
1892
0
    length=limit32-start32;
1893
0
    if(length>destCapacity) {
1894
0
        limit32 = start32 + destCapacity;
1895
0
    }
1896
0
    UnicodeString buffer(dest, 0, destCapacity); // writable alias
1897
0
    rep->extractBetween(start32, limit32, buffer);
1898
0
    repTextAccess(ut, limit32, true);
1899
1900
0
    return u_terminateUChars(dest, destCapacity, length, status);
1901
0
}
1902
1903
static int32_t U_CALLCONV
1904
repTextReplace(UText *ut,
1905
               int64_t start, int64_t limit,
1906
               const char16_t *src, int32_t length,
1907
0
               UErrorCode *status) {
1908
0
    Replaceable *rep=(Replaceable *)ut->context;
1909
0
    int32_t oldLength;
1910
1911
0
    if(U_FAILURE(*status)) {
1912
0
        return 0;
1913
0
    }
1914
0
    if(src==nullptr && length!=0) {
1915
0
        *status=U_ILLEGAL_ARGUMENT_ERROR;
1916
0
        return 0;
1917
0
    }
1918
0
    oldLength=rep->length(); // will subtract from new length
1919
0
    if(start>limit ) {
1920
0
        *status=U_INDEX_OUTOFBOUNDS_ERROR;
1921
0
        return 0;
1922
0
    }
1923
1924
0
    int32_t start32 = pinIndex(start, oldLength);
1925
0
    int32_t limit32 = pinIndex(limit, oldLength);
1926
1927
    // Snap start & limit to code point boundaries.
1928
0
    if (start32<oldLength && U16_IS_TRAIL(rep->charAt(start32)) &&
1929
0
        start32>0 && U16_IS_LEAD(rep->charAt(start32-1)))
1930
0
    {
1931
0
            start32--;
1932
0
    }
1933
0
    if (limit32<oldLength && U16_IS_LEAD(rep->charAt(limit32-1)) &&
1934
0
        U16_IS_TRAIL(rep->charAt(limit32)))
1935
0
    {
1936
0
            limit32++;
1937
0
    }
1938
1939
    // Do the actual replace operation using methods of the Replaceable class
1940
0
    UnicodeString replStr(length < 0, src, length); // read-only alias
1941
0
    rep->handleReplaceBetween(start32, limit32, replStr);
1942
0
    int32_t newLength = rep->length();
1943
0
    int32_t lengthDelta = newLength - oldLength;
1944
1945
    // Is the UText chunk buffer OK?
1946
0
    if (ut->chunkNativeLimit > start32) {
1947
        // this replace operation may have impacted the current chunk.
1948
        // invalidate it, which will force a reload on the next access.
1949
0
        invalidateChunk(ut);
1950
0
    }
1951
1952
    // set the iteration position to the end of the newly inserted replacement text.
1953
0
    int32_t newIndexPos = limit32 + lengthDelta;
1954
0
    repTextAccess(ut, newIndexPos, true);
1955
1956
0
    return lengthDelta;
1957
0
}
1958
1959
1960
static void U_CALLCONV
1961
repTextCopy(UText *ut,
1962
                int64_t start, int64_t limit,
1963
                int64_t destIndex,
1964
                UBool move,
1965
                UErrorCode *status)
1966
0
{
1967
0
    Replaceable *rep=(Replaceable *)ut->context;
1968
0
    int32_t length=rep->length();
1969
1970
0
    if(U_FAILURE(*status)) {
1971
0
        return;
1972
0
    }
1973
0
    if (start>limit || (start<destIndex && destIndex<limit))
1974
0
    {
1975
0
        *status=U_INDEX_OUTOFBOUNDS_ERROR;
1976
0
        return;
1977
0
    }
1978
1979
0
    int32_t start32     = pinIndex(start, length);
1980
0
    int32_t limit32     = pinIndex(limit, length);
1981
0
    int32_t destIndex32 = pinIndex(destIndex, length);
1982
1983
    // TODO:  snap input parameters to code point boundaries.
1984
1985
0
    if(move) {
1986
        // move: copy to destIndex, then replace original with nothing
1987
0
        int32_t segLength=limit32-start32;
1988
0
        rep->copy(start32, limit32, destIndex32);
1989
0
        if(destIndex32<start32) {
1990
0
            start32+=segLength;
1991
0
            limit32+=segLength;
1992
0
        }
1993
0
        rep->handleReplaceBetween(start32, limit32, UnicodeString());
1994
0
    } else {
1995
        // copy
1996
0
        rep->copy(start32, limit32, destIndex32);
1997
0
    }
1998
1999
    // If the change to the text touched the region in the chunk buffer,
2000
    //  invalidate the buffer.
2001
0
    int32_t firstAffectedIndex = destIndex32;
2002
0
    if (move && start32<firstAffectedIndex) {
2003
0
        firstAffectedIndex = start32;
2004
0
    }
2005
0
    if (firstAffectedIndex < ut->chunkNativeLimit) {
2006
        // changes may have affected range covered by the chunk
2007
0
        invalidateChunk(ut);
2008
0
    }
2009
2010
    // Put iteration position at the newly inserted (moved) block,
2011
0
    int32_t  nativeIterIndex = destIndex32 + limit32 - start32;
2012
0
    if (move && destIndex32>start32) {
2013
        // moved a block of text towards the end of the string.
2014
0
        nativeIterIndex = destIndex32;
2015
0
    }
2016
2017
    // Set position, reload chunk if needed.
2018
0
    repTextAccess(ut, nativeIterIndex, true);
2019
0
}
2020
2021
static const struct UTextFuncs repFuncs =
2022
{
2023
    sizeof(UTextFuncs),
2024
    0, 0, 0,           // Reserved alignment padding
2025
    repTextClone,
2026
    repTextLength,
2027
    repTextAccess,
2028
    repTextExtract,
2029
    repTextReplace,
2030
    repTextCopy,
2031
    nullptr,              // MapOffsetToNative,
2032
    nullptr,              // MapIndexToUTF16,
2033
    repTextClose,
2034
    nullptr,              // spare 1
2035
    nullptr,              // spare 2
2036
    nullptr               // spare 3
2037
};
2038
2039
2040
U_CAPI UText * U_EXPORT2
2041
utext_openReplaceable(UText *ut, Replaceable *rep, UErrorCode *status)
2042
0
{
2043
0
    if(U_FAILURE(*status)) {
2044
0
        return nullptr;
2045
0
    }
2046
0
    if(rep==nullptr) {
2047
0
        *status=U_ILLEGAL_ARGUMENT_ERROR;
2048
0
        return nullptr;
2049
0
    }
2050
0
    ut = utext_setup(ut, sizeof(ReplExtra), status);
2051
0
    if(U_FAILURE(*status)) {
2052
0
        return ut;
2053
0
    }
2054
2055
0
    ut->providerProperties = I32_FLAG(UTEXT_PROVIDER_WRITABLE);
2056
0
    if(rep->hasMetaData()) {
2057
0
        ut->providerProperties |=I32_FLAG(UTEXT_PROVIDER_HAS_META_DATA);
2058
0
    }
2059
2060
0
    ut->pFuncs  = &repFuncs;
2061
0
    ut->context =  rep;
2062
0
    return ut;
2063
0
}
2064
2065
U_CDECL_END
2066
2067
2068
2069
2070
2071
2072
2073
2074
//------------------------------------------------------------------------------
2075
//
2076
//     UText implementation for UnicodeString (read/write)  and
2077
//                    for const UnicodeString (read only)
2078
//             (same implementation, only the flags are different)
2079
//
2080
//         Use of UText data members:
2081
//            context    pointer to UnicodeString
2082
//            p          pointer to UnicodeString IF this UText owns the string
2083
//                       and it must be deleted on close().  nullptr otherwise.
2084
//
2085
//------------------------------------------------------------------------------
2086
2087
U_CDECL_BEGIN
2088
2089
2090
static UText * U_CALLCONV
2091
15.6k
unistrTextClone(UText *dest, const UText *src, UBool deep, UErrorCode *status) {
2092
    // First do a generic shallow clone.  Does everything needed for the UText struct itself.
2093
15.6k
    dest = shallowTextClone(dest, src, status);
2094
2095
    // For deep clones, make a copy of the UnicodeSring.
2096
    //  The copied UnicodeString storage is owned by the newly created UText clone.
2097
    //  A non-nullptr pointer in UText.p is the signal to the close() function to delete
2098
    //    the UText.
2099
    //
2100
15.6k
    if (deep && U_SUCCESS(*status)) {
2101
0
        const UnicodeString *srcString = (const UnicodeString *)src->context;
2102
0
        dest->context = new UnicodeString(*srcString);
2103
0
        dest->providerProperties |= I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT);
2104
2105
        // with deep clone, the copy is writable, even when the source is not.
2106
0
        dest->providerProperties |= I32_FLAG(UTEXT_PROVIDER_WRITABLE);
2107
0
    }
2108
15.6k
    return dest;
2109
15.6k
}
2110
2111
static void U_CALLCONV
2112
4.75M
unistrTextClose(UText *ut) {
2113
    // Most of the work of close is done by the generic UText framework close.
2114
    // All that needs to be done here is delete the UnicodeString if the UText
2115
    //  owns it.  This occurs if the UText was created by cloning.
2116
4.75M
    if (ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT)) {
2117
0
        UnicodeString *str = (UnicodeString *)ut->context;
2118
0
        delete str;
2119
0
        ut->context = nullptr;
2120
0
    }
2121
4.75M
}
2122
2123
2124
static int64_t U_CALLCONV
2125
23.3k
unistrTextLength(UText *t) {
2126
23.3k
    return ((const UnicodeString *)t->context)->length();
2127
23.3k
}
2128
2129
2130
static UBool U_CALLCONV
2131
2.27M
unistrTextAccess(UText *ut, int64_t index, UBool  forward) {
2132
2.27M
    int32_t length  = ut->chunkLength;
2133
2.27M
    ut->chunkOffset = pinIndex(index, length);
2134
2135
    // Check whether request is at the start or end
2136
2.27M
    UBool retVal = (forward && index<length) || (!forward && index>0);
2137
2.27M
    return retVal;
2138
2.27M
}
2139
2140
2141
2142
static int32_t U_CALLCONV
2143
unistrTextExtract(UText *t,
2144
                  int64_t start, int64_t limit,
2145
                  char16_t *dest, int32_t destCapacity,
2146
3.28k
                  UErrorCode *pErrorCode) {
2147
3.28k
    const UnicodeString *us=(const UnicodeString *)t->context;
2148
3.28k
    int32_t length=us->length();
2149
2150
3.28k
    if(U_FAILURE(*pErrorCode)) {
2151
662
        return 0;
2152
662
    }
2153
2.61k
    if(destCapacity<0 || (dest==nullptr && destCapacity>0)) {
2154
0
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
2155
0
    }
2156
2.61k
    if(start<0 || start>limit) {
2157
662
        *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
2158
662
        return 0;
2159
662
    }
2160
2161
1.95k
    int32_t start32 = start<length ? us->getChar32Start((int32_t)start) : length;
2162
1.95k
    int32_t limit32 = limit<length ? us->getChar32Start((int32_t)limit) : length;
2163
2164
1.95k
    length=limit32-start32;
2165
1.95k
    if (destCapacity>0 && dest!=nullptr) {
2166
1.95k
        int32_t trimmedLength = length;
2167
1.95k
        if(trimmedLength>destCapacity) {
2168
0
            trimmedLength=destCapacity;
2169
0
        }
2170
1.95k
        us->extract(start32, trimmedLength, dest);
2171
1.95k
        t->chunkOffset = start32+trimmedLength;
2172
1.95k
    } else {
2173
0
        t->chunkOffset = start32;
2174
0
    }
2175
1.95k
    u_terminateUChars(dest, destCapacity, length, pErrorCode);
2176
1.95k
    return length;
2177
2.61k
}
2178
2179
static int32_t U_CALLCONV
2180
unistrTextReplace(UText *ut,
2181
                  int64_t start, int64_t limit,
2182
                  const char16_t *src, int32_t length,
2183
0
                  UErrorCode *pErrorCode) {
2184
0
    UnicodeString *us=(UnicodeString *)ut->context;
2185
0
    int32_t oldLength;
2186
2187
0
    if(U_FAILURE(*pErrorCode)) {
2188
0
        return 0;
2189
0
    }
2190
0
    if(src==nullptr && length!=0) {
2191
0
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
2192
0
    }
2193
0
    if(start>limit) {
2194
0
        *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
2195
0
        return 0;
2196
0
    }
2197
0
    oldLength=us->length();
2198
0
    int32_t start32 = pinIndex(start, oldLength);
2199
0
    int32_t limit32 = pinIndex(limit, oldLength);
2200
0
    if (start32 < oldLength) {
2201
0
        start32 = us->getChar32Start(start32);
2202
0
    }
2203
0
    if (limit32 < oldLength) {
2204
0
        limit32 = us->getChar32Start(limit32);
2205
0
    }
2206
2207
    // replace
2208
0
    us->replace(start32, limit32-start32, src, length);
2209
0
    int32_t newLength = us->length();
2210
2211
    // Update the chunk description.
2212
0
    ut->chunkContents    = us->getBuffer();
2213
0
    ut->chunkLength      = newLength;
2214
0
    ut->chunkNativeLimit = newLength;
2215
0
    ut->nativeIndexingLimit = newLength;
2216
2217
    // Set iteration position to the point just following the newly inserted text.
2218
0
    int32_t lengthDelta = newLength - oldLength;
2219
0
    ut->chunkOffset = limit32 + lengthDelta;
2220
2221
0
    return lengthDelta;
2222
0
}
2223
2224
static void U_CALLCONV
2225
unistrTextCopy(UText *ut,
2226
               int64_t start, int64_t limit,
2227
               int64_t destIndex,
2228
               UBool move,
2229
0
               UErrorCode *pErrorCode) {
2230
0
    UnicodeString *us=(UnicodeString *)ut->context;
2231
0
    int32_t length=us->length();
2232
2233
0
    if(U_FAILURE(*pErrorCode)) {
2234
0
        return;
2235
0
    }
2236
0
    int32_t start32 = pinIndex(start, length);
2237
0
    int32_t limit32 = pinIndex(limit, length);
2238
0
    int32_t destIndex32 = pinIndex(destIndex, length);
2239
2240
0
    if( start32>limit32 || (start32<destIndex32 && destIndex32<limit32)) {
2241
0
        *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
2242
0
        return;
2243
0
    }
2244
2245
0
    if(move) {
2246
        // move: copy to destIndex, then remove original
2247
0
        int32_t segLength=limit32-start32;
2248
0
        us->copy(start32, limit32, destIndex32);
2249
0
        if(destIndex32<start32) {
2250
0
            start32+=segLength;
2251
0
        }
2252
0
        us->remove(start32, segLength);
2253
0
    } else {
2254
        // copy
2255
0
        us->copy(start32, limit32, destIndex32);
2256
0
    }
2257
2258
    // update chunk description, set iteration position.
2259
0
    ut->chunkContents = us->getBuffer();
2260
0
    if (move==false) {
2261
        // copy operation, string length grows
2262
0
        ut->chunkLength += limit32-start32;
2263
0
        ut->chunkNativeLimit = ut->chunkLength;
2264
0
        ut->nativeIndexingLimit = ut->chunkLength;
2265
0
    }
2266
2267
    // Iteration position to end of the newly inserted text.
2268
0
    ut->chunkOffset = destIndex32+limit32-start32;
2269
0
    if (move && destIndex32>start32) {
2270
0
        ut->chunkOffset = destIndex32;
2271
0
    }
2272
2273
0
}
2274
2275
static const struct UTextFuncs unistrFuncs =
2276
{
2277
    sizeof(UTextFuncs),
2278
    0, 0, 0,             // Reserved alignment padding
2279
    unistrTextClone,
2280
    unistrTextLength,
2281
    unistrTextAccess,
2282
    unistrTextExtract,
2283
    unistrTextReplace,
2284
    unistrTextCopy,
2285
    nullptr,                // MapOffsetToNative,
2286
    nullptr,                // MapIndexToUTF16,
2287
    unistrTextClose,
2288
    nullptr,                // spare 1
2289
    nullptr,                // spare 2
2290
    nullptr                 // spare 3
2291
};
2292
2293
2294
2295
U_CDECL_END
2296
2297
2298
U_CAPI UText * U_EXPORT2
2299
4.71M
utext_openUnicodeString(UText *ut, UnicodeString *s, UErrorCode *status) {
2300
4.71M
    ut = utext_openConstUnicodeString(ut, s, status);
2301
4.71M
    if (U_SUCCESS(*status)) {
2302
4.71M
        ut->providerProperties |= I32_FLAG(UTEXT_PROVIDER_WRITABLE);
2303
4.71M
    }
2304
4.71M
    return ut;
2305
4.71M
}
2306
2307
2308
2309
U_CAPI UText * U_EXPORT2
2310
4.73M
utext_openConstUnicodeString(UText *ut, const UnicodeString *s, UErrorCode *status) {
2311
4.73M
    if (U_SUCCESS(*status) && s->isBogus()) {
2312
        // The UnicodeString is bogus, but we still need to detach the UText
2313
        //   from whatever it was hooked to before, if anything.
2314
0
        utext_openUChars(ut, nullptr, 0, status);
2315
0
        *status = U_ILLEGAL_ARGUMENT_ERROR;
2316
0
        return ut;
2317
0
    }
2318
4.73M
    ut = utext_setup(ut, 0, status);
2319
    //    note:  use the standard (writable) function table for UnicodeString.
2320
    //           The flag settings disable writing, so having the functions in
2321
    //           the table is harmless.
2322
4.73M
    if (U_SUCCESS(*status)) {
2323
4.73M
        ut->pFuncs              = &unistrFuncs;
2324
4.73M
        ut->context             = s;
2325
4.73M
        ut->providerProperties  = I32_FLAG(UTEXT_PROVIDER_STABLE_CHUNKS);
2326
4.73M
        ut->chunkContents       = s->getBuffer();
2327
4.73M
        ut->chunkLength         = s->length();
2328
4.73M
        ut->chunkNativeStart    = 0;
2329
4.73M
        ut->chunkNativeLimit    = ut->chunkLength;
2330
4.73M
        ut->nativeIndexingLimit = ut->chunkLength;
2331
4.73M
    }
2332
4.73M
    return ut;
2333
4.73M
}
2334
2335
//------------------------------------------------------------------------------
2336
//
2337
//     UText implementation for const char16_t * strings
2338
//
2339
//         Use of UText data members:
2340
//            context    pointer to UnicodeString
2341
//            a          length.  -1 if not yet known.
2342
//
2343
//         TODO:  support 64 bit lengths.
2344
//
2345
//------------------------------------------------------------------------------
2346
2347
U_CDECL_BEGIN
2348
2349
2350
static UText * U_CALLCONV
2351
37.4k
ucstrTextClone(UText *dest, const UText * src, UBool deep, UErrorCode * status) {
2352
    // First do a generic shallow clone.
2353
37.4k
    dest = shallowTextClone(dest, src, status);
2354
2355
    // For deep clones, make a copy of the string.
2356
    //  The copied storage is owned by the newly created clone.
2357
    //  A non-nullptr pointer in UText.p is the signal to the close() function to delete
2358
    //    it.
2359
    //
2360
37.4k
    if (deep && U_SUCCESS(*status)) {
2361
0
        U_ASSERT(utext_nativeLength(dest) < INT32_MAX);
2362
0
        int32_t  len = (int32_t)utext_nativeLength(dest);
2363
2364
        // The cloned string IS going to be NUL terminated, whether or not the original was.
2365
0
        const char16_t *srcStr = (const char16_t *)src->context;
2366
0
        char16_t *copyStr = (char16_t *)uprv_malloc((len+1) * sizeof(char16_t));
2367
0
        if (copyStr == nullptr) {
2368
0
            *status = U_MEMORY_ALLOCATION_ERROR;
2369
0
        } else {
2370
0
            int64_t i;
2371
0
            for (i=0; i<len; i++) {
2372
0
                copyStr[i] = srcStr[i];
2373
0
            }
2374
0
            copyStr[len] = 0;
2375
0
            dest->context = copyStr;
2376
0
            dest->providerProperties |= I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT);
2377
0
        }
2378
0
    }
2379
37.4k
    return dest;
2380
37.4k
}
2381
2382
2383
static void U_CALLCONV
2384
88.8k
ucstrTextClose(UText *ut) {
2385
    // Most of the work of close is done by the generic UText framework close.
2386
    // All that needs to be done here is delete the string if the UText
2387
    //  owns it.  This occurs if the UText was created by cloning.
2388
88.8k
    if (ut->providerProperties & I32_FLAG(UTEXT_PROVIDER_OWNS_TEXT)) {
2389
0
        char16_t *s = (char16_t *)ut->context;
2390
0
        uprv_free(s);
2391
0
        ut->context = nullptr;
2392
0
    }
2393
88.8k
}
2394
2395
2396
2397
static int64_t U_CALLCONV
2398
27.0k
ucstrTextLength(UText *ut) {
2399
27.0k
    if (ut->a < 0) {
2400
        // null terminated, we don't yet know the length. Scan for it.
2401
        //    Access is not convenient for doing this
2402
        //    because the current iteration position can't be changed.
2403
0
        const char16_t  *str = (const char16_t *)ut->context;
2404
0
        for (;;) {
2405
0
            if (str[ut->chunkNativeLimit] == 0) {
2406
0
                break;
2407
0
            }
2408
0
            ut->chunkNativeLimit++;
2409
0
        }
2410
0
        ut->a = ut->chunkNativeLimit;
2411
0
        ut->chunkLength = (int32_t)ut->chunkNativeLimit;
2412
0
        ut->nativeIndexingLimit = ut->chunkLength;
2413
0
        ut->providerProperties &= ~I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE);
2414
0
    }
2415
27.0k
    return ut->a;
2416
27.0k
}
2417
2418
2419
static UBool U_CALLCONV
2420
75.0k
ucstrTextAccess(UText *ut, int64_t index, UBool  forward) {
2421
75.0k
    const char16_t *str   = (const char16_t *)ut->context;
2422
2423
    // pin the requested index to the bounds of the string,
2424
    //  and set current iteration position.
2425
75.0k
    if (index<0) {
2426
2.78k
        index = 0;
2427
72.2k
    } else if (index < ut->chunkNativeLimit) {
2428
        // The request data is within the chunk as it is known so far.
2429
        // Put index on a code point boundary.
2430
6.85k
        U16_SET_CP_START(str, 0, index);
2431
65.3k
    } else if (ut->a >= 0) {
2432
        // We know the length of this string, and the user is requesting something
2433
        // at or beyond the length.  Pin the requested index to the length.
2434
65.3k
        index = ut->a;
2435
65.3k
    } else {
2436
        // Null terminated string, length not yet known, and the requested index
2437
        //  is beyond where we have scanned so far.
2438
        //  Scan to 32 UChars beyond the requested index.  The strategy here is
2439
        //  to avoid fully scanning a long string when the caller only wants to
2440
        //  see a few characters at its beginning.
2441
0
        int32_t scanLimit = (int32_t)index + 32;
2442
0
        if ((index + 32)>INT32_MAX || (index + 32)<0 ) {   // note: int64 expression
2443
0
            scanLimit = INT32_MAX;
2444
0
        }
2445
2446
0
        int32_t chunkLimit = (int32_t)ut->chunkNativeLimit;
2447
0
        for (; chunkLimit<scanLimit; chunkLimit++) {
2448
0
            if (str[chunkLimit] == 0) {
2449
                // We found the end of the string.  Remember it, pin the requested index to it,
2450
                //  and bail out of here.
2451
0
                ut->a = chunkLimit;
2452
0
                ut->chunkLength = chunkLimit;
2453
0
                ut->nativeIndexingLimit = chunkLimit;
2454
0
                if (index >= chunkLimit) {
2455
0
                    index = chunkLimit;
2456
0
                } else {
2457
0
                    U16_SET_CP_START(str, 0, index);
2458
0
                }
2459
2460
0
                ut->chunkNativeLimit = chunkLimit;
2461
0
                ut->providerProperties &= ~I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE);
2462
0
                goto breakout;
2463
0
            }
2464
0
        }
2465
        // We scanned through the next batch of UChars without finding the end.
2466
0
        U16_SET_CP_START(str, 0, index);
2467
0
        if (chunkLimit == INT32_MAX) {
2468
            // Scanned to the limit of a 32 bit length.
2469
            // Forceably trim the overlength string back so length fits in int32
2470
            //  TODO:  add support for 64 bit strings.
2471
0
            ut->a = chunkLimit;
2472
0
            ut->chunkLength = chunkLimit;
2473
0
            ut->nativeIndexingLimit = chunkLimit;
2474
0
            if (index > chunkLimit) {
2475
0
                index = chunkLimit;
2476
0
            }
2477
0
            ut->chunkNativeLimit = chunkLimit;
2478
0
            ut->providerProperties &= ~I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE);
2479
0
        } else {
2480
            // The endpoint of a chunk must not be left in the middle of a surrogate pair.
2481
            // If the current end is on a lead surrogate, back the end up by one.
2482
            // It doesn't matter if the end char happens to be an unpaired surrogate,
2483
            //    and it's simpler not to worry about it.
2484
0
            if (U16_IS_LEAD(str[chunkLimit-1])) {
2485
0
                --chunkLimit;
2486
0
            }
2487
            // Null-terminated chunk with end still unknown.
2488
            // Update the chunk length to reflect what has been scanned thus far.
2489
            // That the full length is still unknown is (still) flagged by
2490
            //    ut->a being < 0.
2491
0
            ut->chunkNativeLimit = chunkLimit;
2492
0
            ut->nativeIndexingLimit = chunkLimit;
2493
0
            ut->chunkLength = chunkLimit;
2494
0
        }
2495
2496
0
    }
2497
75.0k
breakout:
2498
75.0k
    U_ASSERT(index<=INT32_MAX);
2499
75.0k
    ut->chunkOffset = (int32_t)index;
2500
2501
    // Check whether request is at the start or end
2502
75.0k
    UBool retVal = (forward && index<ut->chunkNativeLimit) || (!forward && index>0);
2503
75.0k
    return retVal;
2504
75.0k
}
2505
2506
2507
2508
static int32_t U_CALLCONV
2509
ucstrTextExtract(UText *ut,
2510
                  int64_t start, int64_t limit,
2511
                  char16_t *dest, int32_t destCapacity,
2512
                  UErrorCode *pErrorCode)
2513
13.4k
{
2514
13.4k
    if(U_FAILURE(*pErrorCode)) {
2515
0
        return 0;
2516
0
    }
2517
13.4k
    if(destCapacity<0 || (dest==nullptr && destCapacity>0) || start>limit) {
2518
0
        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
2519
0
        return 0;
2520
0
    }
2521
2522
    //const char16_t *s=(const char16_t *)ut->context;
2523
13.4k
    int32_t si, di;
2524
2525
13.4k
    int32_t start32;
2526
13.4k
    int32_t limit32;
2527
2528
    // Access the start.  Does two things we need:
2529
    //   Pins 'start' to the length of the string, if it came in out-of-bounds.
2530
    //   Snaps 'start' to the beginning of a code point.
2531
13.4k
    ucstrTextAccess(ut, start, true);
2532
13.4k
    const char16_t *s=ut->chunkContents;
2533
13.4k
    start32 = ut->chunkOffset;
2534
2535
13.4k
    int32_t strLength=(int32_t)ut->a;
2536
13.4k
    if (strLength >= 0) {
2537
13.4k
        limit32 = pinIndex(limit, strLength);
2538
13.4k
    } else {
2539
0
        limit32 = pinIndex(limit, INT32_MAX);
2540
0
    }
2541
13.4k
    di = 0;
2542
102k
    for (si=start32; si<limit32; si++) {
2543
88.6k
        if (strLength<0 && s[si]==0) {
2544
            // Just hit the end of a null-terminated string.
2545
0
            ut->a = si;               // set string length for this UText
2546
0
            ut->chunkNativeLimit    = si;
2547
0
            ut->chunkLength         = si;
2548
0
            ut->nativeIndexingLimit = si;
2549
0
            strLength               = si;
2550
0
            limit32                 = si;
2551
0
            break;
2552
0
        }
2553
88.6k
        U_ASSERT(di>=0); /* to ensure di never exceeds INT32_MAX, which must not happen logically */
2554
88.6k
        if (di<destCapacity) {
2555
            // only store if there is space.
2556
88.6k
            dest[di] = s[si];
2557
88.6k
        } else {
2558
0
            if (strLength>=0) {
2559
                // We have filled the destination buffer, and the string length is known.
2560
                //  Cut the loop short.  There is no need to scan string termination.
2561
0
                di = limit32 - start32;
2562
0
                si = limit32;
2563
0
                break;
2564
0
            }
2565
0
        }
2566
88.6k
        di++;
2567
88.6k
    }
2568
2569
    // If the limit index points to a lead surrogate of a pair,
2570
    //   add the corresponding trail surrogate to the destination.
2571
13.4k
    if (si>0 && U16_IS_LEAD(s[si-1]) &&
2572
13.4k
            ((si<strLength || strLength<0)  && U16_IS_TRAIL(s[si])))
2573
3
    {
2574
3
        if (di<destCapacity) {
2575
            // store only if there is space in the output buffer.
2576
3
            dest[di++] = s[si];
2577
3
        }
2578
3
        si++;
2579
3
    }
2580
2581
    // Put iteration position at the point just following the extracted text
2582
13.4k
    if (si <= ut->chunkNativeLimit) {
2583
13.4k
        ut->chunkOffset = si;
2584
13.4k
    } else {
2585
0
        ucstrTextAccess(ut, si, true);
2586
0
    }
2587
2588
    // Add a terminating NUL if space in the buffer permits,
2589
    // and set the error status as required.
2590
13.4k
    u_terminateUChars(dest, destCapacity, di, pErrorCode);
2591
13.4k
    return di;
2592
13.4k
}
2593
2594
static const struct UTextFuncs ucstrFuncs =
2595
{
2596
    sizeof(UTextFuncs),
2597
    0, 0, 0,           // Reserved alignment padding
2598
    ucstrTextClone,
2599
    ucstrTextLength,
2600
    ucstrTextAccess,
2601
    ucstrTextExtract,
2602
    nullptr,              // Replace
2603
    nullptr,              // Copy
2604
    nullptr,              // MapOffsetToNative,
2605
    nullptr,              // MapIndexToUTF16,
2606
    ucstrTextClose,
2607
    nullptr,              // spare 1
2608
    nullptr,              // spare 2
2609
    nullptr,              // spare 3
2610
};
2611
2612
U_CDECL_END
2613
2614
static const char16_t gEmptyUString[] = {0};
2615
2616
U_CAPI UText * U_EXPORT2
2617
51.4k
utext_openUChars(UText *ut, const char16_t *s, int64_t length, UErrorCode *status) {
2618
51.4k
    if (U_FAILURE(*status)) {
2619
0
        return nullptr;
2620
0
    }
2621
51.4k
    if(s==nullptr && length==0) {
2622
32.4k
        s = gEmptyUString;
2623
32.4k
    }
2624
51.4k
    if (s==nullptr || length < -1 || length>INT32_MAX) {
2625
0
        *status = U_ILLEGAL_ARGUMENT_ERROR;
2626
0
        return nullptr;
2627
0
    }
2628
51.4k
    ut = utext_setup(ut, 0, status);
2629
51.4k
    if (U_SUCCESS(*status)) {
2630
51.4k
        ut->pFuncs               = &ucstrFuncs;
2631
51.4k
        ut->context              = s;
2632
51.4k
        ut->providerProperties   = I32_FLAG(UTEXT_PROVIDER_STABLE_CHUNKS);
2633
51.4k
        if (length==-1) {
2634
0
            ut->providerProperties |= I32_FLAG(UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE);
2635
0
        }
2636
51.4k
        ut->a                    = length;
2637
51.4k
        ut->chunkContents        = s;
2638
51.4k
        ut->chunkNativeStart     = 0;
2639
51.4k
        ut->chunkNativeLimit     = length>=0? length : 0;
2640
51.4k
        ut->chunkLength          = (int32_t)ut->chunkNativeLimit;
2641
51.4k
        ut->chunkOffset          = 0;
2642
51.4k
        ut->nativeIndexingLimit  = ut->chunkLength;
2643
51.4k
    }
2644
51.4k
    return ut;
2645
51.4k
}
2646
2647
2648
//------------------------------------------------------------------------------
2649
//
2650
//     UText implementation for text from ICU CharacterIterators
2651
//
2652
//         Use of UText data members:
2653
//            context    pointer to the CharacterIterator
2654
//            a          length of the full text.
2655
//            p          pointer to  buffer 1
2656
//            b          start index of local buffer 1 contents
2657
//            q          pointer to buffer 2
2658
//            c          start index of local buffer 2 contents
2659
//            r          pointer to the character iterator if the UText owns it.
2660
//                       Null otherwise.
2661
//
2662
//------------------------------------------------------------------------------
2663
0
#define CIBufSize 16
2664
2665
U_CDECL_BEGIN
2666
static void U_CALLCONV
2667
0
charIterTextClose(UText *ut) {
2668
    // Most of the work of close is done by the generic UText framework close.
2669
    // All that needs to be done here is delete the CharacterIterator if the UText
2670
    //  owns it.  This occurs if the UText was created by cloning.
2671
0
    CharacterIterator *ci = (CharacterIterator *)ut->r;
2672
0
    delete ci;
2673
0
    ut->r = nullptr;
2674
0
}
2675
2676
static int64_t U_CALLCONV
2677
0
charIterTextLength(UText *ut) {
2678
0
    return (int32_t)ut->a;
2679
0
}
2680
2681
static UBool U_CALLCONV
2682
0
charIterTextAccess(UText *ut, int64_t index, UBool  forward) {
2683
0
    CharacterIterator *ci   = (CharacterIterator *)ut->context;
2684
2685
0
    int32_t clippedIndex = (int32_t)index;
2686
0
    if (clippedIndex<0) {
2687
0
        clippedIndex=0;
2688
0
    } else if (clippedIndex>=ut->a) {
2689
0
        clippedIndex=(int32_t)ut->a;
2690
0
    }
2691
0
    int32_t neededIndex = clippedIndex;
2692
0
    if (!forward && neededIndex>0) {
2693
        // reverse iteration, want the position just before what was asked for.
2694
0
        neededIndex--;
2695
0
    } else if (forward && neededIndex==ut->a && neededIndex>0) {
2696
        // Forward iteration, don't ask for something past the end of the text.
2697
0
        neededIndex--;
2698
0
    }
2699
2700
    // Find the native index of the start of the buffer containing what we want.
2701
0
    neededIndex -= neededIndex % CIBufSize;
2702
2703
0
    char16_t *buf = nullptr;
2704
0
    UBool  needChunkSetup = true;
2705
0
    int    i;
2706
0
    if (ut->chunkNativeStart == neededIndex) {
2707
        // The buffer we want is already the current chunk.
2708
0
        needChunkSetup = false;
2709
0
    } else if (ut->b == neededIndex) {
2710
        // The first buffer (buffer p) has what we need.
2711
0
        buf = (char16_t *)ut->p;
2712
0
    } else if (ut->c == neededIndex) {
2713
        // The second buffer (buffer q) has what we need.
2714
0
        buf = (char16_t *)ut->q;
2715
0
    } else {
2716
        // Neither buffer already has what we need.
2717
        // Load new data from the character iterator.
2718
        // Use the buf that is not the current buffer.
2719
0
        buf = (char16_t *)ut->p;
2720
0
        if (ut->p == ut->chunkContents) {
2721
0
            buf = (char16_t *)ut->q;
2722
0
        }
2723
0
        ci->setIndex(neededIndex);
2724
0
        for (i=0; i<CIBufSize; i++) {
2725
0
            buf[i] = ci->nextPostInc();
2726
0
            if (i+neededIndex > ut->a) {
2727
0
                break;
2728
0
            }
2729
0
        }
2730
0
    }
2731
2732
    // We have a buffer with the data we need.
2733
    // Set it up as the current chunk, if it wasn't already.
2734
0
    if (needChunkSetup) {
2735
0
        ut->chunkContents = buf;
2736
0
        ut->chunkLength   = CIBufSize;
2737
0
        ut->chunkNativeStart = neededIndex;
2738
0
        ut->chunkNativeLimit = neededIndex + CIBufSize;
2739
0
        if (ut->chunkNativeLimit > ut->a) {
2740
0
            ut->chunkNativeLimit = ut->a;
2741
0
            ut->chunkLength  = (int32_t)(ut->chunkNativeLimit)-(int32_t)(ut->chunkNativeStart);
2742
0
        }
2743
0
        ut->nativeIndexingLimit = ut->chunkLength;
2744
0
        U_ASSERT(ut->chunkOffset>=0 && ut->chunkOffset<=CIBufSize);
2745
0
    }
2746
0
    ut->chunkOffset = clippedIndex - (int32_t)ut->chunkNativeStart;
2747
0
    UBool success = (forward? ut->chunkOffset<ut->chunkLength : ut->chunkOffset>0);
2748
0
    return success;
2749
0
}
2750
2751
static UText * U_CALLCONV
2752
0
charIterTextClone(UText *dest, const UText *src, UBool deep, UErrorCode * status) {
2753
0
    if (U_FAILURE(*status)) {
2754
0
        return nullptr;
2755
0
    }
2756
2757
0
    if (deep) {
2758
        // There is no CharacterIterator API for cloning the underlying text storage.
2759
0
        *status = U_UNSUPPORTED_ERROR;
2760
0
        return nullptr;
2761
0
    } else {
2762
0
        CharacterIterator *srcCI =(CharacterIterator *)src->context;
2763
0
        srcCI = srcCI->clone();
2764
0
        dest = utext_openCharacterIterator(dest, srcCI, status);
2765
0
        if (U_FAILURE(*status)) {
2766
0
            return dest;
2767
0
        }
2768
        // cast off const on getNativeIndex.
2769
        //   For CharacterIterator based UTexts, this is safe, the operation is const.
2770
0
        int64_t  ix = utext_getNativeIndex((UText *)src);
2771
0
        utext_setNativeIndex(dest, ix);
2772
0
        dest->r = srcCI;    // flags that this UText owns the CharacterIterator
2773
0
    }
2774
0
    return dest;
2775
0
}
2776
2777
static int32_t U_CALLCONV
2778
charIterTextExtract(UText *ut,
2779
                  int64_t start, int64_t limit,
2780
                  char16_t *dest, int32_t destCapacity,
2781
                  UErrorCode *status)
2782
0
{
2783
0
    if(U_FAILURE(*status)) {
2784
0
        return 0;
2785
0
    }
2786
0
    if(destCapacity<0 || (dest==nullptr && destCapacity>0) || start>limit) {
2787
0
        *status=U_ILLEGAL_ARGUMENT_ERROR;
2788
0
        return 0;
2789
0
    }
2790
0
    int32_t  length  = (int32_t)ut->a;
2791
0
    int32_t  start32 = pinIndex(start, length);
2792
0
    int32_t  limit32 = pinIndex(limit, length);
2793
0
    int32_t  desti   = 0;
2794
0
    int32_t  srci;
2795
0
    int32_t  copyLimit;
2796
2797
0
    CharacterIterator *ci = (CharacterIterator *)ut->context;
2798
0
    ci->setIndex32(start32);   // Moves ix to lead of surrogate pair, if needed.
2799
0
    srci = ci->getIndex();
2800
0
    copyLimit = srci;
2801
0
    while (srci<limit32) {
2802
0
        UChar32 c = ci->next32PostInc();
2803
0
        int32_t  len = U16_LENGTH(c);
2804
0
        U_ASSERT(desti+len>0); /* to ensure desti+len never exceeds MAX_INT32, which must not happen logically */
2805
0
        if (desti+len <= destCapacity) {
2806
0
            U16_APPEND_UNSAFE(dest, desti, c);
2807
0
            copyLimit = srci+len;
2808
0
        } else {
2809
0
            desti += len;
2810
0
            *status = U_BUFFER_OVERFLOW_ERROR;
2811
0
        }
2812
0
        srci += len;
2813
0
    }
2814
2815
0
    charIterTextAccess(ut, copyLimit, true);
2816
2817
0
    u_terminateUChars(dest, destCapacity, desti, status);
2818
0
    return desti;
2819
0
}
2820
2821
static const struct UTextFuncs charIterFuncs =
2822
{
2823
    sizeof(UTextFuncs),
2824
    0, 0, 0,             // Reserved alignment padding
2825
    charIterTextClone,
2826
    charIterTextLength,
2827
    charIterTextAccess,
2828
    charIterTextExtract,
2829
    nullptr,                // Replace
2830
    nullptr,                // Copy
2831
    nullptr,                // MapOffsetToNative,
2832
    nullptr,                // MapIndexToUTF16,
2833
    charIterTextClose,
2834
    nullptr,                // spare 1
2835
    nullptr,                // spare 2
2836
    nullptr                 // spare 3
2837
};
2838
U_CDECL_END
2839
2840
2841
U_CAPI UText * U_EXPORT2
2842
0
utext_openCharacterIterator(UText *ut, CharacterIterator *ci, UErrorCode *status) {
2843
0
    if (U_FAILURE(*status)) {
2844
0
        return nullptr;
2845
0
    }
2846
2847
0
    if (ci->startIndex() > 0) {
2848
        // No support for CharacterIterators that do not start indexing from zero.
2849
0
        *status = U_UNSUPPORTED_ERROR;
2850
0
        return nullptr;
2851
0
    }
2852
2853
    // Extra space in UText for 2 buffers of CIBufSize UChars each.
2854
0
    int32_t  extraSpace = 2 * CIBufSize * sizeof(char16_t);
2855
0
    ut = utext_setup(ut, extraSpace, status);
2856
0
    if (U_SUCCESS(*status)) {
2857
0
        ut->pFuncs                = &charIterFuncs;
2858
0
        ut->context              = ci;
2859
0
        ut->providerProperties   = 0;
2860
0
        ut->a                    = ci->endIndex();        // Length of text
2861
0
        ut->p                    = ut->pExtra;            // First buffer
2862
0
        ut->b                    = -1;                    // Native index of first buffer contents
2863
0
        ut->q                    = (char16_t*)ut->pExtra+CIBufSize;  // Second buffer
2864
0
        ut->c                    = -1;                    // Native index of second buffer contents
2865
2866
        // Initialize current chunk contents to be empty.
2867
        //   First access will fault something in.
2868
        //   Note:  The initial nativeStart and chunkOffset must sum to zero
2869
        //          so that getNativeIndex() will correctly compute to zero
2870
        //          if no call to Access() has ever been made.  They can't be both
2871
        //          zero without Access() thinking that the chunk is valid.
2872
0
        ut->chunkContents        = (char16_t *)ut->p;
2873
0
        ut->chunkNativeStart     = -1;
2874
0
        ut->chunkOffset          = 1;
2875
0
        ut->chunkNativeLimit     = 0;
2876
0
        ut->chunkLength          = 0;
2877
0
        ut->nativeIndexingLimit  = ut->chunkOffset;  // enables native indexing
2878
0
    }
2879
0
    return ut;
2880
0
}