summaryrefslogtreecommitdiff
path: root/src/mongo/db/storage/key_string.cpp
blob: 7ff962f5c4588da2a8de11527eeb7cddf9aa441b (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
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */


#include "mongo/platform/basic.h"

#include "mongo/db/storage/key_string.h"

#include <cmath>
#include <type_traits>

#include "mongo/base/data_cursor.h"
#include "mongo/base/data_view.h"
#include "mongo/bson/bson_depth.h"
#include "mongo/db/exec/sbe/values/value_builder.h"
#include "mongo/logv2/log.h"
#include "mongo/platform/bits.h"
#include "mongo/platform/strnlen.h"
#include "mongo/util/decimal_counter.h"
#include "mongo/util/hex.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kStorage


#define keyStringAssert(msgid, msg, expr) \
    uassert(msgid, str::stream() << "KeyString format error: " << msg, expr)
#define keyStringAsserted(msgid, msg) \
    uasserted(msgid, str::stream() << "KeyString format error: " << msg)

namespace mongo {

using std::string;

template class StackBufBuilderBase<KeyString::TypeBits::SmallStackSize>;

namespace KeyString {


namespace {

namespace CType {
// canonical types namespace. (would be enum class CType: uint8_t in C++11)
// Note 0-9 and 246-255 are disallowed and reserved for value encodings.
// For types that encode value information in the ctype byte, the value in this list is
// the "generic" one to be used to represent all values of that ctype, such as in the
// encoding of fields in Objects.
const uint8_t kMinKey = 10;
const uint8_t kUndefined = 15;
const uint8_t kNullish = 20;
const uint8_t kNumeric = 30;
const uint8_t kStringLike = 60;
const uint8_t kObject = 70;
const uint8_t kArray = 80;
const uint8_t kBinData = 90;
const uint8_t kOID = 100;
const uint8_t kBool = 110;
const uint8_t kDate = 120;
const uint8_t kTimestamp = 130;
const uint8_t kRegEx = 140;
const uint8_t kDBRef = 150;
const uint8_t kCode = 160;
const uint8_t kCodeWithScope = 170;
const uint8_t kMaxKey = 240;

// These are ordered by the numeric value of the values encoded in each format.
// Therefore each format can be considered independently without considering
// cross-format comparisons.
const uint8_t kNumericNaN = kNumeric + 0;
const uint8_t kNumericNegativeLargeMagnitude = kNumeric + 1;  // <= -2**63 including -Inf
const uint8_t kNumericNegative8ByteInt = kNumeric + 2;
const uint8_t kNumericNegative7ByteInt = kNumeric + 3;
const uint8_t kNumericNegative6ByteInt = kNumeric + 4;
const uint8_t kNumericNegative5ByteInt = kNumeric + 5;
const uint8_t kNumericNegative4ByteInt = kNumeric + 6;
const uint8_t kNumericNegative3ByteInt = kNumeric + 7;
const uint8_t kNumericNegative2ByteInt = kNumeric + 8;
const uint8_t kNumericNegative1ByteInt = kNumeric + 9;
const uint8_t kNumericNegativeSmallMagnitude = kNumeric + 10;  // between 0 and -1 exclusive
const uint8_t kNumericZero = kNumeric + 11;
const uint8_t kNumericPositiveSmallMagnitude = kNumeric + 12;  // between 0 and 1 exclusive
const uint8_t kNumericPositive1ByteInt = kNumeric + 13;
const uint8_t kNumericPositive2ByteInt = kNumeric + 14;
const uint8_t kNumericPositive3ByteInt = kNumeric + 15;
const uint8_t kNumericPositive4ByteInt = kNumeric + 16;
const uint8_t kNumericPositive5ByteInt = kNumeric + 17;
const uint8_t kNumericPositive6ByteInt = kNumeric + 18;
const uint8_t kNumericPositive7ByteInt = kNumeric + 19;
const uint8_t kNumericPositive8ByteInt = kNumeric + 20;
const uint8_t kNumericPositiveLargeMagnitude = kNumeric + 21;  // >= 2**63 including +Inf
MONGO_STATIC_ASSERT(kNumericPositiveLargeMagnitude < kStringLike);

const uint8_t kBoolFalse = kBool + 0;
const uint8_t kBoolTrue = kBool + 1;
MONGO_STATIC_ASSERT(kBoolTrue < kDate);

std::string toString(uint8_t ctype) {
    switch (ctype) {
        case kMinKey:
            return "MinKey";
        case kUndefined:
            return "Undefined";
        case kNullish:
            return "Nullish";
        case kStringLike:
            return "StringLike";
        case kObject:
            return "Object";
        case kArray:
            return "Array";
        case kBinData:
            return "BinData";
        case kOID:
            return "OID";
        case kDate:
            return "Date";
        case kTimestamp:
            return "Timestamp";
        case kRegEx:
            return "RegEx";
        case kDBRef:
            return "DBRef";
        case kCode:
            return "Code";
        case kCodeWithScope:
            return "CodeWithScope";
        case kMaxKey:
            return "MaxKey";
        case kNumericNaN:
            return "NumericNaN";
        case kNumericNegativeLargeMagnitude:
            return "NumericNegativeLargeMagnitude";
        case kNumericNegative8ByteInt:
            return "NumericNegative8ByteInt";
        case kNumericNegative7ByteInt:
            return "NumericNegative7ByteInt";
        case kNumericNegative6ByteInt:
            return "NumericNegative6ByteInt";
        case kNumericNegative5ByteInt:
            return "NumericNegative5ByteInt";
        case kNumericNegative4ByteInt:
            return "NumericNegative4ByteInt";
        case kNumericNegative3ByteInt:
            return "NumericNegative3ByteInt";
        case kNumericNegative2ByteInt:
            return "NumericNegative2ByteInt";
        case kNumericNegative1ByteInt:
            return "NumericNegative1ByteInt";
        case kNumericNegativeSmallMagnitude:
            return "NumericNegativeSmallMagnitude";
        case kNumericZero:
            return "NumericZero";
        case kNumericPositiveSmallMagnitude:
            return "NumericPositiveSmallMagnitude";
        case kNumericPositive1ByteInt:
            return "NumericPositive1ByteInt";
        case kNumericPositive2ByteInt:
            return "NumericPositive2ByteInt";
        case kNumericPositive3ByteInt:
            return "NumericPositive3ByteInt";
        case kNumericPositive4ByteInt:
            return "NumericPositive4ByteInt";
        case kNumericPositive5ByteInt:
            return "NumericPositive5ByteInt";
        case kNumericPositive6ByteInt:
            return "NumericPositive6ByteInt";
        case kNumericPositive7ByteInt:
            return "NumericPositive7ByteInt";
        case kNumericPositive8ByteInt:
            return "NumericPositive8ByteInt";
        case kNumericPositiveLargeMagnitude:
            return "NumericPositiveLargeMagnitude";
        case kBoolFalse:
            return "BoolFalse";
        case kBoolTrue:
            return "BoolTrue";
        default:
            return fmt::format("unknown {}", ctype);
    }
    MONGO_UNREACHABLE;
}

size_t numBytesForInt(uint8_t ctype) {
    if (ctype >= kNumericPositive1ByteInt) {
        dassert(ctype <= kNumericPositive8ByteInt);
        return ctype - kNumericPositive1ByteInt + 1;
    }

    dassert(ctype <= kNumericNegative1ByteInt);
    dassert(ctype >= kNumericNegative8ByteInt);
    return kNumericNegative1ByteInt - ctype + 1;
}
}  // namespace CType

uint8_t bsonTypeToGenericKeyStringType(BSONType type) {
    switch (type) {
        case MinKey:
            return CType::kMinKey;

        case EOO:
        case jstNULL:
            return CType::kNullish;

        case Undefined:
            return CType::kUndefined;

        case NumberDecimal:
        case NumberDouble:
        case NumberInt:
        case NumberLong:
            return CType::kNumeric;

        case mongo::String:
        case Symbol:
            return CType::kStringLike;

        case Object:
            return CType::kObject;
        case Array:
            return CType::kArray;
        case BinData:
            return CType::kBinData;
        case jstOID:
            return CType::kOID;
        case Bool:
            return CType::kBool;
        case Date:
            return CType::kDate;
        case bsonTimestamp:
            return CType::kTimestamp;
        case RegEx:
            return CType::kRegEx;
        case DBRef:
            return CType::kDBRef;

        case Code:
            return CType::kCode;
        case CodeWScope:
            return CType::kCodeWithScope;

        case MaxKey:
            return CType::kMaxKey;
    }
    MONGO_UNREACHABLE;
}

// Doubles smaller than this store only a single bit indicating a decimal continuation follows.
const double kTiniestDoubleWith2BitDCM = std::ldexp(1, -255);

// Amount to add to exponent of doubles tinier than kTiniestDoubleWith2BitDCM to avoid subnormals.
const int kTinyDoubleExponentShift = 256;

// Amount to multiply tiny doubles to perform a shift of the exponent by
// kSmallMagnitudeExponentShift.
const double kTinyDoubleExponentUpshiftFactor = std::ldexp(1, kTinyDoubleExponentShift);

// Amount to multiply scaled tiny doubles by to recover the unscaled value.
const double kTinyDoubleExponentDownshiftFactor = std::ldexp(1, -kTinyDoubleExponentShift);

// An underestimate of 2**256.
const Decimal128 kTinyDoubleExponentUpshiftFactorAsDecimal(std::ldexp(1, kTinyDoubleExponentShift),
                                                           Decimal128::kRoundTo34Digits,
                                                           Decimal128::kRoundTowardZero);

// An underestimate of 2**(-256).
const Decimal128 kTinyDoubleExponentDownshiftFactorAsDecimal(std::ldexp(1,
                                                                        -kTinyDoubleExponentShift),
                                                             Decimal128::kRoundTo34Digits,
                                                             Decimal128::kRoundTowardZero);

// First double that isn't an int64.
const double kMinLargeDouble = 1ULL << 63;

// Integers larger than this may not be representable as doubles.
const double kMaxIntForDouble = 1ULL << 53;

// Factors for scaling a double by powers of 256 to do a logical shift left of x bytes.
const double kPow256[] = {1.0,                                             // 2**0
                          1.0 * 256,                                       // 2**8
                          1.0 * 256 * 256,                                 // 2**16
                          1.0 * 256 * 256 * 256,                           // 2**24
                          1.0 * 256 * 256 * 256 * 256,                     // 2**32
                          1.0 * 256 * 256 * 256 * 256 * 256,               // 2**40
                          1.0 * 256 * 256 * 256 * 256 * 256 * 256,         // 2**48
                          1.0 * 256 * 256 * 256 * 256 * 256 * 256 * 256};  // 2**56
// Factors for scaling a double by negative powers of 256 to do a logical shift right of x bytes.
const double kInvPow256[] = {1.0,                                             // 2**0
                             1.0 / 256,                                       // 2**(-8)
                             1.0 / 256 / 256,                                 // 2**(-16)
                             1.0 / 256 / 256 / 256,                           // 2**(-24)
                             1.0 / 256 / 256 / 256 / 256,                     // 2**(-32)
                             1.0 / 256 / 256 / 256 / 256 / 256,               // 2**(-40)
                             1.0 / 256 / 256 / 256 / 256 / 256 / 256,         // 2**(-48)
                             1.0 / 256 / 256 / 256 / 256 / 256 / 256 / 256};  // 2**(-56)

const uint8_t kEnd = 0x4;

// These overlay with CType or kEnd bytes and therefor must be less/greater than all of
// them (and their inverses). They also can't equal 0 or 255 since that would collide with
// the encoding of NUL bytes in strings as "\x00\xff".
const uint8_t kLess = 1;
const uint8_t kGreater = 254;

}  // namespace

// some utility functions
namespace {

void memcpy_flipBits(void* dst, const void* src, size_t bytes) {
    const char* input = static_cast<const char*>(src);
    char* output = static_cast<char*>(dst);
    const char* const end = input + bytes;
    while (input != end) {
        *output++ = ~(*input++);
    }
}

template <typename T>
T readType(BufReader* reader, bool inverted) {
    MONGO_STATIC_ASSERT(std::is_integral<T>::value);
    T t = ConstDataView(static_cast<const char*>(reader->skip(sizeof(T)))).read<T>();
    if (inverted)
        return ~t;
    return t;
}

StringData readCString(BufReader* reader) {
    const char* start = static_cast<const char*>(reader->pos());
    const char* end = static_cast<const char*>(memchr(start, 0x0, reader->remaining()));
    keyStringAssert(50816, "Failed to find null terminator in string.", end);
    size_t actualBytes = end - start;
    reader->skip(1 + actualBytes);
    return StringData(start, actualBytes);
}

/**
 * scratch must be empty when passed in. It will be used if there is a NUL byte in the
 * output string. In that case the returned StringData will point into scratch, otherwise
 * it will point directly into the input buffer.
 */
StringData readCStringWithNuls(BufReader* reader, std::string* scratch) {
    const StringData initial = readCString(reader);
    if (!reader->remaining() || reader->peek<unsigned char>() != 0xFF)
        return initial;  // Don't alloc or copy for simple case with no NUL bytes.

    scratch->append(initial.rawData(), initial.size());
    while (reader->remaining() && reader->peek<unsigned char>() == 0xFF) {
        // Each time we enter this loop it means we hit a NUL byte encoded as "\x00\xFF".
        *scratch += '\0';
        reader->skip(1);

        const StringData nextPart = readCString(reader);
        scratch->append(nextPart.rawData(), nextPart.size());
    }

    return *scratch;
}

string readInvertedCString(BufReader* reader) {
    const char* start = static_cast<const char*>(reader->pos());
    const char* end = static_cast<const char*>(memchr(start, 0xFF, reader->remaining()));
    keyStringAssert(50817, "Failed to find '0xFF' in inverted string.", end);
    size_t actualBytes = end - start;
    string s(start, actualBytes);
    for (size_t i = 0; i < s.size(); i++) {
        s[i] = ~s[i];
    }
    reader->skip(1 + actualBytes);
    return s;
}

string readInvertedCStringWithNuls(BufReader* reader) {
    std::string out;
    bool firstPass = true;
    do {
        if (firstPass) {
            firstPass = false;
        } else {
            // If this isn't our first pass through the loop it means we hit an NUL byte
            // encoded as "\xFF\00" in our inverted string.
            reader->skip(1);
            out += '\xFF';  // will be flipped to '\0' with rest of out before returning.
        }

        const char* start = static_cast<const char*>(reader->pos());
        const char* end = static_cast<const char*>(memchr(start, 0xFF, reader->remaining()));
        keyStringAssert(50820, "Failed to find '0xFF' in inverted string.", end);
        size_t actualBytes = end - start;

        out.append(start, actualBytes);
        reader->skip(1 + actualBytes);
    } while (reader->peek<unsigned char>() == 0x00);

    for (size_t i = 0; i < out.size(); i++) {
        out[i] = ~out[i];
    }

    return out;
}
}  // namespace

template <class BufferT>
void BuilderBase<BufferT>::resetToKey(const BSONObj& obj, Ordering ord, const RecordId& recordId) {
    resetToEmpty(ord);
    _appendAllElementsForIndexing(obj, Discriminator::kInclusive);
    appendRecordId(recordId);
}

template <class BufferT>
void BuilderBase<BufferT>::resetToKey(const BSONObj& obj,
                                      Ordering ord,
                                      Discriminator discriminator) {
    resetToEmpty(ord, discriminator);
    _appendAllElementsForIndexing(obj, discriminator);
}

template <class BufferT>
void BuilderBase<BufferT>::appendBSONElement(const BSONElement& elem, const StringTransformFn& f) {
    _verifyAppendingState();
    _appendBsonValue(elem, _shouldInvertOnAppend(), nullptr, f);
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendBool(bool val) {
    _verifyAppendingState();
    _appendBool(val, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendString(StringData val, const StringTransformFn& f) {
    _verifyAppendingState();
    _appendString(val, _shouldInvertOnAppend(), f);
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendSymbol(StringData val) {
    _verifyAppendingState();
    _appendSymbol(val, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendCode(StringData val) {
    _verifyAppendingState();
    _appendCode(val, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendNumberDouble(double num) {
    _verifyAppendingState();
    _appendNumberDouble(num, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendNumberLong(long long num) {
    _verifyAppendingState();
    _appendNumberLong(num, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendNumberInt(int num) {
    _verifyAppendingState();
    _appendNumberInt(num, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendNumberDecimal(Decimal128 num) {
    _verifyAppendingState();
    _appendNumberDecimal(num, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendNull() {
    _verifyAppendingState();
    _append(CType::kNullish, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendUndefined() {
    _verifyAppendingState();
    _append(CType::kUndefined, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendCodeWString(const BSONCodeWScope& val) {
    _verifyAppendingState();
    _appendCodeWString(val, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendBinData(const BSONBinData& data) {
    _verifyAppendingState();
    _appendBinData(data, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendRegex(const BSONRegEx& val) {
    _verifyAppendingState();
    _appendRegex(val, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendSetAsArray(const BSONElementSet& set, const StringTransformFn& f) {
    _verifyAppendingState();
    _appendSetAsArray(set, _shouldInvertOnAppend(), nullptr);
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendOID(OID oid) {
    _verifyAppendingState();
    _appendOID(oid, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendDate(Date_t date) {
    _verifyAppendingState();
    _appendDate(date, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendTimestamp(Timestamp val) {
    _verifyAppendingState();
    _appendTimestamp(val, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendBytes(const void* source, size_t bytes) {
    _verifyAppendingState();
    _appendBytes(source, bytes, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendDBRef(const BSONDBRef& val) {
    _verifyAppendingState();
    _appendDBRef(val, _shouldInvertOnAppend());
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendObject(const BSONObj& val, const StringTransformFn& f) {
    _verifyAppendingState();
    _appendObject(val, _shouldInvertOnAppend(), f);
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendArray(const BSONArray& val, const StringTransformFn& f) {
    _verifyAppendingState();
    _appendArray(val, _shouldInvertOnAppend(), f);
    _elemCount++;
}

template <class BufferT>
void BuilderBase<BufferT>::appendDiscriminator(const Discriminator discriminator) {
    // The discriminator forces this KeyString to compare Less/Greater than any KeyString with
    // the same prefix of keys. As an example, this can be used to land on the first key in the
    // index with the value "a" regardless of the RecordId. In compound indexes it can use a
    // prefix of the full key to ignore the later keys.
    switch (discriminator) {
        case Discriminator::kExclusiveBefore:
            _append(kLess, false);
            break;
        case Discriminator::kExclusiveAfter:
            _append(kGreater, false);
            break;
        case Discriminator::kInclusive:
            break;  // No discriminator byte.
    }

    // TODO (SERVER-43178): consider omitting kEnd when using a discriminator byte. It is not a
    // storage format change since keystrings with discriminators are not allowed to be stored.
    _appendEnd();
}
// ----------------------------------------------------------------------
// -----------   APPEND CODE  -------------------------------------------
// ----------------------------------------------------------------------

template <class BufferT>
void BuilderBase<BufferT>::_appendEnd() {
    _transition(BuildState::kEndAdded);
    _append(kEnd, false);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendAllElementsForIndexing(const BSONObj& obj,
                                                         Discriminator discriminator) {
    _transition(BuildState::kAppendingBSONElements);
    BSONObjIterator it(obj);
    while (auto elem = it.next()) {
        appendBSONElement(elem);
        dassert(elem.fieldNameSize() < 3);  // fieldNameSize includes the NUL
    }
    appendDiscriminator(discriminator);
}

template <class BufferT>
void BuilderBase<BufferT>::appendRecordId(const RecordId& loc) {
    _doneAppending();
    _transition(BuildState::kAppendedRecordID);
    loc.withFormat([](RecordId::Null n) { invariant(false); },
                   [&](int64_t rid) { _appendRecordIdLong(rid); },
                   [&](const char* str, int size) { _appendRecordIdStr(str, size); });
}

template <class BufferT>
void BuilderBase<BufferT>::_appendRecordIdLong(int64_t val) {
    // The RecordId encoding must be able to determine the full length starting from the last
    // byte, without knowing where the first byte is since it is stored at the end of a
    // KeyString, and we need to be able to read the RecordId without decoding the whole thing.

    // This encoding places a number (N) between 0 and 7 in both the high 3 bits of the first
    // byte and the low 3 bits of the last byte. This is the number of bytes between the first
    // and last byte (ie total bytes is N + 2). The remaining bits of the first and last bytes
    // are combined with the bits of the in-between bytes to store the 64-bit RecordId in
    // big-endian order. This does not encode negative RecordIds to give maximum space to
    // positive RecordIds which are the only ones that are allowed to be stored in an index.

    int64_t raw = val;
    if (raw < 0) {
        // Note: we encode RecordId::minLong() and RecordId() the same which is ok, as they
        // are never stored so they will never be compared to each other.
        invariant(raw == RecordId::minLong().getLong());
        raw = 0;
    }
    const uint64_t value = static_cast<uint64_t>(raw);
    const int bitsNeeded = 64 - countLeadingZeros64(raw);
    const int extraBytesNeeded =
        bitsNeeded <= 10 ? 0 : ((bitsNeeded - 10) + 7) / 8;  // ceil((bitsNeeded - 10) / 8)

    // extraBytesNeeded must fit in 3 bits.
    dassert(extraBytesNeeded >= 0 && extraBytesNeeded < 8);

    // firstByte combines highest 5 bits of value with extraBytesNeeded.
    const uint8_t firstByte =
        uint8_t((extraBytesNeeded << 5) | (value >> (5 + (extraBytesNeeded * 8))));
    // lastByte combines lowest 5 bits of value with extraBytesNeeded.
    const uint8_t lastByte = uint8_t((value << 3) | extraBytesNeeded);

    // RecordIds are never appended inverted.
    _append(firstByte, false);
    if (extraBytesNeeded) {
        const uint64_t extraBytes = endian::nativeToBig(value >> 5);
        // Only using the low-order extraBytesNeeded bytes of extraBytes.
        _appendBytes(reinterpret_cast<const char*>(&extraBytes) + sizeof(extraBytes) -
                         extraBytesNeeded,
                     extraBytesNeeded,
                     false);
    }
    _append(lastByte, false);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendRecordIdStr(const char* str, int size) {
    // Append the RecordId binary string as-is, then append the encoded binary string size.
    // The binary string size is encoded in 7-bit increments over one or more size bytes.
    // The 8th bit of a size byte is a continuation bit that is set on all size bytes except
    // the leftmost (i.e. the last) one. This allows decoding the size right-to-left until there are
    // no more size bytes remaining with continuation bits. See decodeRecordIdStrAtEnd for the
    // decoding algorithm. This 7-bit size encoding ensures backward compatibility with 5.0, which
    // supports RecordId binary strings up to 127 bytes, or what fits in 7 bits.

    invariant(size > 0);
    invariant(size <= RecordId::kBigStrMaxSize);

    const bool invert = false;

    // Encode size
    uint8_t encodedSize[kRecordIdStrEncodedSizeMaxBytes] = {0};
    int highestSizeByte = 0;
    bool highestSizeByteSet = false;

    for (int sizeBytes = kRecordIdStrEncodedSizeMaxBytes - 1; sizeBytes >= 0; sizeBytes--) {
        encodedSize[sizeBytes] = (size >> (sizeBytes * 7)) & 0x7F;
        if (encodedSize[sizeBytes] && highestSizeByteSet == false) {
            highestSizeByteSet = true;
            highestSizeByte = sizeBytes;
        }
    }
    for (int i = highestSizeByte; i > 0; i--) {
        encodedSize[i] |= 0x80;
    }

    const int encodedSizeLen = highestSizeByte + 1;

    // Preallocate room for the RecordId binary string and its encoded size
    // to reduce the number of potential reallocs
    _buffer().reserveBytes(size + encodedSizeLen);
    _buffer().claimReservedBytes(size + encodedSizeLen);

    // Append RecordId and its encoded size
    _appendBytes(str, size, invert);
    _appendBytes(encodedSize, encodedSizeLen, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::appendTypeBits(const TypeBits& typeBits) {
    _transition(BuildState::kAppendedTypeBits);
    // As an optimization, encode AllZeros as a single 0 byte.
    if (typeBits.isAllZeros()) {
        _append(uint8_t(0), false);
        return;
    }

    _appendBytes(typeBits.getBuffer(), typeBits.getSize(), false);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendBool(bool val, bool invert) {
    _append(val ? CType::kBoolTrue : CType::kBoolFalse, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendDate(Date_t val, bool invert) {
    _append(CType::kDate, invert);
    // see: http://en.wikipedia.org/wiki/Offset_binary
    uint64_t encoded = static_cast<uint64_t>(val.asInt64());
    encoded ^= (1LL << 63);  // flip highest bit (equivalent to bias encoding)
    _append(endian::nativeToBig(encoded), invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendTimestamp(Timestamp val, bool invert) {
    _append(CType::kTimestamp, invert);
    _append(endian::nativeToBig(val.asLL()), invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendOID(OID val, bool invert) {
    _append(CType::kOID, invert);
    _appendBytes(val.view().view(), OID::kOIDSize, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendString(StringData val, bool invert, const StringTransformFn& f) {
    _typeBits.appendString();
    _append(CType::kStringLike, invert);
    if (f) {
        _appendStringLike(f(val), invert);
    } else {
        _appendStringLike(val, invert);
    }
}

template <class BufferT>
void BuilderBase<BufferT>::_appendSymbol(StringData val, bool invert) {
    _typeBits.appendSymbol();
    _append(CType::kStringLike, invert);  // Symbols and Strings compare equally
    _appendStringLike(val, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendCode(StringData val, bool invert) {
    _append(CType::kCode, invert);
    _appendStringLike(val, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendCodeWString(const BSONCodeWScope& val, bool invert) {
    _append(CType::kCodeWithScope, invert);
    _appendStringLike(val.code, invert);
    _appendBson(val.scope, invert, nullptr);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendBinData(const BSONBinData& val, bool invert) {
    _append(CType::kBinData, invert);
    if (val.length < 0xff) {
        // size fits in one byte so use one byte to encode.
        _append(uint8_t(val.length), invert);
    } else {
        // Encode 0xff prefix to indicate that the size takes 4 bytes.
        _append(uint8_t(0xff), invert);
        _append(endian::nativeToBig(int32_t(val.length)), invert);
    }
    _append(uint8_t(val.type), invert);
    _appendBytes(val.data, val.length, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendRegex(const BSONRegEx& val, bool invert) {
    _append(CType::kRegEx, invert);
    // note: NULL is not allowed in pattern or flags
    _appendBytes(val.pattern.rawData(), val.pattern.size(), invert);
    _append(int8_t(0), invert);
    _appendBytes(val.flags.rawData(), val.flags.size(), invert);
    _append(int8_t(0), invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendDBRef(const BSONDBRef& val, bool invert) {
    _append(CType::kDBRef, invert);
    _append(endian::nativeToBig(int32_t(val.ns.size())), invert);
    _appendBytes(val.ns.rawData(), val.ns.size(), invert);
    _appendBytes(val.oid.view().view(), OID::kOIDSize, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendArray(const BSONArray& val,
                                        bool invert,
                                        const StringTransformFn& f) {
    _append(CType::kArray, invert);
    for (const auto& elem : val) {
        // No generic ctype byte needed here since no name is encoded.
        _appendBsonValue(elem, invert, nullptr, f);
    }
    _append(int8_t(0), invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendSetAsArray(const BSONElementSet& val,
                                             bool invert,
                                             const StringTransformFn& f) {
    _append(CType::kArray, invert);
    for (const auto& elem : val) {
        // No generic ctype byte needed here since no name is encoded.
        _appendBsonValue(elem, invert, nullptr, f);
    }
    _append(int8_t(0), invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendObject(const BSONObj& val,
                                         bool invert,
                                         const StringTransformFn& f) {
    _append(CType::kObject, invert);
    _appendBson(val, invert, f);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendNumberDouble(const double num, bool invert) {
    if (num == 0.0 && std::signbit(num))
        _typeBits.appendZero(TypeBits::kNegativeDoubleZero);
    else
        _typeBits.appendNumberDouble();

    _appendDoubleWithoutTypeBits(num, kDCMEqualToDouble, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendDoubleWithoutTypeBits(const double num,
                                                        DecimalContinuationMarker dcm,
                                                        bool invert) {
    const bool isNegative = num < 0.0;
    const double magnitude = isNegative ? -num : num;

    // Tests are structured such that NaNs and infinities fall through correctly.
    if (!(magnitude >= 1.0)) {
        if (magnitude > 0.0) {
            // This includes subnormal numbers.
            _appendSmallDouble(num, dcm, invert);
        } else if (num == 0.0) {
            // We are collapsing -0.0 and 0.0 to the same value here, the type bits disambiguate.
            _append(CType::kNumericZero, invert);
        } else {
            invariant(std::isnan(num));
            _append(CType::kNumericNaN, invert);
        }
        return;
    }

    if (magnitude < kMinLargeDouble) {
        uint64_t integerPart = static_cast<uint64_t>(magnitude);
        if (static_cast<double>(integerPart) == magnitude && dcm == kDCMEqualToDouble) {
            // No fractional part
            _appendPreshiftedIntegerPortion(integerPart << 1, isNegative, invert);
            return;
        }

        if (version == Version::V0) {
            invariant(dcm == kDCMEqualToDouble);
            // There is a fractional part.
            _appendPreshiftedIntegerPortion((integerPart << 1) | 1, isNegative, invert);

            // Append the bytes of the mantissa that include fractional bits.
            const size_t fractionalBits = 53 - (64 - countLeadingZeros64(integerPart));
            const size_t fractionalBytes = (fractionalBits + 7) / 8;
            dassert(fractionalBytes > 0);
            uint64_t mantissa;
            memcpy(&mantissa, &num, sizeof(mantissa));
            mantissa &= ~(uint64_t(-1) << fractionalBits);  // set non-fractional bits to 0;

            mantissa = endian::nativeToBig(mantissa);

            const void* firstUsedByte =
                reinterpret_cast<const char*>((&mantissa) + 1) - fractionalBytes;
            _appendBytes(firstUsedByte, fractionalBytes, isNegative ? !invert : invert);
        } else {
            const size_t fractionalBytes = countLeadingZeros64(integerPart << 1) / 8;
            const auto ctype = isNegative ? CType::kNumericNegative8ByteInt + fractionalBytes
                                          : CType::kNumericPositive8ByteInt - fractionalBytes;
            _append(static_cast<uint8_t>(ctype), invert);

            // Multiplying the double by 256 to the power X is logically equivalent to shifting the
            // fraction left by X bytes.
            uint64_t encoding = static_cast<uint64_t>(magnitude * kPow256[fractionalBytes]);
            dassert(encoding == magnitude * kPow256[fractionalBytes]);

            // Merge in the bit indicating the value has a fractional part by doubling the integer
            // part and adding 1. This leaves encoding with the high 8-fractionalBytes bytes in the
            // same form they'd have with _appendPreshiftedIntegerPortion(). The remaining low bytes
            // are the fractional bytes left-shifted by 2 bits to make room for the DCM.
            encoding += (integerPart + 1) << (fractionalBytes * 8);
            invariant((encoding & 0x3ULL) == 0);
            encoding |= dcm;
            encoding = endian::nativeToBig(encoding);
            _append(encoding, isNegative ? !invert : invert);
        }
    } else {
        _appendLargeDouble(num, dcm, invert);
    }
}

template <class BufferT>
void BuilderBase<BufferT>::_appendNumberLong(const long long num, bool invert) {
    _typeBits.appendNumberLong();
    _appendInteger(num, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendNumberInt(const int num, bool invert) {
    _typeBits.appendNumberInt();
    _appendInteger(num, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendNumberDecimal(const Decimal128 dec, bool invert) {
    bool isNegative = dec.isNegative();
    if (dec.isZero()) {
        uint32_t zeroExp = dec.getBiasedExponent();
        if (isNegative)
            zeroExp += Decimal128::kMaxBiasedExponent + 1;

        _typeBits.appendDecimalZero(zeroExp);
        _append(CType::kNumericZero, invert);
        return;
    }

    if (dec.isNaN()) {
        _append(CType::kNumericNaN, invert);
        _typeBits.appendNumberDecimal();
        return;
    }

    if (dec.isInfinite()) {
        _append(isNegative ? CType::kNumericNegativeLargeMagnitude
                           : CType::kNumericPositiveLargeMagnitude,
                invert);
        const uint64_t infinity = ~0ULL;
        _append(infinity, isNegative ? !invert : invert);
        _typeBits.appendNumberDecimal();
        return;
    }

    const uint32_t biasedExponent = dec.getBiasedExponent();
    dassert(biasedExponent <= Decimal128::kInfinityExponent);
    _typeBits.appendNumberDecimal();
    _typeBits.appendDecimalExponent(biasedExponent & TypeBits::kStoredDecimalExponentMask);

    uint32_t signalingFlags = Decimal128::kNoFlag;
    const double bin = dec.toDouble(&signalingFlags, Decimal128::kRoundTowardZero);

    // Easy case: the decimal actually is a double. True for many integers, fractions like 1.5, etc.
    if (!Decimal128::hasFlag(signalingFlags, Decimal128::kInexact) &&
        !Decimal128::hasFlag(signalingFlags, Decimal128::kOverflow)) {
        _appendDoubleWithoutTypeBits(bin, kDCMEqualToDouble, invert);
        return;
    }

    // Values smaller than the double normalized range need special handling: a regular double
    // wouldn't give 15 digits, if any at all.
    const double absBin = std::abs(bin);
    if (absBin < std::numeric_limits<double>::min()) {
        _appendTinyDecimalWithoutTypeBits(dec, bin, invert);
        return;
    }

    // Huge finite values are encoded directly. Because the value is not exact, and truncates
    // to the maximum double, the original decimal was outside of the range of finite doubles.
    // Because all decimals larger than the max finite double round down to that value, strict
    // less-than would be incorrect.
    if (absBin >= std::numeric_limits<double>::max()) {
        _appendHugeDecimalWithoutTypeBits(dec, invert);
        return;
    }

    const auto roundAwayFromZero =
        isNegative ? Decimal128::kRoundTowardNegative : Decimal128::kRoundTowardPositive;
    const uint64_t k1E15 = 1E15;  // Exact in both double and int64_t.

    // If the conditions below fall through, a decimal continuation is needed to represent the
    // difference between the stored value and the actual decimal. All paths that fall through
    // must set 'storedValue', overwriting the NaN.
    Decimal128 storedValue = Decimal128::kPositiveNaN;

    if (absBin >= kMinLargeDouble) {
        // Large finite decimals that are not exactly equal to a double require a decimal
        // continuation, even if they only have 15 significant digits, as there only is a single bit
        // for the DCM.
        _appendLargeDouble(bin, kDCMHasContinuationLargerThanDoubleRoundedUpTo15Digits, invert);
        storedValue = Decimal128(bin, Decimal128::kRoundTo34Digits, roundAwayFromZero);

    } else if (absBin < kTiniestDoubleWith2BitDCM) {
        // Small finite decimals not exactly equal to a double similarly require a decimal
        // continuation if they're small enough to only have a single bit for the DCM.
        _appendSmallDouble(bin, kDCMHasContinuationLargerThanDoubleRoundedUpTo15Digits, invert);
        storedValue = Decimal128(bin, Decimal128::kRoundTo34Digits, roundAwayFromZero);

    } else if (absBin >= kMaxIntForDouble) {
        // For doubles in this range, 'bin' may have lost precision in the integer part, which would
        // lead to miscompares with integers. So, instead handle explicitly.
        uint32_t signalingFlags = Decimal128::kNoFlag;
        Decimal128 truncated = dec.quantize(
            Decimal128::kNormalizedZero, &signalingFlags, Decimal128::kRoundTowardZero);
        dassert(truncated.getBiasedExponent() == Decimal128::kExponentBias);
        dassert(truncated.getCoefficientHigh() == 0 &&
                truncated.getCoefficientLow() < (1ULL << 63));
        int64_t integerPart = truncated.getCoefficientLow();
        bool hasFraction = Decimal128::hasFlag(signalingFlags, Decimal128::kInexact);
        bool isNegative = truncated.isNegative();
        bool has8bytes = integerPart >= (1LL << 55);
        uint64_t preshifted = integerPart << 1;
        _appendPreshiftedIntegerPortion(
            preshifted | static_cast<uint64_t>(hasFraction), isNegative, invert);
        if (!hasFraction)
            return;
        if (!has8bytes) {
            // A Fraction byte follows, but the leading 7 bytes already encode 53 bits of the
            // coefficient, so just store the DCM.
            uint8_t dcm = kDCMHasContinuationLargerThanDoubleRoundedUpTo15Digits;
            _append(dcm, isNegative ? !invert : invert);
        }

        storedValue = Decimal128(isNegative, Decimal128::kExponentBias, 0, integerPart);

    } else if (dec.getCoefficientHigh() == 0 && dec.getCoefficientLow() < k1E15) {
        // Common case: the coefficient less than 1E15, so at most 15 digits, and the number is
        // in the range of double where we have 2 spare bits for the DCM, so the decimal can be
        // represented with at least 15 digits of precision by the double 'bin'.
        dassert(Decimal128(absBin, Decimal128::kRoundTo15Digits, Decimal128::kRoundTowardPositive)
                    .isEqual(dec.toAbs()));
        _appendDoubleWithoutTypeBits(bin, kDCMEqualToDoubleRoundedUpTo15Digits, invert);
        return;
    } else {
        // The coefficient has more digits, but may still be 15 digits after removing trailing
        // zeros.
        Decimal128 decFromBin = Decimal128(bin, Decimal128::kRoundTo15Digits, roundAwayFromZero);
        if (decFromBin.isEqual(dec)) {
            _appendDoubleWithoutTypeBits(bin, kDCMEqualToDoubleRoundedUpTo15Digits, invert);
            return;
        }
        // Harder cases: decimal continuation is needed.
        // First store the double and kind of continuation needed.
        DecimalContinuationMarker dcm = dec.isLess(decFromBin) != isNegative
            ? kDCMHasContinuationLessThanDoubleRoundedUpTo15Digits
            : kDCMHasContinuationLargerThanDoubleRoundedUpTo15Digits;
        _appendDoubleWithoutTypeBits(bin, dcm, invert);

        // Note that 'dec' and 'bin' can be negative.
        storedValue = Decimal128(bin, Decimal128::kRoundTo34Digits, roundAwayFromZero);
    }
    invariant(!storedValue.isNaN());        // Should have been set explicitly.
    storedValue = storedValue.normalize();  // Normalize to 34 digits to fix decDiff exponent.

    Decimal128 decDiff = dec.subtract(storedValue);
    invariant(decDiff.isNegative() == dec.isNegative() || decDiff.isZero());
    invariant(decDiff.getBiasedExponent() == storedValue.getBiasedExponent());
    invariant(decDiff.getCoefficientHigh() == 0);

    // Now we know that we can recover the original decimal value (but not its precision, which is
    // given by the type bits) from the binary double plus the decimal continuation.
    uint64_t decimalContinuation = decDiff.getCoefficientLow();
    dassert(
        storedValue
            .add(Decimal128(isNegative, storedValue.getBiasedExponent(), 0, decimalContinuation))
            .isEqual(dec));
    decimalContinuation = endian::nativeToBig(decimalContinuation);
    _append(decimalContinuation, isNegative ? !invert : invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendBsonValue(const BSONElement& elem,
                                            bool invert,
                                            const StringData* name,
                                            const StringTransformFn& f) {
    if (name) {
        _appendBytes(name->rawData(), name->size() + 1, invert);  // + 1 for NUL
    }

    switch (elem.type()) {
        case MinKey:
        case MaxKey:
        case EOO:
        case Undefined:
        case jstNULL:
            _append(bsonTypeToGenericKeyStringType(elem.type()), invert);
            break;

        case NumberDouble:
            _appendNumberDouble(elem._numberDouble(), invert);
            break;
        case String:
            _appendString(elem.valueStringData(), invert, f);
            break;
        case Object:
            _appendObject(elem.Obj(), invert, f);
            break;
        case Array:
            _appendArray(BSONArray(elem.Obj()), invert, f);
            break;
        case BinData: {
            int len;
            const char* data = elem.binData(len);
            _appendBinData(BSONBinData(data, len, elem.binDataType()), invert);
            break;
        }

        case jstOID:
            _appendOID(elem.__oid(), invert);
            break;
        case Bool:
            _appendBool(elem.boolean(), invert);
            break;
        case Date:
            _appendDate(elem.date(), invert);
            break;

        case RegEx:
            _appendRegex(BSONRegEx(elem.regex(), elem.regexFlags()), invert);
            break;
        case DBRef:
            _appendDBRef(BSONDBRef(elem.dbrefNS(), elem.dbrefOID()), invert);
            break;
        case Symbol:
            if (f) {
                keyStringAsserted(
                    ErrorCodes::CannotBuildIndexKeys,
                    str::stream()
                        << "Cannot index type Symbol with a collation. Failed to index element: "
                        << elem << ".");
            }
            _appendSymbol(elem.valueStringData(), invert);
            break;
        case Code:
            _appendCode(elem.valueStringData(), invert);
            break;
        case CodeWScope: {
            _appendCodeWString(
                BSONCodeWScope(StringData(elem.codeWScopeCode(), elem.codeWScopeCodeLen() - 1),
                               BSONObj(elem.codeWScopeScopeData())),
                invert);
            break;
        }
        case NumberInt:
            _appendNumberInt(elem._numberInt(), invert);
            break;
        case bsonTimestamp:
            _appendTimestamp(elem.timestamp(), invert);
            break;
        case NumberLong:
            _appendNumberLong(elem._numberLong(), invert);
            break;
        case NumberDecimal:
            uassert(ErrorCodes::UnsupportedFormat,
                    "Index version does not support NumberDecimal",
                    version >= Version::V1);
            _appendNumberDecimal(elem._numberDecimal(), invert);
            break;
    }
}


/// -- lowest level

template <class BufferT>
void BuilderBase<BufferT>::_appendStringLike(StringData str, bool invert) {
    while (true) {
        size_t firstNul = strnlen(str.rawData(), str.size());
        // No NULs in string.
        _appendBytes(str.rawData(), firstNul, invert);
        if (firstNul == str.size() || firstNul == std::string::npos) {
            _append(int8_t(0), invert);
            break;
        }

        // replace "\x00" with "\x00\xFF"
        _appendBytes("\x00\xFF", 2, invert);
        str = str.substr(firstNul + 1);  // skip over the NUL byte
    }
}

template <class BufferT>
void BuilderBase<BufferT>::_appendBson(const BSONObj& obj,
                                       bool invert,
                                       const StringTransformFn& f) {
    BSONForEach(elem, obj) {
        // Force the order to be based on (ctype, name, value).
        _append(bsonTypeToGenericKeyStringType(elem.type()), invert);
        StringData name = elem.fieldNameStringData();
        _appendBsonValue(elem, invert, &name, f);
    }
    _append(int8_t(0), invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendSmallDouble(double value,
                                              DecimalContinuationMarker dcm,
                                              bool invert) {
    bool isNegative = value < 0;
    double magnitude = isNegative ? -value : value;
    dassert(!std::isnan(value) && value != 0 && magnitude < 1);

    _append(isNegative ? CType::kNumericNegativeSmallMagnitude
                       : CType::kNumericPositiveSmallMagnitude,
            invert);

    uint64_t encoded;

    if (version == Version::V0) {
        // Not using magnitude to preserve sign bit in V0
        memcpy(&encoded, &value, sizeof(encoded));
    } else if (magnitude >= kTiniestDoubleWith2BitDCM) {
        // Values in the range [2**(-255), 1) get the prefix 0b11
        memcpy(&encoded, &magnitude, sizeof(encoded));
        dassert((encoded & (0x3ULL << 62)) == 0);
        encoded <<= 2;
        encoded |= dcm;
        dassert(encoded >> 62 == 0x3);
    } else {
        invariant(dcm != kDCMEqualToDoubleRoundedUpTo15Digits);  // only single DCM bit here
        // Values in the range [numeric_limits<double>::denorm_min(), 2**(-255)) get the prefixes
        // 0b01 or 0b10. The 0b00 prefix is used by _appendHugeDecimalWithoutTypeBits for decimals
        // smaller than that.
        magnitude *= kTinyDoubleExponentUpshiftFactor;
        memcpy(&encoded, &magnitude, sizeof(encoded));
        encoded <<= 1;
        encoded |= (dcm != kDCMEqualToDouble);
        // Change the two most significant bits from 0b00 or 0b01 to 0b01 or 0b10.
        encoded += (1ULL << 62);
        dassert(encoded >> 62 == 0x1 || encoded >> 62 == 0x2);
    }

    _append(endian::nativeToBig(encoded), isNegative ? !invert : invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendLargeDouble(double value,
                                              DecimalContinuationMarker dcm,
                                              bool invert) {
    dassert(!std::isnan(value));
    dassert(value != 0.0);
    invariant(dcm != kDCMEqualToDoubleRoundedUpTo15Digits);  // only single DCM bit here

    _append(value > 0 ? CType::kNumericPositiveLargeMagnitude
                      : CType::kNumericNegativeLargeMagnitude,
            invert);

    uint64_t encoded;
    memcpy(&encoded, &value, sizeof(encoded));

    if (version != Version::V0) {
        if (std::isfinite(value)) {
            encoded <<= 1;
            encoded &= ~(1ULL << 63);
            encoded |= (dcm != kDCMEqualToDouble);
        } else {
            encoded = ~0ULL;  // infinity
        }
    }
    encoded = endian::nativeToBig(encoded);
    _append(encoded, value > 0 ? invert : !invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendTinyDecimalWithoutTypeBits(const Decimal128 dec,
                                                             const double bin,
                                                             bool invert) {
    // This function is only for 'dec' that doesn't exactly equal a double, but rounds to 'bin'
    dassert(bin == dec.toDouble(Decimal128::kRoundTowardZero));
    dassert(std::abs(bin) < DBL_MIN);
    const bool isNegative = dec.isNegative();
    Decimal128 magnitude = isNegative ? dec.negate() : dec;

    _append(isNegative ? CType::kNumericNegativeSmallMagnitude
                       : CType::kNumericPositiveSmallMagnitude,
            invert);

    // For decimals smaller than the smallest subnormal double, just store the decimal number
    if (bin == 0.0) {
        Decimal128 normalized = magnitude.normalize();
        uint64_t hi = normalized.getValue().high64;
        uint64_t lo = normalized.getValue().low64;
        invariant((hi & (0x3ULL << 62)) == 0);
        _append(endian::nativeToBig(hi), isNegative ? !invert : invert);
        _append(endian::nativeToBig(lo), isNegative ? !invert : invert);
        return;
    }
    // Encode decimal in subnormal double range by scaling in the decimal domain. Round down at
    // each step, but ensure not to get below the subnormal double. This will ensure that
    // 'scaledBin' is monotonically increasing and will only be off by at most a few units in the
    // last place, so the decimal continuation will stay in range.
    Decimal128 scaledDec =
        magnitude.multiply(kTinyDoubleExponentUpshiftFactorAsDecimal, Decimal128::kRoundTowardZero);
    double scaledBin = scaledDec.toDouble(Decimal128::kRoundTowardZero);

    // Here we know that scaledBin contains the first 15 significant digits of scaled dec, and
    // sorts correctly with scaled double.
    scaledBin = std::max(scaledBin, std::abs(bin) * kTinyDoubleExponentUpshiftFactor);
    uint64_t encoded;
    memcpy(&encoded, &scaledBin, sizeof(encoded));
    encoded <<= 1;
    encoded |= 1;  // Even if decDiff.isZero() we aren't exactly equal
    encoded += (1ULL << 62);
    dassert(encoded >> 62 == 0x1);
    _append(endian::nativeToBig(encoded), isNegative ? !invert : invert);

    // Round down, so it is certain that in all cases a non-negative continuation can be found.
    Decimal128 storedVal(scaledBin, Decimal128::kRoundTo34Digits, Decimal128::kRoundTowardZero);
    storedVal =
        storedVal
            .multiply(kTinyDoubleExponentDownshiftFactorAsDecimal, Decimal128::kRoundTowardZero)
            .add(Decimal128::kLargestNegativeExponentZero);
    dassert(storedVal.isLess(magnitude));
    Decimal128 decDiff = magnitude.subtract(storedVal);
    dassert(decDiff.getBiasedExponent() == storedVal.getBiasedExponent() || decDiff.isZero());
    dassert(decDiff.getCoefficientHigh() == 0 && !decDiff.isNegative());
    uint64_t continuation = decDiff.getCoefficientLow();
    _append(endian::nativeToBig(continuation), isNegative ? !invert : invert);
}


template <class BufferT>
void BuilderBase<BufferT>::_appendHugeDecimalWithoutTypeBits(const Decimal128 dec, bool invert) {
    // To allow us to use CType::kNumericNegativeLargeMagnitude we need to fit between the highest
    // finite double and the representation of +/-Inf. We do this by forcing the high bit to 1
    // (large doubles always have 0) and never encoding ~0 here.

    const bool isNegative = dec.isNegative();
    Decimal128 normalizedMagnitude = (isNegative ? dec.negate() : dec).normalize();
    uint64_t hi = normalizedMagnitude.getValue().high64;
    uint64_t lo = normalizedMagnitude.getValue().low64;
    dassert(hi < (1ULL << 63));
    hi |= (1ULL << 63);
    _append(isNegative ? CType::kNumericNegativeLargeMagnitude
                       : CType::kNumericPositiveLargeMagnitude,
            invert);
    _append(endian::nativeToBig(hi), isNegative ? !invert : invert);
    _append(endian::nativeToBig(lo), isNegative ? !invert : invert);
}

// Handles NumberLong and NumberInt which are encoded identically except for the TypeBits.
template <class BufferT>
void BuilderBase<BufferT>::_appendInteger(const long long num, bool invert) {
    if (num == std::numeric_limits<long long>::min()) {
        // -2**63 is exactly representable as a double and not as a positive int64.
        // Therefore we encode it as a double.
        dassert(-double(num) == kMinLargeDouble);
        _appendLargeDouble(static_cast<double>(num), kDCMEqualToDouble, invert);
        return;
    }

    if (num == 0) {
        _append(CType::kNumericZero, invert);
        return;
    }

    const bool isNegative = num < 0;
    const uint64_t magnitude = isNegative ? -num : num;
    _appendPreshiftedIntegerPortion(magnitude << 1, isNegative, invert);
}

template <class BufferT>
void BuilderBase<BufferT>::_appendPreshiftedIntegerPortion(uint64_t value,
                                                           bool isNegative,
                                                           bool invert) {
    dassert(value != 0ULL);
    dassert(value != 1ULL);

    const size_t bytesNeeded = (64 - countLeadingZeros64(value) + 7) / 8;

    // Append the low bytes of value in big endian order.
    value = endian::nativeToBig(value);
    const void* firstUsedByte = reinterpret_cast<const char*>((&value) + 1) - bytesNeeded;

    if (isNegative) {
        _append(uint8_t(CType::kNumericNegative1ByteInt - (bytesNeeded - 1)), invert);
        _appendBytes(firstUsedByte, bytesNeeded, !invert);
    } else {
        _append(uint8_t(CType::kNumericPositive1ByteInt + (bytesNeeded - 1)), invert);
        _appendBytes(firstUsedByte, bytesNeeded, invert);
    }
}


template <class BufferT>
void BuilderBase<BufferT>::_appendBytes(const void* source, size_t bytes, bool invert) {
    char* const base = _buffer().skip(bytes);

    if (invert) {
        memcpy_flipBits(base, source, bytes);
    } else {
        memcpy(base, source, bytes);
    }
}


// ----------------------------------------------------------------------
// ----------- DECODING CODE --------------------------------------------
// ----------------------------------------------------------------------

namespace {
template <class Stream>
void toBsonValue(uint8_t ctype,
                 BufReader* reader,
                 TypeBits::ReaderBase* typeBits,
                 bool inverted,
                 Version version,
                 Stream* stream,
                 uint32_t depth);

void toBson(BufReader* reader,
            TypeBits::ReaderBase* typeBits,
            bool inverted,
            Version version,
            BSONObjBuilder* builder,
            uint32_t depth) {
    while (readType<uint8_t>(reader, inverted) != 0) {
        if (inverted) {
            std::string name = readInvertedCString(reader);
            BSONObjBuilderValueStream& stream = *builder << name;
            toBsonValue(readType<uint8_t>(reader, inverted),
                        reader,
                        typeBits,
                        inverted,
                        version,
                        &stream,
                        depth);
        } else {
            StringData name = readCString(reader);
            BSONObjBuilderValueStream& stream = *builder << name;
            toBsonValue(readType<uint8_t>(reader, inverted),
                        reader,
                        typeBits,
                        inverted,
                        version,
                        &stream,
                        depth);
        }
    }
}

/**
 * Helper function to read the least significant type bits for 'num' and return a value that
 * is numerically equal to 'num', but has its exponent adjusted to match the stored exponent bits.
 */
Decimal128 adjustDecimalExponent(TypeBits::ReaderBase* typeBits, Decimal128 num);

/**
 * Helper function that takes a 'num' with 15 decimal digits of precision, normalizes it to 34
 * digits and reads a 64-bit (19-digit) continuation to obtain the full 34-bit value.
 */
Decimal128 readDecimalContinuation(BufReader* reader, bool inverted, Decimal128 num) {
    uint32_t flags = Decimal128::kNoFlag;
    uint64_t continuation = endian::bigToNative(readType<uint64_t>(reader, inverted));
    num = num.normalize();
    keyStringAssert(
        50850,
        "Invalid decimal continuation.",
        Decimal128::isValid(num.isNegative(), num.getBiasedExponent(), 0, continuation));
    num = num.add(Decimal128(num.isNegative(), num.getBiasedExponent(), 0, continuation), &flags);
    keyStringAssert(50815,
                    "Unexpected inexact flag set after Decimal addition.",
                    !(Decimal128::hasFlag(flags, Decimal128::kInexact)));
    return num;
}

template <class Stream>
void toBsonValue(uint8_t ctype,
                 BufReader* reader,
                 TypeBits::ReaderBase* typeBits,
                 bool inverted,
                 Version version,
                 Stream* stream,
                 uint32_t depth) {
    keyStringAssert(ErrorCodes::Overflow,
                    "KeyString encoding exceeded maximum allowable BSON nesting depth",
                    depth <= BSONDepth::getMaxAllowableDepth());

    // This is only used by the kNumeric.*ByteInt types, but needs to be declared up here
    // since it is used across a fallthrough.
    bool isNegative = false;

    switch (ctype) {
        case CType::kMinKey:
            *stream << MINKEY;
            break;
        case CType::kMaxKey:
            *stream << MAXKEY;
            break;
        case CType::kNullish:
            *stream << BSONNULL;
            break;
        case CType::kUndefined:
            *stream << BSONUndefined;
            break;

        case CType::kBoolTrue:
            *stream << true;
            break;
        case CType::kBoolFalse:
            *stream << false;
            break;

        case CType::kDate:
            *stream << Date_t::fromMillisSinceEpoch(
                endian::bigToNative(readType<uint64_t>(reader, inverted)) ^ (1LL << 63));
            break;

        case CType::kTimestamp:
            *stream << Timestamp(endian::bigToNative(readType<uint64_t>(reader, inverted)));
            break;

        case CType::kOID:
            if (inverted) {
                char buf[OID::kOIDSize];
                memcpy_flipBits(buf, reader->skip(OID::kOIDSize), OID::kOIDSize);
                *stream << OID::from(buf);
            } else {
                *stream << OID::from(reader->skip(OID::kOIDSize));
            }
            break;

        case CType::kStringLike: {
            const uint8_t originalType = typeBits->readStringLike();
            if (inverted) {
                if (originalType == TypeBits::kString) {
                    *stream << readInvertedCStringWithNuls(reader);
                } else {
                    keyStringAssert(50827,
                                    "Expected original type to be Symbol.",
                                    originalType == TypeBits::kSymbol);
                    *stream << BSONSymbol(readInvertedCStringWithNuls(reader));
                }

            } else {
                std::string scratch;
                if (originalType == TypeBits::kString) {
                    *stream << readCStringWithNuls(reader, &scratch);
                } else {
                    keyStringAssert(50828,
                                    "Expected original type to be Symbol.",
                                    originalType == TypeBits::kSymbol);
                    *stream << BSONSymbol(readCStringWithNuls(reader, &scratch));
                }
            }
            break;
        }

        case CType::kCode: {
            if (inverted) {
                *stream << BSONCode(readInvertedCStringWithNuls(reader));
            } else {
                std::string scratch;
                *stream << BSONCode(readCStringWithNuls(reader, &scratch));
            }
            break;
        }

        case CType::kCodeWithScope: {
            std::string scratch;
            StringData code;  // will point to either scratch or the raw encoded bytes.
            if (inverted) {
                scratch = readInvertedCStringWithNuls(reader);
                code = scratch;
            } else {
                code = readCStringWithNuls(reader, &scratch);
            }
            // Not going to optimize CodeWScope, but limit stack space usage due to recursion.
            auto scope = std::make_unique<BSONObjBuilder>();
            // BSON validation counts a CodeWithScope as two nesting levels, so match that.
            toBson(reader, typeBits, inverted, version, scope.get(), depth + 2);
            *stream << BSONCodeWScope(code, scope->done());
            break;
        }

        case CType::kBinData: {
            size_t size = readType<uint8_t>(reader, inverted);
            if (size == 0xff) {
                // size was stored in 4 bytes.
                size = endian::bigToNative(readType<uint32_t>(reader, inverted));
            }
            BinDataType subType = BinDataType(readType<uint8_t>(reader, inverted));
            const void* ptr = reader->skip(size);
            if (!inverted) {
                *stream << BSONBinData(ptr, size, subType);
            } else {
                std::unique_ptr<char[]> flipped(new char[size]);
                memcpy_flipBits(flipped.get(), ptr, size);
                *stream << BSONBinData(flipped.get(), size, subType);
            }
            break;
        }

        case CType::kRegEx: {
            if (inverted) {
                string pattern = readInvertedCString(reader);
                string flags = readInvertedCString(reader);
                *stream << BSONRegEx(pattern, flags);
            } else {
                StringData pattern = readCString(reader);
                StringData flags = readCString(reader);
                *stream << BSONRegEx(pattern, flags);
            }
            break;
        }

        case CType::kDBRef: {
            size_t size = endian::bigToNative(readType<uint32_t>(reader, inverted));
            if (inverted) {
                std::unique_ptr<char[]> ns(new char[size]);
                memcpy_flipBits(ns.get(), reader->skip(size), size);
                char oidBytes[OID::kOIDSize];
                memcpy_flipBits(oidBytes, reader->skip(OID::kOIDSize), OID::kOIDSize);
                OID oid = OID::from(oidBytes);
                *stream << BSONDBRef(StringData(ns.get(), size), oid);
            } else {
                const char* ns = static_cast<const char*>(reader->skip(size));
                OID oid = OID::from(reader->skip(OID::kOIDSize));
                *stream << BSONDBRef(StringData(ns, size), oid);
            }
            break;
        }

        case CType::kObject: {
            BSONObjBuilder subObj(stream->subobjStart());
            toBson(reader, typeBits, inverted, version, &subObj, depth + 1);
            break;
        }

        case CType::kArray: {
            BSONObjBuilder subArr(stream->subarrayStart());
            DecimalCounter<unsigned> index;
            uint8_t elemType;
            while ((elemType = readType<uint8_t>(reader, inverted)) != 0) {
                toBsonValue(elemType,
                            reader,
                            typeBits,
                            inverted,
                            version,
                            &(subArr << StringData{index}),
                            depth + 1);
                ++index;
            }
            break;
        }

            //
            // Numerics
            //

        case CType::kNumericNaN: {
            auto type = typeBits->readNumeric();
            if (type == TypeBits::kDouble) {
                *stream << std::numeric_limits<double>::quiet_NaN();
            } else {
                keyStringAssert(50819,
                                "Invalid type bits for numeric NaN",
                                type == TypeBits::kDecimal && version == Version::V1);
                *stream << Decimal128::kPositiveNaN;
            }
            break;
        }

        case CType::kNumericZero: {
            uint8_t zeroType = typeBits->readZero();
            switch (zeroType) {
                case TypeBits::kDouble:
                    *stream << 0.0;
                    break;
                case TypeBits::kInt:
                    *stream << 0;
                    break;
                case TypeBits::kLong:
                    *stream << 0ll;
                    break;
                case TypeBits::kNegativeDoubleZero:
                    *stream << -0.0;
                    break;
                default:
                    const uint32_t whichZero = typeBits->readDecimalZero(zeroType);
                    const bool isNegative = whichZero > Decimal128::kMaxBiasedExponent;
                    const uint32_t biasedExponent =
                        isNegative ? whichZero - (Decimal128::kMaxBiasedExponent + 1) : whichZero;

                    keyStringAssert(50846,
                                    "Invalid numeric zero decimal.",
                                    Decimal128::isValid(isNegative, biasedExponent, 0, 0));
                    *stream << Decimal128(isNegative, biasedExponent, 0, 0);
                    break;
            }
            break;
        }

        case CType::kNumericNegativeLargeMagnitude:
            inverted = !inverted;
            isNegative = true;
            [[fallthrough]];  // format is the same as positive, but inverted
        case CType::kNumericPositiveLargeMagnitude: {
            const uint8_t originalType = typeBits->readNumeric();
            keyStringAssert(31231,
                            "Unexpected decimal encoding for V0 KeyString.",
                            version > Version::V0 || originalType != TypeBits::kDecimal);
            uint64_t encoded = readType<uint64_t>(reader, inverted);
            encoded = endian::bigToNative(encoded);
            bool hasDecimalContinuation = false;
            double bin;

            // Backward compatibility
            if (version == Version::V0) {
                memcpy(&bin, &encoded, sizeof(bin));
            } else if (!(encoded & (1ULL << 63))) {  // In range of (finite) doubles
                hasDecimalContinuation = encoded & 1;
                encoded >>= 1;          // remove decimal continuation marker
                encoded |= 1ULL << 62;  // implied leading exponent bit
                memcpy(&bin, &encoded, sizeof(bin));
                if (isNegative)
                    bin = -bin;
            } else if (encoded == ~0ULL) {  // infinity
                bin = isNegative ? -std::numeric_limits<double>::infinity()
                                 : std::numeric_limits<double>::infinity();
            } else {  // Huge decimal number, directly output
                keyStringAssert(50818,
                                "Invalid type bits for decimal number.",
                                originalType == TypeBits::kDecimal);
                uint64_t highbits = encoded & ~(1ULL << 63);
                uint64_t lowbits = endian::bigToNative(readType<uint64_t>(reader, inverted));
                Decimal128 dec(Decimal128::Value{lowbits, highbits});
                if (isNegative)
                    dec = dec.negate();
                if (dec.isFinite())
                    dec = adjustDecimalExponent(typeBits, dec);
                *stream << dec;
                break;
            }

            // 'bin' contains the value of the input, rounded toward zero in case of decimal
            if (originalType == TypeBits::kDouble) {
                *stream << bin;
            } else if (originalType == TypeBits::kLong) {
                // This can only happen for a single number.
                keyStringAssert(50821,
                                "Unexpected value for large number.",
                                bin == static_cast<double>(std::numeric_limits<long long>::min()));
                *stream << std::numeric_limits<long long>::min();
            } else {
                keyStringAssert(50826,
                                "Unexpected type of large number.",
                                originalType == TypeBits::kDecimal && version != Version::V0);
                const auto roundAwayFromZero = isNegative ? Decimal128::kRoundTowardNegative
                                                          : Decimal128::kRoundTowardPositive;
                Decimal128 dec(bin, Decimal128::kRoundTo34Digits, roundAwayFromZero);
                if (hasDecimalContinuation)
                    dec = readDecimalContinuation(reader, inverted, dec);
                if (dec.isFinite())
                    dec = adjustDecimalExponent(typeBits, dec);
                *stream << dec;
            }
            break;
        }

        case CType::kNumericNegativeSmallMagnitude:
            inverted = !inverted;
            isNegative = true;
            [[fallthrough]];  // format is the same as positive, but inverted

        case CType::kNumericPositiveSmallMagnitude: {
            const uint8_t originalType = typeBits->readNumeric();
            uint64_t encoded = readType<uint64_t>(reader, inverted);
            encoded = endian::bigToNative(encoded);

            if (version == Version::V0) {
                // for these, the raw double was stored intact, including sign bit.
                keyStringAssert(50812,
                                "Invalid type bits for small number.",
                                originalType == TypeBits::kDouble);
                double d;
                memcpy(&d, &encoded, sizeof(d));
                *stream << d;
                break;
            }

            switch (encoded >> 62) {
                case 0x0: {
                    // Teeny tiny decimal, smaller magnitude than 2**(-1074)
                    uint64_t lowbits = readType<uint64_t>(reader, inverted);
                    lowbits = endian::bigToNative(lowbits);
                    Decimal128 dec = Decimal128(Decimal128::Value{lowbits, encoded});
                    dec = adjustDecimalExponent(typeBits, dec);
                    if (ctype == CType::kNumericNegativeSmallMagnitude)
                        dec = dec.negate();
                    *stream << dec;
                    break;
                }
                case 0x1:
                case 0x2: {
                    // Tiny double or decimal, magnitude from 2**(-1074) to 2**(-255), exclusive.
                    // The exponent is shifted by 256 in order to avoid subnormals, which would
                    // result in less than 15 significant digits. Because 2**(-255) has 179
                    // decimal digits, no doubles exactly equal decimals, so all decimals have
                    // a continuation. The bit is still needed for comparison purposes.
                    bool hasDecimalContinuation = encoded & 1;
                    encoded -= 1ULL << 62;
                    encoded >>= 1;
                    double scaledBin;
                    memcpy(&scaledBin, &encoded, sizeof(scaledBin));
                    if (originalType == TypeBits::kDouble) {
                        keyStringAssert(
                            50822, "Unexpected decimal continuation.", !hasDecimalContinuation);
                        double bin = scaledBin * kTinyDoubleExponentDownshiftFactor;
                        *stream << (isNegative ? -bin : bin);
                        break;
                    }
                    keyStringAssert(50823,
                                    "Expected decimal continuation.",
                                    originalType == TypeBits::kDecimal && hasDecimalContinuation);

                    // If the actual double would be subnormal, scale in decimal domain.
                    Decimal128 dec;
                    if (scaledBin <
                        std::numeric_limits<double>::min() * kTinyDoubleExponentUpshiftFactor) {
                        // For subnormals, we rounded down everywhere, to ensure that the
                        // continuation will always be positive. Needs to be done consistently in
                        // encoding/decoding (see storedVal in _appendTinyDecimalWithoutTypeBits).

                        Decimal128 scaledDec = Decimal128(
                            scaledBin, Decimal128::kRoundTo34Digits, Decimal128::kRoundTowardZero);
                        dec = scaledDec.multiply(kTinyDoubleExponentDownshiftFactorAsDecimal,
                                                 Decimal128::kRoundTowardZero);
                    } else {
                        double bin = scaledBin * kTinyDoubleExponentDownshiftFactor;
                        dec = Decimal128(
                            bin, Decimal128::kRoundTo34Digits, Decimal128::kRoundTowardPositive);
                    }

                    dec = readDecimalContinuation(reader, inverted, dec);
                    *stream << adjustDecimalExponent(typeBits, isNegative ? dec.negate() : dec);
                    break;
                }
                case 0x3: {
                    // Small double, 2**(-255) or more in magnitude. Common case.
                    auto dcm = static_cast<DecimalContinuationMarker>(encoded & 3);
                    encoded >>= 2;
                    double bin;
                    memcpy(&bin, &encoded, sizeof(bin));
                    if (originalType == TypeBits::kDouble) {
                        keyStringAssert(
                            50824, "Decimal contuation mismatch.", dcm == kDCMEqualToDouble);
                        *stream << (isNegative ? -bin : bin);
                        break;
                    }

                    // Deal with decimal cases
                    keyStringAssert(50825,
                                    "Unexpected type for small number, expected decimal.",
                                    originalType == TypeBits::kDecimal);
                    Decimal128 dec;
                    switch (dcm) {
                        case kDCMEqualToDoubleRoundedUpTo15Digits:
                            dec = Decimal128(bin,
                                             Decimal128::kRoundTo15Digits,
                                             Decimal128::kRoundTowardPositive);
                            break;
                        case kDCMEqualToDouble:
                            dec = Decimal128(bin,
                                             Decimal128::kRoundTo34Digits,
                                             Decimal128::kRoundTowardPositive);
                            break;
                        case kDCMHasContinuationLessThanDoubleRoundedUpTo15Digits:
                        case kDCMHasContinuationLargerThanDoubleRoundedUpTo15Digits:
                            // Deal with decimal continuation
                            dec = Decimal128(bin,
                                             Decimal128::kRoundTo34Digits,
                                             Decimal128::kRoundTowardPositive);
                            dec = readDecimalContinuation(reader, inverted, dec);
                    }
                    *stream << adjustDecimalExponent(typeBits, isNegative ? dec.negate() : dec);
                    break;
                }
                default:
                    MONGO_UNREACHABLE;
            }
            break;
        }

        case CType::kNumericNegative8ByteInt:
        case CType::kNumericNegative7ByteInt:
        case CType::kNumericNegative6ByteInt:
        case CType::kNumericNegative5ByteInt:
        case CType::kNumericNegative4ByteInt:
        case CType::kNumericNegative3ByteInt:
        case CType::kNumericNegative2ByteInt:
        case CType::kNumericNegative1ByteInt:
            inverted = !inverted;
            isNegative = true;
            [[fallthrough]];  // format is the same as positive, but inverted

        case CType::kNumericPositive1ByteInt:
        case CType::kNumericPositive2ByteInt:
        case CType::kNumericPositive3ByteInt:
        case CType::kNumericPositive4ByteInt:
        case CType::kNumericPositive5ByteInt:
        case CType::kNumericPositive6ByteInt:
        case CType::kNumericPositive7ByteInt:
        case CType::kNumericPositive8ByteInt: {
            const uint8_t originalType = typeBits->readNumeric();

            uint64_t encodedIntegerPart = 0;
            {
                size_t intBytesRemaining = CType::numBytesForInt(ctype);
                while (intBytesRemaining--) {
                    encodedIntegerPart =
                        (encodedIntegerPart << 8) | readType<uint8_t>(reader, inverted);
                }
            }

            const bool haveFractionalPart = (encodedIntegerPart & 1);
            int64_t integerPart = encodedIntegerPart >> 1;

            if (!haveFractionalPart) {
                if (isNegative)
                    integerPart = -integerPart;

                switch (originalType) {
                    case TypeBits::kDouble:
                        *stream << double(integerPart);
                        break;
                    case TypeBits::kInt:
                        *stream << int(integerPart);
                        break;
                    case TypeBits::kLong:
                        *stream << static_cast<long long>(integerPart);
                        break;
                    case TypeBits::kDecimal:
                        *stream << adjustDecimalExponent(typeBits, Decimal128(integerPart));
                        break;
                    default:
                        keyStringAsserted(50831, "Unexpected type for positive int.");
                }
                break;
            }

            // KeyString V0: anything fractional is a double
            if (version == Version::V0) {
                keyStringAssert(50832,
                                "Expected type double for fractional part.",
                                originalType == TypeBits::kDouble);
                keyStringAssert(31209,
                                "Integer part is too big to be a double.",
                                integerPart < kMaxIntForDouble);

                const uint64_t exponent = (64 - countLeadingZeros64(integerPart)) - 1;
                const size_t fractionalBits = (52 - exponent);
                const size_t fractionalBytes = (fractionalBits + 7) / 8;

                // build up the bits of a double here.
                uint64_t doubleBits = integerPart << fractionalBits;
                doubleBits &= ~(1ULL << 52);  // clear implicit leading 1
                doubleBits |= (exponent + 1023 /*bias*/) << 52;
                if (isNegative) {
                    doubleBits |= (1ULL << 63);  // sign bit
                }
                for (size_t i = 0; i < fractionalBytes; i++) {
                    // fold in the fractional bytes
                    const uint64_t byte = readType<uint8_t>(reader, inverted);
                    doubleBits |= (byte << ((fractionalBytes - i - 1) * 8));
                }

                double number;
                memcpy(&number, &doubleBits, sizeof(number));
                *stream << number;
                break;
            }

            // KeyString V1: all numeric values with fractions have at least 8 bytes.
            // Start with integer part, and read until we have a full 8 bytes worth of data.
            const size_t fracBytes = 8 - CType::numBytesForInt(ctype);
            uint64_t encodedFraction = integerPart;

            for (int fracBytesRemaining = fracBytes; fracBytesRemaining; fracBytesRemaining--)
                encodedFraction = (encodedFraction << 8) | readType<uint8_t>(reader, inverted);

            // Zero out the DCM and convert the whole binary fraction
            double bin = static_cast<double>(encodedFraction & ~3ULL) * kInvPow256[fracBytes];
            if (originalType == TypeBits::kDouble) {
                *stream << (isNegative ? -bin : bin);
                break;
            }

            // The two lsb's are the DCM, except for the 8-byte case, where it's already known
            DecimalContinuationMarker dcm = fracBytes
                ? static_cast<DecimalContinuationMarker>(encodedFraction & 3)
                : kDCMHasContinuationLargerThanDoubleRoundedUpTo15Digits;

            // Deal with decimal cases
            keyStringAssert(50810, "Expected type Decimal.", originalType == TypeBits::kDecimal);
            Decimal128 dec;
            switch (dcm) {
                case kDCMEqualToDoubleRoundedUpTo15Digits:
                    dec = Decimal128(
                        bin, Decimal128::kRoundTo15Digits, Decimal128::kRoundTowardPositive);
                    break;
                case kDCMEqualToDouble:
                    dec = Decimal128(
                        bin, Decimal128::kRoundTo34Digits, Decimal128::kRoundTowardPositive);
                    break;
                default:
                    // Deal with decimal continuation
                    dec = integerPart > kMaxIntForDouble
                        ? Decimal128(integerPart)
                        : Decimal128(
                              bin, Decimal128::kRoundTo34Digits, Decimal128::kRoundTowardPositive);
                    dec = readDecimalContinuation(reader, inverted, dec);
            }
            *stream << adjustDecimalExponent(typeBits, isNegative ? dec.negate() : dec);
            break;
        }
        default:
            keyStringAsserted(50811, str::stream() << "Unknown type: " << ctype);
    }
}

void filterKeyFromKeyString(uint8_t ctype, BufReader* reader, bool inverted, Version version);

void readBson(BufReader* reader, bool inverted, Version version) {
    while (readType<uint8_t>(reader, inverted) != 0) {
        if (inverted) {
            std::string name = readInvertedCString(reader);
            filterKeyFromKeyString(readType<uint8_t>(reader, inverted), reader, inverted, version);
        } else {
            (void)readCString(reader);
            filterKeyFromKeyString(readType<uint8_t>(reader, inverted), reader, inverted, version);
        }
    }
}

void filterKeyFromKeyString(uint8_t ctype, BufReader* reader, bool inverted, Version version) {
    switch (ctype) {
        case CType::kMinKey:
        case CType::kMaxKey:
        case CType::kNullish:
        case CType::kUndefined:
        case CType::kBoolTrue:
        case CType::kBoolFalse:
            break;

        case CType::kDate:
        case CType::kTimestamp:
            reader->skip(sizeof(std::uint64_t));
            break;

        case CType::kOID:
            reader->skip(OID::kOIDSize);
            break;

        case CType::kStringLike:
        case CType::kCode: {
            if (inverted) {
                (void)readInvertedCStringWithNuls(reader);
            } else {
                std::string scratch;
                (void)readCStringWithNuls(reader, &scratch);
            }
            break;
        }

        case CType::kCodeWithScope: {
            std::string scratch;
            if (inverted) {
                (void)readInvertedCStringWithNuls(reader);
            } else {
                (void)readCStringWithNuls(reader, &scratch);
            }
            // Not going to optimize CodeWScope.
            readBson(reader, inverted, version);
            break;
        }

        case CType::kBinData: {
            size_t size = readType<uint8_t>(reader, inverted);
            if (size == 0xff) {
                // size was stored in 4 bytes.
                size = endian::bigToNative(readType<uint32_t>(reader, inverted));
            }
            // Read the subtype of BinData
            (void)readType<uint8_t>(reader, inverted);
            // Advance by size of BinData
            reader->skip(size);
            break;
        }

        case CType::kRegEx: {
            if (inverted) {
                // Read the pattern
                (void)readInvertedCString(reader);
                // Read flags
                (void)readInvertedCString(reader);
            } else {
                // Read the pattern
                (void)readCString(reader);
                // Read flags
                (void)readCString(reader);
            }
            break;
        }

        case CType::kDBRef: {
            size_t size = endian::bigToNative(readType<uint32_t>(reader, inverted));
            reader->skip(size);
            reader->skip(OID::kOIDSize);
            break;
        }

        case CType::kObject: {
            readBson(reader, inverted, version);
            break;
        }

        case CType::kArray: {
            while (std::uint8_t elemType = readType<uint8_t>(reader, inverted)) {
                filterKeyFromKeyString(elemType, reader, inverted, version);
            }
            break;
        }

            //
            // Numerics
            //

        case CType::kNumericNaN: {
            break;
        }

        case CType::kNumericZero: {
            break;
        }

        case CType::kNumericNegativeLargeMagnitude:
            inverted = !inverted;
            [[fallthrough]];  // format is the same as positive, but inverted
        case CType::kNumericPositiveLargeMagnitude: {
            uint64_t encoded = readType<uint64_t>(reader, inverted);
            encoded = endian::bigToNative(encoded);
            bool hasDecimalContinuation = false;

            // Backward compatibility or infinity
            if (version == Version::V0 || encoded == ~0ULL) {
                break;
            } else if (!(encoded & (1ULL << 63))) {  // In range of (finite) doubles
                hasDecimalContinuation = encoded & 1;
            } else {  // Huge decimal number, get the low bits
                // It should be of type kDecimal
                (void)readType<uint64_t>(reader, inverted);
                break;
            }

            if (hasDecimalContinuation) {
                reader->skip(sizeof(std::uint64_t));
            }
            break;
        }

        case CType::kNumericNegativeSmallMagnitude:
            inverted = !inverted;
            [[fallthrough]];  // format is the same as positive, but inverted

        case CType::kNumericPositiveSmallMagnitude: {
            uint64_t encoded = readType<uint64_t>(reader, inverted);
            encoded = endian::bigToNative(encoded);

            if (version == Version::V0) {
                break;
            }

            switch (encoded >> 62) {
                case 0x0: {
                    // Teeny tiny decimal, smaller magnitude than 2**(-1074)
                    (void)readType<uint64_t>(reader, inverted);
                    break;
                }
                case 0x1:
                case 0x2: {
                    // Tiny double or decimal, magnitude from 2**(-1074) to 2**(-255), exclusive.
                    // The exponent is shifted by 256 in order to avoid subnormals, which would
                    // result in less than 15 significant digits. Because 2**(-255) has 179
                    // decimal digits, no doubles exactly equal decimals, so all decimals have
                    // a continuation.
                    bool hasDecimalContinuation = encoded & 1;
                    if (hasDecimalContinuation) {
                        reader->skip(sizeof(std::uint64_t));
                    }

                    break;
                }
                case 0x3: {
                    // Small double, 2**(-255) or more in magnitude. Common case.
                    auto dcm = static_cast<DecimalContinuationMarker>(encoded & 3);

                    // Deal with decimal cases
                    switch (dcm) {
                        case kDCMEqualToDoubleRoundedUpTo15Digits:
                        case kDCMEqualToDouble:
                            break;
                        case kDCMHasContinuationLessThanDoubleRoundedUpTo15Digits:
                        case kDCMHasContinuationLargerThanDoubleRoundedUpTo15Digits:
                            // Deal with decimal continuation
                            reader->skip(sizeof(std::uint64_t));
                    }
                    break;
                }
                default:
                    MONGO_UNREACHABLE;
            }
            break;
        }

        case CType::kNumericNegative8ByteInt:
        case CType::kNumericNegative7ByteInt:
        case CType::kNumericNegative6ByteInt:
        case CType::kNumericNegative5ByteInt:
        case CType::kNumericNegative4ByteInt:
        case CType::kNumericNegative3ByteInt:
        case CType::kNumericNegative2ByteInt:
        case CType::kNumericNegative1ByteInt:
            inverted = !inverted;
            [[fallthrough]];  // format is the same as positive, but inverted

        case CType::kNumericPositive1ByteInt:
        case CType::kNumericPositive2ByteInt:
        case CType::kNumericPositive3ByteInt:
        case CType::kNumericPositive4ByteInt:
        case CType::kNumericPositive5ByteInt:
        case CType::kNumericPositive6ByteInt:
        case CType::kNumericPositive7ByteInt:
        case CType::kNumericPositive8ByteInt: {
            uint64_t encodedIntegerPart = 0;
            {
                size_t intBytesRemaining = CType::numBytesForInt(ctype);
                while (intBytesRemaining--) {
                    encodedIntegerPart =
                        (encodedIntegerPart << 8) | readType<uint8_t>(reader, inverted);
                }
            }

            const bool haveFractionalPart = (encodedIntegerPart & 1);
            int64_t integerPart = encodedIntegerPart >> 1;

            if (!haveFractionalPart) {
                break;
            }

            // KeyString V0: anything fractional is a double
            if (version == Version::V0) {
                const uint64_t exponent = (64 - countLeadingZeros64(integerPart)) - 1;
                const size_t fractionalBits = (52 - exponent);
                const size_t fractionalBytes = (fractionalBits + 7) / 8;

                for (size_t i = 0; i < fractionalBytes; i++) {
                    // fold in the fractional bytes
                    reader->skip(sizeof(std::uint8_t));
                }
                break;
            }

            // KeyString V1: all numeric values with fractions have at least 8 bytes.
            // Start with integer part, and read until we have a full 8 bytes worth of data.
            const size_t fracBytes = 8 - CType::numBytesForInt(ctype);
            uint64_t encodedFraction = integerPart;

            for (int fracBytesRemaining = fracBytes; fracBytesRemaining; fracBytesRemaining--)
                encodedFraction = (encodedFraction << 8) | readType<uint8_t>(reader, inverted);

            // The two lsb's are the DCM, except for the 8-byte case, where it's already known
            DecimalContinuationMarker dcm = fracBytes
                ? static_cast<DecimalContinuationMarker>(encodedFraction & 3)
                : kDCMHasContinuationLargerThanDoubleRoundedUpTo15Digits;

            // Deal with decimal cases
            switch (dcm) {
                case kDCMEqualToDoubleRoundedUpTo15Digits:
                case kDCMEqualToDouble:
                    break;
                default:
                    // Deal with decimal continuation
                    reader->skip(sizeof(std::uint64_t));
            }
            break;
        }
        default:
            MONGO_UNREACHABLE;
    }
}

Decimal128 adjustDecimalExponent(TypeBits::ReaderBase* typeBits, Decimal128 num) {
    // The last 6 bits of the exponent are stored in the type bits. First figure out if the exponent
    // of 'num' is too high or too low. Even for a non-zero number with only a single significant
    // digit, there are only 34 possiblities while exponents with the given low 6 bits are spaced
    // (1 << 6) == 64 apart. This is not quite enough to figure out whether to shift the expnent up
    // or down when the difference is for example 32 in either direction. However, if the high part
    // of the coefficient is zero, the coefficient can only be scaled down by up to 1E19 (increasing
    // the exponent by 19), as 2**64 < 1E20. If scaling down to match the higher exponent isn't
    // possible, we must be able to scale up. Scaling always must be exact and not change the value.
    const uint32_t kMaxExpAdjust = 33;
    const uint32_t kMaxExpIncrementForZeroHighCoefficient = 19;
    keyStringAssert(50829, "Expected non-zero number for decimal.", !num.isZero());
    const uint32_t origExp = num.getBiasedExponent();
    const uint8_t storedBits = typeBits->readDecimalExponent();

    uint32_t highExp = (origExp & ~TypeBits::kStoredDecimalExponentMask) | storedBits;

    // Start by determining an exponent that's not less than num's and matches the stored bits.
    if (highExp < origExp)
        highExp += (1U << TypeBits::kStoredDecimalExponentBits);

    // This must be the right exponent, as no scaling is required.
    if (highExp == origExp)
        return num;

    // For increasing the exponent, quantize the existing number. This must be
    // exact, as the value stays in the same cohort.
    if (highExp <= origExp + kMaxExpAdjust &&
        (num.getCoefficientHigh() != 0 ||
         highExp <= origExp + kMaxExpIncrementForZeroHighCoefficient)) {
        // Increase exponent and decrease (right shift) coefficient.
        uint32_t flags = Decimal128::SignalingFlag::kNoFlag;
        keyStringAssert(50845,
                        "Unexpected exponent values after adjusting Decimal.",
                        Decimal128::isValid(0, highExp, 0, 0));
        auto quantized = num.quantize(Decimal128(0, highExp, 0, 1), &flags);
        keyStringAssert(50813,
                        "Unexpected signaling flag for Decimal quantization.",
                        flags == Decimal128::SignalingFlag::kNoFlag);  // must be exact
        num = quantized;
    } else {
        // Decrease exponent and increase (left shift) coefficient.
        uint32_t lowExp = highExp - (1U << TypeBits::kStoredDecimalExponentBits);
        keyStringAssert(50814,
                        "Unexpected exponent values after adjusting Decimal.",
                        lowExp >= origExp - kMaxExpAdjust && Decimal128::isValid(0, lowExp, 0, 0));
        num = num.add(Decimal128(0, lowExp, 0, 0));
    }
    keyStringAssert(50830,
                    "Unexpected biased exponent in decimal.",
                    (num.getBiasedExponent() & TypeBits::kStoredDecimalExponentMask) ==
                        (highExp & TypeBits::kStoredDecimalExponentMask));
    return num;
}

}  // namespace

// ----------------------------------------------------------------------
//  --------- MISC class utils --------
// ----------------------------------------------------------------------

template <class BufferT>
std::string BuilderBase<BufferT>::toString() const {
    return hexblob::encode(getBuffer(), getSize());
}

std::string Value::toString() const {
    return hexblob::encode(getBuffer(), getSize());
}

TypeBits& TypeBits::operator=(const TypeBits& tb) {
    if (&tb == this) {
        return *this;
    }

    version = tb.version;
    _curBit = tb._curBit;
    _isAllZeros = tb._isAllZeros;

    _buf.reset();
    _buf.appendBuf(tb._buf.buf(), tb._buf.len());

    return *this;
}

uint32_t TypeBits::readSizeFromBuffer(BufReader* reader) {
    const uint8_t firstByte = reader->peek<uint8_t>();

    // Case 2: all bits in one byte; no size byte.
    if (firstByte > 0 && firstByte < 0x80) {
        return 1;
    }

    // Skip the indicator byte.
    reader->skip(1);

    // Case 3: <= 127 bytes; use one size byte.
    if (firstByte > 0x80) {
        return firstByte & 0x7f;
    }

    // Case 4: > 127 bytes; needs 4 size bytes.
    if (firstByte == 0x80) {
        // The next 4 bytes represent the size in little endian order.
        uint32_t s = reader->read<LittleEndian<uint32_t>>();
        keyStringAssert(50910, "Invalid overlong encoding.", s > kMaxBytesForShortEncoding);
        return s;
    }

    // Case 1: all zeros.
    dassert(firstByte == 0);
    return 0;
}


void TypeBits::setRawSize(uint32_t size) {
    // Grow the data buffer if needed.
    if (size > getDataBufferLen()) {
        _buf.grow(size - getDataBufferLen());
    }

    if (size > kMaxBytesForShortEncoding) {
        DataCursor(_buf.buf())
            .writeAndAdvance<uint8_t>(0x80)
            .writeAndAdvance<LittleEndian<uint32_t>>(size);
    } else {
        DataView(getDataBuffer() - 1).write<uint8_t>(0x80 | size);
    }
}


void TypeBits::resetFromBuffer(BufReader* reader) {
    reset();

    if (!reader->remaining())
        // This means AllZeros state was encoded as an empty buffer.
        return;

    uint32_t size = readSizeFromBuffer(reader);
    if (size > 0)
        _isAllZeros = false;
    setRawSize(size);
    memcpy(getDataBuffer(), reader->skip(size), size);
}

void TypeBits::appendBit(uint8_t oneOrZero) {
    dassert(oneOrZero == 0 || oneOrZero == 1);

    if (oneOrZero == 1)
        _isAllZeros = false;

    const uint32_t byte = _curBit / 8;
    const uint8_t offsetInByte = _curBit % 8;
    if (offsetInByte == 0) {
        setRawSize(byte + 1);
        getDataBuffer()[byte] = oneOrZero;  // zeros bits 1-7
    } else {
        getDataBuffer()[byte] |= (oneOrZero << offsetInByte);
    }

    _curBit++;
}

void TypeBits::appendZero(uint8_t zeroType) {
    switch (zeroType) {
        // 2-bit encodings
        case kInt:
        case kDouble:
        case kLong:
            appendBit(zeroType >> 1);
            appendBit(zeroType & 1);
            break;
        case kNegativeDoubleZero:
            if (version == Version::V0) {
                appendBit(kV0NegativeDoubleZero >> 1);
                appendBit(kV0NegativeDoubleZero & 1);
                break;
            }
            zeroType = kV1NegativeDoubleZero;
            [[fallthrough]];  // fallthrough for 5-bit encodings
        case kDecimalZero0xxx:
        case kDecimalZero1xxx:
        case kDecimalZero2xxx:
        case kDecimalZero3xxx:
        case kDecimalZero4xxx:
        case kDecimalZero5xxx:
            // first two bits output are ones
            dassert((zeroType >> 3) == 3);
            for (int bitPos = 4; bitPos >= 0; bitPos--)
                appendBit((zeroType >> bitPos) & 1);
            break;
        default:
            MONGO_UNREACHABLE;
    }
}

void TypeBits::appendDecimalZero(uint32_t whichZero) {
    invariant((whichZero >> 12) <= kDecimalZero5xxx - kDecimalZero0xxx);
    appendZero((whichZero >> 12) + kDecimalZero0xxx);
    for (int bitPos = 11; bitPos >= 0; bitPos--)
        appendBit((whichZero >> bitPos) & 1);
}

void TypeBits::appendDecimalExponent(uint8_t storedExponentBits) {
    invariant(storedExponentBits < (1U << kStoredDecimalExponentBits));
    for (int bitPos = kStoredDecimalExponentBits - 1; bitPos >= 0; bitPos--)
        appendBit((storedExponentBits >> bitPos) & 1);
}

uint8_t TypeBits::Reader::readBit() {
    if (_typeBits._isAllZeros)
        return 0;

    const uint32_t byte = _curBit / 8;
    const uint8_t offsetInByte = _curBit % 8;
    _curBit++;

    keyStringAssert(50615, "Invalid size byte(s).", byte < _typeBits.getDataBufferLen());

    return (_typeBits.getDataBuffer()[byte] & (1 << offsetInByte)) ? 1 : 0;
}

uint8_t TypeBits::Reader::readStringLike() {
    return readBit();
}

uint8_t TypeBits::Reader::readNumeric() {
    uint8_t highBit = readBit();
    return (highBit << 1) | readBit();
}

uint8_t TypeBits::Reader::readZero() {
    uint8_t res = readNumeric();

    // For keyString v1, negative and decimal zeros require at least 3 more bits.
    if (_typeBits.version != Version::V0 && res == kSpecialZeroPrefix) {
        res = (res << 1) | readBit();
        res = (res << 1) | readBit();
        res = (res << 1) | readBit();
    }
    if (res == kV1NegativeDoubleZero || res == kV0NegativeDoubleZero)
        res = kNegativeDoubleZero;
    return res;
}

uint32_t TypeBits::Reader::readDecimalZero(uint8_t zeroType) {
    uint32_t whichZero = zeroType - kDecimalZero0xxx;
    for (int bitPos = 11; bitPos >= 0; bitPos--)
        whichZero = (whichZero << 1) | readBit();

    return whichZero;
}

uint8_t TypeBits::Reader::readDecimalExponent() {
    uint8_t exponentBits = 0;
    for (int bitPos = kStoredDecimalExponentBits - 1; bitPos >= 0; bitPos--)
        exponentBits = (exponentBits << 1) | readBit();
    return exponentBits;
}

uint8_t TypeBits::ExplainReader::readStringLike() {
    auto val = _reader.readStringLike();
    if (val == TypeBits::kString) {
        _explain << "String";
    } else if (val == TypeBits::kSymbol) {
        _explain << "Symbol";
    }
    return val;
}

uint8_t TypeBits::ExplainReader::readNumeric() {
    auto val = _reader.readNumeric();
    _explain << [&]() -> std::string {
        switch (val) {
            case TypeBits::kInt:
                return "Int";
            case TypeBits::kLong:
                return "Long";
            case TypeBits::kDouble:
                return "Double";
            case TypeBits::kDecimal:
                return "Decimal";
            default:
                return fmt::format("unknown {}", val);
        }
    }();
    return val;
}

uint8_t TypeBits::ExplainReader::readZero() {
    auto val = _reader.readZero();
    _explain << [&]() {
        switch (val) {
            case TypeBits::kInt:
                return "Int";
            case TypeBits::kLong:
                return "Long";
            case TypeBits::kDouble:
                return "Double";
            case TypeBits::kNegativeDoubleZero:
                return "NegativeDoubleZero";
            default:
                return "DecimalZero";
        }
    }();
    return val;
}

uint32_t TypeBits::ExplainReader::readDecimalZero(uint8_t zeroType) {
    return _reader.readDecimalZero(zeroType);
}

uint8_t TypeBits::ExplainReader::readDecimalExponent() {
    return _reader.readDecimalExponent();
}

size_t getKeySize(const char* buffer, size_t len, Ordering ord, const TypeBits& typeBits) {
    invariant(len > 0);
    BufReader reader(buffer, len);
    unsigned remainingBytes;
    for (int i = 0; (remainingBytes = reader.remaining()); i++) {
        const bool invert = (ord.get(i) == -1);
        uint8_t ctype = readType<uint8_t>(&reader, invert);
        // We have already read the Key.
        if (ctype == kEnd)
            break;

        // Read the Key that comes after the first byte in KeyString.
        filterKeyFromKeyString(ctype, &reader, invert, typeBits.version);
    }

    invariant(len > remainingBytes);
    // Key size = buffer len - number of bytes comprising the RecordId
    return (len - (remainingBytes - 1));
}

// This discriminator byte only exists in KeyStrings for queries, not in KeyStrings stored in an
// index.
Discriminator decodeDiscriminator(const char* buffer,
                                  size_t len,
                                  Ordering ord,
                                  const TypeBits& typeBits) {
    BufReader reader(buffer, len);
    TypeBits::Reader typeBitsReader(typeBits);
    for (int i = 0; reader.remaining(); i++) {
        const bool invert = (ord.get(i) == -1);
        uint8_t ctype = readType<uint8_t>(&reader, invert);
        if (ctype == kLess || ctype == kGreater) {
            // Invert it back if discriminator byte got mistakenly inverted.
            if (invert)
                ctype = ~ctype;
            return ctype == kLess ? Discriminator::kExclusiveBefore
                                  : Discriminator::kExclusiveAfter;
        }

        if (ctype == kEnd)
            break;
        filterKeyFromKeyString(ctype, &reader, invert, typeBits.version);
    }
    return Discriminator::kInclusive;
}

void toBsonSafe(const char* buffer,
                size_t len,
                Ordering ord,
                const TypeBits& typeBits,
                BSONObjBuilder& builder) {
    BufReader reader(buffer, len);
    TypeBits::Reader typeBitsReader(typeBits);
    for (int i = 0; reader.remaining(); i++) {
        const bool invert = (ord.get(i) == -1);
        uint8_t ctype = readType<uint8_t>(&reader, invert);
        if (ctype == kLess || ctype == kGreater) {
            // This was just a discriminator which is logically part of the previous field. This
            // will only be encountered on queries, not in the keys stored in an index.
            // Note: this should probably affect the BSON key name of the last field, but it
            // must be read *after* the value so it isn't possible.
            ctype = readType<uint8_t>(&reader, invert);
        }

        if (ctype == kEnd)
            break;
        toBsonValue(ctype, &reader, &typeBitsReader, invert, typeBits.version, &(builder << ""), 1);
    }
}

BSONObj toBsonSafe(const char* buffer, size_t len, Ordering ord, const TypeBits& typeBits) {
    BSONObjBuilder builder;
    toBsonSafe(buffer, len, ord, typeBits, builder);
    return builder.obj();
}

BSONObj toBson(const char* buffer, size_t len, Ordering ord, const TypeBits& typeBits) noexcept {
    return toBsonSafe(buffer, len, ord, typeBits);
}

BSONObj toBson(StringData data, Ordering ord, const TypeBits& typeBits) {
    return toBson(data.rawData(), data.size(), ord, typeBits);
}

RecordId decodeRecordIdLongAtEnd(const void* bufferRaw, size_t bufSize) {
    const unsigned char* buffer = static_cast<const unsigned char*>(bufferRaw);
    invariant(bufSize >= 2);  // smallest possible encoding of a RecordId.
    const unsigned char lastByte = *(buffer + bufSize - 1);
    const size_t ridSize = 2 + (lastByte & 0x7);  // stored in low 3 bits.
    invariant(bufSize >= ridSize);
    const unsigned char* firstBytePtr = buffer + bufSize - ridSize;
    BufReader reader(firstBytePtr, ridSize);
    return decodeRecordIdLong(&reader);
}

size_t sizeWithoutRecordIdLongAtEnd(const void* bufferRaw, size_t bufSize) {
    invariant(bufSize >= 2);  // smallest possible encoding of a RecordId.
    const unsigned char* buffer = static_cast<const unsigned char*>(bufferRaw);
    const unsigned char lastByte = *(buffer + bufSize - 1);
    const size_t ridSize = 2 + (lastByte & 0x7);  // stored in low 3 bits.
    invariant(bufSize >= ridSize);
    return bufSize - ridSize;
}

size_t sizeWithoutRecordIdStrAtEnd(const void* bufferRaw, size_t bufSize) {
    // See decodeRecordIdStrAtEnd for the size decoding algorithm
    invariant(bufSize > 0);
    const uint8_t* buffer = static_cast<const uint8_t*>(bufferRaw);

    // Decode RecordId binary string size
    size_t ridSize = 0;
    uint8_t sizes[kRecordIdStrEncodedSizeMaxBytes] = {0};

    // Continuation bytes
    size_t sizeByteId = 0;
    for (; buffer[bufSize - 1 - sizeByteId] & 0x80; sizeByteId++) {
        invariant(bufSize >= sizeByteId + 1 /* non-cont bytes */);
        invariant(sizeByteId < kRecordIdStrEncodedSizeMaxBytes);
        sizes[sizeByteId] = buffer[bufSize - 1 - sizeByteId] & 0x7F;
    }
    // Last (non-continuation) byte
    invariant(sizeByteId < kRecordIdStrEncodedSizeMaxBytes);
    sizes[sizeByteId] = buffer[bufSize - 1 - sizeByteId];

    const size_t numSegments = sizeByteId + 1;

    for (; sizeByteId > 0; sizeByteId--) {
        ridSize += static_cast<size_t>(sizes[sizeByteId]) << ((numSegments - sizeByteId - 1) * 7);
    }
    ridSize += static_cast<size_t>(sizes[sizeByteId]) << ((numSegments - sizeByteId - 1) * 7);

    invariant(bufSize >= ridSize + numSegments);
    return bufSize - ridSize - numSegments;
}

RecordId decodeRecordIdLong(BufReader* reader) {
    const uint8_t firstByte = readType<uint8_t>(reader, false);
    const uint8_t numExtraBytes = firstByte >> 5;  // high 3 bits in firstByte
    uint64_t repr = firstByte & 0x1f;              // low 5 bits in firstByte
    for (int i = 0; i < numExtraBytes; i++) {
        repr = (repr << 8) | readType<uint8_t>(reader, false);
    }

    const uint8_t lastByte = readType<uint8_t>(reader, false);
    invariant((lastByte & 0x7) == numExtraBytes);
    repr = (repr << 5) | (lastByte >> 3);  // fold in high 5 bits of last byte
    return RecordId(repr);
}

RecordId decodeRecordIdStrAtEnd(const void* bufferRaw, size_t bufSize) {
    // See _appendRecordIdStr for the encoding scheme.
    // The RecordId binary string size is decoded right-to-left, up to the size byte
    // without continuation bit.

    invariant(bufSize > 0);
    const uint8_t* buffer = static_cast<const uint8_t*>(bufferRaw);

    // Decode RecordId binary string size
    size_t ridSize = 0;
    uint8_t sizes[kRecordIdStrEncodedSizeMaxBytes] = {0};

    // Continuation bytes
    size_t sizeByteId = 0;
    for (; buffer[bufSize - 1 - sizeByteId] & 0x80; sizeByteId++) {
        invariant(bufSize >= sizeByteId + 1 /* non-cont byte */);
        invariant(sizeByteId < kRecordIdStrEncodedSizeMaxBytes);
        sizes[sizeByteId] = buffer[bufSize - 1 - sizeByteId] & 0x7F;
    }
    // Last (non-continuation) byte
    invariant(sizeByteId < kRecordIdStrEncodedSizeMaxBytes);
    sizes[sizeByteId] = buffer[bufSize - 1 - sizeByteId];

    const size_t numSegments = sizeByteId + 1;

    for (; sizeByteId > 0; sizeByteId--) {
        ridSize += static_cast<size_t>(sizes[sizeByteId]) << ((numSegments - sizeByteId - 1) * 7);
    }
    ridSize += static_cast<size_t>(sizes[sizeByteId]) << ((numSegments - sizeByteId - 1) * 7);

    invariant(bufSize >= ridSize + numSegments);

    return RecordId(reinterpret_cast<const char*>(buffer) + (bufSize - ridSize - numSegments),
                    ridSize);
}

int compare(const char* leftBuf, const char* rightBuf, size_t leftSize, size_t rightSize) {
    // memcmp has undefined behavior if either leftBuf or rightBuf is a null pointer.
    if (MONGO_unlikely(leftSize == 0))
        return rightSize == 0 ? 0 : -1;
    else if (MONGO_unlikely(rightSize == 0))
        return 1;

    int min = std::min(leftSize, rightSize);

    int cmp = memcmp(leftBuf, rightBuf, min);

    if (cmp) {
        if (cmp < 0)
            return -1;
        return 1;
    }

    // keys match

    if (leftSize == rightSize)
        return 0;

    return leftSize < rightSize ? -1 : 1;
}

int Value::compareWithTypeBits(const Value& other) const {
    return KeyString::compare(getBuffer(), other.getBuffer(), _buffer.size(), other._buffer.size());
}

bool readSBEValue(BufReader* reader,
                  TypeBits::ReaderBase* typeBits,
                  bool inverted,
                  Version version,
                  sbe::value::ValueBuilder* valueBuilder) {
    uint8_t ctype;
    if (!reader->remaining() || (ctype = readType<uint8_t>(reader, inverted)) == kEnd) {
        return false;
    }

    // This function is only intended to read stored index entries. The 'kLess' and 'kGreater'
    // "discriminator" types are used for querying and are never stored in an index.
    invariant(ctype > kLess && ctype < kGreater);

    const uint32_t depth = 1;  // This function only gets called for a top-level KeyString::Value.
    toBsonValue(ctype, reader, typeBits, inverted, version, valueBuilder, depth);
    return true;
}

void appendSingleFieldToBSONAs(
    const char* buf, int len, StringData fieldName, BSONObjBuilder* builder, Version version) {
    const bool inverted = false;

    BufReader reader(buf, len);
    invariant(reader.remaining());
    uint8_t ctype = readType<uint8_t>(&reader, inverted);
    invariant(ctype != kEnd && ctype > kLess && ctype < kGreater);

    const uint32_t depth = 1;  // This function only gets called for a top-level KeyString::Value.
    // Callers discard their TypeBits.
    TypeBits typeBits(version);
    TypeBits::Reader typeBitsReader(typeBits);

    BSONObjBuilderValueStream& stream = *builder << fieldName;
    toBsonValue(ctype, &reader, &typeBitsReader, inverted, version, &stream, depth);
}

void appendToBSONArray(const char* buf, int len, BSONArrayBuilder* builder, Version version) {
    const bool inverted = false;

    BufReader reader(buf, len);
    invariant(reader.remaining());
    uint8_t ctype = readType<uint8_t>(&reader, inverted);
    invariant(ctype != kEnd && ctype > kLess && ctype < kGreater);

    // This function only gets called for a top-level KeyString::Value.
    const uint32_t depth = 1;
    // All users of this currently discard type bits.
    TypeBits typeBits(version);
    TypeBits::Reader typeBitsReader(typeBits);

    toBsonValue(ctype, &reader, &typeBitsReader, inverted, version, builder, depth);
}

void Value::serializeWithoutRecordIdLong(BufBuilder& buf) const {
    dassert(decodeRecordIdLongAtEnd(_buffer.get(), _ksSize).isValid());

    const int32_t sizeWithoutRecordId = sizeWithoutRecordIdLongAtEnd(_buffer.get(), _ksSize);
    buf.appendNum(sizeWithoutRecordId);                 // Serialize size of KeyString
    buf.appendBuf(_buffer.get(), sizeWithoutRecordId);  // Serialize KeyString
    buf.appendBuf(_buffer.get() + _ksSize, _buffer.size() - _ksSize);  // Serialize TypeBits
}

void Value::serializeWithoutRecordIdStr(BufBuilder& buf) const {
    dassert(decodeRecordIdStrAtEnd(_buffer.get(), _ksSize).isValid());

    const int32_t sizeWithoutRecordId = sizeWithoutRecordIdStrAtEnd(_buffer.get(), _ksSize);
    buf.appendNum(sizeWithoutRecordId);                 // Serialize size of KeyString
    buf.appendBuf(_buffer.get(), sizeWithoutRecordId);  // Serialize KeyString
    buf.appendBuf(_buffer.get() + _ksSize, _buffer.size() - _ksSize);  // Serialize TypeBits
}

size_t Value::getApproximateSize() const {
    auto size = sizeof(Value);
    size += !_buffer.isShared() ? SharedBuffer::kHolderSize + _buffer.size() : 0;
    return size;
}

template class BuilderBase<Builder>;
template class BuilderBase<HeapBuilder>;
template class BuilderBase<PooledBuilder>;

void logKeyString(const RecordId& recordId,
                  const Value& keyStringValue,
                  const BSONObj& keyPatternBson,
                  const BSONObj& keyStringBson,
                  std::string callerLogPrefix) {
    // We need to rehydrate the keyString to something readable.
    BSONObj rehydratedKey = rehydrateKey(keyPatternBson, keyStringBson);

    LOGV2(51811,
          "logging keystring",
          "caller"_attr = callerLogPrefix,
          "record_id"_attr = recordId,
          "rehydrated_key"_attr = rehydratedKey,
          "key_string"_attr = keyStringValue);
}

BSONObj rehydrateKey(const BSONObj& keyPatternBson, const BSONObj& keyStringBson) {
    auto keyPatternIter = keyPatternBson.begin();
    auto keyStringIter = keyStringBson.begin();
    BSONObjBuilder b;
    while (keyPatternIter != keyPatternBson.end() && keyStringIter != keyStringBson.end()) {
        b.appendAs(*keyStringIter, keyPatternIter->fieldName());
        ++keyPatternIter;
        ++keyStringIter;
    }
    // Wildcard index documents can have more values in the keystring.
    while (keyStringIter != keyStringBson.end()) {
        b.append(*keyStringIter);
        ++keyStringIter;
    }
    return b.obj();
}

std::string explain(const char* buffer,
                    int len,
                    const BSONObj& keyPattern,
                    const TypeBits& typeBits,
                    boost::optional<KeyFormat> keyFormat) {
    const auto ord = Ordering::make(keyPattern);

    auto keyPatternIter = keyPattern.begin();
    BufReader reader(buffer, len);
    str::stream str;
    TypeBits::Reader typeBitsReader(typeBits);
    for (int i = 0; reader.remaining(); i++) {
        const bool invert = (ord.get(i) == -1);
        uint8_t ctype = readType<uint8_t>(&reader, false /* invert */);
        str << fmt::format("Byte: {0:#x} ", ctype);
        if (invert) {
            ctype = ~ctype;
            str << fmt::format("(inverted {0:#x}) ", ctype);
        }
        str << "\n";
        if (ctype == kLess) {
            str << "  Discriminator: kLess\n";
        } else if (ctype == kGreater) {
            str << "  Discriminator: kGreater\n";
        } else if (ctype == kEnd) {
            str << "  End\n";
            break;
        } else {
            const auto ctypeName = CType::toString(ctype);
            str << fmt::format("  CType: {}\n", ctypeName);

            const auto startPos = reader.pos();
            const auto startOff = reader.offset();

            BSONObjBuilder builder;
            TypeBits::ExplainReader explainReader(typeBitsReader);
            auto fieldName = (keyPatternIter->eoo()) ? "" : (keyPatternIter++)->fieldName();

            toBsonValue(ctype,
                        &reader,
                        &explainReader,
                        invert,
                        typeBits.version,
                        &(builder << fieldName),
                        1);

            const auto endOff = reader.offset();
            if (auto bytes = (endOff - startOff); bytes > 0) {
                str << "Bytes: 0x" << hexblob::encodeLower(startPos, bytes) << "\n";
            }

            if (auto tbExplain = explainReader.getExplain(); !tbExplain.empty()) {
                str << "  TypeBits: " << tbExplain << "\n";
            }
            str << "  BSON: " << builder.done().toString() << "\n";
        }
    }

    if (!reader.remaining()) {
        str << "No RecordId\n";
    } else if (keyFormat) {
        const auto startPos = reader.pos();
        const auto startOff = reader.offset();

        RecordId recordId;
        if (keyFormat == KeyFormat::Long) {
            recordId = KeyString::decodeRecordIdLongAtEnd(buffer, len);
        } else {
            recordId = KeyString::decodeRecordIdStrAtEnd(buffer, len);
        }
        str << "Bytes: 0x" << hexblob::encodeLower(startPos, (len - startOff)) << "\n";
        auto kfString = (*keyFormat == KeyFormat::Long) ? "Long" : "String";
        str << fmt::format("  RecordId {}: {}\n", kfString, recordId.toString());
    } else {
        str << "RecordId present but no format provided\n";
    }

    return str;
}

}  // namespace KeyString

}  // namespace mongo