• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 ******************************************************************************
3 *
4 *   Copyright (C) 1999-2009, International Business Machines
5 *   Corporation and others.  All Rights Reserved.
6 *
7 ******************************************************************************
8 *   file name:  ubidi.c
9 *   encoding:   US-ASCII
10 *   tab size:   8 (not used)
11 *   indentation:4
12 *
13 *   created on: 1999jul27
14 *   created by: Markus W. Scherer, updated by Matitiahu Allouche
15 */
16 
17 #include "cmemory.h"
18 #include "unicode/utypes.h"
19 #include "unicode/ustring.h"
20 #include "unicode/uchar.h"
21 #include "unicode/ubidi.h"
22 #include "ubidi_props.h"
23 #include "ubidiimp.h"
24 #include "uassert.h"
25 
26 /*
27  * General implementation notes:
28  *
29  * Throughout the implementation, there are comments like (W2) that refer to
30  * rules of the BiDi algorithm in its version 5, in this example to the second
31  * rule of the resolution of weak types.
32  *
33  * For handling surrogate pairs, where two UChar's form one "abstract" (or UTF-32)
34  * character according to UTF-16, the second UChar gets the directional property of
35  * the entire character assigned, while the first one gets a BN, a boundary
36  * neutral, type, which is ignored by most of the algorithm according to
37  * rule (X9) and the implementation suggestions of the BiDi algorithm.
38  *
39  * Later, adjustWSLevels() will set the level for each BN to that of the
40  * following character (UChar), which results in surrogate pairs getting the
41  * same level on each of their surrogates.
42  *
43  * In a UTF-8 implementation, the same thing could be done: the last byte of
44  * a multi-byte sequence would get the "real" property, while all previous
45  * bytes of that sequence would get BN.
46  *
47  * It is not possible to assign all those parts of a character the same real
48  * property because this would fail in the resolution of weak types with rules
49  * that look at immediately surrounding types.
50  *
51  * As a related topic, this implementation does not remove Boundary Neutral
52  * types from the input, but ignores them wherever this is relevant.
53  * For example, the loop for the resolution of the weak types reads
54  * types until it finds a non-BN.
55  * Also, explicit embedding codes are neither changed into BN nor removed.
56  * They are only treated the same way real BNs are.
57  * As stated before, adjustWSLevels() takes care of them at the end.
58  * For the purpose of conformance, the levels of all these codes
59  * do not matter.
60  *
61  * Note that this implementation never modifies the dirProps
62  * after the initial setup.
63  *
64  *
65  * In this implementation, the resolution of weak types (Wn),
66  * neutrals (Nn), and the assignment of the resolved level (In)
67  * are all done in one single loop, in resolveImplicitLevels().
68  * Changes of dirProp values are done on the fly, without writing
69  * them back to the dirProps array.
70  *
71  *
72  * This implementation contains code that allows to bypass steps of the
73  * algorithm that are not needed on the specific paragraph
74  * in order to speed up the most common cases considerably,
75  * like text that is entirely LTR, or RTL text without numbers.
76  *
77  * Most of this is done by setting a bit for each directional property
78  * in a flags variable and later checking for whether there are
79  * any LTR characters or any RTL characters, or both, whether
80  * there are any explicit embedding codes, etc.
81  *
82  * If the (Xn) steps are performed, then the flags are re-evaluated,
83  * because they will then not contain the embedding codes any more
84  * and will be adjusted for override codes, so that subsequently
85  * more bypassing may be possible than what the initial flags suggested.
86  *
87  * If the text is not mixed-directional, then the
88  * algorithm steps for the weak type resolution are not performed,
89  * and all levels are set to the paragraph level.
90  *
91  * If there are no explicit embedding codes, then the (Xn) steps
92  * are not performed.
93  *
94  * If embedding levels are supplied as a parameter, then all
95  * explicit embedding codes are ignored, and the (Xn) steps
96  * are not performed.
97  *
98  * White Space types could get the level of the run they belong to,
99  * and are checked with a test of (flags&MASK_EMBEDDING) to
100  * consider if the paragraph direction should be considered in
101  * the flags variable.
102  *
103  * If there are no White Space types in the paragraph, then
104  * (L1) is not necessary in adjustWSLevels().
105  */
106 
107 /* to avoid some conditional statements, use tiny constant arrays */
108 static const Flags flagLR[2]={ DIRPROP_FLAG(L), DIRPROP_FLAG(R) };
109 static const Flags flagE[2]={ DIRPROP_FLAG(LRE), DIRPROP_FLAG(RLE) };
110 static const Flags flagO[2]={ DIRPROP_FLAG(LRO), DIRPROP_FLAG(RLO) };
111 
112 #define DIRPROP_FLAG_LR(level) flagLR[(level)&1]
113 #define DIRPROP_FLAG_E(level) flagE[(level)&1]
114 #define DIRPROP_FLAG_O(level) flagO[(level)&1]
115 
116 /* UBiDi object management -------------------------------------------------- */
117 
118 U_CAPI UBiDi * U_EXPORT2
ubidi_open(void)119 ubidi_open(void)
120 {
121     UErrorCode errorCode=U_ZERO_ERROR;
122     return ubidi_openSized(0, 0, &errorCode);
123 }
124 
125 U_CAPI UBiDi * U_EXPORT2
ubidi_openSized(int32_t maxLength,int32_t maxRunCount,UErrorCode * pErrorCode)126 ubidi_openSized(int32_t maxLength, int32_t maxRunCount, UErrorCode *pErrorCode) {
127     UBiDi *pBiDi;
128 
129     /* check the argument values */
130     if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
131         return NULL;
132     } else if(maxLength<0 || maxRunCount<0) {
133         *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
134         return NULL;    /* invalid arguments */
135     }
136 
137     /* allocate memory for the object */
138     pBiDi=(UBiDi *)uprv_malloc(sizeof(UBiDi));
139     if(pBiDi==NULL) {
140         *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
141         return NULL;
142     }
143 
144     /* reset the object, all pointers NULL, all flags FALSE, all sizes 0 */
145     uprv_memset(pBiDi, 0, sizeof(UBiDi));
146 
147     /* get BiDi properties */
148     pBiDi->bdp=ubidi_getSingleton(pErrorCode);
149     if(U_FAILURE(*pErrorCode)) {
150         uprv_free(pBiDi);
151         return NULL;
152     }
153 
154     /* allocate memory for arrays as requested */
155     if(maxLength>0) {
156         if( !getInitialDirPropsMemory(pBiDi, maxLength) ||
157             !getInitialLevelsMemory(pBiDi, maxLength)
158         ) {
159             *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
160         }
161     } else {
162         pBiDi->mayAllocateText=TRUE;
163     }
164 
165     if(maxRunCount>0) {
166         if(maxRunCount==1) {
167             /* use simpleRuns[] */
168             pBiDi->runsSize=sizeof(Run);
169         } else if(!getInitialRunsMemory(pBiDi, maxRunCount)) {
170             *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
171         }
172     } else {
173         pBiDi->mayAllocateRuns=TRUE;
174     }
175 
176     if(U_SUCCESS(*pErrorCode)) {
177         return pBiDi;
178     } else {
179         ubidi_close(pBiDi);
180         return NULL;
181     }
182 }
183 
184 /*
185  * We are allowed to allocate memory if memory==NULL or
186  * mayAllocate==TRUE for each array that we need.
187  * We also try to grow memory as needed if we
188  * allocate it.
189  *
190  * Assume sizeNeeded>0.
191  * If *pMemory!=NULL, then assume *pSize>0.
192  *
193  * ### this realloc() may unnecessarily copy the old data,
194  * which we know we don't need any more;
195  * is this the best way to do this??
196  */
197 U_CFUNC UBool
ubidi_getMemory(BidiMemoryForAllocation * bidiMem,int32_t * pSize,UBool mayAllocate,int32_t sizeNeeded)198 ubidi_getMemory(BidiMemoryForAllocation *bidiMem, int32_t *pSize, UBool mayAllocate, int32_t sizeNeeded) {
199     void **pMemory = (void **)bidiMem;
200     /* check for existing memory */
201     if(*pMemory==NULL) {
202         /* we need to allocate memory */
203         if(mayAllocate && (*pMemory=uprv_malloc(sizeNeeded))!=NULL) {
204             *pSize=sizeNeeded;
205             return TRUE;
206         } else {
207             return FALSE;
208         }
209     } else {
210         if(sizeNeeded<=*pSize) {
211             /* there is already enough memory */
212             return TRUE;
213         }
214         else if(!mayAllocate) {
215             /* not enough memory, and we must not allocate */
216             return FALSE;
217         } else {
218             /* we try to grow */
219             void *memory;
220             /* in most cases, we do not need the copy-old-data part of
221              * realloc, but it is needed when adding runs using getRunsMemory()
222              * in setParaRunsOnly()
223              */
224             if((memory=uprv_realloc(*pMemory, sizeNeeded))!=NULL) {
225                 *pMemory=memory;
226                 *pSize=sizeNeeded;
227                 return TRUE;
228             } else {
229                 /* we failed to grow */
230                 return FALSE;
231             }
232         }
233     }
234 }
235 
236 U_CAPI void U_EXPORT2
ubidi_close(UBiDi * pBiDi)237 ubidi_close(UBiDi *pBiDi) {
238     if(pBiDi!=NULL) {
239         pBiDi->pParaBiDi=NULL;          /* in case one tries to reuse this block */
240         if(pBiDi->dirPropsMemory!=NULL) {
241             uprv_free(pBiDi->dirPropsMemory);
242         }
243         if(pBiDi->levelsMemory!=NULL) {
244             uprv_free(pBiDi->levelsMemory);
245         }
246         if(pBiDi->runsMemory!=NULL) {
247             uprv_free(pBiDi->runsMemory);
248         }
249         if(pBiDi->parasMemory!=NULL) {
250             uprv_free(pBiDi->parasMemory);
251         }
252         if(pBiDi->insertPoints.points!=NULL) {
253             uprv_free(pBiDi->insertPoints.points);
254         }
255 
256         uprv_free(pBiDi);
257     }
258 }
259 
260 /* set to approximate "inverse BiDi" ---------------------------------------- */
261 
262 U_CAPI void U_EXPORT2
ubidi_setInverse(UBiDi * pBiDi,UBool isInverse)263 ubidi_setInverse(UBiDi *pBiDi, UBool isInverse) {
264     if(pBiDi!=NULL) {
265         pBiDi->isInverse=isInverse;
266         pBiDi->reorderingMode = isInverse ? UBIDI_REORDER_INVERSE_NUMBERS_AS_L
267                                           : UBIDI_REORDER_DEFAULT;
268     }
269 }
270 
271 U_CAPI UBool U_EXPORT2
ubidi_isInverse(UBiDi * pBiDi)272 ubidi_isInverse(UBiDi *pBiDi) {
273     if(pBiDi!=NULL) {
274         return pBiDi->isInverse;
275     } else {
276         return FALSE;
277     }
278 }
279 
280 /* FOOD FOR THOUGHT: currently the reordering modes are a mixture of
281  * algorithm for direct BiDi, algorithm for inverse BiDi and the bizarre
282  * concept of RUNS_ONLY which is a double operation.
283  * It could be advantageous to divide this into 3 concepts:
284  * a) Operation: direct / inverse / RUNS_ONLY
285  * b) Direct algorithm: default / NUMBERS_SPECIAL / GROUP_NUMBERS_WITH_R
286  * c) Inverse algorithm: default / INVERSE_LIKE_DIRECT / NUMBERS_SPECIAL
287  * This would allow combinations not possible today like RUNS_ONLY with
288  * NUMBERS_SPECIAL.
289  * Also allow to set INSERT_MARKS for the direct step of RUNS_ONLY and
290  * REMOVE_CONTROLS for the inverse step.
291  * Not all combinations would be supported, and probably not all do make sense.
292  * This would need to document which ones are supported and what are the
293  * fallbacks for unsupported combinations.
294  */
295 U_CAPI void U_EXPORT2
ubidi_setReorderingMode(UBiDi * pBiDi,UBiDiReorderingMode reorderingMode)296 ubidi_setReorderingMode(UBiDi *pBiDi, UBiDiReorderingMode reorderingMode) {
297     if ((pBiDi!=NULL) && (reorderingMode >= UBIDI_REORDER_DEFAULT)
298                         && (reorderingMode < UBIDI_REORDER_COUNT)) {
299         pBiDi->reorderingMode = reorderingMode;
300         pBiDi->isInverse = (UBool)(reorderingMode == UBIDI_REORDER_INVERSE_NUMBERS_AS_L);
301     }
302 }
303 
304 U_CAPI UBiDiReorderingMode U_EXPORT2
ubidi_getReorderingMode(UBiDi * pBiDi)305 ubidi_getReorderingMode(UBiDi *pBiDi) {
306     if (pBiDi!=NULL) {
307         return pBiDi->reorderingMode;
308     } else {
309         return UBIDI_REORDER_DEFAULT;
310     }
311 }
312 
313 U_CAPI void U_EXPORT2
ubidi_setReorderingOptions(UBiDi * pBiDi,uint32_t reorderingOptions)314 ubidi_setReorderingOptions(UBiDi *pBiDi, uint32_t reorderingOptions) {
315     if (reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS) {
316         reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS;
317     }
318     if (pBiDi!=NULL) {
319         pBiDi->reorderingOptions=reorderingOptions;
320     }
321 }
322 
323 U_CAPI uint32_t U_EXPORT2
ubidi_getReorderingOptions(UBiDi * pBiDi)324 ubidi_getReorderingOptions(UBiDi *pBiDi) {
325     if (pBiDi!=NULL) {
326         return pBiDi->reorderingOptions;
327     } else {
328         return 0;
329     }
330 }
331 
332 /* perform (P2)..(P3) ------------------------------------------------------- */
333 
334 /*
335  * Get the directional properties for the text,
336  * calculate the flags bit-set, and
337  * determine the paragraph level if necessary.
338  */
339 static void
getDirProps(UBiDi * pBiDi)340 getDirProps(UBiDi *pBiDi) {
341     const UChar *text=pBiDi->text;
342     DirProp *dirProps=pBiDi->dirPropsMemory;    /* pBiDi->dirProps is const */
343 
344     int32_t i=0, i1, length=pBiDi->originalLength;
345     Flags flags=0;      /* collect all directionalities in the text */
346     UChar32 uchar;
347     DirProp dirProp=0, paraDirDefault=0;/* initialize to avoid compiler warnings */
348     UBool isDefaultLevel=IS_DEFAULT_LEVEL(pBiDi->paraLevel);
349     /* for inverse BiDi, the default para level is set to RTL if there is a
350        strong R or AL character at either end of the text                           */
351     UBool isDefaultLevelInverse=isDefaultLevel && (UBool)
352             (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT ||
353              pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL);
354     int32_t lastArabicPos=-1;
355     int32_t controlCount=0;
356     UBool removeBiDiControls = (UBool)(pBiDi->reorderingOptions &
357                                        UBIDI_OPTION_REMOVE_CONTROLS);
358 
359     typedef enum {
360          NOT_CONTEXTUAL,                /* 0: not contextual paraLevel */
361          LOOKING_FOR_STRONG,            /* 1: looking for first strong char */
362          FOUND_STRONG_CHAR              /* 2: found first strong char       */
363     } State;
364     State state;
365     int32_t paraStart=0;                /* index of first char in paragraph */
366     DirProp paraDir;                    /* == CONTEXT_RTL within paragraphs
367                                            starting with strong R char      */
368     DirProp lastStrongDir=0;            /* for default level & inverse BiDi */
369     int32_t lastStrongLTR=0;            /* for STREAMING option             */
370 
371     if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
372         pBiDi->length=0;
373         lastStrongLTR=0;
374     }
375     if(isDefaultLevel) {
376         paraDirDefault=pBiDi->paraLevel&1 ? CONTEXT_RTL : 0;
377         paraDir=paraDirDefault;
378         lastStrongDir=paraDirDefault;
379         state=LOOKING_FOR_STRONG;
380     } else {
381         state=NOT_CONTEXTUAL;
382         paraDir=0;
383     }
384     /* count paragraphs and determine the paragraph level (P2..P3) */
385     /*
386      * see comment in ubidi.h:
387      * the DEFAULT_XXX values are designed so that
388      * their bit 0 alone yields the intended default
389      */
390     for( /* i=0 above */ ; i<length; ) {
391         /* i is incremented by U16_NEXT */
392         U16_NEXT(text, i, length, uchar);
393         flags|=DIRPROP_FLAG(dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar));
394         dirProps[i-1]=dirProp|paraDir;
395         if(uchar>0xffff) {  /* set the lead surrogate's property to BN */
396             flags|=DIRPROP_FLAG(BN);
397             dirProps[i-2]=(DirProp)(BN|paraDir);
398         }
399         if(state==LOOKING_FOR_STRONG) {
400             if(dirProp==L) {
401                 state=FOUND_STRONG_CHAR;
402                 if(paraDir) {
403                     paraDir=0;
404                     for(i1=paraStart; i1<i; i1++) {
405                         dirProps[i1]&=~CONTEXT_RTL;
406                     }
407                 }
408                 continue;
409             }
410             if(dirProp==R || dirProp==AL) {
411                 state=FOUND_STRONG_CHAR;
412                 if(paraDir==0) {
413                     paraDir=CONTEXT_RTL;
414                     for(i1=paraStart; i1<i; i1++) {
415                         dirProps[i1]|=CONTEXT_RTL;
416                     }
417                 }
418                 continue;
419             }
420         }
421         if(dirProp==L) {
422             lastStrongDir=0;
423             lastStrongLTR=i;            /* i is index to next character */
424         }
425         else if(dirProp==R) {
426             lastStrongDir=CONTEXT_RTL;
427         }
428         else if(dirProp==AL) {
429             lastStrongDir=CONTEXT_RTL;
430             lastArabicPos=i-1;
431         }
432         else if(dirProp==B) {
433             if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
434                 pBiDi->length=i;        /* i is index to next character */
435             }
436             if(isDefaultLevelInverse && (lastStrongDir==CONTEXT_RTL) &&(paraDir!=lastStrongDir)) {
437                 for( ; paraStart<i; paraStart++) {
438                     dirProps[paraStart]|=CONTEXT_RTL;
439                 }
440             }
441             if(i<length) {              /* B not last char in text */
442                 if(!((uchar==CR) && (text[i]==LF))) {
443                     pBiDi->paraCount++;
444                 }
445                 if(isDefaultLevel) {
446                     state=LOOKING_FOR_STRONG;
447                     paraStart=i;        /* i is index to next character */
448                     paraDir=paraDirDefault;
449                     lastStrongDir=paraDirDefault;
450                 }
451             }
452         }
453         if(removeBiDiControls && IS_BIDI_CONTROL_CHAR(uchar)) {
454             controlCount++;
455         }
456     }
457     if(isDefaultLevelInverse && (lastStrongDir==CONTEXT_RTL) &&(paraDir!=lastStrongDir)) {
458         for(i1=paraStart; i1<length; i1++) {
459             dirProps[i1]|=CONTEXT_RTL;
460         }
461     }
462     if(isDefaultLevel) {
463         pBiDi->paraLevel=GET_PARALEVEL(pBiDi, 0);
464     }
465     if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
466         if((lastStrongLTR>pBiDi->length) &&
467            (GET_PARALEVEL(pBiDi, lastStrongLTR)==0)) {
468             pBiDi->length = lastStrongLTR;
469         }
470         if(pBiDi->length<pBiDi->originalLength) {
471             pBiDi->paraCount--;
472         }
473     }
474     /* The following line does nothing new for contextual paraLevel, but is
475        needed for absolute paraLevel.                               */
476     flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
477 
478     if(pBiDi->orderParagraphsLTR && (flags&DIRPROP_FLAG(B))) {
479         flags|=DIRPROP_FLAG(L);
480     }
481 
482     pBiDi->controlCount = controlCount;
483     pBiDi->flags=flags;
484     pBiDi->lastArabicPos=lastArabicPos;
485 }
486 
487 /* perform (X1)..(X9) ------------------------------------------------------- */
488 
489 /* determine if the text is mixed-directional or single-directional */
490 static UBiDiDirection
directionFromFlags(UBiDi * pBiDi)491 directionFromFlags(UBiDi *pBiDi) {
492     Flags flags=pBiDi->flags;
493     /* if the text contains AN and neutrals, then some neutrals may become RTL */
494     if(!(flags&MASK_RTL || ((flags&DIRPROP_FLAG(AN)) && (flags&MASK_POSSIBLE_N)))) {
495         return UBIDI_LTR;
496     } else if(!(flags&MASK_LTR)) {
497         return UBIDI_RTL;
498     } else {
499         return UBIDI_MIXED;
500     }
501 }
502 
503 /*
504  * Resolve the explicit levels as specified by explicit embedding codes.
505  * Recalculate the flags to have them reflect the real properties
506  * after taking the explicit embeddings into account.
507  *
508  * The BiDi algorithm is designed to result in the same behavior whether embedding
509  * levels are externally specified (from "styled text", supposedly the preferred
510  * method) or set by explicit embedding codes (LRx, RLx, PDF) in the plain text.
511  * That is why (X9) instructs to remove all explicit codes (and BN).
512  * However, in a real implementation, this removal of these codes and their index
513  * positions in the plain text is undesirable since it would result in
514  * reallocated, reindexed text.
515  * Instead, this implementation leaves the codes in there and just ignores them
516  * in the subsequent processing.
517  * In order to get the same reordering behavior, positions with a BN or an
518  * explicit embedding code just get the same level assigned as the last "real"
519  * character.
520  *
521  * Some implementations, not this one, then overwrite some of these
522  * directionality properties at "real" same-level-run boundaries by
523  * L or R codes so that the resolution of weak types can be performed on the
524  * entire paragraph at once instead of having to parse it once more and
525  * perform that resolution on same-level-runs.
526  * This limits the scope of the implicit rules in effectively
527  * the same way as the run limits.
528  *
529  * Instead, this implementation does not modify these codes.
530  * On one hand, the paragraph has to be scanned for same-level-runs, but
531  * on the other hand, this saves another loop to reset these codes,
532  * or saves making and modifying a copy of dirProps[].
533  *
534  *
535  * Note that (Pn) and (Xn) changed significantly from version 4 of the BiDi algorithm.
536  *
537  *
538  * Handling the stack of explicit levels (Xn):
539  *
540  * With the BiDi stack of explicit levels,
541  * as pushed with each LRE, RLE, LRO, and RLO and popped with each PDF,
542  * the explicit level must never exceed UBIDI_MAX_EXPLICIT_LEVEL==61.
543  *
544  * In order to have a correct push-pop semantics even in the case of overflows,
545  * there are two overflow counters:
546  * - countOver60 is incremented with each LRx at level 60
547  * - from level 60, one RLx increases the level to 61
548  * - countOver61 is incremented with each LRx and RLx at level 61
549  *
550  * Popping levels with PDF must work in the opposite order so that level 61
551  * is correct at the correct point. Underflows (too many PDFs) must be checked.
552  *
553  * This implementation assumes that UBIDI_MAX_EXPLICIT_LEVEL is odd.
554  */
555 static UBiDiDirection
resolveExplicitLevels(UBiDi * pBiDi)556 resolveExplicitLevels(UBiDi *pBiDi) {
557     const DirProp *dirProps=pBiDi->dirProps;
558     UBiDiLevel *levels=pBiDi->levels;
559     const UChar *text=pBiDi->text;
560 
561     int32_t i=0, length=pBiDi->length;
562     Flags flags=pBiDi->flags;       /* collect all directionalities in the text */
563     DirProp dirProp;
564     UBiDiLevel level=GET_PARALEVEL(pBiDi, 0);
565 
566     UBiDiDirection direction;
567     int32_t paraIndex=0;
568 
569     /* determine if the text is mixed-directional or single-directional */
570     direction=directionFromFlags(pBiDi);
571 
572     /* we may not need to resolve any explicit levels, but for multiple
573        paragraphs we want to loop on all chars to set the para boundaries */
574     if((direction!=UBIDI_MIXED) && (pBiDi->paraCount==1)) {
575         /* not mixed directionality: levels don't matter - trailingWSStart will be 0 */
576     } else if((pBiDi->paraCount==1) &&
577               (!(flags&MASK_EXPLICIT) ||
578                (pBiDi->reorderingMode > UBIDI_REORDER_LAST_LOGICAL_TO_VISUAL))) {
579         /* mixed, but all characters are at the same embedding level */
580         /* or we are in "inverse BiDi" */
581         /* and we don't have contextual multiple paragraphs with some B char */
582         /* set all levels to the paragraph level */
583         for(i=0; i<length; ++i) {
584             levels[i]=level;
585         }
586     } else {
587         /* continue to perform (Xn) */
588 
589         /* (X1) level is set for all codes, embeddingLevel keeps track of the push/pop operations */
590         /* both variables may carry the UBIDI_LEVEL_OVERRIDE flag to indicate the override status */
591         UBiDiLevel embeddingLevel=level, newLevel, stackTop=0;
592 
593         UBiDiLevel stack[UBIDI_MAX_EXPLICIT_LEVEL];        /* we never push anything >=UBIDI_MAX_EXPLICIT_LEVEL */
594         uint32_t countOver60=0, countOver61=0;  /* count overflows of explicit levels */
595 
596         /* recalculate the flags */
597         flags=0;
598 
599         for(i=0; i<length; ++i) {
600             dirProp=NO_CONTEXT_RTL(dirProps[i]);
601             switch(dirProp) {
602             case LRE:
603             case LRO:
604                 /* (X3, X5) */
605                 newLevel=(UBiDiLevel)((embeddingLevel+2)&~(UBIDI_LEVEL_OVERRIDE|1)); /* least greater even level */
606                 if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL) {
607                     stack[stackTop]=embeddingLevel;
608                     ++stackTop;
609                     embeddingLevel=newLevel;
610                     if(dirProp==LRO) {
611                         embeddingLevel|=UBIDI_LEVEL_OVERRIDE;
612                     }
613                     /* we don't need to set UBIDI_LEVEL_OVERRIDE off for LRE
614                        since this has already been done for newLevel which is
615                        the source for embeddingLevel.
616                      */
617                 } else if((embeddingLevel&~UBIDI_LEVEL_OVERRIDE)==UBIDI_MAX_EXPLICIT_LEVEL) {
618                     ++countOver61;
619                 } else /* (embeddingLevel&~UBIDI_LEVEL_OVERRIDE)==UBIDI_MAX_EXPLICIT_LEVEL-1 */ {
620                     ++countOver60;
621                 }
622                 flags|=DIRPROP_FLAG(BN);
623                 break;
624             case RLE:
625             case RLO:
626                 /* (X2, X4) */
627                 newLevel=(UBiDiLevel)(((embeddingLevel&~UBIDI_LEVEL_OVERRIDE)+1)|1); /* least greater odd level */
628                 if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL) {
629                     stack[stackTop]=embeddingLevel;
630                     ++stackTop;
631                     embeddingLevel=newLevel;
632                     if(dirProp==RLO) {
633                         embeddingLevel|=UBIDI_LEVEL_OVERRIDE;
634                     }
635                     /* we don't need to set UBIDI_LEVEL_OVERRIDE off for RLE
636                        since this has already been done for newLevel which is
637                        the source for embeddingLevel.
638                      */
639                 } else {
640                     ++countOver61;
641                 }
642                 flags|=DIRPROP_FLAG(BN);
643                 break;
644             case PDF:
645                 /* (X7) */
646                 /* handle all the overflow cases first */
647                 if(countOver61>0) {
648                     --countOver61;
649                 } else if(countOver60>0 && (embeddingLevel&~UBIDI_LEVEL_OVERRIDE)!=UBIDI_MAX_EXPLICIT_LEVEL) {
650                     /* handle LRx overflows from level 60 */
651                     --countOver60;
652                 } else if(stackTop>0) {
653                     /* this is the pop operation; it also pops level 61 while countOver60>0 */
654                     --stackTop;
655                     embeddingLevel=stack[stackTop];
656                 /* } else { (underflow) */
657                 }
658                 flags|=DIRPROP_FLAG(BN);
659                 break;
660             case B:
661                 stackTop=0;
662                 countOver60=countOver61=0;
663                 level=GET_PARALEVEL(pBiDi, i);
664                 if((i+1)<length) {
665                     embeddingLevel=GET_PARALEVEL(pBiDi, i+1);
666                     if(!((text[i]==CR) && (text[i+1]==LF))) {
667                         pBiDi->paras[paraIndex++]=i+1;
668                     }
669                 }
670                 flags|=DIRPROP_FLAG(B);
671                 break;
672             case BN:
673                 /* BN, LRE, RLE, and PDF are supposed to be removed (X9) */
674                 /* they will get their levels set correctly in adjustWSLevels() */
675                 flags|=DIRPROP_FLAG(BN);
676                 break;
677             default:
678                 /* all other types get the "real" level */
679                 if(level!=embeddingLevel) {
680                     level=embeddingLevel;
681                     if(level&UBIDI_LEVEL_OVERRIDE) {
682                         flags|=DIRPROP_FLAG_O(level)|DIRPROP_FLAG_MULTI_RUNS;
683                     } else {
684                         flags|=DIRPROP_FLAG_E(level)|DIRPROP_FLAG_MULTI_RUNS;
685                     }
686                 }
687                 if(!(level&UBIDI_LEVEL_OVERRIDE)) {
688                     flags|=DIRPROP_FLAG(dirProp);
689                 }
690                 break;
691             }
692 
693             /*
694              * We need to set reasonable levels even on BN codes and
695              * explicit codes because we will later look at same-level runs (X10).
696              */
697             levels[i]=level;
698         }
699         if(flags&MASK_EMBEDDING) {
700             flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
701         }
702         if(pBiDi->orderParagraphsLTR && (flags&DIRPROP_FLAG(B))) {
703             flags|=DIRPROP_FLAG(L);
704         }
705 
706         /* subsequently, ignore the explicit codes and BN (X9) */
707 
708         /* again, determine if the text is mixed-directional or single-directional */
709         pBiDi->flags=flags;
710         direction=directionFromFlags(pBiDi);
711     }
712 
713     return direction;
714 }
715 
716 /*
717  * Use a pre-specified embedding levels array:
718  *
719  * Adjust the directional properties for overrides (->LEVEL_OVERRIDE),
720  * ignore all explicit codes (X9),
721  * and check all the preset levels.
722  *
723  * Recalculate the flags to have them reflect the real properties
724  * after taking the explicit embeddings into account.
725  */
726 static UBiDiDirection
checkExplicitLevels(UBiDi * pBiDi,UErrorCode * pErrorCode)727 checkExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) {
728     const DirProp *dirProps=pBiDi->dirProps;
729     DirProp dirProp;
730     UBiDiLevel *levels=pBiDi->levels;
731     const UChar *text=pBiDi->text;
732 
733     int32_t i, length=pBiDi->length;
734     Flags flags=0;  /* collect all directionalities in the text */
735     UBiDiLevel level;
736     uint32_t paraIndex=0;
737 
738     for(i=0; i<length; ++i) {
739         level=levels[i];
740         dirProp=NO_CONTEXT_RTL(dirProps[i]);
741         if(level&UBIDI_LEVEL_OVERRIDE) {
742             /* keep the override flag in levels[i] but adjust the flags */
743             level&=~UBIDI_LEVEL_OVERRIDE;     /* make the range check below simpler */
744             flags|=DIRPROP_FLAG_O(level);
745         } else {
746             /* set the flags */
747             flags|=DIRPROP_FLAG_E(level)|DIRPROP_FLAG(dirProp);
748         }
749         if((level<GET_PARALEVEL(pBiDi, i) &&
750             !((0==level)&&(dirProp==B))) ||
751            (UBIDI_MAX_EXPLICIT_LEVEL<level)) {
752             /* level out of bounds */
753             *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
754             return UBIDI_LTR;
755         }
756         if((dirProp==B) && ((i+1)<length)) {
757             if(!((text[i]==CR) && (text[i+1]==LF))) {
758                 pBiDi->paras[paraIndex++]=i+1;
759             }
760         }
761     }
762     if(flags&MASK_EMBEDDING) {
763         flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
764     }
765 
766     /* determine if the text is mixed-directional or single-directional */
767     pBiDi->flags=flags;
768     return directionFromFlags(pBiDi);
769 }
770 
771 /******************************************************************
772  The Properties state machine table
773 *******************************************************************
774 
775  All table cells are 8 bits:
776       bits 0..4:  next state
777       bits 5..7:  action to perform (if > 0)
778 
779  Cells may be of format "n" where n represents the next state
780  (except for the rightmost column).
781  Cells may also be of format "s(x,y)" where x represents an action
782  to perform and y represents the next state.
783 
784 *******************************************************************
785  Definitions and type for properties state table
786 *******************************************************************
787 */
788 #define IMPTABPROPS_COLUMNS 14
789 #define IMPTABPROPS_RES (IMPTABPROPS_COLUMNS - 1)
790 #define GET_STATEPROPS(cell) ((cell)&0x1f)
791 #define GET_ACTIONPROPS(cell) ((cell)>>5)
792 #define s(action, newState) ((uint8_t)(newState+(action<<5)))
793 
794 static const uint8_t groupProp[] =          /* dirProp regrouped */
795 {
796 /*  L   R   EN  ES  ET  AN  CS  B   S   WS  ON  LRE LRO AL  RLE RLO PDF NSM BN  */
797     0,  1,  2,  7,  8,  3,  9,  6,  5,  4,  4,  10, 10, 12, 10, 10, 10, 11, 10
798 };
799 enum { DirProp_L=0, DirProp_R=1, DirProp_EN=2, DirProp_AN=3, DirProp_ON=4, DirProp_S=5, DirProp_B=6 }; /* reduced dirProp */
800 
801 /******************************************************************
802 
803       PROPERTIES  STATE  TABLE
804 
805  In table impTabProps,
806       - the ON column regroups ON and WS
807       - the BN column regroups BN, LRE, RLE, LRO, RLO, PDF
808       - the Res column is the reduced property assigned to a run
809 
810  Action 1: process current run1, init new run1
811         2: init new run2
812         3: process run1, process run2, init new run1
813         4: process run1, set run1=run2, init new run2
814 
815  Notes:
816   1) This table is used in resolveImplicitLevels().
817   2) This table triggers actions when there is a change in the Bidi
818      property of incoming characters (action 1).
819   3) Most such property sequences are processed immediately (in
820      fact, passed to processPropertySeq().
821   4) However, numbers are assembled as one sequence. This means
822      that undefined situations (like CS following digits, until
823      it is known if the next char will be a digit) are held until
824      following chars define them.
825      Example: digits followed by CS, then comes another CS or ON;
826               the digits will be processed, then the CS assigned
827               as the start of an ON sequence (action 3).
828   5) There are cases where more than one sequence must be
829      processed, for instance digits followed by CS followed by L:
830      the digits must be processed as one sequence, and the CS
831      must be processed as an ON sequence, all this before starting
832      assembling chars for the opening L sequence.
833 
834 
835 */
836 static const uint8_t impTabProps[][IMPTABPROPS_COLUMNS] =
837 {
838 /*                        L ,     R ,    EN ,    AN ,    ON ,     S ,     B ,    ES ,    ET ,    CS ,    BN ,   NSM ,    AL ,  Res */
839 /* 0 Init        */ {     1 ,     2 ,     4 ,     5 ,     7 ,    15 ,    17 ,     7 ,     9 ,     7 ,     0 ,     7 ,     3 ,  DirProp_ON },
840 /* 1 L           */ {     1 , s(1,2), s(1,4), s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), s(1,9), s(1,7),     1 ,     1 , s(1,3),   DirProp_L },
841 /* 2 R           */ { s(1,1),     2 , s(1,4), s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), s(1,9), s(1,7),     2 ,     2 , s(1,3),   DirProp_R },
842 /* 3 AL          */ { s(1,1), s(1,2), s(1,6), s(1,6), s(1,8),s(1,16),s(1,17), s(1,8), s(1,8), s(1,8),     3 ,     3 ,     3 ,   DirProp_R },
843 /* 4 EN          */ { s(1,1), s(1,2),     4 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,10),    11 ,s(2,10),     4 ,     4 , s(1,3),  DirProp_EN },
844 /* 5 AN          */ { s(1,1), s(1,2), s(1,4),     5 , s(1,7),s(1,15),s(1,17), s(1,7), s(1,9),s(2,12),     5 ,     5 , s(1,3),  DirProp_AN },
845 /* 6 AL:EN/AN    */ { s(1,1), s(1,2),     6 ,     6 , s(1,8),s(1,16),s(1,17), s(1,8), s(1,8),s(2,13),     6 ,     6 , s(1,3),  DirProp_AN },
846 /* 7 ON          */ { s(1,1), s(1,2), s(1,4), s(1,5),     7 ,s(1,15),s(1,17),     7 ,s(2,14),     7 ,     7 ,     7 , s(1,3),  DirProp_ON },
847 /* 8 AL:ON       */ { s(1,1), s(1,2), s(1,6), s(1,6),     8 ,s(1,16),s(1,17),     8 ,     8 ,     8 ,     8 ,     8 , s(1,3),  DirProp_ON },
848 /* 9 ET          */ { s(1,1), s(1,2),     4 , s(1,5),     7 ,s(1,15),s(1,17),     7 ,     9 ,     7 ,     9 ,     9 , s(1,3),  DirProp_ON },
849 /*10 EN+ES/CS    */ { s(3,1), s(3,2),     4 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7),    10 , s(4,7), s(3,3),  DirProp_EN },
850 /*11 EN+ET       */ { s(1,1), s(1,2),     4 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7),    11 , s(1,7),    11 ,    11 , s(1,3),  DirProp_EN },
851 /*12 AN+CS       */ { s(3,1), s(3,2), s(3,4),     5 , s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7),    12 , s(4,7), s(3,3),  DirProp_AN },
852 /*13 AL:EN/AN+CS */ { s(3,1), s(3,2),     6 ,     6 , s(4,8),s(3,16),s(3,17), s(4,8), s(4,8), s(4,8),    13 , s(4,8), s(3,3),  DirProp_AN },
853 /*14 ON+ET       */ { s(1,1), s(1,2), s(4,4), s(1,5),     7 ,s(1,15),s(1,17),     7 ,    14 ,     7 ,    14 ,    14 , s(1,3),  DirProp_ON },
854 /*15 S           */ { s(1,1), s(1,2), s(1,4), s(1,5), s(1,7),    15 ,s(1,17), s(1,7), s(1,9), s(1,7),    15 , s(1,7), s(1,3),   DirProp_S },
855 /*16 AL:S        */ { s(1,1), s(1,2), s(1,6), s(1,6), s(1,8),    16 ,s(1,17), s(1,8), s(1,8), s(1,8),    16 , s(1,8), s(1,3),   DirProp_S },
856 /*17 B           */ { s(1,1), s(1,2), s(1,4), s(1,5), s(1,7),s(1,15),    17 , s(1,7), s(1,9), s(1,7),    17 , s(1,7), s(1,3),   DirProp_B }
857 };
858 
859 /*  we must undef macro s because the levels table have a different
860  *  structure (4 bits for action and 4 bits for next state.
861  */
862 #undef s
863 
864 /******************************************************************
865  The levels state machine tables
866 *******************************************************************
867 
868  All table cells are 8 bits:
869       bits 0..3:  next state
870       bits 4..7:  action to perform (if > 0)
871 
872  Cells may be of format "n" where n represents the next state
873  (except for the rightmost column).
874  Cells may also be of format "s(x,y)" where x represents an action
875  to perform and y represents the next state.
876 
877  This format limits each table to 16 states each and to 15 actions.
878 
879 *******************************************************************
880  Definitions and type for levels state tables
881 *******************************************************************
882 */
883 #define IMPTABLEVELS_COLUMNS (DirProp_B + 2)
884 #define IMPTABLEVELS_RES (IMPTABLEVELS_COLUMNS - 1)
885 #define GET_STATE(cell) ((cell)&0x0f)
886 #define GET_ACTION(cell) ((cell)>>4)
887 #define s(action, newState) ((uint8_t)(newState+(action<<4)))
888 
889 typedef uint8_t ImpTab[][IMPTABLEVELS_COLUMNS];
890 typedef uint8_t ImpAct[];
891 
892 /* FOOD FOR THOUGHT: each ImpTab should have its associated ImpAct,
893  * instead of having a pair of ImpTab and a pair of ImpAct.
894  */
895 typedef struct ImpTabPair {
896     const void * pImpTab[2];
897     const void * pImpAct[2];
898 } ImpTabPair;
899 
900 /******************************************************************
901 
902       LEVELS  STATE  TABLES
903 
904  In all levels state tables,
905       - state 0 is the initial state
906       - the Res column is the increment to add to the text level
907         for this property sequence.
908 
909  The impAct arrays for each table of a pair map the local action
910  numbers of the table to the total list of actions. For instance,
911  action 2 in a given table corresponds to the action number which
912  appears in entry [2] of the impAct array for that table.
913  The first entry of all impAct arrays must be 0.
914 
915  Action 1: init conditional sequence
916         2: prepend conditional sequence to current sequence
917         3: set ON sequence to new level - 1
918         4: init EN/AN/ON sequence
919         5: fix EN/AN/ON sequence followed by R
920         6: set previous level sequence to level 2
921 
922  Notes:
923   1) These tables are used in processPropertySeq(). The input
924      is property sequences as determined by resolveImplicitLevels.
925   2) Most such property sequences are processed immediately
926      (levels are assigned).
927   3) However, some sequences cannot be assigned a final level till
928      one or more following sequences are received. For instance,
929      ON following an R sequence within an even-level paragraph.
930      If the following sequence is R, the ON sequence will be
931      assigned basic run level+1, and so will the R sequence.
932   4) S is generally handled like ON, since its level will be fixed
933      to paragraph level in adjustWSLevels().
934 
935 */
936 
937 static const ImpTab impTabL_DEFAULT =   /* Even paragraph level */
938 /*  In this table, conditional sequences receive the higher possible level
939     until proven otherwise.
940 */
941 {
942 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
943 /* 0 : init       */ {     0 ,     1 ,     0 ,     2 ,     0 ,     0 ,     0 ,  0 },
944 /* 1 : R          */ {     0 ,     1 ,     3 ,     3 , s(1,4), s(1,4),     0 ,  1 },
945 /* 2 : AN         */ {     0 ,     1 ,     0 ,     2 , s(1,5), s(1,5),     0 ,  2 },
946 /* 3 : R+EN/AN    */ {     0 ,     1 ,     3 ,     3 , s(1,4), s(1,4),     0 ,  2 },
947 /* 4 : R+ON       */ { s(2,0),     1 ,     3 ,     3 ,     4 ,     4 , s(2,0),  1 },
948 /* 5 : AN+ON      */ { s(2,0),     1 , s(2,0),     2 ,     5 ,     5 , s(2,0),  1 }
949 };
950 static const ImpTab impTabR_DEFAULT =   /* Odd  paragraph level */
951 /*  In this table, conditional sequences receive the lower possible level
952     until proven otherwise.
953 */
954 {
955 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
956 /* 0 : init       */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  0 },
957 /* 1 : L          */ {     1 ,     0 ,     1 ,     3 , s(1,4), s(1,4),     0 ,  1 },
958 /* 2 : EN/AN      */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  1 },
959 /* 3 : L+AN       */ {     1 ,     0 ,     1 ,     3 ,     5 ,     5 ,     0 ,  1 },
960 /* 4 : L+ON       */ { s(2,1),     0 , s(2,1),     3 ,     4 ,     4 ,     0 ,  0 },
961 /* 5 : L+AN+ON    */ {     1 ,     0 ,     1 ,     3 ,     5 ,     5 ,     0 ,  0 }
962 };
963 static const ImpAct impAct0 = {0,1,2,3,4,5,6};
964 static const ImpTabPair impTab_DEFAULT = {{&impTabL_DEFAULT,
965                                            &impTabR_DEFAULT},
966                                           {&impAct0, &impAct0}};
967 
968 static const ImpTab impTabL_NUMBERS_SPECIAL =   /* Even paragraph level */
969 /*  In this table, conditional sequences receive the higher possible level
970     until proven otherwise.
971 */
972 {
973 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
974 /* 0 : init       */ {     0 ,     2 ,    1 ,      1 ,     0 ,     0 ,     0 ,  0 },
975 /* 1 : L+EN/AN    */ {     0 ,     2 ,    1 ,      1 ,     0 ,     0 ,     0 ,  2 },
976 /* 2 : R          */ {     0 ,     2 ,    4 ,      4 , s(1,3),     0 ,     0 ,  1 },
977 /* 3 : R+ON       */ { s(2,0),     2 ,    4 ,      4 ,     3 ,     3 , s(2,0),  1 },
978 /* 4 : R+EN/AN    */ {     0 ,     2 ,    4 ,      4 , s(1,3), s(1,3),     0 ,  2 }
979   };
980 static const ImpTabPair impTab_NUMBERS_SPECIAL = {{&impTabL_NUMBERS_SPECIAL,
981                                                    &impTabR_DEFAULT},
982                                                   {&impAct0, &impAct0}};
983 
984 static const ImpTab impTabL_GROUP_NUMBERS_WITH_R =
985 /*  In this table, EN/AN+ON sequences receive levels as if associated with R
986     until proven that there is L or sor/eor on both sides. AN is handled like EN.
987 */
988 {
989 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
990 /* 0 init         */ {     0 ,     3 , s(1,1), s(1,1),     0 ,     0 ,     0 ,  0 },
991 /* 1 EN/AN        */ { s(2,0),     3 ,     1 ,     1 ,     2 , s(2,0), s(2,0),  2 },
992 /* 2 EN/AN+ON     */ { s(2,0),     3 ,     1 ,     1 ,     2 , s(2,0), s(2,0),  1 },
993 /* 3 R            */ {     0 ,     3 ,     5 ,     5 , s(1,4),     0 ,     0 ,  1 },
994 /* 4 R+ON         */ { s(2,0),     3 ,     5 ,     5 ,     4 , s(2,0), s(2,0),  1 },
995 /* 5 R+EN/AN      */ {     0 ,     3 ,     5 ,     5 , s(1,4),     0 ,     0 ,  2 }
996 };
997 static const ImpTab impTabR_GROUP_NUMBERS_WITH_R =
998 /*  In this table, EN/AN+ON sequences receive levels as if associated with R
999     until proven that there is L on both sides. AN is handled like EN.
1000 */
1001 {
1002 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1003 /* 0 init         */ {     2 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1004 /* 1 EN/AN        */ {     2 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  1 },
1005 /* 2 L            */ {     2 ,     0 , s(1,4), s(1,4), s(1,3),     0 ,     0 ,  1 },
1006 /* 3 L+ON         */ { s(2,2),     0 ,     4 ,     4 ,     3 ,     0 ,     0 ,  0 },
1007 /* 4 L+EN/AN      */ { s(2,2),     0 ,     4 ,     4 ,     3 ,     0 ,     0 ,  1 }
1008 };
1009 static const ImpTabPair impTab_GROUP_NUMBERS_WITH_R = {
1010                         {&impTabL_GROUP_NUMBERS_WITH_R,
1011                          &impTabR_GROUP_NUMBERS_WITH_R},
1012                         {&impAct0, &impAct0}};
1013 
1014 
1015 static const ImpTab impTabL_INVERSE_NUMBERS_AS_L =
1016 /*  This table is identical to the Default LTR table except that EN and AN are
1017     handled like L.
1018 */
1019 {
1020 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1021 /* 0 : init       */ {     0 ,     1 ,     0 ,     0 ,     0 ,     0 ,     0 ,  0 },
1022 /* 1 : R          */ {     0 ,     1 ,     0 ,     0 , s(1,4), s(1,4),     0 ,  1 },
1023 /* 2 : AN         */ {     0 ,     1 ,     0 ,     0 , s(1,5), s(1,5),     0 ,  2 },
1024 /* 3 : R+EN/AN    */ {     0 ,     1 ,     0 ,     0 , s(1,4), s(1,4),     0 ,  2 },
1025 /* 4 : R+ON       */ { s(2,0),     1 , s(2,0), s(2,0),     4 ,     4 , s(2,0),  1 },
1026 /* 5 : AN+ON      */ { s(2,0),     1 , s(2,0), s(2,0),     5 ,     5 , s(2,0),  1 }
1027 };
1028 static const ImpTab impTabR_INVERSE_NUMBERS_AS_L =
1029 /*  This table is identical to the Default RTL table except that EN and AN are
1030     handled like L.
1031 */
1032 {
1033 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1034 /* 0 : init       */ {     1 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1035 /* 1 : L          */ {     1 ,     0 ,     1 ,     1 , s(1,4), s(1,4),     0 ,  1 },
1036 /* 2 : EN/AN      */ {     1 ,     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  1 },
1037 /* 3 : L+AN       */ {     1 ,     0 ,     1 ,     1 ,     5 ,     5 ,     0 ,  1 },
1038 /* 4 : L+ON       */ { s(2,1),     0 , s(2,1), s(2,1),     4 ,     4 ,     0 ,  0 },
1039 /* 5 : L+AN+ON    */ {     1 ,     0 ,     1 ,     1 ,     5 ,     5 ,     0 ,  0 }
1040 };
1041 static const ImpTabPair impTab_INVERSE_NUMBERS_AS_L = {
1042                         {&impTabL_INVERSE_NUMBERS_AS_L,
1043                          &impTabR_INVERSE_NUMBERS_AS_L},
1044                         {&impAct0, &impAct0}};
1045 
1046 static const ImpTab impTabR_INVERSE_LIKE_DIRECT =   /* Odd  paragraph level */
1047 /*  In this table, conditional sequences receive the lower possible level
1048     until proven otherwise.
1049 */
1050 {
1051 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1052 /* 0 : init       */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  0 },
1053 /* 1 : L          */ {     1 ,     0 ,     1 ,     2 , s(1,3), s(1,3),     0 ,  1 },
1054 /* 2 : EN/AN      */ {     1 ,     0 ,     2 ,     2 ,     0 ,     0 ,     0 ,  1 },
1055 /* 3 : L+ON       */ { s(2,1), s(3,0),     6 ,     4 ,     3 ,     3 , s(3,0),  0 },
1056 /* 4 : L+ON+AN    */ { s(2,1), s(3,0),     6 ,     4 ,     5 ,     5 , s(3,0),  3 },
1057 /* 5 : L+AN+ON    */ { s(2,1), s(3,0),     6 ,     4 ,     5 ,     5 , s(3,0),  2 },
1058 /* 6 : L+ON+EN    */ { s(2,1), s(3,0),     6 ,     4 ,     3 ,     3 , s(3,0),  1 }
1059 };
1060 static const ImpAct impAct1 = {0,1,11,12};
1061 /* FOOD FOR THOUGHT: in LTR table below, check case "JKL 123abc"
1062  */
1063 static const ImpTabPair impTab_INVERSE_LIKE_DIRECT = {
1064                         {&impTabL_DEFAULT,
1065                          &impTabR_INVERSE_LIKE_DIRECT},
1066                         {&impAct0, &impAct1}};
1067 
1068 static const ImpTab impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS =
1069 /*  The case handled in this table is (visually):  R EN L
1070 */
1071 {
1072 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1073 /* 0 : init       */ {     0 , s(6,3),     0 ,     1 ,     0 ,     0 ,     0 ,  0 },
1074 /* 1 : L+AN       */ {     0 , s(6,3),     0 ,     1 , s(1,2), s(3,0),     0 ,  4 },
1075 /* 2 : L+AN+ON    */ { s(2,0), s(6,3), s(2,0),     1 ,     2 , s(3,0), s(2,0),  3 },
1076 /* 3 : R          */ {     0 , s(6,3), s(5,5), s(5,6), s(1,4), s(3,0),     0 ,  3 },
1077 /* 4 : R+ON       */ { s(3,0), s(4,3), s(5,5), s(5,6),     4 , s(3,0), s(3,0),  3 },
1078 /* 5 : R+EN       */ { s(3,0), s(4,3),     5 , s(5,6), s(1,4), s(3,0), s(3,0),  4 },
1079 /* 6 : R+AN       */ { s(3,0), s(4,3), s(5,5),     6 , s(1,4), s(3,0), s(3,0),  4 }
1080 };
1081 static const ImpTab impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS =
1082 /*  The cases handled in this table are (visually):  R EN L
1083                                                      R L AN L
1084 */
1085 {
1086 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1087 /* 0 : init       */ { s(1,3),     0 ,     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1088 /* 1 : R+EN/AN    */ { s(2,3),     0 ,     1 ,     1 ,     2 , s(4,0),     0 ,  1 },
1089 /* 2 : R+EN/AN+ON */ { s(2,3),     0 ,     1 ,     1 ,     2 , s(4,0),     0 ,  0 },
1090 /* 3 : L          */ {     3 ,     0 ,     3 , s(3,6), s(1,4), s(4,0),     0 ,  1 },
1091 /* 4 : L+ON       */ { s(5,3), s(4,0),     5 , s(3,6),     4 , s(4,0), s(4,0),  0 },
1092 /* 5 : L+ON+EN    */ { s(5,3), s(4,0),     5 , s(3,6),     4 , s(4,0), s(4,0),  1 },
1093 /* 6 : L+AN       */ { s(5,3), s(4,0),     6 ,     6 ,     4 , s(4,0), s(4,0),  3 }
1094 };
1095 static const ImpAct impAct2 = {0,1,7,8,9,10};
1096 static const ImpTabPair impTab_INVERSE_LIKE_DIRECT_WITH_MARKS = {
1097                         {&impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS,
1098                          &impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS},
1099                         {&impAct0, &impAct2}};
1100 
1101 static const ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL = {
1102                         {&impTabL_NUMBERS_SPECIAL,
1103                          &impTabR_INVERSE_LIKE_DIRECT},
1104                         {&impAct0, &impAct1}};
1105 
1106 static const ImpTab impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS =
1107 /*  The case handled in this table is (visually):  R EN L
1108 */
1109 {
1110 /*                         L ,     R ,    EN ,    AN ,    ON ,     S ,     B , Res */
1111 /* 0 : init       */ {     0 , s(6,2),     1 ,     1 ,     0 ,     0 ,     0 ,  0 },
1112 /* 1 : L+EN/AN    */ {     0 , s(6,2),     1 ,     1 ,     0 , s(3,0),     0 ,  4 },
1113 /* 2 : R          */ {     0 , s(6,2), s(5,4), s(5,4), s(1,3), s(3,0),     0 ,  3 },
1114 /* 3 : R+ON       */ { s(3,0), s(4,2), s(5,4), s(5,4),     3 , s(3,0), s(3,0),  3 },
1115 /* 4 : R+EN/AN    */ { s(3,0), s(4,2),     4 ,     4 , s(1,3), s(3,0), s(3,0),  4 }
1116 };
1117 static const ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS = {
1118                         {&impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS,
1119                          &impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS},
1120                         {&impAct0, &impAct2}};
1121 
1122 #undef s
1123 
1124 typedef struct {
1125     const ImpTab * pImpTab;             /* level table pointer          */
1126     const ImpAct * pImpAct;             /* action map array             */
1127     int32_t startON;                    /* start of ON sequence         */
1128     int32_t startL2EN;                  /* start of level 2 sequence    */
1129     int32_t lastStrongRTL;              /* index of last found R or AL  */
1130     int32_t state;                      /* current state                */
1131     UBiDiLevel runLevel;                /* run level before implicit solving */
1132 } LevState;
1133 
1134 /*------------------------------------------------------------------------*/
1135 
1136 static void
addPoint(UBiDi * pBiDi,int32_t pos,int32_t flag)1137 addPoint(UBiDi *pBiDi, int32_t pos, int32_t flag)
1138   /* param pos:     position where to insert
1139      param flag:    one of LRM_BEFORE, LRM_AFTER, RLM_BEFORE, RLM_AFTER
1140   */
1141 {
1142 #define FIRSTALLOC  10
1143     Point point;
1144     InsertPoints * pInsertPoints=&(pBiDi->insertPoints);
1145 
1146     if (pInsertPoints->capacity == 0)
1147     {
1148         pInsertPoints->points=uprv_malloc(sizeof(Point)*FIRSTALLOC);
1149         if (pInsertPoints->points == NULL)
1150         {
1151             pInsertPoints->errorCode=U_MEMORY_ALLOCATION_ERROR;
1152             return;
1153         }
1154         pInsertPoints->capacity=FIRSTALLOC;
1155     }
1156     if (pInsertPoints->size >= pInsertPoints->capacity) /* no room for new point */
1157     {
1158         void * savePoints=pInsertPoints->points;
1159         pInsertPoints->points=uprv_realloc(pInsertPoints->points,
1160                                            pInsertPoints->capacity*2*sizeof(Point));
1161         if (pInsertPoints->points == NULL)
1162         {
1163             pInsertPoints->points=savePoints;
1164             pInsertPoints->errorCode=U_MEMORY_ALLOCATION_ERROR;
1165             return;
1166         }
1167         else  pInsertPoints->capacity*=2;
1168     }
1169     point.pos=pos;
1170     point.flag=flag;
1171     pInsertPoints->points[pInsertPoints->size]=point;
1172     pInsertPoints->size++;
1173 #undef FIRSTALLOC
1174 }
1175 
1176 /* perform rules (Wn), (Nn), and (In) on a run of the text ------------------ */
1177 
1178 /*
1179  * This implementation of the (Wn) rules applies all rules in one pass.
1180  * In order to do so, it needs a look-ahead of typically 1 character
1181  * (except for W5: sequences of ET) and keeps track of changes
1182  * in a rule Wp that affect a later Wq (p<q).
1183  *
1184  * The (Nn) and (In) rules are also performed in that same single loop,
1185  * but effectively one iteration behind for white space.
1186  *
1187  * Since all implicit rules are performed in one step, it is not necessary
1188  * to actually store the intermediate directional properties in dirProps[].
1189  */
1190 
1191 static void
processPropertySeq(UBiDi * pBiDi,LevState * pLevState,uint8_t _prop,int32_t start,int32_t limit)1192 processPropertySeq(UBiDi *pBiDi, LevState *pLevState, uint8_t _prop,
1193                    int32_t start, int32_t limit) {
1194     uint8_t cell, oldStateSeq, actionSeq;
1195     const ImpTab * pImpTab=pLevState->pImpTab;
1196     const ImpAct * pImpAct=pLevState->pImpAct;
1197     UBiDiLevel * levels=pBiDi->levels;
1198     UBiDiLevel level, addLevel;
1199     InsertPoints * pInsertPoints;
1200     int32_t start0, k;
1201 
1202     start0=start;                           /* save original start position */
1203     oldStateSeq=(uint8_t)pLevState->state;
1204     cell=(*pImpTab)[oldStateSeq][_prop];
1205     pLevState->state=GET_STATE(cell);       /* isolate the new state */
1206     actionSeq=(*pImpAct)[GET_ACTION(cell)]; /* isolate the action */
1207     addLevel=(*pImpTab)[pLevState->state][IMPTABLEVELS_RES];
1208 
1209     if(actionSeq) {
1210         switch(actionSeq) {
1211         case 1:                         /* init ON seq */
1212             pLevState->startON=start0;
1213             break;
1214 
1215         case 2:                         /* prepend ON seq to current seq */
1216             start=pLevState->startON;
1217             break;
1218 
1219         case 3:                         /* L or S after possible relevant EN/AN */
1220             /* check if we had EN after R/AL */
1221             if (pLevState->startL2EN >= 0) {
1222                 addPoint(pBiDi, pLevState->startL2EN, LRM_BEFORE);
1223             }
1224             pLevState->startL2EN=-1;  /* not within previous if since could also be -2 */
1225             /* check if we had any relevant EN/AN after R/AL */
1226             pInsertPoints=&(pBiDi->insertPoints);
1227             if ((pInsertPoints->capacity == 0) ||
1228                 (pInsertPoints->size <= pInsertPoints->confirmed))
1229             {
1230                 /* nothing, just clean up */
1231                 pLevState->lastStrongRTL=-1;
1232                 /* check if we have a pending conditional segment */
1233                 level=(*pImpTab)[oldStateSeq][IMPTABLEVELS_RES];
1234                 if ((level & 1) && (pLevState->startON > 0)) {  /* after ON */
1235                     start=pLevState->startON;   /* reset to basic run level */
1236                 }
1237                 if (_prop == DirProp_S)                /* add LRM before S */
1238                 {
1239                     addPoint(pBiDi, start0, LRM_BEFORE);
1240                     pInsertPoints->confirmed=pInsertPoints->size;
1241                 }
1242                 break;
1243             }
1244             /* reset previous RTL cont to level for LTR text */
1245             for (k=pLevState->lastStrongRTL+1; k<start0; k++)
1246             {
1247                 /* reset odd level, leave runLevel+2 as is */
1248                 levels[k]=(levels[k] - 2) & ~1;
1249             }
1250             /* mark insert points as confirmed */
1251             pInsertPoints->confirmed=pInsertPoints->size;
1252             pLevState->lastStrongRTL=-1;
1253             if (_prop == DirProp_S)            /* add LRM before S */
1254             {
1255                 addPoint(pBiDi, start0, LRM_BEFORE);
1256                 pInsertPoints->confirmed=pInsertPoints->size;
1257             }
1258             break;
1259 
1260         case 4:                         /* R/AL after possible relevant EN/AN */
1261             /* just clean up */
1262             pInsertPoints=&(pBiDi->insertPoints);
1263             if (pInsertPoints->capacity > 0)
1264                 /* remove all non confirmed insert points */
1265                 pInsertPoints->size=pInsertPoints->confirmed;
1266             pLevState->startON=-1;
1267             pLevState->startL2EN=-1;
1268             pLevState->lastStrongRTL=limit - 1;
1269             break;
1270 
1271         case 5:                         /* EN/AN after R/AL + possible cont */
1272             /* check for real AN */
1273             if ((_prop == DirProp_AN) && (NO_CONTEXT_RTL(pBiDi->dirProps[start0]) == AN) &&
1274                 (pBiDi->reorderingMode!=UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL))
1275             {
1276                 /* real AN */
1277                 if (pLevState->startL2EN == -1) /* if no relevant EN already found */
1278                 {
1279                     /* just note the righmost digit as a strong RTL */
1280                     pLevState->lastStrongRTL=limit - 1;
1281                     break;
1282                 }
1283                 if (pLevState->startL2EN >= 0)  /* after EN, no AN */
1284                 {
1285                     addPoint(pBiDi, pLevState->startL2EN, LRM_BEFORE);
1286                     pLevState->startL2EN=-2;
1287                 }
1288                 /* note AN */
1289                 addPoint(pBiDi, start0, LRM_BEFORE);
1290                 break;
1291             }
1292             /* if first EN/AN after R/AL */
1293             if (pLevState->startL2EN == -1) {
1294                 pLevState->startL2EN=start0;
1295             }
1296             break;
1297 
1298         case 6:                         /* note location of latest R/AL */
1299             pLevState->lastStrongRTL=limit - 1;
1300             pLevState->startON=-1;
1301             break;
1302 
1303         case 7:                         /* L after R+ON/EN/AN */
1304             /* include possible adjacent number on the left */
1305             for (k=start0-1; k>=0 && !(levels[k]&1); k--);
1306             if(k>=0) {
1307                 addPoint(pBiDi, k, RLM_BEFORE);             /* add RLM before */
1308                 pInsertPoints=&(pBiDi->insertPoints);
1309                 pInsertPoints->confirmed=pInsertPoints->size;   /* confirm it */
1310             }
1311             pLevState->startON=start0;
1312             break;
1313 
1314         case 8:                         /* AN after L */
1315             /* AN numbers between L text on both sides may be trouble. */
1316             /* tentatively bracket with LRMs; will be confirmed if followed by L */
1317             addPoint(pBiDi, start0, LRM_BEFORE);    /* add LRM before */
1318             addPoint(pBiDi, start0, LRM_AFTER);     /* add LRM after  */
1319             break;
1320 
1321         case 9:                         /* R after L+ON/EN/AN */
1322             /* false alert, infirm LRMs around previous AN */
1323             pInsertPoints=&(pBiDi->insertPoints);
1324             pInsertPoints->size=pInsertPoints->confirmed;
1325             if (_prop == DirProp_S)            /* add RLM before S */
1326             {
1327                 addPoint(pBiDi, start0, RLM_BEFORE);
1328                 pInsertPoints->confirmed=pInsertPoints->size;
1329             }
1330             break;
1331 
1332         case 10:                        /* L after L+ON/AN */
1333             level=pLevState->runLevel + addLevel;
1334             for(k=pLevState->startON; k<start0; k++) {
1335                 if (levels[k]<level)
1336                     levels[k]=level;
1337             }
1338             pInsertPoints=&(pBiDi->insertPoints);
1339             pInsertPoints->confirmed=pInsertPoints->size;   /* confirm inserts */
1340             pLevState->startON=start0;
1341             break;
1342 
1343         case 11:                        /* L after L+ON+EN/AN/ON */
1344             level=pLevState->runLevel;
1345             for(k=start0-1; k>=pLevState->startON; k--) {
1346                 if(levels[k]==level+3) {
1347                     while(levels[k]==level+3) {
1348                         levels[k--]-=2;
1349                     }
1350                     while(levels[k]==level) {
1351                         k--;
1352                     }
1353                 }
1354                 if(levels[k]==level+2) {
1355                     levels[k]=level;
1356                     continue;
1357                 }
1358                 levels[k]=level+1;
1359             }
1360             break;
1361 
1362         case 12:                        /* R after L+ON+EN/AN/ON */
1363             level=pLevState->runLevel+1;
1364             for(k=start0-1; k>=pLevState->startON; k--) {
1365                 if(levels[k]>level) {
1366                     levels[k]-=2;
1367                 }
1368             }
1369             break;
1370 
1371         default:                        /* we should never get here */
1372             U_ASSERT(FALSE);
1373             break;
1374         }
1375     }
1376     if((addLevel) || (start < start0)) {
1377         level=pLevState->runLevel + addLevel;
1378         for(k=start; k<limit; k++) {
1379             levels[k]=level;
1380         }
1381     }
1382 }
1383 
1384 static void
resolveImplicitLevels(UBiDi * pBiDi,int32_t start,int32_t limit,DirProp sor,DirProp eor)1385 resolveImplicitLevels(UBiDi *pBiDi,
1386                       int32_t start, int32_t limit,
1387                       DirProp sor, DirProp eor) {
1388     const DirProp *dirProps=pBiDi->dirProps;
1389 
1390     LevState levState;
1391     int32_t i, start1, start2;
1392     uint8_t oldStateImp, stateImp, actionImp;
1393     uint8_t gprop, resProp, cell;
1394     UBool inverseRTL;
1395     DirProp nextStrongProp=R;
1396     int32_t nextStrongPos=-1;
1397 
1398     levState.startON = -1;  /* silence gcc flow analysis */
1399 
1400     /* check for RTL inverse BiDi mode */
1401     /* FOOD FOR THOUGHT: in case of RTL inverse BiDi, it would make sense to
1402      * loop on the text characters from end to start.
1403      * This would need a different properties state table (at least different
1404      * actions) and different levels state tables (maybe very similar to the
1405      * LTR corresponding ones.
1406      */
1407     inverseRTL=(UBool)
1408         ((start<pBiDi->lastArabicPos) && (GET_PARALEVEL(pBiDi, start) & 1) &&
1409          (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT  ||
1410           pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL));
1411     /* initialize for levels state table */
1412     levState.startL2EN=-1;              /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */
1413     levState.lastStrongRTL=-1;          /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */
1414     levState.state=0;
1415     levState.runLevel=pBiDi->levels[start];
1416     levState.pImpTab=(const ImpTab*)((pBiDi->pImpTabPair)->pImpTab)[levState.runLevel&1];
1417     levState.pImpAct=(const ImpAct*)((pBiDi->pImpTabPair)->pImpAct)[levState.runLevel&1];
1418     processPropertySeq(pBiDi, &levState, sor, start, start);
1419     /* initialize for property state table */
1420     if(NO_CONTEXT_RTL(dirProps[start])==NSM) {
1421         stateImp = 1 + sor;
1422     } else {
1423         stateImp=0;
1424     }
1425     start1=start;
1426     start2=start;
1427 
1428     for(i=start; i<=limit; i++) {
1429         if(i>=limit) {
1430             gprop=eor;
1431         } else {
1432             DirProp prop, prop1;
1433             prop=NO_CONTEXT_RTL(dirProps[i]);
1434             if(inverseRTL) {
1435                 if(prop==AL) {
1436                     /* AL before EN does not make it AN */
1437                     prop=R;
1438                 } else if(prop==EN) {
1439                     if(nextStrongPos<=i) {
1440                         /* look for next strong char (L/R/AL) */
1441                         int32_t j;
1442                         nextStrongProp=R;   /* set default */
1443                         nextStrongPos=limit;
1444                         for(j=i+1; j<limit; j++) {
1445                             prop1=NO_CONTEXT_RTL(dirProps[j]);
1446                             if(prop1==L || prop1==R || prop1==AL) {
1447                                 nextStrongProp=prop1;
1448                                 nextStrongPos=j;
1449                                 break;
1450                             }
1451                         }
1452                     }
1453                     if(nextStrongProp==AL) {
1454                         prop=AN;
1455                     }
1456                 }
1457             }
1458             gprop=groupProp[prop];
1459         }
1460         oldStateImp=stateImp;
1461         cell=impTabProps[oldStateImp][gprop];
1462         stateImp=GET_STATEPROPS(cell);      /* isolate the new state */
1463         actionImp=GET_ACTIONPROPS(cell);    /* isolate the action */
1464         if((i==limit) && (actionImp==0)) {
1465             /* there is an unprocessed sequence if its property == eor   */
1466             actionImp=1;                    /* process the last sequence */
1467         }
1468         if(actionImp) {
1469             resProp=impTabProps[oldStateImp][IMPTABPROPS_RES];
1470             switch(actionImp) {
1471             case 1:             /* process current seq1, init new seq1 */
1472                 processPropertySeq(pBiDi, &levState, resProp, start1, i);
1473                 start1=i;
1474                 break;
1475             case 2:             /* init new seq2 */
1476                 start2=i;
1477                 break;
1478             case 3:             /* process seq1, process seq2, init new seq1 */
1479                 processPropertySeq(pBiDi, &levState, resProp, start1, start2);
1480                 processPropertySeq(pBiDi, &levState, DirProp_ON, start2, i);
1481                 start1=i;
1482                 break;
1483             case 4:             /* process seq1, set seq1=seq2, init new seq2 */
1484                 processPropertySeq(pBiDi, &levState, resProp, start1, start2);
1485                 start1=start2;
1486                 start2=i;
1487                 break;
1488             default:            /* we should never get here */
1489                 U_ASSERT(FALSE);
1490                 break;
1491             }
1492         }
1493     }
1494     /* flush possible pending sequence, e.g. ON */
1495     processPropertySeq(pBiDi, &levState, eor, limit, limit);
1496 }
1497 
1498 /* perform (L1) and (X9) ---------------------------------------------------- */
1499 
1500 /*
1501  * Reset the embedding levels for some non-graphic characters (L1).
1502  * This function also sets appropriate levels for BN, and
1503  * explicit embedding types that are supposed to have been removed
1504  * from the paragraph in (X9).
1505  */
1506 static void
adjustWSLevels(UBiDi * pBiDi)1507 adjustWSLevels(UBiDi *pBiDi) {
1508     const DirProp *dirProps=pBiDi->dirProps;
1509     UBiDiLevel *levels=pBiDi->levels;
1510     int32_t i;
1511 
1512     if(pBiDi->flags&MASK_WS) {
1513         UBool orderParagraphsLTR=pBiDi->orderParagraphsLTR;
1514         Flags flag;
1515 
1516         i=pBiDi->trailingWSStart;
1517         while(i>0) {
1518             /* reset a sequence of WS/BN before eop and B/S to the paragraph paraLevel */
1519             while(i>0 && (flag=DIRPROP_FLAG_NC(dirProps[--i]))&MASK_WS) {
1520                 if(orderParagraphsLTR&&(flag&DIRPROP_FLAG(B))) {
1521                     levels[i]=0;
1522                 } else {
1523                     levels[i]=GET_PARALEVEL(pBiDi, i);
1524                 }
1525             }
1526 
1527             /* reset BN to the next character's paraLevel until B/S, which restarts above loop */
1528             /* here, i+1 is guaranteed to be <length */
1529             while(i>0) {
1530                 flag=DIRPROP_FLAG_NC(dirProps[--i]);
1531                 if(flag&MASK_BN_EXPLICIT) {
1532                     levels[i]=levels[i+1];
1533                 } else if(orderParagraphsLTR&&(flag&DIRPROP_FLAG(B))) {
1534                     levels[i]=0;
1535                     break;
1536                 } else if(flag&MASK_B_S) {
1537                     levels[i]=GET_PARALEVEL(pBiDi, i);
1538                     break;
1539                 }
1540             }
1541         }
1542     }
1543 }
1544 
1545 #define BIDI_MIN(x, y)   ((x)<(y) ? (x) : (y))
1546 #define BIDI_ABS(x)      ((x)>=0  ? (x) : (-(x)))
1547 static void
setParaRunsOnly(UBiDi * pBiDi,const UChar * text,int32_t length,UBiDiLevel paraLevel,UErrorCode * pErrorCode)1548 setParaRunsOnly(UBiDi *pBiDi, const UChar *text, int32_t length,
1549                 UBiDiLevel paraLevel, UErrorCode *pErrorCode) {
1550     void *runsOnlyMemory;
1551     int32_t *visualMap;
1552     UChar *visualText;
1553     int32_t saveLength, saveTrailingWSStart;
1554     const UBiDiLevel *levels;
1555     UBiDiLevel *saveLevels;
1556     UBiDiDirection saveDirection;
1557     UBool saveMayAllocateText;
1558     Run *runs;
1559     int32_t visualLength, i, j, visualStart, logicalStart,
1560             runCount, runLength, addedRuns, insertRemove,
1561             start, limit, step, indexOddBit, logicalPos,
1562             index0, index1;
1563     uint32_t saveOptions;
1564 
1565     pBiDi->reorderingMode=UBIDI_REORDER_DEFAULT;
1566     if(length==0) {
1567         ubidi_setPara(pBiDi, text, length, paraLevel, NULL, pErrorCode);
1568         goto cleanup3;
1569     }
1570     /* obtain memory for mapping table and visual text */
1571     runsOnlyMemory=uprv_malloc(length*(sizeof(int32_t)+sizeof(UChar)+sizeof(UBiDiLevel)));
1572     if(runsOnlyMemory==NULL) {
1573         *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
1574         goto cleanup3;
1575     }
1576     visualMap=runsOnlyMemory;
1577     visualText=(UChar *)&visualMap[length];
1578     saveLevels=(UBiDiLevel *)&visualText[length];
1579     saveOptions=pBiDi->reorderingOptions;
1580     if(saveOptions & UBIDI_OPTION_INSERT_MARKS) {
1581         pBiDi->reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS;
1582         pBiDi->reorderingOptions|=UBIDI_OPTION_REMOVE_CONTROLS;
1583     }
1584     paraLevel&=1;                       /* accept only 0 or 1 */
1585     ubidi_setPara(pBiDi, text, length, paraLevel, NULL, pErrorCode);
1586     if(U_FAILURE(*pErrorCode)) {
1587         goto cleanup3;
1588     }
1589     /* we cannot access directly pBiDi->levels since it is not yet set if
1590      * direction is not MIXED
1591      */
1592     levels=ubidi_getLevels(pBiDi, pErrorCode);
1593     uprv_memcpy(saveLevels, levels, pBiDi->length*sizeof(UBiDiLevel));
1594     saveTrailingWSStart=pBiDi->trailingWSStart;
1595     saveLength=pBiDi->length;
1596     saveDirection=pBiDi->direction;
1597 
1598     /* FOOD FOR THOUGHT: instead of writing the visual text, we could use
1599      * the visual map and the dirProps array to drive the second call
1600      * to ubidi_setPara (but must make provision for possible removal of
1601      * BiDi controls.  Alternatively, only use the dirProps array via
1602      * customized classifier callback.
1603      */
1604     visualLength=ubidi_writeReordered(pBiDi, visualText, length,
1605                                       UBIDI_DO_MIRRORING, pErrorCode);
1606     ubidi_getVisualMap(pBiDi, visualMap, pErrorCode);
1607     if(U_FAILURE(*pErrorCode)) {
1608         goto cleanup2;
1609     }
1610     pBiDi->reorderingOptions=saveOptions;
1611 
1612     pBiDi->reorderingMode=UBIDI_REORDER_INVERSE_LIKE_DIRECT;
1613     paraLevel^=1;
1614     /* Because what we did with reorderingOptions, visualText may be shorter
1615      * than the original text. But we don't want the levels memory to be
1616      * reallocated shorter than the original length, since we need to restore
1617      * the levels as after the first call to ubidi_setpara() before returning.
1618      * We will force mayAllocateText to FALSE before the second call to
1619      * ubidi_setpara(), and will restore it afterwards.
1620      */
1621     saveMayAllocateText=pBiDi->mayAllocateText;
1622     pBiDi->mayAllocateText=FALSE;
1623     ubidi_setPara(pBiDi, visualText, visualLength, paraLevel, NULL, pErrorCode);
1624     pBiDi->mayAllocateText=saveMayAllocateText;
1625     ubidi_getRuns(pBiDi, pErrorCode);
1626     if(U_FAILURE(*pErrorCode)) {
1627         goto cleanup1;
1628     }
1629     /* check if some runs must be split, count how many splits */
1630     addedRuns=0;
1631     runCount=pBiDi->runCount;
1632     runs=pBiDi->runs;
1633     visualStart=0;
1634     for(i=0; i<runCount; i++, visualStart+=runLength) {
1635         runLength=runs[i].visualLimit-visualStart;
1636         if(runLength<2) {
1637             continue;
1638         }
1639         logicalStart=GET_INDEX(runs[i].logicalStart);
1640         for(j=logicalStart+1; j<logicalStart+runLength; j++) {
1641             index0=visualMap[j];
1642             index1=visualMap[j-1];
1643             if((BIDI_ABS(index0-index1)!=1) || (saveLevels[index0]!=saveLevels[index1])) {
1644                 addedRuns++;
1645             }
1646         }
1647     }
1648     if(addedRuns) {
1649         if(getRunsMemory(pBiDi, runCount+addedRuns)) {
1650             if(runCount==1) {
1651                 /* because we switch from UBiDi.simpleRuns to UBiDi.runs */
1652                 pBiDi->runsMemory[0]=runs[0];
1653             }
1654             runs=pBiDi->runs=pBiDi->runsMemory;
1655             pBiDi->runCount+=addedRuns;
1656         } else {
1657             goto cleanup1;
1658         }
1659     }
1660     /* split runs which are not consecutive in source text */
1661     for(i=runCount-1; i>=0; i--) {
1662         runLength= i==0 ? runs[0].visualLimit :
1663                           runs[i].visualLimit-runs[i-1].visualLimit;
1664         logicalStart=runs[i].logicalStart;
1665         indexOddBit=GET_ODD_BIT(logicalStart);
1666         logicalStart=GET_INDEX(logicalStart);
1667         if(runLength<2) {
1668             if(addedRuns) {
1669                 runs[i+addedRuns]=runs[i];
1670             }
1671             logicalPos=visualMap[logicalStart];
1672             runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
1673                                             saveLevels[logicalPos]^indexOddBit);
1674             continue;
1675         }
1676         if(indexOddBit) {
1677             start=logicalStart;
1678             limit=logicalStart+runLength-1;
1679             step=1;
1680         } else {
1681             start=logicalStart+runLength-1;
1682             limit=logicalStart;
1683             step=-1;
1684         }
1685         for(j=start; j!=limit; j+=step) {
1686             index0=visualMap[j];
1687             index1=visualMap[j+step];
1688             if((BIDI_ABS(index0-index1)!=1) || (saveLevels[index0]!=saveLevels[index1])) {
1689                 logicalPos=BIDI_MIN(visualMap[start], index0);
1690                 runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
1691                                             saveLevels[logicalPos]^indexOddBit);
1692                 runs[i+addedRuns].visualLimit=runs[i].visualLimit;
1693                 runs[i].visualLimit-=BIDI_ABS(j-start)+1;
1694                 insertRemove=runs[i].insertRemove&(LRM_AFTER|RLM_AFTER);
1695                 runs[i+addedRuns].insertRemove=insertRemove;
1696                 runs[i].insertRemove&=~insertRemove;
1697                 start=j+step;
1698                 addedRuns--;
1699             }
1700         }
1701         if(addedRuns) {
1702             runs[i+addedRuns]=runs[i];
1703         }
1704         logicalPos=BIDI_MIN(visualMap[start], visualMap[limit]);
1705         runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
1706                                             saveLevels[logicalPos]^indexOddBit);
1707     }
1708 
1709   cleanup1:
1710     /* restore initial paraLevel */
1711     pBiDi->paraLevel^=1;
1712   cleanup2:
1713     /* restore real text */
1714     pBiDi->text=text;
1715     pBiDi->length=saveLength;
1716     pBiDi->originalLength=length;
1717     pBiDi->direction=saveDirection;
1718     /* the saved levels should never excess levelsSize, but we check anyway */
1719     if(saveLength>pBiDi->levelsSize) {
1720         saveLength=pBiDi->levelsSize;
1721     }
1722     uprv_memcpy(pBiDi->levels, saveLevels, saveLength*sizeof(UBiDiLevel));
1723     pBiDi->trailingWSStart=saveTrailingWSStart;
1724     /* free memory for mapping table and visual text */
1725     uprv_free(runsOnlyMemory);
1726     if(pBiDi->runCount>1) {
1727         pBiDi->direction=UBIDI_MIXED;
1728     }
1729   cleanup3:
1730     pBiDi->reorderingMode=UBIDI_REORDER_RUNS_ONLY;
1731 }
1732 
1733 /* ubidi_setPara ------------------------------------------------------------ */
1734 
1735 U_CAPI void U_EXPORT2
ubidi_setPara(UBiDi * pBiDi,const UChar * text,int32_t length,UBiDiLevel paraLevel,UBiDiLevel * embeddingLevels,UErrorCode * pErrorCode)1736 ubidi_setPara(UBiDi *pBiDi, const UChar *text, int32_t length,
1737               UBiDiLevel paraLevel, UBiDiLevel *embeddingLevels,
1738               UErrorCode *pErrorCode) {
1739     UBiDiDirection direction;
1740 
1741     /* check the argument values */
1742     RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
1743     if(pBiDi==NULL || text==NULL || length<-1 ||
1744        (paraLevel>UBIDI_MAX_EXPLICIT_LEVEL && paraLevel<UBIDI_DEFAULT_LTR)) {
1745         *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
1746         return;
1747     }
1748 
1749     if(length==-1) {
1750         length=u_strlen(text);
1751     }
1752 
1753     /* special treatment for RUNS_ONLY mode */
1754     if(pBiDi->reorderingMode==UBIDI_REORDER_RUNS_ONLY) {
1755         setParaRunsOnly(pBiDi, text, length, paraLevel, pErrorCode);
1756         return;
1757     }
1758 
1759     /* initialize the UBiDi structure */
1760     pBiDi->pParaBiDi=NULL;          /* mark unfinished setPara */
1761     pBiDi->text=text;
1762     pBiDi->length=pBiDi->originalLength=pBiDi->resultLength=length;
1763     pBiDi->paraLevel=paraLevel;
1764     pBiDi->direction=UBIDI_LTR;
1765     pBiDi->paraCount=1;
1766 
1767     pBiDi->dirProps=NULL;
1768     pBiDi->levels=NULL;
1769     pBiDi->runs=NULL;
1770     pBiDi->insertPoints.size=0;         /* clean up from last call */
1771     pBiDi->insertPoints.confirmed=0;    /* clean up from last call */
1772 
1773     /*
1774      * Save the original paraLevel if contextual; otherwise, set to 0.
1775      */
1776     if(IS_DEFAULT_LEVEL(paraLevel)) {
1777         pBiDi->defaultParaLevel=paraLevel;
1778     } else {
1779         pBiDi->defaultParaLevel=0;
1780     }
1781 
1782     if(length==0) {
1783         /*
1784          * For an empty paragraph, create a UBiDi object with the paraLevel and
1785          * the flags and the direction set but without allocating zero-length arrays.
1786          * There is nothing more to do.
1787          */
1788         if(IS_DEFAULT_LEVEL(paraLevel)) {
1789             pBiDi->paraLevel&=1;
1790             pBiDi->defaultParaLevel=0;
1791         }
1792         if(paraLevel&1) {
1793             pBiDi->flags=DIRPROP_FLAG(R);
1794             pBiDi->direction=UBIDI_RTL;
1795         } else {
1796             pBiDi->flags=DIRPROP_FLAG(L);
1797             pBiDi->direction=UBIDI_LTR;
1798         }
1799 
1800         pBiDi->runCount=0;
1801         pBiDi->paraCount=0;
1802         pBiDi->pParaBiDi=pBiDi;         /* mark successful setPara */
1803         return;
1804     }
1805 
1806     pBiDi->runCount=-1;
1807 
1808     /*
1809      * Get the directional properties,
1810      * the flags bit-set, and
1811      * determine the paragraph level if necessary.
1812      */
1813     if(getDirPropsMemory(pBiDi, length)) {
1814         pBiDi->dirProps=pBiDi->dirPropsMemory;
1815         getDirProps(pBiDi);
1816     } else {
1817         *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
1818         return;
1819     }
1820     /* the processed length may have changed if UBIDI_OPTION_STREAMING */
1821     length= pBiDi->length;
1822     pBiDi->trailingWSStart=length;  /* the levels[] will reflect the WS run */
1823     /* allocate paras memory */
1824     if(pBiDi->paraCount>1) {
1825         if(getInitialParasMemory(pBiDi, pBiDi->paraCount)) {
1826             pBiDi->paras=pBiDi->parasMemory;
1827             pBiDi->paras[pBiDi->paraCount-1]=length;
1828         } else {
1829             *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
1830             return;
1831         }
1832     } else {
1833         /* initialize paras for single paragraph */
1834         pBiDi->paras=pBiDi->simpleParas;
1835         pBiDi->simpleParas[0]=length;
1836     }
1837 
1838     /* are explicit levels specified? */
1839     if(embeddingLevels==NULL) {
1840         /* no: determine explicit levels according to the (Xn) rules */\
1841         if(getLevelsMemory(pBiDi, length)) {
1842             pBiDi->levels=pBiDi->levelsMemory;
1843             direction=resolveExplicitLevels(pBiDi);
1844         } else {
1845             *pErrorCode=U_MEMORY_ALLOCATION_ERROR;
1846             return;
1847         }
1848     } else {
1849         /* set BN for all explicit codes, check that all levels are 0 or paraLevel..UBIDI_MAX_EXPLICIT_LEVEL */
1850         pBiDi->levels=embeddingLevels;
1851         direction=checkExplicitLevels(pBiDi, pErrorCode);
1852         if(U_FAILURE(*pErrorCode)) {
1853             return;
1854         }
1855     }
1856 
1857     /*
1858      * The steps after (X9) in the UBiDi algorithm are performed only if
1859      * the paragraph text has mixed directionality!
1860      */
1861     pBiDi->direction=direction;
1862     switch(direction) {
1863     case UBIDI_LTR:
1864         /* make sure paraLevel is even */
1865         pBiDi->paraLevel=(UBiDiLevel)((pBiDi->paraLevel+1)&~1);
1866 
1867         /* all levels are implicitly at paraLevel (important for ubidi_getLevels()) */
1868         pBiDi->trailingWSStart=0;
1869         break;
1870     case UBIDI_RTL:
1871         /* make sure paraLevel is odd */
1872         pBiDi->paraLevel|=1;
1873 
1874         /* all levels are implicitly at paraLevel (important for ubidi_getLevels()) */
1875         pBiDi->trailingWSStart=0;
1876         break;
1877     default:
1878         /*
1879          *  Choose the right implicit state table
1880          */
1881         switch(pBiDi->reorderingMode) {
1882         case UBIDI_REORDER_DEFAULT:
1883             pBiDi->pImpTabPair=&impTab_DEFAULT;
1884             break;
1885         case UBIDI_REORDER_NUMBERS_SPECIAL:
1886             pBiDi->pImpTabPair=&impTab_NUMBERS_SPECIAL;
1887             break;
1888         case UBIDI_REORDER_GROUP_NUMBERS_WITH_R:
1889             pBiDi->pImpTabPair=&impTab_GROUP_NUMBERS_WITH_R;
1890             break;
1891         case UBIDI_REORDER_INVERSE_NUMBERS_AS_L:
1892             pBiDi->pImpTabPair=&impTab_INVERSE_NUMBERS_AS_L;
1893             break;
1894         case UBIDI_REORDER_INVERSE_LIKE_DIRECT:
1895             if (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) {
1896                 pBiDi->pImpTabPair=&impTab_INVERSE_LIKE_DIRECT_WITH_MARKS;
1897             } else {
1898                 pBiDi->pImpTabPair=&impTab_INVERSE_LIKE_DIRECT;
1899             }
1900             break;
1901         case UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL:
1902             if (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) {
1903                 pBiDi->pImpTabPair=&impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS;
1904             } else {
1905                 pBiDi->pImpTabPair=&impTab_INVERSE_FOR_NUMBERS_SPECIAL;
1906             }
1907             break;
1908         default:
1909             /* we should never get here */
1910             U_ASSERT(FALSE);
1911             break;
1912         }
1913         /*
1914          * If there are no external levels specified and there
1915          * are no significant explicit level codes in the text,
1916          * then we can treat the entire paragraph as one run.
1917          * Otherwise, we need to perform the following rules on runs of
1918          * the text with the same embedding levels. (X10)
1919          * "Significant" explicit level codes are ones that actually
1920          * affect non-BN characters.
1921          * Examples for "insignificant" ones are empty embeddings
1922          * LRE-PDF, LRE-RLE-PDF-PDF, etc.
1923          */
1924         if(embeddingLevels==NULL && pBiDi->paraCount<=1 &&
1925                                    !(pBiDi->flags&DIRPROP_FLAG_MULTI_RUNS)) {
1926             resolveImplicitLevels(pBiDi, 0, length,
1927                                     GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, 0)),
1928                                     GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, length-1)));
1929         } else {
1930             /* sor, eor: start and end types of same-level-run */
1931             UBiDiLevel *levels=pBiDi->levels;
1932             int32_t start, limit=0;
1933             UBiDiLevel level, nextLevel;
1934             DirProp sor, eor;
1935 
1936             /* determine the first sor and set eor to it because of the loop body (sor=eor there) */
1937             level=GET_PARALEVEL(pBiDi, 0);
1938             nextLevel=levels[0];
1939             if(level<nextLevel) {
1940                 eor=GET_LR_FROM_LEVEL(nextLevel);
1941             } else {
1942                 eor=GET_LR_FROM_LEVEL(level);
1943             }
1944 
1945             do {
1946                 /* determine start and limit of the run (end points just behind the run) */
1947 
1948                 /* the values for this run's start are the same as for the previous run's end */
1949                 start=limit;
1950                 level=nextLevel;
1951                 if((start>0) && (NO_CONTEXT_RTL(pBiDi->dirProps[start-1])==B)) {
1952                     /* except if this is a new paragraph, then set sor = para level */
1953                     sor=GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, start));
1954                 } else {
1955                     sor=eor;
1956                 }
1957 
1958                 /* search for the limit of this run */
1959                 while(++limit<length && levels[limit]==level) {}
1960 
1961                 /* get the correct level of the next run */
1962                 if(limit<length) {
1963                     nextLevel=levels[limit];
1964                 } else {
1965                     nextLevel=GET_PARALEVEL(pBiDi, length-1);
1966                 }
1967 
1968                 /* determine eor from max(level, nextLevel); sor is last run's eor */
1969                 if((level&~UBIDI_LEVEL_OVERRIDE)<(nextLevel&~UBIDI_LEVEL_OVERRIDE)) {
1970                     eor=GET_LR_FROM_LEVEL(nextLevel);
1971                 } else {
1972                     eor=GET_LR_FROM_LEVEL(level);
1973                 }
1974 
1975                 /* if the run consists of overridden directional types, then there
1976                    are no implicit types to be resolved */
1977                 if(!(level&UBIDI_LEVEL_OVERRIDE)) {
1978                     resolveImplicitLevels(pBiDi, start, limit, sor, eor);
1979                 } else {
1980                     /* remove the UBIDI_LEVEL_OVERRIDE flags */
1981                     do {
1982                         levels[start++]&=~UBIDI_LEVEL_OVERRIDE;
1983                     } while(start<limit);
1984                 }
1985             } while(limit<length);
1986         }
1987         /* check if we got any memory shortage while adding insert points */
1988         if (U_FAILURE(pBiDi->insertPoints.errorCode))
1989         {
1990             *pErrorCode=pBiDi->insertPoints.errorCode;
1991             return;
1992         }
1993         /* reset the embedding levels for some non-graphic characters (L1), (X9) */
1994         adjustWSLevels(pBiDi);
1995         break;
1996     }
1997     /* add RLM for inverse Bidi with contextual orientation resolving
1998      * to RTL which would not round-trip otherwise
1999      */
2000     if((pBiDi->defaultParaLevel>0) &&
2001        (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) &&
2002        ((pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT) ||
2003         (pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL))) {
2004         int32_t i, j, start, last;
2005         DirProp dirProp;
2006         for(i=0; i<pBiDi->paraCount; i++) {
2007             last=pBiDi->paras[i]-1;
2008             if((pBiDi->dirProps[last] & CONTEXT_RTL)==0) {
2009                 continue;           /* LTR paragraph */
2010             }
2011             start= i==0 ? 0 : pBiDi->paras[i - 1];
2012             for(j=last; j>=start; j--) {
2013                 dirProp=NO_CONTEXT_RTL(pBiDi->dirProps[j]);
2014                 if(dirProp==L) {
2015                     if(j<last) {
2016                         while(NO_CONTEXT_RTL(pBiDi->dirProps[last])==B) {
2017                             last--;
2018                         }
2019                     }
2020                     addPoint(pBiDi, last, RLM_BEFORE);
2021                     break;
2022                 }
2023                 if(DIRPROP_FLAG(dirProp) & MASK_R_AL) {
2024                     break;
2025                 }
2026             }
2027         }
2028     }
2029 
2030     if(pBiDi->reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS) {
2031         pBiDi->resultLength -= pBiDi->controlCount;
2032     } else {
2033         pBiDi->resultLength += pBiDi->insertPoints.size;
2034     }
2035     pBiDi->pParaBiDi=pBiDi;             /* mark successful setPara */
2036 }
2037 
2038 U_CAPI void U_EXPORT2
ubidi_orderParagraphsLTR(UBiDi * pBiDi,UBool orderParagraphsLTR)2039 ubidi_orderParagraphsLTR(UBiDi *pBiDi, UBool orderParagraphsLTR) {
2040     if(pBiDi!=NULL) {
2041         pBiDi->orderParagraphsLTR=orderParagraphsLTR;
2042     }
2043 }
2044 
2045 U_CAPI UBool U_EXPORT2
ubidi_isOrderParagraphsLTR(UBiDi * pBiDi)2046 ubidi_isOrderParagraphsLTR(UBiDi *pBiDi) {
2047     if(pBiDi!=NULL) {
2048         return pBiDi->orderParagraphsLTR;
2049     } else {
2050         return FALSE;
2051     }
2052 }
2053 
2054 U_CAPI UBiDiDirection U_EXPORT2
ubidi_getDirection(const UBiDi * pBiDi)2055 ubidi_getDirection(const UBiDi *pBiDi) {
2056     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2057         return pBiDi->direction;
2058     } else {
2059         return UBIDI_LTR;
2060     }
2061 }
2062 
2063 U_CAPI const UChar * U_EXPORT2
ubidi_getText(const UBiDi * pBiDi)2064 ubidi_getText(const UBiDi *pBiDi) {
2065     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2066         return pBiDi->text;
2067     } else {
2068         return NULL;
2069     }
2070 }
2071 
2072 U_CAPI int32_t U_EXPORT2
ubidi_getLength(const UBiDi * pBiDi)2073 ubidi_getLength(const UBiDi *pBiDi) {
2074     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2075         return pBiDi->originalLength;
2076     } else {
2077         return 0;
2078     }
2079 }
2080 
2081 U_CAPI int32_t U_EXPORT2
ubidi_getProcessedLength(const UBiDi * pBiDi)2082 ubidi_getProcessedLength(const UBiDi *pBiDi) {
2083     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2084         return pBiDi->length;
2085     } else {
2086         return 0;
2087     }
2088 }
2089 
2090 U_CAPI int32_t U_EXPORT2
ubidi_getResultLength(const UBiDi * pBiDi)2091 ubidi_getResultLength(const UBiDi *pBiDi) {
2092     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2093         return pBiDi->resultLength;
2094     } else {
2095         return 0;
2096     }
2097 }
2098 
2099 /* paragraphs API functions ------------------------------------------------- */
2100 
2101 U_CAPI UBiDiLevel U_EXPORT2
ubidi_getParaLevel(const UBiDi * pBiDi)2102 ubidi_getParaLevel(const UBiDi *pBiDi) {
2103     if(IS_VALID_PARA_OR_LINE(pBiDi)) {
2104         return pBiDi->paraLevel;
2105     } else {
2106         return 0;
2107     }
2108 }
2109 
2110 U_CAPI int32_t U_EXPORT2
ubidi_countParagraphs(UBiDi * pBiDi)2111 ubidi_countParagraphs(UBiDi *pBiDi) {
2112     if(!IS_VALID_PARA_OR_LINE(pBiDi)) {
2113         return 0;
2114     } else {
2115         return pBiDi->paraCount;
2116     }
2117 }
2118 
2119 U_CAPI void U_EXPORT2
ubidi_getParagraphByIndex(const UBiDi * pBiDi,int32_t paraIndex,int32_t * pParaStart,int32_t * pParaLimit,UBiDiLevel * pParaLevel,UErrorCode * pErrorCode)2120 ubidi_getParagraphByIndex(const UBiDi *pBiDi, int32_t paraIndex,
2121                           int32_t *pParaStart, int32_t *pParaLimit,
2122                           UBiDiLevel *pParaLevel, UErrorCode *pErrorCode) {
2123     int32_t paraStart;
2124 
2125     /* check the argument values */
2126     RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
2127     RETURN_VOID_IF_NOT_VALID_PARA_OR_LINE(pBiDi, *pErrorCode);
2128     RETURN_VOID_IF_BAD_RANGE(paraIndex, 0, pBiDi->paraCount, *pErrorCode);
2129 
2130     pBiDi=pBiDi->pParaBiDi;             /* get Para object if Line object */
2131     if(paraIndex) {
2132         paraStart=pBiDi->paras[paraIndex-1];
2133     } else {
2134         paraStart=0;
2135     }
2136     if(pParaStart!=NULL) {
2137         *pParaStart=paraStart;
2138     }
2139     if(pParaLimit!=NULL) {
2140         *pParaLimit=pBiDi->paras[paraIndex];
2141     }
2142     if(pParaLevel!=NULL) {
2143         *pParaLevel=GET_PARALEVEL(pBiDi, paraStart);
2144     }
2145 }
2146 
2147 U_CAPI int32_t U_EXPORT2
ubidi_getParagraph(const UBiDi * pBiDi,int32_t charIndex,int32_t * pParaStart,int32_t * pParaLimit,UBiDiLevel * pParaLevel,UErrorCode * pErrorCode)2148 ubidi_getParagraph(const UBiDi *pBiDi, int32_t charIndex,
2149                           int32_t *pParaStart, int32_t *pParaLimit,
2150                           UBiDiLevel *pParaLevel, UErrorCode *pErrorCode) {
2151     uint32_t paraIndex;
2152 
2153     /* check the argument values */
2154     /* pErrorCode will be checked by the call to ubidi_getParagraphByIndex */
2155     RETURN_IF_NULL_OR_FAILING_ERRCODE(pErrorCode, -1);
2156     RETURN_IF_NOT_VALID_PARA_OR_LINE(pBiDi, *pErrorCode, -1);
2157     pBiDi=pBiDi->pParaBiDi;             /* get Para object if Line object */
2158     RETURN_IF_BAD_RANGE(charIndex, 0, pBiDi->length, *pErrorCode, -1);
2159 
2160     for(paraIndex=0; charIndex>=pBiDi->paras[paraIndex]; paraIndex++);
2161     ubidi_getParagraphByIndex(pBiDi, paraIndex, pParaStart, pParaLimit, pParaLevel, pErrorCode);
2162     return paraIndex;
2163 }
2164 
2165 U_CAPI void U_EXPORT2
ubidi_setClassCallback(UBiDi * pBiDi,UBiDiClassCallback * newFn,const void * newContext,UBiDiClassCallback ** oldFn,const void ** oldContext,UErrorCode * pErrorCode)2166 ubidi_setClassCallback(UBiDi *pBiDi, UBiDiClassCallback *newFn,
2167                        const void *newContext, UBiDiClassCallback **oldFn,
2168                        const void **oldContext, UErrorCode *pErrorCode)
2169 {
2170     RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
2171     if(pBiDi==NULL) {
2172         *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
2173         return;
2174     }
2175     if( oldFn )
2176     {
2177         *oldFn = pBiDi->fnClassCallback;
2178     }
2179     if( oldContext )
2180     {
2181         *oldContext = pBiDi->coClassCallback;
2182     }
2183     pBiDi->fnClassCallback = newFn;
2184     pBiDi->coClassCallback = newContext;
2185 }
2186 
2187 U_CAPI void U_EXPORT2
ubidi_getClassCallback(UBiDi * pBiDi,UBiDiClassCallback ** fn,const void ** context)2188 ubidi_getClassCallback(UBiDi *pBiDi, UBiDiClassCallback **fn, const void **context)
2189 {
2190     if(pBiDi==NULL) {
2191         return;
2192     }
2193     if( fn )
2194     {
2195         *fn = pBiDi->fnClassCallback;
2196     }
2197     if( context )
2198     {
2199         *context = pBiDi->coClassCallback;
2200     }
2201 }
2202 
2203 U_CAPI UCharDirection U_EXPORT2
ubidi_getCustomizedClass(UBiDi * pBiDi,UChar32 c)2204 ubidi_getCustomizedClass(UBiDi *pBiDi, UChar32 c)
2205 {
2206     UCharDirection dir;
2207 
2208     if( pBiDi->fnClassCallback == NULL ||
2209         (dir = (*pBiDi->fnClassCallback)(pBiDi->coClassCallback, c)) == U_BIDI_CLASS_DEFAULT )
2210     {
2211         return ubidi_getClass(pBiDi->bdp, c);
2212     } else {
2213         return dir;
2214     }
2215 }
2216 
2217