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