Coverage Report

Created: 2026-09-28 06:10

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