summaryrefslogtreecommitdiffstats
path: root/android_icu4j/src/main/java/android/icu/impl/number/AffixUtils.java
blob: 6cd0ba8075ecfb844cdb0bef741042ffe295af44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/* GENERATED SOURCE. DO NOT MODIFY. */
// © 2017 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
package android.icu.impl.number;

import android.icu.text.NumberFormat;
import android.icu.text.UnicodeSet;

/**
 * Performs manipulations on affix patterns: the prefix and suffix strings associated with a decimal
 * format pattern. For example:
 *
 * <table>
 * <tr>
 * <th>Affix Pattern</th>
 * <th>Example Unescaped (Formatted) String</th>
 * </tr>
 * <tr>
 * <td>abc</td>
 * <td>abc</td>
 * </tr>
 * <tr>
 * <td>ab-</td>
 * <td>ab−</td>
 * </tr>
 * <tr>
 * <td>ab'-'</td>
 * <td>ab-</td>
 * </tr>
 * <tr>
 * <td>ab''</td>
 * <td>ab'</td>
 * </tr>
 * </table>
 *
 * To manually iterate over tokens in a literal string, use the following pattern, which is designed to
 * be efficient.
 *
 * <pre>
 * long tag = 0L;
 * while (AffixPatternUtils.hasNext(tag, patternString)) {
 *     tag = AffixPatternUtils.nextToken(tag, patternString);
 *     int typeOrCp = AffixPatternUtils.getTypeOrCp(tag);
 *     switch (typeOrCp) {
 *     case AffixPatternUtils.TYPE_MINUS_SIGN:
 *         // Current token is a minus sign.
 *         break;
 *     case AffixPatternUtils.TYPE_PLUS_SIGN:
 *         // Current token is a plus sign.
 *         break;
 *     case AffixPatternUtils.TYPE_PERCENT:
 *         // Current token is a percent sign.
 *         break;
 *     // ... other types ...
 *     default:
 *         // Current token is an arbitrary code point.
 *         // The variable typeOrCp is the code point.
 *         break;
 *     }
 * }
 * </pre>
 * @hide Only a subset of ICU is exposed in Android
 */
public class AffixUtils {

    private static final int STATE_BASE = 0;
    private static final int STATE_FIRST_QUOTE = 1;
    private static final int STATE_INSIDE_QUOTE = 2;
    private static final int STATE_AFTER_QUOTE = 3;
    private static final int STATE_FIRST_CURR = 4;
    private static final int STATE_SECOND_CURR = 5;
    private static final int STATE_THIRD_CURR = 6;
    private static final int STATE_FOURTH_CURR = 7;
    private static final int STATE_FIFTH_CURR = 8;
    private static final int STATE_OVERFLOW_CURR = 9;

    /** Represents a literal character; the value is stored in the code point field. */
    private static final int TYPE_CODEPOINT = 0;

    /** Represents a minus sign symbol '-'. */
    public static final int TYPE_MINUS_SIGN = -1;

    /** Represents a plus sign symbol '+'. */
    public static final int TYPE_PLUS_SIGN = -2;

    /** Represents a percent sign symbol '%'. */
    public static final int TYPE_PERCENT = -3;

    /** Represents a permille sign symbol '‰'. */
    public static final int TYPE_PERMILLE = -4;

    /** Represents a single currency symbol '¤'. */
    public static final int TYPE_CURRENCY_SINGLE = -5;

    /** Represents a double currency symbol '¤¤'. */
    public static final int TYPE_CURRENCY_DOUBLE = -6;

    /** Represents a triple currency symbol '¤¤¤'. */
    public static final int TYPE_CURRENCY_TRIPLE = -7;

    /** Represents a quadruple currency symbol '¤¤¤¤'. */
    public static final int TYPE_CURRENCY_QUAD = -8;

    /** Represents a quintuple currency symbol '¤¤¤¤¤'. */
    public static final int TYPE_CURRENCY_QUINT = -9;

    /** Represents a sequence of six or more currency symbols. */
    public static final int TYPE_CURRENCY_OVERFLOW = -15;

    /**
     * @hide Only a subset of ICU is exposed in Android
     */
    public static interface SymbolProvider {
        public CharSequence getSymbol(int type);
    }

    /**
     * @hide Only a subset of ICU is exposed in Android
     */
    public static interface TokenConsumer {
        public void consumeToken(int typeOrCp);
    }

    /**
     * Estimates the number of code points present in an unescaped version of the affix pattern string
     * (one that would be returned by {@link #unescape}), assuming that all interpolated symbols consume
     * one code point and that currencies consume as many code points as their symbol width. Used for
     * computing padding width.
     *
     * @param patternString
     *            The original string whose width will be estimated.
     * @return The length of the unescaped string.
     */
    public static int estimateLength(CharSequence patternString) {
        if (patternString == null)
            return 0;
        int state = STATE_BASE;
        int offset = 0;
        int length = 0;
        for (; offset < patternString.length();) {
            int cp = Character.codePointAt(patternString, offset);

            switch (state) {
            case STATE_BASE:
                if (cp == '\'') {
                    // First quote
                    state = STATE_FIRST_QUOTE;
                } else {
                    // Unquoted symbol
                    length++;
                }
                break;
            case STATE_FIRST_QUOTE:
                if (cp == '\'') {
                    // Repeated quote
                    length++;
                    state = STATE_BASE;
                } else {
                    // Quoted code point
                    length++;
                    state = STATE_INSIDE_QUOTE;
                }
                break;
            case STATE_INSIDE_QUOTE:
                if (cp == '\'') {
                    // End of quoted sequence
                    state = STATE_AFTER_QUOTE;
                } else {
                    // Quoted code point
                    length++;
                }
                break;
            case STATE_AFTER_QUOTE:
                if (cp == '\'') {
                    // Double quote inside of quoted sequence
                    length++;
                    state = STATE_INSIDE_QUOTE;
                } else {
                    // Unquoted symbol
                    length++;
                }
                break;
            default:
                throw new AssertionError();
            }

            offset += Character.charCount(cp);
        }

        switch (state) {
        case STATE_FIRST_QUOTE:
        case STATE_INSIDE_QUOTE:
            throw new IllegalArgumentException("Unterminated quote: \"" + patternString + "\"");
        default:
            break;
        }

        return length;
    }

    /**
     * Takes a string and escapes (quotes) characters that have special meaning in the affix pattern
     * syntax. This function does not reverse-lookup symbols.
     *
     * <p>
     * Example input: "-$x"; example output: "'-'$x"
     *
     * @param input
     *            The string to be escaped.
     * @param output
     *            The string builder to which to append the escaped string.
     * @return The number of chars (UTF-16 code units) appended to the output.
     */
    public static int escape(CharSequence input, StringBuilder output) {
        if (input == null)
            return 0;
        int state = STATE_BASE;
        int offset = 0;
        int startLength = output.length();
        for (; offset < input.length();) {
            int cp = Character.codePointAt(input, offset);

            switch (cp) {
            case '\'':
                output.append("''");
                break;

            case '-':
            case '+':
            case '%':
            case '‰':
            case '¤':
                if (state == STATE_BASE) {
                    output.append('\'');
                    output.appendCodePoint(cp);
                    state = STATE_INSIDE_QUOTE;
                } else {
                    output.appendCodePoint(cp);
                }
                break;

            default:
                if (state == STATE_INSIDE_QUOTE) {
                    output.append('\'');
                    output.appendCodePoint(cp);
                    state = STATE_BASE;
                } else {
                    output.appendCodePoint(cp);
                }
                break;
            }
            offset += Character.charCount(cp);
        }

        if (state == STATE_INSIDE_QUOTE) {
            output.append('\'');
        }

        return output.length() - startLength;
    }

    /** Version of {@link #escape} that returns a String, or null if input is null. */
    public static String escape(CharSequence input) {
        if (input == null)
            return null;
        StringBuilder sb = new StringBuilder();
        escape(input, sb);
        return sb.toString();
    }

    public static final NumberFormat.Field getFieldForType(int type) {
        switch (type) {
        case TYPE_MINUS_SIGN:
            return NumberFormat.Field.SIGN;
        case TYPE_PLUS_SIGN:
            return NumberFormat.Field.SIGN;
        case TYPE_PERCENT:
            return NumberFormat.Field.PERCENT;
        case TYPE_PERMILLE:
            return NumberFormat.Field.PERMILLE;
        case TYPE_CURRENCY_SINGLE:
            return NumberFormat.Field.CURRENCY;
        case TYPE_CURRENCY_DOUBLE:
            return NumberFormat.Field.CURRENCY;
        case TYPE_CURRENCY_TRIPLE:
            return NumberFormat.Field.CURRENCY;
        case TYPE_CURRENCY_QUAD:
            return NumberFormat.Field.CURRENCY;
        case TYPE_CURRENCY_QUINT:
            return NumberFormat.Field.CURRENCY;
        case TYPE_CURRENCY_OVERFLOW:
            return NumberFormat.Field.CURRENCY;
        default:
            throw new AssertionError();
        }
    }

    /**
     * Executes the unescape state machine. Replaces the unquoted characters "-", "+", "%", "‰", and "¤"
     * with the corresponding symbols provided by the {@link SymbolProvider}, and inserts the result into
     * the NumberStringBuilder at the requested location.
     *
     * <p>
     * Example input: "'-'¤x"; example output: "-$x"
     *
     * @param affixPattern
     *            The original string to be unescaped.
     * @param output
     *            The NumberStringBuilder to mutate with the result.
     * @param position
     *            The index into the NumberStringBuilder to insert the the string.
     * @param provider
     *            An object to generate locale symbols.
     * @return The length of the string added to affixPattern.
     */
    public static int unescape(
            CharSequence affixPattern,
            NumberStringBuilder output,
            int position,
            SymbolProvider provider) {
        assert affixPattern != null;
        int length = 0;
        long tag = 0L;
        while (hasNext(tag, affixPattern)) {
            tag = nextToken(tag, affixPattern);
            int typeOrCp = getTypeOrCp(tag);
            if (typeOrCp == TYPE_CURRENCY_OVERFLOW) {
                // Don't go to the provider for this special case
                length += output.insertCodePoint(position + length, 0xFFFD, NumberFormat.Field.CURRENCY);
            } else if (typeOrCp < 0) {
                length += output.insert(position + length,
                        provider.getSymbol(typeOrCp),
                        getFieldForType(typeOrCp));
            } else {
                length += output.insertCodePoint(position + length, typeOrCp, null);
            }
        }
        return length;
    }

    /**
     * Sames as {@link #unescape}, but only calculates the length or code point count. More efficient
     * than {@link #unescape} if you only need the length but not the string itself.
     *
     * @param affixPattern
     *            The original string to be unescaped.
     * @param lengthOrCount
     *            true to count length (UTF-16 code units); false to count code points
     * @param provider
     *            An object to generate locale symbols.
     * @return The number of code points in the unescaped string.
     */
    public static int unescapedCount(
            CharSequence affixPattern,
            boolean lengthOrCount,
            SymbolProvider provider) {
        int length = 0;
        long tag = 0L;
        while (hasNext(tag, affixPattern)) {
            tag = nextToken(tag, affixPattern);
            int typeOrCp = getTypeOrCp(tag);
            if (typeOrCp == TYPE_CURRENCY_OVERFLOW) {
                // U+FFFD is one char
                length += 1;
            } else if (typeOrCp < 0) {
                CharSequence symbol = provider.getSymbol(typeOrCp);
                length += lengthOrCount ? symbol.length()
                        : Character.codePointCount(symbol, 0, symbol.length());
            } else {
                length += lengthOrCount ? Character.charCount(typeOrCp) : 1;
            }
        }
        return length;
    }

    /**
     * Checks whether the given affix pattern contains at least one token of the given type, which is one
     * of the constants "TYPE_" in {@link AffixUtils}.
     *
     * @param affixPattern
     *            The affix pattern to check.
     * @param type
     *            The token type.
     * @return true if the affix pattern contains the given token type; false otherwise.
     */
    public static boolean containsType(CharSequence affixPattern, int type) {
        if (affixPattern == null || affixPattern.length() == 0) {
            return false;
        }
        long tag = 0L;
        while (hasNext(tag, affixPattern)) {
            tag = nextToken(tag, affixPattern);
            if (getTypeOrCp(tag) == type) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks whether the specified affix pattern has any unquoted currency symbols ("¤").
     *
     * @param affixPattern
     *            The string to check for currency symbols.
     * @return true if the literal has at least one unquoted currency symbol; false otherwise.
     */
    public static boolean hasCurrencySymbols(CharSequence affixPattern) {
        if (affixPattern == null || affixPattern.length() == 0)
            return false;
        long tag = 0L;
        while (hasNext(tag, affixPattern)) {
            tag = nextToken(tag, affixPattern);
            int typeOrCp = getTypeOrCp(tag);
            if (typeOrCp < 0 && getFieldForType(typeOrCp) == NumberFormat.Field.CURRENCY) {
                return true;
            }
        }
        return false;
    }

    /**
     * Replaces all occurrences of tokens with the given type with the given replacement char.
     *
     * @param affixPattern
     *            The source affix pattern (does not get modified).
     * @param type
     *            The token type.
     * @param replacementChar
     *            The char to substitute in place of chars of the given token type.
     * @return A string containing the new affix pattern.
     */
    public static String replaceType(CharSequence affixPattern, int type, char replacementChar) {
        if (affixPattern == null || affixPattern.length() == 0)
            return "";
        char[] chars = affixPattern.toString().toCharArray();
        long tag = 0L;
        while (hasNext(tag, affixPattern)) {
            tag = nextToken(tag, affixPattern);
            if (getTypeOrCp(tag) == type) {
                int offset = getOffset(tag);
                chars[offset - 1] = replacementChar;
            }
        }
        return new String(chars);
    }

    /**
     * Returns whether the given affix pattern contains only symbols and ignorables as defined by the
     * given ignorables set.
     */
    public static boolean containsOnlySymbolsAndIgnorables(
            CharSequence affixPattern,
            UnicodeSet ignorables) {
        if (affixPattern == null) {
            return true;
        }
        long tag = 0L;
        while (hasNext(tag, affixPattern)) {
            tag = nextToken(tag, affixPattern);
            int typeOrCp = getTypeOrCp(tag);
            if (typeOrCp >= 0 && !ignorables.contains(typeOrCp)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Iterates over the affix pattern, calling the TokenConsumer for each token.
     */
    public static void iterateWithConsumer(CharSequence affixPattern, TokenConsumer consumer) {
        assert affixPattern != null;
        long tag = 0L;
        while (hasNext(tag, affixPattern)) {
            tag = nextToken(tag, affixPattern);
            int typeOrCp = getTypeOrCp(tag);
            consumer.consumeToken(typeOrCp);
        }
    }

    /**
     * Returns the next token from the affix pattern.
     *
     * @param tag
     *            A bitmask used for keeping track of state from token to token. The initial value should
     *            be 0L.
     * @param patternString
     *            The affix pattern.
     * @return The bitmask tag to pass to the next call of this method to retrieve the following token
     *         (never negative), or -1 if there were no more tokens in the affix pattern.
     * @see #hasNext
     */
    private static long nextToken(long tag, CharSequence patternString) {
        int offset = getOffset(tag);
        int state = getState(tag);
        for (; offset < patternString.length();) {
            int cp = Character.codePointAt(patternString, offset);
            int count = Character.charCount(cp);

            switch (state) {
            case STATE_BASE:
                switch (cp) {
                case '\'':
                    state = STATE_FIRST_QUOTE;
                    offset += count;
                    // continue to the next code point
                    break;
                case '-':
                    return makeTag(offset + count, TYPE_MINUS_SIGN, STATE_BASE, 0);
                case '+':
                    return makeTag(offset + count, TYPE_PLUS_SIGN, STATE_BASE, 0);
                case '%':
                    return makeTag(offset + count, TYPE_PERCENT, STATE_BASE, 0);
                case '‰':
                    return makeTag(offset + count, TYPE_PERMILLE, STATE_BASE, 0);
                case '¤':
                    state = STATE_FIRST_CURR;
                    offset += count;
                    // continue to the next code point
                    break;
                default:
                    return makeTag(offset + count, TYPE_CODEPOINT, STATE_BASE, cp);
                }
                break;
            case STATE_FIRST_QUOTE:
                if (cp == '\'') {
                    return makeTag(offset + count, TYPE_CODEPOINT, STATE_BASE, cp);
                } else {
                    return makeTag(offset + count, TYPE_CODEPOINT, STATE_INSIDE_QUOTE, cp);
                }
            case STATE_INSIDE_QUOTE:
                if (cp == '\'') {
                    state = STATE_AFTER_QUOTE;
                    offset += count;
                    // continue to the next code point
                    break;
                } else {
                    return makeTag(offset + count, TYPE_CODEPOINT, STATE_INSIDE_QUOTE, cp);
                }
            case STATE_AFTER_QUOTE:
                if (cp == '\'') {
                    return makeTag(offset + count, TYPE_CODEPOINT, STATE_INSIDE_QUOTE, cp);
                } else {
                    state = STATE_BASE;
                    // re-evaluate this code point
                    break;
                }
            case STATE_FIRST_CURR:
                if (cp == '¤') {
                    state = STATE_SECOND_CURR;
                    offset += count;
                    // continue to the next code point
                    break;
                } else {
                    return makeTag(offset, TYPE_CURRENCY_SINGLE, STATE_BASE, 0);
                }
            case STATE_SECOND_CURR:
                if (cp == '¤') {
                    state = STATE_THIRD_CURR;
                    offset += count;
                    // continue to the next code point
                    break;
                } else {
                    return makeTag(offset, TYPE_CURRENCY_DOUBLE, STATE_BASE, 0);
                }
            case STATE_THIRD_CURR:
                if (cp == '¤') {
                    state = STATE_FOURTH_CURR;
                    offset += count;
                    // continue to the next code point
                    break;
                } else {
                    return makeTag(offset, TYPE_CURRENCY_TRIPLE, STATE_BASE, 0);
                }
            case STATE_FOURTH_CURR:
                if (cp == '¤') {
                    state = STATE_FIFTH_CURR;
                    offset += count;
                    // continue to the next code point
                    break;
                } else {
                    return makeTag(offset, TYPE_CURRENCY_QUAD, STATE_BASE, 0);
                }
            case STATE_FIFTH_CURR:
                if (cp == '¤') {
                    state = STATE_OVERFLOW_CURR;
                    offset += count;
                    // continue to the next code point
                    break;
                } else {
                    return makeTag(offset, TYPE_CURRENCY_QUINT, STATE_BASE, 0);
                }
            case STATE_OVERFLOW_CURR:
                if (cp == '¤') {
                    offset += count;
                    // continue to the next code point and loop back to this state
                    break;
                } else {
                    return makeTag(offset, TYPE_CURRENCY_OVERFLOW, STATE_BASE, 0);
                }
            default:
                throw new AssertionError();
            }
        }
        // End of string
        switch (state) {
        case STATE_BASE:
            // No more tokens in string.
            return -1L;
        case STATE_FIRST_QUOTE:
        case STATE_INSIDE_QUOTE:
            // For consistent behavior with the JDK and ICU 58, throw an exception here.
            throw new IllegalArgumentException(
                    "Unterminated quote in pattern affix: \"" + patternString + "\"");
        case STATE_AFTER_QUOTE:
            // No more tokens in string.
            return -1L;
        case STATE_FIRST_CURR:
            return makeTag(offset, TYPE_CURRENCY_SINGLE, STATE_BASE, 0);
        case STATE_SECOND_CURR:
            return makeTag(offset, TYPE_CURRENCY_DOUBLE, STATE_BASE, 0);
        case STATE_THIRD_CURR:
            return makeTag(offset, TYPE_CURRENCY_TRIPLE, STATE_BASE, 0);
        case STATE_FOURTH_CURR:
            return makeTag(offset, TYPE_CURRENCY_QUAD, STATE_BASE, 0);
        case STATE_FIFTH_CURR:
            return makeTag(offset, TYPE_CURRENCY_QUINT, STATE_BASE, 0);
        case STATE_OVERFLOW_CURR:
            return makeTag(offset, TYPE_CURRENCY_OVERFLOW, STATE_BASE, 0);
        default:
            throw new AssertionError();
        }
    }

    /**
     * Returns whether the affix pattern string has any more tokens to be retrieved from a call to
     * {@link #nextToken}.
     *
     * @param tag
     *            The bitmask tag of the previous token, as returned by {@link #nextToken}.
     * @param string
     *            The affix pattern.
     * @return true if there are more tokens to consume; false otherwise.
     */
    private static boolean hasNext(long tag, CharSequence string) {
        assert tag >= 0;
        int state = getState(tag);
        int offset = getOffset(tag);
        // Special case: the last character in string is an end quote.
        if (state == STATE_INSIDE_QUOTE
                && offset == string.length() - 1
                && string.charAt(offset) == '\'') {
            return false;
        } else if (state != STATE_BASE) {
            return true;
        } else {
            return offset < string.length();
        }
    }

    /**
     * This function helps determine the identity of the token consumed by {@link #nextToken}. Converts
     * from a bitmask tag, based on a call to {@link #nextToken}, to its corresponding symbol type or
     * code point.
     *
     * @param tag
     *            The bitmask tag of the current token, as returned by {@link #nextToken}.
     * @return If less than zero, a symbol type corresponding to one of the <code>TYPE_</code> constants,
     *         such as {@link #TYPE_MINUS_SIGN}. If greater than or equal to zero, a literal code point.
     */
    private static int getTypeOrCp(long tag) {
        assert tag >= 0;
        int type = getType(tag);
        return (type == TYPE_CODEPOINT) ? getCodePoint(tag) : -type;
    }

    /**
     * Encodes the given values into a 64-bit tag.
     *
     * <ul>
     * <li>Bits 0-31 => offset (int32)
     * <li>Bits 32-35 => type (uint4)
     * <li>Bits 36-39 => state (uint4)
     * <li>Bits 40-60 => code point (uint21)
     * <li>Bits 61-63 => unused
     * </ul>
     */
    private static long makeTag(int offset, int type, int state, int cp) {
        long tag = 0L;
        tag |= offset;
        tag |= (-(long) type) << 32;
        tag |= ((long) state) << 36;
        tag |= ((long) cp) << 40;
        assert tag >= 0;
        return tag;
    }

    private static int getOffset(long tag) {
        return (int) (tag & 0xffffffff);
    }

    private static int getType(long tag) {
        return (int) ((tag >>> 32) & 0xf);
    }

    private static int getState(long tag) {
        return (int) ((tag >>> 36) & 0xf);
    }

    private static int getCodePoint(long tag) {
        return (int) (tag >>> 40);
    }
}