summaryrefslogtreecommitdiffstats
path: root/gfx/src/nsRegion.h
blob: 505e55e2f2c182211877b62325825669122c1af9 (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
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
/* -*- 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/. */

#ifndef nsRegion_h__
#define nsRegion_h__

#include <stddef.h>  // for size_t
#include <stdint.h>  // for uint32_t, uint64_t

#include <ostream>  // for std::ostream
#include <utility>  // for mozilla::Move

#include "mozilla/ArrayView.h"      // for ArrayView
#include "mozilla/gfx/MatrixFwd.h"  // for mozilla::gfx::Matrix4x4
#include "nsCoord.h"                // for nscoord
#include "nsMargin.h"               // for nsIntMargin
#include "nsPoint.h"                // for nsIntPoint, nsPoint
#include "nsRect.h"                 // for mozilla::gfx::IntRect, nsRect
#include "nsRectAbsolute.h"
#include "nsRegionFwd.h"  // for nsIntRegion
#include "nsString.h"     // for nsCString
#include "nsTArray.h"
#include "pixman.h"

// Uncomment this line to get additional integrity checking.
// #define DEBUG_REGIONS
#ifdef DEBUG_REGIONS
#  include <sstream>
#endif

/* For information on the internal representation look at pixman-region.c
 *
 * This replaces an older homebrew implementation of nsRegion. The
 * representation used here may use more rectangles than nsRegion however, the
 * representation is canonical.  This means that there's no need for an
 * Optimize() method because for a paticular region there is only one
 * representation. This means that nsIntRegion will have more predictable
 * performance characteristics than the old nsRegion and should not become
 * degenerate.
 *
 * The pixman region code originates from X11 which has spread to a variety of
 * projects including Qt, Gtk, Wine. It should perform reasonably well.
 */

enum class VisitSide { TOP, BOTTOM, LEFT, RIGHT };

namespace regiondetails {
struct Band;
}

template <>
struct nsTArray_RelocationStrategy<regiondetails::Band> {
  typedef nsTArray_RelocateUsingMoveConstructor<regiondetails::Band> Type;
};

namespace regiondetails {

template <typename T, typename E>
class UncheckedArray : public T {
 public:
  using T::Elements;
  using T::Length;

  UncheckedArray() = default;
  MOZ_IMPLICIT UncheckedArray(T&& aSrc) : T(std::move(aSrc)) {}

  E& operator[](size_t aIndex) { return Elements()[aIndex]; }
  const E& operator[](size_t aIndex) const { return Elements()[aIndex]; }
  E& LastElement() { return Elements()[Length() - 1]; }
  const E& LastElement() const { return Elements()[Length() - 1]; }

  using iterator = E*;
  using const_iterator = const E*;

  iterator begin() { return iterator(Elements()); }
  const_iterator begin() const { return const_iterator(Elements()); }
  const_iterator cbegin() const { return begin(); }
  iterator end() { return iterator(Elements() + Length()); }
  const_iterator end() const { return const_iterator(Elements() + Length()); }
  const_iterator cend() const { return end(); }
};

struct Strip {
  // Default constructor should never be called, but is required for
  // vector::resize to compile.
  Strip() { MOZ_CRASH(); }
  Strip(int32_t aLeft, int32_t aRight) : left(aLeft), right(aRight) {}

  bool operator!=(const Strip& aOther) const {
    return left != aOther.left || right != aOther.right;
  }

  uint32_t Size() const { return right - left; }

  int32_t left;
  int32_t right;
};

struct Band {
  using Strip = regiondetails::Strip;
#ifndef DEBUG
  using StripArray =
      regiondetails::UncheckedArray<CopyableAutoTArray<Strip, 2>, Strip>;
#else
  using StripArray = CopyableAutoTArray<Strip, 2>;
#endif

  MOZ_IMPLICIT Band(const nsRectAbsolute& aRect)
      : top(aRect.Y()), bottom(aRect.YMost()) {
    mStrips.AppendElement(Strip{aRect.X(), aRect.XMost()});
  }

  Band(const Band& aOther) = default;
  Band(Band&& aOther) = default;

  void InsertStrip(const Strip& aStrip) {
    for (size_t i = 0; i < mStrips.Length(); i++) {
      Strip& strip = mStrips[i];
      if (strip.left > aStrip.right) {
        // Current strip is beyond aStrip, insert aStrip before.
        mStrips.InsertElementAt(i, aStrip);
        return;
      }

      if (strip.right < aStrip.left) {
        // Current strip is before aStrip, try the next.
        continue;
      }

      // Current strip intersects with aStrip, extend to the lext.
      strip.left = std::min(strip.left, aStrip.left);

      if (strip.right >= aStrip.right) {
        // Current strip extends beyond aStrip, done.
        return;
      }

      size_t next = i;
      next++;
      // Consume any subsequent strips intersecting with aStrip.
      while (next < mStrips.Length() && mStrips[next].left <= aStrip.right) {
        strip.right = mStrips[next].right;

        mStrips.RemoveElementAt(next);
      }

      // Extend the strip in case the aStrip goes on beyond it.
      strip.right = std::max(strip.right, aStrip.right);
      return;
    }
    mStrips.AppendElement(aStrip);
  }

  void SubStrip(const Strip& aStrip) {
    for (size_t i = 0; i < mStrips.Length(); i++) {
      Strip& strip = mStrips[i];
      if (strip.left > aStrip.right) {
        // Strip is entirely to the right of aStrip. Done.
        return;
      }

      if (strip.right < aStrip.left) {
        // Strip is entirely to the left of aStrip. Move on.
        continue;
      }

      if (strip.left < aStrip.left) {
        if (strip.right <= aStrip.right) {
          strip.right = aStrip.left;
          // This strip lies to the left of the start of aStrip.
          continue;
        }

        // aStrip is completely contained by this strip.
        Strip newStrip(aStrip.right, strip.right);
        strip.right = aStrip.left;
        if (i < mStrips.Length()) {
          i++;
          mStrips.InsertElementAt(i, newStrip);
        } else {
          mStrips.AppendElement(newStrip);
        }
        return;
      }

      // This strip lies to the right of the start of aStrip.
      if (strip.right <= aStrip.right) {
        // aStrip completely contains this strip.
        mStrips.RemoveElementAt(i);
        // Make sure we evaluate the strip now at i. This loop will increment.
        i--;
        continue;
      }
      strip.left = aStrip.right;
      return;
    }
  }

  bool Intersects(const Strip& aStrip) const {
    for (const Strip& strip : mStrips) {
      if (strip.left >= aStrip.right) {
        return false;
      }

      if (strip.right <= aStrip.left) {
        continue;
      }

      return true;
    }
    return false;
  }

  bool IntersectStripBounds(Strip& aStrip) const {
    bool intersected = false;

    int32_t rightMost;
    for (const Strip& strip : mStrips) {
      if (strip.left > aStrip.right) {
        break;
      }

      if (strip.right <= aStrip.left) {
        continue;
      }

      if (!intersected) {
        // First intersection, this is where the left side begins.
        aStrip.left = std::max(aStrip.left, strip.left);
      }

      intersected = true;
      // Expand to the right for each intersecting strip found.
      rightMost = std::min(strip.right, aStrip.right);
    }

    if (intersected) {
      aStrip.right = rightMost;
    } else {
      aStrip.right = aStrip.left = 0;
    }
    return intersected;
  }

  bool ContainsStrip(const Strip& aStrip) const {
    for (const Strip& strip : mStrips) {
      if (strip.left > aStrip.left) {
        return false;
      }

      if (strip.right >= aStrip.right) {
        return true;
      }
    }
    return false;
  }

  bool EqualStrips(const Band& aBand) const {
    if (mStrips.Length() != aBand.mStrips.Length()) {
      return false;
    }

    for (auto iter1 = mStrips.begin(), iter2 = aBand.mStrips.begin();
         iter1 != mStrips.end(); iter1++, iter2++) {
      if (*iter1 != *iter2) {
        return false;
      }
    }

    return true;
  }

  void IntersectStrip(const Strip& aStrip) {
    size_t i = 0;

    while (i < mStrips.Length()) {
      Strip& strip = mStrips[i];
      if (strip.right <= aStrip.left) {
        mStrips.RemoveElementAt(i);
        continue;
      }

      if (strip.left >= aStrip.right) {
        mStrips.TruncateLength(i);
        return;
      }

      strip.left = std::max(aStrip.left, strip.left);
      strip.right = std::min(aStrip.right, strip.right);
      i++;
    }
  }

  void IntersectStrips(const Band& aOther) {
    auto iter = mStrips.begin();
    auto iterOther = aOther.mStrips.begin();

    StripArray newStrips;

    // This function finds the intersection between two sets of strips.
    while (true) {
      while (true) {
        while (iter != mStrips.end() && iter->right <= iterOther->left) {
          // Increment our current strip until it ends beyond aOther's current
          // strip.
          iter++;
        }

        if (iter == mStrips.end()) {
          // End of our strips. Done.
          break;
        }

        while (iterOther != aOther.mStrips.end() &&
               iterOther->right <= iter->left) {
          // Increment aOther's current strip until it lies beyond our current
          // strip.
          iterOther++;
        }

        if (iterOther == aOther.mStrips.end()) {
          // End of aOther's strips. Done.
          break;
        }

        if (iterOther->left < iter->right) {
          // Intersection!
          break;
        }
      }

      if (iter == mStrips.end() || iterOther == aOther.mStrips.end()) {
        break;
      }

      newStrips.AppendElement(Strip(std::max(iter->left, iterOther->left),
                                    std::min(iterOther->right, iter->right)));

      if (iterOther->right < iter->right) {
        iterOther++;
        if (iterOther == aOther.mStrips.end()) {
          break;
        }
      } else {
        iter++;
      }
    }

    mStrips = std::move(newStrips);
  }

  bool Intersects(const Band& aOther) const {
    auto iter = mStrips.begin();
    auto iterOther = aOther.mStrips.begin();

    // This function finds the intersection between two sets of strips.
    while (true) {
      while (true) {
        while (iter != mStrips.end() && iter->right <= iterOther->left) {
          // Increment our current strip until it ends beyond aOther's current
          // strip.
          iter++;
        }

        if (iter == mStrips.end()) {
          // End of our strips. Done.
          break;
        }

        while (iterOther != aOther.mStrips.end() &&
               iterOther->right <= iter->left) {
          // Increment aOther's current strip until it lies beyond our current
          // strip.
          iterOther++;
        }

        if (iterOther == aOther.mStrips.end()) {
          // End of aOther's strips. Done.
          break;
        }

        if (iterOther->left < iter->right) {
          // Intersection!
          break;
        }
      }

      if (iter == mStrips.end() || iterOther == aOther.mStrips.end()) {
        break;
      }

      return true;
    }
    return false;
  }

  void SubStrips(const Band& aOther) {
    size_t idx = 0;
    auto iterOther = aOther.mStrips.begin();

    // This function finds the intersection between two sets of strips.
    while (true) {
      while (true) {
        while (idx < mStrips.Length() &&
               mStrips[idx].right <= iterOther->left) {
          // Increment our current strip until it ends beyond aOther's current
          // strip.
          idx++;
        }

        if (idx == mStrips.Length()) {
          // End of our strips. Done.
          break;
        }

        while (iterOther != aOther.mStrips.end() &&
               iterOther->right <= mStrips[idx].left) {
          // Increment aOther's current strip until it lies beyond our current
          // strip.
          iterOther++;
        }

        if (iterOther == aOther.mStrips.end()) {
          // End of aOther's strips. Done.
          break;
        }

        if (iterOther->left < mStrips[idx].right) {
          // Intersection!
          break;
        }
      }

      if (idx == mStrips.Length() || iterOther == aOther.mStrips.end()) {
        break;
      }

      if (mStrips[idx].left < iterOther->left) {
        size_t oldIdx = idx;
        // Our strip starts beyond other's
        if (mStrips[idx].right > iterOther->right) {
          // Our strip ends beyond other's as well.
          Strip newStrip(mStrips[idx]);
          newStrip.left = iterOther->right;
          mStrips.InsertElementAt(idx + 1, newStrip);
          idx++;
        }
        mStrips[oldIdx].right = iterOther->left;
        // Either idx was just incremented, or the current index no longer
        // intersects with iterOther.
        continue;
      } else if (mStrips[idx].right > iterOther->right) {
        mStrips[idx].left = iterOther->right;
        // Current strip no longer intersects, continue.
        iterOther++;
        if (iterOther == aOther.mStrips.end()) {
          break;
        }
        continue;
      }

      // Our current strip is completely contained by the other strip.
      mStrips.RemoveElementAt(idx);
    }
  }

  int32_t top;
  int32_t bottom;
  StripArray mStrips;
};
}  // namespace regiondetails

class nsRegion {
 public:
  using Band = regiondetails::Band;
  using Strip = regiondetails::Strip;
#ifndef DEBUG
  using BandArray = regiondetails::UncheckedArray<nsTArray<Band>, Band>;
  using StripArray = regiondetails::UncheckedArray<AutoTArray<Strip, 2>, Strip>;
#else
  using BandArray = nsTArray<Band>;
  using StripArray = AutoTArray<Strip, 2>;
#endif

  typedef nsRect RectType;
  typedef nsPoint PointType;
  typedef nsMargin MarginType;

  nsRegion() = default;
  MOZ_IMPLICIT nsRegion(const nsRect& aRect) {
    mBounds = nsRectAbsolute::FromRect(aRect);
  }
  MOZ_IMPLICIT nsRegion(const nsRectAbsolute& aRect) { mBounds = aRect; }
  explicit nsRegion(mozilla::gfx::ArrayView<pixman_box32_t> aRects) {
    for (uint32_t i = 0; i < aRects.Length(); i++) {
      AddRect(BoxToRect(aRects[i]));
    }
  }

  nsRegion(const nsRegion& aRegion) { Copy(aRegion); }
  nsRegion(nsRegion&& aRegion)
      : mBands(std::move(aRegion.mBands)), mBounds(aRegion.mBounds) {
    aRegion.SetEmpty();
  }
  nsRegion& operator=(nsRegion&& aRegion) {
    mBands = std::move(aRegion.mBands);
    mBounds = aRegion.mBounds;
    aRegion.SetEmpty();
    return *this;
  }
  nsRegion& operator=(const nsRect& aRect) {
    Copy(aRect);
    return *this;
  }
  nsRegion& operator=(const nsRegion& aRegion) {
    Copy(aRegion);
    return *this;
  }
  bool operator==(const nsRegion& aRgn) const { return IsEqual(aRgn); }
  bool operator!=(const nsRegion& aRgn) const { return !(*this == aRgn); }

  friend std::ostream& operator<<(std::ostream& stream, const nsRegion& m);
  void OutputToStream(std::string aObjName, std::ostream& stream) const;

 private:
#ifdef DEBUG_REGIONS
  class OperationStringGenerator {
   public:
    virtual ~OperationStringGenerator() = default;

    virtual void OutputOp() = 0;
  };
#endif
 public:
  void AssertStateInternal() const;
  void AssertState() const {
#ifdef DEBUG_REGIONS
    AssertStateInternal();
#endif
  }

 private:
  void And(BandArray& aOut, const BandArray& aIn1, const BandArray& aIn2) {
    size_t idx = 0;
    size_t idxOther = 0;

    // This algorithm essentially forms a new list of bands, by iterating over
    // both regions' lists of band simultaneously, and building a new band
    // wherever the two regions intersect.
    while (true) {
      while (true) {
        while (idx != aIn1.Length() && aIn1[idx].bottom <= aIn2[idxOther].top) {
          // Increment our current band until it ends beyond aOther's current
          // band.
          idx++;
        }

        if (idx == aIn1.Length()) {
          // This region is out of bands, the other region's future bands are
          // ignored.
          break;
        }

        while (idxOther != aIn2.Length() &&
               aIn2[idxOther].bottom <= aIn1[idx].top) {
          // Increment aOther's current band until it ends beyond our current
          // band.
          idxOther++;
        }

        if (idxOther == aIn2.Length()) {
          // The other region's bands are all processed, all our future bands
          // are ignored.
          break;
        }

        if (aIn2[idxOther].top < aIn1[idx].bottom) {
          // We know the other band's bottom lies beyond our band's top because
          // otherwise we would've incremented above. Intersecting bands found.
          break;
        }
      }

      if (idx == aIn1.Length() || idxOther == aIn2.Length()) {
        // The above loop executed a break because we're done.
        break;
      }

      Band newBand(aIn1[idx]);
      // The new band is the intersection of the two current bands from both
      // regions.
      newBand.top = std::max(aIn1[idx].top, aIn2[idxOther].top);
      newBand.bottom = std::min(aIn1[idx].bottom, aIn2[idxOther].bottom);
      newBand.IntersectStrips(aIn2[idxOther]);

      if (newBand.mStrips.Length()) {
        // The intersecting area of the bands had overlapping strips, if it is
        // identical to the band above it merge, otherwise append.
        if (aOut.Length() && aOut.LastElement().bottom == newBand.top &&
            aOut.LastElement().EqualStrips(newBand)) {
          aOut.LastElement().bottom = newBand.bottom;
        } else {
          aOut.AppendElement(std::move(newBand));
        }
      }

      if (aIn2[idxOther].bottom < aIn1[idx].bottom) {
        idxOther++;
        if (idxOther == aIn2.Length()) {
          // Since we will access idxOther the next iteration, check if we're
          // not done.
          break;
        }
      } else {
        // No need to check here since we do at the beginning of the next
        // iteration.
        idx++;
      }
    }
  }

 public:
  nsRegion& AndWith(const nsRegion& aRegion) {
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorAndWith : public OperationStringGenerator {
     public:
      OperationStringGeneratorAndWith(nsRegion& aRegion,
                                      const nsRegion& aOtherRegion)
          : mRegion(&aRegion),
            mRegionCopy(aRegion),
            mOtherRegion(aOtherRegion) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorAndWith() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegionCopy.OutputToStream("r1", stream);
        mOtherRegion.OutputToStream("r2", stream);
        stream << "r1.AndWith(r2);\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegionCopy;
      nsRegion mOtherRegion;
    };

    OperationStringGeneratorAndWith opGenerator(*this, aRegion);
#endif
    if (mBounds.IsEmpty()) {
      // Region is empty, stays empty.
      return *this;
    }

    if (aRegion.IsEmpty()) {
      SetEmpty();
      return *this;
    }

    if (aRegion.mBands.IsEmpty()) {
      // Other region is a rect.
      return AndWith(aRegion.mBounds);
    }

    if (mBands.IsEmpty()) {
      mBands.AppendElement(mBounds);
    }

    BandArray newBands;

    And(newBands, mBands, aRegion.mBands);

    mBands = std::move(newBands);
    if (!mBands.Length()) {
      mBounds = nsRectAbsolute();
    } else {
      mBounds = CalculateBounds();
    }

    EnsureSimplified();
    AssertState();
    return *this;
  }

  nsRegion& AndWith(const nsRectAbsolute& aRect) {
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorAndWith : public OperationStringGenerator {
     public:
      OperationStringGeneratorAndWith(nsRegion& aRegion,
                                      const nsRectAbsolute& aRect)
          : mRegion(&aRegion), mRegionCopy(aRegion), mRect(aRect) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorAndWith() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegionCopy.OutputToStream("r", stream);
        stream << "r.AndWith(nsRect(" << mRect.X() << ", " << mRect.Y() << ", "
               << mRect.Width() << ", " << mRect.Height() << "));\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegionCopy;
      nsRectAbsolute mRect;
    };

    OperationStringGeneratorAndWith opGenerator(*this, aRect);
#endif
    if (aRect.IsEmpty()) {
      SetEmpty();
      return *this;
    }

    if (mBands.IsEmpty()) {
      mBounds = mBounds.Intersect(aRect);
      return *this;
    }

    size_t idx = 0;

    size_t removeStart = 0;

    // This removes all bands that do not intersect with aRect, and intersects
    // the remaining ones with aRect.

    // Start by figuring out how much to remove from the start.
    while (idx != mBands.Length() && mBands[idx].bottom <= aRect.Y()) {
      idx++;
    }

    // We'll remove these later to avoid needless copying in the array.
    removeStart = idx;

    while (idx != mBands.Length()) {
      if (mBands[idx].top >= aRect.YMost()) {
        mBands.TruncateLength(idx);
        break;
      }

      mBands[idx].top = std::max(mBands[idx].top, aRect.Y());
      mBands[idx].bottom = std::min(mBands[idx].bottom, aRect.YMost());

      mBands[idx].IntersectStrip(Strip(aRect.X(), aRect.XMost()));

      if (!mBands[idx].mStrips.Length()) {
        mBands.RemoveElementAt(idx);
      } else {
        if (idx > removeStart) {
          CompressBefore(idx);
        }
        idx++;
      }
    }

    if (removeStart) {
      mBands.RemoveElementsAt(0, removeStart);
    }

    if (mBands.Length()) {
      mBounds = CalculateBounds();
    } else {
      mBounds.SetEmpty();
    }
    EnsureSimplified();
    AssertState();
    return *this;
  }
  nsRegion& AndWith(const nsRect& aRect) {
    return AndWith(nsRectAbsolute::FromRect(aRect));
  }
  nsRegion& And(const nsRegion& aRgn1, const nsRegion& aRgn2) {
    if (&aRgn1 == this) {
      return AndWith(aRgn2);
    }
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorAnd : public OperationStringGenerator {
     public:
      OperationStringGeneratorAnd(nsRegion& aRegion, const nsRegion& aRegion1,
                                  const nsRegion& aRegion2)
          : mRegion(&aRegion), mRegion1(aRegion1), mRegion2(aRegion2) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorAnd() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegion1.OutputToStream("r1", stream);
        mRegion2.OutputToStream("r2", stream);
        stream << "nsRegion r3;\nr3.And(r1, r2);\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegion1;
      nsRegion mRegion2;
    };

    OperationStringGeneratorAnd opGenerator(*this, aRgn1, aRgn2);
#endif
    mBands.Clear();

    if (aRgn1.IsEmpty() || aRgn2.IsEmpty()) {
      mBounds.SetEmpty();
      return *this;
    }

    if (aRgn1.mBands.IsEmpty() && aRgn2.mBands.IsEmpty()) {
      mBounds = aRgn1.mBounds.Intersect(aRgn2.mBounds);
      return *this;
    } else if (aRgn1.mBands.IsEmpty()) {
      return And(aRgn2, aRgn1.mBounds);
    } else if (aRgn2.mBands.IsEmpty()) {
      return And(aRgn1, aRgn2.mBounds);
    }

    And(mBands, aRgn1.mBands, aRgn2.mBands);

    if (!mBands.Length()) {
      mBounds = nsRectAbsolute();
    } else {
      mBounds = CalculateBounds();
    }

    EnsureSimplified();
    AssertState();
    return *this;
  }
  nsRegion& And(const nsRect& aRect, const nsRegion& aRegion) {
    return And(aRegion, aRect);
  }
  nsRegion& And(const nsRegion& aRegion, const nsRectAbsolute& aRect) {
    if (&aRegion == this) {
      return AndWith(aRect);
    }
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorAnd : public OperationStringGenerator {
     public:
      OperationStringGeneratorAnd(nsRegion& aThisRegion,
                                  const nsRegion& aRegion,
                                  const nsRectAbsolute& aRect)
          : mThisRegion(&aThisRegion), mRegion(aRegion), mRect(aRect) {
        aThisRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorAnd() {
        mThisRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegion.OutputToStream("r", stream);
        stream << "nsRegion r2;\nr.And(r2, nsRect(" << mRect.X() << ", "
               << mRect.Y() << ", " << mRect.Width() << ", " << mRect.Height()
               << "));\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mThisRegion;
      nsRegion mRegion;
      nsRectAbsolute mRect;
    };

    OperationStringGeneratorAnd opGenerator(*this, aRegion, aRect);
#endif
    mBands.Clear();

    if (aRect.IsEmpty()) {
      mBounds.SetEmpty();
      return *this;
    }

    if (aRegion.mBands.IsEmpty()) {
      mBounds = aRegion.mBounds.Intersect(aRect);
      return *this;
    }

    size_t idx = 0;
    const BandArray& bands = aRegion.mBands;

    mBands.SetCapacity(bands.Length() + 3);
    while (idx != bands.Length()) {
      // Ignore anything before.
      if (bands[idx].bottom <= aRect.Y()) {
        idx++;
        continue;
      }
      // We're done once we've reached the bottom.
      if (bands[idx].top >= aRect.YMost()) {
        break;
      }

      // Now deal with bands actually intersecting the rectangle.
      Band newBand(bands[idx]);
      newBand.top = std::max(bands[idx].top, aRect.Y());
      newBand.bottom = std::min(bands[idx].bottom, aRect.YMost());

      newBand.IntersectStrip(Strip(aRect.X(), aRect.XMost()));

      if (newBand.mStrips.Length()) {
        if (!mBands.IsEmpty() && newBand.top == mBands.LastElement().bottom &&
            newBand.EqualStrips(mBands.LastElement())) {
          mBands.LastElement().bottom = newBand.bottom;
        } else {
          mBands.AppendElement(std::move(newBand));
        }
      }
      idx++;
    }

    if (mBands.Length()) {
      mBounds = CalculateBounds();
    } else {
      mBounds.SetEmpty();
    }

    EnsureSimplified();
    AssertState();
    return *this;
  }
  nsRegion& And(const nsRegion& aRegion, const nsRect& aRect) {
    return And(aRegion, nsRectAbsolute::FromRect(aRect));
  }
  nsRegion& And(const nsRect& aRect1, const nsRect& aRect2) {
    nsRect tmpRect;

    tmpRect.IntersectRect(aRect1, aRect2);
    return Copy(tmpRect);
  }

  nsRegion& OrWith(const nsRegion& aOther) {
    for (RectIterator idx(aOther); !idx.Done(); idx.Next()) {
      AddRect(idx.GetAbsolute());
    }
    return *this;
  }
  nsRegion& OrWith(const nsRect& aOther) {
    AddRect(nsRectAbsolute::FromRect(aOther));
    return *this;
  }
  nsRegion& Or(const nsRegion& aRgn1, const nsRegion& aRgn2) {
    if (&aRgn1 != this) {
      *this = aRgn1;
    }
    for (RectIterator idx(aRgn2); !idx.Done(); idx.Next()) {
      AddRect(idx.GetAbsolute());
    }
    return *this;
  }
  nsRegion& Or(const nsRegion& aRegion, const nsRect& aRect) {
    if (&aRegion != this) {
      *this = aRegion;
    }
    AddRect(nsRectAbsolute::FromRect(aRect));
    return *this;
  }
  nsRegion& Or(const nsRect& aRect, const nsRegion& aRegion) {
    return Or(aRegion, aRect);
  }
  nsRegion& Or(const nsRect& aRect1, const nsRect& aRect2) {
    Copy(aRect1);
    return Or(*this, aRect2);
  }

  nsRegion& XorWith(const nsRegion& aOther) { return Xor(*this, aOther); }
  nsRegion& XorWith(const nsRect& aOther) { return Xor(*this, aOther); }
  nsRegion& Xor(const nsRegion& aRgn1, const nsRegion& aRgn2) {
    // this could be implemented better if pixman had direct
    // support for xoring regions.
    nsRegion p;
    p.Sub(aRgn1, aRgn2);
    nsRegion q;
    q.Sub(aRgn2, aRgn1);
    return Or(p, q);
  }
  nsRegion& Xor(const nsRegion& aRegion, const nsRect& aRect) {
    return Xor(aRegion, nsRegion(aRect));
  }
  nsRegion& Xor(const nsRect& aRect, const nsRegion& aRegion) {
    return Xor(nsRegion(aRect), aRegion);
  }
  nsRegion& Xor(const nsRect& aRect1, const nsRect& aRect2) {
    return Xor(nsRegion(aRect1), nsRegion(aRect2));
  }

  nsRegion ToAppUnits(nscoord aAppUnitsPerPixel) const;

  nsRegion& SubWith(const nsRegion& aOther) {
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorSubWith : public OperationStringGenerator {
     public:
      OperationStringGeneratorSubWith(nsRegion& aRegion,
                                      const nsRegion& aOtherRegion)
          : mRegion(&aRegion),
            mRegionCopy(aRegion),
            mOtherRegion(aOtherRegion) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorSubWith() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegionCopy.OutputToStream("r1", stream);
        mOtherRegion.OutputToStream("r2", stream);
        stream << "r1.SubWith(r2);\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegionCopy;
      nsRegion mOtherRegion;
    };

    OperationStringGeneratorSubWith opGenerator(*this, aOther);
#endif

    if (mBounds.IsEmpty()) {
      return *this;
    }

    if (aOther.mBands.IsEmpty()) {
      return SubWith(aOther.mBounds);
    }

    if (mBands.IsEmpty()) {
      mBands.AppendElement(Band(mBounds));
    }

    size_t idx = 0;
    size_t idxOther = 0;
    while (idx < mBands.Length()) {
      while (true) {
        while (idx != mBands.Length() &&
               mBands[idx].bottom <= aOther.mBands[idxOther].top) {
          // Increment our current band until it ends beyond aOther's current
          // band.
          idx++;
        }

        if (idx == mBands.Length()) {
          // This region is out of bands, the other region's future bands are
          // ignored.
          break;
        }

        while (idxOther != aOther.mBands.Length() &&
               aOther.mBands[idxOther].bottom <= mBands[idx].top) {
          // Increment aOther's current band until it ends beyond our current
          // band.
          idxOther++;
        }

        if (idxOther == aOther.mBands.Length()) {
          // The other region's bands are all processed, all our future bands
          // are ignored.
          break;
        }

        if (aOther.mBands[idxOther].top < mBands[idx].bottom) {
          // We know the other band's bottom lies beyond our band's top because
          // otherwise we would've incremented above. Intersecting bands found.
          break;
        }
      }

      if (idx == mBands.Length() || idxOther == aOther.mBands.Length()) {
        // The above loop executed a break because we're done.
        break;
      }

      const Band& bandOther = aOther.mBands[idxOther];

      if (!mBands[idx].Intersects(bandOther)) {
        if (mBands[idx].bottom < bandOther.bottom) {
          idx++;
        } else {
          idxOther++;
          if (idxOther == aOther.mBands.Length()) {
            break;
          }
        }
        continue;
      }

      // These bands actually intersect.
      if (mBands[idx].top < bandOther.top) {
        mBands.InsertElementAt(idx + 1, Band(mBands[idx]));
        mBands[idx].bottom = bandOther.top;
        idx++;
        mBands[idx].top = bandOther.top;
      }

      // mBands[idx].top >= bandOther.top;
      if (mBands[idx].bottom <= bandOther.bottom) {
        mBands[idx].SubStrips(bandOther);
        if (mBands[idx].mStrips.IsEmpty()) {
          mBands.RemoveElementAt(idx);
        } else {
          CompressBefore(idx);
          idx++;
          // The band before us just changed, it may be identical now.
          CompressBefore(idx);
        }
        continue;
      }

      // mBands[idx].bottom > bandOther.bottom
      Band newBand = mBands[idx];
      newBand.SubStrips(bandOther);

      if (!newBand.mStrips.IsEmpty()) {
        mBands.InsertElementAt(idx, newBand);
        mBands[idx].bottom = bandOther.bottom;
        CompressBefore(idx);
        idx++;
      }

      mBands[idx].top = bandOther.bottom;

      idxOther++;
      if (idxOther == aOther.mBands.Length()) {
        break;
      }
    }

    if (mBands.IsEmpty()) {
      mBounds.SetEmpty();
    } else {
      mBounds = CalculateBounds();
    }

    AssertState();
    EnsureSimplified();
    return *this;
  }
  nsRegion& SubOut(const nsRegion& aOther) { return SubWith(aOther); }
  nsRegion& SubOut(const nsRect& aOther) { return SubWith(aOther); }

 private:
  void AppendOrExtend(const Band& aNewBand) {
    if (aNewBand.mStrips.IsEmpty()) {
      return;
    }
    if (mBands.IsEmpty()) {
      mBands.AppendElement(aNewBand);
      return;
    }

    if (mBands.LastElement().bottom == aNewBand.top &&
        mBands.LastElement().EqualStrips(aNewBand)) {
      mBands.LastElement().bottom = aNewBand.bottom;
    } else {
      mBands.AppendElement(aNewBand);
    }
  }
  void AppendOrExtend(const Band&& aNewBand) {
    if (aNewBand.mStrips.IsEmpty()) {
      return;
    }
    if (mBands.IsEmpty()) {
      mBands.AppendElement(std::move(aNewBand));
      return;
    }

    if (mBands.LastElement().bottom == aNewBand.top &&
        mBands.LastElement().EqualStrips(aNewBand)) {
      mBands.LastElement().bottom = aNewBand.bottom;
    } else {
      mBands.AppendElement(std::move(aNewBand));
    }
  }

 public:
  nsRegion& Sub(const nsRegion& aRgn1, const nsRegion& aRgn2) {
    if (&aRgn1 == this) {
      return SubWith(aRgn2);
    }
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorSub : public OperationStringGenerator {
     public:
      OperationStringGeneratorSub(nsRegion& aRegion, const nsRegion& aRgn1,
                                  const nsRegion& aRgn2)
          : mRegion(&aRegion), mRegion1(aRgn1), mRegion2(aRgn2) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorSub() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegion1.OutputToStream("r1", stream);
        mRegion2.OutputToStream("r2", stream);
        stream << "nsRegion r3;\nr3.Sub(r1, r2);\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegion1;
      nsRegion mRegion2;
    };

    OperationStringGeneratorSub opGenerator(*this, aRgn1, aRgn2);
#endif

    mBands.Clear();

    if (aRgn1.mBounds.IsEmpty()) {
      mBounds.SetEmpty();
      return *this;
    }

    if (aRgn2.mBounds.IsEmpty()) {
      Copy(aRgn1);
      return *this;
    }

    if (aRgn1.mBands.IsEmpty() && aRgn2.mBands.IsEmpty()) {
      return Sub(aRgn1.mBounds, aRgn2.mBounds);
    } else if (aRgn1.mBands.IsEmpty()) {
      return Sub(aRgn1.mBounds, aRgn2);
    } else if (aRgn2.mBands.IsEmpty()) {
      return Sub(aRgn1, aRgn2.mBounds);
    }

    const BandArray& bands1 = aRgn1.mBands;
    const BandArray& bands2 = aRgn2.mBands;

    size_t idx = 0;
    size_t idxOther = 0;

    // We iterate the source region's bands, subtracting the other regions bands
    // from them as we move them into ours.
    while (idx < bands1.Length()) {
      while (idxOther < bands2.Length() &&
             bands2[idxOther].bottom <= bands1[idx].top) {
        // These other bands are irrelevant as they don't intersect with the
        // band we're currently processing.
        idxOther++;
      }
      if (idxOther == bands2.Length()) {
        break;
      }

      const Band& other = bands2[idxOther];

      // bands2[idxOther].bottom >= bands1[idx].top
      Band origBand(bands1[idx]);
      if (other.top >= origBand.bottom) {
        // No intersecting bands, append and continue.
        AppendOrExtend(origBand);
        idx++;
        continue;
      }

      // Push a band for an uncovered region above our band.
      if (origBand.top < other.top) {
        Band newBand(origBand);
        newBand.bottom = other.top;
        AppendOrExtend(std::move(newBand));
      }

      int32_t lastBottom = std::max(other.top, origBand.top);
      while (idxOther < bands2.Length() &&
             bands2[idxOther].top < origBand.bottom) {
        const Band& other = bands2[idxOther];
        Band newBand(origBand);
        newBand.top = std::max(origBand.top, other.top);
        newBand.bottom = std::min(origBand.bottom, other.bottom);

        // If there was a gap, we need to add the original band there.
        if (newBand.top > lastBottom) {
          Band betweenBand(newBand);
          betweenBand.top = lastBottom;
          betweenBand.bottom = newBand.top;
          AppendOrExtend(std::move(betweenBand));
        }

        lastBottom = newBand.bottom;
        newBand.SubStrips(other);
        AppendOrExtend(std::move(newBand));
        idxOther++;
      }
      // Decrement other here so we are back at the last band in region 2
      // that intersected.
      idxOther--;

      if (bands2[idxOther].bottom < origBand.bottom) {
        // The last band in region2 that intersected ended before this one,
        // we can copy the rest.
        Band newBand(origBand);
        newBand.top = bands2[idxOther].bottom;
        AppendOrExtend(std::move(newBand));
        idxOther++;
      }
      idx++;
    }

    // Copy any remaining bands, the first one may have to be extended to fit
    // the last one added before. The rest can be unconditionally appended.
    if (idx < bands1.Length()) {
      AppendOrExtend(bands1[idx]);
      idx++;
    }

    while (idx < bands1.Length()) {
      mBands.AppendElement(bands1[idx]);
      idx++;
    }

    if (mBands.IsEmpty()) {
      mBounds.SetEmpty();
    } else {
      mBounds = CalculateBounds();
    }

    AssertState();
    EnsureSimplified();
    return *this;
  }

 private:
  // Internal helper for executing subtraction.
  void RunSubtraction(const nsRectAbsolute& aRect) {
    Strip rectStrip(aRect.X(), aRect.XMost());

    size_t idx = 0;

    while (idx < mBands.Length()) {
      if (mBands[idx].top >= aRect.YMost()) {
        return;
      }

      if (mBands[idx].bottom <= aRect.Y()) {
        // This band is entirely before aRect, move on.
        idx++;
        continue;
      }

      if (!mBands[idx].Intersects(Strip(aRect.X(), aRect.XMost()))) {
        // This band does not intersect aRect horizontally. Move on.
        idx++;
        continue;
      }

      // This band intersects with aRect.

      if (mBands[idx].top < aRect.Y()) {
        // This band starts above the start of aRect, split the band into two
        // along the intersection, and continue to the next iteration to process
        // the one that now intersects exactly.
        auto above = mBands.InsertElementAt(idx, Band(mBands[idx]));
        above->bottom = aRect.Y();
        idx++;
        mBands[idx].top = aRect.Y();
        // Continue to run the loop for the next band.
        continue;
      }

      if (mBands[idx].bottom <= aRect.YMost()) {
        // This band ends before the end of aRect.
        mBands[idx].SubStrip(rectStrip);
        if (mBands[idx].mStrips.Length()) {
          CompressAdjacentBands(idx);
        } else {
          mBands.RemoveElementAt(idx);
        }
        continue;
      }

      // This band extends beyond aRect.
      Band newBand = mBands[idx];
      newBand.SubStrip(rectStrip);
      newBand.bottom = aRect.YMost();
      mBands[idx].top = aRect.YMost();

      if (newBand.mStrips.Length()) {
        if (idx && mBands[idx - 1].bottom == newBand.top &&
            newBand.EqualStrips(mBands[idx - 1])) {
          mBands[idx - 1].bottom = aRect.YMost();
        } else {
          mBands.InsertElementAt(idx, std::move(newBand));
        }
      }

      return;
    }
  }

 public:
  nsRegion& SubWith(const nsRectAbsolute& aRect) {
    if (!mBounds.Intersects(aRect)) {
      return *this;
    }

    if (aRect.Contains(mBounds)) {
      SetEmpty();
      return *this;
    }

#ifdef DEBUG_REGIONS
    class OperationStringGeneratorSubWith : public OperationStringGenerator {
     public:
      OperationStringGeneratorSubWith(nsRegion& aRegion,
                                      const nsRectAbsolute& aRect)
          : mRegion(&aRegion), mRegionCopy(aRegion), mRect(aRect) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorSubWith() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegionCopy.OutputToStream("r", stream);
        stream << "r.SubWith(nsRect(" << mRect.X() << ", " << mRect.Y() << ", "
               << mRect.Width() << ", " << mRect.Height() << "));\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegionCopy;
      nsRectAbsolute mRect;
    };

    OperationStringGeneratorSubWith opGenerator(*this, aRect);
#endif

    if (mBands.IsEmpty()) {
      mBands.AppendElement(Band(mBounds));
    }

    RunSubtraction(aRect);

    if (aRect.X() <= mBounds.X() || aRect.Y() <= mBounds.Y() ||
        aRect.XMost() >= mBounds.XMost() || aRect.YMost() >= mBounds.YMost()) {
      mBounds = CalculateBounds();
    }
    EnsureSimplified();
    AssertState();
    return *this;
  }
  nsRegion& Sub(const nsRegion& aRegion, const nsRectAbsolute& aRect) {
    if (aRect.Contains(aRegion.mBounds)) {
      SetEmpty();
      return *this;
    }
    if (&aRegion == this) {
      return SubWith(aRect);
    }
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorSub : public OperationStringGenerator {
     public:
      OperationStringGeneratorSub(nsRegion& aRegion,
                                  const nsRegion& aRegionOther,
                                  const nsRectAbsolute& aRect)
          : mRegion(&aRegion), mRegionOther(aRegionOther), mRect(aRect) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorSub() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegionOther.OutputToStream("r1", stream);
        stream << "nsRegion r2;\nr2.Sub(r1, nsRect(" << mRect.X() << ", "
               << mRect.Y() << ", " << mRect.Width() << ", " << mRect.Height()
               << "));\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegionOther;
      nsRectAbsolute mRect;
    };

    OperationStringGeneratorSub opGenerator(*this, aRegion, aRect);
#endif

    mBands.Clear();

    if (aRegion.mBounds.IsEmpty()) {
      mBounds.SetEmpty();
      return *this;
    }

    if (aRect.IsEmpty()) {
      Copy(aRegion);
      return *this;
    }

    if (aRegion.mBands.IsEmpty()) {
      Copy(aRegion.mBounds);
      return SubWith(aRect);
    }

    const BandArray& bands = aRegion.mBands;

    size_t idx = 0;

    Strip strip(aRect.X(), aRect.XMost());

    mBands.SetCapacity(bands.Length() + 3);

    // Process all bands that lie before aRect.
    while (idx < bands.Length() && bands[idx].bottom <= aRect.Y()) {
      mBands.AppendElement(bands[idx]);
      idx++;
    }

    // This band's bottom lies beyond aRect.
    if (idx < bands.Length() && bands[idx].top < aRect.Y()) {
      Band newBand(bands[idx]);
      if (bands[idx].Intersects(strip)) {
        newBand.bottom = aRect.Y();
      } else {
        idx++;
      }
      mBands.AppendElement(std::move(newBand));
    }

    // This tracks whether the band when we -exit- the next loop intersected the
    // rectangle.
    bool didIntersect = false;

    while (idx < bands.Length() && bands[idx].top < aRect.YMost()) {
      // Process all bands intersecting with aRect.
      if (!bands[idx].Intersects(strip)) {
        AppendOrExtend(bands[idx]);
        idx++;
        didIntersect = false;
        continue;
      }

      didIntersect = true;
      Band newBand(bands[idx]);
      newBand.top = std::max(newBand.top, aRect.Y());
      newBand.bottom = std::min(newBand.bottom, aRect.YMost());
      newBand.SubStrip(strip);
      AppendOrExtend(std::move(newBand));
      idx++;
    }

    if (didIntersect) {
      if (aRect.YMost() < bands[idx - 1].bottom) {
        // If this band does not intersect the loop above has already added the
        // whole unmodified band.
        Band newBand(bands[idx - 1]);
        newBand.top = aRect.YMost();
        AppendOrExtend(std::move(newBand));
      }
    }

    // Now process all bands beyond aRect.
    if (idx < bands.Length()) {
      AppendOrExtend(bands[idx]);
      idx++;
    }

    mBands.AppendElements(bands.Elements() + idx, bands.Length() - idx);

    if (mBands.IsEmpty()) {
      mBounds.SetEmpty();
    } else {
      mBounds = CalculateBounds();
    }

    AssertState();
    EnsureSimplified();
    return *this;
  }
  nsRegion& SubWith(const nsRect& aRect) {
    return SubWith(nsRectAbsolute::FromRect(aRect));
  }
  nsRegion& Sub(const nsRect& aRect, const nsRegion& aRegion) {
    Copy(aRect);
    return SubWith(aRegion);
  }
  nsRegion& Sub(const nsRectAbsolute& aRect, const nsRegion& aRegion) {
    Copy(aRect);
    return SubWith(aRegion);
  }
  nsRegion& Sub(const nsRect& aRect1, const nsRect& aRect2) {
    Copy(aRect1);
    return SubWith(aRect2);
  }
  nsRegion& Sub(const nsRegion& aRegion, const nsRect& aRect) {
    return Sub(aRegion, nsRectAbsolute::FromRect(aRect));
  }
  nsRegion& Sub(const nsRectAbsolute& aRect1, const nsRectAbsolute& aRect2) {
    Copy(aRect1);
    return SubWith(aRect2);
  }

  /**
   * Returns true if the given point is inside the region. A region
   * created from a rect (x=0, y=0, w=100, h=100) will NOT contain
   * the point x=100, y=100.
   */
  bool Contains(int aX, int aY) const {
    if (mBands.IsEmpty()) {
      return mBounds.Contains(aX, aY);
    }

    auto iter = mBands.begin();

    while (iter != mBands.end()) {
      if (iter->bottom <= aY) {
        iter++;
        continue;
      }

      if (iter->top > aY) {
        return false;
      }

      if (iter->ContainsStrip(Strip(aX, aX + 1))) {
        return true;
      }
      return false;
    }
    return false;
  }

  bool Contains(const nsPoint& aPoint) const {
    return Contains(aPoint.x, aPoint.y);
  }

  bool Contains(const nsRectAbsolute& aRect) const {
    if (aRect.IsEmpty()) {
      return false;
    }

    if (mBands.IsEmpty()) {
      return mBounds.Contains(aRect);
    }

    auto iter = mBands.begin();

    while (iter != mBands.end()) {
      if (iter->bottom <= aRect.Y()) {
        iter++;
        continue;
      }

      if (iter->top > aRect.Y()) {
        return false;
      }

      // Now inside the rectangle.
      if (!iter->ContainsStrip(Strip(aRect.X(), aRect.XMost()))) {
        return false;
      }

      if (iter->bottom >= aRect.YMost()) {
        return true;
      }

      int32_t lastY = iter->bottom;
      iter++;
      while (iter != mBands.end()) {
        // Bands do not connect.
        if (iter->top != lastY) {
          return false;
        }

        if (!iter->ContainsStrip(Strip(aRect.X(), aRect.XMost()))) {
          return false;
        }

        if (iter->bottom >= aRect.YMost()) {
          return true;
        }

        lastY = iter->bottom;
        iter++;
      }
    }
    return false;
  }
  bool Contains(const nsRect& aRect) const {
    return Contains(nsRectAbsolute::FromRect(aRect));
  }

  bool Contains(const nsRegion& aRgn) const;
  bool Intersects(const nsRectAbsolute& aRect) const;
  bool Intersects(const nsRect& aRect) const {
    return Intersects(nsRectAbsolute::FromRect(aRect));
  }

  void MoveBy(int32_t aXOffset, int32_t aYOffset) {
    MoveBy(nsPoint(aXOffset, aYOffset));
  }
  void MoveBy(nsPoint aPt) {
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorMoveBy : public OperationStringGenerator {
     public:
      OperationStringGeneratorMoveBy(nsRegion& aRegion, const nsPoint& aPoint)
          : mRegion(&aRegion), mRegionCopy(aRegion), mPoint(aPoint) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorMoveBy() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegionCopy.OutputToStream("r", stream);
        stream << "r.MoveBy(nsPoint(" << mPoint.x << ", " << mPoint.y
               << "));\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegionCopy;
      nsPoint mPoint;
    };

    OperationStringGeneratorMoveBy opGenerator(*this, aPt);
#endif

    mBounds.MoveBy(aPt);
    for (Band& band : mBands) {
      band.top += aPt.Y();
      band.bottom += aPt.Y();
      for (Strip& strip : band.mStrips) {
        strip.left += aPt.X();
        strip.right += aPt.X();
      }
    }
    AssertState();
  }
  void SetEmpty() {
    mBands.Clear();
    mBounds.SetEmpty();
  }

  nsRegion MovedBy(int32_t aXOffset, int32_t aYOffset) const {
    return MovedBy(nsPoint(aXOffset, aYOffset));
  }
  nsRegion MovedBy(const nsPoint& aPt) const {
    nsRegion copy(*this);
    copy.MoveBy(aPt);
    return copy;
  }

  nsRegion Intersect(const nsRegion& aOther) const {
    nsRegion intersection;
    intersection.And(*this, aOther);
    return intersection;
  }

  void Inflate(const nsMargin& aMargin);

  nsRegion Inflated(const nsMargin& aMargin) const {
    nsRegion copy(*this);
    copy.Inflate(aMargin);
    return copy;
  }

  bool IsEmpty() const { return mBounds.IsEmpty(); }
  bool IsComplex() const { return GetNumRects() > 1; }
  bool IsEqual(const nsRegion& aRegion) const {
    if (!mBounds.IsEqualInterior(aRegion.mBounds)) {
      return false;
    }

    if (mBands.Length() != aRegion.mBands.Length()) {
      return false;
    }

    for (auto iter1 = mBands.begin(), iter2 = aRegion.mBands.begin();
         iter1 != mBands.end(); iter1++, iter2++) {
      if (iter1->top != iter2->top || iter1->bottom != iter2->bottom ||
          !iter1->EqualStrips(*iter2)) {
        return false;
      }
    }

    return true;
  }

  uint32_t GetNumRects() const {
    if (mBands.IsEmpty()) {
      return mBounds.IsEmpty() ? 0 : 1;
    }

    uint32_t rects = 0;

    for (const Band& band : mBands) {
      rects += band.mStrips.Length();
    }

    return rects;
  }
  const nsRect GetBounds() const { return mBounds.ToNSRect(); }
  const nsRectAbsolute GetAbsoluteBounds() const { return mBounds; }
  uint64_t Area() const;

  /**
   * Return this region scaled to a different appunits per pixel (APP) ratio.
   * This applies nsRect::ScaleToOtherAppUnitsRoundOut/In to each rect of the
   * region.
   * @param aFromAPP the APP to scale from
   * @param aToAPP the APP to scale to
   * @note this can turn an empty region into a non-empty region
   */
  [[nodiscard]] nsRegion ScaleToOtherAppUnitsRoundOut(int32_t aFromAPP,
                                                      int32_t aToAPP) const;
  [[nodiscard]] nsRegion ScaleToOtherAppUnitsRoundIn(int32_t aFromAPP,
                                                     int32_t aToAPP) const;
  nsRegion& ScaleRoundOut(float aXScale, float aYScale);
  nsRegion& ScaleInverseRoundOut(float aXScale, float aYScale);
  nsRegion& Transform(const mozilla::gfx::Matrix4x4& aTransform);
  nsIntRegion ScaleToOutsidePixels(float aXScale, float aYScale,
                                   nscoord aAppUnitsPerPixel) const;
  nsIntRegion ScaleToInsidePixels(float aXScale, float aYScale,
                                  nscoord aAppUnitsPerPixel) const;
  nsIntRegion ScaleToNearestPixels(float aXScale, float aYScale,
                                   nscoord aAppUnitsPerPixel) const;
  nsIntRegion ToOutsidePixels(nscoord aAppUnitsPerPixel) const;
  nsIntRegion ToNearestPixels(nscoord aAppUnitsPerPixel) const;

  /**
   * Gets the largest rectangle contained in the region.
   * @param aContainingRect if non-empty, we choose a rectangle that
   * maximizes the area intersecting with aContainingRect (and break ties by
   * then choosing the largest rectangle overall)
   */
  nsRect GetLargestRectangle(const nsRect& aContainingRect = nsRect()) const;

  /**
   * Make sure the region has at most aMaxRects by adding area to it
   * if necessary. The simplified region will be a superset of the
   * original region. The simplified region's bounding box will be
   * the same as for the current region.
   */
  void SimplifyOutward(uint32_t aMaxRects);
  /**
   * Simplify the region by adding at most aThreshold area between spans of
   * rects.  The simplified region will be a superset of the original region.
   * The simplified region's bounding box will be the same as for the current
   * region.
   */
  void SimplifyOutwardByArea(uint32_t aThreshold);
  /**
   * Make sure the region has at most aMaxRects by removing area from
   * it if necessary. The simplified region will be a subset of the
   * original region.
   */
  void SimplifyInward(uint32_t aMaxRects);

  /**
   * VisitEdges is a weird kind of function that we use for padding
   * out surfaces to prevent texture filtering artifacts.
   * It calls the visitFn callback for each of the exterior edges of
   * the regions. The top and bottom edges will be expanded 1 pixel
   * to the left and right if there's an outside corner. The order
   * the edges are visited is not guaranteed.
   *
   * visitFn has a side parameter that can be TOP,BOTTOM,LEFT,RIGHT
   * and specifies which kind of edge is being visited. x1, y1, x2, y2
   * are the coordinates of the line. (x1 == x2) || (y1 == y2)
   */
  typedef void (*visitFn)(void* closure, VisitSide side, int x1, int y1, int x2,
                          int y2);
  void VisitEdges(visitFn, void* closure) const;

  nsCString ToString() const;

  static inline pixman_box32_t RectToBox(const nsRect& aRect) {
    pixman_box32_t box = {aRect.X(), aRect.Y(), aRect.XMost(), aRect.YMost()};
    return box;
  }

  static inline pixman_box32_t RectToBox(const mozilla::gfx::IntRect& aRect) {
    pixman_box32_t box = {aRect.X(), aRect.Y(), aRect.XMost(), aRect.YMost()};
    return box;
  }

 private:
  nsIntRegion ToPixels(nscoord aAppUnitsPerPixel, bool aOutsidePixels) const;

  nsRegion& Copy(const nsRegion& aRegion) {
    mBounds = aRegion.mBounds;
    mBands = aRegion.mBands.Clone();
    return *this;
  }

  nsRegion& Copy(const nsRect& aRect) {
    mBands.Clear();
    mBounds = nsRectAbsolute::FromRect(aRect);
    return *this;
  }

  nsRegion& Copy(const nsRectAbsolute& aRect) {
    mBands.Clear();
    mBounds = aRect;
    return *this;
  }

  void EnsureSimplified() {
    if (mBands.Length() == 1 && mBands.begin()->mStrips.Length() == 1) {
      mBands.Clear();
    }
  }

  static inline nsRectAbsolute BoxToRect(const pixman_box32_t& aBox) {
    return nsRectAbsolute(aBox.x1, aBox.y1, aBox.x2, aBox.y2);
  }

  void AddRect(const nsRectAbsolute& aRect) {
#ifdef DEBUG_REGIONS
    class OperationStringGeneratorAddRect : public OperationStringGenerator {
     public:
      OperationStringGeneratorAddRect(nsRegion& aRegion,
                                      const nsRectAbsolute& aRect)
          : mRegion(&aRegion), mRegionCopy(aRegion), mRect(aRect) {
        aRegion.mCurrentOpGenerator = this;
      }
      virtual ~OperationStringGeneratorAddRect() {
        mRegion->mCurrentOpGenerator = nullptr;
      }

      virtual void OutputOp() override {
        std::stringstream stream;
        mRegionCopy.OutputToStream("r", stream);
        stream << "r.OrWith(nsRect(" << mRect.X() << ", " << mRect.Y() << ", "
               << mRect.Width() << ", " << mRect.Height() << "));\n";
        gfxCriticalError() << stream.str();
      }

     private:
      nsRegion* mRegion;
      nsRegion mRegionCopy;
      nsRectAbsolute mRect;
    };

    OperationStringGeneratorAddRect opGenerator(*this, aRect);
#endif
    if (aRect.IsEmpty()) {
      return;
    }

    if (mBands.IsEmpty()) {
      if (mBounds.IsEmpty()) {
        mBounds = aRect;
        return;
      } else if (mBounds.Contains(aRect)) {
        return;
      }

      mBands.AppendElement(Band(mBounds));
    }

    mBounds = aRect.UnsafeUnion(mBounds);

    size_t idx = 0;

    Strip strip(aRect.X(), aRect.XMost());
    Band remaining(aRect);

    while (idx != mBands.Length()) {
      if (mBands[idx].bottom <= remaining.top) {
        // This band lies wholly above aRect.
        idx++;
        continue;
      }

      if (remaining.top >= remaining.bottom) {
        AssertState();
        EnsureSimplified();
        return;
      }

      if (mBands[idx].top >= remaining.bottom) {
        // This band lies wholly below aRect.
        break;
      }

      if (mBands[idx].EqualStrips(remaining)) {
        mBands[idx].top = std::min(mBands[idx].top, remaining.top);
        // Nothing to do for this band. Just expand.
        remaining.top = mBands[idx].bottom;
        CompressBefore(idx);
        idx++;
        continue;
      }

      if (mBands[idx].top > remaining.top) {
        auto before = mBands.InsertElementAt(idx, remaining);
        before->bottom = mBands[idx + 1].top;
        remaining.top = before->bottom;
        CompressBefore(idx);
        idx++;
        CompressBefore(idx);
        continue;
      }

      if (mBands[idx].ContainsStrip(strip)) {
        remaining.top = mBands[idx].bottom;
        idx++;
        continue;
      }

      // mBands[idx].top <= remaining.top.

      if (mBands[idx].top < remaining.top) {
        auto before = mBands.InsertElementAt(idx, Band(mBands[idx]));
        before->bottom = remaining.top;
        idx++;
        mBands[idx].top = remaining.top;
        continue;
      }

      // mBands[idx].top == remaining.top
      if (mBands[idx].bottom > remaining.bottom) {
        auto below = mBands.InsertElementAt(idx + 1, Band(mBands[idx]));
        below->top = remaining.bottom;
        mBands[idx].bottom = remaining.bottom;
      }

      mBands[idx].InsertStrip(strip);
      CompressBefore(idx);
      remaining.top = mBands[idx].bottom;
      idx++;
      CompressBefore(idx);
    }

    if (remaining.top < remaining.bottom) {
      // We didn't find any bands that overlapped aRect.
      if (idx) {
        if (mBands[idx - 1].bottom == remaining.top &&
            mBands[idx - 1].EqualStrips(remaining)) {
          mBands[idx - 1].bottom = remaining.bottom;
          CompressBefore(idx);
          AssertState();
          EnsureSimplified();
          return;
        }
      }
      mBands.InsertElementAt(idx, remaining);
      idx++;
      CompressBefore(idx);
    } else {
      CompressBefore(idx);
    }

    AssertState();
    EnsureSimplified();
  }

  // Most callers could probably do this on the fly, if this ever shows up
  // in profiles we could optimize this.
  nsRectAbsolute CalculateBounds() const {
    if (mBands.IsEmpty()) {
      return mBounds;
    }

    int32_t top = mBands.begin()->top;
    int32_t bottom = mBands.LastElement().bottom;

    int32_t leftMost = mBands.begin()->mStrips.begin()->left;
    int32_t rightMost = mBands.begin()->mStrips.LastElement().right;
    for (const Band& band : mBands) {
      leftMost = std::min(leftMost, band.mStrips.begin()->left);
      rightMost = std::max(rightMost, band.mStrips.LastElement().right);
    }

    return nsRectAbsolute(leftMost, top, rightMost, bottom);
  }

  static uint32_t ComputeMergedAreaIncrease(const Band& aTopBand,
                                            const Band& aBottomBand);

  // Returns true if idx is now referring to the 'next' band
  bool CompressAdjacentBands(size_t& aIdx) {
    if ((aIdx + 1) < mBands.Length()) {
      if (mBands[aIdx + 1].top == mBands[aIdx].bottom &&
          mBands[aIdx + 1].EqualStrips(mBands[aIdx])) {
        mBands[aIdx].bottom = mBands[aIdx + 1].bottom;
        mBands.RemoveElementAt(aIdx + 1);
      }
    }
    if (aIdx) {
      if (mBands[aIdx - 1].bottom == mBands[aIdx].top &&
          mBands[aIdx].EqualStrips(mBands[aIdx - 1])) {
        mBands[aIdx - 1].bottom = mBands[aIdx].bottom;
        mBands.RemoveElementAt(aIdx);
        return true;
      }
    }
    return false;
  }

  void CompressBefore(size_t& aIdx) {
    if (aIdx && aIdx < mBands.Length()) {
      if (mBands[aIdx - 1].bottom == mBands[aIdx].top &&
          mBands[aIdx - 1].EqualStrips(mBands[aIdx])) {
        mBands[aIdx].top = mBands[aIdx - 1].top;
        mBands.RemoveElementAt(aIdx - 1);
        aIdx--;
      }
    }
  }

  BandArray mBands;
  // Considering we only ever OR with nsRects, the bounds should fit in an
  // nsRect as well.
  nsRectAbsolute mBounds;
#ifdef DEBUG_REGIONS
  friend class OperationStringGenerator;
  OperationStringGenerator* mCurrentOpGenerator;
#endif

 public:
  class RectIterator {
    const nsRegion& mRegion;
    typename BandArray::const_iterator mCurrentBand;
    typename StripArray::const_iterator mCurrentStrip;

   public:
    explicit RectIterator(const nsRegion& aRegion)
        : mRegion(aRegion),
          mCurrentBand(aRegion.mBands.begin())
#ifndef DEBUG
          ,
          mCurrentStrip(nullptr)
#endif
    {
      mIsDone = mRegion.mBounds.IsEmpty();
      if (mCurrentBand != aRegion.mBands.end()) {
        mCurrentStrip = mCurrentBand->mStrips.begin();
      }
    }

    bool Done() const { return mIsDone; }

    const nsRect Get() const {
      if (mRegion.mBands.IsEmpty()) {
        return mRegion.GetBounds();
      }
      return nsRect(mCurrentStrip->left, mCurrentBand->top,
                    mCurrentStrip->right - mCurrentStrip->left,
                    mCurrentBand->bottom - mCurrentBand->top);
    }

    const nsRectAbsolute GetAbsolute() const {
      if (mRegion.mBands.IsEmpty()) {
        return mRegion.mBounds;
      }
      return nsRectAbsolute(mCurrentStrip->left, mCurrentBand->top,
                            mCurrentStrip->right, mCurrentBand->bottom);
    }

    void Next() {
      if (mRegion.mBands.IsEmpty()) {
        mIsDone = true;
        return;
      }

      mCurrentStrip++;
      if (mCurrentStrip == mCurrentBand->mStrips.end()) {
        mCurrentBand++;
        if (mCurrentBand != mRegion.mBands.end()) {
          mCurrentStrip = mCurrentBand->mStrips.begin();
        } else {
          mIsDone = true;
        }
      }
    }

    bool mIsDone;
  };

  RectIterator RectIter() const { return RectIterator(*this); }
};

namespace mozilla {
namespace gfx {

/**
 * BaseIntRegions use int32_t coordinates.
 */
template <typename Derived, typename Rect, typename Point, typename Margin>
class BaseIntRegion {
  friend class ::nsRegion;

  // Give access to all specializations of IntRegionTyped, not just ones that
  // derive from this specialization of BaseIntRegion.
  template <typename units>
  friend class IntRegionTyped;

 public:
  typedef Rect RectType;
  typedef Point PointType;
  typedef Margin MarginType;

  BaseIntRegion() = default;
  MOZ_IMPLICIT BaseIntRegion(const Rect& aRect) : mImpl(ToRect(aRect)) {}
  explicit BaseIntRegion(mozilla::gfx::ArrayView<pixman_box32_t> aRects)
      : mImpl(aRects) {}
  BaseIntRegion(const BaseIntRegion& aRegion) : mImpl(aRegion.mImpl) {}
  BaseIntRegion(BaseIntRegion&& aRegion) : mImpl(std::move(aRegion.mImpl)) {}
  Derived& operator=(const Rect& aRect) {
    mImpl = ToRect(aRect);
    return This();
  }
  Derived& operator=(const Derived& aRegion) {
    mImpl = aRegion.mImpl;
    return This();
  }
  Derived& operator=(Derived&& aRegion) {
    mImpl = std::move(aRegion.mImpl);
    return This();
  }

  bool operator==(const Derived& aRgn) const { return IsEqual(aRgn); }
  bool operator!=(const Derived& aRgn) const { return !(*this == aRgn); }

  friend std::ostream& operator<<(std::ostream& stream, const Derived& m) {
    return stream << m.mImpl;
  }

  void AndWith(const Derived& aOther) { And(This(), aOther); }
  void AndWith(const Rect& aOther) { And(This(), aOther); }
  Derived& And(const Derived& aRgn1, const Derived& aRgn2) {
    mImpl.And(aRgn1.mImpl, aRgn2.mImpl);
    return This();
  }
  Derived& And(const Derived& aRegion, const Rect& aRect) {
    mImpl.And(aRegion.mImpl, ToRect(aRect));
    return This();
  }
  Derived& And(const Rect& aRect, const Derived& aRegion) {
    return And(aRegion, aRect);
  }
  Derived& And(const Rect& aRect1, const Rect& aRect2) {
    Rect TmpRect;

    TmpRect.IntersectRect(aRect1, aRect2);
    mImpl = ToRect(TmpRect);
    return This();
  }

  Derived& OrWith(const Derived& aOther) { return Or(This(), aOther); }
  Derived& OrWith(const Rect& aOther) { return Or(This(), aOther); }
  Derived& Or(const Derived& aRgn1, const Derived& aRgn2) {
    mImpl.Or(aRgn1.mImpl, aRgn2.mImpl);
    return This();
  }
  Derived& Or(const Derived& aRegion, const Rect& aRect) {
    mImpl.Or(aRegion.mImpl, ToRect(aRect));
    return This();
  }
  Derived& Or(const Rect& aRect, const Derived& aRegion) {
    return Or(aRegion, aRect);
  }
  Derived& Or(const Rect& aRect1, const Rect& aRect2) {
    mImpl = ToRect(aRect1);
    return Or(This(), aRect2);
  }

  Derived& XorWith(const Derived& aOther) { return Xor(This(), aOther); }
  Derived& XorWith(const Rect& aOther) { return Xor(This(), aOther); }
  Derived& Xor(const Derived& aRgn1, const Derived& aRgn2) {
    mImpl.Xor(aRgn1.mImpl, aRgn2.mImpl);
    return This();
  }
  Derived& Xor(const Derived& aRegion, const Rect& aRect) {
    mImpl.Xor(aRegion.mImpl, ToRect(aRect));
    return This();
  }
  Derived& Xor(const Rect& aRect, const Derived& aRegion) {
    return Xor(aRegion, aRect);
  }
  Derived& Xor(const Rect& aRect1, const Rect& aRect2) {
    mImpl = ToRect(aRect1);
    return Xor(This(), aRect2);
  }

  Derived& SubOut(const Derived& aOther) { return Sub(This(), aOther); }
  Derived& SubOut(const Rect& aOther) { return Sub(This(), aOther); }
  Derived& Sub(const Derived& aRgn1, const Derived& aRgn2) {
    mImpl.Sub(aRgn1.mImpl, aRgn2.mImpl);
    return This();
  }
  Derived& Sub(const Derived& aRegion, const Rect& aRect) {
    mImpl.Sub(aRegion.mImpl, ToRect(aRect));
    return This();
  }
  Derived& Sub(const Rect& aRect, const Derived& aRegion) {
    return Sub(Derived(aRect), aRegion);
  }
  Derived& Sub(const Rect& aRect1, const Rect& aRect2) {
    mImpl = ToRect(aRect1);
    return Sub(This(), aRect2);
  }

  /**
   * Returns true iff the given point is inside the region. A region
   * created from a rect (x=0, y=0, w=100, h=100) will NOT contain
   * the point x=100, y=100.
   */
  bool Contains(int aX, int aY) const { return mImpl.Contains(aX, aY); }
  bool Contains(const Point& aPoint) const {
    return mImpl.Contains(aPoint.x, aPoint.y);
  }
  bool Contains(const Rect& aRect) const {
    return mImpl.Contains(ToRect(aRect));
  }
  bool Contains(const Derived& aRgn) const {
    return mImpl.Contains(aRgn.mImpl);
  }
  bool Intersects(const Rect& aRect) const {
    return mImpl.Intersects(ToRect(aRect));
  }

  void MoveBy(int32_t aXOffset, int32_t aYOffset) {
    MoveBy(Point(aXOffset, aYOffset));
  }
  void MoveBy(Point aPt) { mImpl.MoveBy(aPt.X(), aPt.Y()); }
  Derived MovedBy(int32_t aXOffset, int32_t aYOffset) const {
    return MovedBy(Point(aXOffset, aYOffset));
  }
  Derived MovedBy(const Point& aPt) const {
    Derived copy(This());
    copy.MoveBy(aPt);
    return copy;
  }

  Derived Intersect(const Derived& aOther) const {
    Derived intersection;
    intersection.And(This(), aOther);
    return intersection;
  }

  void Inflate(const Margin& aMargin) {
    mImpl.Inflate(
        nsMargin(aMargin.top, aMargin.right, aMargin.bottom, aMargin.left));
  }
  Derived Inflated(const Margin& aMargin) const {
    Derived copy(This());
    copy.Inflate(aMargin);
    return copy;
  }

  void SetEmpty() { mImpl.SetEmpty(); }

  bool IsEmpty() const { return mImpl.IsEmpty(); }
  bool IsComplex() const { return mImpl.IsComplex(); }
  bool IsEqual(const Derived& aRegion) const {
    return mImpl.IsEqual(aRegion.mImpl);
  }
  uint32_t GetNumRects() const { return mImpl.GetNumRects(); }
  Rect GetBounds() const { return FromRect(mImpl.GetBounds()); }
  uint64_t Area() const { return mImpl.Area(); }
  nsRegion ToAppUnits(nscoord aAppUnitsPerPixel) const {
    nsRegion result;
    for (auto iter = RectIterator(*this); !iter.Done(); iter.Next()) {
      nsRect appRect = ::ToAppUnits(iter.Get(), aAppUnitsPerPixel);
      result.Or(result, appRect);
    }
    return result;
  }
  Rect GetLargestRectangle(const Rect& aContainingRect = Rect()) const {
    return FromRect(mImpl.GetLargestRectangle(ToRect(aContainingRect)));
  }

  Derived& ScaleRoundOut(float aXScale, float aYScale) {
    mImpl.ScaleRoundOut(aXScale, aYScale);
    return This();
  }

  Derived& ScaleInverseRoundOut(float aXScale, float aYScale) {
    mImpl.ScaleInverseRoundOut(aXScale, aYScale);
    return This();
  }

  // Prefer using TransformBy(matrix, region) from UnitTransforms.h,
  // as applying the transform should typically change the unit system.
  // TODO(botond): Move this to IntRegionTyped and disable it for
  //               unit != UnknownUnits.
  Derived& Transform(const mozilla::gfx::Matrix4x4& aTransform) {
    mImpl.Transform(aTransform);
    return This();
  }

  /**
   * Make sure the region has at most aMaxRects by adding area to it
   * if necessary. The simplified region will be a superset of the
   * original region. The simplified region's bounding box will be
   * the same as for the current region.
   */
  void SimplifyOutward(uint32_t aMaxRects) { mImpl.SimplifyOutward(aMaxRects); }
  void SimplifyOutwardByArea(uint32_t aThreshold) {
    mImpl.SimplifyOutwardByArea(aThreshold);
  }
  /**
   * Make sure the region has at most aMaxRects by removing area from
   * it if necessary. The simplified region will be a subset of the
   * original region.
   */
  void SimplifyInward(uint32_t aMaxRects) { mImpl.SimplifyInward(aMaxRects); }

  typedef void (*visitFn)(void* closure, VisitSide side, int x1, int y1, int x2,
                          int y2);
  void VisitEdges(visitFn visit, void* closure) const {
    mImpl.VisitEdges(visit, closure);
  }

  nsCString ToString() const { return mImpl.ToString(); }

  class RectIterator {
    nsRegion::RectIterator mImpl;  // The underlying iterator.
    mutable Rect mTmp;             // The most recently gotten rectangle.

   public:
    explicit RectIterator(const BaseIntRegion& aRegion)
        : mImpl(aRegion.mImpl) {}

    bool Done() const { return mImpl.Done(); }

    const Rect& Get() const {
      mTmp = FromRect(mImpl.Get());
      return mTmp;
    }

    void Next() { mImpl.Next(); }
  };

  RectIterator RectIter() const { return RectIterator(*this); }

 protected:
  // Expose enough to derived classes from them to define conversions
  // between different types of BaseIntRegions.
  explicit BaseIntRegion(const nsRegion& aImpl) : mImpl(aImpl) {}
  const nsRegion& Impl() const { return mImpl; }

 private:
  nsRegion mImpl;

  static nsRect ToRect(const Rect& aRect) {
    return nsRect(aRect.X(), aRect.Y(), aRect.Width(), aRect.Height());
  }
  static Rect FromRect(const nsRect& aRect) {
    return Rect(aRect.X(), aRect.Y(), aRect.Width(), aRect.Height());
  }

  Derived& This() { return *static_cast<Derived*>(this); }
  const Derived& This() const { return *static_cast<const Derived*>(this); }
};

template <class units>
class IntRegionTyped
    : public BaseIntRegion<IntRegionTyped<units>, IntRectTyped<units>,
                           IntPointTyped<units>, IntMarginTyped<units>> {
  typedef BaseIntRegion<IntRegionTyped<units>, IntRectTyped<units>,
                        IntPointTyped<units>, IntMarginTyped<units>>
      Super;

  // Make other specializations of IntRegionTyped friends.
  template <typename OtherUnits>
  friend class IntRegionTyped;

  static_assert(IsPixel<units>::value,
                "'units' must be a coordinate system tag");

 public:
  typedef IntRectTyped<units> RectType;
  typedef IntPointTyped<units> PointType;
  typedef IntMarginTyped<units> MarginType;

  // Forward constructors.
  IntRegionTyped() = default;
  MOZ_IMPLICIT IntRegionTyped(const IntRectTyped<units>& aRect)
      : Super(aRect) {}
  IntRegionTyped(const IntRegionTyped& aRegion) : Super(aRegion) {}
  explicit IntRegionTyped(mozilla::gfx::ArrayView<pixman_box32_t> aRects)
      : Super(aRects) {}
  IntRegionTyped(IntRegionTyped&& aRegion) : Super(std::move(aRegion)) {}

  // Assignment operators need to be forwarded as well, otherwise the compiler
  // will declare deleted ones.
  IntRegionTyped& operator=(const IntRegionTyped& aRegion) {
    return Super::operator=(aRegion);
  }
  IntRegionTyped& operator=(IntRegionTyped&& aRegion) {
    return Super::operator=(std::move(aRegion));
  }

  static IntRegionTyped FromUnknownRegion(const IntRegion& aRegion) {
    return IntRegionTyped(aRegion.Impl());
  }
  IntRegion ToUnknownRegion() const {
    // Need |this->| because Impl() is defined in a dependent base class.
    return IntRegion(this->Impl());
  }

 private:
  // This is deliberately private, so calling code uses FromUnknownRegion().
  explicit IntRegionTyped(const nsRegion& aRegion) : Super(aRegion) {}
};

}  // namespace gfx
}  // namespace mozilla

typedef mozilla::gfx::IntRegion nsIntRegion;

#endif