summaryrefslogtreecommitdiffstats
path: root/dom/base/nsAttrValue.cpp
blob: ebdb61909d25d07ef6d50cb1156a9b623a7a1bb1 (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
/* -*- 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/. */

/*
 * A struct that represents the value (type and actual data) of an
 * attribute.
 */

#include "mozilla/DebugOnly.h"
#include "mozilla/HashFunctions.h"

#include "mozilla/URLExtraData.h"
#include "nsAttrValue.h"
#include "nsAttrValueInlines.h"
#include "nsAtom.h"
#include "nsUnicharUtils.h"
#include "mozilla/BloomFilter.h"
#include "mozilla/CORSMode.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/ServoBindingTypes.h"
#include "mozilla/ServoUtils.h"
#include "mozilla/ShadowParts.h"
#include "mozilla/SVGAttrValueWrapper.h"
#include "mozilla/DeclarationBlock.h"
#include "mozilla/dom/CSSRuleBinding.h"
#include "mozilla/dom/Document.h"
#include "nsContentUtils.h"
#include "nsReadableUtils.h"
#include "nsHTMLCSSStyleSheet.h"
#include "nsStyledElement.h"
#include "nsIURI.h"
#include "ReferrerInfo.h"
#include <algorithm>

using namespace mozilla;

constexpr uint32_t kMiscContainerCacheSize = 128;
static void* gMiscContainerCache[kMiscContainerCacheSize];
static uint32_t gMiscContainerCount = 0;

/* static */
MiscContainer* nsAttrValue::AllocMiscContainer() {
  MOZ_ASSERT(NS_IsMainThread());

  static_assert(sizeof(gMiscContainerCache) <= 1024);
  static_assert(sizeof(MiscContainer) <= 32);

  // Allocate MiscContainer objects in batches to improve performance.
  if (gMiscContainerCount == 0) {
    for (; gMiscContainerCount < kMiscContainerCacheSize;
         ++gMiscContainerCount) {
      gMiscContainerCache[gMiscContainerCount] =
          moz_xmalloc(sizeof(MiscContainer));
    }
  }

  return new (gMiscContainerCache[--gMiscContainerCount]) MiscContainer();
}

/* static */
void nsAttrValue::DeallocMiscContainer(MiscContainer* aCont) {
  MOZ_ASSERT(NS_IsMainThread());
  if (!aCont) {
    return;
  }

  aCont->~MiscContainer();

  if (gMiscContainerCount < kMiscContainerCacheSize) {
    gMiscContainerCache[gMiscContainerCount++] = aCont;
    return;
  }

  free(aCont);
}

bool MiscContainer::GetString(nsAString& aString) const {
  bool isString;
  void* ptr = GetStringOrAtomPtr(isString);
  if (!ptr) {
    return false;
  }
  if (isString) {
    auto* buffer = static_cast<nsStringBuffer*>(ptr);
    buffer->ToString(buffer->StorageSize() / sizeof(char16_t) - 1, aString);
  } else {
    static_cast<nsAtom*>(ptr)->ToString(aString);
  }
  return true;
}

void MiscContainer::Cache() {
  // Not implemented for anything else yet.
  if (mType != nsAttrValue::eCSSDeclaration) {
    MOZ_ASSERT_UNREACHABLE("unexpected cached nsAttrValue type");
    return;
  }

  MOZ_ASSERT(IsRefCounted());
  MOZ_ASSERT(mValue.mRefCount > 0);
  MOZ_ASSERT(!mValue.mCached);

  nsHTMLCSSStyleSheet* sheet = mValue.mCSSDeclaration->GetHTMLCSSStyleSheet();
  if (!sheet) {
    return;
  }

  nsString str;
  bool gotString = GetString(str);
  if (!gotString) {
    return;
  }

  sheet->CacheStyleAttr(str, this);
  mValue.mCached = 1;

  // This has to be immutable once it goes into the cache.
  mValue.mCSSDeclaration->SetImmutable();
}

void MiscContainer::Evict() {
  // Not implemented for anything else yet.
  if (mType != nsAttrValue::eCSSDeclaration) {
    MOZ_ASSERT_UNREACHABLE("unexpected cached nsAttrValue type");
    return;
  }
  MOZ_ASSERT(IsRefCounted());
  MOZ_ASSERT(mValue.mRefCount == 0);

  if (!mValue.mCached) {
    return;
  }

  nsHTMLCSSStyleSheet* sheet = mValue.mCSSDeclaration->GetHTMLCSSStyleSheet();
  MOZ_ASSERT(sheet);

  nsString str;
  DebugOnly<bool> gotString = GetString(str);
  MOZ_ASSERT(gotString);

  sheet->EvictStyleAttr(str, this);
  mValue.mCached = 0;
}

nsTArray<const nsAttrValue::EnumTable*>* nsAttrValue::sEnumTableArray = nullptr;

nsAttrValue::nsAttrValue() : mBits(0) {}

nsAttrValue::nsAttrValue(const nsAttrValue& aOther) : mBits(0) {
  SetTo(aOther);
}

nsAttrValue::nsAttrValue(const nsAString& aValue) : mBits(0) { SetTo(aValue); }

nsAttrValue::nsAttrValue(nsAtom* aValue) : mBits(0) { SetTo(aValue); }

nsAttrValue::nsAttrValue(already_AddRefed<DeclarationBlock> aValue,
                         const nsAString* aSerialized)
    : mBits(0) {
  SetTo(std::move(aValue), aSerialized);
}

nsAttrValue::~nsAttrValue() { ResetIfSet(); }

/* static */
void nsAttrValue::Init() {
  MOZ_ASSERT(!sEnumTableArray, "nsAttrValue already initialized");
  sEnumTableArray = new nsTArray<const EnumTable*>;
}

/* static */
void nsAttrValue::Shutdown() {
  MOZ_ASSERT(NS_IsMainThread());
  delete sEnumTableArray;
  sEnumTableArray = nullptr;

  for (uint32_t i = 0; i < gMiscContainerCount; ++i) {
    free(gMiscContainerCache[i]);
  }
  gMiscContainerCount = 0;
}

void nsAttrValue::Reset() {
  switch (BaseType()) {
    case eStringBase: {
      nsStringBuffer* str = static_cast<nsStringBuffer*>(GetPtr());
      if (str) {
        str->Release();
      }

      break;
    }
    case eOtherBase: {
      MiscContainer* cont = GetMiscContainer();
      if (cont->IsRefCounted() && cont->mValue.mRefCount > 1) {
        NS_RELEASE(cont);
        break;
      }

      DeallocMiscContainer(ClearMiscContainer());

      break;
    }
    case eAtomBase: {
      nsAtom* atom = GetAtomValue();
      NS_RELEASE(atom);

      break;
    }
    case eIntegerBase: {
      break;
    }
  }

  mBits = 0;
}

void nsAttrValue::SetTo(const nsAttrValue& aOther) {
  if (this == &aOther) {
    return;
  }

  switch (aOther.BaseType()) {
    case eStringBase: {
      ResetIfSet();
      nsStringBuffer* str = static_cast<nsStringBuffer*>(aOther.GetPtr());
      if (str) {
        str->AddRef();
        SetPtrValueAndType(str, eStringBase);
      }
      return;
    }
    case eOtherBase: {
      break;
    }
    case eAtomBase: {
      ResetIfSet();
      nsAtom* atom = aOther.GetAtomValue();
      NS_ADDREF(atom);
      SetPtrValueAndType(atom, eAtomBase);
      return;
    }
    case eIntegerBase: {
      ResetIfSet();
      mBits = aOther.mBits;
      return;
    }
  }

  MiscContainer* otherCont = aOther.GetMiscContainer();
  if (otherCont->IsRefCounted()) {
    DeallocMiscContainer(ClearMiscContainer());
    NS_ADDREF(otherCont);
    SetPtrValueAndType(otherCont, eOtherBase);
    return;
  }

  MiscContainer* cont = EnsureEmptyMiscContainer();
  switch (otherCont->mType) {
    case eInteger: {
      cont->mValue.mInteger = otherCont->mValue.mInteger;
      break;
    }
    case eEnum: {
      cont->mValue.mEnumValue = otherCont->mValue.mEnumValue;
      break;
    }
    case ePercent: {
      cont->mDoubleValue = otherCont->mDoubleValue;
      break;
    }
    case eColor: {
      cont->mValue.mColor = otherCont->mValue.mColor;
      break;
    }
    case eShadowParts:
    case eCSSDeclaration: {
      MOZ_CRASH("These should be refcounted!");
    }
    case eURL: {
      NS_ADDREF(cont->mValue.mURL = otherCont->mValue.mURL);
      break;
    }
    case eAtomArray: {
      if (!EnsureEmptyAtomArray()) {
        Reset();
        return;
      }
      // XXX(Bug 1631371) Check if this should use a fallible operation as it
      // pretended earlier.
      *GetAtomArrayValue() = otherCont->mValue.mAtomArray->Clone();

      break;
    }
    case eDoubleValue: {
      cont->mDoubleValue = otherCont->mDoubleValue;
      break;
    }
    default: {
      if (IsSVGType(otherCont->mType)) {
        // All SVG types are just pointers to classes and will therefore have
        // the same size so it doesn't really matter which one we assign
        cont->mValue.mSVGLength = otherCont->mValue.mSVGLength;
      } else {
        MOZ_ASSERT_UNREACHABLE("unknown type stored in MiscContainer");
      }
      break;
    }
  }

  bool isString;
  if (void* otherPtr = otherCont->GetStringOrAtomPtr(isString)) {
    if (isString) {
      static_cast<nsStringBuffer*>(otherPtr)->AddRef();
    } else {
      static_cast<nsAtom*>(otherPtr)->AddRef();
    }
    cont->SetStringBitsMainThread(otherCont->mStringBits);
  }
  // Note, set mType after switch-case, otherwise EnsureEmptyAtomArray doesn't
  // work correctly.
  cont->mType = otherCont->mType;
}

void nsAttrValue::SetTo(const nsAString& aValue) {
  ResetIfSet();
  nsStringBuffer* buf = GetStringBuffer(aValue).take();
  if (buf) {
    SetPtrValueAndType(buf, eStringBase);
  }
}

void nsAttrValue::SetTo(nsAtom* aValue) {
  ResetIfSet();
  if (aValue) {
    NS_ADDREF(aValue);
    SetPtrValueAndType(aValue, eAtomBase);
  }
}

void nsAttrValue::SetTo(int16_t aInt) {
  ResetIfSet();
  SetIntValueAndType(aInt, eInteger, nullptr);
}

void nsAttrValue::SetTo(int32_t aInt, const nsAString* aSerialized) {
  ResetIfSet();
  SetIntValueAndType(aInt, eInteger, aSerialized);
}

void nsAttrValue::SetTo(double aValue, const nsAString* aSerialized) {
  MiscContainer* cont = EnsureEmptyMiscContainer();
  cont->mDoubleValue = aValue;
  cont->mType = eDoubleValue;
  SetMiscAtomOrString(aSerialized);
}

void nsAttrValue::SetTo(already_AddRefed<DeclarationBlock> aValue,
                        const nsAString* aSerialized) {
  MiscContainer* cont = EnsureEmptyMiscContainer();
  MOZ_ASSERT(cont->mValue.mRefCount == 0);
  cont->mValue.mCSSDeclaration = aValue.take();
  cont->mType = eCSSDeclaration;
  NS_ADDREF(cont);
  SetMiscAtomOrString(aSerialized);
  MOZ_ASSERT(cont->mValue.mRefCount == 1);
}

void nsAttrValue::SetTo(nsIURI* aValue, const nsAString* aSerialized) {
  MiscContainer* cont = EnsureEmptyMiscContainer();
  NS_ADDREF(cont->mValue.mURL = aValue);
  cont->mType = eURL;
  SetMiscAtomOrString(aSerialized);
}

void nsAttrValue::SetToSerialized(const nsAttrValue& aOther) {
  if (aOther.Type() != nsAttrValue::eString &&
      aOther.Type() != nsAttrValue::eAtom) {
    nsAutoString val;
    aOther.ToString(val);
    SetTo(val);
  } else {
    SetTo(aOther);
  }
}

void nsAttrValue::SetTo(const SVGAnimatedOrient& aValue,
                        const nsAString* aSerialized) {
  SetSVGType(eSVGOrient, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGAnimatedIntegerPair& aValue,
                        const nsAString* aSerialized) {
  SetSVGType(eSVGIntegerPair, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGAnimatedLength& aValue,
                        const nsAString* aSerialized) {
  SetSVGType(eSVGLength, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGLengthList& aValue,
                        const nsAString* aSerialized) {
  // While an empty string will parse as a length list, there's no need to store
  // it (and SetMiscAtomOrString will assert if we try)
  if (aSerialized && aSerialized->IsEmpty()) {
    aSerialized = nullptr;
  }
  SetSVGType(eSVGLengthList, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGNumberList& aValue,
                        const nsAString* aSerialized) {
  // While an empty string will parse as a number list, there's no need to store
  // it (and SetMiscAtomOrString will assert if we try)
  if (aSerialized && aSerialized->IsEmpty()) {
    aSerialized = nullptr;
  }
  SetSVGType(eSVGNumberList, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGAnimatedNumberPair& aValue,
                        const nsAString* aSerialized) {
  SetSVGType(eSVGNumberPair, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGPathData& aValue,
                        const nsAString* aSerialized) {
  // While an empty string will parse as path data, there's no need to store it
  // (and SetMiscAtomOrString will assert if we try)
  if (aSerialized && aSerialized->IsEmpty()) {
    aSerialized = nullptr;
  }
  SetSVGType(eSVGPathData, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGPointList& aValue,
                        const nsAString* aSerialized) {
  // While an empty string will parse as a point list, there's no need to store
  // it (and SetMiscAtomOrString will assert if we try)
  if (aSerialized && aSerialized->IsEmpty()) {
    aSerialized = nullptr;
  }
  SetSVGType(eSVGPointList, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGAnimatedPreserveAspectRatio& aValue,
                        const nsAString* aSerialized) {
  SetSVGType(eSVGPreserveAspectRatio, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGStringList& aValue,
                        const nsAString* aSerialized) {
  // While an empty string will parse as a string list, there's no need to store
  // it (and SetMiscAtomOrString will assert if we try)
  if (aSerialized && aSerialized->IsEmpty()) {
    aSerialized = nullptr;
  }
  SetSVGType(eSVGStringList, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGTransformList& aValue,
                        const nsAString* aSerialized) {
  // While an empty string will parse as a transform list, there's no need to
  // store it (and SetMiscAtomOrString will assert if we try)
  if (aSerialized && aSerialized->IsEmpty()) {
    aSerialized = nullptr;
  }
  SetSVGType(eSVGTransformList, &aValue, aSerialized);
}

void nsAttrValue::SetTo(const SVGAnimatedViewBox& aValue,
                        const nsAString* aSerialized) {
  SetSVGType(eSVGViewBox, &aValue, aSerialized);
}

void nsAttrValue::SwapValueWith(nsAttrValue& aOther) {
  uintptr_t tmp = aOther.mBits;
  aOther.mBits = mBits;
  mBits = tmp;
}

void nsAttrValue::ToString(nsAString& aResult) const {
  MiscContainer* cont = nullptr;
  if (BaseType() == eOtherBase) {
    cont = GetMiscContainer();

    if (cont->GetString(aResult)) {
      return;
    }
  }

  switch (Type()) {
    case eString: {
      nsStringBuffer* str = static_cast<nsStringBuffer*>(GetPtr());
      if (str) {
        str->ToString(str->StorageSize() / sizeof(char16_t) - 1, aResult);
      } else {
        aResult.Truncate();
      }
      break;
    }
    case eAtom: {
      nsAtom* atom = static_cast<nsAtom*>(GetPtr());
      atom->ToString(aResult);

      break;
    }
    case eInteger: {
      nsAutoString intStr;
      intStr.AppendInt(GetIntegerValue());
      aResult = intStr;

      break;
    }
#ifdef DEBUG
    case eColor: {
      MOZ_ASSERT_UNREACHABLE("color attribute without string data");
      aResult.Truncate();
      break;
    }
#endif
    case eEnum: {
      GetEnumString(aResult, false);
      break;
    }
    case ePercent: {
      nsAutoString str;
      if (cont) {
        str.AppendFloat(cont->mDoubleValue);
      } else {
        str.AppendInt(GetIntInternal());
      }
      aResult = str + u"%"_ns;

      break;
    }
    case eCSSDeclaration: {
      aResult.Truncate();
      MiscContainer* container = GetMiscContainer();
      if (DeclarationBlock* decl = container->mValue.mCSSDeclaration) {
        nsAutoCString result;
        decl->ToString(result);
        CopyUTF8toUTF16(result, aResult);
      }

      // This can be reached during parallel selector matching with attribute
      // selectors on the style attribute. SetMiscAtomOrString handles this
      // case, and as of this writing this is the only consumer that needs it.
      const_cast<nsAttrValue*>(this)->SetMiscAtomOrString(&aResult);

      break;
    }
    case eDoubleValue: {
      aResult.Truncate();
      aResult.AppendFloat(GetDoubleValue());
      break;
    }
    case eSVGIntegerPair: {
      SVGAttrValueWrapper::ToString(
          GetMiscContainer()->mValue.mSVGAnimatedIntegerPair, aResult);
      break;
    }
    case eSVGOrient: {
      SVGAttrValueWrapper::ToString(
          GetMiscContainer()->mValue.mSVGAnimatedOrient, aResult);
      break;
    }
    case eSVGLength: {
      SVGAttrValueWrapper::ToString(GetMiscContainer()->mValue.mSVGLength,
                                    aResult);
      break;
    }
    case eSVGLengthList: {
      SVGAttrValueWrapper::ToString(GetMiscContainer()->mValue.mSVGLengthList,
                                    aResult);
      break;
    }
    case eSVGNumberList: {
      SVGAttrValueWrapper::ToString(GetMiscContainer()->mValue.mSVGNumberList,
                                    aResult);
      break;
    }
    case eSVGNumberPair: {
      SVGAttrValueWrapper::ToString(
          GetMiscContainer()->mValue.mSVGAnimatedNumberPair, aResult);
      break;
    }
    case eSVGPathData: {
      SVGAttrValueWrapper::ToString(GetMiscContainer()->mValue.mSVGPathData,
                                    aResult);
      break;
    }
    case eSVGPointList: {
      SVGAttrValueWrapper::ToString(GetMiscContainer()->mValue.mSVGPointList,
                                    aResult);
      break;
    }
    case eSVGPreserveAspectRatio: {
      SVGAttrValueWrapper::ToString(
          GetMiscContainer()->mValue.mSVGAnimatedPreserveAspectRatio, aResult);
      break;
    }
    case eSVGStringList: {
      SVGAttrValueWrapper::ToString(GetMiscContainer()->mValue.mSVGStringList,
                                    aResult);
      break;
    }
    case eSVGTransformList: {
      SVGAttrValueWrapper::ToString(
          GetMiscContainer()->mValue.mSVGTransformList, aResult);
      break;
    }
    case eSVGViewBox: {
      SVGAttrValueWrapper::ToString(
          GetMiscContainer()->mValue.mSVGAnimatedViewBox, aResult);
      break;
    }
    default: {
      aResult.Truncate();
      break;
    }
  }
}

already_AddRefed<nsAtom> nsAttrValue::GetAsAtom() const {
  switch (Type()) {
    case eString:
      return NS_AtomizeMainThread(GetStringValue());

    case eAtom: {
      RefPtr<nsAtom> atom = GetAtomValue();
      return atom.forget();
    }

    default: {
      nsAutoString val;
      ToString(val);
      return NS_AtomizeMainThread(val);
    }
  }
}

const nsCheapString nsAttrValue::GetStringValue() const {
  MOZ_ASSERT(Type() == eString, "wrong type");

  return nsCheapString(static_cast<nsStringBuffer*>(GetPtr()));
}

bool nsAttrValue::GetColorValue(nscolor& aColor) const {
  if (Type() != eColor) {
    // Unparseable value, treat as unset.
    NS_ASSERTION(Type() == eString, "unexpected type for color-valued attr");
    return false;
  }

  aColor = GetMiscContainer()->mValue.mColor;
  return true;
}

void nsAttrValue::GetEnumString(nsAString& aResult, bool aRealTag) const {
  MOZ_ASSERT(Type() == eEnum, "wrong type");

  uint32_t allEnumBits = (BaseType() == eIntegerBase)
                             ? static_cast<uint32_t>(GetIntInternal())
                             : GetMiscContainer()->mValue.mEnumValue;
  int16_t val = allEnumBits >> NS_ATTRVALUE_ENUMTABLEINDEX_BITS;
  const EnumTable* table = sEnumTableArray->ElementAt(
      allEnumBits & NS_ATTRVALUE_ENUMTABLEINDEX_MASK);

  while (table->tag) {
    if (table->value == val) {
      aResult.AssignASCII(table->tag);
      if (!aRealTag &&
          allEnumBits & NS_ATTRVALUE_ENUMTABLE_VALUE_NEEDS_TO_UPPER) {
        nsContentUtils::ASCIIToUpper(aResult);
      }
      return;
    }
    table++;
  }

  MOZ_ASSERT_UNREACHABLE("couldn't find value in EnumTable");
}

void AttrAtomArray::DoRemoveDuplicates() {
  MOZ_ASSERT(mMayContainDuplicates);

  bool usingHashTable = false;
  BitBloomFilter<8, nsAtom> filter;
  nsTHashSet<nsPtrHashKey<nsAtom>> hash;

  auto CheckDuplicate = [&](size_t i) {
    nsAtom* atom = mArray[i];
    if (!usingHashTable) {
      if (!filter.mightContain(atom)) {
        filter.add(atom);
        return false;
      }
      for (size_t j = 0; j < i; ++j) {
        hash.Insert(mArray[j]);
      }
      usingHashTable = true;
    }
    return !hash.EnsureInserted(atom);
  };

  size_t len = mArray.Length();
  for (size_t i = 0; i < len; ++i) {
    if (!CheckDuplicate(i)) {
      continue;
    }
    mArray.RemoveElementAt(i);
    --i;
    --len;
  }

  mMayContainDuplicates = false;
}

uint32_t nsAttrValue::GetAtomCount() const {
  ValueType type = Type();

  if (type == eAtom) {
    return 1;
  }

  if (type == eAtomArray) {
    return GetAtomArrayValue()->mArray.Length();
  }

  return 0;
}

nsAtom* nsAttrValue::AtomAt(int32_t aIndex) const {
  MOZ_ASSERT(aIndex >= 0, "Index must not be negative");
  MOZ_ASSERT(GetAtomCount() > uint32_t(aIndex), "aIndex out of range");

  if (BaseType() == eAtomBase) {
    return GetAtomValue();
  }

  NS_ASSERTION(Type() == eAtomArray, "GetAtomCount must be confused");
  return GetAtomArrayValue()->mArray.ElementAt(aIndex);
}

uint32_t nsAttrValue::HashValue() const {
  switch (BaseType()) {
    case eStringBase: {
      nsStringBuffer* str = static_cast<nsStringBuffer*>(GetPtr());
      if (str) {
        uint32_t len = str->StorageSize() / sizeof(char16_t) - 1;
        return HashString(static_cast<char16_t*>(str->Data()), len);
      }

      return 0;
    }
    case eOtherBase: {
      break;
    }
    case eAtomBase:
    case eIntegerBase: {
      // mBits and uint32_t might have different size. This should silence
      // any warnings or compile-errors. This is what the implementation of
      // NS_PTR_TO_INT32 does to take care of the same problem.
      return mBits - 0;
    }
  }

  MiscContainer* cont = GetMiscContainer();
  if (static_cast<ValueBaseType>(cont->mStringBits &
                                 NS_ATTRVALUE_BASETYPE_MASK) == eAtomBase) {
    return cont->mStringBits - 0;
  }

  switch (cont->mType) {
    case eInteger: {
      return cont->mValue.mInteger;
    }
    case eEnum: {
      return cont->mValue.mEnumValue;
    }
    case ePercent: {
      return cont->mDoubleValue;
    }
    case eColor: {
      return cont->mValue.mColor;
    }
    case eCSSDeclaration: {
      return NS_PTR_TO_INT32(cont->mValue.mCSSDeclaration);
    }
    case eURL: {
      nsString str;
      ToString(str);
      return HashString(str);
    }
    case eAtomArray: {
      uint32_t hash = 0;
      for (const auto& atom : cont->mValue.mAtomArray->mArray) {
        hash = AddToHash(hash, atom.get());
      }
      return hash;
    }
    case eDoubleValue: {
      // XXX this is crappy, but oh well
      return cont->mDoubleValue;
    }
    default: {
      if (IsSVGType(cont->mType)) {
        // All SVG types are just pointers to classes so we can treat them alike
        return NS_PTR_TO_INT32(cont->mValue.mSVGLength);
      }
      MOZ_ASSERT_UNREACHABLE("unknown type stored in MiscContainer");
      return 0;
    }
  }
}

bool nsAttrValue::Equals(const nsAttrValue& aOther) const {
  if (BaseType() != aOther.BaseType()) {
    return false;
  }

  switch (BaseType()) {
    case eStringBase: {
      return GetStringValue().Equals(aOther.GetStringValue());
    }
    case eOtherBase: {
      break;
    }
    case eAtomBase:
    case eIntegerBase: {
      return mBits == aOther.mBits;
    }
  }

  MiscContainer* thisCont = GetMiscContainer();
  MiscContainer* otherCont = aOther.GetMiscContainer();
  if (thisCont == otherCont) {
    return true;
  }

  if (thisCont->mType != otherCont->mType) {
    return false;
  }

  bool needsStringComparison = false;

  switch (thisCont->mType) {
    case eInteger: {
      if (thisCont->mValue.mInteger == otherCont->mValue.mInteger) {
        needsStringComparison = true;
      }
      break;
    }
    case eEnum: {
      if (thisCont->mValue.mEnumValue == otherCont->mValue.mEnumValue) {
        needsStringComparison = true;
      }
      break;
    }
    case ePercent: {
      if (thisCont->mDoubleValue == otherCont->mDoubleValue) {
        needsStringComparison = true;
      }
      break;
    }
    case eColor: {
      if (thisCont->mValue.mColor == otherCont->mValue.mColor) {
        needsStringComparison = true;
      }
      break;
    }
    case eCSSDeclaration: {
      return thisCont->mValue.mCSSDeclaration ==
             otherCont->mValue.mCSSDeclaration;
    }
    case eURL: {
      return thisCont->mValue.mURL == otherCont->mValue.mURL;
    }
    case eAtomArray: {
      // For classlists we could be insensitive to order, however
      // classlists are never mapped attributes so they are never compared.

      if (!(*thisCont->mValue.mAtomArray == *otherCont->mValue.mAtomArray)) {
        return false;
      }

      needsStringComparison = true;
      break;
    }
    case eDoubleValue: {
      return thisCont->mDoubleValue == otherCont->mDoubleValue;
    }
    default: {
      if (IsSVGType(thisCont->mType)) {
        // Currently this method is never called for nsAttrValue objects that
        // point to SVG data types.
        // If that changes then we probably want to add methods to the
        // corresponding SVG types to compare their base values.
        // As a shortcut, however, we can begin by comparing the pointers.
        MOZ_ASSERT(false, "Comparing nsAttrValues that point to SVG data");
        return false;
      }
      MOZ_ASSERT_UNREACHABLE("unknown type stored in MiscContainer");
      return false;
    }
  }
  if (needsStringComparison) {
    if (thisCont->mStringBits == otherCont->mStringBits) {
      return true;
    }
    if ((static_cast<ValueBaseType>(thisCont->mStringBits &
                                    NS_ATTRVALUE_BASETYPE_MASK) ==
         eStringBase) &&
        (static_cast<ValueBaseType>(otherCont->mStringBits &
                                    NS_ATTRVALUE_BASETYPE_MASK) ==
         eStringBase)) {
      return nsCheapString(reinterpret_cast<nsStringBuffer*>(
                               static_cast<uintptr_t>(thisCont->mStringBits)))
          .Equals(nsCheapString(reinterpret_cast<nsStringBuffer*>(
              static_cast<uintptr_t>(otherCont->mStringBits))));
    }
  }
  return false;
}

bool nsAttrValue::Equals(const nsAString& aValue,
                         nsCaseTreatment aCaseSensitive) const {
  switch (BaseType()) {
    case eStringBase: {
      if (auto* str = static_cast<nsStringBuffer*>(GetPtr())) {
        nsDependentString dep(static_cast<char16_t*>(str->Data()),
                              str->StorageSize() / sizeof(char16_t) - 1);
        return aCaseSensitive == eCaseMatters
                   ? aValue.Equals(dep)
                   : nsContentUtils::EqualsIgnoreASCIICase(aValue, dep);
      }
      return aValue.IsEmpty();
    }
    case eAtomBase: {
      auto* atom = static_cast<nsAtom*>(GetPtr());
      if (aCaseSensitive == eCaseMatters) {
        return atom->Equals(aValue);
      }
      return nsContentUtils::EqualsIgnoreASCIICase(nsDependentAtomString(atom),
                                                   aValue);
    }
    default:
      break;
  }

  nsAutoString val;
  ToString(val);
  return aCaseSensitive == eCaseMatters
             ? val.Equals(aValue)
             : nsContentUtils::EqualsIgnoreASCIICase(val, aValue);
}

bool nsAttrValue::Equals(const nsAtom* aValue,
                         nsCaseTreatment aCaseSensitive) const {
  if (auto* atom = GetStoredAtom()) {
    if (atom == aValue) {
      return true;
    }
    if (aCaseSensitive == eCaseMatters) {
      return false;
    }
    if (atom->IsAsciiLowercase() && aValue->IsAsciiLowercase()) {
      return false;
    }
  }
  return Equals(nsDependentAtomString(aValue), aCaseSensitive);
}

struct HasPrefixFn {
  static bool Check(const char16_t* aAttrValue, size_t aAttrLen,
                    const nsAString& aSearchValue,
                    nsCaseTreatment aCaseSensitive) {
    if (aCaseSensitive == eCaseMatters) {
      if (aSearchValue.Length() > aAttrLen) {
        return false;
      }
      return !memcmp(aAttrValue, aSearchValue.BeginReading(),
                     aSearchValue.Length() * sizeof(char16_t));
    }
    return StringBeginsWith(nsDependentString(aAttrValue, aAttrLen),
                            aSearchValue,
                            nsASCIICaseInsensitiveStringComparator);
  }
};

struct HasSuffixFn {
  static bool Check(const char16_t* aAttrValue, size_t aAttrLen,
                    const nsAString& aSearchValue,
                    nsCaseTreatment aCaseSensitive) {
    if (aCaseSensitive == eCaseMatters) {
      if (aSearchValue.Length() > aAttrLen) {
        return false;
      }
      return !memcmp(aAttrValue + aAttrLen - aSearchValue.Length(),
                     aSearchValue.BeginReading(),
                     aSearchValue.Length() * sizeof(char16_t));
    }
    return StringEndsWith(nsDependentString(aAttrValue, aAttrLen), aSearchValue,
                          nsASCIICaseInsensitiveStringComparator);
  }
};

struct HasSubstringFn {
  static bool Check(const char16_t* aAttrValue, size_t aAttrLen,
                    const nsAString& aSearchValue,
                    nsCaseTreatment aCaseSensitive) {
    if (aCaseSensitive == eCaseMatters) {
      if (aSearchValue.IsEmpty()) {
        return true;
      }
      const char16_t* end = aAttrValue + aAttrLen;
      return std::search(aAttrValue, end, aSearchValue.BeginReading(),
                         aSearchValue.EndReading()) != end;
    }
    return FindInReadable(aSearchValue, nsDependentString(aAttrValue, aAttrLen),
                          nsASCIICaseInsensitiveStringComparator);
  }
};

template <typename F>
bool nsAttrValue::SubstringCheck(const nsAString& aValue,
                                 nsCaseTreatment aCaseSensitive) const {
  switch (BaseType()) {
    case eStringBase: {
      auto str = static_cast<nsStringBuffer*>(GetPtr());
      if (str) {
        return F::Check(static_cast<char16_t*>(str->Data()),
                        str->StorageSize() / sizeof(char16_t) - 1, aValue,
                        aCaseSensitive);
      }
      return aValue.IsEmpty();
    }
    case eAtomBase: {
      auto atom = static_cast<nsAtom*>(GetPtr());
      return F::Check(atom->GetUTF16String(), atom->GetLength(), aValue,
                      aCaseSensitive);
    }
    default:
      break;
  }

  nsAutoString val;
  ToString(val);
  return F::Check(val.BeginReading(), val.Length(), aValue, aCaseSensitive);
}

bool nsAttrValue::HasPrefix(const nsAString& aValue,
                            nsCaseTreatment aCaseSensitive) const {
  return SubstringCheck<HasPrefixFn>(aValue, aCaseSensitive);
}

bool nsAttrValue::HasSuffix(const nsAString& aValue,
                            nsCaseTreatment aCaseSensitive) const {
  return SubstringCheck<HasSuffixFn>(aValue, aCaseSensitive);
}

bool nsAttrValue::HasSubstring(const nsAString& aValue,
                               nsCaseTreatment aCaseSensitive) const {
  return SubstringCheck<HasSubstringFn>(aValue, aCaseSensitive);
}

bool nsAttrValue::EqualsAsStrings(const nsAttrValue& aOther) const {
  if (Type() == aOther.Type()) {
    return Equals(aOther);
  }

  // We need to serialize at least one nsAttrValue before passing to
  // Equals(const nsAString&), but we can avoid unnecessarily serializing both
  // by checking if one is already of a string type.
  bool thisIsString = (BaseType() == eStringBase || BaseType() == eAtomBase);
  const nsAttrValue& lhs = thisIsString ? *this : aOther;
  const nsAttrValue& rhs = thisIsString ? aOther : *this;

  switch (rhs.BaseType()) {
    case eAtomBase:
      return lhs.Equals(rhs.GetAtomValue(), eCaseMatters);

    case eStringBase:
      return lhs.Equals(rhs.GetStringValue(), eCaseMatters);

    default: {
      nsAutoString val;
      rhs.ToString(val);
      return lhs.Equals(val, eCaseMatters);
    }
  }
}

bool nsAttrValue::Contains(nsAtom* aValue,
                           nsCaseTreatment aCaseSensitive) const {
  switch (BaseType()) {
    case eAtomBase: {
      nsAtom* atom = GetAtomValue();
      if (aCaseSensitive == eCaseMatters) {
        return aValue == atom;
      }

      // For performance reasons, don't do a full on unicode case insensitive
      // string comparison. This is only used for quirks mode anyway.
      return nsContentUtils::EqualsIgnoreASCIICase(aValue, atom);
    }
    default: {
      if (Type() == eAtomArray) {
        AttrAtomArray* array = GetAtomArrayValue();
        if (aCaseSensitive == eCaseMatters) {
          return array->mArray.Contains(aValue);
        }

        for (RefPtr<nsAtom>& cur : array->mArray) {
          // For performance reasons, don't do a full on unicode case
          // insensitive string comparison. This is only used for quirks mode
          // anyway.
          if (nsContentUtils::EqualsIgnoreASCIICase(aValue, cur)) {
            return true;
          }
        }
      }
    }
  }

  return false;
}

struct AtomArrayStringComparator {
  bool Equals(nsAtom* atom, const nsAString& string) const {
    return atom->Equals(string);
  }
};

bool nsAttrValue::Contains(const nsAString& aValue) const {
  switch (BaseType()) {
    case eAtomBase: {
      nsAtom* atom = GetAtomValue();
      return atom->Equals(aValue);
    }
    default: {
      if (Type() == eAtomArray) {
        AttrAtomArray* array = GetAtomArrayValue();
        return array->mArray.Contains(aValue, AtomArrayStringComparator());
      }
    }
  }

  return false;
}

void nsAttrValue::ParseAtom(const nsAString& aValue) {
  ResetIfSet();

  RefPtr<nsAtom> atom = NS_Atomize(aValue);
  if (atom) {
    SetPtrValueAndType(atom.forget().take(), eAtomBase);
  }
}

void nsAttrValue::ParseAtomArray(const nsAString& aValue) {
  nsAString::const_iterator iter, end;
  aValue.BeginReading(iter);
  aValue.EndReading(end);
  bool hasSpace = false;

  // skip initial whitespace
  while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
    hasSpace = true;
    ++iter;
  }

  if (iter == end) {
    SetTo(aValue);
    return;
  }

  nsAString::const_iterator start(iter);

  // get first - and often only - atom
  do {
    ++iter;
  } while (iter != end && !nsContentUtils::IsHTMLWhitespace(*iter));

  RefPtr<nsAtom> classAtom = NS_AtomizeMainThread(Substring(start, iter));
  if (!classAtom) {
    Reset();
    return;
  }

  // skip whitespace
  while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
    hasSpace = true;
    ++iter;
  }

  if (iter == end && !hasSpace) {
    // we only found one classname and there was no whitespace so
    // don't bother storing a list
    ResetIfSet();
    nsAtom* atom = nullptr;
    classAtom.swap(atom);
    SetPtrValueAndType(atom, eAtomBase);
    return;
  }

  if (!EnsureEmptyAtomArray()) {
    return;
  }

  AttrAtomArray* array = GetAtomArrayValue();

  // XXX(Bug 1631371) Check if this should use a fallible operation as it
  // pretended earlier.
  array->mArray.AppendElement(std::move(classAtom));

  // parse the rest of the classnames
  while (iter != end) {
    start = iter;

    do {
      ++iter;
    } while (iter != end && !nsContentUtils::IsHTMLWhitespace(*iter));

    classAtom = NS_AtomizeMainThread(Substring(start, iter));

    // XXX(Bug 1631371) Check if this should use a fallible operation as it
    // pretended earlier.
    array->mArray.AppendElement(std::move(classAtom));
    array->mMayContainDuplicates = true;

    // skip whitespace
    while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
      ++iter;
    }
  }

  SetMiscAtomOrString(&aValue);
}

void nsAttrValue::ParseStringOrAtom(const nsAString& aValue) {
  uint32_t len = aValue.Length();
  // Don't bother with atoms if it's an empty string since
  // we can store those efficiently anyway.
  if (len && len <= NS_ATTRVALUE_MAX_STRINGLENGTH_ATOM) {
    ParseAtom(aValue);
  } else {
    SetTo(aValue);
  }
}

void nsAttrValue::ParsePartMapping(const nsAString& aValue) {
  ResetIfSet();
  MiscContainer* cont = EnsureEmptyMiscContainer();

  cont->mType = eShadowParts;
  cont->mValue.mShadowParts = new ShadowParts(ShadowParts::Parse(aValue));
  NS_ADDREF(cont);
  SetMiscAtomOrString(&aValue);
  MOZ_ASSERT(cont->mValue.mRefCount == 1);
}

void nsAttrValue::SetIntValueAndType(int32_t aValue, ValueType aType,
                                     const nsAString* aStringValue) {
  if (aStringValue || aValue > NS_ATTRVALUE_INTEGERTYPE_MAXVALUE ||
      aValue < NS_ATTRVALUE_INTEGERTYPE_MINVALUE) {
    MiscContainer* cont = EnsureEmptyMiscContainer();
    switch (aType) {
      case eInteger: {
        cont->mValue.mInteger = aValue;
        break;
      }
      case ePercent: {
        cont->mDoubleValue = aValue;
        break;
      }
      case eEnum: {
        cont->mValue.mEnumValue = aValue;
        break;
      }
      default: {
        MOZ_ASSERT_UNREACHABLE("unknown integer type");
        break;
      }
    }
    cont->mType = aType;
    SetMiscAtomOrString(aStringValue);
  } else {
    NS_ASSERTION(!mBits, "Reset before calling SetIntValueAndType!");
    mBits = (aValue * NS_ATTRVALUE_INTEGERTYPE_MULTIPLIER) | aType;
  }
}

void nsAttrValue::SetDoubleValueAndType(double aValue, ValueType aType,
                                        const nsAString* aStringValue) {
  MOZ_ASSERT(aType == eDoubleValue || aType == ePercent, "Unexpected type");
  MiscContainer* cont = EnsureEmptyMiscContainer();
  cont->mDoubleValue = aValue;
  cont->mType = aType;
  SetMiscAtomOrString(aStringValue);
}

nsAtom* nsAttrValue::GetStoredAtom() const {
  if (BaseType() == eAtomBase) {
    return static_cast<nsAtom*>(GetPtr());
  }
  if (BaseType() == eOtherBase) {
    return GetMiscContainer()->GetStoredAtom();
  }
  return nullptr;
}

nsStringBuffer* nsAttrValue::GetStoredStringBuffer() const {
  if (BaseType() == eStringBase) {
    return static_cast<nsStringBuffer*>(GetPtr());
  }
  if (BaseType() == eOtherBase) {
    return GetMiscContainer()->GetStoredStringBuffer();
  }
  return nullptr;
}

int16_t nsAttrValue::GetEnumTableIndex(const EnumTable* aTable) {
  int16_t index = sEnumTableArray->IndexOf(aTable);
  if (index < 0) {
    index = sEnumTableArray->Length();
    NS_ASSERTION(index <= NS_ATTRVALUE_ENUMTABLEINDEX_MAXVALUE,
                 "too many enum tables");
    sEnumTableArray->AppendElement(aTable);
  }

  return index;
}

int32_t nsAttrValue::EnumTableEntryToValue(const EnumTable* aEnumTable,
                                           const EnumTable* aTableEntry) {
  int16_t index = GetEnumTableIndex(aEnumTable);
  int32_t value =
      (aTableEntry->value << NS_ATTRVALUE_ENUMTABLEINDEX_BITS) + index;
  return value;
}

bool nsAttrValue::ParseEnumValue(const nsAString& aValue,
                                 const EnumTable* aTable, bool aCaseSensitive,
                                 const EnumTable* aDefaultValue) {
  ResetIfSet();
  const EnumTable* tableEntry = aTable;

  while (tableEntry->tag) {
    if (aCaseSensitive ? aValue.EqualsASCII(tableEntry->tag)
                       : aValue.LowerCaseEqualsASCII(tableEntry->tag)) {
      int32_t value = EnumTableEntryToValue(aTable, tableEntry);

      bool equals = aCaseSensitive || aValue.EqualsASCII(tableEntry->tag);
      if (!equals) {
        nsAutoString tag;
        tag.AssignASCII(tableEntry->tag);
        nsContentUtils::ASCIIToUpper(tag);
        if ((equals = tag.Equals(aValue))) {
          value |= NS_ATTRVALUE_ENUMTABLE_VALUE_NEEDS_TO_UPPER;
        }
      }
      SetIntValueAndType(value, eEnum, equals ? nullptr : &aValue);
      NS_ASSERTION(GetEnumValue() == tableEntry->value,
                   "failed to store enum properly");

      return true;
    }
    tableEntry++;
  }

  if (aDefaultValue) {
    MOZ_ASSERT(aTable <= aDefaultValue && aDefaultValue < tableEntry,
               "aDefaultValue not inside aTable?");
    SetIntValueAndType(EnumTableEntryToValue(aTable, aDefaultValue), eEnum,
                       &aValue);
    return true;
  }

  return false;
}

bool nsAttrValue::DoParseHTMLDimension(const nsAString& aInput,
                                       bool aEnsureNonzero) {
  ResetIfSet();

  // We don't use nsContentUtils::ParseHTMLInteger here because we
  // need a bunch of behavioral differences from it.  We _could_ try to
  // use it, but it would not be a great fit.

  // https://html.spec.whatwg.org/multipage/#rules-for-parsing-dimension-values

  // Steps 1 and 2.
  const char16_t* position = aInput.BeginReading();
  const char16_t* end = aInput.EndReading();

  // We will need to keep track of whether this was a canonical representation
  // or not.  It's non-canonical if it has leading whitespace, leading '+',
  // leading '0' characters, or trailing garbage.
  bool canonical = true;

  // Step 3.
  while (position != end && nsContentUtils::IsHTMLWhitespace(*position)) {
    canonical = false;  // Leading whitespace
    ++position;
  }

  // Step 4.
  if (position == end || *position < char16_t('0') ||
      *position > char16_t('9')) {
    return false;
  }

  // Step 5.
  CheckedInt32 value = 0;

  // Collect up leading '0' first to avoid extra branching in the main
  // loop to set 'canonical' properly.
  while (position != end && *position == char16_t('0')) {
    canonical = false;  // Leading '0'
    ++position;
  }

  // Now collect up other digits.
  while (position != end && *position >= char16_t('0') &&
         *position <= char16_t('9')) {
    value = value * 10 + (*position - char16_t('0'));
    if (!value.isValid()) {
      // The spec assumes we can deal with arbitrary-size integers here, but we
      // really can't.  If someone sets something too big, just bail out and
      // ignore it.
      return false;
    }
    ++position;
  }

  // Step 6 is implemented implicitly via the various "position != end" guards
  // from this point on.

  Maybe<double> doubleValue;
  // Step 7.  The return in step 7.2 is handled by just falling through to the
  // code below this block when we reach end of input or a non-digit, because
  // the while loop will terminate at that point.
  if (position != end && *position == char16_t('.')) {
    canonical = false;  // Let's not rely on double serialization reproducing
                        // the string we started with.
    // Step 7.1.
    ++position;
    // If we have a '.' _not_ followed by digits, this is not as efficient as it
    // could be, because we will store as a double while we could have stored as
    // an int.  But that seems like a pretty rare case.
    doubleValue.emplace(value.value());
    // Step 7.3.
    double divisor = 1.0f;
    // Step 7.4.
    while (position != end && *position >= char16_t('0') &&
           *position <= char16_t('9')) {
      // Step 7.4.1.
      divisor = divisor * 10.0f;
      // Step 7.4.2.
      doubleValue.ref() += (*position - char16_t('0')) / divisor;
      // Step 7.4.3.
      ++position;
      // Step 7.4.4 and 7.4.5 are captured in the while loop condition and the
      // "position != end" checks below.
    }
  }

  if (aEnsureNonzero && value.value() == 0 &&
      (!doubleValue || *doubleValue == 0.0f)) {
    // Not valid.  Just drop it.
    return false;
  }

  // Step 8 and the spec's early return from step 7.2.
  ValueType type;
  if (position != end && *position == char16_t('%')) {
    type = ePercent;
    ++position;
  } else if (doubleValue) {
    type = eDoubleValue;
  } else {
    type = eInteger;
  }

  if (position != end) {
    canonical = false;
  }

  if (doubleValue) {
    MOZ_ASSERT(!canonical, "We set it false above!");
    SetDoubleValueAndType(*doubleValue, type, &aInput);
  } else {
    SetIntValueAndType(value.value(), type, canonical ? nullptr : &aInput);
  }

#ifdef DEBUG
  nsAutoString str;
  ToString(str);
  MOZ_ASSERT(str == aInput, "We messed up our 'canonical' boolean!");
#endif

  return true;
}

bool nsAttrValue::ParseIntWithBounds(const nsAString& aString, int32_t aMin,
                                     int32_t aMax) {
  MOZ_ASSERT(aMin < aMax, "bad boundaries");

  ResetIfSet();

  nsContentUtils::ParseHTMLIntegerResultFlags result;
  int32_t originalVal = nsContentUtils::ParseHTMLInteger(aString, &result);
  if (result & nsContentUtils::eParseHTMLInteger_Error) {
    return false;
  }

  int32_t val = std::max(originalVal, aMin);
  val = std::min(val, aMax);
  bool nonStrict =
      (val != originalVal) ||
      (result & nsContentUtils::eParseHTMLInteger_NonStandard) ||
      (result & nsContentUtils::eParseHTMLInteger_DidNotConsumeAllInput);

  SetIntValueAndType(val, eInteger, nonStrict ? &aString : nullptr);

  return true;
}

void nsAttrValue::ParseIntWithFallback(const nsAString& aString,
                                       int32_t aDefault, int32_t aMax) {
  ResetIfSet();

  nsContentUtils::ParseHTMLIntegerResultFlags result;
  int32_t val = nsContentUtils::ParseHTMLInteger(aString, &result);
  bool nonStrict = false;
  if ((result & nsContentUtils::eParseHTMLInteger_Error) || val < 1) {
    val = aDefault;
    nonStrict = true;
  }

  if (val > aMax) {
    val = aMax;
    nonStrict = true;
  }

  if ((result & nsContentUtils::eParseHTMLInteger_NonStandard) ||
      (result & nsContentUtils::eParseHTMLInteger_DidNotConsumeAllInput)) {
    nonStrict = true;
  }

  SetIntValueAndType(val, eInteger, nonStrict ? &aString : nullptr);
}

void nsAttrValue::ParseClampedNonNegativeInt(const nsAString& aString,
                                             int32_t aDefault, int32_t aMin,
                                             int32_t aMax) {
  ResetIfSet();

  nsContentUtils::ParseHTMLIntegerResultFlags result;
  int32_t val = nsContentUtils::ParseHTMLInteger(aString, &result);
  bool nonStrict =
      (result & nsContentUtils::eParseHTMLInteger_NonStandard) ||
      (result & nsContentUtils::eParseHTMLInteger_DidNotConsumeAllInput);

  if (result & nsContentUtils::eParseHTMLInteger_ErrorOverflow) {
    if (result & nsContentUtils::eParseHTMLInteger_Negative) {
      val = aDefault;
    } else {
      val = aMax;
    }
    nonStrict = true;
  } else if ((result & nsContentUtils::eParseHTMLInteger_Error) || val < 0) {
    val = aDefault;
    nonStrict = true;
  } else if (val < aMin) {
    val = aMin;
    nonStrict = true;
  } else if (val > aMax) {
    val = aMax;
    nonStrict = true;
  }

  SetIntValueAndType(val, eInteger, nonStrict ? &aString : nullptr);
}

bool nsAttrValue::ParseNonNegativeIntValue(const nsAString& aString) {
  ResetIfSet();

  nsContentUtils::ParseHTMLIntegerResultFlags result;
  int32_t originalVal = nsContentUtils::ParseHTMLInteger(aString, &result);
  if ((result & nsContentUtils::eParseHTMLInteger_Error) || originalVal < 0) {
    return false;
  }

  bool nonStrict =
      (result & nsContentUtils::eParseHTMLInteger_NonStandard) ||
      (result & nsContentUtils::eParseHTMLInteger_DidNotConsumeAllInput);

  SetIntValueAndType(originalVal, eInteger, nonStrict ? &aString : nullptr);

  return true;
}

bool nsAttrValue::ParsePositiveIntValue(const nsAString& aString) {
  ResetIfSet();

  nsContentUtils::ParseHTMLIntegerResultFlags result;
  int32_t originalVal = nsContentUtils::ParseHTMLInteger(aString, &result);
  if ((result & nsContentUtils::eParseHTMLInteger_Error) || originalVal <= 0) {
    return false;
  }

  bool nonStrict =
      (result & nsContentUtils::eParseHTMLInteger_NonStandard) ||
      (result & nsContentUtils::eParseHTMLInteger_DidNotConsumeAllInput);

  SetIntValueAndType(originalVal, eInteger, nonStrict ? &aString : nullptr);

  return true;
}

void nsAttrValue::SetColorValue(nscolor aColor, const nsAString& aString) {
  nsStringBuffer* buf = GetStringBuffer(aString).take();
  if (!buf) {
    return;
  }

  MiscContainer* cont = EnsureEmptyMiscContainer();
  cont->mValue.mColor = aColor;
  cont->mType = eColor;

  // Save the literal string we were passed for round-tripping.
  cont->SetStringBitsMainThread(reinterpret_cast<uintptr_t>(buf) | eStringBase);
}

bool nsAttrValue::ParseColor(const nsAString& aString) {
  ResetIfSet();

  // FIXME (partially, at least): HTML5's algorithm says we shouldn't do
  // the whitespace compression, trimming, or the test for emptiness.
  // (I'm a little skeptical that we shouldn't do the whitespace
  // trimming; WebKit also does it.)
  nsAutoString colorStr(aString);
  colorStr.CompressWhitespace(true, true);
  if (colorStr.IsEmpty()) {
    return false;
  }

  nscolor color;
  // No color names begin with a '#'; in standards mode, all acceptable
  // numeric colors do.
  if (colorStr.First() == '#') {
    nsDependentString withoutHash(colorStr.get() + 1, colorStr.Length() - 1);
    if (NS_HexToRGBA(withoutHash, nsHexColorType::NoAlpha, &color)) {
      SetColorValue(color, aString);
      return true;
    }
  } else {
    if (NS_ColorNameToRGB(colorStr, &color)) {
      SetColorValue(color, aString);
      return true;
    }
  }

  // FIXME (maybe): HTML5 says we should handle system colors.  This
  // means we probably need another storage type, since we'd need to
  // handle dynamic changes.  However, I think this is a bad idea:
  // http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2010-May/026449.html

  // Use NS_LooseHexToRGB as a fallback if nothing above worked.
  if (NS_LooseHexToRGB(colorStr, &color)) {
    SetColorValue(color, aString);
    return true;
  }

  return false;
}

bool nsAttrValue::ParseDoubleValue(const nsAString& aString) {
  ResetIfSet();

  nsresult ec;
  double val = PromiseFlatString(aString).ToDouble(&ec);
  if (NS_FAILED(ec)) {
    return false;
  }

  MiscContainer* cont = EnsureEmptyMiscContainer();
  cont->mDoubleValue = val;
  cont->mType = eDoubleValue;
  nsAutoString serializedFloat;
  serializedFloat.AppendFloat(val);
  SetMiscAtomOrString(serializedFloat.Equals(aString) ? nullptr : &aString);
  return true;
}

bool nsAttrValue::ParseStyleAttribute(const nsAString& aString,
                                      nsIPrincipal* aMaybeScriptedPrincipal,
                                      nsStyledElement* aElement) {
  dom::Document* doc = aElement->OwnerDoc();
  nsHTMLCSSStyleSheet* sheet = doc->GetInlineStyleSheet();
  NS_ASSERTION(aElement->NodePrincipal() == doc->NodePrincipal(),
               "This is unexpected");

  nsIPrincipal* principal = aMaybeScriptedPrincipal ? aMaybeScriptedPrincipal
                                                    : aElement->NodePrincipal();
  RefPtr<URLExtraData> data = aElement->GetURLDataForStyleAttr(principal);

  // If the (immutable) document URI does not match the element's base URI
  // (the common case is that they do match) do not cache the rule.  This is
  // because the results of the CSS parser are dependent on these URIs, and we
  // do not want to have to account for the URIs in the hash lookup.
  // Similarly, if the triggering principal does not match the node principal,
  // do not cache the rule, since the principal will be encoded in any parsed
  // URLs in the rule.
  const bool cachingAllowed = sheet &&
                              doc->GetDocumentURI() == data->BaseURI() &&
                              principal == aElement->NodePrincipal();
  if (cachingAllowed) {
    MiscContainer* cont = sheet->LookupStyleAttr(aString);
    if (cont) {
      // Set our MiscContainer to the cached one.
      NS_ADDREF(cont);
      SetPtrValueAndType(cont, eOtherBase);
      return true;
    }
  }

  RefPtr<DeclarationBlock> decl =
      DeclarationBlock::FromCssText(aString, data, doc->GetCompatibilityMode(),
                                    doc->CSSLoader(), StyleCssRuleType::Style);
  if (!decl) {
    return false;
  }
  decl->SetHTMLCSSStyleSheet(sheet);
  SetTo(decl.forget(), &aString);

  if (cachingAllowed) {
    MiscContainer* cont = GetMiscContainer();
    cont->Cache();
  }

  return true;
}

void nsAttrValue::SetMiscAtomOrString(const nsAString* aValue) {
  NS_ASSERTION(GetMiscContainer(), "Must have MiscContainer!");
  NS_ASSERTION(!GetMiscContainer()->mStringBits || IsInServoTraversal(),
               "Trying to re-set atom or string!");
  if (aValue) {
    uint32_t len = aValue->Length();
    // * We're allowing eCSSDeclaration attributes to store empty
    //   strings as it can be beneficial to store an empty style
    //   attribute as a parsed rule.
    // * We're allowing enumerated values because sometimes the empty
    //   string corresponds to a particular enumerated value, especially
    //   for enumerated values that are not limited enumerated.
    // Add other types as needed.
    NS_ASSERTION(len || Type() == eCSSDeclaration || Type() == eEnum,
                 "Empty string?");
    MiscContainer* cont = GetMiscContainer();

    if (len <= NS_ATTRVALUE_MAX_STRINGLENGTH_ATOM) {
      nsAtom* atom = MOZ_LIKELY(!IsInServoTraversal())
                         ? NS_AtomizeMainThread(*aValue).take()
                         : NS_Atomize(*aValue).take();
      NS_ENSURE_TRUE_VOID(atom);
      uintptr_t bits = reinterpret_cast<uintptr_t>(atom) | eAtomBase;

      // In the common case we're not in the servo traversal, and we can just
      // set the bits normally. The parallel case requires more care.
      if (MOZ_LIKELY(!IsInServoTraversal())) {
        cont->SetStringBitsMainThread(bits);
      } else if (!cont->mStringBits.compareExchange(0, bits)) {
        // We raced with somebody else setting the bits. Release our copy.
        atom->Release();
      }
    } else {
      nsStringBuffer* buffer = GetStringBuffer(*aValue).take();
      NS_ENSURE_TRUE_VOID(buffer);
      uintptr_t bits = reinterpret_cast<uintptr_t>(buffer) | eStringBase;

      // In the common case we're not in the servo traversal, and we can just
      // set the bits normally. The parallel case requires more care.
      if (MOZ_LIKELY(!IsInServoTraversal())) {
        cont->SetStringBitsMainThread(bits);
      } else if (!cont->mStringBits.compareExchange(0, bits)) {
        // We raced with somebody else setting the bits. Release our copy.
        buffer->Release();
      }
    }
  }
}

void nsAttrValue::ResetMiscAtomOrString() {
  MiscContainer* cont = GetMiscContainer();
  bool isString;
  if (void* ptr = cont->GetStringOrAtomPtr(isString)) {
    if (isString) {
      static_cast<nsStringBuffer*>(ptr)->Release();
    } else {
      static_cast<nsAtom*>(ptr)->Release();
    }
    cont->SetStringBitsMainThread(0);
  }
}

void nsAttrValue::SetSVGType(ValueType aType, const void* aValue,
                             const nsAString* aSerialized) {
  MOZ_ASSERT(IsSVGType(aType), "Not an SVG type");

  MiscContainer* cont = EnsureEmptyMiscContainer();
  // All SVG types are just pointers to classes so just setting any of them
  // will do. We'll lose type-safety but the signature of the calling
  // function should ensure we don't get anything unexpected, and once we
  // stick aValue in a union we lose type information anyway.
  cont->mValue.mSVGLength = static_cast<const SVGAnimatedLength*>(aValue);
  cont->mType = aType;
  SetMiscAtomOrString(aSerialized);
}

MiscContainer* nsAttrValue::ClearMiscContainer() {
  MiscContainer* cont = nullptr;
  if (BaseType() == eOtherBase) {
    cont = GetMiscContainer();
    if (cont->IsRefCounted() && cont->mValue.mRefCount > 1) {
      // This MiscContainer is shared, we need a new one.
      NS_RELEASE(cont);

      cont = AllocMiscContainer();
      SetPtrValueAndType(cont, eOtherBase);
    } else {
      switch (cont->mType) {
        case eCSSDeclaration: {
          MOZ_ASSERT(cont->mValue.mRefCount == 1);
          cont->Release();
          cont->Evict();
          NS_RELEASE(cont->mValue.mCSSDeclaration);
          break;
        }
        case eShadowParts: {
          MOZ_ASSERT(cont->mValue.mRefCount == 1);
          cont->Release();
          delete cont->mValue.mShadowParts;
          break;
        }
        case eURL: {
          NS_RELEASE(cont->mValue.mURL);
          break;
        }
        case eAtomArray: {
          delete cont->mValue.mAtomArray;
          break;
        }
        default: {
          break;
        }
      }
    }
    ResetMiscAtomOrString();
  } else {
    ResetIfSet();
  }

  return cont;
}

MiscContainer* nsAttrValue::EnsureEmptyMiscContainer() {
  MiscContainer* cont = ClearMiscContainer();
  if (cont) {
    MOZ_ASSERT(BaseType() == eOtherBase);
    ResetMiscAtomOrString();
    cont = GetMiscContainer();
  } else {
    cont = AllocMiscContainer();
    SetPtrValueAndType(cont, eOtherBase);
  }

  return cont;
}

bool nsAttrValue::EnsureEmptyAtomArray() {
  if (Type() == eAtomArray) {
    ResetMiscAtomOrString();
    GetAtomArrayValue()->Clear();
    return true;
  }

  MiscContainer* cont = EnsureEmptyMiscContainer();
  cont->mValue.mAtomArray = new AttrAtomArray;
  cont->mType = eAtomArray;

  return true;
}

already_AddRefed<nsStringBuffer> nsAttrValue::GetStringBuffer(
    const nsAString& aValue) const {
  uint32_t len = aValue.Length();
  if (!len) {
    return nullptr;
  }

  RefPtr<nsStringBuffer> buf = nsStringBuffer::FromString(aValue);
  if (buf && (buf->StorageSize() / sizeof(char16_t) - 1) == len) {
    return buf.forget();
  }

  buf = nsStringBuffer::Alloc((len + 1) * sizeof(char16_t));
  if (!buf) {
    return nullptr;
  }
  char16_t* data = static_cast<char16_t*>(buf->Data());
  CopyUnicodeTo(aValue, 0, data, len);
  data[len] = char16_t(0);
  return buf.forget();
}

size_t nsAttrValue::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
  size_t n = 0;

  switch (BaseType()) {
    case eStringBase: {
      nsStringBuffer* str = static_cast<nsStringBuffer*>(GetPtr());
      n += str ? str->SizeOfIncludingThisIfUnshared(aMallocSizeOf) : 0;
      break;
    }
    case eOtherBase: {
      MiscContainer* container = GetMiscContainer();
      if (!container) {
        break;
      }
      if (container->IsRefCounted() && container->mValue.mRefCount > 1) {
        // We don't report this MiscContainer at all in order to avoid
        // twice-reporting it.
        // TODO DMD, bug 1027551 - figure out how to report this ref-counted
        // object just once.
        break;
      }
      n += aMallocSizeOf(container);

      // We only count the size of the object pointed by otherPtr if it's a
      // string. When it's an atom, it's counted separatly.
      if (nsStringBuffer* buf = container->GetStoredStringBuffer()) {
        n += buf->SizeOfIncludingThisIfUnshared(aMallocSizeOf);
      }

      if (Type() == eCSSDeclaration && container->mValue.mCSSDeclaration) {
        // TODO: mCSSDeclaration might be owned by another object which
        //       would make us count them twice, bug 677493.
        // Bug 1281964: For DeclarationBlock if we do measure we'll
        // need a way to call the Servo heap_size_of function.
        // n += container->mCSSDeclaration->SizeOfIncludingThis(aMallocSizeOf);
      } else if (Type() == eAtomArray && container->mValue.mAtomArray) {
        // Don't measure each nsAtom, they are measured separatly.
        n += container->mValue.mAtomArray->mArray.ShallowSizeOfIncludingThis(
            aMallocSizeOf);
      }
      break;
    }
    case eAtomBase:     // Atoms are counted separately.
    case eIntegerBase:  // The value is in mBits, nothing to do.
      break;
  }

  return n;
}