summaryrefslogtreecommitdiff
path: root/layout/style/CounterStyleManager.cpp
blob: bccc9b836075bc017aeb9c49745b3323e4f7a1e7 (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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "CounterStyleManager.h"

#include "mozilla/ArenaObjectID.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Types.h"
#include "mozilla/WritingModes.h"
#include "nsCSSRules.h"
#include "nsString.h"
#include "nsStyleSet.h"
#include "nsTArray.h"
#include "nsTHashtable.h"
#include "nsUnicodeProperties.h"
#include "mozilla/StyleSetHandle.h"
#include "mozilla/StyleSetHandleInlines.h"

namespace mozilla {

struct AdditiveSymbol
{
  CounterValue weight;
  nsString symbol;
};

struct NegativeType
{
  nsString before, after;
};

struct PadType
{
  int32_t width;
  nsString symbol;
};

// This limitation will be applied to some systems, and pad descriptor.
// Any initial representation generated by symbolic or additive which is
// longer than this limitation will be dropped. If any pad is longer
// than this, the whole counter text will be dropped as well.
// The spec requires user agents to support at least 60 Unicode code-
// points for counter text. However, this constant only limits the
// length in 16-bit units. So it has to be at least 120, since code-
// points outside the BMP will need 2 16-bit units.
#define LENGTH_LIMIT 150

static bool
GetCyclicCounterText(CounterValue aOrdinal,
                     nsSubstring& aResult,
                     const nsTArray<nsString>& aSymbols)
{
  MOZ_ASSERT(aSymbols.Length() >= 1,
             "No symbol available for cyclic counter.");
  auto n = aSymbols.Length();
  CounterValue index = (aOrdinal - 1) % n;
  aResult = aSymbols[index >= 0 ? index : index + n];
  return true;
}

static bool
GetFixedCounterText(CounterValue aOrdinal,
                    nsSubstring& aResult,
                    CounterValue aStart,
                    const nsTArray<nsString>& aSymbols)
{
  CounterValue index = aOrdinal - aStart;
  if (index >= 0 && index < CounterValue(aSymbols.Length())) {
    aResult = aSymbols[index];
    return true;
  } else {
    return false;
  }
}

static bool
GetSymbolicCounterText(CounterValue aOrdinal,
                       nsSubstring& aResult,
                       const nsTArray<nsString>& aSymbols)
{
  MOZ_ASSERT(aSymbols.Length() >= 1,
             "No symbol available for symbolic counter.");
  MOZ_ASSERT(aOrdinal >= 0, "Invalid ordinal.");
  if (aOrdinal == 0) {
    return false;
  }

  aResult.Truncate();
  auto n = aSymbols.Length();
  const nsString& symbol = aSymbols[(aOrdinal - 1) % n];
  size_t len = (aOrdinal + n - 1) / n;
  auto symbolLength = symbol.Length();
  if (symbolLength > 0) {
    if (len > LENGTH_LIMIT || symbolLength > LENGTH_LIMIT ||
        len * symbolLength > LENGTH_LIMIT) {
      return false;
    }
    for (size_t i = 0; i < len; ++i) {
      aResult.Append(symbol);
    }
  }
  return true;
}

static bool
GetAlphabeticCounterText(CounterValue aOrdinal,
                         nsSubstring& aResult,
                         const nsTArray<nsString>& aSymbols)
{
  MOZ_ASSERT(aSymbols.Length() >= 2,
             "Too few symbols for alphabetic counter.");
  MOZ_ASSERT(aOrdinal >= 0, "Invalid ordinal.");
  if (aOrdinal == 0) {
    return false;
  }

  auto n = aSymbols.Length();
  // The precise length of this array should be
  // ceil(log((double) aOrdinal / n * (n - 1) + 1) / log(n)).
  // The max length is slightly smaller than which defined below.
  AutoTArray<int32_t, std::numeric_limits<CounterValue>::digits> indexes;
  while (aOrdinal > 0) {
    --aOrdinal;
    indexes.AppendElement(aOrdinal % n);
    aOrdinal /= n;
  }

  aResult.Truncate();
  for (auto i = indexes.Length(); i > 0; --i) {
    aResult.Append(aSymbols[indexes[i - 1]]);
  }
  return true;
}

static bool
GetNumericCounterText(CounterValue aOrdinal,
                      nsSubstring& aResult,
                      const nsTArray<nsString>& aSymbols)
{
  MOZ_ASSERT(aSymbols.Length() >= 2,
             "Too few symbols for numeric counter.");
  MOZ_ASSERT(aOrdinal >= 0, "Invalid ordinal.");

  if (aOrdinal == 0) {
    aResult = aSymbols[0];
    return true;
  }

  auto n = aSymbols.Length();
  AutoTArray<int32_t, std::numeric_limits<CounterValue>::digits> indexes;
  while (aOrdinal > 0) {
    indexes.AppendElement(aOrdinal % n);
    aOrdinal /= n;
  }

  aResult.Truncate();
  for (auto i = indexes.Length(); i > 0; --i) {
    aResult.Append(aSymbols[indexes[i - 1]]);
  }
  return true;
}

static bool
GetAdditiveCounterText(CounterValue aOrdinal,
                       nsSubstring& aResult,
                       const nsTArray<AdditiveSymbol>& aSymbols)
{
  MOZ_ASSERT(aOrdinal >= 0, "Invalid ordinal.");

  if (aOrdinal == 0) {
    const AdditiveSymbol& last = aSymbols.LastElement();
    if (last.weight == 0) {
      aResult = last.symbol;
      return true;
    }
    return false;
  }

  aResult.Truncate();
  size_t length = 0;
  for (size_t i = 0, iEnd = aSymbols.Length(); i < iEnd; ++i) {
    const AdditiveSymbol& symbol = aSymbols[i];
    if (symbol.weight == 0) {
      break;
    }
    CounterValue times = aOrdinal / symbol.weight;
    if (times > 0) {
      auto symbolLength = symbol.symbol.Length();
      if (symbolLength > 0) {
        length += times * symbolLength;
        if (times > LENGTH_LIMIT ||
            symbolLength > LENGTH_LIMIT ||
            length > LENGTH_LIMIT) {
          return false;
        }
        for (CounterValue j = 0; j < times; ++j) {
          aResult.Append(symbol.symbol);
        }
      }
      aOrdinal -= times * symbol.weight;
    }
  }
  return aOrdinal == 0;
}

static bool
DecimalToText(CounterValue aOrdinal, nsSubstring& aResult)
{
  aResult.AppendInt(aOrdinal);
  return true;
}

// We know cjk-ideographic need 31 characters to display 99,999,999,999,999,999
// georgian needs 6 at most
// armenian needs 12 at most
// hebrew may need more...

#define NUM_BUF_SIZE 34

enum CJKIdeographicLang {
  CHINESE, KOREAN, JAPANESE
};
struct CJKIdeographicData {
  char16_t digit[10];
  char16_t unit[3];
  char16_t unit10K[2];
  uint8_t lang;
  bool informal;
};
static const CJKIdeographicData gDataJapaneseInformal = {
  {                           // digit
    0x3007, 0x4e00, 0x4e8c, 0x4e09, 0x56db,
    0x4e94, 0x516d, 0x4e03, 0x516b, 0x4e5d
  },
  { 0x5341, 0x767e, 0x5343 }, // unit
  { 0x4e07, 0x5104 },         // unit10K
  JAPANESE,                   // lang
  true                        // informal
};
static const CJKIdeographicData gDataJapaneseFormal = {
  {                           // digit
    0x96f6, 0x58f1, 0x5f10, 0x53c2, 0x56db,
    0x4f0d, 0x516d, 0x4e03, 0x516b, 0x4e5d
  },
  { 0x62fe, 0x767e, 0x9621 }, // unit
  { 0x842c, 0x5104 },         // unit10K
  JAPANESE,                   // lang
  false                       // informal
};
static const CJKIdeographicData gDataKoreanHangulFormal = {
  {                           // digit
    0xc601, 0xc77c, 0xc774, 0xc0bc, 0xc0ac,
    0xc624, 0xc721, 0xce60, 0xd314, 0xad6c
  },
  { 0xc2ed, 0xbc31, 0xcc9c }, // unit
  { 0xb9cc, 0xc5b5 },         // unit10K
  KOREAN,                     // lang
  false                       // informal
};
static const CJKIdeographicData gDataKoreanHanjaInformal = {
  {                           // digit
    0x96f6, 0x4e00, 0x4e8c, 0x4e09, 0x56db,
    0x4e94, 0x516d, 0x4e03, 0x516b, 0x4e5d
  },
  { 0x5341, 0x767e, 0x5343 }, // unit
  { 0x842c, 0x5104 },         // unit10K
  KOREAN,                     // lang
  true                        // informal
};
static const CJKIdeographicData gDataKoreanHanjaFormal = {
  {                           // digit
    0x96f6, 0x58f9, 0x8cb3, 0x53c3, 0x56db,
    0x4e94, 0x516d, 0x4e03, 0x516b, 0x4e5d
  },
  { 0x62fe, 0x767e, 0x4edf }, // unit
  { 0x842c, 0x5104 },         // unit10K
  KOREAN,                     // lang
  false                       // informal
};
static const CJKIdeographicData gDataSimpChineseInformal = {
  {                           // digit
    0x96f6, 0x4e00, 0x4e8c, 0x4e09, 0x56db,
    0x4e94, 0x516d, 0x4e03, 0x516b, 0x4e5d
  },
  { 0x5341, 0x767e, 0x5343 }, // unit
  { 0x4e07, 0x4ebf },         // unit10K
  CHINESE,                    // lang
  true                        // informal
};
static const CJKIdeographicData gDataSimpChineseFormal = {
  {                           // digit
    0x96f6, 0x58f9, 0x8d30, 0x53c1, 0x8086,
    0x4f0d, 0x9646, 0x67d2, 0x634c, 0x7396
  },
  { 0x62fe, 0x4f70, 0x4edf }, // unit
  { 0x4e07, 0x4ebf },         // unit10K
  CHINESE,                    // lang
  false                       // informal
};
static const CJKIdeographicData gDataTradChineseInformal = {
  {                           // digit
    0x96f6, 0x4e00, 0x4e8c, 0x4e09, 0x56db,
    0x4e94, 0x516d, 0x4e03, 0x516b, 0x4e5d
  },
  { 0x5341, 0x767e, 0x5343 }, // unit
  { 0x842c, 0x5104 },         // unit10K
  CHINESE,                    // lang
  true                        // informal
};
static const CJKIdeographicData gDataTradChineseFormal = {
  {                           // digit
    0x96f6, 0x58f9, 0x8cb3, 0x53c3, 0x8086,
    0x4f0d, 0x9678, 0x67d2, 0x634c, 0x7396
  },
  { 0x62fe, 0x4f70, 0x4edf }, // unit
  { 0x842c, 0x5104 },         // unit10K
  CHINESE,                    // lang
  false                       // informal
};

static bool
CJKIdeographicToText(CounterValue aOrdinal, nsSubstring& aResult,
                     const CJKIdeographicData& data)
{
  NS_ASSERTION(aOrdinal >= 0, "Only accept non-negative ordinal");
  char16_t buf[NUM_BUF_SIZE];
  int32_t idx = NUM_BUF_SIZE;
  int32_t pos = 0;
  bool needZero = (aOrdinal == 0);
  int32_t unitidx = 0, unit10Kidx = 0;
  do {
    unitidx = pos % 4;
    if (unitidx == 0) {
      unit10Kidx = pos / 4;
    }
    auto cur = static_cast<MakeUnsigned<CounterValue>::Type>(aOrdinal) % 10;
    if (cur == 0) {
      if (needZero) {
        needZero = false;
        buf[--idx] = data.digit[0];
      }
    } else {
      if (data.lang == CHINESE) {
        needZero = true;
      }
      if (unit10Kidx != 0) {
        if (data.lang == KOREAN && idx != NUM_BUF_SIZE) {
          buf[--idx] = ' ';
        }
        buf[--idx] = data.unit10K[unit10Kidx - 1];
      }
      if (unitidx != 0) {
        buf[--idx] = data.unit[unitidx - 1];
      }
      if (cur != 1) {
        buf[--idx] = data.digit[cur];
      } else {
        bool needOne = true;
        if (data.informal) {
          switch (data.lang) {
            case CHINESE:
              if (unitidx == 1 &&
                  (aOrdinal == 1 || (pos > 4 && aOrdinal % 1000 == 1))) {
                needOne = false;
              }
              break;
            case JAPANESE:
              if (unitidx > 0 &&
                  (unitidx != 3 || (pos == 3 && aOrdinal == 1))) {
                needOne = false;
              }
              break;
            case KOREAN:
              if (unitidx > 0 || (pos == 4 && (aOrdinal % 1000) == 1)) {
                needOne = false;
              }
              break;
          }
        }
        if (needOne) {
          buf[--idx] = data.digit[1];
        }
      }
      unit10Kidx = 0;
    }
    aOrdinal /= 10;
    pos++;
  } while (aOrdinal > 0);
  aResult.Assign(buf + idx, NUM_BUF_SIZE - idx);
  return true;
}

#define HEBREW_GERESH       0x05F3
static const char16_t gHebrewDigit[22] =
{
  //   1       2       3       4       5       6       7       8       9
  0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8,
  //  10      20      30      40      50      60      70      80      90
  0x05D9, 0x05DB, 0x05DC, 0x05DE, 0x05E0, 0x05E1, 0x05E2, 0x05E4, 0x05E6,
  // 100     200     300     400
  0x05E7, 0x05E8, 0x05E9, 0x05EA
};

static bool
HebrewToText(CounterValue aOrdinal, nsSubstring& aResult)
{
  if (aOrdinal < 1 || aOrdinal > 999999) {
    return false;
  }

  bool outputSep = false;
  nsAutoString allText, thousandsGroup;
  do {
    thousandsGroup.Truncate();
    int32_t n3 = aOrdinal % 1000;
    // Process digit for 100 - 900
    for(int32_t n1 = 400; n1 > 0; )
    {
      if( n3 >= n1)
      {
        n3 -= n1;
        thousandsGroup.Append(gHebrewDigit[(n1/100)-1+18]);
      } else {
        n1 -= 100;
      } // if
    } // for

    // Process digit for 10 - 90
    int32_t n2;
    if( n3 >= 10 )
    {
      // Special process for 15 and 16
      if(( 15 == n3 ) || (16 == n3)) {
        // Special rule for religious reason...
        // 15 is represented by 9 and 6, not 10 and 5
        // 16 is represented by 9 and 7, not 10 and 6
        n2 = 9;
        thousandsGroup.Append(gHebrewDigit[ n2 - 1]);
      } else {
        n2 = n3 - (n3 % 10);
        thousandsGroup.Append(gHebrewDigit[(n2/10)-1+9]);
      } // if
      n3 -= n2;
    } // if

    // Process digit for 1 - 9
    if ( n3 > 0)
      thousandsGroup.Append(gHebrewDigit[n3-1]);
    if (outputSep)
      thousandsGroup.Append((char16_t)HEBREW_GERESH);
    if (allText.IsEmpty())
      allText = thousandsGroup;
    else
      allText = thousandsGroup + allText;
    aOrdinal /= 1000;
    outputSep = true;
  } while (aOrdinal >= 1);

  aResult = allText;
  return true;
}

// Convert ordinal to Ethiopic numeric representation.
// The detail is available at http://www.ethiopic.org/Numerals/
// The algorithm used here is based on the pseudo-code put up there by
// Daniel Yacob <yacob@geez.org>.
// Another reference is Unicode 3.0 standard section 11.1.
#define ETHIOPIC_ONE             0x1369
#define ETHIOPIC_TEN             0x1372
#define ETHIOPIC_HUNDRED         0x137B
#define ETHIOPIC_TEN_THOUSAND    0x137C

static bool
EthiopicToText(CounterValue aOrdinal, nsSubstring& aResult)
{
  if (aOrdinal < 1) {
    return false;
  }

  nsAutoString asciiNumberString;      // decimal string representation of ordinal
  DecimalToText(aOrdinal, asciiNumberString);
  uint8_t asciiStringLength = asciiNumberString.Length();

  // If number length is odd, add a leading "0"
  // the leading "0" preconditions the string to always have the
  // leading tens place populated, this avoids a check within the loop.
  // If we didn't add the leading "0", decrement asciiStringLength so
  // it will be equivalent to a zero-based index in both cases.
  if (asciiStringLength & 1) {
    asciiNumberString.Insert(NS_LITERAL_STRING("0"), 0);
  } else {
    asciiStringLength--;
  }

  aResult.Truncate();
  // Iterate from the highest digits to lowest
  // indexFromLeft       indexes digits (0 = most significant)
  // groupIndexFromRight indexes pairs of digits (0 = least significant)
  for (uint8_t indexFromLeft = 0, groupIndexFromRight = asciiStringLength >> 1;
       indexFromLeft <= asciiStringLength;
       indexFromLeft += 2, groupIndexFromRight--) {
    uint8_t tensValue  = asciiNumberString.CharAt(indexFromLeft) & 0x0F;
    uint8_t unitsValue = asciiNumberString.CharAt(indexFromLeft + 1) & 0x0F;
    uint8_t groupValue = tensValue * 10 + unitsValue;

    bool oddGroup = (groupIndexFromRight & 1);

    // we want to clear ETHIOPIC_ONE when it is superfluous
    if (aOrdinal > 1 &&
        groupValue == 1 &&                  // one without a leading ten
        (oddGroup || indexFromLeft == 0)) { // preceding (100) or leading the sequence
      unitsValue = 0;
    }

    // put it all together...
    if (tensValue) {
      // map onto Ethiopic "tens":
      aResult.Append((char16_t) (tensValue +  ETHIOPIC_TEN - 1));
    }
    if (unitsValue) {
      //map onto Ethiopic "units":
      aResult.Append((char16_t) (unitsValue + ETHIOPIC_ONE - 1));
    }
    // Add a separator for all even groups except the last,
    // and for odd groups with non-zero value.
    if (oddGroup) {
      if (groupValue) {
        aResult.Append((char16_t) ETHIOPIC_HUNDRED);
      }
    } else {
      if (groupIndexFromRight) {
        aResult.Append((char16_t) ETHIOPIC_TEN_THOUSAND);
      }
    }
  }
  return true;
}

static uint8_t
GetDefaultSpeakAsForSystem(uint8_t aSystem)
{
  MOZ_ASSERT(aSystem != NS_STYLE_COUNTER_SYSTEM_EXTENDS,
             "Extends system does not have static default speak-as");
  switch (aSystem) {
    case NS_STYLE_COUNTER_SYSTEM_ALPHABETIC:
      return NS_STYLE_COUNTER_SPEAKAS_SPELL_OUT;
    case NS_STYLE_COUNTER_SYSTEM_CYCLIC:
      return NS_STYLE_COUNTER_SPEAKAS_BULLETS;
    default:
      return NS_STYLE_COUNTER_SPEAKAS_NUMBERS;
  }
}

static bool
SystemUsesNegativeSign(uint8_t aSystem)
{
  MOZ_ASSERT(aSystem != NS_STYLE_COUNTER_SYSTEM_EXTENDS,
             "Cannot check this for extending style");
  switch (aSystem) {
    case NS_STYLE_COUNTER_SYSTEM_SYMBOLIC:
    case NS_STYLE_COUNTER_SYSTEM_ALPHABETIC:
    case NS_STYLE_COUNTER_SYSTEM_NUMERIC:
    case NS_STYLE_COUNTER_SYSTEM_ADDITIVE:
      return true;
    default:
      return false;
  }
}

class BuiltinCounterStyle : public CounterStyle
{
public:
  friend class CounterStyleManager;

  // will be initialized by CounterStyleManager::InitializeBuiltinCounterStyles
  constexpr BuiltinCounterStyle()
    : CounterStyle(NS_STYLE_LIST_STYLE_NONE)
  {
  }

protected:
  constexpr explicit BuiltinCounterStyle(int32_t aStyle)
    : CounterStyle(aStyle)
  {
  }

public:
  virtual void GetStyleName(nsSubstring& aResult) override;
  virtual void GetPrefix(nsSubstring& aResult) override;
  virtual void GetSuffix(nsSubstring& aResult) override;
  virtual void GetSpokenCounterText(CounterValue aOrdinal,
                                    WritingMode aWritingMode,
                                    nsSubstring& aResult,
                                    bool& aIsBullet) override;
  virtual bool IsBullet() override;

  virtual void GetNegative(NegativeType& aResult) override;
  virtual bool IsOrdinalInRange(CounterValue aOrdinal) override;
  virtual bool IsOrdinalInAutoRange(CounterValue aOrdinal) override;
  virtual void GetPad(PadType& aResult) override;
  virtual CounterStyle* GetFallback() override;
  virtual uint8_t GetSpeakAs() override;
  virtual bool UseNegativeSign() override;

  virtual bool GetInitialCounterText(CounterValue aOrdinal,
                                     WritingMode aWritingMode,
                                     nsSubstring& aResult,
                                     bool& aIsRTL) override;

  // Builtin counter style does not need refcount at all
  NS_IMETHOD_(MozExternalRefCountType) AddRef() override { return 2; }
  NS_IMETHOD_(MozExternalRefCountType) Release() override { return 2; }
};

/* virtual */ void
BuiltinCounterStyle::GetStyleName(nsSubstring& aResult)
{
  MOZ_ASSERT(mStyle != NS_STYLE_LIST_STYLE_CUSTOM);
  const nsAFlatCString& str =
    nsCSSProps::ValueToKeyword(mStyle, nsCSSProps::kListStyleKTable);
  MOZ_ASSERT(!str.IsEmpty());
  aResult.Assign(NS_ConvertUTF8toUTF16(str));
}

/* virtual */ void
BuiltinCounterStyle::GetPrefix(nsSubstring& aResult)
{
  aResult.Truncate();
}

/* virtual */ void
BuiltinCounterStyle::GetSuffix(nsSubstring& aResult)
{
  switch (mStyle) {
    case NS_STYLE_LIST_STYLE_NONE:
      aResult.Truncate();
      break;

    case NS_STYLE_LIST_STYLE_DISC:
    case NS_STYLE_LIST_STYLE_CIRCLE:
    case NS_STYLE_LIST_STYLE_SQUARE:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_CLOSED:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_OPEN:
    case NS_STYLE_LIST_STYLE_ETHIOPIC_NUMERIC:
      aResult = ' ';
      break;

    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_JAPANESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_JAPANESE_FORMAL:
      aResult = 0x3001;
      break;

    case NS_STYLE_LIST_STYLE_KOREAN_HANGUL_FORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_INFORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_FORMAL:
      aResult.AssignLiteral(u", ");
      break;

    default:
      aResult.AssignLiteral(u". ");
      break;
  }
}

static const char16_t kDiscCharacter = 0x2022;
static const char16_t kCircleCharacter = 0x25e6;
static const char16_t kSquareCharacter = 0x25fe;
static const char16_t kRightPointingCharacter = 0x25b8;
static const char16_t kLeftPointingCharacter = 0x25c2;
static const char16_t kDownPointingCharacter = 0x25be;

/* virtual */ void
BuiltinCounterStyle::GetSpokenCounterText(CounterValue aOrdinal,
                                          WritingMode aWritingMode,
                                          nsSubstring& aResult,
                                          bool& aIsBullet)
{
  switch (mStyle) {
    case NS_STYLE_LIST_STYLE_NONE:
    case NS_STYLE_LIST_STYLE_DISC:
    case NS_STYLE_LIST_STYLE_CIRCLE:
    case NS_STYLE_LIST_STYLE_SQUARE:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_CLOSED:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_OPEN: {
      // Same as the initial representation
      bool isRTL;
      GetInitialCounterText(aOrdinal, aWritingMode, aResult, isRTL);
      aIsBullet = true;
      break;
    }
    default:
      CounterStyle::GetSpokenCounterText(
          aOrdinal, aWritingMode, aResult, aIsBullet);
      break;
  }
}

/* virtual */ bool
BuiltinCounterStyle::IsBullet()
{
  switch (mStyle) {
    case NS_STYLE_LIST_STYLE_DISC:
    case NS_STYLE_LIST_STYLE_CIRCLE:
    case NS_STYLE_LIST_STYLE_SQUARE:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_CLOSED:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_OPEN:
      return true;
    default:
      return false;
  }
}

static const char16_t gJapaneseNegative[] = {
  0x30de, 0x30a4, 0x30ca, 0x30b9, 0x0000
};
static const char16_t gKoreanNegative[] = {
  0xb9c8, 0xc774, 0xb108, 0xc2a4, 0x0020, 0x0000
};
static const char16_t gSimpChineseNegative[] = {
  0x8d1f, 0x0000
};
static const char16_t gTradChineseNegative[] = {
  0x8ca0, 0x0000
};

/* virtual */ void
BuiltinCounterStyle::GetNegative(NegativeType& aResult)
{
  switch (mStyle) {
    case NS_STYLE_LIST_STYLE_JAPANESE_FORMAL:
    case NS_STYLE_LIST_STYLE_JAPANESE_INFORMAL:
      aResult.before = gJapaneseNegative;
      break;

    case NS_STYLE_LIST_STYLE_KOREAN_HANGUL_FORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_INFORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_FORMAL:
      aResult.before = gKoreanNegative;
      break;

    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_INFORMAL:
      aResult.before = gSimpChineseNegative;
      break;

    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_INFORMAL:
      aResult.before = gTradChineseNegative;
      break;

    default:
      aResult.before.AssignLiteral(u"-");
  }
  aResult.after.Truncate();
}

/* virtual */ bool
BuiltinCounterStyle::IsOrdinalInRange(CounterValue aOrdinal)
{
  switch (mStyle) {
    default:
    // cyclic
    case NS_STYLE_LIST_STYLE_NONE:
    case NS_STYLE_LIST_STYLE_DISC:
    case NS_STYLE_LIST_STYLE_CIRCLE:
    case NS_STYLE_LIST_STYLE_SQUARE:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_CLOSED:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_OPEN:
    // use DecimalToText
    case NS_STYLE_LIST_STYLE_DECIMAL:
    // use CJKIdeographicToText
    case NS_STYLE_LIST_STYLE_JAPANESE_FORMAL:
    case NS_STYLE_LIST_STYLE_JAPANESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_FORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_INFORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANGUL_FORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_INFORMAL:
      return true;

    // use EthiopicToText
    case NS_STYLE_LIST_STYLE_ETHIOPIC_NUMERIC:
      return aOrdinal >= 1;

    // use HebrewToText
    case NS_STYLE_LIST_STYLE_HEBREW:
      return aOrdinal >= 1 && aOrdinal <= 999999;
  }
}

/* virtual */ bool
BuiltinCounterStyle::IsOrdinalInAutoRange(CounterValue aOrdinal)
{
  switch (mStyle) {
    // cyclic:
    case NS_STYLE_LIST_STYLE_NONE:
    case NS_STYLE_LIST_STYLE_DISC:
    case NS_STYLE_LIST_STYLE_CIRCLE:
    case NS_STYLE_LIST_STYLE_SQUARE:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_CLOSED:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_OPEN:
    // numeric:
    case NS_STYLE_LIST_STYLE_DECIMAL:
      return true;

    // additive:
    case NS_STYLE_LIST_STYLE_HEBREW:
      return aOrdinal >= 0;

    // complex predefined:
    case NS_STYLE_LIST_STYLE_JAPANESE_FORMAL:
    case NS_STYLE_LIST_STYLE_JAPANESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_FORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_INFORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANGUL_FORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_ETHIOPIC_NUMERIC:
      return IsOrdinalInRange(aOrdinal);

    default:
      NS_NOTREACHED("Unknown counter style");
      return false;
  }
}

/* virtual */ void
BuiltinCounterStyle::GetPad(PadType& aResult)
{
  aResult.width = 0;
  aResult.symbol.Truncate();
}

/* virtual */ CounterStyle*
BuiltinCounterStyle::GetFallback()
{
  // Fallback of dependent builtin counter styles are handled in class
  // DependentBuiltinCounterStyle.
  return CounterStyleManager::GetDecimalStyle();
}

/* virtual */ uint8_t
BuiltinCounterStyle::GetSpeakAs()
{
  switch (mStyle) {
    case NS_STYLE_LIST_STYLE_NONE:
    case NS_STYLE_LIST_STYLE_DISC:
    case NS_STYLE_LIST_STYLE_CIRCLE:
    case NS_STYLE_LIST_STYLE_SQUARE:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_CLOSED:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_OPEN:
      return NS_STYLE_COUNTER_SPEAKAS_BULLETS;
    default:
      return NS_STYLE_COUNTER_SPEAKAS_NUMBERS;
  }
}

/* virtual */ bool
BuiltinCounterStyle::UseNegativeSign()
{
  switch (mStyle) {
    case NS_STYLE_LIST_STYLE_NONE:
    case NS_STYLE_LIST_STYLE_DISC:
    case NS_STYLE_LIST_STYLE_CIRCLE:
    case NS_STYLE_LIST_STYLE_SQUARE:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_CLOSED:
    case NS_STYLE_LIST_STYLE_DISCLOSURE_OPEN:
      return false;
    default:
      return true;
  }
}

/* virtual */ bool
BuiltinCounterStyle::GetInitialCounterText(CounterValue aOrdinal,
                                           WritingMode aWritingMode,
                                           nsSubstring& aResult,
                                           bool& aIsRTL)
{
  aIsRTL = false;
  switch (mStyle) {
    // used by counters & extends counter-style code only
    // XXX We really need to do this the same way we do list bullets.
    case NS_STYLE_LIST_STYLE_NONE:
      aResult.Truncate();
      return true;
    case NS_STYLE_LIST_STYLE_DISC:
      aResult.Assign(kDiscCharacter);
      return true;
    case NS_STYLE_LIST_STYLE_CIRCLE:
      aResult.Assign(kCircleCharacter);
      return true;
    case NS_STYLE_LIST_STYLE_SQUARE:
      aResult.Assign(kSquareCharacter);
      return true;
    case NS_STYLE_LIST_STYLE_DISCLOSURE_CLOSED:
      if (aWritingMode.IsVertical()) {
        aResult.Assign(kDownPointingCharacter);
      } else if (aWritingMode.IsBidiLTR()) {
        aResult.Assign(kRightPointingCharacter);
      } else {
        aResult.Assign(kLeftPointingCharacter);
      }
      return true;
    case NS_STYLE_LIST_STYLE_DISCLOSURE_OPEN:
      if (!aWritingMode.IsVertical()) {
        aResult.Assign(kDownPointingCharacter);
      } else if (aWritingMode.IsVerticalLR()) {
        aResult.Assign(kRightPointingCharacter);
      } else {
        aResult.Assign(kLeftPointingCharacter);
      }
      return true;

    case NS_STYLE_LIST_STYLE_DECIMAL:
      return DecimalToText(aOrdinal, aResult);

    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_INFORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataTradChineseInformal);
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_FORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataTradChineseFormal);
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_INFORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataSimpChineseInformal);
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_FORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataSimpChineseFormal);
    case NS_STYLE_LIST_STYLE_JAPANESE_INFORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataJapaneseInformal);
    case NS_STYLE_LIST_STYLE_JAPANESE_FORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataJapaneseFormal);
    case NS_STYLE_LIST_STYLE_KOREAN_HANGUL_FORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataKoreanHangulFormal);
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_INFORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataKoreanHanjaInformal);
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_FORMAL:
      return CJKIdeographicToText(aOrdinal, aResult, gDataKoreanHanjaFormal);

    case NS_STYLE_LIST_STYLE_HEBREW:
      aIsRTL = true;
      return HebrewToText(aOrdinal, aResult);

    case NS_STYLE_LIST_STYLE_ETHIOPIC_NUMERIC:
      return EthiopicToText(aOrdinal, aResult);

    default:
      NS_NOTREACHED("Unknown builtin counter style");
      return false;
  }
}

class DependentBuiltinCounterStyle final : public BuiltinCounterStyle
{
private:
  ~DependentBuiltinCounterStyle() {}
public:
  DependentBuiltinCounterStyle(int32_t aStyle, CounterStyleManager* aManager)
    : BuiltinCounterStyle(aStyle),
      mManager(aManager)
  {
    NS_ASSERTION(IsDependentStyle(), "Not a dependent builtin style");
    MOZ_ASSERT(!IsCustomStyle(), "Not a builtin style");
  }

  virtual CounterStyle* GetFallback() override;

  // DependentBuiltinCounterStyle is managed in the same way as
  // CustomCounterStyle.
  NS_IMETHOD_(MozExternalRefCountType) AddRef() override;
  NS_IMETHOD_(MozExternalRefCountType) Release() override;

  void* operator new(size_t sz, nsPresContext* aPresContext)
  {
    return aPresContext->PresShell()->AllocateByObjectID(
        eArenaObjectID_DependentBuiltinCounterStyle, sz);
  }

private:
  void Destroy()
  {
    nsIPresShell* shell = mManager->PresContext()->PresShell();
    this->~DependentBuiltinCounterStyle();
    shell->FreeByObjectID(eArenaObjectID_DependentBuiltinCounterStyle, this);
  }

  CounterStyleManager* mManager;

  nsAutoRefCnt mRefCnt;
  NS_DECL_OWNINGTHREAD
};

NS_IMPL_ADDREF(DependentBuiltinCounterStyle)
NS_IMPL_RELEASE_WITH_DESTROY(DependentBuiltinCounterStyle, Destroy())

/* virtual */ CounterStyle*
DependentBuiltinCounterStyle::GetFallback()
{
  switch (GetStyle()) {
    case NS_STYLE_LIST_STYLE_JAPANESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_JAPANESE_FORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANGUL_FORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_INFORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_FORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_FORMAL:
      // These styles all have a larger range than cjk-decimal, so the
      // only case fallback is accessed is that they are extended.
      // Since extending styles will cache the data themselves, we need
      // not cache it here.
      return mManager->BuildCounterStyle(NS_LITERAL_STRING("cjk-decimal"));
    default:
      NS_NOTREACHED("Not a valid dependent builtin style");
      return BuiltinCounterStyle::GetFallback();
  }
}

class CustomCounterStyle final : public CounterStyle
{
private:
  ~CustomCounterStyle() {}
public:
  CustomCounterStyle(const nsAString& aName,
                     CounterStyleManager* aManager,
                     nsCSSCounterStyleRule* aRule)
    : CounterStyle(NS_STYLE_LIST_STYLE_CUSTOM),
      mName(aName),
      mManager(aManager),
      mRule(aRule),
      mRuleGeneration(aRule->GetGeneration()),
      mSystem(aRule->GetSystem()),
      mFlags(0),
      mFallback(nullptr),
      mSpeakAsCounter(nullptr),
      mExtends(nullptr),
      mExtendsRoot(nullptr)
  {
  }

  // This method will clear all cached data in the style and update the
  // generation number of the rule. It should be called when the rule of
  // this style is changed.
  void ResetCachedData();

  // This method will reset all cached data which may depend on other
  // counter style. It will reset all pointers to other counter styles.
  // For counter style extends other, in addition, all fields will be
  // reset to uninitialized state. This method should be called when any
  // other counter style is added, removed, or changed.
  void ResetDependentData();

  nsCSSCounterStyleRule* GetRule() const { return mRule; }
  uint32_t GetRuleGeneration() const { return mRuleGeneration; }

  virtual void GetStyleName(nsSubstring& aResult) override;
  virtual void GetPrefix(nsSubstring& aResult) override;
  virtual void GetSuffix(nsSubstring& aResult) override;
  virtual void GetSpokenCounterText(CounterValue aOrdinal,
                                    WritingMode aWritingMode,
                                    nsSubstring& aResult,
                                    bool& aIsBullet) override;
  virtual bool IsBullet() override;

  virtual void GetNegative(NegativeType& aResult) override;
  virtual bool IsOrdinalInRange(CounterValue aOrdinal) override;
  virtual bool IsOrdinalInAutoRange(CounterValue aOrdinal) override;
  virtual void GetPad(PadType& aResult) override;
  virtual CounterStyle* GetFallback() override;
  virtual uint8_t GetSpeakAs() override;
  virtual bool UseNegativeSign() override;

  virtual void CallFallbackStyle(CounterValue aOrdinal,
                                 WritingMode aWritingMode,
                                 nsSubstring& aResult,
                                 bool& aIsRTL) override;
  virtual bool GetInitialCounterText(CounterValue aOrdinal,
                                     WritingMode aWritingMode,
                                     nsSubstring& aResult,
                                     bool& aIsRTL) override;

  bool IsExtendsSystem()
  {
    return mSystem == NS_STYLE_COUNTER_SYSTEM_EXTENDS;
  }

  // CustomCounterStyle should be reference-counted because it may be
  // dereferenced from the manager but still referenced by nodes and
  // frames before the style change is propagated.
  NS_IMETHOD_(MozExternalRefCountType) AddRef() override;
  NS_IMETHOD_(MozExternalRefCountType) Release() override;

  void* operator new(size_t sz, nsPresContext* aPresContext)
  {
    return aPresContext->PresShell()->AllocateByObjectID(
        eArenaObjectID_CustomCounterStyle, sz);
  }

private:
  void Destroy()
  {
    nsIPresShell* shell = mManager->PresContext()->PresShell();
    this->~CustomCounterStyle();
    shell->FreeByObjectID(eArenaObjectID_CustomCounterStyle, this);
  }

  const nsTArray<nsString>& GetSymbols();
  const nsTArray<AdditiveSymbol>& GetAdditiveSymbols();

  // The speak-as values of counter styles may form a loop, and the
  // loops may have complex interaction with the loop formed by
  // extending. To solve this problem, the computation of speak-as is
  // divided into two phases:
  // 1. figure out the raw value, by ComputeRawSpeakAs, and
  // 2. eliminate loop, by ComputeSpeakAs.
  // See comments before the definitions of these methods for details.
  uint8_t GetSpeakAsAutoValue();
  void ComputeRawSpeakAs(uint8_t& aSpeakAs,
                         CounterStyle*& aSpeakAsCounter);
  CounterStyle* ComputeSpeakAs();

  CounterStyle* ComputeExtends();
  CounterStyle* GetExtends();
  CounterStyle* GetExtendsRoot();

  nsString mName;

  // CounterStyleManager should always overlive any CounterStyle as it
  // is owned by nsPresContext, and will be released after all nodes and
  // frames are released.
  CounterStyleManager* mManager;

  RefPtr<nsCSSCounterStyleRule> mRule;
  uint32_t mRuleGeneration;

  uint8_t mSystem;
  // GetSpeakAs will ensure that private member mSpeakAs is initialized before used
  MOZ_INIT_OUTSIDE_CTOR uint8_t mSpeakAs;

  enum {
    // loop detection
    FLAG_EXTENDS_VISITED = 1 << 0,
    FLAG_EXTENDS_LOOP    = 1 << 1,
    FLAG_SPEAKAS_VISITED  = 1 << 2,
    FLAG_SPEAKAS_LOOP     = 1 << 3,
    // field status
    FLAG_NEGATIVE_INITED  = 1 << 4,
    FLAG_PREFIX_INITED    = 1 << 5,
    FLAG_SUFFIX_INITED    = 1 << 6,
    FLAG_PAD_INITED       = 1 << 7,
    FLAG_SPEAKAS_INITED   = 1 << 8,
  };
  uint16_t mFlags;

  // Fields below will be initialized when necessary.
  nsTArray<nsString> mSymbols;
  nsTArray<AdditiveSymbol> mAdditiveSymbols;
  NegativeType mNegative;
  nsString mPrefix, mSuffix;
  PadType mPad;

  // CounterStyleManager will guarantee that none of the pointers below
  // refers to a freed CounterStyle. There are two possible cases where
  // the manager will release its reference to a CounterStyle: 1. the
  // manager itself is released, 2. a rule is invalidated. In the first
  // case, all counter style are removed from the manager, and should
  // also have been dereferenced from other objects. All styles will be
  // released all together. In the second case, CounterStyleManager::
  // NotifyRuleChanged will guarantee that all pointers will be reset
  // before any CounterStyle is released.

  CounterStyle* mFallback;
  // This field refers to the last counter in a speak-as chain.
  // That counter must not speak as another counter.
  CounterStyle* mSpeakAsCounter;

  CounterStyle* mExtends;
  // This field refers to the last counter in the extends chain. The
  // counter must be either a builtin style or a style whose system is
  // not 'extends'.
  CounterStyle* mExtendsRoot;

  nsAutoRefCnt mRefCnt;
  NS_DECL_OWNINGTHREAD
};

NS_IMPL_ADDREF(CustomCounterStyle)
NS_IMPL_RELEASE_WITH_DESTROY(CustomCounterStyle, Destroy())

void
CustomCounterStyle::ResetCachedData()
{
  mSymbols.Clear();
  mAdditiveSymbols.Clear();
  mFlags &= ~(FLAG_NEGATIVE_INITED |
              FLAG_PREFIX_INITED |
              FLAG_SUFFIX_INITED |
              FLAG_PAD_INITED |
              FLAG_SPEAKAS_INITED);
  mFallback = nullptr;
  mSpeakAsCounter = nullptr;
  mExtends = nullptr;
  mExtendsRoot = nullptr;
  mRuleGeneration = mRule->GetGeneration();
}

void
CustomCounterStyle::ResetDependentData()
{
  mFlags &= ~FLAG_SPEAKAS_INITED;
  mSpeakAsCounter = nullptr;
  mFallback = nullptr;
  mExtends = nullptr;
  mExtendsRoot = nullptr;
  if (IsExtendsSystem()) {
    mFlags &= ~(FLAG_NEGATIVE_INITED |
                FLAG_PREFIX_INITED |
                FLAG_SUFFIX_INITED |
                FLAG_PAD_INITED);
  }
}

/* virtual */ void
CustomCounterStyle::GetStyleName(nsSubstring& aResult)
{
  aResult.Assign(mName);
}

/* virtual */ void
CustomCounterStyle::GetPrefix(nsSubstring& aResult)
{
  if (!(mFlags & FLAG_PREFIX_INITED)) {
    mFlags |= FLAG_PREFIX_INITED;

    const nsCSSValue& value = mRule->GetDesc(eCSSCounterDesc_Prefix);
    if (value.UnitHasStringValue()) {
      value.GetStringValue(mPrefix);
    } else if (IsExtendsSystem()) {
      GetExtends()->GetPrefix(mPrefix);
    } else {
      mPrefix.Truncate();
    }
  }
  aResult = mPrefix;
}

/* virtual */ void
CustomCounterStyle::GetSuffix(nsSubstring& aResult)
{
  if (!(mFlags & FLAG_SUFFIX_INITED)) {
    mFlags |= FLAG_SUFFIX_INITED;

    const nsCSSValue& value = mRule->GetDesc(eCSSCounterDesc_Suffix);
    if (value.UnitHasStringValue()) {
      value.GetStringValue(mSuffix);
    } else if (IsExtendsSystem()) {
      GetExtends()->GetSuffix(mSuffix);
    } else {
      mSuffix.AssignLiteral(u". ");
    }
  }
  aResult = mSuffix;
}

/* virtual */ void
CustomCounterStyle::GetSpokenCounterText(CounterValue aOrdinal,
                                         WritingMode aWritingMode,
                                         nsSubstring& aResult,
                                         bool& aIsBullet)
{
  if (GetSpeakAs() != NS_STYLE_COUNTER_SPEAKAS_OTHER) {
    CounterStyle::GetSpokenCounterText(
        aOrdinal, aWritingMode, aResult, aIsBullet);
  } else {
    MOZ_ASSERT(mSpeakAsCounter,
               "mSpeakAsCounter should have been initialized.");
    mSpeakAsCounter->GetSpokenCounterText(
        aOrdinal, aWritingMode, aResult, aIsBullet);
  }
}

/* virtual */ bool
CustomCounterStyle::IsBullet()
{
  switch (mSystem) {
    case NS_STYLE_COUNTER_SYSTEM_CYCLIC:
      // Only use ::-moz-list-bullet for cyclic system
      return true;
    case NS_STYLE_COUNTER_SYSTEM_EXTENDS:
      return GetExtendsRoot()->IsBullet();
    default:
      return false;
  }
}

/* virtual */ void
CustomCounterStyle::GetNegative(NegativeType& aResult)
{
  if (!(mFlags & FLAG_NEGATIVE_INITED)) {
    mFlags |= FLAG_NEGATIVE_INITED;
    const nsCSSValue& value = mRule->GetDesc(eCSSCounterDesc_Negative);
    switch (value.GetUnit()) {
      case eCSSUnit_Ident:
      case eCSSUnit_String:
        value.GetStringValue(mNegative.before);
        mNegative.after.Truncate();
        break;
      case eCSSUnit_Pair: {
        const nsCSSValuePair& pair = value.GetPairValue();
        pair.mXValue.GetStringValue(mNegative.before);
        pair.mYValue.GetStringValue(mNegative.after);
        break;
      }
      default: {
        if (IsExtendsSystem()) {
          GetExtends()->GetNegative(mNegative);
        } else {
          mNegative.before.AssignLiteral(u"-");
          mNegative.after.Truncate();
        }
      }
    }
  }
  aResult = mNegative;
}

static inline bool
IsRangeValueInfinite(const nsCSSValue& aValue)
{
  return aValue.GetUnit() == eCSSUnit_Enumerated &&
         aValue.GetIntValue() == NS_STYLE_COUNTER_RANGE_INFINITE;
}

/* virtual */ bool
CustomCounterStyle::IsOrdinalInRange(CounterValue aOrdinal)
{
  const nsCSSValue& value = mRule->GetDesc(eCSSCounterDesc_Range);
  if (value.GetUnit() == eCSSUnit_PairList) {
    for (const nsCSSValuePairList* item = value.GetPairListValue();
         item != nullptr; item = item->mNext) {
      const nsCSSValue& lowerBound = item->mXValue;
      const nsCSSValue& upperBound = item->mYValue;
      if ((IsRangeValueInfinite(lowerBound) ||
           aOrdinal >= lowerBound.GetIntValue()) &&
          (IsRangeValueInfinite(upperBound) ||
           aOrdinal <= upperBound.GetIntValue())) {
        return true;
      }
    }
    return false;
  } else if (IsExtendsSystem() && value.GetUnit() == eCSSUnit_None) {
    // Only use the range of extended style when 'range' is not specified.
    return GetExtends()->IsOrdinalInRange(aOrdinal);
  }
  return IsOrdinalInAutoRange(aOrdinal);
}

/* virtual */ bool
CustomCounterStyle::IsOrdinalInAutoRange(CounterValue aOrdinal)
{
  switch (mSystem) {
    case NS_STYLE_COUNTER_SYSTEM_CYCLIC:
    case NS_STYLE_COUNTER_SYSTEM_NUMERIC:
    case NS_STYLE_COUNTER_SYSTEM_FIXED:
      return true;
    case NS_STYLE_COUNTER_SYSTEM_ALPHABETIC:
    case NS_STYLE_COUNTER_SYSTEM_SYMBOLIC:
      return aOrdinal >= 1;
    case NS_STYLE_COUNTER_SYSTEM_ADDITIVE:
      return aOrdinal >= 0;
    case NS_STYLE_COUNTER_SYSTEM_EXTENDS:
      return GetExtendsRoot()->IsOrdinalInAutoRange(aOrdinal);
    default:
      NS_NOTREACHED("Invalid system for computing auto value.");
      return false;
  }
}

/* virtual */ void
CustomCounterStyle::GetPad(PadType& aResult)
{
  if (!(mFlags & FLAG_PAD_INITED)) {
    mFlags |= FLAG_PAD_INITED;
    const nsCSSValue& value = mRule->GetDesc(eCSSCounterDesc_Pad);
    if (value.GetUnit() == eCSSUnit_Pair) {
      const nsCSSValuePair& pair = value.GetPairValue();
      mPad.width = pair.mXValue.GetIntValue();
      pair.mYValue.GetStringValue(mPad.symbol);
    } else if (IsExtendsSystem()) {
      GetExtends()->GetPad(mPad);
    } else {
      mPad.width = 0;
      mPad.symbol.Truncate();
    }
  }
  aResult = mPad;
}

/* virtual */ CounterStyle*
CustomCounterStyle::GetFallback()
{
  if (!mFallback) {
    const nsCSSValue& value = mRule->GetDesc(eCSSCounterDesc_Fallback);
    if (value.UnitHasStringValue()) {
      mFallback = mManager->BuildCounterStyle(
          nsDependentString(value.GetStringBufferValue()));
    } else if (IsExtendsSystem()) {
      mFallback = GetExtends()->GetFallback();
    } else {
      mFallback = CounterStyleManager::GetDecimalStyle();
    }
  }
  return mFallback;
}

/* virtual */ uint8_t
CustomCounterStyle::GetSpeakAs()
{
  if (!(mFlags & FLAG_SPEAKAS_INITED)) {
    ComputeSpeakAs();
  }
  return mSpeakAs;
}

/* virtual */ bool
CustomCounterStyle::UseNegativeSign()
{
  if (mSystem == NS_STYLE_COUNTER_SYSTEM_EXTENDS) {
    return GetExtendsRoot()->UseNegativeSign();
  }
  return SystemUsesNegativeSign(mSystem);
}

/* virtual */ void
CustomCounterStyle::CallFallbackStyle(CounterValue aOrdinal,
                                      WritingMode aWritingMode,
                                      nsSubstring& aResult,
                                      bool& aIsRTL)
{
  CounterStyle* fallback = GetFallback();
  // If it recursively falls back to this counter style again,
  // it will then fallback to decimal to break the loop.
  mFallback = CounterStyleManager::GetDecimalStyle();
  fallback->GetCounterText(aOrdinal, aWritingMode, aResult, aIsRTL);
  mFallback = fallback;
}

/* virtual */ bool
CustomCounterStyle::GetInitialCounterText(CounterValue aOrdinal,
                                          WritingMode aWritingMode,
                                          nsSubstring& aResult,
                                          bool& aIsRTL)
{
  switch (mSystem) {
    case NS_STYLE_COUNTER_SYSTEM_CYCLIC:
      return GetCyclicCounterText(aOrdinal, aResult, GetSymbols());
    case NS_STYLE_COUNTER_SYSTEM_FIXED: {
      int32_t start = mRule->GetSystemArgument().GetIntValue();
      return GetFixedCounterText(aOrdinal, aResult, start, GetSymbols());
    }
    case NS_STYLE_COUNTER_SYSTEM_SYMBOLIC:
      return GetSymbolicCounterText(aOrdinal, aResult, GetSymbols());
    case NS_STYLE_COUNTER_SYSTEM_ALPHABETIC:
      return GetAlphabeticCounterText(aOrdinal, aResult, GetSymbols());
    case NS_STYLE_COUNTER_SYSTEM_NUMERIC:
      return GetNumericCounterText(aOrdinal, aResult, GetSymbols());
    case NS_STYLE_COUNTER_SYSTEM_ADDITIVE:
      return GetAdditiveCounterText(aOrdinal, aResult, GetAdditiveSymbols());
    case NS_STYLE_COUNTER_SYSTEM_EXTENDS:
      return GetExtendsRoot()->
        GetInitialCounterText(aOrdinal, aWritingMode, aResult, aIsRTL);
    default:
      NS_NOTREACHED("Invalid system.");
      return false;
  }
}

const nsTArray<nsString>&
CustomCounterStyle::GetSymbols()
{
  if (mSymbols.IsEmpty()) {
    const nsCSSValue& values = mRule->GetDesc(eCSSCounterDesc_Symbols);
    for (const nsCSSValueList* item = values.GetListValue();
         item; item = item->mNext) {
      nsString* symbol = mSymbols.AppendElement();
      item->mValue.GetStringValue(*symbol);
    }
    mSymbols.Compact();
  }
  return mSymbols;
}

const nsTArray<AdditiveSymbol>&
CustomCounterStyle::GetAdditiveSymbols()
{
  if (mAdditiveSymbols.IsEmpty()) {
    const nsCSSValue& values = mRule->GetDesc(eCSSCounterDesc_AdditiveSymbols);
    for (const nsCSSValuePairList* item = values.GetPairListValue();
         item; item = item->mNext) {
      AdditiveSymbol* symbol = mAdditiveSymbols.AppendElement();
      symbol->weight = item->mXValue.GetIntValue();
      item->mYValue.GetStringValue(symbol->symbol);
    }
    mAdditiveSymbols.Compact();
  }
  return mAdditiveSymbols;
}

// This method is used to provide the computed value for 'auto'.
uint8_t
CustomCounterStyle::GetSpeakAsAutoValue()
{
  uint8_t system = mSystem;
  if (IsExtendsSystem()) {
    CounterStyle* root = GetExtendsRoot();
    if (!root->IsCustomStyle()) {
      // It is safe to call GetSpeakAs on non-custom style.
      return root->GetSpeakAs();
    }
    system = static_cast<CustomCounterStyle*>(root)->mSystem;
  }
  return GetDefaultSpeakAsForSystem(system);
}

// This method corresponds to the first stage of computation of the
// value of speak-as. It will extract the value from the rule and
// possibly recursively call itself on the extended style to figure
// out the raw value. To keep things clear, this method is designed to
// have no side effects (but functions it calls may still affect other
// fields in the style.)
void
CustomCounterStyle::ComputeRawSpeakAs(uint8_t& aSpeakAs,
                                    CounterStyle*& aSpeakAsCounter)
{
  NS_ASSERTION(!(mFlags & FLAG_SPEAKAS_INITED),
               "ComputeRawSpeakAs is called with speak-as inited.");

  const nsCSSValue& value = mRule->GetDesc(eCSSCounterDesc_SpeakAs);
  switch (value.GetUnit()) {
    case eCSSUnit_Auto:
      aSpeakAs = GetSpeakAsAutoValue();
      break;
    case eCSSUnit_Enumerated:
      aSpeakAs = value.GetIntValue();
      break;
    case eCSSUnit_Ident:
      aSpeakAs = NS_STYLE_COUNTER_SPEAKAS_OTHER;
      aSpeakAsCounter = mManager->BuildCounterStyle(
          nsDependentString(value.GetStringBufferValue()));
      break;
    case eCSSUnit_Null: {
      if (!IsExtendsSystem()) {
        aSpeakAs = GetSpeakAsAutoValue();
      } else {
        CounterStyle* extended = GetExtends();
        if (!extended->IsCustomStyle()) {
          // It is safe to call GetSpeakAs on non-custom style.
          aSpeakAs = extended->GetSpeakAs();
        } else {
          CustomCounterStyle* custom =
            static_cast<CustomCounterStyle*>(extended);
          if (!(custom->mFlags & FLAG_SPEAKAS_INITED)) {
            custom->ComputeRawSpeakAs(aSpeakAs, aSpeakAsCounter);
          } else {
            aSpeakAs = custom->mSpeakAs;
            aSpeakAsCounter = custom->mSpeakAsCounter;
          }
        }
      }
      break;
    }
    default:
      NS_NOTREACHED("Invalid speak-as value");
  }
}

// This method corresponds to the second stage of getting speak-as
// related values. It will recursively figure out the final value of
// mSpeakAs and mSpeakAsCounter. This method returns nullptr if the
// caller is in a loop, and the root counter style in the chain
// otherwise. It use the same loop detection algorithm as
// CustomCounterStyle::ComputeExtends, see comments before that
// method for more details.
CounterStyle*
CustomCounterStyle::ComputeSpeakAs()
{
  if (mFlags & FLAG_SPEAKAS_INITED) {
    if (mSpeakAs == NS_STYLE_COUNTER_SPEAKAS_OTHER) {
      return mSpeakAsCounter;
    }
    return this;
  }

  if (mFlags & FLAG_SPEAKAS_VISITED) {
    // loop detected
    mFlags |= FLAG_SPEAKAS_LOOP;
    return nullptr;
  }

  CounterStyle* speakAsCounter;
  ComputeRawSpeakAs(mSpeakAs, speakAsCounter);

  bool inLoop = false;
  if (mSpeakAs != NS_STYLE_COUNTER_SPEAKAS_OTHER) {
    mSpeakAsCounter = nullptr;
  } else if (!speakAsCounter->IsCustomStyle()) {
    mSpeakAsCounter = speakAsCounter;
  } else {
    mFlags |= FLAG_SPEAKAS_VISITED;
    CounterStyle* target =
      static_cast<CustomCounterStyle*>(speakAsCounter)->ComputeSpeakAs();
    mFlags &= ~FLAG_SPEAKAS_VISITED;

    if (target) {
      NS_ASSERTION(!(mFlags & FLAG_SPEAKAS_LOOP),
                   "Invalid state for speak-as loop detecting");
      mSpeakAsCounter = target;
    } else {
      mSpeakAs = GetSpeakAsAutoValue();
      mSpeakAsCounter = nullptr;
      if (mFlags & FLAG_SPEAKAS_LOOP) {
        mFlags &= ~FLAG_SPEAKAS_LOOP;
      } else {
        inLoop = true;
      }
    }
  }

  mFlags |= FLAG_SPEAKAS_INITED;
  if (inLoop) {
    return nullptr;
  }
  return mSpeakAsCounter ? mSpeakAsCounter : this;
}

// This method will recursively figure out mExtends in the whole chain.
// It will return nullptr if the caller is in a loop, and return this
// otherwise. To detect the loop, this method marks the style VISITED
// before the recursive call. When a VISITED style is reached again, the
// loop is detected, and flag LOOP will be marked on the first style in
// loop. mExtends of all counter styles in loop will be set to decimal
// according to the spec.
CounterStyle*
CustomCounterStyle::ComputeExtends()
{
  if (!IsExtendsSystem() || mExtends) {
    return this;
  }
  if (mFlags & FLAG_EXTENDS_VISITED) {
    // loop detected
    mFlags |= FLAG_EXTENDS_LOOP;
    return nullptr;
  }

  const nsCSSValue& value = mRule->GetSystemArgument();
  CounterStyle* nextCounter = mManager->BuildCounterStyle(
      nsDependentString(value.GetStringBufferValue()));
  CounterStyle* target = nextCounter;
  if (nextCounter->IsCustomStyle()) {
    mFlags |= FLAG_EXTENDS_VISITED;
    target = static_cast<CustomCounterStyle*>(nextCounter)->ComputeExtends();
    mFlags &= ~FLAG_EXTENDS_VISITED;
  }

  if (target) {
    NS_ASSERTION(!(mFlags & FLAG_EXTENDS_LOOP),
                 "Invalid state for extends loop detecting");
    mExtends = nextCounter;
    return this;
  } else {
    mExtends = CounterStyleManager::GetDecimalStyle();
    if (mFlags & FLAG_EXTENDS_LOOP) {
      mFlags &= ~FLAG_EXTENDS_LOOP;
      return this;
    } else {
      return nullptr;
    }
  }
}

CounterStyle*
CustomCounterStyle::GetExtends()
{
  if (!mExtends) {
    // Any extends loop will be eliminated in the method below.
    ComputeExtends();
  }
  return mExtends;
}

CounterStyle*
CustomCounterStyle::GetExtendsRoot()
{
  if (!mExtendsRoot) {
    CounterStyle* extended = GetExtends();
    mExtendsRoot = extended;
    if (extended->IsCustomStyle()) {
      CustomCounterStyle* custom = static_cast<CustomCounterStyle*>(extended);
      if (custom->IsExtendsSystem()) {
        // This will make mExtendsRoot in the whole extends chain be
        // set recursively, which could save work when part of a chain
        // is shared by multiple counter styles.
        mExtendsRoot = custom->GetExtendsRoot();
      }
    }
  }
  return mExtendsRoot;
}

AnonymousCounterStyle::AnonymousCounterStyle(const nsSubstring& aContent)
  : CounterStyle(NS_STYLE_LIST_STYLE_CUSTOM)
  , mSingleString(true)
  , mSystem(NS_STYLE_COUNTER_SYSTEM_CYCLIC)
{
  mSymbols.SetCapacity(1);
  mSymbols.AppendElement(aContent);
}

AnonymousCounterStyle::AnonymousCounterStyle(const nsCSSValue::Array* aParams)
  : CounterStyle(NS_STYLE_LIST_STYLE_CUSTOM)
  , mSingleString(false)
  , mSystem(aParams->Item(0).GetIntValue())
{
  for (const nsCSSValueList* item = aParams->Item(1).GetListValue();
       item; item = item->mNext) {
    item->mValue.GetStringValue(*mSymbols.AppendElement());
  }
  mSymbols.Compact();
}

/* virtual */ void
AnonymousCounterStyle::GetStyleName(nsAString& aResult)
{
  aResult.Truncate();
}

/* virtual */ void
AnonymousCounterStyle::GetPrefix(nsAString& aResult)
{
  aResult.Truncate();
}

/* virtual */ void
AnonymousCounterStyle::GetSuffix(nsAString& aResult)
{
  if (IsSingleString()) {
    aResult.Truncate();
  } else {
    aResult = ' ';
  }
}

/* virtual */ bool
AnonymousCounterStyle::IsBullet()
{
  switch (mSystem) {
    case NS_STYLE_COUNTER_SYSTEM_CYCLIC:
      // Only use ::-moz-list-bullet for cyclic system
      return true;
    default:
      return false;
  }
}

/* virtual */ void
AnonymousCounterStyle::GetNegative(NegativeType& aResult)
{
  aResult.before.AssignLiteral(u"-");
  aResult.after.Truncate();
}

/* virtual */ bool
AnonymousCounterStyle::IsOrdinalInRange(CounterValue aOrdinal)
{
  switch (mSystem) {
    case NS_STYLE_COUNTER_SYSTEM_CYCLIC:
    case NS_STYLE_COUNTER_SYSTEM_NUMERIC:
    case NS_STYLE_COUNTER_SYSTEM_FIXED:
      return true;
    case NS_STYLE_COUNTER_SYSTEM_ALPHABETIC:
    case NS_STYLE_COUNTER_SYSTEM_SYMBOLIC:
      return aOrdinal >= 1;
    default:
      NS_NOTREACHED("Invalid system.");
      return false;
  }
}

/* virtual */ bool
AnonymousCounterStyle::IsOrdinalInAutoRange(CounterValue aOrdinal)
{
  return AnonymousCounterStyle::IsOrdinalInRange(aOrdinal);
}

/* virtual */ void
AnonymousCounterStyle::GetPad(PadType& aResult)
{
  aResult.width = 0;
  aResult.symbol.Truncate();
}

/* virtual */ CounterStyle*
AnonymousCounterStyle::GetFallback()
{
  return CounterStyleManager::GetDecimalStyle();
}

/* virtual */ uint8_t
AnonymousCounterStyle::GetSpeakAs()
{
  return GetDefaultSpeakAsForSystem(mSystem);
}

/* virtual */ bool
AnonymousCounterStyle::UseNegativeSign()
{
  return SystemUsesNegativeSign(mSystem);
}

/* virtual */ bool
AnonymousCounterStyle::GetInitialCounterText(CounterValue aOrdinal,
                                             WritingMode aWritingMode,
                                             nsAString& aResult,
                                             bool& aIsRTL)
{
  switch (mSystem) {
    case NS_STYLE_COUNTER_SYSTEM_CYCLIC:
      return GetCyclicCounterText(aOrdinal, aResult, mSymbols);
    case NS_STYLE_COUNTER_SYSTEM_FIXED:
      return GetFixedCounterText(aOrdinal, aResult, 1, mSymbols);
    case NS_STYLE_COUNTER_SYSTEM_SYMBOLIC:
      return GetSymbolicCounterText(aOrdinal, aResult, mSymbols);
    case NS_STYLE_COUNTER_SYSTEM_ALPHABETIC:
      return GetAlphabeticCounterText(aOrdinal, aResult, mSymbols);
    case NS_STYLE_COUNTER_SYSTEM_NUMERIC:
      return GetNumericCounterText(aOrdinal, aResult, mSymbols);
    default:
      NS_NOTREACHED("Invalid system.");
      return false;
  }
}

bool
CounterStyle::IsDependentStyle() const
{
  switch (mStyle) {
    // CustomCounterStyle
    case NS_STYLE_LIST_STYLE_CUSTOM:
    // DependentBuiltinCounterStyle
    case NS_STYLE_LIST_STYLE_JAPANESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_JAPANESE_FORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANGUL_FORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_INFORMAL:
    case NS_STYLE_LIST_STYLE_KOREAN_HANJA_FORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_SIMP_CHINESE_FORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_INFORMAL:
    case NS_STYLE_LIST_STYLE_TRAD_CHINESE_FORMAL:
      return true;

    // BuiltinCounterStyle
    default:
      return false;
  }
}

void
CounterStyle::GetCounterText(CounterValue aOrdinal,
                             WritingMode aWritingMode,
                             nsSubstring& aResult,
                             bool& aIsRTL)
{
  bool success = IsOrdinalInRange(aOrdinal);
  aIsRTL = false;

  if (success) {
    // generate initial representation
    bool useNegativeSign = UseNegativeSign();
    nsAutoString initialText;
    CounterValue ordinal;
    if (!useNegativeSign) {
      ordinal = aOrdinal;
    } else {
      CheckedInt<CounterValue> absolute(Abs(aOrdinal));
      ordinal = absolute.isValid() ?
        absolute.value() : std::numeric_limits<CounterValue>::max();
    }
    success = GetInitialCounterText(
        ordinal, aWritingMode, initialText, aIsRTL);

    // add pad & negative, build the final result
    if (success) {
      PadType pad;
      GetPad(pad);
      // We have to calculate the difference here since suffix part of negative
      // sign may be appended to initialText later.
      int32_t diff = pad.width -
        unicode::CountGraphemeClusters(initialText.Data(),
                                       initialText.Length());
      aResult.Truncate();
      if (useNegativeSign && aOrdinal < 0) {
        NegativeType negative;
        GetNegative(negative);
        aResult.Append(negative.before);
        // There is nothing between the suffix part of negative and initial
        // representation, so we append it directly here.
        initialText.Append(negative.after);
      }
      if (diff > 0) {
        auto length = pad.symbol.Length();
        if (diff > LENGTH_LIMIT || length > LENGTH_LIMIT ||
            diff * length > LENGTH_LIMIT) {
          success = false;
        } else if (length > 0) {
          for (int32_t i = 0; i < diff; ++i) {
            aResult.Append(pad.symbol);
          }
        }
      }
      if (success) {
        aResult.Append(initialText);
      }
    }
  }

  if (!success) {
    CallFallbackStyle(aOrdinal, aWritingMode, aResult, aIsRTL);
  }
}

/* virtual */ void
CounterStyle::GetSpokenCounterText(CounterValue aOrdinal,
                                   WritingMode aWritingMode,
                                   nsSubstring& aResult,
                                   bool& aIsBullet)
{
  bool isRTL; // we don't care about direction for spoken text
  aIsBullet = false;
  switch (GetSpeakAs()) {
    case NS_STYLE_COUNTER_SPEAKAS_BULLETS:
      aResult.Assign(kDiscCharacter);
      aIsBullet = true;
      break;
    case NS_STYLE_COUNTER_SPEAKAS_NUMBERS:
      DecimalToText(aOrdinal, aResult);
      break;
    case NS_STYLE_COUNTER_SPEAKAS_SPELL_OUT:
      // we currently do not actually support 'spell-out',
      // so 'words' is used instead.
    case NS_STYLE_COUNTER_SPEAKAS_WORDS:
      GetCounterText(aOrdinal, WritingMode(), aResult, isRTL);
      break;
    case NS_STYLE_COUNTER_SPEAKAS_OTHER:
      // This should be processed by CustomCounterStyle
      NS_NOTREACHED("Invalid speak-as value");
      break;
    default:
      NS_NOTREACHED("Unknown speak-as value");
      break;
  }
}

/* virtual */ void
CounterStyle::CallFallbackStyle(CounterValue aOrdinal,
                                WritingMode aWritingMode,
                                nsAString& aResult,
                                bool& aIsRTL)
{
  GetFallback()->GetCounterText(aOrdinal, aWritingMode, aResult, aIsRTL);
}

static BuiltinCounterStyle gBuiltinStyleTable[NS_STYLE_LIST_STYLE__MAX];

CounterStyleManager::CounterStyleManager(nsPresContext* aPresContext)
  : mPresContext(aPresContext)
{
  // Insert the static styles into cache table
  mCacheTable.Put(NS_LITERAL_STRING("none"), GetNoneStyle());
  mCacheTable.Put(NS_LITERAL_STRING("decimal"), GetDecimalStyle());
}

CounterStyleManager::~CounterStyleManager()
{
  MOZ_ASSERT(!mPresContext, "Disconnect should have been called");
}

/* static */ void
CounterStyleManager::InitializeBuiltinCounterStyles()
{
  for (uint32_t i = 0; i < NS_STYLE_LIST_STYLE__MAX; ++i) {
    gBuiltinStyleTable[i].mStyle = i;
  }
}

void
CounterStyleManager::Disconnect()
{
#ifdef DEBUG
  for (auto iter = mCacheTable.Iter(); !iter.Done(); iter.Next()) {
    CounterStyle* style = iter.UserData();
    style->AddRef();
    auto refcnt = style->Release();
    NS_ASSERTION(!style->IsDependentStyle() || refcnt == 1,
                 "Counter style is still referenced by other objects.");
  }
#endif
  mCacheTable.Clear();
  mPresContext = nullptr;
}

CounterStyle*
CounterStyleManager::BuildCounterStyle(const nsSubstring& aName)
{
  CounterStyle* data = mCacheTable.GetWeak(aName);
  if (data) {
    return data;
  }

  // It is intentional that the predefined names are case-insensitive
  // but the user-defined names case-sensitive.
  // XXXheycam ServoStyleSets do not support custom counter styles yet.
  StyleSetHandle styleSet = mPresContext->StyleSet();
  NS_ASSERTION(styleSet->IsGecko(),
               "stylo: ServoStyleSets do not support custom counter "
               "styles yet");
  nsCSSCounterStyleRule* rule = styleSet->IsGecko() ?
    styleSet->AsGecko()->CounterStyleRuleForName(aName) : nullptr;
  if (rule) {
    data = new (mPresContext) CustomCounterStyle(aName, this, rule);
  } else {
    int32_t type;
    nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(aName);
    if (nsCSSProps::FindKeyword(keyword, nsCSSProps::kListStyleKTable, type)) {
      if (gBuiltinStyleTable[type].IsDependentStyle()) {
        data = new (mPresContext) DependentBuiltinCounterStyle(type, this);
      } else {
        data = GetBuiltinStyle(type);
      }
    }
  }
  if (!data) {
    data = GetDecimalStyle();
  }
  mCacheTable.Put(aName, data);
  return data;
}

/* static */ CounterStyle*
CounterStyleManager::GetBuiltinStyle(int32_t aStyle)
{
  MOZ_ASSERT(0 <= aStyle && aStyle < NS_STYLE_LIST_STYLE__MAX,
             "Require a valid builtin style constant");
  MOZ_ASSERT(!gBuiltinStyleTable[aStyle].IsDependentStyle(),
             "Cannot get dependent builtin style");
  return &gBuiltinStyleTable[aStyle];
}

bool
CounterStyleManager::NotifyRuleChanged()
{
  bool changed = false;
  nsTArray<RefPtr<CounterStyle>> kungFuDeathGrip;
  for (auto iter = mCacheTable.Iter(); !iter.Done(); iter.Next()) {
    RefPtr<CounterStyle>& style = iter.Data();
    bool toBeUpdated = false;
    bool toBeRemoved = false;
    // XXXheycam ServoStyleSets do not support custom counter styles yet.
    StyleSetHandle styleSet = mPresContext->StyleSet();
    NS_ASSERTION(styleSet->IsGecko(),
                 "stylo: ServoStyleSets do not support custom counter "
                 "styles yet");
    nsCSSCounterStyleRule* newRule = styleSet->IsGecko() ?
        styleSet->AsGecko()->CounterStyleRuleForName(iter.Key()) : nullptr;
    if (!newRule) {
      if (style->IsCustomStyle()) {
        toBeRemoved = true;
      }
    } else {
      if (!style->IsCustomStyle()) {
        toBeRemoved = true;
      } else {
        auto custom = static_cast<CustomCounterStyle*>(style.get());
        if (custom->GetRule() != newRule) {
          toBeRemoved = true;
        } else if (custom->GetRuleGeneration() != newRule->GetGeneration()) {
          toBeUpdated = true;
          custom->ResetCachedData();
        }
      }
    }
    changed = changed || toBeUpdated || toBeRemoved;
    if (toBeRemoved) {
      if (style->IsDependentStyle()) {
        if (style->IsCustomStyle()) {
          // Since |style| is being removed from mCacheTable, it won't be
          // visited by our post-removal iteration. So, we have to give it a
          // manual ResetDependentData() call. (This only really matters if
          // something else is holding a reference and keeping it alive.)
          static_cast<CustomCounterStyle*>(style.get())->ResetDependentData();
        }
        // The object has to be held here so that it will not be released
        // before all pointers that refer to it are reset. It will be released
        // when kungFuDeathGrip goes out of scope at the end of this function.
        kungFuDeathGrip.AppendElement(style);
      }
      iter.Remove();
    }
  }

  if (changed) {
    for (auto iter = mCacheTable.Iter(); !iter.Done(); iter.Next()) {
      CounterStyle* style = iter.UserData();
      if (style->IsCustomStyle()) {
        CustomCounterStyle* custom = static_cast<CustomCounterStyle*>(style);
        custom->ResetDependentData();
      }
      // There is no dependent data cached in DependentBuiltinCounterStyle
      // instances, so we don't need to reset their data.
    }
  }
  return changed;
}

} // namespace mozilla