yo-resp 0.3.12

The RESP2 and RESP3 codec: borrowed request frames in, wire bytes out, no allocation on the hot path.
Documentation
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
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
//! From a decoded command to a written reply.
//!
//! This is the layer Y23 exists to keep thin. The wire and the embedded API
//! both have to reach the same code, or there are two implementations of `INCR`
//! and one of them is wrong. So `yo-kv` holds one method per command taking
//! ordinary Rust values, and everything here is about the part that is only
//! true on a socket: which keyword goes where, which combinations a real server
//! refuses, and which of the two protocols the answer is spelled in.
//!
//! # What runs a command
//!
//! [`Server`] holds the databases. [`Session`] holds what one connection has
//! chosen: which database, which name it gave itself, what its id is. The
//! protocol version lives in the [`Out`] because that is what needs it, and
//! `HELLO` changes it there.
//!
//! ```
//! use yo_resp::{Argv, Limits, Out, Proto};
//! use yo_resp::dispatch::{Args, Flow, Server, Session, execute};
//!
//! let mut server = Server::new();
//! let mut session = Session::new(1);
//! let mut out = Out::new(Proto::Resp2);
//!
//! let wire = b"*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$1\r\nv\r\n";
//! let mut argv = Argv::new();
//! argv.decode(wire, &Limits::default())?;
//! let flow = execute(&mut server, &mut session, Args::new(&argv, wire), &mut out);
//!
//! assert_eq!(flow, Flow::Continue);
//! assert_eq!(out.as_slice(), b"+OK\r\n");
//! # Ok::<(), yo_resp::ProtocolError>(())
//! ```
//!
//! # Errors are values until the last moment
//!
//! A command body returns a [`Result`], and this module turns the error into
//! the line that goes on the wire. That is what keeps the same body usable from
//! the embedded API, where an error is a value with a [`Code`] on it and not a
//! sentence to be parsed.
//!
//! The reply buffer is rolled back to where it was before a failing command
//! wrote anything, so a body that checks its arguments halfway through cannot
//! leave half a reply in front of the error.
//!
//! # Nothing here allocates
//!
//! Arguments are slices of the connection's read buffer, keywords are compared
//! in place, numbers are written straight into the reply, and the pairs of
//! `MSET` reach the store as an iterator rather than a `Vec`. The two places
//! that do allocate, an error message and the text of `INFO`, say so and wrap
//! it, because a shard thread that allocates aborts.

mod args;
mod arrays;
mod blocking;
mod cpu;
mod hashes;
mod keyspace;
mod lists;
mod migrate;
mod scan;
mod scripting;
mod server;
mod sets;
mod strings;
pub mod table;
mod zsets;

pub use args::Args;
pub use blocking::{Parked, Waiters};
pub use table::{COMMANDS, Spec, arity_ok, lookup};

use crate::reply::Out;
use yo_common::{Code, Error};
use yo_kv::{Clock, Keyspace};

/// How many databases a server has.
///
/// Redis's default is sixteen and its `databases` setting can change it. Ours
/// is sixteen and cannot, which is why `CONFIG GET databases` can answer with a
/// constant. Nothing in the design needs the number to be fixed; nothing yet
/// needs it not to be.
pub const DATABASES: usize = 16;

/// Every database's bit in [`Server::dirty`], which is what a fresh server
/// starts on so that the first maintenance turn asks all of them.
///
/// A `u64` holds sixteen bits with room to spare, and the assertion below is
/// what turns raising [`DATABASES`] past sixty four into a build failure rather
/// than a shift that silently drops the databases past the end.
const ALL_DATABASES: u64 = if DATABASES == 64 {
    u64::MAX
} else {
    (1u64 << DATABASES) - 1
};
const _: () = assert!(DATABASES <= 64);

/// How many keys one command throws away before it leaves the rest to the next.
///
/// A bound and not a loop to the end, because this runs in front of a client
/// that is waiting for its reply, and a server a long way over its limit would
/// otherwise hold that client for as long as it took to walk all the way back
/// under. Sixty four is a batch's worth of commands, so a server that went over
/// by what one batch allocated comes back under in one command, and a server
/// whose limit was just cut in half works through it over the next few thousand
/// rather than in one long stall. Redis bounds the same loop by a time slice
/// instead of a count and hands the rest to a timer; there is no timer here, so
/// the rest goes to the next command that runs.
const EVICT_BUDGET: usize = 64;

/// What a server says to a command that would allocate when it has no room.
///
/// Redis's `shared.oomerr`, word for word including the full stop, because
/// clients match on the `OOM` prefix and people match on the sentence.
const OOM: &[u8] = b"command not allowed when used memory > 'maxmemory'.";

/// What the connection should do after a command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Flow {
    /// Read the next command.
    Continue,
    /// Write what is buffered and then close, which is what `QUIT` asks for.
    Close,
    /// Nothing was written and nothing is owed yet.
    ///
    /// The client is on the waiter list and its reply comes when a key it named
    /// has something in it or when its deadline passes, whichever happens first.
    /// Until then the connection stops reading commands, because a client that
    /// is waiting for an answer is not a client that has sent another question.
    Block,
}

/// The numbers `INFO` reports that this layer cannot see for itself.
///
/// The reactor owns the sockets, so the reactor is what knows how many clients
/// there are. It writes these directly and nothing here does anything with them
/// except report them.
#[derive(Debug, Clone, Copy, Default)]
pub struct Stats {
    /// Connections open right now.
    pub clients: u64,
    /// Connections accepted since the server started.
    pub connections: u64,
    /// Commands run since the server started, which this layer counts itself.
    pub commands: u64,
}

/// Everything a server holds.
///
/// One of these per shard thread, not one per process: the databases inside are
/// not `Sync` and are reached by sending their thread a command. What makes
/// this a server rather than a shard is that it is the whole of what a
/// connection can address.
pub struct Server {
    dbs: Vec<Keyspace>,
    clock: Clock,
    started_ms: u64,
    /// Where the next maintenance turn starts looking, so that a database
    /// under constant write load cannot hold the other fifteen's space.
    next_db: usize,
    /// One bit per database, set when a command ran against it.
    ///
    /// The maintenance turn after every batch used to ask all sixteen
    /// databases whether they had anything to collect, and asking costs a load
    /// and a store in each one. Fifteen of those are cold lines on a server
    /// where every client is on database zero, which is every server, and the
    /// answer is no every time. This is the cheap half of the question: a
    /// database nobody has touched since it last said no cannot have started
    /// saying yes.
    dirty: u64,
    /// What the connections are holding, kept by the engine.
    conn_bytes: usize,
    /// The `maxmemory` limit in bytes, zero when there is not one.
    ///
    /// Zero is the default and it is the whole reason the check in front of
    /// every write is one comparison against a field that is already warm.
    maxmemory: u64,
    /// What [`Server::memory_bytes`] said at the last maintenance turn.
    ///
    /// The reading is a walk over every collection in every database and cannot
    /// go on a command path, so the command path reads this instead and is at
    /// most one batch behind. What that costs is overshoot: a server can end a
    /// batch holding one batch's worth of allocation more than its limit before
    /// anything notices. A batch is 64 commands, so that is bounded by what 64
    /// commands can allocate and not by how long the server runs.
    ///
    /// Only kept up to date when there is a limit to judge it against. A server
    /// with no `maxmemory` never reads it and never pays for it.
    used: usize,
    /// Which database the next eviction draws from.
    ///
    /// Its own cursor and not [`Server::next_db`], because eviction and
    /// compaction move at different rates and sharing one would make the
    /// database that gets compacted depend on how many keys were evicted.
    evict_db: usize,
    /// Which database the next active expiry sweep starts at.
    ///
    /// A third cursor for the same reason there is a second one. A sweep runs on
    /// every turn of the loop and compaction runs when there is dead space, so
    /// sharing a cursor would make which database gets swept depend on which one
    /// was last collected.
    expire_db: usize,
    /// The millisecond the last active expiry sweep ran on, so the next one on
    /// the same millisecond does not bother.
    expire_ms: u64,
    /// Clients parked on a blocking command.
    waiters: Waiters,
    /// Sockets `MIGRATE` is holding open to the servers it has talked to.
    ///
    /// Empty on a server nobody has migrated a key out of, which is nearly all
    /// of them, and it costs a vector's three words to be empty.
    peers: migrate::Peers,
    /// The numbers the reactor keeps for `INFO`.
    pub stats: Stats,
}

impl Server {
    /// A server with [`DATABASES`] empty databases on the system clock.
    #[must_use]
    pub fn new() -> Server {
        let clock = Clock::system();
        Server {
            dbs: (0..DATABASES)
                .map(|_| Keyspace::with_clock(clock))
                .collect(),
            clock,
            started_ms: clock.now_ms(),
            next_db: 0,
            dirty: ALL_DATABASES,
            conn_bytes: 0,
            maxmemory: 0,
            used: 0,
            evict_db: 0,
            expire_db: 0,
            expire_ms: 0,
            waiters: Waiters::default(),
            peers: migrate::Peers::default(),
            stats: Stats::default(),
        }
    }

    /// A server on a clock the caller moves by hand, for tests.
    #[must_use]
    pub fn with_clock(clock: Clock) -> Server {
        Server {
            dbs: (0..DATABASES)
                .map(|_| Keyspace::with_clock(clock))
                .collect(),
            clock,
            started_ms: clock.now_ms(),
            next_db: 0,
            dirty: ALL_DATABASES,
            conn_bytes: 0,
            maxmemory: 0,
            used: 0,
            evict_db: 0,
            expire_db: 0,
            expire_ms: 0,
            waiters: Waiters::default(),
            peers: migrate::Peers::default(),
            stats: Stats::default(),
        }
    }

    /// One database, by index.
    ///
    /// # Panics
    ///
    /// If `i` is not a database. `SELECT` is the only way a client changes the
    /// index and it checks, so an index that is out of range here is a bug in
    /// the caller and not something a client can ask for.
    pub fn db(&mut self, i: usize) -> &mut Keyspace {
        // The borrow is mutable, so assume it is used. Anything that only reads
        // has [`Server::db_ref`] and does not come through here.
        self.dirty |= 1u64 << i;
        &mut self.dbs[i]
    }

    /// One database, by index, without taking it mutably.
    ///
    /// What the prefetch stage needs. It runs for all 64 commands in a batch
    /// before any of them executes, so it cannot hold the mutable borrow `run`
    /// is about to want, and it does not need one: warming a cache line reads
    /// nothing and changes nothing.
    ///
    /// # Panics
    ///
    /// As [`Server::db`].
    #[must_use]
    pub fn db_ref(&self, i: usize) -> &Keyspace {
        &self.dbs[i]
    }

    /// Take a new clock reading and give it to every database.
    ///
    /// Once per turn of the event loop, which is the only place time moves. A
    /// command asking what the time is gets the answer the whole batch got, so
    /// two keys written by the same batch expire together (`04` section 3).
    pub fn refresh_clock(&mut self) {
        self.clock.refresh();
        let now = self.clock.now_ms();
        for db in &mut self.dbs {
            db.clock_mut().set(now);
        }
    }

    /// Move every clock here to `ms` by hand, for tests about expiry.
    ///
    /// A test cannot wait a hundred seconds and a test that waits a hundred
    /// milliseconds is a test that fails on a loaded machine, so time moves on
    /// request. The system clock underneath will overwrite this on the next
    /// [`Server::refresh_clock`], which is why this is only useful in a test
    /// that drives commands directly rather than through the event loop.
    pub fn set_clock_ms(&mut self, ms: u64) {
        self.clock.set(ms);
        for db in &mut self.dbs {
            db.clock_mut().set(ms);
        }
    }

    /// Seconds since this server was built.
    #[must_use]
    pub fn uptime_secs(&self) -> u64 {
        self.clock.now_ms().saturating_sub(self.started_ms) / 1000
    }

    /// Bytes held by every database's index and arena, plus the read and reply
    /// buffers of every connection.
    ///
    /// The buffers are in here because they are real and because Redis counts
    /// its own, so leaving them out would make the one number people compare
    /// flattering rather than true. They are not a database, so nothing in the
    /// keyspace can change them and the engine has to say when they move.
    #[must_use]
    pub fn memory_bytes(&self) -> usize {
        self.dbs.iter().map(Keyspace::memory_bytes).sum::<usize>() + self.conn_bytes
    }

    /// What the keyspace itself is holding, live records only.
    ///
    /// `used_memory` minus this is what the store costs to run: the index, the
    /// space dead records are sitting in until compaction gets to them, and the
    /// connections' buffers.
    #[must_use]
    pub fn dataset_bytes(&self) -> usize {
        self.dbs
            .iter()
            .map(|db| db.map().arena().live_bytes() as usize)
            .sum()
    }

    /// Bytes the arenas are holding, live and dead together.
    #[must_use]
    pub fn arena_bytes(&self) -> usize {
        self.dbs
            .iter()
            .map(|db| db.map().arena().reserved_bytes() as usize)
            .sum()
    }

    /// Bytes the indexes are holding.
    #[must_use]
    pub fn index_bytes(&self) -> usize {
        self.dbs
            .iter()
            .map(|db| db.map().index().memory_bytes())
            .sum()
    }

    /// Arena segments whose pages are real, across every database.
    #[must_use]
    pub fn segment_count(&self) -> usize {
        self.dbs
            .iter()
            .map(|db| db.map().arena().resident_segments())
            .sum()
    }

    /// What the connections' read and reply buffers are holding.
    #[must_use]
    pub const fn conn_bytes(&self) -> usize {
        self.conn_bytes
    }

    /// Note that the connections are holding `delta` bytes more than they were,
    /// or fewer when it is negative.
    ///
    /// A delta and not a total because the alternative is a walk over every
    /// connection, and the walk would have to happen on a turn of the loop
    /// rather than when `INFO` asks, which puts the cost of a report on the
    /// command path of a server nobody is asking.
    pub fn note_conn_bytes(&mut self, delta: isize) {
        self.conn_bytes = self.conn_bytes.saturating_add_signed(delta);
    }

    /// Keys reclaimed by running into them after their deadline.
    #[must_use]
    pub fn expired_keys(&self) -> u64 {
        self.dbs.iter().map(Keyspace::expired_keys).sum()
    }

    /// Keys thrown away to make room, which is the other number entirely.
    #[must_use]
    pub fn evicted_keys(&self) -> u64 {
        self.dbs.iter().map(Keyspace::evicted_keys).sum()
    }

    /// The `maxmemory` limit in bytes, zero when there is not one.
    #[must_use]
    pub const fn maxmemory(&self) -> u64 {
        self.maxmemory
    }

    /// Set the limit, and take a reading straight away.
    ///
    /// The reading is here rather than left to the next maintenance turn because
    /// a client that sets the limit and sends a write in the same batch expects
    /// the write to be judged against the limit it just set, and because the
    /// cached number is meaningless until the first time there is a limit to
    /// compare it with.
    ///
    /// Turning the limit on also turns on the running total every slab keeps of
    /// what its collections hold, and turning it off turns that back off, so a
    /// server with no limit is not paying to count something nobody reads. The
    /// first reading after switching it on is the walk that the total starts
    /// from, and it is the only walk.
    pub fn set_maxmemory(&mut self, bytes: u64) {
        self.maxmemory = bytes;
        for db in &mut self.dbs {
            db.track_memory(bytes != 0);
        }
        self.used = self.settled_memory();
    }

    /// Take a fresh memory reading, which the maintenance turn does once a batch.
    ///
    /// Nothing at all when there is no limit, which is the default and is every
    /// server that has not asked for one.
    pub fn refresh_memory(&mut self) {
        if self.maxmemory != 0 {
            self.used = self.settled_memory();
        }
    }

    /// [`Server::memory_bytes`], asked the cheap way.
    ///
    /// The same number. The difference is that this asks each database only
    /// about the collections that could have moved since the last time, which is
    /// what a batch touched rather than what the server holds, so it can be
    /// asked once a batch and again on every command that is over the limit.
    fn settled_memory(&mut self) -> usize {
        self.dbs
            .iter_mut()
            .map(Keyspace::settled_memory_bytes)
            .sum::<usize>()
            + self.conn_bytes
    }

    /// Make room under the `maxmemory` limit, throwing keys away if that is what
    /// it takes. Answers whether there is anything left it could throw away.
    ///
    /// Redis runs the same thing from `processCommand` before every command and
    /// so does this: a client that writes has to be judged at the moment it
    /// writes, not a batch later, or the limit is a suggestion.
    ///
    /// Three things happen in the loop and all three are needed. Eviction picks
    /// a key and drops it. Compaction gives the pages back, because dropping a
    /// key marks its record dead and returns nothing on its own, so a loop that
    /// only evicted would throw the whole keyspace away and watch the number
    /// stay where it was. The reading is taken again each time round, because
    /// the two of them together are the only thing that moves it.
    ///
    /// # Why running out of budget is not a no
    ///
    /// `false` means there was nothing left to evict, which is `noeviction`, or
    /// a `volatile` policy on a database where nothing has a deadline, or a
    /// keyspace that is already empty. It does not mean the server is still over
    /// its limit, and that difference is Redis's: `performEvictions` answers
    /// `EVICT_FAIL` only when it has run out of things to delete, and
    /// `processCommand` refuses the client on that and on nothing else. Running
    /// out of time part way through a job it is doing well comes back as
    /// `EVICT_RUNNING` and the command goes through, because a server that is
    /// evicting steadily and refusing every write while it does it is worse for
    /// the client than a little overshoot.
    ///
    /// # What the limit is worth
    ///
    /// Space comes back a segment at a time and a segment is two megabytes, so
    /// this holds a server to its limit give or take a segment. A `maxmemory` of
    /// a few hundred megabytes gets what it asked for. A `maxmemory` of four
    /// megabytes is asking for a precision this store does not have.
    pub fn make_room(&mut self) -> bool {
        if self.maxmemory == 0 || self.used as u64 <= self.maxmemory {
            return true;
        }
        // The cached reading is a batch old and the batch may have compacted
        // since, so take a fresh one before throwing anything away. It is the
        // settled reading and not the walk, so what this costs is the handful of
        // collections the last batch touched and not the whole database.
        self.used = self.settled_memory();
        let mut budget = EVICT_BUDGET;
        while self.used as u64 > self.maxmemory {
            if !self.evict_step() {
                return false;
            }
            self.compact_hard_step();
            self.used = self.settled_memory();
            budget -= 1;
            if budget == 0 {
                break;
            }
        }
        true
    }

    /// Throw one key away, from whichever database has one to give.
    ///
    /// Round robin from a cursor rather than always starting at database zero,
    /// so a server using more than one of them does not empty the first before
    /// touching the second. Almost every server is on database zero only, where
    /// this is one call that answers and fifteen that say the map is empty.
    fn evict_step(&mut self) -> bool {
        for turn in 0..self.dbs.len() {
            let i = (self.evict_db + turn) % self.dbs.len();
            if self.dbs[i].evict_one() {
                self.evict_db = (i + 1) % self.dbs.len();
                self.dirty |= 1u64 << i;
                return true;
            }
        }
        false
    }

    /// The sweep the shard loop calls, at most once a millisecond.
    ///
    /// The gate is the whole difference between this and [`Server::expire_step`].
    /// A maintenance slice runs on every turn of the loop and a turn is a
    /// hundred nanoseconds, so an ungated sweep would draw a fresh sample ten
    /// thousand times per millisecond and spend a real share of the shard on
    /// looking for keys that cannot have died since the last look. Nothing in a
    /// database changes fast enough to be worth asking about more often than the
    /// clock can tell the difference, and the clock here is milliseconds.
    ///
    /// A millisecond is also far finer than Redis, whose slow cycle runs at ten
    /// hertz, so this is not the thing that decides how promptly memory comes
    /// back. What it decides is that an idle server sweeps a thousand times a
    /// second rather than a million.
    pub fn expire_slice(&mut self, budget: usize) -> usize {
        let now = self.clock.now_ms();
        if now == self.expire_ms {
            return 0;
        }
        self.expire_ms = now;
        self.expire_step(budget)
    }

    /// Sweep dead keys out of the databases, spending at most `budget` looks.
    ///
    /// Answers what it spent, so the caller can charge its maintenance slice for
    /// it. See [`yo_kv::expiry`] for why the budget is in keys looked at.
    ///
    /// Round robin from its own cursor, and every database gets offered whatever
    /// is left of the budget rather than a sixteenth of it each, so a server on
    /// database zero only, which is nearly every server, spends the whole slice
    /// where the keys are. The fifteen empty ones cost a comparison apiece
    /// because a database with no key carrying a deadline says so without
    /// drawing anything.
    ///
    /// The cursor moves to the database after whichever one did the work, so two
    /// busy databases take turns instead of the lower numbered one starving the
    /// other.
    pub fn expire_step(&mut self, budget: usize) -> usize {
        let mut spent = 0;
        for turn in 0..self.dbs.len() {
            if spent >= budget {
                break;
            }
            let i = (self.expire_db + turn) % self.dbs.len();
            let c = self.dbs[i].expire_cycle(budget - spent);
            spent += c.examined;
            if c.expired > 0 {
                self.expire_db = (i + 1) % self.dbs.len();
                self.dirty |= 1u64 << i;
            }
        }
        spent
    }

    /// One slice of compaction for a server that is over its limit.
    ///
    /// Takes the databases in the same order [`Server::compact_step`] does and
    /// stops at the first one that had something to move, and it asks with the
    /// ratios off. See [`Keyspace::compact_hard`] for what that changes.
    fn compact_hard_step(&mut self) -> Option<usize> {
        for turn in 0..self.dbs.len() {
            let i = (self.next_db + turn) % self.dbs.len();
            if let Some(moved) = self.dbs[i].compact_hard() {
                self.next_db = (i + 1) % self.dbs.len();
                return Some(moved);
            }
        }
        None
    }

    /// Give one database's dead space back, if any database has enough of it to
    /// be worth the move. `None` when no database had a candidate.
    ///
    /// Once per batch, next to the clock. Overwriting a key writes a new record
    /// and counts the old one dead, so without this a server holds everything
    /// it has ever written: 400000 sets over 100000 keys measured at 742 bytes
    /// a key against Redis at 144 for the same load, and the whole difference
    /// was dead records nothing ever came back for.
    ///
    /// At most one segment moves per call and the search starts one database
    /// further along each time, so the cost of asking is a comparison per
    /// database and the cost of acting is bounded by a segment.
    pub fn compact_step(&mut self) -> Option<usize> {
        for turn in 0..self.dbs.len() {
            let i = (self.next_db + turn) % self.dbs.len();
            // Nothing has run against this database since it last said it had
            // nothing to collect, so it still has nothing to collect and the
            // line it lives on stays where it is.
            if self.dirty & (1 << i) == 0 {
                continue;
            }
            if let Some(moved) = self.dbs[i].compact_step() {
                self.next_db = (i + 1) % self.dbs.len();
                return Some(moved);
            }
            self.dirty &= !(1u64 << i);
        }
        None
    }
}

impl Default for Server {
    fn default() -> Server {
        Server::new()
    }
}

/// What one connection has chosen.
pub struct Session {
    db: usize,
    id: u64,
    name: Vec<u8>,
}

impl Session {
    /// A new connection, on database zero with no name.
    #[must_use]
    pub fn new(id: u64) -> Session {
        Session {
            db: 0,
            id,
            name: Vec::new(),
        }
    }

    /// The connection id, which `HELLO` reports and `CLIENT` will.
    #[must_use]
    pub const fn id(&self) -> u64 {
        self.id
    }

    /// Which database this connection is working in.
    #[must_use]
    pub const fn db(&self) -> usize {
        self.db
    }

    /// The name the client gave itself, empty if it gave none.
    #[must_use]
    pub fn name(&self) -> &[u8] {
        &self.name
    }

    /// Put everything back the way it was when the connection was opened.
    ///
    /// The protocol is not here because it is not here: it lives in the reply
    /// buffer, and `RESET` sets it back there.
    pub fn reset(&mut self) {
        self.db = 0;
        self.name.clear();
    }

    /// Record the name from `HELLO ... SETNAME`.
    fn set_name(&mut self, name: &[u8]) {
        yo_alloc::allow(|| {
            self.name.clear();
            self.name.extend_from_slice(name);
        });
    }
}

/// Run one command and write its reply.
///
/// The name is looked up and the arity is checked here, once, so that no body
/// has to. Everything after that is the command's own.
pub fn execute(server: &mut Server, session: &mut Session, args: Args<'_>, out: &mut Out) -> Flow {
    // The decoder never produces a command with no name. If one ever arrives,
    // it is not something to answer.
    if args.is_empty() {
        return Flow::Continue;
    }
    server.stats.commands += 1;

    let Some(spec) = lookup(args.name()) else {
        write_error(out, &args::unknown_command(args));
        return Flow::Continue;
    };
    if !arity_ok(spec, args.len()) {
        write_error(out, &args::wrong_arity(spec.name));
        return Flow::Continue;
    }

    // The limit first, so a server with no `maxmemory`, which is the default and
    // is nearly all of them, pays one comparison against a field that is already
    // warm. Every command and not only the writes, because that is where Redis
    // puts it: making room is the server's job whatever the client asked for,
    // and the flag only decides who gets told no when there is no room to make.
    //
    // The flag is Redis's own `denyoom` and the list of commands carrying it is
    // Redis's list, so a command that only frees is let through with nothing
    // left, which is what lets a client dig itself out with `DEL`.
    if server.maxmemory != 0 && !server.make_room() && spec.flags.contains(&"denyoom") {
        out.error_line(b"OOM ", OOM);
        return Flow::Continue;
    }

    // Which databases the maintenance turn after this batch has to ask. Marked
    // for every command and not only for the writes, because a read can make
    // garbage too: a `GET` on a key whose expiry has passed reaps it, and the
    // record it dropped is exactly the kind of thing the collector is for.
    // `COPY`, `SWAPDB` and `FLUSHALL` reach a database nobody selected, so the
    // two groups that hold them mark all of them rather than the session's.
    server.dirty |= match spec.group {
        "string" | "set" | "hash" | "list" | "zset" | "array" => 1u64 << session.db,
        _ => ALL_DATABASES,
    };

    let mark = out.len();
    // Before the group, because the five that block are list commands and would
    // otherwise land in `lists`, which is handed one database and nothing that
    // could park a client. The flag is the right thing to branch on rather than
    // a list of names: it is what `COMMAND INFO` reports about exactly these
    // commands, and the sorted set and stream ones that arrive later carry it
    // too.
    let done = if spec.flags.contains(&"blocking") {
        blocking::execute(server, session, spec, args, out)
    } else {
        match spec.group {
            "string" => {
                let db = session.db;
                strings::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
            }
            "set" => {
                let db = session.db;
                sets::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
            }
            "hash" => {
                let db = session.db;
                hashes::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
            }
            "list" => {
                let db = session.db;
                lists::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
            }
            "zset" => {
                let db = session.db;
                zsets::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
            }
            "array" => {
                let db = session.db;
                arrays::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
            }
            // The one keyspace command that needs more than the databases,
            // because the socket it talks down is held on the server between
            // commands and not opened again for each one.
            "keyspace" if spec.name == "migrate" => {
                migrate::execute(server, session.db, args, out).map(|()| Flow::Continue)
            }
            // Every database and not the one the session is on, because `COPY` takes
            // a `DB n` and writes into a database nobody selected.
            "keyspace" => keyspace::execute(&mut server.dbs, session.db, spec, args, out)
                .map(|()| Flow::Continue),
            "scripting" => scripting::execute(spec, args, out).map(|()| Flow::Continue),
            _ => server::execute(server, session, spec, args, out),
        }
    };
    match done {
        Ok(flow) => flow,
        Err(e) => {
            out.truncate(mark);
            write_error(out, &e);
            Flow::Continue
        }
    }
}

/// The error line for an error value.
///
/// The prefix is what a client branches on, and there are only two of them in
/// this milestone: `WRONGTYPE` for a command sent at the wrong kind of value,
/// and `ERR` for everything else. The three errors that need a different one,
/// `NOPROTO`, `WRONGPASS` and `OOM`, are written where they are decided rather
/// than routed through here. `OOM` is not a [`Code`] of its own because
/// [`Code::Full`] already covers the string that is too long for
/// `proto-max-bulk-len`, and that one goes out as `ERR` on a real server.
fn write_error(out: &mut Out, e: &Error) {
    let prefix: &[u8] = match e.code() {
        Code::WrongType => b"WRONGTYPE ",
        _ => b"ERR ",
    };
    out.error_line(prefix, e.message().as_bytes());
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::proto::{Limits, Proto};
    use crate::request::Argv;

    /// Build the wire bytes for a command.
    ///
    /// Tests go through the codec rather than around it, so an argument in a
    /// test is the same borrowed slice a connection produces.
    pub(crate) fn encode(parts: &[&[u8]]) -> Vec<u8> {
        let mut wire = format!("*{}\r\n", parts.len()).into_bytes();
        for p in parts {
            wire.extend_from_slice(format!("${}\r\n", p.len()).as_bytes());
            wire.extend_from_slice(p);
            wire.extend_from_slice(b"\r\n");
        }
        wire
    }

    /// A server, a connection and a buffer, driven the way the reactor will.
    struct Fixture {
        server: Server,
        session: Session,
        argv: Argv,
        out: Out,
    }

    impl Fixture {
        fn new() -> Fixture {
            Fixture {
                server: Server::new(),
                session: Session::new(7),
                argv: Argv::new(),
                out: Out::new(Proto::Resp2),
            }
        }

        /// Run one command and answer with the bytes it wrote.
        fn run(&mut self, parts: &[&[u8]]) -> String {
            self.flow(parts).1
        }

        /// Run one command and answer with the bytes exactly as written.
        ///
        /// [`Fixture::run`] goes through `from_utf8_lossy`, which is fine for
        /// every reply that is text and destroys a `DUMP` payload, since a
        /// payload is arbitrary bytes and a checksum on the end of them.
        fn raw(&mut self, parts: &[&[u8]]) -> Vec<u8> {
            let wire = encode(parts);
            self.argv.decode(&wire, &Limits::default()).unwrap();
            self.out.clear();
            execute(
                &mut self.server,
                &mut self.session,
                Args::new(&self.argv, &wire),
                &mut self.out,
            );
            self.out.as_slice().to_vec()
        }

        /// Move every clock in the server on by `ms`.
        fn advance(&mut self, ms: u64) {
            for db in 0..DATABASES {
                self.server.db(db).clock_mut().advance(ms);
            }
        }

        /// The same, with what the connection should do next.
        fn flow(&mut self, parts: &[&[u8]]) -> (Flow, String) {
            let wire = encode(parts);
            self.argv.decode(&wire, &Limits::default()).unwrap();
            self.out.clear();
            let flow = execute(
                &mut self.server,
                &mut self.session,
                Args::new(&self.argv, &wire),
                &mut self.out,
            );
            (
                flow,
                String::from_utf8_lossy(self.out.as_slice()).into_owned(),
            )
        }
    }

    /// What a client does all day: write the same keys again and again. Every
    /// one of those writes leaves the previous record behind, so a server that
    /// never compacts holds every version of every key it has ever been sent.
    #[test]
    fn rewriting_the_same_keys_does_not_grow_the_server() {
        let mut f = Fixture::new();
        let val = vec![b'v'; 1024];
        let keys: Vec<Vec<u8>> = (0..64).map(|i| format!("key:{i}").into_bytes()).collect();

        for k in &keys {
            f.run(&[b"SET", k, &val]);
        }
        f.server.compact_step();
        let after_first = f.server.memory_bytes();

        // 64 KiB a pass, five hundred passes, and the same 64 keys at the end
        // of it. Thirty two megabytes written to hold sixty four kilobytes,
        // which is the shape of a real workload and is enough churn to fill
        // sixteen segments if nothing ever comes back.
        for _ in 0..500 {
            for k in &keys {
                f.run(&[b"SET", k, &val]);
            }
            f.server.compact_step();
        }

        assert!(
            f.server.memory_bytes() <= after_first * 2,
            "held {} after five hundred passes against {after_first} after one",
            f.server.memory_bytes()
        );
        assert_eq!(f.run(&[b"DBSIZE"]), format!(":{}\r\n", keys.len()));
        assert_eq!(f.run(&[b"STRLEN", b"key:7"]), ":1024\r\n");
    }

    /// The same churn on a database nobody starts on, either side of a quiet
    /// spell long enough for the maintenance turn to stop asking about it.
    ///
    /// The turn after each batch skips a database that has already said it has
    /// nothing to collect and has not been touched since, which is what keeps a
    /// server whose clients are all on database zero from loading and storing
    /// in the other fifteen every batch to be told no. Two things could go
    /// wrong with that. A database might never be marked at all, so this uses
    /// database nine, which nothing marks by accident. And a database whose
    /// mark was cleared might never get it back, so this drains the collector
    /// until it says there is nothing left, checks the mark really is gone, and
    /// then writes another thirty two megabytes through the same sixty four
    /// keys. If either went wrong the server would hold all of it.
    #[test]
    fn a_database_nobody_started_on_is_still_collected() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SELECT", b"9"]), "+OK\r\n");
        let val = vec![b'v'; 1024];
        let keys: Vec<Vec<u8>> = (0..64).map(|i| format!("key:{i}").into_bytes()).collect();

        for k in &keys {
            f.run(&[b"SET", k, &val]);
        }
        while f.server.compact_step().is_some() {}
        assert_eq!(
            f.server.dirty & (1 << 9),
            0,
            "database nine was drained and should not be asked again until it is written to"
        );
        let after_first = f.server.memory_bytes();

        for _ in 0..500 {
            for k in &keys {
                f.run(&[b"SET", k, &val]);
            }
            f.server.compact_step();
        }

        assert!(
            f.server.memory_bytes() <= after_first * 2,
            "held {} after five hundred passes against {after_first} after one",
            f.server.memory_bytes()
        );
        assert_eq!(f.run(&[b"DBSIZE"]), format!(":{}\r\n", keys.len()));
        assert_eq!(f.run(&[b"STRLEN", b"key:7"]), ":1024\r\n");
        // And nothing landed anywhere else on the way.
        f.run(&[b"SELECT", b"0"]);
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
    }

    #[test]
    fn a_command_goes_from_bytes_to_bytes() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SET", b"k", b"v"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"k"]), "$1\r\nv\r\n");
        assert_eq!(f.run(&[b"GET", b"nosuch"]), "$-1\r\n");
        assert_eq!(f.run(&[b"STRLEN", b"k"]), ":1\r\n");
        // The name is matched whatever case it came in, and so are the options.
        assert_eq!(f.run(&[b"set", b"k", b"v2", b"xx"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"k"]), "$2\r\nv2\r\n");
    }

    #[test]
    fn deleting_counts_keys_removed_and_existing_counts_arguments_matched() {
        let mut f = Fixture::new();
        f.run(&[b"MSET", b"a", b"1", b"b", b"2", b"c", b"3"]);
        // A key named twice exists twice and can only be deleted once, and both
        // of those are Redis's answers rather than tidier ones.
        assert_eq!(f.run(&[b"EXISTS", b"a", b"a", b"nosuch"]), ":2\r\n");
        assert_eq!(f.run(&[b"DEL", b"a", b"a", b"nosuch"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"a"]), ":0\r\n");
        // UNLINK is the same body and reports the same way.
        assert_eq!(f.run(&[b"UNLINK", b"b", b"c"]), ":2\r\n");
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
    }

    #[test]
    fn type_is_a_simple_string_and_says_none_for_a_key_that_is_not_there() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"k", b"v"]);
        // A simple string on both protocols, which is unusual: most replies
        // that carry a word are bulk strings.
        assert_eq!(f.run(&[b"TYPE", b"k"]), "+string\r\n");
        assert_eq!(f.run(&[b"TYPE", b"nosuch"]), "+none\r\n");
    }

    #[test]
    fn touch_counts_the_way_exists_counts() {
        let mut f = Fixture::new();
        f.run(&[b"MSET", b"a", b"1", b"b", b"2"]);
        assert_eq!(f.run(&[b"TOUCH", b"a", b"b"]), ":2\r\n");
        assert_eq!(
            f.run(&[b"TOUCH", b"a", b"a"]),
            ":2\r\n",
            "twice counts twice"
        );
        assert_eq!(f.run(&[b"TOUCH", b"a", b"nosuch"]), ":1\r\n");
        assert_eq!(f.run(&[b"TOUCH", b"nosuch"]), ":0\r\n");
    }

    #[test]
    fn a_rename_moves_the_deadline_with_the_value_and_drops_the_one_it_lands_on() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"v1", b"EX", b"100"]);
        f.run(&[b"SET", b"b", b"v2", b"EX", b"500"]);

        assert_eq!(f.run(&[b"RENAME", b"a", b"b"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"b"]), "$2\r\nv1\r\n");
        assert_eq!(
            f.run(&[b"TTL", b"b"]),
            ":100\r\n",
            "the source's and not b's"
        );
        assert_eq!(f.run(&[b"EXISTS", b"a"]), ":0\r\n");
    }

    #[test]
    fn a_rename_with_no_source_is_an_error_and_not_a_zero() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"RENAME", b"a", b"b"]), "-ERR no such key\r\n");
        // The source is checked before the destination, so this is the error
        // and not the zero RENAMENX would otherwise answer for a taken name.
        assert_eq!(f.run(&[b"RENAMENX", b"a", b"a"]), "-ERR no such key\r\n");
    }

    #[test]
    fn renamenx_refuses_a_taken_name_including_the_one_it_already_has() {
        let mut f = Fixture::new();
        f.run(&[b"MSET", b"a", b"v1", b"b", b"v2"]);

        assert_eq!(f.run(&[b"RENAMENX", b"a", b"b"]), ":0\r\n");
        assert_eq!(f.run(&[b"GET", b"b"]), "$2\r\nv2\r\n");
        // Renaming onto itself is 0 here and OK for plain RENAME, which is the
        // one call the two disagree about and neither does any work for.
        assert_eq!(f.run(&[b"RENAMENX", b"a", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"RENAME", b"a", b"a"]), "+OK\r\n");
        assert_eq!(f.run(&[b"RENAMENX", b"a", b"c"]), ":1\r\n");
        assert_eq!(f.run(&[b"GET", b"c"]), "$2\r\nv1\r\n");
    }

    #[test]
    fn renaming_a_set_does_not_touch_a_member() {
        let mut f = Fixture::new();
        for i in 0..300 {
            f.run(&[b"SADD", b"s", format!("m{i}").as_bytes()]);
        }
        let before = f.server.memory_bytes();

        assert_eq!(f.run(&[b"RENAME", b"s", b"t"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SCARD", b"t"]), ":300\r\n");
        assert_eq!(f.run(&[b"TYPE", b"t"]), "+set\r\n");
        assert!(
            f.server.memory_bytes().abs_diff(before) < 256,
            "the members were copied: {} against {before}",
            f.server.memory_bytes()
        );
    }

    #[test]
    fn a_copy_is_a_second_value_and_not_a_second_name() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"m1", b"m2"]);

        assert_eq!(f.run(&[b"COPY", b"s", b"t"]), ":1\r\n");
        f.run(&[b"SADD", b"t", b"m3"]);
        assert_eq!(f.run(&[b"SCARD", b"s"]), ":2\r\n", "the original is intact");
        assert_eq!(f.run(&[b"SCARD", b"t"]), ":3\r\n");
    }

    /// Every type a key can hold, copied, because two of them used to panic.
    ///
    /// `COPY` reads the value out of the source through one match on the type
    /// tag, and that match had a catch all at the bottom from back when a set
    /// and a hash were the only bodies. The list and the sorted set landed after
    /// it and nobody came back, so `COPY mylist other` took the shard down. It
    /// is an ordinary command against a type the server supports everywhere
    /// else, so this walks all five rather than the two that were broken: the
    /// point is that the next type cannot land the same way.
    #[test]
    fn every_type_can_be_copied() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v1"]);
        f.run(&[b"SADD", b"set", b"m1"]);
        f.run(&[b"HSET", b"hash", b"f", b"v"]);
        f.run(&[b"RPUSH", b"list", b"a", b"b"]);
        f.run(&[b"ZADD", b"zset", b"1", b"m1"]);

        for name in [
            &b"str"[..],
            &b"set"[..],
            &b"hash"[..],
            &b"list"[..],
            &b"zset"[..],
        ] {
            let dst = [name, b":copy"].concat();
            assert_eq!(
                f.run(&[b"COPY", name, &dst]),
                ":1\r\n",
                "copying {}",
                String::from_utf8_lossy(name)
            );
            assert_eq!(f.run(&[b"TYPE", name]), f.run(&[b"TYPE", &dst]));
        }

        assert_eq!(f.run(&[b"LRANGE", b"list:copy", b"0", b"-1"]), {
            let mut want = String::from("*2\r\n");
            want.push_str("$1\r\na\r\n$1\r\nb\r\n");
            want
        });
        assert_eq!(f.run(&[b"ZSCORE", b"zset:copy", b"m1"]), "$1\r\n1\r\n");

        // And the copy is its own value, not a second name for the source.
        f.run(&[b"RPUSH", b"list:copy", b"c"]);
        assert_eq!(f.run(&[b"LLEN", b"list"]), ":2\r\n");
        assert_eq!(f.run(&[b"LLEN", b"list:copy"]), ":3\r\n");
    }

    #[test]
    fn a_copy_refuses_a_taken_destination_until_it_is_told_it_can_have_it() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"v1", b"EX", b"100"]);
        f.run(&[b"SET", b"b", b"v2"]);

        assert_eq!(f.run(&[b"COPY", b"a", b"b"]), ":0\r\n");
        assert_eq!(f.run(&[b"GET", b"b"]), "$2\r\nv2\r\n");
        assert_eq!(f.run(&[b"COPY", b"a", b"b", b"REPLACE"]), ":1\r\n");
        assert_eq!(f.run(&[b"GET", b"b"]), "$2\r\nv1\r\n");
        assert_eq!(f.run(&[b"TTL", b"b"]), ":100\r\n", "the deadline came too");
        assert_eq!(f.run(&[b"COPY", b"nosuch", b"z"]), ":0\r\n");
    }

    #[test]
    fn a_copy_into_another_database_is_a_copy_and_onto_itself_there_is_too() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"v1"]);

        // Same key, different database, so this is not the same object and is
        // an ordinary copy. Same key in the same database is the error below.
        assert_eq!(f.run(&[b"COPY", b"a", b"a", b"DB", b"1"]), ":1\r\n");
        f.run(&[b"SELECT", b"1"]);
        assert_eq!(f.run(&[b"GET", b"a"]), "$2\r\nv1\r\n");
        assert_eq!(
            f.run(&[b"COPY", b"a", b"a", b"DB", b"0"]),
            ":0\r\n",
            "taken"
        );
        assert_eq!(
            f.run(&[b"COPY", b"a", b"a", b"DB", b"0", b"REPLACE"]),
            ":1\r\n"
        );
    }

    #[test]
    fn sort_takes_its_options_in_any_order_and_the_last_one_wins() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"l", b"3", b"1", b"2"]);
        assert_eq!(
            f.run(&[b"SORT", b"l"]),
            "*3\r\n$1\r\n1\r\n$1\r\n2\r\n$1\r\n3\r\n"
        );
        // DESC then ASC is ASC, because the only thing ASC does is undo a DESC.
        assert_eq!(
            f.run(&[b"SORT", b"l", b"DESC", b"asc"]),
            "*3\r\n$1\r\n1\r\n$1\r\n2\r\n$1\r\n3\r\n"
        );
        assert_eq!(
            f.run(&[b"sort", b"l", b"LIMIT", b"1", b"1", b"DESC"]),
            "*1\r\n$1\r\n2\r\n"
        );
    }

    #[test]
    fn sort_reads_a_key_per_element_for_by_and_for_get() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"l", b"a", b"b"]);
        f.run(&[b"MSET", b"w_a", b"2", b"w_b", b"1", b"d_b", b"bee"]);
        // `b` weighs less so it comes first, and its `GET` hits where `a`'s
        // misses, which is a nil in the middle of the array and not a short one.
        assert_eq!(
            f.run(&[b"SORT", b"l", b"BY", b"w_*", b"GET", b"#", b"GET", b"d_*"]),
            "*4\r\n$1\r\nb\r\n$3\r\nbee\r\n$1\r\na\r\n$-1\r\n"
        );
    }

    #[test]
    fn sort_store_writes_a_list_and_answers_its_length() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"l", b"3", b"1", b"2"]);
        assert_eq!(f.run(&[b"SORT", b"l", b"STORE", b"out"]), ":3\r\n");
        assert_eq!(f.run(&[b"TYPE", b"out"]), "+list\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"out", b"0", b"-1"]),
            "*3\r\n$1\r\n1\r\n$1\r\n2\r\n$1\r\n3\r\n"
        );
        // An empty result takes the destination with it rather than leaving a
        // list that holds nothing.
        assert_eq!(f.run(&[b"SORT", b"missing", b"STORE", b"out"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"out"]), ":0\r\n");
    }

    #[test]
    fn sort_ro_does_not_know_the_word_store() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"l", b"2", b"1"]);
        assert_eq!(f.run(&[b"SORT_RO", b"l"]), "*2\r\n$1\r\n1\r\n$1\r\n2\r\n");
        assert_eq!(
            f.run(&[b"SORT_RO", b"l", b"STORE", b"d"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
    }

    #[test]
    fn sort_refuses_what_it_cannot_sort() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SORT", b"nosuchkey"]), "*0\r\n");
        f.run(&[b"SET", b"s", b"x"]);
        assert_eq!(
            f.run(&[b"SORT", b"s"]),
            "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
        );
        f.run(&[b"RPUSH", b"words", b"one", b"two"]);
        assert_eq!(
            f.run(&[b"SORT", b"words"]),
            "-ERR One or more scores can't be converted into double\r\n"
        );
        assert_eq!(
            f.run(&[b"SORT", b"words", b"ALPHA"]),
            "*2\r\n$3\r\none\r\n$3\r\ntwo\r\n"
        );
        assert_eq!(f.run(&[b"SORT", b"words", b"BY"]), "-ERR syntax error\r\n");
    }

    #[test]
    fn move_takes_the_key_out_of_one_database_and_puts_it_in_another() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"RPUSH", b"l", b"a", b"b"]), ":2\r\n");
        assert_eq!(f.run(&[b"MOVE", b"l", b"1"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"l"]), ":0\r\n");
        assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"l", b"0", b"-1"]),
            "*2\r\n$1\r\na\r\n$1\r\nb\r\n"
        );
        // And back, which proves the body survived the trip rather than being
        // rebuilt from a copy that happened to look the same.
        assert_eq!(f.run(&[b"MOVE", b"l", b"0"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"l"]), ":0\r\n");
    }

    #[test]
    fn move_answers_zero_when_either_end_says_no() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"MOVE", b"nope", b"1"]), ":0\r\n");
        assert_eq!(f.run(&[b"SET", b"a", b"here"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SET", b"a", b"there"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SELECT", b"0"]), "+OK\r\n");
        // The destination is taken, so nothing moves and the source is still
        // there with what it had.
        assert_eq!(f.run(&[b"MOVE", b"a", b"1"]), ":0\r\n");
        assert_eq!(f.run(&[b"GET", b"a"]), "$4\r\nhere\r\n");
        assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"a"]), "$5\r\nthere\r\n");
    }

    #[test]
    fn move_refuses_a_database_that_is_not_one_and_the_one_it_is_on() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"MOVE", b"a", b"0"]),
            "-ERR source and destination objects are the same\r\n"
        );
        assert_eq!(
            f.run(&[b"MOVE", b"a", b"99"]),
            "-ERR DB index is out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"MOVE", b"a", b"-1"]),
            "-ERR DB index is out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"MOVE", b"a", b"x"]),
            "-ERR value is not an integer or out of range\r\n"
        );
    }

    #[test]
    fn swapdb_swaps_what_two_connections_would_see() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SET", b"k", b"zero"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SET", b"k", b"one"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SELECT", b"0"]), "+OK\r\n");

        assert_eq!(f.run(&[b"SWAPDB", b"0", b"1"]), "+OK\r\n");
        // Still on database zero, and database zero is a different database.
        assert_eq!(f.run(&[b"GET", b"k"]), "$3\r\none\r\n");
        assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"k"]), "$4\r\nzero\r\n");
        // A database swapped with itself is fine and changes nothing.
        assert_eq!(f.run(&[b"SWAPDB", b"1", b"1"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"k"]), "$4\r\nzero\r\n");
    }

    #[test]
    fn swapdb_says_which_index_it_could_not_read() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"SWAPDB", b"x", b"1"]),
            "-ERR invalid first DB index\r\n"
        );
        assert_eq!(
            f.run(&[b"SWAPDB", b"0", b"y"]),
            "-ERR invalid second DB index\r\n"
        );
        // A number too big to be an index on a server that keeps one in an int
        // is the same complaint, and a plausible one that is not ours is the
        // range complaint instead. The split is Redis's.
        assert_eq!(
            f.run(&[b"SWAPDB", b"99999999999999", b"1"]),
            "-ERR invalid first DB index\r\n"
        );
        assert_eq!(
            f.run(&[b"SWAPDB", b"0", b"99"]),
            "-ERR DB index is out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"SWAPDB", b"-1", b"0"]),
            "-ERR DB index is out of range\r\n"
        );
    }

    #[test]
    fn wait_answers_zero_replicas_without_waiting() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SET", b"a", b"v"]), "+OK\r\n");
        assert_eq!(f.run(&[b"WAIT", b"0", b"0"]), ":0\r\n");
        // A replica that is never going to arrive, and a timeout that would be
        // a real wait on a server that had one.
        assert_eq!(f.run(&[b"WAIT", b"3", b"1000"]), ":0\r\n");
        // Negative replicas is not an error, because zero is already more than
        // it asked for.
        assert_eq!(f.run(&[b"WAIT", b"-1", b"0"]), ":0\r\n");
        assert_eq!(
            f.run(&[b"WAIT", b"x", b"0"]),
            "-ERR value is not an integer or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"WAIT", b"0", b"-1"]),
            "-ERR timeout is negative\r\n"
        );
        assert_eq!(
            f.run(&[b"WAIT", b"0", b"1.5"]),
            "-ERR timeout is not an integer or out of range\r\n"
        );
    }

    #[test]
    fn waitaof_answers_two_zeroes_and_refuses_a_local_wait() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"WAITAOF", b"0", b"0", b"0"]), "*2\r\n:0\r\n:0\r\n");
        assert_eq!(
            f.run(&[b"WAITAOF", b"1", b"0", b"0"]),
            "-ERR WAITAOF cannot be used when numlocal is set but appendonly is disabled.\r\n"
        );
        assert_eq!(
            f.run(&[b"WAITAOF", b"2", b"0", b"0"]),
            "-ERR value is out of range, value must between 0 and 1\r\n"
        );
        assert_eq!(
            f.run(&[b"WAITAOF", b"0", b"-1", b"0"]),
            "-ERR value is out of range, must be positive\r\n"
        );
        // The arguments are all read before the server looks at itself, so a
        // bad timeout beats the append only complaint even with numlocal set.
        assert_eq!(
            f.run(&[b"WAITAOF", b"1", b"0", b"-5"]),
            "-ERR timeout is negative\r\n"
        );
    }

    /// The bytes inside a bulk reply, with the header and the trailing break
    /// taken off. Every `DUMP` test needs this and none of them care how the
    /// length was written.
    fn payload(reply: &[u8]) -> Vec<u8> {
        let head = reply.windows(2).position(|w| w == b"\r\n").unwrap();
        reply[head + 2..reply.len() - 2].to_vec()
    }

    #[test]
    fn a_value_survives_a_dump_and_a_restore() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"s", b"hello"]);
        f.run(&[b"RPUSH", b"l", b"a", b"b", b"c"]);
        f.run(&[b"SADD", b"t", b"1", b"2", b"3"]);
        f.run(&[b"SADD", b"u", b"x", b"y"]);
        f.run(&[b"HSET", b"h", b"f", b"1", b"g", b"2"]);
        f.run(&[b"ZADD", b"z", b"1.5", b"a", b"2.5", b"b"]);

        for key in [&b"s"[..], b"l", b"t", b"u", b"h", b"z"] {
            let mut copy = key.to_vec();
            copy.push(b'2');
            let bytes = payload(&f.raw(&[b"DUMP", key]));
            assert_eq!(f.run(&[b"RESTORE", &copy, b"0", &bytes]), "+OK\r\n");
            assert_eq!(f.run(&[b"TYPE", &copy]), f.run(&[b"TYPE", key]));
        }

        assert_eq!(f.run(&[b"GET", b"s2"]), "$5\r\nhello\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"l2", b"0", b"-1"]),
            "*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"t2"])), ["1", "2", "3"]);
        assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"u2"])), ["x", "y"]);
        assert_eq!(f.run(&[b"HGET", b"h2", b"g"]), "$1\r\n2\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z2", b"b"]), "$3\r\n2.5\r\n");
        // The encoding survives too, since the payload names the plainest legal
        // type and the loader puts the value back on the rung it belongs on.
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING", b"t2"]),
            f.run(&[b"OBJECT", b"ENCODING", b"t"])
        );
    }

    #[test]
    fn a_dumped_hash_keeps_its_field_deadlines() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"keep", b"1", b"go", b"2"]);
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"100", b"FIELDS", b"1", b"go"]),
            "*1\r\n:1\r\n"
        );
        let bytes = payload(&f.raw(&[b"DUMP", b"h"]));
        assert_eq!(f.run(&[b"RESTORE", b"h2", b"0", &bytes]), "+OK\r\n");
        assert_eq!(
            f.run(&[b"HTTL", b"h2", b"FIELDS", b"2", b"keep", b"go"]),
            "*2\r\n:-1\r\n:100\r\n"
        );
    }

    #[test]
    fn dump_leaves_the_deadline_behind_and_restore_is_given_a_new_one() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"v", b"EX", b"100"]);
        let bytes = payload(&f.raw(&[b"DUMP", b"a"]));
        assert_eq!(f.run(&[b"RESTORE", b"b", b"0", &bytes]), "+OK\r\n");
        assert_eq!(f.run(&[b"TTL", b"b"]), ":-1\r\n");
        assert_eq!(f.run(&[b"RESTORE", b"c", b"5000", &bytes]), "+OK\r\n");
        assert_eq!(f.run(&[b"TTL", b"c"]), ":5\r\n");
        // An absolute deadline that has already gone is not an error. The key is
        // not created and the reply is the same OK a live one gets.
        assert_eq!(
            f.run(&[b"RESTORE", b"d", b"1", &bytes, b"ABSTTL"]),
            "+OK\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
    }

    #[test]
    fn dump_answers_nothing_for_a_key_that_is_not_there() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"DUMP", b"nope"]), "$-1\r\n");
        f.run(&[b"SET", b"gone", b"v", b"PX", b"10"]);
        f.advance(50);
        assert_eq!(f.run(&[b"DUMP", b"gone"]), "$-1\r\n");
    }

    #[test]
    fn restore_refuses_a_key_that_is_there_unless_it_is_told_to_replace() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"first"]);
        f.run(&[b"SET", b"b", b"second"]);
        let bytes = payload(&f.raw(&[b"DUMP", b"b"]));
        assert_eq!(
            f.run(&[b"RESTORE", b"a", b"0", &bytes]),
            "-BUSYKEY Target key name already exists.\r\n"
        );
        assert_eq!(f.run(&[b"GET", b"a"]), "$5\r\nfirst\r\n");
        assert_eq!(
            f.run(&[b"RESTORE", b"a", b"0", &bytes, b"REPLACE"]),
            "+OK\r\n"
        );
        assert_eq!(f.run(&[b"GET", b"a"]), "$6\r\nsecond\r\n");
    }

    /// The busy key comes before the payload, which is not the order the
    /// arguments read in. Whether a key is taken should not depend on whether
    /// the bytes behind it happened to be good.
    #[test]
    fn restore_asks_about_the_key_before_it_looks_at_the_bytes() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"v"]);
        assert_eq!(
            f.run(&[b"RESTORE", b"a", b"0", b"rubbish"]),
            "-BUSYKEY Target key name already exists.\r\n"
        );
        // And the options come before even that, so a bad FREQ beats the busy
        // key the same way a bad DB beats a missing source in COPY.
        assert_eq!(
            f.run(&[b"RESTORE", b"a", b"0", b"rubbish", b"FREQ", b"300"]),
            "-ERR Invalid FREQ value, must be >= 0 and <= 255\r\n"
        );
    }

    #[test]
    fn restore_can_tell_a_bad_footer_from_bad_bytes() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"hello"]);
        let good = payload(&f.raw(&[b"DUMP", b"a"]));

        let mut flipped = good.clone();
        flipped[2] ^= 0x40;
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"0", &flipped]),
            "-ERR DUMP payload version or checksum are wrong\r\n"
        );
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"0", b"short"]),
            "-ERR DUMP payload version or checksum are wrong\r\n"
        );
        // A footer that is right over a body that is not. The type byte says
        // string and there is nothing behind it, so the checksum agrees and the
        // value does not exist.
        let mut truncated = good[..1].to_vec();
        truncated.extend_from_slice(&good[good.len() - 10..good.len() - 8]);
        let crc = yo_common::crc::crc64(0, &truncated);
        truncated.extend_from_slice(&crc.to_le_bytes());
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"0", &truncated]),
            "-ERR Bad data format\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"b"]), ":0\r\n");
    }

    #[test]
    fn restore_checks_the_three_numbers_a_client_can_get_wrong() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"v"]);
        let bytes = payload(&f.raw(&[b"DUMP", b"a"]));
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"-1", &bytes]),
            "-ERR Invalid TTL value, must be >= 0\r\n"
        );
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"0", &bytes, b"IDLETIME", b"-1"]),
            "-ERR Invalid IDLETIME value, must be >= 0\r\n"
        );
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"0", &bytes, b"FREQ", b"256"]),
            "-ERR Invalid FREQ value, must be >= 0 and <= 255\r\n"
        );
        // Both are accepted and both are then dropped, which is D-26.
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"0", &bytes, b"IDLETIME", b"90"]),
            "+OK\r\n"
        );
        assert_eq!(
            f.run(&[b"RESTORE", b"c", b"0", &bytes, b"FREQ", b"200", b"REPLACE"]),
            "+OK\r\n"
        );
    }

    /// Neither word is refused for being the wrong one. Each is only accepted
    /// while the other is unset, so the second of the two falls through to the
    /// plain syntax error rather than getting a message of its own.
    #[test]
    fn restore_takes_idletime_or_freq_and_not_both() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"a", b"v"]);
        let bytes = payload(&f.raw(&[b"DUMP", b"a"]));
        assert_eq!(
            f.run(&[
                b"RESTORE",
                b"b",
                b"0",
                &bytes,
                b"IDLETIME",
                b"1",
                b"FREQ",
                b"2"
            ]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[
                b"RESTORE",
                b"b",
                b"0",
                &bytes,
                b"FREQ",
                b"2",
                b"IDLETIME",
                b"1"
            ]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"0", &bytes, b"FREQ"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"RESTORE", b"b", b"0", &bytes, b"NOSUCH"]),
            "-ERR syntax error\r\n"
        );
    }

    #[test]
    fn copy_checks_its_options_before_it_looks_for_anything() {
        let mut f = Fixture::new();
        // No key exists at all, and every one of these is still the option
        // complaint rather than a zero, which is the order a real server uses.
        assert_eq!(
            f.run(&[b"COPY", b"a", b"b", b"DB", b"99"]),
            "-ERR DB index is out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"COPY", b"a", b"b", b"DB", b"-1"]),
            "-ERR DB index is out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"COPY", b"a", b"b", b"DB", b"x"]),
            "-ERR value is not an integer or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"COPY", b"a", b"b", b"nonsense"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"COPY", b"a", b"a"]),
            "-ERR source and destination objects are the same\r\n"
        );
        // Repeated, reordered and lowercased, and the last DB wins.
        assert_eq!(
            f.run(&[b"COPY", b"a", b"b", b"dB", b"1", b"rEpLaCe", b"db", b"2"]),
            ":0\r\n"
        );
    }

    #[test]
    fn time_is_two_bulk_strings_and_moves() {
        let mut f = Fixture::new();
        let first = f.run(&[b"TIME"]);
        assert!(first.starts_with("*2\r\n$"), "got {first}");
        let parts: Vec<&str> = first.split("\r\n").collect();
        let secs: i64 = parts[2].parse().expect("seconds as decimal text");
        let micros: i64 = parts[4].parse().expect("microseconds as decimal text");
        assert!(secs > 1_700_000_000, "a real wall clock, got {secs}");
        assert!((0..1_000_000).contains(&micros), "got {micros}");
        // The coarse clock the keyspace uses is a cached millisecond that a
        // background tick refreshes, so a TIME built on it would answer the
        // same microsecond twice in a row here.
        assert_ne!(first, f.run(&[b"TIME"]));
    }

    #[test]
    fn a_keyspace_scan_walks_every_key_once() {
        let mut f = Fixture::new();
        for i in 0..500 {
            f.run(&[b"SET", format!("k{i}").as_bytes(), b"v"]);
        }

        let mut seen: Vec<String> = Vec::new();
        let mut cursor = "0".to_owned();
        let mut calls = 0;
        loop {
            let (next, keys) = scan_reply(&f.run(&[b"SCAN", cursor.as_bytes(), b"COUNT", b"32"]));
            seen.extend(keys);
            cursor = next;
            calls += 1;
            assert!(calls < 10_000, "the cursor is not advancing");
            if cursor == "0" {
                break;
            }
        }

        seen.sort();
        seen.dedup();
        assert_eq!(seen.len(), 500, "every key once and only once");
        // And more than one call to get them, or the COUNT is being ignored and
        // the loop above proved nothing about resuming.
        assert!(calls > 1, "500 keys came back in one batch");
    }

    #[test]
    fn a_scan_narrows_by_pattern_and_by_type() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v"]);
        f.run(&[b"SADD", b"members", b"a"]);
        f.run(&[b"HSET", b"fields", b"f", b"v"]);

        let all = |f: &mut Fixture, args: &[&[u8]]| {
            let mut out: Vec<String> = Vec::new();
            let mut cursor = "0".to_owned();
            loop {
                let mut line: Vec<&[u8]> = vec![b"SCAN", cursor.as_bytes()];
                line.extend_from_slice(args);
                let (next, keys) = scan_reply(&f.run(&line));
                out.extend(keys);
                cursor = next;
                if cursor == "0" {
                    break;
                }
            }
            out.sort();
            out
        };

        assert_eq!(all(&mut f, &[]), ["fields", "members", "str"]);
        assert_eq!(all(&mut f, &[b"MATCH", b"*e*"]), ["fields", "members"]);
        assert_eq!(all(&mut f, &[b"TYPE", b"set"]), ["members"]);
        // Case insensitive, the same as Redis's own comparison.
        assert_eq!(all(&mut f, &[b"TYPE", b"HASH"]), ["fields"]);
        // A type nothing can hold is not an error, it just matches nothing.
        assert!(all(&mut f, &[b"TYPE", b"list"]).is_empty());
        assert!(all(&mut f, &[b"TYPE", b"banana"]).is_empty());
        // Both filters at once, and they are an and rather than an or.
        assert!(all(&mut f, &[b"MATCH", b"str*", b"TYPE", b"set"]).is_empty());
    }

    #[test]
    fn a_scan_says_what_is_wrong_with_it() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SCAN", b"nope"]), "-ERR invalid cursor\r\n");
        assert_eq!(f.run(&[b"SCAN", b"-1"]), "-ERR invalid cursor\r\n");
        assert_eq!(f.run(&[b"SCAN", b"0", b"MATCH"]), "-ERR syntax error\r\n");
        assert_eq!(
            f.run(&[b"SCAN", b"0", b"COUNT", b"0"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"SCAN", b"0", b"COUNT", b"x"]),
            "-ERR value is not an integer or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"SCAN", b"0", b"WAT", b"1"]),
            "-ERR syntax error\r\n"
        );
        // A cursor the client made up is a cursor. It resumes somewhere
        // arbitrary and answers whatever is there, which is what Redis does and
        // is the only behaviour that does not need the server to remember every
        // cursor it has handed out.
        assert!(f.run(&[b"SCAN", b"18446744073709551615"]).starts_with("*2"));
    }

    #[test]
    fn keys_and_randomkey_look_at_the_whole_database() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"KEYS", b"*"]), "*0\r\n");
        assert_eq!(f.run(&[b"RANDOMKEY"]), "$-1\r\n");

        for name in ["one", "two", "three"] {
            f.run(&[b"SET", name.as_bytes(), b"v"]);
        }
        assert_eq!(sorted(&f.run(&[b"KEYS", b"*"])), ["one", "three", "two"]);
        assert_eq!(sorted(&f.run(&[b"KEYS", b"t*"])), ["three", "two"]);
        assert_eq!(f.run(&[b"KEYS", b"nothing"]), "*0\r\n");

        for _ in 0..50 {
            let got = f.run(&[b"RANDOMKEY"]);
            assert!(
                ["$3\r\none\r\n", "$3\r\ntwo\r\n", "$5\r\nthree\r\n"].contains(&got.as_str()),
                "got {got}"
            );
        }
    }

    #[test]
    fn a_walk_does_not_answer_keys_that_have_expired() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"alive", b"v"]);
        f.run(&[b"SET", b"dead", b"v", b"PX", b"1"]);
        f.server.db(0).clock_mut().advance(2);
        assert_eq!(
            f.run(&[b"DBSIZE"]),
            ":2\r\n",
            "nothing has collected it yet"
        );

        assert_eq!(f.run(&[b"KEYS", b"*"]), "*1\r\n$5\r\nalive\r\n");
        let (_, keys) = scan_reply(&f.run(&[b"SCAN", b"0", b"COUNT", b"1000"]));
        assert_eq!(keys, ["alive"]);
        for _ in 0..20 {
            assert_eq!(f.run(&[b"RANDOMKEY"]), "$5\r\nalive\r\n");
        }
        // The walk collected it on the way past, which is what makes DBSIZE
        // here answer what Redis answers once its own cycle has been round.
        assert_eq!(f.run(&[b"DBSIZE"]), ":1\r\n");
    }

    #[test]
    fn a_key_deadline_goes_on_and_comes_back_in_all_four_units() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"k", b"v"]);
        assert_eq!(f.run(&[b"TTL", b"k"]), ":-1\r\n", "there and no deadline");
        assert_eq!(f.run(&[b"TTL", b"nosuch"]), ":-2\r\n", "not there at all");

        assert_eq!(f.run(&[b"EXPIRE", b"k", b"100"]), ":1\r\n");
        assert_eq!(f.run(&[b"TTL", b"k"]), ":100\r\n");
        let ms = int(&f.run(&[b"PTTL", b"k"]));
        assert!((99_000..=100_000).contains(&ms), "got {ms}");

        // The absolute pair, derived from the same one number the store kept.
        let at = int(&f.run(&[b"EXPIRETIME", b"k"]));
        let at_ms = int(&f.run(&[b"PEXPIRETIME", b"k"]));
        assert_eq!(at, (at_ms + 500) / 1000);
        assert!(at_ms > 1_700_000_000_000, "an absolute moment, got {at_ms}");

        assert_eq!(f.run(&[b"PERSIST", b"k"]), ":1\r\n");
        assert_eq!(f.run(&[b"TTL", b"k"]), ":-1\r\n");
        assert_eq!(
            f.run(&[b"PERSIST", b"k"]),
            ":0\r\n",
            "nothing to take off the second time"
        );
        assert_eq!(f.run(&[b"PERSIST", b"nosuch"]), ":0\r\n");
        assert_eq!(
            f.run(&[b"GET", b"k"]),
            "$1\r\nv\r\n",
            "and the value went through all of that untouched"
        );
    }

    #[test]
    fn every_type_can_be_given_a_deadline_and_it_is_the_same_deadline() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v"]);
        f.run(&[b"SADD", b"set", b"a", b"b"]);
        f.run(&[b"HSET", b"hash", b"f", b"v"]);

        for key in [b"str".as_slice(), b"set", b"hash"] {
            assert_eq!(f.run(&[b"EXPIRE", key, b"100"]), ":1\r\n");
            assert_eq!(f.run(&[b"TTL", key]), ":100\r\n");
        }
        // The body is not touched by any of that, which is the whole reason the
        // deadline lives in the record and the body lives somewhere else.
        assert_eq!(f.run(&[b"SCARD", b"set"]), ":2\r\n");
        assert_eq!(f.run(&[b"HGET", b"hash", b"f"]), "$1\r\nv\r\n");
        assert_eq!(f.run(&[b"GET", b"str"]), "$1\r\nv\r\n");
    }

    #[test]
    fn a_deadline_that_has_already_gone_deletes_the_key_now() {
        let mut f = Fixture::new();
        for key in [b"a".as_slice(), b"b", b"c", b"d"] {
            f.run(&[b"SET", key, b"v"]);
        }
        // Four ways of naming a moment that has passed, and all four are a
        // delete answering 1 rather than an error. Zero is a moment, minus one
        // is a moment, and the hash field commands refuse the negative one.
        assert_eq!(f.run(&[b"EXPIRE", b"a", b"0"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXPIRE", b"b", b"-1"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXPIREAT", b"c", b"1"]), ":1\r\n");
        assert_eq!(f.run(&[b"PEXPIREAT", b"d", b"1"]), ":1\r\n");
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
        assert_eq!(
            f.run(&[b"EXPIRE", b"a", b"100"]),
            ":0\r\n",
            "and the key really went, so there is nothing to put a deadline on"
        );
    }

    #[test]
    fn the_four_conditions_decide_whether_the_deadline_moves() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"k", b"v"]);

        assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"XX"]), ":0\r\n");
        assert_eq!(f.run(&[b"TTL", b"k"]), ":-1\r\n", "and XX left it alone");
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"GT"]), ":0\r\n");
        assert_eq!(
            f.run(&[b"EXPIRE", b"k", b"100", b"LT"]),
            ":1\r\n",
            "no deadline reads as infinitely far away, so LT passes where GT fails"
        );

        assert_eq!(f.run(&[b"EXPIRE", b"k", b"50", b"NX"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"50", b"GT"]), ":0\r\n");
        assert_eq!(f.run(&[b"TTL", b"k"]), ":100\r\n");
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"50", b"LT"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"200", b"GT"]), ":1\r\n");
        assert_eq!(f.run(&[b"TTL", b"k"]), ":200\r\n");

        // The condition is answered before the past check, so this is a 0 and
        // the key survives. The other order would delete it.
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"0", b"NX"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"k"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"0", b"XX"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n", "and XX let it through");
    }

    #[test]
    fn the_conditions_are_a_set_and_not_a_keyword() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"k", b"v"]);

        assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"nx"]), ":1\r\n");
        assert_eq!(
            f.run(&[b"EXPIRE", b"k", b"100", b"nx", b"nx"]),
            ":0\r\n",
            "the same keyword twice means it once, and NX now has a deadline to fail on"
        );

        // XX with LT is the one pair that is not either of them on its own: LT
        // alone would accept a key with no deadline and this does not.
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"200", b"xx", b"gt"]), ":1\r\n");
        assert_eq!(f.run(&[b"TTL", b"k"]), ":200\r\n");
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"gt", b"xx"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"XX", b"LT"]), ":1\r\n");
        assert_eq!(f.run(&[b"TTL", b"k"]), ":100\r\n");
        f.run(&[b"PERSIST", b"k"]);
        assert_eq!(
            f.run(&[b"EXPIRE", b"k", b"100", b"XX", b"LT"]),
            ":0\r\n",
            "where LT on its own would have taken it"
        );
        assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"LT"]), ":1\r\n");
    }

    #[test]
    fn a_key_is_gone_once_its_moment_passes() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"k", b"v"]);
        f.run(&[b"EXPIRE", b"k", b"100"]);

        let at = int(&f.run(&[b"PEXPIRETIME", b"k"]));
        f.server.set_clock_ms(at as u64 + 1);
        assert_eq!(f.run(&[b"GET", b"k"]), "$-1\r\n");
        assert_eq!(f.run(&[b"TTL", b"k"]), ":-2\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
    }

    #[test]
    fn the_expiry_commands_refuse_what_a_real_server_refuses() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"k", b"v"]);
        for (bad, want) in [
            (
                &[b"EXPIRE".as_slice(), b"k", b"soon"][..],
                "-ERR value is not an integer or out of range\r\n",
            ),
            (
                &[b"EXPIRE", b"k", b"100", b"MAYBE"],
                "-ERR Unsupported option MAYBE\r\n",
            ),
            (
                &[b"EXPIRE", b"k", b"100", b"NX", b"XX"],
                "-ERR NX and XX, GT or LT options at the same time are not compatible\r\n",
            ),
            (
                &[b"EXPIRE", b"k", b"100", b"NX", b"GT"],
                "-ERR NX and XX, GT or LT options at the same time are not compatible\r\n",
            ),
            (
                &[b"EXPIRE", b"k", b"100", b"GT", b"LT", b"GT"],
                "-ERR GT and LT options at the same time are not compatible\r\n",
            ),
            // Seconds that overflow when multiplied into milliseconds. Every
            // message names the command it came from.
            (
                &[b"EXPIRE", b"k", b"9223372036854775807"],
                "-ERR invalid expire time in 'expire' command\r\n",
            ),
            (
                &[b"EXPIREAT", b"k", b"9223372036854775807"],
                "-ERR invalid expire time in 'expireat' command\r\n",
            ),
            (
                &[b"PEXPIRE", b"k", b"9223372036854775807"],
                "-ERR invalid expire time in 'pexpire' command\r\n",
            ),
        ] {
            assert_eq!(f.run(bad), want, "for {bad:?}");
        }
        assert_eq!(
            f.run(&[b"TTL", b"k"]),
            ":-1\r\n",
            "and none of those put a deadline on anything"
        );

        // The one of the four that has no arithmetic to overflow. Redis takes
        // it and holds the number as given, and a record here holds forty six
        // bits, so it lands in the year 4199 instead. D-17.
        assert_eq!(
            f.run(&[b"PEXPIREAT", b"k", b"9223372036854775807"]),
            ":1\r\n"
        );
        assert_eq!(f.run(&[b"PEXPIRETIME", b"k"]), ":70368744177663\r\n");
    }

    #[test]
    fn flushing_empties_this_database_or_every_one_of_them() {
        let mut f = Fixture::new();
        f.run(&[b"SELECT", b"0"]);
        f.run(&[b"MSET", b"a", b"1", b"b", b"2"]);
        f.run(&[b"SELECT", b"1"]);
        f.run(&[b"SET", b"c", b"3"]);
        assert_eq!(f.run(&[b"DBSIZE"]), ":1\r\n");
        // ASYNC and SYNC are both taken and neither changes anything, since the
        // keyspace is empty before the OK goes out either way.
        assert_eq!(f.run(&[b"FLUSHDB", b"async"]), "+OK\r\n");
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
        // Only database one was emptied.
        f.run(&[b"SELECT", b"0"]);
        assert_eq!(f.run(&[b"DBSIZE"]), ":2\r\n");
        assert_eq!(f.run(&[b"FLUSHALL", b"SYNC"]), "+OK\r\n");
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
        f.run(&[b"SELECT", b"1"]);
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
        // Anything else after the name is a syntax error, and so is a third
        // argument even when the second one is a word we take.
        assert_eq!(f.run(&[b"FLUSHALL", b"nope"]), "-ERR syntax error\r\n");
        assert_eq!(
            f.run(&[b"FLUSHDB", b"sync", b"sync"]),
            "-ERR syntax error\r\n"
        );
    }

    #[test]
    fn the_script_cache_and_the_library_set_answer_for_being_empty() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SCRIPT", b"FLUSH"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SCRIPT", b"FLUSH", b"async"]), "+OK\r\n");
        assert_eq!(f.run(&[b"FUNCTION", b"FLUSH", b"SYNC"]), "+OK\r\n");
        // Nothing is cached, so nothing is there, one answer per hash asked
        // about.
        assert_eq!(
            f.run(&[b"SCRIPT", b"EXISTS", b"aaaa", b"bbbb"]),
            "*2\r\n:0\r\n:0\r\n"
        );
        assert_eq!(f.run(&[b"FUNCTION", b"LIST"]), "*0\r\n");
        assert_eq!(
            f.run(&[b"FUNCTION", b"LIST", b"LIBRARYNAME", b"x", b"WITHCODE"]),
            "*0\r\n"
        );
        assert_eq!(
            f.run(&[b"FUNCTION", b"DELETE", b"nosuch"]),
            "-ERR Library not found\r\n"
        );

        // Redis's two messages here are its own, one per container, and one of
        // them reads like a typo.
        assert_eq!(
            f.run(&[b"SCRIPT", b"FLUSH", b"nope"]),
            "-ERR SCRIPT FLUSH only support SYNC|ASYNC option\r\n"
        );
        assert_eq!(
            f.run(&[b"FUNCTION", b"FLUSH", b"nope"]),
            "-ERR FUNCTION FLUSH only supports SYNC|ASYNC option\r\n"
        );
        // A second argument after the mode is the generic one instead, because
        // the count is checked before the word is looked at.
        assert_eq!(
            f.run(&[b"FUNCTION", b"FLUSH", b"sync", b"sync"]),
            "-ERR unknown subcommand or wrong number of arguments for 'flush'. Try FUNCTION HELP.\r\n"
        );
        assert_eq!(
            f.run(&[b"FUNCTION", b"LIST", b"bogus"]),
            "-ERR Unknown argument bogus\r\n"
        );
        assert_eq!(
            f.run(&[b"SCRIPT", b"EXISTS"]),
            "-ERR wrong number of arguments for 'script|exists' command\r\n"
        );

        // The ones that need an interpreter are not here, and say so rather
        // than answering OK to a load that loaded nothing.
        assert_eq!(
            f.run(&[b"SCRIPT", b"LOAD", b"return 1"]),
            "-ERR unknown subcommand 'LOAD'. Try SCRIPT HELP.\r\n"
        );
        assert_eq!(
            f.run(&[b"FUNCTION", b"STATS"]),
            "-ERR unknown subcommand 'STATS'. Try FUNCTION HELP.\r\n"
        );
    }

    #[test]
    fn a_counter_is_an_integer_and_not_a_string_of_digits() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"INCR", b"c"]), ":1\r\n");
        assert_eq!(f.run(&[b"INCRBY", b"c", b"41"]), ":42\r\n");
        assert_eq!(f.run(&[b"DECRBY", b"c", b"2"]), ":40\r\n");
        // Read back as a string it is still an integer, written out as digits
        // only because somebody asked for them.
        assert_eq!(f.run(&[b"GET", b"c"]), "$2\r\n40\r\n");
        assert_eq!(f.run(&[b"INCRBYFLOAT", b"c", b"0.5"]), "$4\r\n40.5\r\n");
        // A counter that is not a number is the error the store raises and this
        // layer only spells, which is the whole point of the split.
        f.run(&[b"SET", b"k", b"hello"]);
        assert_eq!(
            f.run(&[b"INCR", b"k"]),
            "-ERR value is not an integer or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"INCRBYFLOAT", b"c", b"inf"]),
            "-ERR increment would produce NaN or Infinity\r\n"
        );
    }

    /// Every one of these was read off a running 8.8. They are the answers a
    /// client library's own test suite checks, and the shapes are not
    /// guessable: `DIGEST` is hexadecimal in a bulk string, `MSETEX` is an
    /// integer, `INCREX` is a pair.
    #[test]
    fn the_newer_commands_reply_in_the_shapes_a_real_server_sends() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SET", b"k", b"hello"]), "+OK\r\n");
        // The same digest a real 8.8 answers for the same five bytes, which is
        // what makes `IFDEQ` usable against a mixed deployment.
        assert_eq!(f.run(&[b"DIGEST", b"k"]), "$16\r\n9555e8555c62dcfd\r\n");
        assert_eq!(f.run(&[b"DIGEST", b"nosuch"]), "$-1\r\n");
        assert_eq!(f.run(&[b"MSETEX", b"1", b"a", b"1"]), ":1\r\n");
        assert_eq!(f.run(&[b"MSETEX", b"1", b"a", b"2", b"NX"]), ":0\r\n");
        assert_eq!(f.run(&[b"GET", b"a"]), "$1\r\n1\r\n");
        assert_eq!(f.run(&[b"INCREX", b"n"]), "*2\r\n:1\r\n:1\r\n");
        assert_eq!(
            f.run(&[b"INCREX", b"n", b"BYINT", b"5", b"UBOUND", b"3"]),
            "*2\r\n:1\r\n:0\r\n",
            "a refused increment reports the value it left alone and applied nothing"
        );
        assert_eq!(
            f.run(&[
                b"INCREX",
                b"n",
                b"BYINT",
                b"5",
                b"UBOUND",
                b"3",
                b"SATURATE"
            ]),
            "*2\r\n:3\r\n:2\r\n"
        );
        assert_eq!(f.run(&[b"DELEX", b"a", b"IFEQ", b"2"]), ":0\r\n");
        assert_eq!(f.run(&[b"DELEX", b"a", b"IFEQ", b"1"]), ":1\r\n");
    }

    #[test]
    fn the_same_answers_come_out_in_resp3_spelling() {
        let mut f = Fixture::new();
        assert!(f.run(&[b"HELLO", b"3"]).starts_with("%7\r\n"));
        assert_eq!(f.run(&[b"GET", b"nosuch"]), "_\r\n");
        // A float counter is a double on RESP3 and the digits in a bulk string
        // on RESP2, and `INCRBYFLOAT` is a bulk string on both.
        assert_eq!(
            f.run(&[b"INCREX", b"c", b"BYFLOAT", b"1.5"]),
            "*2\r\n,1.5\r\n,1.5\r\n"
        );
        assert_eq!(f.run(&[b"INCRBYFLOAT", b"f", b"2.5"]), "$3\r\n2.5\r\n");
        // `RESET` puts the protocol back, which is the part that is easy to
        // miss and leaves a pooled connection speaking the wrong one.
        assert_eq!(f.run(&[b"RESET"]), "+RESET\r\n");
        assert_eq!(f.run(&[b"GET", b"nosuch"]), "$-1\r\n");
    }

    #[test]
    fn a_command_nobody_has_heard_of_is_an_error_and_not_a_closed_socket() {
        let mut f = Fixture::new();
        let (flow, reply) = f.flow(&[b"NOPE", b"a", b"b"]);
        assert_eq!(flow, Flow::Continue);
        assert_eq!(
            reply,
            "-ERR unknown command 'NOPE', with args beginning with: 'a' 'b' \r\n"
        );
        // A name with a line ending in it cannot write its own frame into the
        // stream, which is the reason the error writer maps them to spaces.
        let reply = f.run(&[b"NO\r\n+PONG\r\nPE"]);
        assert_eq!(reply.matches("\r\n").count(), 1);
    }

    #[test]
    fn arity_is_checked_before_the_command_is() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"GET"]),
            "-ERR wrong number of arguments for 'get' command\r\n"
        );
        assert_eq!(
            f.run(&[b"MSET", b"k"]),
            "-ERR wrong number of arguments for 'mset' command\r\n"
        );
        // The table says `PING` takes one or more and a real server then
        // refuses three, which is the sort of thing that only shows up against
        // the real thing.
        assert_eq!(
            f.run(&[b"PING", b"a", b"b"]),
            "-ERR wrong number of arguments for 'ping' command\r\n"
        );
        assert_eq!(f.run(&[b"PING"]), "+PONG\r\n");
        assert_eq!(f.run(&[b"PING", b"hi"]), "$2\r\nhi\r\n");
        // `DELEX` takes two or four and nothing between.
        assert_eq!(
            f.run(&[b"DELEX", b"k", b"IFEQ"]),
            "-ERR wrong number of arguments for 'delex' command\r\n"
        );
    }

    /// The option rules, all of them measured against 8.8 rather than read off
    /// the documentation. The surprising one is that `SET` accepts the same
    /// keyword twice and `INCREX` does not.
    #[test]
    fn the_option_combinations_are_the_ones_a_real_server_accepts() {
        let mut f = Fixture::new();
        let syntax = "-ERR syntax error\r\n";
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"NX", b"XX"]), syntax);
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"NX", b"IFEQ", b"a"]), syntax);
        assert_eq!(
            f.run(&[b"SET", b"k", b"v", b"KEEPTTL", b"EX", b"5"]),
            syntax
        );
        assert_eq!(
            f.run(&[b"SET", b"k", b"v", b"EX", b"5", b"PX", b"5"]),
            syntax
        );
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"PERSIST"]), syntax);
        // Twice is fine, and the last one wins.
        assert_eq!(
            f.run(&[b"SET", b"k", b"v", b"EX", b"5", b"EX", b"100"]),
            "+OK\r\n"
        );
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"XX", b"XX"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"GET", b"GET"]), "$1\r\nv\r\n");
        // `INCREX` refuses what `SET` allows.
        assert_eq!(
            f.run(&[b"INCREX", b"n", b"BYINT", b"1", b"BYINT", b"2"]),
            syntax
        );
        assert_eq!(
            f.run(&[b"INCREX", b"n", b"ENX"]),
            "-ERR ENX flag requires an expiration\r\n"
        );
        assert_eq!(
            f.run(&[b"INCREX", b"n", b"UBOUND", b"abc"]),
            "-ERR UBOUND is not an integer or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"INCREX", b"n", b"LBOUND", b"10", b"UBOUND", b"5"]),
            "-ERR LBOUND can't be greater than UBOUND\r\n"
        );
        assert_eq!(
            f.run(&[b"LCS", b"a", b"b", b"LEN", b"IDX"]),
            "-ERR If you want both the length and indexes, please just use IDX.\r\n"
        );
    }

    /// Where the expiration rules bite. The one worth the test is `GETEX` on a
    /// key that is not there, which answers null without ever looking at the
    /// expiration it was given.
    #[test]
    fn the_expiry_rules_are_redis_own() {
        let mut f = Fixture::new();
        let bad = "-ERR invalid expire time in 'set' command\r\n";
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"EX", b"0"]), bad);
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"EX", b"-1"]), bad);
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"EXAT", b"0"]), bad);
        assert_eq!(
            f.run(&[b"SET", b"k", b"v", b"EX", b"9999999999999999"]),
            bad
        );
        assert_eq!(
            f.run(&[b"SET", b"k", b"v", b"PX", b"99999999999999999999"]),
            "-ERR value is not an integer or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"SETEX", b"k", b"0", b"v"]),
            "-ERR invalid expire time in 'setex' command\r\n"
        );
        assert_eq!(f.run(&[b"GETEX", b"nosuch", b"EX", b"0"]), "$-1\r\n");
        assert_eq!(f.run(&[b"GETEX", b"nosuch", b"EX", b"abc"]), "$-1\r\n");
        assert_eq!(
            f.run(&[b"GETEX", b"nosuch", b"KEEPTTL"]),
            "-ERR syntax error\r\n",
            "the option list is still checked before the key is looked up"
        );
        // A deadline in the past is accepted and the key goes with it.
        assert_eq!(f.run(&[b"SET", b"k", b"v"]), "+OK\r\n");
        assert_eq!(f.run(&[b"SET", b"k", b"v", b"EXAT", b"1"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"k"]), "$-1\r\n");
    }

    #[test]
    fn mset_takes_its_pairs_from_the_read_buffer() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"MSET", b"a", b"1", b"b", b"2"]), "+OK\r\n");
        assert_eq!(
            f.run(&[b"MGET", b"a", b"b", b"nosuch"]),
            "*3\r\n$1\r\n1\r\n$1\r\n2\r\n$-1\r\n"
        );
        assert_eq!(f.run(&[b"MSETNX", b"b", b"9", b"c", b"3"]), ":0\r\n");
        assert_eq!(f.run(&[b"MSETNX", b"c", b"3", b"d", b"4"]), ":1\r\n");
        assert_eq!(
            f.run(&[b"MSETEX", b"2", b"e", b"5"]),
            "-ERR wrong number of key-value pairs\r\n"
        );
        assert_eq!(
            f.run(&[b"MSETEX", b"0", b"e", b"5"]),
            "-ERR invalid numkeys value\r\n"
        );
        assert_eq!(
            f.run(&[b"MSETEX", b"abc", b"e", b"5"]),
            "-ERR invalid numkeys value\r\n"
        );
    }

    #[test]
    fn lcs_answers_the_length_the_string_and_the_runs() {
        let mut f = Fixture::new();
        f.run(&[b"MSET", b"a", b"ohmytext", b"b", b"mynewtext"]);
        assert_eq!(f.run(&[b"LCS", b"a", b"b"]), "$6\r\nmytext\r\n");
        assert_eq!(f.run(&[b"LCS", b"a", b"b", b"LEN"]), ":6\r\n");
        assert_eq!(
            f.run(&[b"LCS", b"a", b"b", b"IDX", b"MINMATCHLEN", b"4"]),
            "*4\r\n$7\r\nmatches\r\n*1\r\n*2\r\n*2\r\n:4\r\n:7\r\n*2\r\n:5\r\n:8\r\n$3\r\nlen\r\n:6\r\n"
        );
        // Without `IDX` the two options that only mean something with it are
        // accepted and ignored, which is what a real server does.
        assert_eq!(
            f.run(&[b"LCS", b"a", b"b", b"MINMATCHLEN", b"4", b"WITHMATCHLEN"]),
            "$6\r\nmytext\r\n"
        );
    }

    #[test]
    fn select_moves_the_connection_and_the_databases_stay_apart() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"k", b"zero"]);
        assert_eq!(f.run(&[b"SELECT", b"4"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"k"]), "$-1\r\n");
        f.run(&[b"SET", b"k", b"four"]);
        assert_eq!(f.run(&[b"SELECT", b"0"]), "+OK\r\n");
        assert_eq!(f.run(&[b"GET", b"k"]), "$4\r\nzero\r\n");
        assert_eq!(
            f.run(&[b"SELECT", b"99"]),
            "-ERR DB index is out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"SELECT", b"-1"]),
            "-ERR DB index is out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"SELECT", b"abc"]),
            "-ERR value is not an integer or out of range\r\n"
        );
        // `RESET` brings it back to zero.
        f.run(&[b"SELECT", b"4"]);
        f.run(&[b"RESET"]);
        assert_eq!(f.run(&[b"GET", b"k"]), "$4\r\nzero\r\n");
    }

    #[test]
    fn hello_agrees_on_a_protocol_and_refuses_the_ones_that_do_not_exist() {
        let mut f = Fixture::new();
        let reply = f.run(&[b"HELLO"]);
        assert!(reply.starts_with("*14\r\n"), "{reply}");
        assert!(reply.contains("$5\r\nredis\r\n"), "{reply}");
        assert!(reply.contains("$5\r\n8.8.0\r\n"), "{reply}");
        assert!(
            reply.contains(":7\r\n"),
            "the connection id is in there: {reply}"
        );
        assert_eq!(
            f.run(&[b"HELLO", b"4"]),
            "-NOPROTO unsupported protocol version\r\n"
        );
        assert_eq!(
            f.run(&[b"HELLO", b"abc"]),
            "-ERR Protocol version is not an integer or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"HELLO", b"3", b"SETNAME"]),
            "-ERR Syntax error in HELLO option 'SETNAME'\r\n"
        );
        assert!(
            f.run(&[b"HELLO", b"3", b"SETNAME", b"bob"])
                .starts_with("%7\r\n")
        );
        assert_eq!(f.session.name(), b"bob");
        f.run(&[b"RESET"]);
        assert_eq!(f.session.name(), b"");
    }

    #[test]
    fn command_describes_this_server_in_the_shape_a_driver_reads() {
        let mut f = Fixture::new();
        let count = format!(":{}\r\n", COMMANDS.len());
        assert_eq!(f.run(&[b"COMMAND", b"COUNT"]), count);
        let info = f.run(&[b"COMMAND", b"INFO", b"get"]);
        assert_eq!(
            info,
            "*1\r\n*10\r\n$3\r\nget\r\n:2\r\n*2\r\n+readonly\r\n+fast\r\n:1\r\n:1\r\n:1\r\n\
             *3\r\n+@read\r\n+@string\r\n+@fast\r\n*0\r\n*0\r\n*0\r\n"
        );
        // A null in the list, and the plain one: `$-1` and not `*-1`.
        assert_eq!(f.run(&[b"COMMAND", b"INFO", b"nosuch"]), "*1\r\n$-1\r\n");
        assert_eq!(
            f.run(&[b"COMMAND", b"LIST", b"FILTERBY", b"PATTERN", b"getr*"]),
            "*1\r\n$8\r\ngetrange\r\n"
        );
        assert_eq!(
            f.run(&[b"COMMAND", b"NOPE"]),
            "-ERR unknown subcommand 'NOPE'. Try COMMAND HELP.\r\n"
        );
    }

    /// A cluster aware client asks this question and then routes on the
    /// answer, so `MSETEX`, whose keys are not where the table says, is the one
    /// that matters.
    #[test]
    fn command_getkeys_finds_the_keys_including_the_hidden_ones() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"COMMAND", b"GETKEYS", b"get", b"k"]),
            "*1\r\n$1\r\nk\r\n"
        );
        assert_eq!(
            f.run(&[b"COMMAND", b"GETKEYS", b"mset", b"a", b"1", b"b", b"2"]),
            "*2\r\n$1\r\na\r\n$1\r\nb\r\n"
        );
        assert_eq!(
            f.run(&[
                b"COMMAND", b"GETKEYS", b"msetex", b"2", b"a", b"1", b"b", b"2"
            ]),
            "*2\r\n$1\r\na\r\n$1\r\nb\r\n"
        );
        assert_eq!(
            f.run(&[b"COMMAND", b"GETKEYS", b"ping"]),
            "-ERR The command has no key arguments\r\n"
        );
        assert_eq!(
            f.run(&[b"COMMAND", b"GETKEYS", b"set"]),
            "-ERR Invalid number of arguments specified for command\r\n"
        );
    }

    #[test]
    fn config_answers_what_it_can_and_refuses_what_it_cannot() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"maxmemory"]),
            "*2\r\n$9\r\nmaxmemory\r\n$1\r\n0\r\n"
        );
        // A pattern matches more than one, and a setting two patterns both ask
        // for is still sent once.
        let both = f.run(&[b"CONFIG", b"GET", b"maxmemory*", b"maxmemory"]);
        assert!(both.starts_with("*6\r\n"), "{both}");
        assert_eq!(f.run(&[b"CONFIG", b"GET", b"nosuch"]), "*0\r\n");
        assert_eq!(f.run(&[b"CONFIG", b"SET", b"appendonly", b"no"]), "+OK\r\n");
        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"appendonly", b"yes"]),
            "-ERR CONFIG SET failed (possibly related to argument 'appendonly') - can't set immutable config\r\n"
        );
        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"nosuch", b"1"]),
            "-ERR Unknown option or number of arguments for CONFIG SET - 'nosuch'\r\n"
        );
        assert_eq!(
            f.run(&[b"CONFIG", b"GET"]),
            "-ERR wrong number of arguments for 'config|get' command\r\n"
        );
        // Too few arguments and an odd number of them are different
        // complaints, which is the sort of thing only the real server tells
        // you.
        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"appendonly"]),
            "-ERR wrong number of arguments for 'config|set' command\r\n"
        );
        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"appendonly", b"no", b"maxmemory"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(f.run(&[b"CONFIG", b"RESETSTAT"]), "+OK\r\n");
        assert_eq!(
            f.run(&[b"CONFIG", b"REWRITE"]),
            "-ERR The server is running without a config file\r\n"
        );
    }

    #[test]
    fn the_eviction_policy_reads_back_what_was_written_to_it() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"maxmemory-policy"]),
            "*2\r\n$16\r\nmaxmemory-policy\r\n$10\r\nnoeviction\r\n"
        );
        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"AllKeys-LFU"]),
            "+OK\r\n",
            "the name is matched without regard to case, like every other one"
        );
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"maxmemory-policy"]),
            "*2\r\n$16\r\nmaxmemory-policy\r\n$11\r\nallkeys-lfu\r\n"
        );
        // And INFO agrees with CONFIG, which it did not when it was a literal.
        assert!(
            f.run(&[b"INFO", b"memory"])
                .contains("maxmemory_policy:allkeys-lfu"),
            "INFO and CONFIG disagree about the policy"
        );
        // The refusal names every legal value in the order the real server's
        // enum table lists them, because a client comparing the message compares
        // the whole string.
        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"garbage"]),
            "-ERR CONFIG SET failed (possibly related to argument 'maxmemory-policy') - argument(s) must be one of the following: volatile-lru, volatile-lfu, volatile-random, volatile-ttl, volatile-lrm, allkeys-lru, allkeys-lfu, allkeys-random, allkeys-lrm, noeviction\r\n"
        );
        // A bad pair leaves the good one in the same command alone, and the
        // policy is checked by the same pass that checks the numbers.
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"maxmemory-policy"]),
            "*2\r\n$16\r\nmaxmemory-policy\r\n$11\r\nallkeys-lfu\r\n"
        );
        f.run(&[
            b"CONFIG",
            b"SET",
            b"hash-max-listpack-entries",
            b"7",
            b"maxmemory-policy",
            b"nonsense",
        ]);
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"hash-max-listpack-entries"]),
            "*2\r\n$25\r\nhash-max-listpack-entries\r\n$3\r\n512\r\n"
        );
    }

    #[test]
    fn the_three_eviction_numbers_read_back_too() {
        let mut f = Fixture::new();
        for (name, default, set) in [
            ("maxmemory-samples", "5", "12"),
            ("lfu-log-factor", "10", "3"),
            ("lfu-decay-time", "1", "60"),
        ] {
            let get = || {
                format!(
                    "*2\r\n${}\r\n{name}\r\n${}\r\n{default}\r\n",
                    name.len(),
                    default.len()
                )
            };
            assert_eq!(f.run(&[b"CONFIG", b"GET", name.as_bytes()]), get());
            assert_eq!(
                f.run(&[b"CONFIG", b"SET", name.as_bytes(), set.as_bytes()]),
                "+OK\r\n"
            );
            assert_eq!(
                f.run(&[b"CONFIG", b"GET", name.as_bytes()]),
                format!(
                    "*2\r\n${}\r\n{name}\r\n${}\r\n{set}\r\n",
                    name.len(),
                    set.len()
                )
            );
            // A number that is not a number is refused with the same sentence
            // every other number gets, which names the setting the client typed.
            assert_eq!(
                f.run(&[b"CONFIG", b"SET", name.as_bytes(), b"soon"]),
                format!(
                    "-ERR CONFIG SET failed (possibly related to argument '{name}') - argument couldn't be parsed into an integer\r\n"
                )
            );
        }
    }

    #[test]
    fn the_memory_limit_reads_back_in_bytes_whatever_the_unit_was() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"maxmemory"]),
            "*2\r\n$9\r\nmaxmemory\r\n$1\r\n0\r\n",
            "no limit is the default"
        );
        // The pairing is Redis's and it is a trap: the bare letter is a power of
        // ten and the one with the b is a power of two.
        for (typed, bytes) in [
            (&b"1024"[..], "1024"),
            (b"1k", "1000"),
            (b"1kb", "1024"),
            (b"1M", "1000000"),
            (b"1Mb", "1048576"),
            (b"1gb", "1073741824"),
            (b"100mb", "104857600"),
        ] {
            assert_eq!(f.run(&[b"CONFIG", b"SET", b"maxmemory", typed]), "+OK\r\n");
            assert_eq!(
                f.run(&[b"CONFIG", b"GET", b"maxmemory"]),
                format!("*2\r\n$9\r\nmaxmemory\r\n${}\r\n{bytes}\r\n", bytes.len()),
                "set {}",
                String::from_utf8_lossy(typed)
            );
        }
        assert!(
            f.run(&[b"INFO", b"memory"]).contains("maxmemory:104857600"),
            "the report agrees with the setting"
        );

        // A unit nobody has heard of, and a negative number, which is not a very
        // large one however it is spelled.
        for bad in [&b"1tb"[..], b"-1", b"", b"lots"] {
            assert_eq!(
                f.run(&[b"CONFIG", b"SET", b"maxmemory", bad]),
                "-ERR CONFIG SET failed (possibly related to argument 'maxmemory') - argument must be a memory value\r\n",
                "refused {}",
                String::from_utf8_lossy(bad)
            );
        }
        assert!(
            f.run(&[b"INFO", b"memory"]).contains("maxmemory:104857600"),
            "and the refusal left the old one alone"
        );
    }

    #[test]
    fn a_write_is_refused_when_there_is_no_room_and_nothing_to_evict() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"here", b"already"]);
        // A byte, which is under what an empty server holds, so nothing this
        // command could do would get it under. The default policy is
        // `noeviction`, so nothing is what it does.
        f.run(&[b"CONFIG", b"SET", b"maxmemory", b"1"]);
        assert_eq!(
            f.run(&[b"SET", b"k", b"v"]),
            "-OOM command not allowed when used memory > 'maxmemory'.\r\n"
        );
        assert_eq!(
            f.run(&[b"LPUSH", b"l", b"v"]),
            "-OOM command not allowed when used memory > 'maxmemory'.\r\n"
        );
        // Reading is allowed, and so is the one thing that would help.
        assert_eq!(f.run(&[b"GET", b"here"]), "$7\r\nalready\r\n");
        assert_eq!(f.run(&[b"DEL", b"here"]), ":1\r\n");
        assert!(f.run(&[b"INFO", b"stats"]).contains("evicted_keys:0"));

        // Taking the limit away lets the write through again.
        f.run(&[b"CONFIG", b"SET", b"maxmemory", b"0"]);
        assert_eq!(f.run(&[b"SET", b"k", b"v"]), "+OK\r\n");
    }

    #[test]
    fn an_allkeys_policy_makes_room_instead_of_refusing() {
        let mut f = Fixture::new();
        let val = vec![b'v'; 256];
        for i in 0..24000u32 {
            let k = format!("key:{i:08}");
            f.run(&[b"SET", k.as_bytes(), &val]);
        }
        let full = f.server.memory_bytes();
        assert!(
            full > 3 * 1024 * 1024,
            "the arena is several segments: {full}"
        );

        // Two megabytes under what it is holding, which is one segment's worth,
        // so getting there means giving a whole segment back and not just
        // dropping a few records.
        let limit = full - 2 * 1024 * 1024;
        f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"allkeys-lru"]);
        f.run(&[
            b"CONFIG",
            b"SET",
            b"maxmemory",
            limit.to_string().as_bytes(),
        ]);

        // Writes keep working the whole way down. The budget means one command
        // does not do it all, so this runs until the server has settled and
        // checks that nothing was refused on the way.
        for i in 0..2000u32 {
            let k = format!("new:{i:08}");
            assert_eq!(
                f.run(&[b"SET", k.as_bytes(), &val]),
                "+OK\r\n",
                "write {i} was refused"
            );
            f.server.refresh_memory();
            if f.server.memory_bytes() <= limit {
                break;
            }
        }
        assert!(
            f.server.memory_bytes() <= limit,
            "it never got under: {} against {limit}",
            f.server.memory_bytes()
        );
        let info = f.run(&[b"INFO", b"stats"]);
        assert!(!info.contains("evicted_keys:0"), "{info}");
        assert!(
            f.run(&[b"DBSIZE"]) != ":0\r\n",
            "and it did not empty the database to get there"
        );
    }

    #[test]
    fn the_running_total_and_the_walk_agree_on_a_mixed_keyspace() {
        // The limit is judged against a number kept as the collections move,
        // rather than found by asking all of them, and the two have to be the
        // same number or the limit is enforced against a fiction. This does the
        // things that move it, which is growing a collection, shrinking one,
        // changing its representation, deleting it and reusing its slot, across
        // all five types, and checks the two against each other as it goes.
        let mut f = Fixture::new();
        f.run(&[b"CONFIG", b"SET", b"maxmemory", b"1gb"]);
        let big = vec![b'v'; 200];

        for i in 0..400u32 {
            let n = i.to_string();
            let n = n.as_bytes();
            f.run(&[b"SADD", b"s", n]);
            f.run(&[b"SADD", b"s2", &big]);
            f.run(&[b"HSET", b"h", n, &big]);
            f.run(&[b"RPUSH", b"l", &big]);
            f.run(&[b"ZADD", b"z", n, n]);
            f.run(&[b"ARSET", b"a", n, &big]);
            if i % 7 == 0 {
                f.run(&[b"SREM", b"s", n]);
                f.run(&[b"HDEL", b"h", n]);
                f.run(&[b"LPOP", b"l"]);
                f.run(&[b"ZREM", b"z", n]);
                f.run(&[b"ARDEL", b"a", n]);
            }
            if i % 53 == 0 {
                // Every type deleted and made again, so a slot goes on the free
                // list and comes back holding something else.
                f.run(&[b"DEL", b"s2"]);
            }
            assert_eq!(
                f.server.settled_memory(),
                f.server.memory_bytes(),
                "after round {i}"
            );
        }

        // The run has to have built something, or the two numbers agreeing is
        // two zeroes agreeing.
        assert_eq!(f.run(&[b"DBSIZE"]), ":6\r\n");
        assert!(
            f.server.memory_bytes() > 512 * 1024,
            "{}",
            f.server.memory_bytes()
        );

        // And it survives the collections going away entirely.
        f.run(&[b"FLUSHALL"]);
        assert_eq!(f.server.settled_memory(), f.server.memory_bytes());
    }

    #[test]
    fn taking_the_limit_away_stops_the_counting_and_putting_it_back_starts_again() {
        // A server with no limit does not keep the running total, so setting a
        // limit on a database that is already full has to start it from a walk.
        // If it did not, the first reading would be zero and the server would
        // think it had all the room in the world.
        let mut f = Fixture::new();
        for i in 0..200u32 {
            let n = i.to_string();
            f.run(&[b"SADD", b"s", n.as_bytes()]);
            f.run(&[b"HSET", b"h", n.as_bytes(), b"value"]);
        }
        f.run(&[b"CONFIG", b"SET", b"maxmemory", b"1gb"]);
        assert_eq!(f.server.settled_memory(), f.server.memory_bytes());

        f.run(&[b"CONFIG", b"SET", b"maxmemory", b"0"]);
        for i in 200..400u32 {
            let n = i.to_string();
            f.run(&[b"SADD", b"s", n.as_bytes()]);
        }
        f.run(&[b"CONFIG", b"SET", b"maxmemory", b"1gb"]);
        assert_eq!(
            f.server.settled_memory(),
            f.server.memory_bytes(),
            "the writes it was not watching are in the number it started from"
        );
    }

    #[test]
    fn evicted_keys_and_expired_keys_are_different_numbers() {
        let mut f = Fixture::new();
        // Nothing has been evicted and nothing can be under the default policy,
        // so this stays at zero while the other one moves.
        f.run(&[b"SET", b"gone", b"v", b"PX", b"1"]);
        f.server.db(0).clock_mut().advance(20);
        f.run(&[b"GET", b"gone"]);
        let info = f.run(&[b"INFO", b"stats"]);
        assert!(info.contains("expired_keys:1"), "{info}");
        assert!(info.contains("evicted_keys:0"), "{info}");
    }

    #[test]
    fn the_object_subcommands_follow_the_policy() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"s", b"v"]);
        // Under the default the clock is kept and the counter is not, and under
        // an LFU policy it is the other way round. Each subcommand refuses on
        // the side where its reading of the three bytes means nothing.
        assert_eq!(f.run(&[b"OBJECT", b"IDLETIME", b"s"]), ":0\r\n");
        assert!(
            f.run(&[b"OBJECT", b"FREQ", b"s"])
                .starts_with("-ERR An LFU maxmemory policy is not selected"),
        );

        f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"allkeys-lfu"]);
        assert!(
            f.run(&[b"OBJECT", b"IDLETIME", b"s"])
                .starts_with("-ERR An LFU maxmemory policy is selected"),
        );
        // The key was written under a clock policy, so what comes back is that
        // clock read as a counter. It is a number and not an error, which is the
        // point: switching at runtime does not invalidate anything, it only makes
        // the old field mean something else until the key is used again.
        assert!(
            f.run(&[b"OBJECT", b"FREQ", b"s"]).starts_with(':'),
            "FREQ should answer under an LFU policy"
        );
    }

    #[test]
    fn object_says_which_rung_of_the_ladder_a_key_is_on() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"s", b"hello"]);
        f.run(&[b"SET", b"n", b"123"]);
        f.run(&[b"SADD", b"si", b"1", b"2", b"3"]);
        f.run(&[b"SADD", b"ss", b"a", b"b"]);
        f.run(&[b"HSET", b"h", b"f", b"v"]);
        for (key, want) in [
            (b"s".as_slice(), "embstr"),
            (b"n", "int"),
            (b"si", "intset"),
            (b"ss", "listpack"),
            (b"h", "listpack"),
        ] {
            let reply = f.run(&[b"OBJECT", b"ENCODING", key]);
            assert_eq!(reply, format!("${}\r\n{want}\r\n", want.len()));
        }

        // A field deadline widens the blob rather than promoting it, and this
        // is the only place a client can see that happen.
        f.run(&[b"HEXPIRE", b"h", b"100", b"FIELDS", b"1", b"f"]);
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING", b"h"]),
            "$10\r\nlistpackex\r\n"
        );

        assert_eq!(f.run(&[b"OBJECT", b"REFCOUNT", b"s"]), ":1\r\n");
        assert_eq!(f.run(&[b"OBJECT", b"IDLETIME", b"s"]), ":0\r\n");
        assert!(f.run(&[b"OBJECT", b"HELP"]).starts_with("*14\r\n+OBJECT "));
    }

    #[test]
    fn object_answers_nil_for_a_key_that_is_not_there() {
        let mut f = Fixture::new();
        for sub in [b"ENCODING".as_slice(), b"REFCOUNT", b"IDLETIME", b"FREQ"] {
            assert_eq!(
                f.run(&[b"OBJECT", sub, b"nokey"]),
                "$-1\r\n",
                "a nil and not an error, which is what 8.10.1 does"
            );
        }
        // And the key is looked up before FREQ has its complaint, so the
        // complaint only reaches a key that exists.
        f.run(&[b"SET", b"s", b"v"]);
        assert!(
            f.run(&[b"OBJECT", b"FREQ", b"s"])
                .starts_with("-ERR An LFU maxmemory policy is not"),
        );
        assert_eq!(
            f.run(&[b"OBJECT", b"NOPE", b"s"]),
            "-ERR unknown subcommand 'NOPE'. Try OBJECT HELP.\r\n"
        );
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING"]),
            "-ERR wrong number of arguments for 'object|encoding' command\r\n"
        );
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING", b"s", b"extra"]),
            "-ERR wrong number of arguments for 'object|encoding' command\r\n"
        );
        assert_eq!(
            f.run(&[b"OBJECT"]),
            "-ERR wrong number of arguments for 'object' command\r\n"
        );
    }

    #[test]
    fn config_moves_the_ladder_and_object_encoding_agrees() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"hash-max-listpack-entries"]),
            "*2\r\n$25\r\nhash-max-listpack-entries\r\n$3\r\n512\r\n",
            "512 and not the 128 everyone remembers, which is what 8.10.1 says"
        );
        // The old spelling is the same number under a different name, and a
        // glob that catches both sends both.
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"hash-max-ziplist-entries"]),
            "*2\r\n$24\r\nhash-max-ziplist-entries\r\n$3\r\n512\r\n"
        );
        assert!(
            f.run(&[b"CONFIG", b"GET", b"hash-max-*"])
                .starts_with("*8\r\n")
        );
        assert!(
            f.run(&[b"CONFIG", b"GET", b"set-max-*"])
                .starts_with("*6\r\n")
        );

        f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2", b"c", b"3"]);
        assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"h"]), "$8\r\nlistpack\r\n");

        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"hash-max-ziplist-entries", b"2"]),
            "+OK\r\n",
            "written under the old name and read back under the new one"
        );
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"hash-max-listpack-entries"]),
            "*2\r\n$25\r\nhash-max-listpack-entries\r\n$1\r\n2\r\n"
        );
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING", b"h"]),
            "$8\r\nlistpack\r\n",
            "the hash that already exists is left exactly where it was"
        );
        f.run(&[b"HSET", b"h2", b"a", b"1", b"b", b"2", b"c", b"3"]);
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING", b"h2"]),
            "$9\r\nhashtable\r\n",
            "and the next one built goes straight to a table"
        );

        // The set has three of these and all three move.
        f.run(&[b"CONFIG", b"SET", b"set-max-intset-entries", b"2"]);
        f.run(&[b"SADD", b"s", b"1", b"2", b"3"]);
        assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"s"]), "$8\r\nlistpack\r\n");
        f.run(&[b"CONFIG", b"SET", b"set-max-listpack-value", b"2"]);
        f.run(&[b"SADD", b"s2", b"abcdefgh"]);
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING", b"s2"]),
            "$9\r\nhashtable\r\n"
        );
    }

    #[test]
    fn config_set_takes_all_of_the_ladder_or_none_of_it() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[
                b"CONFIG",
                b"SET",
                b"hash-max-listpack-entries",
                b"7",
                b"set-max-listpack-entries",
                b"abc"
            ]),
            "-ERR CONFIG SET failed (possibly related to argument 'set-max-listpack-entries') - argument couldn't be parsed into an integer\r\n"
        );
        assert_eq!(
            f.run(&[b"CONFIG", b"GET", b"hash-max-listpack-entries"]),
            "*2\r\n$25\r\nhash-max-listpack-entries\r\n$3\r\n512\r\n",
            "the pair in front of the bad one did not go in"
        );
        // The name in the complaint is the one that was typed, so the old
        // spelling comes back as the old spelling.
        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"hash-max-ziplist-entries", b"abc"]),
            "-ERR CONFIG SET failed (possibly related to argument 'hash-max-ziplist-entries') - argument couldn't be parsed into an integer\r\n"
        );
        assert_eq!(
            f.run(&[b"CONFIG", b"SET", b"set-max-intset-entries", b"-1"]),
            "-ERR CONFIG SET failed (possibly related to argument 'set-max-intset-entries') - argument must be between 0 and 9223372036854775807 inclusive\r\n"
        );
        // A number past what an i64 holds is the parse complaint and not the
        // range one, which is upstream reading it before it checks it.
        assert_eq!(
            f.run(&[
                b"CONFIG",
                b"SET",
                b"set-max-intset-entries",
                b"99999999999999999999"
            ]),
            "-ERR CONFIG SET failed (possibly related to argument 'set-max-intset-entries') - argument couldn't be parsed into an integer\r\n"
        );
        assert_eq!(
            f.run(&[
                b"CONFIG",
                b"SET",
                b"set-max-intset-entries",
                b"9223372036854775807"
            ]),
            "+OK\r\n"
        );
    }

    #[test]
    fn a_setting_moved_on_one_database_moved_on_all_of_them() {
        let mut f = Fixture::new();
        f.run(&[b"CONFIG", b"SET", b"hash-max-listpack-entries", b"1"]);
        f.run(&[b"SELECT", b"3"]);
        f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING", b"h"]),
            "$9\r\nhashtable\r\n",
            "these are one server wide number in Redis, whatever a Keyspace carries"
        );
    }

    #[test]
    fn info_reports_the_numbers_it_can_stand_behind() {
        let mut f = Fixture::new();
        f.run(&[b"MSET", b"a", b"1", b"b", b"2"]);
        let all = f.run(&[b"INFO"]);
        assert!(all.contains("redis_version:8.8.0"), "{all}");
        assert!(
            all.contains(concat!("yo_version:", env!("CARGO_PKG_VERSION"))),
            "{all}"
        );
        assert!(all.contains("db0:keys=2,expires=0,avg_ttl=0"), "{all}");
        assert!(all.contains("role:master"), "{all}");
        // One section is one section.
        let clients = f.run(&[b"INFO", b"clients"]);
        assert!(clients.contains("connected_clients:0"), "{clients}");
        assert!(!clients.contains("redis_version"), "{clients}");
        assert_eq!(f.run(&[b"INFO", b"nosuch"]), "$0\r\n\r\n");
    }

    /// A cache that writes with a deadline and never reads back used to hold
    /// every key it had ever written, because lazy expiry needs somebody to walk
    /// past a key before it can reclaim it and nobody ever did.
    #[test]
    fn the_active_sweep_reclaims_keys_no_client_comes_back_for() {
        let mut f = Fixture::new();
        for i in 0..3_000u32 {
            f.run(&[b"SET", format!("d{i}").as_bytes(), b"v", b"PX", b"50"]);
        }
        for i in 0..1_000u32 {
            f.run(&[b"SET", format!("k{i}").as_bytes(), b"v"]);
        }
        assert_eq!(f.run(&[b"DBSIZE"]), ":4000\r\n");
        f.advance(100);
        assert_eq!(
            f.run(&[b"DBSIZE"]),
            ":4000\r\n",
            "DBSIZE counts records and nothing has read past the dead ones yet"
        );

        // What the shard loop does, one slice at a time.
        let mut spent = 0;
        for _ in 0..2_000 {
            spent += f.server.expire_step(4096);
            if f.run(&[b"DBSIZE"]) == ":1000\r\n" {
                break;
            }
        }
        assert_eq!(f.run(&[b"DBSIZE"]), ":1000\r\n", "spent {spent} looks");
        assert!(f.run(&[b"INFO", b"stats"]).contains("expired_keys:3000"));
        for i in 0..1_000u32 {
            assert_eq!(
                f.run(&[b"GET", format!("k{i}").as_bytes()]),
                "$1\r\nv\r\n",
                "it took a key that had no deadline"
            );
        }
    }

    #[test]
    fn a_sweep_of_a_server_with_no_deadlines_anywhere_costs_nothing() {
        let mut f = Fixture::new();
        for i in 0..2_000u32 {
            f.run(&[b"SET", format!("k{i}").as_bytes(), b"v"]);
        }
        assert_eq!(f.server.expire_step(4096), 0);
        // And one database having them does not make the other fifteen pay.
        f.run(&[b"SELECT", b"3"]);
        f.run(&[b"SET", b"x", b"v", b"PX", b"50"]);
        f.advance(100);
        for _ in 0..64 {
            f.server.expire_step(4096);
        }
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
        f.run(&[b"SELECT", b"0"]);
        assert_eq!(f.run(&[b"DBSIZE"]), ":2000\r\n");
        assert_eq!(f.server.expire_step(4096), 0, "and it is quiet again");
    }

    /// The gate, which is what stops a maintenance slice that runs every hundred
    /// nanoseconds from drawing a sample every hundred nanoseconds.
    #[test]
    fn the_sweep_the_loop_calls_runs_at_most_once_a_millisecond() {
        let mut f = Fixture::new();
        for i in 0..500u32 {
            f.run(&[b"SET", format!("d{i}").as_bytes(), b"v", b"PX", b"50"]);
        }
        f.advance(100);
        let at = f.server.db(0).clock().now_ms();
        f.server.set_clock_ms(at);
        // A small budget, so that one slice cannot finish the job and a second
        // one having nothing to do would mean the gate and not an empty
        // database.
        assert!(f.server.expire_slice(8) > 0, "the first one works");
        for _ in 0..1_000 {
            assert_eq!(
                f.server.expire_slice(8),
                0,
                "the millisecond has not moved and neither should this"
            );
        }
        assert!(
            f.server.db(0).expires() > 400,
            "there is plenty left to take"
        );
        f.server.set_clock_ms(at + 1);
        assert!(f.server.expire_slice(8) > 0, "and then it goes again");
    }

    /// `expires=` used to be a hardcoded zero, which meant a dashboard watching
    /// how much of a cache is volatile was reading a constant.
    #[test]
    fn info_keyspace_counts_the_keys_that_have_a_deadline() {
        let mut f = Fixture::new();
        f.run(&[b"MSET", b"a", b"1", b"b", b"2", b"c", b"3"]);
        assert!(
            f.run(&[b"INFO", b"keyspace"])
                .contains("db0:keys=3,expires=0"),
            "none of them has one yet"
        );
        f.run(&[b"EXPIRE", b"a", b"1000"]);
        f.run(&[b"EXPIRE", b"b", b"1000"]);
        let two = f.run(&[b"INFO", b"keyspace"]);
        assert!(two.contains("db0:keys=3,expires=2"), "{two}");
        f.run(&[b"PERSIST", b"a"]);
        f.run(&[b"DEL", b"b"]);
        let none = f.run(&[b"INFO", b"keyspace"]);
        assert!(none.contains("db0:keys=2,expires=0"), "{none}");

        // Each database answers for itself, the way Redis reports it.
        f.run(&[b"SELECT", b"1"]);
        f.run(&[b"SET", b"x", b"1", b"EX", b"1000"]);
        let both = f.run(&[b"INFO", b"keyspace"]);
        assert!(both.contains("db0:keys=2,expires=0"), "{both}");
        assert!(both.contains("db1:keys=1,expires=1"), "{both}");
    }

    #[cfg(unix)]
    #[test]
    fn info_cpu_reports_processor_time_that_was_really_measured() {
        let mut f = Fixture::new();
        let cpu = f.run(&[b"INFO", b"cpu"]);
        assert!(cpu.contains("# CPU"), "{cpu}");
        // Redis's unit/info-command asks for this one by name in three tests.
        assert!(cpu.contains("used_cpu_user:"), "{cpu}");
        assert!(cpu.contains("used_cpu_sys:"), "{cpu}");
        assert!(cpu.contains("used_cpu_user_children:0.000000"), "{cpu}");
        assert!(!cpu.contains("redis_version"), "{cpu}");

        // It is a measurement and not a constant, so it goes up when work
        // happens. A tight loop rather than a sleep, because sleeping is the
        // one thing that does not move this number.
        let before = used_cpu_user(&cpu);
        let mut n = 0u64;
        let mut rounds = 0;
        while used_cpu_user(&f.run(&[b"INFO", b"cpu"])) <= before {
            for i in 0..1_000_000u64 {
                n = n.wrapping_add(i.wrapping_mul(i));
            }
            rounds += 1;
            // A bound rather than a spin, so a platform where this number does
            // not move fails here instead of hanging. Even a clock with whole
            // millisecond granularity gets there in the first round or two.
            assert!(rounds < 1_000, "cpu time never moved, n is {n}");
        }
    }

    /// Pull `used_cpu_user` back out of an `INFO cpu` reply.
    #[cfg(unix)]
    fn used_cpu_user(info: &str) -> f64 {
        info.lines()
            .find_map(|l| l.strip_prefix("used_cpu_user:"))
            .expect("no used_cpu_user in the reply")
            .trim()
            .parse()
            .expect("used_cpu_user is not a number")
    }

    /// The safety net under the rule that a body checks its arguments before
    /// it writes anything. `MGET` writes its array header first and then reads
    /// each key, so if a later argument could fail the header would already be
    /// out. Nothing in the string group does that today and this is what would
    /// catch the first one that did.
    #[test]
    fn a_command_that_fails_leaves_nothing_half_written() {
        let mut f = Fixture::new();
        let reply = f.run(&[b"SETRANGE", b"k", b"-1", b"x"]);
        assert_eq!(reply, "-ERR offset is out of range\r\n");
        assert!(!reply.contains(':'), "no integer went out in front of it");
    }

    #[test]
    fn quit_answers_first_and_closes_after() {
        let mut f = Fixture::new();
        let (flow, reply) = f.flow(&[b"QUIT"]);
        assert_eq!(reply, "+OK\r\n");
        assert_eq!(flow, Flow::Close);
    }

    #[test]
    fn the_command_counter_counts_every_command_including_the_bad_ones() {
        let mut f = Fixture::new();
        f.run(&[b"PING"]);
        f.run(&[b"NOPE"]);
        f.run(&[b"GET"]);
        assert_eq!(f.server.stats.commands, 3);
    }

    #[test]
    fn a_set_goes_from_bytes_to_bytes() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SADD", b"s", b"a", b"b", b"c"]), ":3\r\n");
        assert_eq!(f.run(&[b"SADD", b"s", b"b", b"d"]), ":1\r\n");
        assert_eq!(f.run(&[b"SCARD", b"s"]), ":4\r\n");
        assert_eq!(f.run(&[b"SISMEMBER", b"s", b"a"]), ":1\r\n");
        assert_eq!(f.run(&[b"SISMEMBER", b"s", b"z"]), ":0\r\n");
        assert_eq!(f.run(&[b"TYPE", b"s"]), "+set\r\n");
        assert_eq!(
            f.run(&[b"SMISMEMBER", b"s", b"a", b"z", b"d"]),
            "*3\r\n:1\r\n:0\r\n:1\r\n"
        );
        assert_eq!(f.run(&[b"SREM", b"s", b"a", b"z"]), ":1\r\n");
        assert_eq!(f.run(&[b"SCARD", b"s"]), ":3\r\n");
    }

    #[test]
    fn a_set_command_at_a_key_that_is_not_there_answers_empty() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"SCARD", b"nope"]), ":0\r\n");
        assert_eq!(f.run(&[b"SISMEMBER", b"nope", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"SREM", b"nope", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"SMEMBERS", b"nope"]), "*0\r\n");
        assert_eq!(
            f.run(&[b"SMISMEMBER", b"nope", b"a", b"b"]),
            "*2\r\n:0\r\n:0\r\n"
        );
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n", "and made nothing");
    }

    #[test]
    fn smembers_answers_a_set_on_resp3_and_an_array_on_resp2() {
        // Not cosmetic. A RESP3 client that gets a `~` hands the caller a set
        // and one that gets a `*` hands it a list, without either of them being
        // told which command was sent.
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"one"]);
        assert_eq!(f.run(&[b"SMEMBERS", b"s"]), "*1\r\n$3\r\none\r\n");

        f.run(&[b"HELLO", b"3"]);
        assert_eq!(f.run(&[b"SMEMBERS", b"s"]), "~1\r\n$3\r\none\r\n");
    }

    #[test]
    fn an_integer_member_comes_back_as_the_digits_it_never_stored() {
        // An intset holds the number, so these digits exist for the first time
        // in the reply buffer.
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"42"]);
        assert_eq!(f.run(&[b"SMEMBERS", b"s"]), "*1\r\n$2\r\n42\r\n");
        assert_eq!(f.run(&[b"SISMEMBER", b"s", b"42"]), ":1\r\n");
        assert_eq!(
            f.run(&[b"SISMEMBER", b"s", b"042"]),
            ":0\r\n",
            "the member is the bytes and not the number they parse to"
        );
    }

    #[test]
    fn the_wrong_command_at_the_wrong_type_says_so_both_ways() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v"]);
        f.run(&[b"SADD", b"set", b"a"]);

        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
        assert_eq!(f.run(&[b"SADD", b"str", b"a"]), wrong);
        assert_eq!(f.run(&[b"SCARD", b"str"]), wrong);
        assert_eq!(f.run(&[b"SMEMBERS", b"str"]), wrong);
        assert_eq!(f.run(&[b"SMISMEMBER", b"str", b"a"]), wrong);
        assert_eq!(f.run(&[b"GET", b"set"]), wrong);
        assert_eq!(f.run(&[b"APPEND", b"set", b"x"]), wrong);
        assert_eq!(f.run(&[b"INCR", b"set"]), wrong);
        assert_eq!(f.run(&[b"STRLEN", b"set"]), wrong);

        // MGET is the one that does not, because Redis gives nil for the odd
        // key out rather than failing the good keys next to it.
        assert_eq!(
            f.run(&[b"MGET", b"str", b"set", b"nope"]),
            "*3\r\n$1\r\nv\r\n$-1\r\n$-1\r\n"
        );
        // And plain SET overwrites any type, which takes the body with it.
        assert_eq!(f.run(&[b"SET", b"set", b"now a string"]), "+OK\r\n");
        assert_eq!(f.run(&[b"TYPE", b"set"]), "+string\r\n");
    }

    #[test]
    fn a_wrongtype_leaves_nothing_half_written() {
        // SMISMEMBER writes an array header and then one reply per member, so
        // it is the first command in the server that could get a header out in
        // front of an error if it checked its key in the wrong order.
        let mut f = Fixture::new();
        f.run(&[b"SET", b"k", b"v"]);
        let reply = f.run(&[b"SMISMEMBER", b"k", b"a", b"b"]);
        assert!(reply.starts_with("-WRONGTYPE"), "got {reply}");
        assert!(!reply.contains('*'), "an array header went out in front");
    }

    #[test]
    fn emptying_a_set_takes_the_key_with_it() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"a", b"b"]);
        assert_eq!(f.run(&[b"DBSIZE"]), ":1\r\n");
        assert_eq!(f.run(&[b"SREM", b"s", b"a", b"b"]), ":2\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"s"]), ":0\r\n");
        assert_eq!(f.run(&[b"TYPE", b"s"]), "+none\r\n");
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
    }

    /// Pull the cursor and the members out of one `SSCAN` reply.
    ///
    /// Crude on purpose. A test that walked a set through a real client would
    /// be testing the client, and what these tests are about is the shape of
    /// the bytes and the fact that a walk sees every member once.
    fn split_scan(reply: &str) -> (String, Vec<String>) {
        let mut lines = reply.split("\r\n");
        assert_eq!(lines.next(), Some("*2"), "got {reply}");
        lines.next().expect("the cursor header");
        let cursor = lines.next().expect("the cursor").to_owned();
        let header = lines.next().expect("the member header");
        let n: usize = header[1..].parse().expect("a member count");
        let mut members = Vec::with_capacity(n);
        for _ in 0..n {
            lines.next().expect("a member header");
            members.push(lines.next().expect("a member").to_owned());
        }
        (cursor, members)
    }

    #[test]
    fn popping_takes_a_member_off_the_set_and_hands_it_back() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"a", b"b", b"c", b"d"]);

        let one = f.run(&[b"SPOP", b"s"]);
        assert!(
            ["$1\r\na\r\n", "$1\r\nb\r\n", "$1\r\nc\r\n", "$1\r\nd\r\n"].contains(&one.as_str()),
            "got {one}"
        );
        assert_eq!(f.run(&[b"SCARD", b"s"]), ":3\r\n");

        // A count takes that many, and the last one takes the key with it.
        let (_, rest) = ("", f.run(&[b"SPOP", b"s", b"3"]));
        assert!(rest.starts_with("*3\r\n"), "got {rest}");
        assert_eq!(f.run(&[b"EXISTS", b"s"]), ":0\r\n");
        // And a pop at a key that is not there is a nil, not an empty bulk.
        assert_eq!(f.run(&[b"SPOP", b"s"]), "$-1\r\n");
        assert_eq!(f.run(&[b"SPOP", b"s", b"2"]), "*0\r\n");
    }

    #[test]
    fn the_two_draws_disagree_about_the_reply_type_and_they_are_right_to() {
        // The one place in the server where the reply type carries something
        // the command name does not. SPOP's members are distinct so a RESP3
        // client can build a set out of them. SRANDMEMBER with a negative count
        // can hand back the same member three times, and a set would lose two.
        let mut f = Fixture::new();
        f.run(&[b"HELLO", b"3"]);
        f.run(&[b"SADD", b"s", b"a", b"b", b"c"]);

        assert!(f.run(&[b"SPOP", b"s", b"2"]).starts_with("~2\r\n"));
        // And a positive count is an array too, since Redis makes it one.
        assert!(f.run(&[b"SRANDMEMBER", b"s", b"1"]).starts_with("*1\r\n"));

        // A negative count against a set of one is where the difference bites:
        // the same member three times, which is a three element reply and would
        // have been a one element reply if it had gone out as a set.
        f.run(&[b"SADD", b"one", b"z"]);
        assert_eq!(
            f.run(&[b"SRANDMEMBER", b"one", b"-3"]),
            "*3\r\n$1\r\nz\r\n$1\r\nz\r\n$1\r\nz\r\n"
        );
    }

    #[test]
    fn drawing_a_member_removes_nothing_and_says_nil_at_a_missing_key() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"only"]);
        assert_eq!(f.run(&[b"SRANDMEMBER", b"s"]), "$4\r\nonly\r\n");
        assert_eq!(f.run(&[b"SRANDMEMBER", b"s"]), "$4\r\nonly\r\n");
        assert_eq!(f.run(&[b"SCARD", b"s"]), ":1\r\n");

        assert_eq!(f.run(&[b"SRANDMEMBER", b"nope"]), "$-1\r\n");
        // The count form answers an empty array rather than a nil, which is the
        // pair of answers Redis gives and is not the pair it looks like.
        assert_eq!(f.run(&[b"SRANDMEMBER", b"nope", b"3"]), "*0\r\n");
        assert_eq!(f.run(&[b"SRANDMEMBER", b"nope", b"-3"]), "*0\r\n");
        // Asking for more than is there answers all of it once and not padding.
        assert_eq!(f.run(&[b"SRANDMEMBER", b"s", b"9"]), "*1\r\n$4\r\nonly\r\n");
    }

    #[test]
    fn a_pop_count_that_is_not_a_positive_number_says_so() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"a"]);
        let bad = "-ERR value is out of range, must be positive\r\n";
        assert_eq!(f.run(&[b"SPOP", b"s", b"-1"]), bad);
        assert_eq!(f.run(&[b"SPOP", b"s", b"abc"]), bad);
        assert_eq!(f.run(&[b"SCARD", b"s"]), ":1\r\n", "and took nothing");
        // Zero is allowed and is a real answer rather than an error.
        assert_eq!(f.run(&[b"SPOP", b"s", b"0"]), "*0\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"s"]), ":1\r\n");
    }

    #[test]
    fn a_scan_walks_a_set_of_any_size_exactly_once() {
        let mut f = Fixture::new();
        let members: Vec<Vec<u8>> = (0..300).map(|i| format!("m{i}").into_bytes()).collect();
        let args: Vec<&[u8]> = [&b"SADD"[..], &b"s"[..]]
            .into_iter()
            .chain(members.iter().map(Vec::as_slice))
            .collect();
        f.run(&args);

        let mut seen = Vec::new();
        let mut cursor = "0".to_owned();
        loop {
            let reply = f.run(&[b"SSCAN", b"s", cursor.as_bytes()]);
            let (next, got) = split_scan(&reply);
            seen.extend(got);
            cursor = next;
            if cursor == "0" {
                break;
            }
        }
        seen.sort();
        seen.dedup();
        assert_eq!(seen.len(), 300, "a walk saw a member twice or missed one");

        // A set small enough to be a listpack answers in one call whatever
        // cursor it was handed, which is what Redis does for that encoding.
        f.run(&[b"SADD", b"small", b"a", b"b", b"c"]);
        let (cursor, got) = split_scan(&f.run(&[b"SSCAN", b"small", b"0", b"COUNT", b"1"]));
        assert_eq!(cursor, "0");
        assert_eq!(got.len(), 3);
        // And a key that is not there is a finished scan of nothing.
        assert_eq!(f.run(&[b"SSCAN", b"nope", b"0"]), "*2\r\n$1\r\n0\r\n*0\r\n");
    }

    #[test]
    fn a_scan_takes_match_and_count_and_refuses_anything_else() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"aa", b"ab", b"ba", b"12", b"13"]);

        let (_, got) = split_scan(&f.run(&[b"SSCAN", b"s", b"0", b"MATCH", b"a*"]));
        let mut got = got;
        got.sort();
        assert_eq!(got, ["aa", "ab"]);

        // An integer member has no digits stored anywhere, so MATCH is the one
        // place a scan pays to write some.
        let (_, got) = split_scan(&f.run(&[b"SSCAN", b"s", b"0", b"MATCH", b"1?"]));
        let mut got = got;
        got.sort();
        assert_eq!(got, ["12", "13"]);

        assert_eq!(f.run(&[b"SSCAN", b"s", b"abc"]), "-ERR invalid cursor\r\n");
        assert_eq!(f.run(&[b"SSCAN", b"s", b"-1"]), "-ERR invalid cursor\r\n");
        assert_eq!(
            f.run(&[b"SSCAN", b"s", b"0", b"NOPE", b"1"]),
            "-ERR syntax error\r\n"
        );
        // A count under one is a syntax error and not a range error, which is
        // the odder of Redis's two answers and the reason it is copied exactly.
        assert_eq!(
            f.run(&[b"SSCAN", b"s", b"0", b"COUNT", b"0"]),
            "-ERR syntax error\r\n"
        );
    }

    #[test]
    fn moving_a_member_takes_it_off_one_set_and_puts_it_on_another() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"src", b"a", b"b"]);
        f.run(&[b"SADD", b"dst", b"c"]);

        assert_eq!(f.run(&[b"SMOVE", b"src", b"dst", b"a"]), ":1\r\n");
        assert_eq!(f.run(&[b"SISMEMBER", b"src", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"SISMEMBER", b"dst", b"a"]), ":1\r\n");
        // A member that is not in the source is a zero and moves nothing.
        assert_eq!(f.run(&[b"SMOVE", b"src", b"dst", b"zz"]), ":0\r\n");
        assert_eq!(f.run(&[b"SCARD", b"dst"]), ":2\r\n");

        // A destination that does not exist gets made, and a source that runs
        // out goes away.
        assert_eq!(f.run(&[b"SMOVE", b"src", b"fresh", b"b"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"src"]), ":0\r\n");
        assert_eq!(f.run(&[b"SMEMBERS", b"fresh"]), "*1\r\n$1\r\nb\r\n");
    }

    #[test]
    fn moving_checks_the_types_in_the_order_redis_checks_them() {
        // Not the order it looks like it should be. A source that is not there
        // answers zero without ever looking at the destination, so this is a
        // zero and not a WRONGTYPE even though the destination is a string.
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v"]);
        f.run(&[b"SADD", b"set", b"a"]);

        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
        assert_eq!(f.run(&[b"SMOVE", b"nope", b"str", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"SMOVE", b"str", b"set", b"a"]), wrong);
        assert_eq!(f.run(&[b"SMOVE", b"set", b"str", b"a"]), wrong);
        assert_eq!(f.run(&[b"SPOP", b"str"]), wrong);
        assert_eq!(f.run(&[b"SRANDMEMBER", b"str"]), wrong);
        assert_eq!(f.run(&[b"SSCAN", b"str", b"0"]), wrong);
        assert_eq!(
            f.run(&[b"SISMEMBER", b"set", b"a"]),
            ":1\r\n",
            "and none of that moved anything"
        );
    }

    #[test]
    fn a_scan_leaves_nothing_half_written_when_its_arguments_are_wrong() {
        // SSCAN writes an outer array header before it walks, so it is the
        // command most likely to get bytes out in front of an error.
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"s", b"a"]);
        for bad in [
            &[b"SSCAN".as_slice(), b"s", b"abc"][..],
            &[b"SSCAN".as_slice(), b"s", b"0", b"COUNT", b"nope"][..],
            &[b"SSCAN".as_slice(), b"s", b"0", b"MATCH"][..],
        ] {
            let reply = f.run(bad);
            assert!(reply.starts_with("-ERR"), "got {reply}");
            assert!(!reply.contains('*'), "an array header went out in front");
        }
    }

    #[test]
    fn a_hash_writes_reads_and_deletes_its_fields() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]), ":2\r\n");
        assert_eq!(f.run(&[b"HSET", b"h", b"a", b"9"]), ":0\r\n", "a was there");
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n9\r\n");
        assert_eq!(f.run(&[b"HGET", b"h", b"nope"]), "$-1\r\n");
        assert_eq!(f.run(&[b"HGET", b"nokey", b"a"]), "$-1\r\n");
        assert_eq!(f.run(&[b"HLEN", b"h"]), ":2\r\n");
        assert_eq!(f.run(&[b"HEXISTS", b"h", b"a"]), ":1\r\n");
        assert_eq!(f.run(&[b"HEXISTS", b"h", b"nope"]), ":0\r\n");
        assert_eq!(f.run(&[b"HSTRLEN", b"h", b"a"]), ":1\r\n");
        assert_eq!(f.run(&[b"HSTRLEN", b"h", b"nope"]), ":0\r\n");

        // The value the client sent is `9`, so HGET h b must not find the `2`
        // that is a value. A search with a step of one would have.
        assert_eq!(f.run(&[b"HGET", b"h", b"2"]), "$-1\r\n");

        assert_eq!(f.run(&[b"HDEL", b"h", b"a", b"nope"]), ":1\r\n");
        assert_eq!(f.run(&[b"HDEL", b"h", b"b"]), ":1\r\n");
        assert_eq!(
            f.run(&[b"EXISTS", b"h"]),
            ":0\r\n",
            "and losing the last field lost the key"
        );
    }

    #[test]
    fn hgetall_answers_a_map_on_resp3_and_the_same_pairs_flat_on_resp2() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1"]);
        assert_eq!(f.run(&[b"HGETALL", b"h"]), "*2\r\n$1\r\na\r\n$1\r\n1\r\n");
        assert_eq!(f.run(&[b"HGETALL", b"nokey"]), "*0\r\n");
        assert_eq!(f.run(&[b"HKEYS", b"h"]), "*1\r\n$1\r\na\r\n");
        assert_eq!(f.run(&[b"HVALS", b"h"]), "*1\r\n$1\r\n1\r\n");
        assert_eq!(f.run(&[b"HKEYS", b"nokey"]), "*0\r\n");

        f.run(&[b"HELLO", b"3"]);
        assert_eq!(f.run(&[b"HGETALL", b"h"]), "%1\r\n$1\r\na\r\n$1\r\n1\r\n");
        assert_eq!(
            f.run(&[b"HGETALL", b"nokey"]),
            "%0\r\n",
            "a missing key is the empty hash and never a nil"
        );
        assert_eq!(
            f.run(&[b"HKEYS", b"h"]),
            "*1\r\n$1\r\na\r\n",
            "and the two that answer one side stay arrays"
        );
    }

    #[test]
    fn hmget_answers_once_per_field_and_hmset_answers_ok() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"HMSET", b"h", b"a", b"1", b"c", b"3"]), "+OK\r\n");
        assert_eq!(
            f.run(&[b"HMGET", b"h", b"a", b"b", b"c"]),
            "*3\r\n$1\r\n1\r\n$-1\r\n$1\r\n3\r\n",
            "the reply is positional, so b is a nil and not a gap"
        );
        assert_eq!(
            f.run(&[b"HMGET", b"nokey", b"a", b"b"]),
            "*2\r\n$-1\r\n$-1\r\n",
            "and a missing key is all nils rather than an empty array"
        );

        assert_eq!(f.run(&[b"HSETNX", b"h", b"a", b"9"]), ":0\r\n");
        assert_eq!(f.run(&[b"HSETNX", b"h", b"z", b"9"]), ":1\r\n");
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n");
    }

    #[test]
    fn a_hash_counts_up_and_says_so_when_it_cannot() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"HINCRBY", b"h", b"n", b"5"]), ":5\r\n");
        assert_eq!(f.run(&[b"HINCRBY", b"h", b"n", b"-7"]), ":-2\r\n");
        assert_eq!(f.run(&[b"HGET", b"h", b"n"]), "$2\r\n-2\r\n");
        assert_eq!(
            f.run(&[b"HINCRBYFLOAT", b"h", b"f", b"10.5"]),
            "$4\r\n10.5\r\n",
            "a bulk string and not a double, on both protocols"
        );

        f.run(&[b"HSET", b"h", b"s", b"words"]);
        let bad = f.run(&[b"HINCRBY", b"h", b"s", b"1"]);
        assert!(
            bad.starts_with("-ERR hash value is not an integer"),
            "{bad}"
        );
        let bad = f.run(&[b"HINCRBY", b"h", b"n", b"nope"]);
        assert!(
            bad.starts_with("-ERR value is not an integer"),
            "a bad argument is not yet a hash value, {bad}"
        );
        assert_eq!(
            f.run(&[b"HGET", b"h", b"s"]),
            "$5\r\nwords\r\n",
            "and neither of them wrote anything"
        );
    }

    #[test]
    fn a_hash_scan_walks_every_pair_once_and_novalues_drops_half_of_it() {
        let mut f = Fixture::new();
        for i in 0..500 {
            let field = format!("field-{i}");
            let value = format!("value-{i}");
            f.run(&[b"HSET", b"h", field.as_bytes(), value.as_bytes()]);
        }

        let mut seen: Vec<String> = Vec::new();
        let mut cursor = "0".to_owned();
        loop {
            let reply = f.run(&[b"HSCAN", b"h", cursor.as_bytes(), b"COUNT", b"32"]);
            let (next, items) = scan_reply(&reply);
            assert_eq!(items.len() % 2, 0, "a pair went out half written");
            for pair in items.chunks(2) {
                assert_eq!(
                    pair[0].strip_prefix("field-"),
                    pair[1].strip_prefix("value-"),
                    "a field came back with someone else's value"
                );
                seen.push(pair[0].clone());
            }
            cursor = next;
            if cursor == "0" {
                break;
            }
        }
        seen.sort();
        seen.dedup();
        assert_eq!(seen.len(), 500, "every field once and only once");

        let (_, items) = scan_reply(&f.run(&[b"HSCAN", b"h", b"0", b"NOVALUES", b"COUNT", b"32"]));
        assert!(
            items.iter().all(|s| s.starts_with("field-")),
            "NOVALUES still sent the values"
        );

        let (_, one) = scan_reply(&f.run(&[
            b"HSCAN",
            b"h",
            b"0",
            b"MATCH",
            b"field-499",
            b"COUNT",
            b"1000",
        ]));
        assert_eq!(one, ["field-499", "value-499"], "MATCH is on the field");
    }

    #[test]
    fn hrandfield_draws_what_it_was_asked_for_and_nests_values_on_resp3() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1"]);
        assert_eq!(f.run(&[b"HRANDFIELD", b"h"]), "$1\r\na\r\n");
        assert_eq!(f.run(&[b"HRANDFIELD", b"nokey"]), "$-1\r\n");
        assert_eq!(f.run(&[b"HRANDFIELD", b"nokey", b"3"]), "*0\r\n");
        assert_eq!(
            f.run(&[b"HRANDFIELD", b"h", b"3"]),
            "*1\r\n$1\r\na\r\n",
            "a positive count is capped at the size of the hash"
        );
        assert_eq!(
            f.run(&[b"HRANDFIELD", b"h", b"-3"]),
            "*3\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n",
            "and a negative one repeats itself"
        );
        assert_eq!(
            f.run(&[b"HRANDFIELD", b"h", b"1", b"WITHVALUES"]),
            "*2\r\n$1\r\na\r\n$1\r\n1\r\n",
            "flat on RESP2"
        );

        f.run(&[b"HELLO", b"3"]);
        assert_eq!(
            f.run(&[b"HRANDFIELD", b"h", b"1", b"WITHVALUES"]),
            "*1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n",
            "and nested on RESP3, but still an array and never a map"
        );
    }

    #[test]
    fn every_hash_command_says_wrongtype_and_writes_nothing() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v"]);
        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";

        for cmd in [
            &[b"HSET".as_slice(), b"str", b"f", b"v"][..],
            &[b"HMSET".as_slice(), b"str", b"f", b"v"][..],
            &[b"HSETNX".as_slice(), b"str", b"f", b"v"][..],
            &[b"HGET".as_slice(), b"str", b"f"][..],
            &[b"HMGET".as_slice(), b"str", b"f"][..],
            &[b"HDEL".as_slice(), b"str", b"f"][..],
            &[b"HLEN".as_slice(), b"str"][..],
            &[b"HEXISTS".as_slice(), b"str", b"f"][..],
            &[b"HSTRLEN".as_slice(), b"str", b"f"][..],
            &[b"HGETALL".as_slice(), b"str"][..],
            &[b"HKEYS".as_slice(), b"str"][..],
            &[b"HVALS".as_slice(), b"str"][..],
            &[b"HINCRBY".as_slice(), b"str", b"f", b"1"][..],
            &[b"HINCRBYFLOAT".as_slice(), b"str", b"f", b"1"][..],
            &[b"HRANDFIELD".as_slice(), b"str"][..],
            &[b"HRANDFIELD".as_slice(), b"str", b"2"][..],
            &[b"HSCAN".as_slice(), b"str", b"0"][..],
        ] {
            let reply = f.run(cmd);
            assert_eq!(reply, wrong, "{:?}", cmd[0]);
        }
        assert_eq!(
            f.run(&[b"GET", b"str"]),
            "$1\r\nv\r\n",
            "and none of them touched the value"
        );
    }

    #[test]
    fn a_hash_scan_leaves_nothing_half_written_when_its_arguments_are_wrong() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"f", b"v"]);
        for bad in [
            &[b"HSCAN".as_slice(), b"h", b"abc"][..],
            &[b"HSCAN".as_slice(), b"h", b"0", b"COUNT", b"nope"][..],
            &[b"HSCAN".as_slice(), b"h", b"0", b"COUNT", b"0"][..],
            &[b"HSCAN".as_slice(), b"h", b"0", b"MATCH"][..],
        ] {
            let reply = f.run(bad);
            assert!(reply.starts_with("-ERR"), "got {reply}");
            assert!(!reply.contains('*'), "an array header went out in front");
        }
    }

    #[test]
    fn a_field_deadline_goes_on_and_comes_back_in_all_four_units() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"100", b"FIELDS", b"1", b"a"]),
            "*1\r\n:1\r\n"
        );
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"3", b"a", b"b", b"nope"]),
            "*3\r\n:100\r\n:-1\r\n:-2\r\n",
            "one answer per field, and the two sentinels are TTL's own"
        );

        // The same deadline in the other three units, all of them derived from
        // the one number the store kept.
        let ms = int_reply(&f.run(&[b"HPTTL", b"h", b"FIELDS", b"1", b"a"]));
        assert!((99_000..=100_000).contains(&ms), "got {ms}");
        let at = int_reply(&f.run(&[b"HEXPIRETIME", b"h", b"FIELDS", b"1", b"a"]));
        let at_ms = int_reply(&f.run(&[b"HPEXPIRETIME", b"h", b"FIELDS", b"1", b"a"]));
        assert_eq!(at, at_ms.div_euclid(1000) + i64::from(at_ms % 1000 != 0));
        assert!(at_ms > 1_700_000_000_000, "an absolute moment, got {at_ms}");

        assert_eq!(
            f.run(&[b"HPERSIST", b"h", b"FIELDS", b"3", b"a", b"b", b"nope"]),
            "*3\r\n:1\r\n:-1\r\n:-2\r\n",
            "one for the deadline taken off, and it does not say what it was"
        );
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:-1\r\n"
        );
        assert_eq!(
            f.run(&[b"HGET", b"h", b"a"]),
            "$1\r\n1\r\n",
            "and the field is still there with the value it had"
        );
    }

    #[test]
    fn a_deadline_that_has_already_gone_deletes_the_field_now() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
        assert_eq!(
            f.run(&[b"HEXPIREAT", b"h", b"1", b"FIELDS", b"1", b"a"]),
            "*1\r\n:2\r\n",
            "two, and not one, because nothing was stored"
        );
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$-1\r\n");
        assert_eq!(f.run(&[b"HLEN", b"h"]), ":1\r\n");

        assert_eq!(
            f.run(&[b"HPEXPIREAT", b"h", b"1", b"FIELDS", b"1", b"b"]),
            "*1\r\n:2\r\n"
        );
        assert_eq!(
            f.run(&[b"EXISTS", b"h"]),
            ":0\r\n",
            "and the last field going took the key with it"
        );

        // Zero is a delete and not an error, where minus one is an error. That
        // is Redis's split and it is easy to get backwards.
        f.run(&[b"HSET", b"h", b"a", b"1"]);
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"0", b"FIELDS", b"1", b"a"]),
            "*1\r\n:2\r\n"
        );
    }

    #[test]
    fn a_field_is_gone_once_its_moment_passes() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
        assert_eq!(
            f.run(&[b"HPEXPIRE", b"h", b"20", b"FIELDS", b"1", b"a"]),
            "*1\r\n:1\r\n"
        );
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n", "not yet");

        // Time moves once per turn of the event loop and nowhere else, so a
        // test moves it by hand rather than by sleeping. There is nothing to
        // sleep for: the deadline is a number and so is the clock.
        f.server.db(0).clock_mut().advance(60);
        assert_eq!(f.run(&[b"HLEN", b"h"]), ":1\r\n");
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$-1\r\n");
        assert_eq!(
            f.run(&[b"HGETALL", b"h"]),
            "*2\r\n$1\r\nb\r\n$1\r\n2\r\n",
            "and the walks do not hand back a field that has expired"
        );
    }

    #[test]
    fn a_missing_key_answers_the_no_field_sentinel_for_every_field() {
        let mut f = Fixture::new();
        for cmd in [
            &[
                b"HEXPIRE".as_slice(),
                b"nokey",
                b"100",
                b"FIELDS",
                b"2",
                b"a",
                b"b",
            ][..],
            &[b"HTTL".as_slice(), b"nokey", b"FIELDS", b"2", b"a", b"b"][..],
            &[b"HPTTL".as_slice(), b"nokey", b"FIELDS", b"2", b"a", b"b"][..],
            &[
                b"HEXPIRETIME".as_slice(),
                b"nokey",
                b"FIELDS",
                b"2",
                b"a",
                b"b",
            ][..],
            &[
                b"HPERSIST".as_slice(),
                b"nokey",
                b"FIELDS",
                b"2",
                b"a",
                b"b",
            ][..],
        ] {
            assert_eq!(f.run(cmd), "*2\r\n:-2\r\n:-2\r\n", "{:?}", cmd[0]);
        }
    }

    #[test]
    fn writing_a_field_clears_the_deadline_that_was_on_it() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1"]);
        f.run(&[b"HEXPIRE", b"h", b"100", b"FIELDS", b"1", b"a"]);
        f.run(&[b"HSET", b"h", b"a", b"2"]);
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:-1\r\n",
            "Redis has done this since 7.4, and it is why HGETEX exists"
        );
    }

    #[test]
    fn the_four_conditions_reach_the_store_the_way_they_were_written() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1"]);
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"100", b"XX", b"FIELDS", b"1", b"a"]),
            "*1\r\n:0\r\n",
            "XX on a field with no deadline changes nothing"
        );
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"100", b"NX", b"FIELDS", b"1", b"a"]),
            "*1\r\n:1\r\n"
        );
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"200", b"NX", b"FIELDS", b"1", b"a"]),
            "*1\r\n:0\r\n",
            "and NX will not move one that is already there"
        );
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"50", b"GT", b"FIELDS", b"1", b"a"]),
            "*1\r\n:0\r\n"
        );
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"500", b"GT", b"FIELDS", b"1", b"a"]),
            "*1\r\n:1\r\n"
        );
        assert_eq!(
            f.run(&[b"HEXPIRE", b"h", b"50", b"LT", b"FIELDS", b"1", b"a"]),
            "*1\r\n:1\r\n"
        );
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:50\r\n"
        );
    }

    #[test]
    fn the_field_ttl_family_leaves_nothing_half_written_on_a_bad_argument() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1"]);
        for (bad, want) in [
            (
                &[b"HEXPIRE".as_slice(), b"h", b"-1", b"FIELDS", b"1", b"a"][..],
                "-ERR invalid expire time, must be >= 0",
            ),
            (
                &[
                    b"HEXPIRE".as_slice(),
                    b"h",
                    b"9999999999999999",
                    b"FIELDS",
                    b"1",
                    b"a",
                ][..],
                "-ERR invalid expire time in 'hexpire' command",
            ),
            (
                &[b"HEXPIRE".as_slice(), b"h", b"100", b"FIELD", b"1", b"a"][..],
                "-ERR wrong number of arguments for 'hexpire' command",
            ),
            (
                &[b"HEXPIRE".as_slice(), b"h", b"100", b"FIELDS", b"0", b"a"][..],
                "-ERR Parameter `numFields` should be greater than 0",
            ),
            (
                &[b"HEXPIRE".as_slice(), b"h", b"100", b"FIELDS", b"2", b"a"][..],
                "-ERR wrong number of arguments",
            ),
            (
                &[b"HTTL".as_slice(), b"h", b"FIELDS", b"3", b"a", b"b"][..],
                "-ERR wrong number of arguments",
            ),
        ] {
            let reply = f.run(bad);
            assert!(reply.starts_with(want), "wanted {want}, got {reply}");
            assert!(!reply.contains('*'), "an array header went out in front");
        }
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:-1\r\n",
            "and not one of them put a deadline on anything"
        );
    }

    #[test]
    fn every_field_ttl_command_says_wrongtype_and_writes_nothing() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v"]);
        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";

        for cmd in [
            &[b"HEXPIRE".as_slice(), b"str", b"100", b"FIELDS", b"1", b"f"][..],
            &[
                b"HPEXPIRE".as_slice(),
                b"str",
                b"100",
                b"FIELDS",
                b"1",
                b"f",
            ][..],
            &[
                b"HEXPIREAT".as_slice(),
                b"str",
                b"9999999999",
                b"FIELDS",
                b"1",
                b"f",
            ][..],
            &[
                b"HPEXPIREAT".as_slice(),
                b"str",
                b"9999999999999",
                b"FIELDS",
                b"1",
                b"f",
            ][..],
            &[b"HTTL".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
            &[b"HPTTL".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
            &[b"HEXPIRETIME".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
            &[b"HPEXPIRETIME".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
            &[b"HPERSIST".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
        ] {
            assert_eq!(f.run(cmd), wrong, "{:?}", cmd[0]);
        }
        assert_eq!(
            f.run(&[b"GET", b"str"]),
            "$1\r\nv\r\n",
            "and none of them touched the value"
        );
    }

    #[test]
    fn hgetdel_hands_the_value_out_and_then_takes_the_field() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
        assert_eq!(
            f.run(&[b"HGETDEL", b"h", b"FIELDS", b"2", b"a", b"nope"]),
            "*2\r\n$1\r\n1\r\n$-1\r\n",
            "positional, so the field that was not there is a nil in its place"
        );
        assert_eq!(f.run(&[b"HLEN", b"h"]), ":1\r\n");
        assert_eq!(
            f.run(&[b"HGETDEL", b"nokey", b"FIELDS", b"1", b"a"]),
            "*1\r\n$-1\r\n"
        );
        assert_eq!(
            f.run(&[b"HGETDEL", b"h", b"FIELDS", b"1", b"b"]),
            "*1\r\n$1\r\n2\r\n"
        );
        assert_eq!(
            f.run(&[b"EXISTS", b"h"]),
            ":0\r\n",
            "and the last field took the key"
        );
    }

    #[test]
    fn hgetex_reads_and_moves_the_deadline_in_one_command() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1"]);
        assert_eq!(
            f.run(&[b"HGETEX", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n$1\r\n1\r\n"
        );
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:-1\r\n",
            "no option means leave it alone, which is the one place this is not GETEX"
        );

        f.run(&[b"HGETEX", b"h", b"EX", b"100", b"FIELDS", b"1", b"a"]);
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:100\r\n"
        );
        f.run(&[b"HGETEX", b"h", b"FIELDS", b"1", b"a"]);
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:100\r\n",
            "and a plain read really does leave it alone"
        );
        assert_eq!(
            f.run(&[b"HGETEX", b"h", b"PERSIST", b"FIELDS", b"1", b"a"]),
            "*1\r\n$1\r\n1\r\n"
        );
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:-1\r\n"
        );

        assert_eq!(
            f.run(&[b"HGETEX", b"h", b"EXAT", b"1", b"FIELDS", b"1", b"a"]),
            "*1\r\n$1\r\n1\r\n",
            "the value goes out before the deadline that has already gone is applied"
        );
        assert_eq!(f.run(&[b"EXISTS", b"h"]), ":0\r\n");
        assert_eq!(
            f.run(&[b"HGETEX", b"nokey", b"EX", b"100", b"FIELDS", b"1", b"a"]),
            "*1\r\n$-1\r\n"
        );
    }

    #[test]
    fn hsetex_writes_all_of_it_or_none_of_it() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"HSETEX", b"h", b"FIELDS", b"1", b"a", b"1"]),
            ":1\r\n"
        );
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n");
        assert_eq!(
            f.run(&[
                b"HSETEX", b"h", b"FNX", b"FIELDS", b"2", b"a", b"9", b"new", b"9"
            ]),
            ":0\r\n",
            "FNX wants every field named to be missing"
        );
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n");
        assert_eq!(
            f.run(&[b"HEXISTS", b"h", b"new"]),
            ":0\r\n",
            "and none of the list was written"
        );
        assert_eq!(
            f.run(&[
                b"HSETEX", b"h", b"FXX", b"FIELDS", b"2", b"a", b"9", b"nope", b"9"
            ]),
            ":0\r\n",
            "and FXX wants every one of them to be there"
        );
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n");
        assert_eq!(
            f.run(&[b"HSETEX", b"h", b"FXX", b"FIELDS", b"1", b"a", b"9"]),
            ":1\r\n"
        );
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n9\r\n");

        assert_eq!(
            f.run(&[b"HSETEX", b"gone", b"FXX", b"FIELDS", b"1", b"a", b"1"]),
            ":0\r\n"
        );
        assert_eq!(
            f.run(&[b"EXISTS", b"gone"]),
            ":0\r\n",
            "a key with no fields cannot meet FXX and is not created trying"
        );
    }

    #[test]
    fn hsetex_clears_the_deadline_unless_it_is_told_to_keep_it() {
        let mut f = Fixture::new();
        f.run(&[b"HSETEX", b"h", b"EX", b"100", b"FIELDS", b"1", b"a", b"1"]);
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:100\r\n"
        );

        f.run(&[b"HSETEX", b"h", b"KEEPTTL", b"FIELDS", b"1", b"a", b"2"]);
        assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n2\r\n");
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:100\r\n",
            "KEEPTTL put back what the write cleared"
        );

        f.run(&[b"HSETEX", b"h", b"FIELDS", b"1", b"a", b"3"]);
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:-1\r\n",
            "and without it a write clears the deadline the way HSET does"
        );

        // Any order, because Redis reads these in a loop and not in a fixed
        // sequence.
        assert_eq!(
            f.run(&[
                b"HSETEX", b"h", b"PX", b"100000", b"FXX", b"FIELDS", b"1", b"a", b"4"
            ]),
            ":1\r\n"
        );
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:100\r\n"
        );

        assert_eq!(
            f.run(&[b"HSETEX", b"h", b"EXAT", b"1", b"FIELDS", b"1", b"a", b"5"]),
            ":1\r\n",
            "written, and not the separate code the HEXPIRE family has for this"
        );
        assert_eq!(
            f.run(&[b"EXISTS", b"h"]),
            ":0\r\n",
            "and storing it and then removing it emptied the hash"
        );
    }

    #[test]
    fn the_last_three_hash_commands_word_their_mistakes_their_own_way() {
        let mut f = Fixture::new();
        f.run(&[b"HSET", b"h", b"a", b"1"]);
        for (bad, want) in [
            // HGETDEL has three sentences of its own for these three mistakes.
            (
                &[b"HGETDEL".as_slice(), b"h", b"FIELDS", b"0", b"a"][..],
                "-ERR Number of fields must be a positive integer",
            ),
            (
                &[b"HGETDEL".as_slice(), b"h", b"FIELDS", b"2", b"a"][..],
                "-ERR The `numfields` parameter must match the number of arguments",
            ),
            (
                &[b"HGETDEL".as_slice(), b"h", b"FIELD", b"1", b"a"][..],
                "-ERR Mandatory argument FIELDS is missing or not at the right position",
            ),
            // And HGETEX and HSETEX have three different ones between them.
            (
                &[b"HGETEX".as_slice(), b"h", b"FIELDS", b"0", b"a"][..],
                "-ERR invalid number of fields",
            ),
            (
                &[b"HGETEX".as_slice(), b"h", b"FIELDS", b"2", b"a"][..],
                "-ERR wrong number of arguments",
            ),
            (
                &[b"HGETEX".as_slice(), b"h", b"FIELD", b"1", b"a"][..],
                "-ERR unknown argument: FIELD",
            ),
            (
                &[
                    b"HGETEX".as_slice(),
                    b"h",
                    b"KEEPTTL",
                    b"FIELDS",
                    b"1",
                    b"a",
                ][..],
                "-ERR unknown argument: KEEPTTL",
            ),
            (
                &[
                    b"HGETEX".as_slice(),
                    b"h",
                    b"EX",
                    b"100",
                    b"PERSIST",
                    b"FIELDS",
                    b"1",
                    b"a",
                ][..],
                "-ERR Only one of EX, PX, EXAT, PXAT or PERSIST arguments can be specified",
            ),
            (
                &[
                    b"HSETEX".as_slice(),
                    b"h",
                    b"EX",
                    b"1",
                    b"KEEPTTL",
                    b"FIELDS",
                    b"1",
                    b"a",
                    b"1",
                ][..],
                "-ERR Only one of EX, PX, EXAT, PXAT or KEEPTTL arguments can be specified",
            ),
            (
                &[
                    b"HSETEX".as_slice(),
                    b"h",
                    b"FNX",
                    b"FXX",
                    b"FIELDS",
                    b"1",
                    b"a",
                    b"1",
                ][..],
                "-ERR Only one of FXX or FNX arguments can be specified",
            ),
            (
                &[
                    b"HSETEX".as_slice(),
                    b"h",
                    b"FIELDS",
                    b"2",
                    b"a",
                    b"1",
                    b"b",
                ][..],
                "-ERR wrong number of arguments",
            ),
            (
                &[
                    b"HGETEX".as_slice(),
                    b"h",
                    b"EX",
                    b"-1",
                    b"FIELDS",
                    b"1",
                    b"a",
                ][..],
                "-ERR invalid expire time, must be >= 0",
            ),
            (
                &[
                    b"HGETEX".as_slice(),
                    b"h",
                    b"PXAT",
                    b"99999999999999",
                    b"FIELDS",
                    b"1",
                    b"a",
                ][..],
                "-ERR invalid expire time in 'hgetex' command",
            ),
            (
                &[
                    b"HSETEX".as_slice(),
                    b"h",
                    b"EX",
                    b"abc",
                    b"FIELDS",
                    b"1",
                    b"a",
                    b"1",
                ][..],
                "-ERR value is not an integer or out of range",
            ),
        ] {
            let reply = f.run(bad);
            assert!(reply.starts_with(want), "wanted {want}, got {reply}");
            assert!(!reply.contains('*'), "an array header went out in front");
        }
        assert_eq!(
            f.run(&[b"HGET", b"h", b"a"]),
            "$1\r\n1\r\n",
            "and not one of them wrote anything"
        );
        assert_eq!(
            f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
            "*1\r\n:-1\r\n"
        );
    }

    #[test]
    fn the_last_three_hash_commands_say_wrongtype_and_write_nothing() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v"]);
        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
        for cmd in [
            &[b"HGETDEL".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
            &[b"HGETEX".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
            &[
                b"HGETEX".as_slice(),
                b"str",
                b"EX",
                b"100",
                b"FIELDS",
                b"1",
                b"f",
            ][..],
            &[b"HSETEX".as_slice(), b"str", b"FIELDS", b"1", b"f", b"v"][..],
        ] {
            assert_eq!(f.run(cmd), wrong, "{:?}", cmd[0]);
        }
        assert_eq!(f.run(&[b"GET", b"str"]), "$1\r\nv\r\n");
    }

    /// The one integer of a single element array reply.
    /// The number out of a plain integer reply.
    ///
    /// [`int_reply`] is the same thing wrapped in a one element array, which is
    /// the shape every hash field command answers in.
    fn int(reply: &str) -> i64 {
        let body = reply
            .strip_prefix(':')
            .and_then(|s| s.strip_suffix("\r\n"))
            .unwrap_or_else(|| panic!("wanted an integer, got {reply}"));
        body.parse().expect("an integer")
    }

    fn int_reply(reply: &str) -> i64 {
        let body = reply
            .strip_prefix("*1\r\n:")
            .and_then(|s| s.strip_suffix("\r\n"))
            .unwrap_or_else(|| panic!("wanted one integer, got {reply}"));
        body.parse().expect("an integer")
    }

    /// The cursor and the flat items of a scan reply.
    fn scan_reply(reply: &str) -> (String, Vec<String>) {
        let mut lines = reply.split("\r\n");
        assert_eq!(lines.next(), Some("*2"), "got {reply}");
        lines.next().expect("the cursor header");
        let cursor = lines.next().expect("a cursor").to_owned();
        let header = lines.next().expect("an item count");
        let n: usize = header[1..].parse().expect("a count");
        let mut items = Vec::with_capacity(n);
        for _ in 0..n {
            lines.next().expect("an item header");
            items.push(lines.next().expect("an item").to_owned());
        }
        (cursor, items)
    }

    /// The members of a set reply, sorted, since none of these promise an
    /// order and a test that asserted one would be asserting an accident.
    fn sorted(reply: &str) -> Vec<String> {
        let mut lines = reply.split("\r\n");
        let header = lines.next().expect("a header");
        assert!(
            header.starts_with('*') || header.starts_with('~'),
            "got {reply}"
        );
        let n: usize = header[1..].parse().expect("a member count");
        let mut got = Vec::with_capacity(n);
        for _ in 0..n {
            lines.next().expect("a member header");
            got.push(lines.next().expect("a member").to_owned());
        }
        got.sort();
        got
    }

    #[test]
    fn the_algebra_answers_what_the_sets_share_and_do_not() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"a", b"1", b"2", b"3"]);
        f.run(&[b"SADD", b"b", b"2", b"3", b"4"]);
        f.run(&[b"SADD", b"c", b"3", b"4", b"5"]);

        assert_eq!(sorted(&f.run(&[b"SINTER", b"a", b"b", b"c"])), ["3"]);
        assert_eq!(
            sorted(&f.run(&[b"SUNION", b"a", b"b", b"c"])),
            ["1", "2", "3", "4", "5"]
        );
        assert_eq!(sorted(&f.run(&[b"SDIFF", b"a", b"b"])), ["1"]);
        assert_eq!(sorted(&f.run(&[b"SINTER", b"a"])), ["1", "2", "3"]);

        // A key that is not there is an empty set, which empties an
        // intersection and does nothing at all to a union.
        assert_eq!(f.run(&[b"SINTER", b"a", b"nope"]), "*0\r\n");
        assert_eq!(sorted(&f.run(&[b"SUNION", b"a", b"nope"])), ["1", "2", "3"]);
        assert_eq!(f.run(&[b"SDIFF", b"nope", b"a"]), "*0\r\n");
        assert_eq!(f.run(&[b"DBSIZE"]), ":3\r\n", "and none of it made a key");
    }

    #[test]
    fn the_algebra_answers_a_set_on_resp3_and_an_array_on_resp2() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"a", b"x"]);
        assert_eq!(f.run(&[b"SINTER", b"a"]), "*1\r\n$1\r\nx\r\n");
        assert_eq!(f.run(&[b"SUNION", b"a"]), "*1\r\n$1\r\nx\r\n");
        assert_eq!(f.run(&[b"SDIFF", b"a"]), "*1\r\n$1\r\nx\r\n");

        f.run(&[b"HELLO", b"3"]);
        assert_eq!(f.run(&[b"SINTER", b"a"]), "~1\r\n$1\r\nx\r\n");
        assert_eq!(f.run(&[b"SUNION", b"a"]), "~1\r\n$1\r\nx\r\n");
        assert_eq!(f.run(&[b"SDIFF", b"a"]), "~1\r\n$1\r\nx\r\n");
        assert_eq!(f.run(&[b"SINTER", b"nope"]), "~0\r\n");
    }

    #[test]
    fn a_store_form_writes_a_key_and_answers_how_big_it_is() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"a", b"1", b"2", b"3"]);
        f.run(&[b"SADD", b"b", b"2", b"3", b"4"]);

        assert_eq!(f.run(&[b"SINTERSTORE", b"d", b"a", b"b"]), ":2\r\n");
        assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"d"])), ["2", "3"]);
        assert_eq!(f.run(&[b"SUNIONSTORE", b"d", b"a", b"b"]), ":4\r\n");
        assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"d"])), ["1", "2", "3", "4"]);
        assert_eq!(f.run(&[b"SDIFFSTORE", b"d", b"a", b"b"]), ":1\r\n");
        assert_eq!(f.run(&[b"SMEMBERS", b"d"]), "*1\r\n$1\r\n1\r\n");

        // An empty answer deletes the destination rather than leaving an empty
        // set behind, and the destination may be one of the sources.
        assert_eq!(f.run(&[b"SDIFFSTORE", b"d", b"a", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
        assert_eq!(f.run(&[b"SINTERSTORE", b"a", b"a", b"b"]), ":2\r\n");
        assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"a"])), ["2", "3"]);

        // And a destination holding something else is overwritten, the same way
        // SET overwrites, rather than refused.
        f.run(&[b"SET", b"str", b"v"]);
        assert_eq!(f.run(&[b"SUNIONSTORE", b"str", b"b"]), ":3\r\n");
        assert_eq!(f.run(&[b"TYPE", b"str"]), "+set\r\n");
    }

    #[test]
    fn sintercard_counts_without_building_and_stops_at_a_limit() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"a", b"1", b"2", b"3", b"4"]);
        f.run(&[b"SADD", b"b", b"2", b"3", b"4", b"5"]);

        assert_eq!(f.run(&[b"SINTERCARD", b"2", b"a", b"b"]), ":3\r\n");
        assert_eq!(
            f.run(&[b"SINTERCARD", b"2", b"a", b"b", b"LIMIT", b"2"]),
            ":2\r\n"
        );
        assert_eq!(
            f.run(&[b"SINTERCARD", b"2", b"a", b"b", b"LIMIT", b"0"]),
            ":3\r\n",
            "a limit of zero is no limit"
        );
        assert_eq!(f.run(&[b"SINTERCARD", b"1", b"a"]), ":4\r\n");
        assert_eq!(f.run(&[b"SINTERCARD", b"2", b"a", b"nope"]), ":0\r\n");

        // The counted keys are what make its three error messages its own.
        assert_eq!(
            f.run(&[b"SINTERCARD", b"0", b"a"]),
            "-ERR numkeys should be greater than 0\r\n"
        );
        assert_eq!(
            f.run(&[b"SINTERCARD", b"abc", b"a"]),
            "-ERR numkeys should be greater than 0\r\n"
        );
        assert_eq!(
            f.run(&[b"SINTERCARD", b"3", b"a", b"b"]),
            "-ERR Number of keys can't be greater than number of args\r\n"
        );
        assert_eq!(
            f.run(&[b"SINTERCARD", b"2", b"a", b"b", b"LIMIT", b"-1"]),
            "-ERR LIMIT can't be negative\r\n"
        );
        assert_eq!(
            f.run(&[b"SINTERCARD", b"2", b"a", b"b", b"NOPE", b"1"]),
            "-ERR syntax error\r\n"
        );
        // A key really can be called LIMIT, which is why the count exists.
        f.run(&[b"SADD", b"LIMIT", b"2"]);
        assert_eq!(f.run(&[b"SINTERCARD", b"2", b"a", b"LIMIT"]), ":1\r\n");
    }

    #[test]
    fn the_algebra_answers_wrongtype_before_it_writes_anything() {
        let mut f = Fixture::new();
        f.run(&[b"SADD", b"a", b"1"]);
        f.run(&[b"SADD", b"d", b"old"]);
        f.run(&[b"SET", b"str", b"v"]);

        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
        for bad in [
            &[b"SINTER".as_slice(), b"a", b"str"][..],
            &[b"SUNION".as_slice(), b"str"][..],
            &[b"SDIFF".as_slice(), b"a", b"str"][..],
            &[b"SINTERCARD".as_slice(), b"2", b"a", b"str"][..],
            &[b"SINTERSTORE".as_slice(), b"d", b"a", b"str"][..],
            &[b"SUNIONSTORE".as_slice(), b"d", b"str"][..],
            &[b"SDIFFSTORE".as_slice(), b"d", b"a", b"str"][..],
        ] {
            let reply = f.run(bad);
            assert_eq!(reply, wrong, "for {:?}", bad[0]);
        }
        assert_eq!(
            f.run(&[b"SMEMBERS", b"d"]),
            "*1\r\n$3\r\nold\r\n",
            "and the destination was left alone every time"
        );
    }

    /// The leak a set can spring that nothing on the wire would ever show: the
    /// key goes, the body does not, and `DBSIZE` looks right the whole time.
    #[test]
    fn churning_sets_does_not_grow_the_server() {
        let mut f = Fixture::new();
        let members: Vec<Vec<u8>> = (0..200).map(|i| format!("m{i}").into_bytes()).collect();
        let args: Vec<&[u8]> = std::iter::once(&b"SADD"[..])
            .chain(std::iter::once(&b"s"[..]))
            .chain(members.iter().map(Vec::as_slice))
            .collect();

        f.run(&args);
        f.run(&[b"DEL", b"s"]);
        f.server.compact_step();
        let after_first = f.server.memory_bytes();

        for _ in 0..200 {
            f.run(&args);
            f.run(&[b"DEL", b"s"]);
            f.server.compact_step();
        }
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
        assert!(
            f.server.memory_bytes() <= after_first * 2,
            "held {} after two hundred passes against {after_first} after one",
            f.server.memory_bytes()
        );
    }

    /// A RESP2 array of bulk strings, which is what most of the list replies
    /// are and what writing them out by hand in every assertion looks like.
    fn bulks(parts: &[&str]) -> String {
        let mut s = format!("*{}\r\n", parts.len());
        for p in parts {
            s.push_str(&format!("${}\r\n{p}\r\n", p.len()));
        }
        s
    }

    #[test]
    fn a_list_is_pushed_from_both_ends_and_the_left_one_reverses() {
        let mut f = Fixture::new();
        // Each element in turn goes at the head, so the last one sent is at the
        // front when it is over. That reads like a bug in the client and it is
        // what every Redis has always done.
        assert_eq!(f.run(&[b"LPUSH", b"k", b"a", b"b", b"c"]), ":3\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
            bulks(&["c", "b", "a"])
        );
        assert_eq!(f.run(&[b"RPUSH", b"k", b"d"]), ":4\r\n");
        assert_eq!(f.run(&[b"LLEN", b"k"]), ":4\r\n");
        assert_eq!(f.run(&[b"LPOP", b"k"]), "$1\r\nc\r\n");
        assert_eq!(f.run(&[b"RPOP", b"k"]), "$1\r\nd\r\n");
        assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["b", "a"]));
        assert_eq!(f.run(&[b"TYPE", b"k"]), "+list\r\n");
    }

    #[test]
    fn the_x_pushes_refuse_to_bring_a_list_back_to_life() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"LPUSHX", b"k", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"RPUSHX", b"k", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
        f.run(&[b"RPUSH", b"k", b"a"]);
        assert_eq!(f.run(&[b"LPUSHX", b"k", b"z"]), ":2\r\n");
        assert_eq!(f.run(&[b"RPUSHX", b"k", b"y"]), ":3\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
            bulks(&["z", "a", "y"])
        );
    }

    /// The four ways a pop can come back with nothing, which are three
    /// different replies and a RESP2 client can tell all of them apart.
    #[test]
    fn an_empty_pop_is_a_different_nothing_with_a_count_and_without() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"LPOP", b"nope"]), "$-1\r\n");
        assert_eq!(f.run(&[b"LPOP", b"nope", b"2"]), "*-1\r\n");
        assert_eq!(f.run(&[b"RPOP", b"nope"]), "$-1\r\n");
        assert_eq!(f.run(&[b"RPOP", b"nope", b"2"]), "*-1\r\n");
        f.run(&[b"RPUSH", b"k", b"a", b"b", b"c"]);
        // A count of zero against a list that is there is an empty array and
        // not a null array, which is the fourth answer.
        assert_eq!(f.run(&[b"LPOP", b"k", b"0"]), "*0\r\n");
        assert_eq!(f.run(&[b"LPOP", b"k", b"1"]), bulks(&["a"]));
        // More than there is takes what there is and the key goes with it.
        assert_eq!(f.run(&[b"RPOP", b"k", b"9"]), bulks(&["c", "b"]));
        assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
    }

    #[test]
    fn a_pop_count_has_its_own_sentence_and_a_third_argument_is_an_arity_error() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a"]);
        let range = "-ERR value is out of range, must be positive\r\n";
        assert_eq!(f.run(&[b"LPOP", b"k", b"-1"]), range);
        assert_eq!(f.run(&[b"LPOP", b"k", b"abc"]), range);
        assert_eq!(f.run(&[b"RPOP", b"k", b"-1"]), range);
        // Redis calls this an arity error and not a syntax error, which is a
        // distinction it does not always make.
        assert_eq!(
            f.run(&[b"LPOP", b"k", b"1", b"2"]),
            "-ERR wrong number of arguments for 'lpop' command\r\n"
        );
        assert_eq!(f.run(&[b"LLEN", b"k"]), ":1\r\n");
    }

    #[test]
    fn a_range_takes_negative_ends_and_clamps_the_ones_that_run_off() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a", b"b", b"c"]);
        assert_eq!(
            f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
            bulks(&["a", "b", "c"])
        );
        assert_eq!(f.run(&[b"LRANGE", b"k", b"-2", b"-1"]), bulks(&["b", "c"]));
        assert_eq!(f.run(&[b"LRANGE", b"k", b"1", b"1"]), bulks(&["b"]));
        assert_eq!(f.run(&[b"LRANGE", b"k", b"5", b"10"]), "*0\r\n");
        assert_eq!(f.run(&[b"LRANGE", b"k", b"2", b"1"]), "*0\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"k", b"-100", b"100"]),
            bulks(&["a", "b", "c"])
        );
        // A key that is not there is an empty range and not a nil, which is the
        // one place a list disagrees with a set.
        assert_eq!(f.run(&[b"LRANGE", b"nope", b"0", b"-1"]), "*0\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"k", b"a", b"b"]),
            "-ERR value is not an integer or out of range\r\n"
        );
    }

    #[test]
    fn an_index_reads_and_writes_from_whichever_end_is_nearer() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a", b"b", b"c"]);
        assert_eq!(f.run(&[b"LINDEX", b"k", b"0"]), "$1\r\na\r\n");
        assert_eq!(f.run(&[b"LINDEX", b"k", b"-1"]), "$1\r\nc\r\n");
        assert_eq!(f.run(&[b"LINDEX", b"k", b"99"]), "$-1\r\n");
        assert_eq!(f.run(&[b"LINDEX", b"nope", b"0"]), "$-1\r\n");
        assert_eq!(f.run(&[b"LSET", b"k", b"-1", b"z"]), "+OK\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
            bulks(&["a", "b", "z"])
        );
        // Both ways of missing are errors here rather than a nil, because a
        // list is never empty and there is nothing else the reply could be.
        assert_eq!(
            f.run(&[b"LSET", b"k", b"99", b"z"]),
            "-ERR index out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"LSET", b"nope", b"0", b"z"]),
            "-ERR no such key\r\n"
        );
    }

    #[test]
    fn linsert_says_three_things_with_one_signed_number() {
        let mut f = Fixture::new();
        // Zero for a key that is not there, which is not the same as minus one
        // for a pivot that is not in a list that is.
        assert_eq!(
            f.run(&[b"LINSERT", b"nope", b"BEFORE", b"a", b"x"]),
            ":0\r\n"
        );
        f.run(&[b"RPUSH", b"k", b"a", b"b"]);
        assert_eq!(f.run(&[b"LINSERT", b"k", b"before", b"a", b"X"]), ":3\r\n");
        assert_eq!(f.run(&[b"LINSERT", b"k", b"AFTER", b"b", b"Y"]), ":4\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
            bulks(&["X", "a", "b", "Y"])
        );
        assert_eq!(
            f.run(&[b"LINSERT", b"k", b"BEFORE", b"zz", b"x"]),
            ":-1\r\n"
        );
        assert_eq!(
            f.run(&[b"LINSERT", b"k", b"SIDEWAYS", b"a", b"x"]),
            "-ERR syntax error\r\n"
        );
    }

    #[test]
    fn lrem_counts_in_three_directions_and_takes_the_key_when_it_empties() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a", b"b", b"a", b"c", b"a"]);
        assert_eq!(f.run(&[b"LREM", b"k", b"2", b"a"]), ":2\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
            bulks(&["b", "c", "a"])
        );
        assert_eq!(f.run(&[b"LREM", b"k", b"-1", b"a"]), ":1\r\n");
        assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["b", "c"]));
        assert_eq!(f.run(&[b"LREM", b"k", b"0", b"b"]), ":1\r\n");
        assert_eq!(f.run(&[b"LREM", b"k", b"0", b"c"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
        assert_eq!(f.run(&[b"LREM", b"nope", b"0", b"a"]), ":0\r\n");
    }

    #[test]
    fn ltrim_keeps_a_window_and_an_empty_one_deletes_the_key() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a", b"b", b"c", b"d"]);
        assert_eq!(f.run(&[b"LTRIM", b"k", b"1", b"-2"]), "+OK\r\n");
        assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["b", "c"]));
        // `LTRIM k 1 0` is the documented way to empty a list, so it has to
        // leave `EXISTS` answering zero rather than leaving an empty one.
        assert_eq!(f.run(&[b"LTRIM", b"k", b"1", b"0"]), "+OK\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
        assert_eq!(f.run(&[b"LTRIM", b"nope", b"0", b"-1"]), "+OK\r\n");
    }

    #[test]
    fn lpos_walks_from_either_end_and_stops_where_it_is_told() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"p", b"a", b"b", b"c", b"a", b"b", b"c", b"a"]);
        assert_eq!(f.run(&[b"LPOS", b"p", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"LPOS", b"p", b"a", b"RANK", b"-1"]), ":6\r\n");
        assert_eq!(f.run(&[b"LPOS", b"p", b"a", b"RANK", b"2"]), ":3\r\n");
        assert_eq!(
            f.run(&[b"LPOS", b"p", b"a", b"COUNT", b"2"]),
            "*2\r\n:0\r\n:3\r\n"
        );
        assert_eq!(
            f.run(&[b"LPOS", b"p", b"a", b"RANK", b"-1", b"COUNT", b"0"]),
            "*3\r\n:6\r\n:3\r\n:0\r\n"
        );
        // MAXLEN counts elements looked at and not matches found, so three
        // stops after `a b c` and finds the one match in it.
        assert_eq!(
            f.run(&[b"LPOS", b"p", b"a", b"COUNT", b"0", b"MAXLEN", b"3"]),
            "*1\r\n:0\r\n"
        );
        // Nothing found is three different replies depending on how it was
        // asked and whether the key is there at all.
        assert_eq!(f.run(&[b"LPOS", b"p", b"zz"]), "$-1\r\n");
        assert_eq!(f.run(&[b"LPOS", b"p", b"zz", b"COUNT", b"0"]), "*0\r\n");
        assert_eq!(f.run(&[b"LPOS", b"nope", b"a"]), "$-1\r\n");
        assert_eq!(f.run(&[b"LPOS", b"nope", b"a", b"COUNT", b"2"]), "*0\r\n");
    }

    #[test]
    fn lpos_words_its_three_mistakes_the_way_redis_does() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"p", b"a"]);
        // The whole sentence and not a prefix, because the older wording of it
        // is still all over the internet and clients match on the text.
        assert_eq!(
            f.run(&[b"LPOS", b"p", b"a", b"RANK", b"0"]),
            "-ERR RANK can't be zero: use 1 to start from the first match, 2 from the second ... or use negative to start from the end of the list\r\n"
        );
        assert_eq!(
            f.run(&[b"LPOS", b"p", b"a", b"COUNT", b"-1"]),
            "-ERR COUNT can't be negative\r\n"
        );
        assert_eq!(
            f.run(&[b"LPOS", b"p", b"a", b"MAXLEN", b"-1"]),
            "-ERR MAXLEN can't be negative\r\n"
        );
        assert_eq!(
            f.run(&[b"LPOS", b"p", b"a", b"RANK"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"LPOS", b"p", b"a", b"FOO", b"1"]),
            "-ERR syntax error\r\n"
        );
    }

    #[test]
    fn a_move_takes_from_one_end_and_gives_to_another_even_on_one_key() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a", b"b", b"c"]);
        assert_eq!(f.run(&[b"RPOPLPUSH", b"k", b"d"]), "$1\r\nc\r\n");
        assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["a", "b"]));
        assert_eq!(f.run(&[b"LRANGE", b"d", b"0", b"-1"]), bulks(&["c"]));
        assert_eq!(
            f.run(&[b"LMOVE", b"k", b"d", b"LEFT", b"RIGHT"]),
            "$1\r\na\r\n"
        );
        assert_eq!(f.run(&[b"LRANGE", b"d", b"0", b"-1"]), bulks(&["c", "a"]));
        // The same key twice is the documented way to rotate a list and falls
        // out of taking the element before deciding where to put it.
        f.run(&[b"DEL", b"r"]);
        f.run(&[b"RPUSH", b"r", b"1", b"2", b"3"]);
        assert_eq!(f.run(&[b"RPOPLPUSH", b"r", b"r"]), "$1\r\n3\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"r", b"0", b"-1"]),
            bulks(&["3", "1", "2"])
        );
        assert_eq!(
            f.run(&[b"LMOVE", b"nope", b"d", b"LEFT", b"LEFT"]),
            "$-1\r\n"
        );
        assert_eq!(
            f.run(&[b"LMOVE", b"r", b"d", b"LEFT", b"SIDEWAYS"]),
            "-ERR syntax error\r\n"
        );
    }

    #[test]
    fn a_move_checks_the_destination_before_it_takes_anything() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a", b"b"]);
        f.run(&[b"SET", b"str", b"v"]);
        assert_eq!(
            f.run(&[b"LMOVE", b"k", b"str", b"LEFT", b"LEFT"]),
            "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
        );
        // The element is still where it was, rather than having gone nowhere.
        assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["a", "b"]));
    }

    #[test]
    fn lmpop_answers_from_the_first_key_that_has_anything() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"b", b"1", b"2", b"3"]);
        // The name of the key that answered comes back with the elements,
        // because the client cannot work out which one it was.
        assert_eq!(
            f.run(&[b"LMPOP", b"2", b"a", b"b", b"LEFT", b"COUNT", b"2"]),
            "*2\r\n$1\r\nb\r\n*2\r\n$1\r\n1\r\n$1\r\n2\r\n"
        );
        assert_eq!(
            f.run(&[b"LMPOP", b"2", b"a", b"b", b"RIGHT"]),
            "*2\r\n$1\r\nb\r\n*1\r\n$1\r\n3\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"b"]), ":0\r\n");
        // A null array and not a null, even though what it stands in for is an
        // array holding a key name and then another array.
        assert_eq!(f.run(&[b"LMPOP", b"2", b"a", b"b", b"LEFT"]), "*-1\r\n");
    }

    #[test]
    fn lmpop_has_its_own_words_for_a_count_and_for_a_key_count() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a"]);
        assert_eq!(
            f.run(&[b"LMPOP", b"0", b"k", b"LEFT"]),
            "-ERR numkeys should be greater than 0\r\n"
        );
        assert_eq!(
            f.run(&[b"LMPOP", b"-1", b"k", b"LEFT"]),
            "-ERR numkeys should be greater than 0\r\n"
        );
        assert_eq!(
            f.run(&[b"LMPOP", b"1", b"k", b"LEFT", b"COUNT", b"0"]),
            "-ERR count should be greater than 0\r\n"
        );
        // A key count that eats the direction is a syntax error and not a
        // sentence about key counts, because the direction is simply not there.
        assert_eq!(
            f.run(&[b"LMPOP", b"3", b"k", b"LEFT"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"LMPOP", b"1", b"k", b"LEFT", b"COUNT", b"1", b"x"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"LMPOP", b"1", b"k", b"LEFT", b"FOO", b"1"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"LMPOP", b"1", b"k", b"SIDEWAYS"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(f.run(&[b"LLEN", b"k"]), ":1\r\n");
    }

    #[test]
    fn every_list_command_says_wrongtype_and_writes_nothing() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"str", b"v"]);
        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
        for cmd in [
            &[b"LPUSH".as_slice(), b"str", b"a"][..],
            &[b"RPUSH", b"str", b"a"],
            &[b"LPUSHX", b"str", b"a"],
            &[b"RPUSHX", b"str", b"a"],
            &[b"LPOP", b"str"],
            &[b"LPOP", b"str", b"2"],
            &[b"RPOP", b"str"],
            &[b"LLEN", b"str"],
            &[b"LRANGE", b"str", b"0", b"-1"],
            &[b"LINDEX", b"str", b"0"],
            &[b"LSET", b"str", b"0", b"a"],
            &[b"LINSERT", b"str", b"BEFORE", b"a", b"b"],
            &[b"LREM", b"str", b"0", b"a"],
            &[b"LTRIM", b"str", b"0", b"-1"],
            &[b"LPOS", b"str", b"a"],
            &[b"LPOS", b"str", b"a", b"COUNT", b"0"],
            &[b"RPOPLPUSH", b"str", b"d"],
            &[b"LMOVE", b"str", b"d", b"LEFT", b"LEFT"],
            &[b"LMPOP", b"1", b"str", b"LEFT"],
        ] {
            assert_eq!(f.run(cmd), wrong, "{:?}", String::from_utf8_lossy(cmd[0]));
        }
        assert_eq!(f.run(&[b"GET", b"str"]), "$1\r\nv\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
    }

    /// A timeout is not an integer and it is not an ordinary float either: the
    /// three sentences it can answer with are its own, and which one a given
    /// argument gets is not what reading the code would suggest.
    #[test]
    fn a_timeout_has_three_ways_of_being_wrong() {
        let mut f = Fixture::new();
        let not_float = "-ERR timeout is not a float or out of range\r\n";
        let range = "-ERR timeout is out of range\r\n";
        for (bad, want) in [
            (&[b"BLPOP".as_slice(), b"k", b"abc"][..], not_float),
            (&[b"BLPOP", b"k", b"nan"], not_float),
            (&[b"BLPOP", b"k", b""], not_float),
            // Whitespace on either side, which `strtold` would take and Redis
            // does not.
            (&[b"BLPOP", b"k", b" 1"], not_float),
            (&[b"BLPOP", b"k", b"1 "], not_float),
            (&[b"BLPOP", b"k", b"-1"], "-ERR timeout is negative\r\n"),
            (&[b"BLPOP", b"k", b"-0.1"], "-ERR timeout is negative\r\n"),
            // These three parse, so they are not the not-a-float error, and all
            // three are further off than an i64 of milliseconds reaches.
            (&[b"BLPOP", b"k", b"1e400"], range),
            (&[b"BLPOP", b"k", b"inf"], range),
            (&[b"BLPOP", b"k", b"9999999999999999"], range),
            (&[b"BRPOP", b"k", b"abc"], not_float),
            (
                &[b"BLMOVE", b"a", b"b", b"LEFT", b"RIGHT", b"abc"],
                not_float,
            ),
            (
                &[b"BRPOPLPUSH", b"a", b"b", b"-1"],
                "-ERR timeout is negative\r\n",
            ),
            (&[b"BLMPOP", b"abc", b"1", b"k", b"LEFT"], not_float),
        ] {
            assert_eq!(f.run(bad), want, "for {bad:?}");
        }
    }

    /// A timeout of exactly zero means no timeout, and there are two ways of
    /// writing exactly zero.
    #[test]
    fn a_zero_timeout_waits_and_the_smallest_positive_one_does_not() {
        let mut f = Fixture::new();
        for timeout in [b"0".as_slice(), b"0.0", b"-0.0"] {
            let (flow, out) = f.flow(&[b"BLPOP", b"k", timeout]);
            assert_eq!(flow, Flow::Block, "for {timeout:?}");
            assert!(out.is_empty(), "for {timeout:?}");
        }
        // Positive, so it is a real deadline, and the deadline is this
        // millisecond. Nothing is written here either: the reply comes from the
        // sweep, which is the engine's and not this layer's.
        let (flow, out) = f.flow(&[b"BLPOP", b"k", b"0.0000001"]);
        assert_eq!(flow, Flow::Block);
        assert!(out.is_empty());
    }

    #[test]
    fn a_blocking_command_that_can_be_answered_answers_like_the_one_it_wraps() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"L", b"a", b"b", b"c", b"d", b"e"]);

        // The one difference from LPOP: the reply names the key that answered,
        // which is what makes BLPOP over several keys usable.
        assert_eq!(
            f.flow(&[b"BLPOP", b"nope", b"L", b"0"]),
            (Flow::Continue, "*2\r\n$1\r\nL\r\n$1\r\na\r\n".to_owned())
        );
        assert_eq!(
            f.run(&[b"BRPOP", b"L", b"0"]),
            "*2\r\n$1\r\nL\r\n$1\r\ne\r\n"
        );
        assert_eq!(
            f.run(&[
                b"BLMPOP", b"0", b"2", b"nope", b"L", b"LEFT", b"COUNT", b"2"
            ]),
            "*2\r\n$1\r\nL\r\n*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        assert_eq!(
            f.run(&[b"BLMOVE", b"L", b"D", b"LEFT", b"RIGHT", b"0"]),
            "$1\r\nd\r\n"
        );
        assert_eq!(
            f.run(&[b"EXISTS", b"L"]),
            ":0\r\n",
            "and the key went with it"
        );
        assert_eq!(f.run(&[b"LRANGE", b"D", b"0", b"-1"]), "*1\r\n$1\r\nd\r\n");
        // Onto itself, which is how a list is rotated and is a real thing to ask
        // a blocking move for.
        f.run(&[b"RPUSH", b"D", b"x"]);
        assert_eq!(f.run(&[b"BRPOPLPUSH", b"D", b"D", b"0"]), "$1\r\nx\r\n");
        assert_eq!(
            f.run(&[b"LRANGE", b"D", b"0", b"-1"]),
            "*2\r\n$1\r\nx\r\n$1\r\nd\r\n"
        );
    }

    #[test]
    fn blmpop_reads_its_count_and_its_key_count_the_way_lmpop_does() {
        let mut f = Fixture::new();
        f.run(&[b"RPUSH", b"k", b"a"]);
        for (bad, want) in [
            (
                &[b"BLMPOP".as_slice(), b"0", b"0", b"k", b"LEFT"][..],
                "-ERR numkeys should be greater than 0\r\n",
            ),
            (
                &[b"BLMPOP", b"0", b"-1", b"k", b"LEFT"],
                "-ERR numkeys should be greater than 0\r\n",
            ),
            // Two keys named and one given, so the word that should have been
            // the direction is a key and there is no direction left.
            (
                &[b"BLMPOP", b"0", b"2", b"k", b"LEFT"],
                "-ERR syntax error\r\n",
            ),
            (
                &[b"BLMPOP", b"0", b"1", b"k", b"SIDEWAYS"],
                "-ERR syntax error\r\n",
            ),
            (
                &[b"BLMPOP", b"0", b"1", b"k", b"LEFT", b"COUNT"],
                "-ERR syntax error\r\n",
            ),
            (
                &[b"BLMPOP", b"0", b"1", b"k", b"LEFT", b"COUNT", b"2", b"x"],
                "-ERR syntax error\r\n",
            ),
            // A count that is not a number at all gets the same sentence a zero
            // or a negative one gets, rather than the usual one about integers.
            (
                &[b"BLMPOP", b"0", b"1", b"k", b"LEFT", b"COUNT", b"0"],
                "-ERR count should be greater than 0\r\n",
            ),
            (
                &[b"BLMPOP", b"0", b"1", b"k", b"LEFT", b"COUNT", b"abc"],
                "-ERR count should be greater than 0\r\n",
            ),
        ] {
            assert_eq!(f.run(bad), want, "for {bad:?}");
        }
        assert_eq!(f.run(&[b"LLEN", b"k"]), ":1\r\n", "and none of them popped");
    }

    #[test]
    fn a_blocking_move_reads_its_directions_before_its_timeout() {
        let mut f = Fixture::new();
        // Both are wrong. Redis checks the directions first, so this is the
        // syntax error and not a complaint about the timeout.
        assert_eq!(
            f.run(&[b"BLMOVE", b"a", b"b", b"UP", b"DOWN", b"abc"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"BLMOVE", b"a", b"b", b"LEFT", b"DOWN", b"0.05"]),
            "-ERR syntax error\r\n"
        );
    }

    /// The four ways a blocking command sees a key of another type, and the one
    /// way it does not.
    #[test]
    fn a_blocking_command_errors_on_a_wrong_type_rather_than_waiting_on_it() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"S", b"v"]);
        f.run(&[b"RPUSH", b"D", b"x"]);
        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";

        assert_eq!(f.run(&[b"BLPOP", b"S", b"0"]), wrong);
        // Every key is checked even when an earlier one would have blocked, so
        // an empty key in front of a string does not hide it.
        assert_eq!(f.run(&[b"BLPOP", b"E", b"S", b"0"]), wrong);
        assert_eq!(f.run(&[b"BRPOP", b"S", b"0"]), wrong);
        assert_eq!(f.run(&[b"BLMPOP", b"0", b"1", b"S", b"LEFT"]), wrong);
        assert_eq!(f.run(&[b"BRPOPLPUSH", b"S", b"D", b"0"]), wrong);
        // The destination, which is only reached because the source has
        // something in it.
        assert_eq!(f.run(&[b"BRPOPLPUSH", b"D", b"S", b"0"]), wrong);
        assert_eq!(f.run(&[b"LRANGE", b"D", b"0", b"-1"]), "*1\r\n$1\r\nx\r\n");

        // And the one that does not: an empty source means the destination is
        // never looked at, so this waits rather than erroring, and on a real
        // server it times out.
        assert_eq!(
            f.flow(&[b"BLMOVE", b"E", b"S", b"LEFT", b"RIGHT", b"0.1"])
                .0,
            Flow::Block
        );
    }

    /// The same churn the set and the string get, because a list that leaks a
    /// chunk per push looks exactly like one that does not until it has run for
    /// an afternoon.
    #[test]
    fn churning_lists_does_not_grow_the_server() {
        let mut f = Fixture::new();
        let vals: Vec<Vec<u8>> = (0..200).map(|i| format!("v{i}").into_bytes()).collect();
        let args: Vec<&[u8]> = [&b"RPUSH"[..], &b"k"[..]]
            .into_iter()
            .chain(vals.iter().map(Vec::as_slice))
            .collect();

        f.run(&args);
        f.run(&[b"DEL", b"k"]);
        f.server.compact_step();
        let after_first = f.server.memory_bytes();

        for _ in 0..200 {
            f.run(&args);
            f.run(&[b"LTRIM", b"k", b"1", b"0"]);
            f.server.compact_step();
        }
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
        assert!(
            f.server.memory_bytes() <= after_first * 2,
            "held {} after two hundred passes against {after_first} after one",
            f.server.memory_bytes()
        );
    }

    // ------------------------------------------------------------ sorted set

    #[test]
    fn a_sorted_set_takes_scores_and_gives_them_back() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b"]), ":2\r\n");
        assert_eq!(f.run(&[b"ZADD", b"z", b"1", b"a", b"3", b"c"]), ":1\r\n");
        assert_eq!(f.run(&[b"ZCARD", b"z"]), ":3\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"b"]), "$1\r\n2\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"nope"]), "$-1\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"nokey", b"b"]), "$-1\r\n");
        assert_eq!(
            f.run(&[b"ZMSCORE", b"z", b"a", b"nope", b"c"]),
            "*3\r\n$1\r\n1\r\n$-1\r\n$1\r\n3\r\n"
        );
        assert_eq!(f.run(&[b"ZREM", b"z", b"a", b"nope"]), ":1\r\n");
        assert_eq!(f.run(&[b"ZCARD", b"z"]), ":2\r\n");
        // The key goes when the last member does.
        assert_eq!(f.run(&[b"ZREM", b"z", b"b", b"c"]), ":2\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
    }

    #[test]
    fn a_score_is_a_double_on_resp3_and_digits_on_resp2() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1.5", b"a", b"inf", b"b", b"-inf", b"c"]);
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"a"]), "$3\r\n1.5\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"b"]), "$3\r\ninf\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"c"]), "$4\r\n-inf\r\n");

        f.out = Out::new(Proto::Resp3);
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"a"]), ",1.5\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"b"]), ",inf\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"c"]), ",-inf\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"nope"]), "_\r\n");
    }

    #[test]
    fn the_zadd_options_gate_what_gets_written() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"5", b"a"]);
        // NX leaves a member that is there alone, XX will not create one.
        assert_eq!(f.run(&[b"ZADD", b"z", b"NX", b"9", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"a"]), "$1\r\n5\r\n");
        assert_eq!(f.run(&[b"ZADD", b"z", b"XX", b"9", b"new"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"z"]), ":1\r\n");
        // GT and LT only move a score one way.
        assert_eq!(f.run(&[b"ZADD", b"z", b"GT", b"CH", b"3", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"ZADD", b"z", b"GT", b"CH", b"7", b"a"]), ":1\r\n");
        assert_eq!(f.run(&[b"ZADD", b"z", b"LT", b"CH", b"9", b"a"]), ":0\r\n");
        // CH counts a moved score and plain ZADD does not.
        assert_eq!(f.run(&[b"ZADD", b"z", b"1", b"a", b"1", b"b"]), ":1\r\n");
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"CH", b"2", b"a", b"2", b"c"]),
            ":2\r\n"
        );
    }

    #[test]
    fn zadd_incr_answers_a_score_or_nothing_at_all() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"ZADD", b"z", b"INCR", b"5", b"m"]), "$1\r\n5\r\n");
        assert_eq!(f.run(&[b"ZADD", b"z", b"INCR", b"2", b"m"]), "$1\r\n7\r\n");
        // A gate that refuses is the string nil, because the reply it stands in
        // for is a score.
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"NX", b"INCR", b"2", b"m"]),
            "$-1\r\n"
        );
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"XX", b"INCR", b"2", b"gone"]),
            "$-1\r\n"
        );
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"GT", b"INCR", b"-1", b"m"]),
            "$-1\r\n"
        );
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"GT", b"INCR", b"1", b"m"]),
            "$1\r\n8\r\n"
        );
        assert_eq!(f.run(&[b"ZINCRBY", b"z", b"2", b"m"]), "$2\r\n10\r\n");
        assert_eq!(f.run(&[b"ZINCRBY", b"z", b"1", b"fresh"]), "$1\r\n1\r\n");
    }

    #[test]
    fn the_two_infinities_will_not_be_added_together() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"inf", b"m"]);
        let nan = "-ERR resulting score is not a number (NaN)\r\n";
        assert_eq!(f.run(&[b"ZINCRBY", b"z", b"-inf", b"m"]), nan);
        assert_eq!(f.run(&[b"ZADD", b"z", b"INCR", b"-inf", b"m"]), nan);
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"m"]), "$3\r\ninf\r\n");
        // And a key made for an increment that then fails does not stay behind.
        assert_eq!(f.run(&[b"ZINCRBY", b"gone", b"1", b"m"]), "$1\r\n1\r\n");
    }

    #[test]
    fn zadd_says_its_mistakes_the_way_redis_says_them() {
        let mut f = Fixture::new();
        // The pairs are counted before the options are looked at, so this is a
        // syntax error about having none and not a complaint about NX and XX.
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"NX", b"XX"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"NX", b"XX", b"1", b"a"]),
            "-ERR XX and NX options at the same time are not compatible\r\n"
        );
        let gtlt = "-ERR GT, LT, and/or NX options at the same time are not compatible\r\n";
        assert_eq!(f.run(&[b"ZADD", b"z", b"NX", b"GT", b"1", b"a"]), gtlt);
        assert_eq!(f.run(&[b"ZADD", b"z", b"GT", b"LT", b"1", b"a"]), gtlt);
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"INCR", b"1", b"a", b"2", b"b"]),
            "-ERR INCR option supports a single increment-element pair\r\n"
        );
        // An odd number of arguments after the options.
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"1", b"a", b"2"]),
            "-ERR syntax error\r\n"
        );
        // Every score is read before the first is stored.
        assert_eq!(
            f.run(&[b"ZADD", b"z", b"1", b"a", b"nonsense", b"b"]),
            "-ERR value is not a valid float\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
    }

    #[test]
    fn a_rank_says_where_a_member_sits_from_either_end() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(f.run(&[b"ZRANK", b"z", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"ZRANK", b"z", b"c"]), ":2\r\n");
        assert_eq!(f.run(&[b"ZREVRANK", b"z", b"c"]), ":0\r\n");
        assert_eq!(f.run(&[b"ZREVRANK", b"z", b"a"]), ":2\r\n");
        // WITHSCORE changes both shapes: the answer and the nothing.
        assert_eq!(
            f.run(&[b"ZRANK", b"z", b"b", b"WITHSCORE"]),
            "*2\r\n:1\r\n$1\r\n2\r\n"
        );
        assert_eq!(f.run(&[b"ZRANK", b"z", b"nope"]), "$-1\r\n");
        assert_eq!(f.run(&[b"ZRANK", b"z", b"nope", b"WITHSCORE"]), "*-1\r\n");
        assert_eq!(f.run(&[b"ZRANK", b"nokey", b"a", b"WITHSCORE"]), "*-1\r\n");
        // A bad option is a syntax error and one argument too many is an arity
        // error, which is Redis's split.
        assert_eq!(
            f.run(&[b"ZRANK", b"z", b"b", b"bogus"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"ZREVRANK", b"z", b"b", b"WITHSCORE", b"more"]),
            "-ERR wrong number of arguments for 'zrevrank' command\r\n"
        );
    }

    #[test]
    fn the_two_counts_read_their_two_kinds_of_bound() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(f.run(&[b"ZCOUNT", b"z", b"-inf", b"+inf"]), ":3\r\n");
        assert_eq!(f.run(&[b"ZCOUNT", b"z", b"2", b"3"]), ":2\r\n");
        assert_eq!(f.run(&[b"ZCOUNT", b"z", b"(1", b"3"]), ":2\r\n");
        assert_eq!(f.run(&[b"ZCOUNT", b"z", b"(1", b"(3"]), ":1\r\n");
        assert_eq!(f.run(&[b"ZCOUNT", b"nokey", b"-inf", b"+inf"]), ":0\r\n");
        assert_eq!(
            f.run(&[b"ZCOUNT", b"z", b"bogus", b"3"]),
            "-ERR min or max is not a float\r\n"
        );

        f.run(&[b"ZADD", b"l", b"0", b"a", b"0", b"b", b"0", b"c"]);
        assert_eq!(f.run(&[b"ZLEXCOUNT", b"l", b"-", b"+"]), ":3\r\n");
        assert_eq!(f.run(&[b"ZLEXCOUNT", b"l", b"[a", b"(c"]), ":2\r\n");
        assert_eq!(f.run(&[b"ZLEXCOUNT", b"l", b"(a", b"+"]), ":2\r\n");
        // A bare member is not a bound, because a member can start with any
        // byte and there would be no way to say the bracket if it were optional.
        assert_eq!(
            f.run(&[b"ZLEXCOUNT", b"l", b"a", b"c"]),
            "-ERR min or max not valid string range item\r\n"
        );
    }

    /// The three ways `ZRANGE` can be asked for a window, forwards and back.
    ///
    /// Every byte in here was read off a real 8.10.1 rather than worked out,
    /// because the interesting part of this command is not what it selects, it
    /// is which of the two ends the client is expected to name first.
    #[test]
    fn one_range_command_selects_by_rank_or_score_or_name() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"0", b"-1"]),
            "*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"-2", b"-1"]),
            "*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        assert_eq!(f.run(&[b"ZRANGE", b"z", b"5", b"9"]), "*0\r\n");
        assert_eq!(f.run(&[b"ZRANGE", b"nokey", b"0", b"-1"]), "*0\r\n");
        // REV over ranks reverses the walk and leaves the two arguments alone,
        // because a rank counts from the end the walk starts at.
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"REV"]),
            "*3\r\n$1\r\nc\r\n$1\r\nb\r\n$1\r\na\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"(1", b"+inf", b"BYSCORE"]),
            "*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        // And REV over scores does swap them, since a bound does not count from
        // anywhere. This is the one line of the parse that tells the two apart.
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"+inf", b"(1", b"BYSCORE", b"REV"]),
            "*2\r\n$1\r\nc\r\n$1\r\nb\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"-", b"+", b"BYLEX"]),
            "*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"+", b"-", b"BYLEX", b"REV"]),
            "*3\r\n$1\r\nc\r\n$1\r\nb\r\n$1\r\na\r\n"
        );
    }

    /// The older spellings, which are the same six windows with the mode in the
    /// name and the high end named first on the three that go backwards.
    #[test]
    fn the_older_range_spellings_name_their_high_end_first() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(
            f.run(&[b"ZREVRANGE", b"z", b"0", b"-1"]),
            "*3\r\n$1\r\nc\r\n$1\r\nb\r\n$1\r\na\r\n"
        );
        assert_eq!(
            f.run(&[b"ZREVRANGE", b"z", b"0", b"0", b"WITHSCORES"]),
            "*2\r\n$1\r\nc\r\n$1\r\n3\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGEBYSCORE", b"z", b"(1", b"3"]),
            "*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        assert_eq!(
            f.run(&[b"ZREVRANGEBYSCORE", b"z", b"3", b"(1"]),
            "*2\r\n$1\r\nc\r\n$1\r\nb\r\n"
        );
        // The two arguments the wrong way round is an empty answer and not an
        // error, which is what the swap being in the parse rather than in the
        // window buys.
        assert_eq!(f.run(&[b"ZREVRANGEBYSCORE", b"z", b"(1", b"3"]), "*0\r\n");
        assert_eq!(
            f.run(&[b"ZRANGEBYLEX", b"z", b"[a", b"(c"]),
            "*2\r\n$1\r\na\r\n$1\r\nb\r\n"
        );
        assert_eq!(
            f.run(&[b"ZREVRANGEBYLEX", b"z", b"(c", b"[a"]),
            "*2\r\n$1\r\nb\r\n$1\r\na\r\n"
        );
        // BYSCORE, BYLEX and REV mean nothing to these, so they are not another
        // way of spelling the mode, they are a syntax error.
        for cmd in [
            &[b"ZREVRANGE".as_slice(), b"z", b"0", b"-1", b"BYSCORE"][..],
            &[b"ZRANGEBYSCORE", b"z", b"1", b"3", b"REV"],
            &[b"ZRANGEBYLEX", b"z", b"[a", b"[c", b"BYLEX"],
        ] {
            assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{:?}", cmd[0]);
        }
    }

    /// `LIMIT` and `WITHSCORES`, which every one of these commands reads and
    /// only some of them accept.
    #[test]
    fn limit_and_withscores_are_read_by_all_of_them_and_refused_afterwards() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(
            f.run(&[
                b"ZRANGE", b"z", b"-inf", b"+inf", b"BYSCORE", b"LIMIT", b"1", b"1"
            ]),
            "*1\r\n$1\r\nb\r\n"
        );
        // A negative offset skips past everything, a negative count is no bound.
        assert_eq!(
            f.run(&[
                b"ZRANGE", b"z", b"-inf", b"+inf", b"BYSCORE", b"LIMIT", b"-1", b"2"
            ]),
            "*0\r\n"
        );
        assert_eq!(
            f.run(&[
                b"ZRANGE", b"z", b"-inf", b"+inf", b"BYSCORE", b"LIMIT", b"0", b"-1"
            ]),
            "*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        // The two options in either order, which falls out of the parse loop.
        let both = "*4\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n";
        assert_eq!(
            f.run(&[
                b"ZRANGEBYSCORE",
                b"z",
                b"1",
                b"3",
                b"WITHSCORES",
                b"LIMIT",
                b"0",
                b"2"
            ]),
            both
        );
        assert_eq!(
            f.run(&[
                b"ZRANGEBYSCORE",
                b"z",
                b"1",
                b"3",
                b"LIMIT",
                b"0",
                b"2",
                b"WITHSCORES"
            ]),
            both
        );
        // LIMIT on a range by rank is refused after the whole option list has
        // been read, so this complains about LIMIT and not about WITHSCORES.
        let needs_by = "-ERR syntax error, LIMIT is only supported in combination with either BYSCORE or BYLEX\r\n";
        assert_eq!(
            f.run(&[
                b"ZREVRANGE",
                b"z",
                b"0",
                b"-1",
                b"WITHSCORES",
                b"LIMIT",
                b"0",
                b"1"
            ]),
            needs_by
        );
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"LIMIT", b"0", b"1"]),
            needs_by
        );
        let not_bylex = "-ERR syntax error, WITHSCORES not supported in combination with BYLEX\r\n";
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"-", b"+", b"BYLEX", b"WITHSCORES"]),
            not_bylex
        );
        assert_eq!(
            f.run(&[b"ZRANGEBYLEX", b"z", b"[a", b"[c", b"WITHSCORES"]),
            not_bylex
        );
        // Two modes at once, an option nobody knows, a LIMIT missing its count,
        // and the three number errors, which are three different sentences.
        for cmd in [
            &[
                b"ZRANGE".as_slice(),
                b"z",
                b"0",
                b"-1",
                b"BYSCORE",
                b"BYLEX",
            ][..],
            &[b"ZRANGE", b"z", b"0", b"-1", b"junk"],
            &[b"ZRANGEBYSCORE", b"z", b"1", b"3", b"LIMIT", b"0"],
        ] {
            assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{cmd:?}");
        }
        assert_eq!(
            f.run(&[b"ZRANGEBYSCORE", b"z", b"bad", b"3"]),
            "-ERR min or max is not a float\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGEBYLEX", b"z", b"a", b"[c"]),
            "-ERR min or max not valid string range item\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGEBYSCORE", b"z", b"1", b"3", b"LIMIT", b"a", b"2"]),
            "-ERR value is not an integer or out of range\r\n"
        );
    }

    /// `WITHSCORES` is the one place in this group where the two protocols
    /// disagree about the shape of the reply and not just the type of a value.
    #[test]
    fn withscores_nests_on_resp3_and_flattens_on_resp2() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"WITHSCORES"]),
            "*6\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n"
        );
        f.out = Out::new(Proto::Resp3);
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"WITHSCORES"]),
            "*3\r\n*2\r\n$1\r\na\r\n,1\r\n*2\r\n$1\r\nb\r\n,2\r\n*2\r\n$1\r\nc\r\n,3\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"0", b"-1"]),
            "*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
    }

    /// The store form, which is the same parse with the destination in front.
    #[test]
    fn a_range_store_writes_the_window_into_another_key() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(f.run(&[b"ZRANGESTORE", b"d", b"z", b"0", b"-1"]), ":3\r\n");
        // A window that selects nothing deletes the destination rather than
        // leaving an empty sorted set, because an empty one does not exist.
        assert_eq!(f.run(&[b"ZRANGESTORE", b"d", b"z", b"5", b"9"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
        assert_eq!(
            f.run(&[b"ZRANGESTORE", b"d", b"z", b"(1", b"+inf", b"BYSCORE"]),
            ":2\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANGE", b"d", b"0", b"-1", b"WITHSCORES"]),
            "*4\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n"
        );
        // The destination is allowed to be the source, because the result is
        // built whole before anything is written over.
        assert_eq!(f.run(&[b"ZRANGESTORE", b"z", b"z", b"1", b"2"]), ":2\r\n");
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"WITHSCORES"]),
            "*4\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n"
        );
        // It takes every option ZRANGE takes except WITHSCORES, which is a
        // plain syntax error here and not the sentence about BYLEX.
        assert_eq!(
            f.run(&[b"ZRANGESTORE", b"d", b"z", b"0", b"-1", b"WITHSCORES"]),
            "-ERR syntax error\r\n"
        );
    }

    /// The three removals, which are the read side's window with the walk
    /// turned into a removal and no options at all.
    #[test]
    fn the_three_removals_share_their_window_with_the_reads() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(f.run(&[b"ZREMRANGEBYRANK", b"z", b"0", b"0"]), ":1\r\n");
        assert_eq!(
            f.run(&[b"ZRANGE", b"z", b"0", b"-1"]),
            "*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
        );
        assert_eq!(
            f.run(&[b"ZREMRANGEBYSCORE", b"z", b"(2", b"+inf"]),
            ":1\r\n"
        );
        assert_eq!(f.run(&[b"ZRANGE", b"z", b"0", b"-1"]), "*1\r\n$1\r\nb\r\n");
        // The last member going takes the key with it.
        assert_eq!(f.run(&[b"ZREMRANGEBYLEX", b"z", b"-", b"+"]), ":1\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
        assert_eq!(
            f.run(&[b"ZREMRANGEBYRANK", b"nokey", b"0", b"-1"]),
            ":0\r\n"
        );
        assert_eq!(
            f.run(&[b"ZREMRANGEBYRANK", b"z", b"0", b"x"]),
            "-ERR value is not an integer or out of range\r\n"
        );
    }

    /// The algebra, which is one gather and three names for it.
    #[test]
    fn the_three_algebra_commands_combine_scores_and_order_the_answer_once() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        f.run(&[b"ZADD", b"y", b"10", b"b", b"20", b"d"]);
        assert_eq!(
            f.run(&[b"ZUNION", b"2", b"z", b"y"]),
            "*4\r\n$1\r\na\r\n$1\r\nc\r\n$1\r\nb\r\n$1\r\nd\r\n"
        );
        // The scores are added where a member is in both, and the answer comes
        // out in the order those combined scores put it in.
        assert_eq!(
            f.run(&[b"ZUNION", b"2", b"z", b"y", b"WITHSCORES"]),
            "*8\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nc\r\n$1\r\n3\r\n$1\r\nb\r\n$2\r\n12\r\n$1\r\nd\r\n$2\r\n20\r\n"
        );
        assert_eq!(
            f.run(&[
                b"ZUNION",
                b"2",
                b"z",
                b"y",
                b"WEIGHTS",
                b"2",
                b"3",
                b"WITHSCORES"
            ]),
            "*8\r\n$1\r\na\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n6\r\n$1\r\nb\r\n$2\r\n34\r\n$1\r\nd\r\n$2\r\n60\r\n"
        );
        assert_eq!(
            f.run(&[
                b"ZUNION",
                b"2",
                b"z",
                b"y",
                b"AGGREGATE",
                b"MIN",
                b"WITHSCORES"
            ]),
            "*8\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n$1\r\nd\r\n$2\r\n20\r\n"
        );
        assert_eq!(
            f.run(&[
                b"ZUNION",
                b"2",
                b"z",
                b"y",
                b"AGGREGATE",
                b"MAX",
                b"WITHSCORES"
            ]),
            "*8\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nc\r\n$1\r\n3\r\n$1\r\nb\r\n$2\r\n10\r\n$1\r\nd\r\n$2\r\n20\r\n"
        );
        assert_eq!(
            f.run(&[b"ZINTER", b"2", b"z", b"y", b"WITHSCORES"]),
            "*2\r\n$1\r\nb\r\n$2\r\n12\r\n"
        );
        assert_eq!(
            f.run(&[b"ZDIFF", b"2", b"z", b"y", b"WITHSCORES"]),
            "*4\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nc\r\n$1\r\n3\r\n"
        );
        assert_eq!(f.run(&[b"ZUNION", b"1", b"nokey"]), "*0\r\n");
        // A plain set is an input, and it behaves as a sorted set in which
        // every member scores one.
        f.run(&[b"SADD", b"p", b"a", b"d"]);
        assert_eq!(
            f.run(&[b"ZUNION", b"2", b"z", b"p", b"WITHSCORES"]),
            "*8\r\n$1\r\nd\r\n$1\r\n1\r\n$1\r\na\r\n$1\r\n2\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n"
        );
        // A difference never combines two scores, so it has nothing for either
        // of the two options to do and refuses both.
        for cmd in [
            &[
                b"ZDIFF".as_slice(),
                b"2",
                b"z",
                b"y",
                b"WEIGHTS",
                b"1",
                b"1",
            ][..],
            &[b"ZDIFF", b"2", b"z", b"y", b"AGGREGATE", b"MIN"],
        ] {
            assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{cmd:?}");
        }
    }

    /// The count of keys, which is what lets a key be named `WEIGHTS`.
    #[test]
    fn the_algebra_counts_its_keys_and_says_so_when_the_count_is_wrong() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a"]);
        f.run(&[b"ZADD", b"y", b"2", b"b"]);
        // Redis names the command in this one, so each spelling says its own.
        assert_eq!(
            f.run(&[b"ZUNION", b"0", b"z"]),
            "-ERR at least 1 input key is needed for 'zunion' command\r\n"
        );
        assert_eq!(
            f.run(&[b"ZUNION", b"-1", b"z"]),
            "-ERR at least 1 input key is needed for 'zunion' command\r\n"
        );
        assert_eq!(
            f.run(&[b"ZINTERCARD", b"0", b"z"]),
            "-ERR at least 1 input key is needed for 'zintercard' command\r\n"
        );
        // A count bigger than the line is a plain syntax error, which reads
        // oddly and is what Redis says.
        assert_eq!(
            f.run(&[b"ZUNION", b"3", b"z", b"y"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"ZUNION", b"x", b"z"]),
            "-ERR value is not an integer or out of range\r\n"
        );
        // A WEIGHTS list that is not one per key is a syntax error, and a
        // weight that is not a number gets a sentence of its own.
        assert_eq!(
            f.run(&[b"ZUNION", b"2", b"z", b"y", b"WEIGHTS", b"1"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"ZUNION", b"2", b"z", b"y", b"WEIGHTS", b"a", b"b"]),
            "-ERR weight value is not a float\r\n"
        );
        assert_eq!(
            f.run(&[b"ZUNION", b"2", b"z", b"y", b"AGGREGATE", b"NOPE"]),
            "-ERR syntax error\r\n"
        );
    }

    /// The three store forms, which answer a count and take no WITHSCORES.
    #[test]
    fn the_algebra_stores_answer_a_count_and_delete_an_empty_destination() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        f.run(&[b"ZADD", b"y", b"10", b"b", b"20", b"d"]);
        assert_eq!(f.run(&[b"ZUNIONSTORE", b"d", b"2", b"z", b"y"]), ":4\r\n");
        assert_eq!(
            f.run(&[b"ZRANGE", b"d", b"0", b"-1", b"WITHSCORES"]),
            "*8\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nc\r\n$1\r\n3\r\n$1\r\nb\r\n$2\r\n12\r\n$1\r\nd\r\n$2\r\n20\r\n"
        );
        assert_eq!(f.run(&[b"ZINTERSTORE", b"d", b"2", b"z", b"y"]), ":1\r\n");
        assert_eq!(f.run(&[b"ZDIFFSTORE", b"d", b"2", b"z", b"y"]), ":2\r\n");
        // An empty result deletes the destination rather than leaving an empty
        // sorted set, because an empty one does not exist.
        assert_eq!(
            f.run(&[b"ZINTERSTORE", b"d", b"2", b"z", b"nokey"]),
            ":0\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
        // The destination is allowed to name its own source.
        assert_eq!(f.run(&[b"ZUNIONSTORE", b"z", b"2", b"z", b"y"]), ":4\r\n");
        assert_eq!(f.run(&[b"ZCARD", b"z"]), ":4\r\n");
        for cmd in [
            &[
                b"ZUNIONSTORE".as_slice(),
                b"d",
                b"2",
                b"z",
                b"y",
                b"WITHSCORES",
            ][..],
            &[
                b"ZDIFFSTORE",
                b"d",
                b"2",
                b"z",
                b"y",
                b"WEIGHTS",
                b"1",
                b"1",
            ],
        ] {
            assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{cmd:?}");
        }
    }

    /// `ZINTERCARD`, which counts without building anything.
    #[test]
    fn intercard_counts_and_stops_at_its_limit() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        f.run(&[b"ZADD", b"y", b"10", b"b", b"20", b"c", b"30", b"d"]);
        assert_eq!(f.run(&[b"ZINTERCARD", b"2", b"z", b"y"]), ":2\r\n");
        // A limit of zero is no limit, which is Redis's reading of it.
        assert_eq!(
            f.run(&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT", b"0"]),
            ":2\r\n"
        );
        assert_eq!(
            f.run(&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT", b"1"]),
            ":1\r\n"
        );
        // A negative limit and a limit that is not a number at all get the same
        // sentence, which looks like a mistake in Redis and is copied as one.
        let bad = "-ERR LIMIT can't be negative\r\n";
        assert_eq!(
            f.run(&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT", b"-1"]),
            bad
        );
        assert_eq!(
            f.run(&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT", b"x"]),
            bad
        );
        for cmd in [
            &[b"ZINTERCARD".as_slice(), b"3", b"z", b"y"][..],
            &[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT"],
            &[b"ZINTERCARD", b"2", b"z", b"y", b"junk", b"1"],
        ] {
            assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{cmd:?}");
        }
    }

    /// `ZRANDMEMBER`, which answers two different shapes out of one name.
    #[test]
    fn a_draw_answers_one_member_or_an_array_of_them() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        // No count is one member or a nil, a count is an array that may be
        // empty, and those are two reply types the client has to tell apart.
        assert_eq!(f.run(&[b"ZRANDMEMBER", b"nokey"]), "$-1\r\n");
        assert_eq!(f.run(&[b"ZRANDMEMBER", b"nokey", b"3"]), "*0\r\n");
        assert_eq!(f.run(&[b"ZRANDMEMBER", b"z", b"0"]), "*0\r\n");
        assert!(f.run(&[b"ZRANDMEMBER", b"z"]).starts_with("$1\r\n"));
        // A positive count draws without replacement, so a count over the size
        // answers the whole set and never a member twice.
        let all = f.run(&[b"ZRANDMEMBER", b"z", b"10"]);
        assert!(all.starts_with("*3\r\n"), "{all}");
        for m in ["a", "b", "c"] {
            assert!(all.contains(m), "{all}");
        }
        // A negative one draws with replacement and answers exactly as many as
        // it was asked for, whatever the size of the set.
        assert!(
            f.run(&[b"ZRANDMEMBER", b"z", b"-5"]).starts_with("*5\r\n"),
            "five draws with replacement"
        );
        assert!(
            f.run(&[b"ZRANDMEMBER", b"z", b"2", b"WITHSCORES"])
                .starts_with("*4\r\n"),
            "two pairs, flat on RESP2"
        );
        f.out = Out::new(Proto::Resp3);
        let got = f.run(&[b"ZRANDMEMBER", b"z", b"2", b"WITHSCORES"]);
        assert!(got.starts_with("*2\r\n*2\r\n"), "{got}");
        assert_eq!(f.run(&[b"ZRANDMEMBER", b"nokey"]), "_\r\n");
        f.out = Out::new(Proto::Resp2);
        assert_eq!(
            f.run(&[b"ZRANDMEMBER", b"z", b"2", b"junk"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"ZRANDMEMBER", b"z", b"x"]),
            "-ERR value is not an integer or out of range\r\n"
        );
    }

    /// `ZSCAN`, and the one sorted set reply where a score is not a double.
    #[test]
    fn a_sorted_set_scan_answers_pairs_of_strings_on_both_protocols() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        let all = "*2\r\n$1\r\n0\r\n*6\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n";
        assert_eq!(f.run(&[b"ZSCAN", b"z", b"0"]), all);
        assert_eq!(f.run(&[b"ZSCAN", b"z", b"0", b"COUNT", b"10"]), all);
        assert_eq!(
            f.run(&[b"ZSCAN", b"z", b"0", b"MATCH", b"a*"]),
            "*2\r\n$1\r\n0\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
        );
        assert_eq!(
            f.run(&[b"ZSCAN", b"nokey", b"0"]),
            "*2\r\n$1\r\n0\r\n*0\r\n"
        );
        // A score stays a bulk string on RESP3, which is the one place the two
        // protocols agree about a score and everywhere else they do not.
        f.out = Out::new(Proto::Resp3);
        assert_eq!(f.run(&[b"ZSCAN", b"z", b"0"]), all);
        f.out = Out::new(Proto::Resp2);
        assert_eq!(
            f.run(&[b"ZSCAN", b"z", b"0", b"NOVALUES"]),
            "-ERR NOVALUES option can only be used in HSCAN\r\n"
        );
        assert_eq!(f.run(&[b"ZSCAN", b"z", b"-1"]), "-ERR invalid cursor\r\n");
        assert_eq!(
            f.run(&[b"ZSCAN", b"z", b"0", b"COUNT", b"0"]),
            "-ERR syntax error\r\n"
        );
    }

    /// The count is what decides the shape, and its value is not.
    #[test]
    fn a_sorted_set_pop_changes_shape_when_it_is_given_a_count() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        // No count, so one flat pair, and the score is a bulk string on RESP2.
        assert_eq!(f.run(&[b"ZPOPMIN", b"z"]), "*2\r\n$1\r\na\r\n$1\r\n1\r\n");
        assert_eq!(f.run(&[b"ZPOPMAX", b"z"]), "*2\r\n$1\r\nc\r\n$1\r\n3\r\n");
        f.run(&[b"ZADD", b"z", b"1", b"a", b"3", b"c"]);
        // A count, so pairs, and on RESP2 they are flattened into one run.
        assert_eq!(
            f.run(&[b"ZPOPMIN", b"z", b"2"]),
            "*4\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n"
        );
        // An empty array rather than a null, which is where a sorted set pop and
        // a list pop part company, and the same answer a count of zero gives.
        assert_eq!(f.run(&[b"ZPOPMIN", b"nokey"]), "*0\r\n");
        assert_eq!(f.run(&[b"ZPOPMIN", b"nokey", b"2"]), "*0\r\n");
        assert_eq!(f.run(&[b"ZPOPMIN", b"z", b"0"]), "*0\r\n");
        // The last member takes the key with it.
        assert_eq!(
            f.run(&[b"ZPOPMIN", b"z", b"9"]),
            "*2\r\n$1\r\nc\r\n$1\r\n3\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");

        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b"]);
        f.out = Out::new(Proto::Resp3);
        assert_eq!(f.run(&[b"ZPOPMIN", b"z"]), "*2\r\n$1\r\na\r\n,1\r\n");
        assert_eq!(
            f.run(&[b"ZPOPMIN", b"z", b"1"]),
            "*1\r\n*2\r\n$1\r\nb\r\n,2\r\n"
        );
        f.out = Out::new(Proto::Resp2);
        // Both of these are the range error rather than the usual sentence about
        // integers, which is the odd answer and so the one worth copying.
        let bad = "-ERR value is out of range, must be positive\r\n";
        assert_eq!(f.run(&[b"ZPOPMIN", b"z", b"x"]), bad);
        assert_eq!(f.run(&[b"ZPOPMIN", b"z", b"-1"]), bad);
        assert_eq!(
            f.run(&[b"ZPOPMIN", b"z", b"1", b"2"]),
            "-ERR syntax error\r\n"
        );
    }

    /// `ZMPOP`, which is `LMPOP` with scores and the same parse.
    #[test]
    fn a_multi_key_pop_names_the_key_that_answered_and_nests_its_pairs() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(
            f.run(&[b"ZMPOP", b"2", b"nokey", b"z", b"MIN"]),
            "*2\r\n$1\r\nz\r\n*1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
        );
        // Nested on RESP2 as well, because the key name is already in front of
        // the pairs and there is nothing left to flatten into.
        assert_eq!(
            f.run(&[b"ZMPOP", b"1", b"z", b"MAX", b"COUNT", b"2"]),
            "*2\r\n$1\r\nz\r\n*2\r\n*2\r\n$1\r\nc\r\n$1\r\n3\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
        );
        // A null array and not a null, the same as LMPOP.
        assert_eq!(f.run(&[b"ZMPOP", b"1", b"nokey", b"MIN"]), "*-1\r\n");
        f.out = Out::new(Proto::Resp3);
        assert_eq!(f.run(&[b"ZMPOP", b"1", b"nokey", b"MIN"]), "_\r\n");
        f.out = Out::new(Proto::Resp2);
        let numkeys = "-ERR numkeys should be greater than 0\r\n";
        for bad in [
            &[b"ZMPOP".as_slice(), b"0", b"z", b"MIN"][..],
            &[b"ZMPOP", b"-1", b"z", b"MIN"],
            &[b"ZMPOP", b"x", b"z", b"MIN"],
        ] {
            assert_eq!(f.run(bad), numkeys, "{:?}", bad[1]);
        }
        let count = "-ERR count should be greater than 0\r\n";
        for bad in [
            &[b"ZMPOP".as_slice(), b"1", b"z", b"MIN", b"COUNT", b"0"][..],
            &[b"ZMPOP", b"1", b"z", b"MIN", b"COUNT", b"-1"],
            &[b"ZMPOP", b"1", b"z", b"MIN", b"COUNT", b"x"],
        ] {
            assert_eq!(f.run(bad), count, "{:?}", bad[5]);
        }
        let syntax = "-ERR syntax error\r\n";
        for bad in [
            // Two keys named and one given, so the word that should have been
            // the direction is a key and there is no direction left.
            &[b"ZMPOP".as_slice(), b"2", b"z", b"MIN"][..],
            &[b"ZMPOP", b"1", b"z", b"SIDEWAYS"],
            &[b"ZMPOP", b"1", b"z", b"MIN", b"junk"],
            &[b"ZMPOP", b"1", b"z", b"MIN", b"COUNT", b"1", b"junk"],
        ] {
            assert_eq!(f.run(bad), syntax, "{bad:?}");
        }
    }

    /// The three that wait, when there is something there and they do not have
    /// to. `BZPOPMIN` is the one reply in the group that is three flat elements.
    #[test]
    fn the_sorted_set_pops_that_wait_answer_like_the_ones_they_wrap() {
        let mut f = Fixture::new();
        f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
        assert_eq!(
            f.flow(&[b"BZPOPMIN", b"nokey", b"z", b"0"]),
            (
                Flow::Continue,
                "*3\r\n$1\r\nz\r\n$1\r\na\r\n$1\r\n1\r\n".to_owned()
            )
        );
        assert_eq!(
            f.run(&[b"BZPOPMAX", b"z", b"0"]),
            "*3\r\n$1\r\nz\r\n$1\r\nc\r\n$1\r\n3\r\n"
        );
        f.run(&[b"ZADD", b"z", b"1", b"a", b"3", b"c"]);
        assert_eq!(
            f.run(&[
                b"BZMPOP", b"0", b"2", b"nokey", b"z", b"MIN", b"COUNT", b"2"
            ]),
            "*2\r\n$1\r\nz\r\n*2\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
        );
        f.out = Out::new(Proto::Resp3);
        assert_eq!(
            f.run(&[b"BZPOPMIN", b"z", b"0"]),
            "*3\r\n$1\r\nz\r\n$1\r\nc\r\n,3\r\n"
        );
        f.out = Out::new(Proto::Resp2);
        // Nothing to take, so the client is parked and nothing was written.
        assert_eq!(
            f.flow(&[b"BZPOPMIN", b"z", b"0"]),
            (Flow::Block, String::new())
        );
        assert_eq!(
            f.flow(&[b"BZMPOP", b"0", b"1", b"z", b"MIN"]),
            (Flow::Block, String::new())
        );
        // The timeout is read before the key count, so this complains about the
        // timeout and not about the count.
        assert_eq!(
            f.run(&[b"BZMPOP", b"abc", b"0", b"z", b"MIN"]),
            "-ERR timeout is not a float or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"BZMPOP", b"0", b"0", b"z", b"MIN"]),
            "-ERR numkeys should be greater than 0\r\n"
        );
        assert_eq!(
            f.run(&[b"BZPOPMIN", b"z", b"-1"]),
            "-ERR timeout is negative\r\n"
        );
    }

    /// A parked sorted set client is served by whatever puts a member under one
    /// of its keys, and is not served by something of another type landing
    /// there.
    #[test]
    fn a_parked_sorted_set_client_waits_for_a_member_and_not_for_a_key() {
        let mut f = Fixture::new();
        assert_eq!(f.flow(&[b"BZPOPMIN", b"z", b"0"]).0, Flow::Block);
        assert_eq!(f.server.waiters().len(), 1);
        // A string under the key is not what it asked for, so it stays parked
        // rather than being handed a WRONGTYPE on a command that was accepted.
        f.run(&[b"SET", b"z", b"v"]);
        let mut out = Out::new(Proto::Resp2);
        assert!(!f.server.serve_waiter(0, 0, &mut out));
        assert!(out.as_slice().is_empty());
        f.run(&[b"DEL", b"z"]);
        f.run(&[b"ZADD", b"z", b"5", b"m"]);
        assert!(f.server.serve_waiter(0, 0, &mut out));
        assert_eq!(
            core::str::from_utf8(out.as_slice()).expect("ascii"),
            "*3\r\n$1\r\nz\r\n$1\r\nm\r\n$1\r\n5\r\n"
        );
        // And the member is gone, which is what makes a queue of workers on a
        // sorted set work at all.
        assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
    }

    #[test]
    fn every_sorted_set_command_says_wrongtype_and_writes_nothing() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"s", b"v"]);
        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
        for cmd in [
            &[b"ZADD".as_slice(), b"s", b"1", b"a"][..],
            &[b"ZINCRBY", b"s", b"1", b"a"],
            &[b"ZCARD", b"s"],
            &[b"ZSCORE", b"s", b"a"],
            &[b"ZMSCORE", b"s", b"a"],
            &[b"ZREM", b"s", b"a"],
            &[b"ZRANK", b"s", b"a"],
            &[b"ZREVRANK", b"s", b"a"],
            &[b"ZCOUNT", b"s", b"1", b"2"],
            &[b"ZLEXCOUNT", b"s", b"-", b"+"],
            &[b"ZRANGE", b"s", b"0", b"-1"],
            &[b"ZREVRANGE", b"s", b"0", b"-1"],
            &[b"ZRANGEBYSCORE", b"s", b"1", b"2"],
            &[b"ZREVRANGEBYSCORE", b"s", b"2", b"1"],
            &[b"ZRANGEBYLEX", b"s", b"-", b"+"],
            &[b"ZREVRANGEBYLEX", b"s", b"+", b"-"],
            &[b"ZRANGESTORE", b"d", b"s", b"0", b"-1"],
            &[b"ZREMRANGEBYRANK", b"s", b"0", b"-1"],
            &[b"ZREMRANGEBYSCORE", b"s", b"1", b"2"],
            &[b"ZREMRANGEBYLEX", b"s", b"-", b"+"],
            &[b"ZUNION", b"1", b"s"],
            &[b"ZINTER", b"1", b"s"],
            &[b"ZDIFF", b"1", b"s"],
            &[b"ZUNIONSTORE", b"d", b"1", b"s"],
            &[b"ZINTERSTORE", b"d", b"1", b"s"],
            &[b"ZDIFFSTORE", b"d", b"1", b"s"],
            &[b"ZINTERCARD", b"1", b"s"],
            &[b"ZRANDMEMBER", b"s"],
            &[b"ZSCAN", b"s", b"0"],
            &[b"ZPOPMIN", b"s"],
            &[b"ZPOPMAX", b"s", b"2"],
            &[b"ZMPOP", b"1", b"s", b"MIN"],
            &[b"BZPOPMIN", b"s", b"0"],
            &[b"BZPOPMAX", b"s", b"0"],
            &[b"BZMPOP", b"0", b"1", b"s", b"MIN"],
        ] {
            assert_eq!(f.run(cmd), wrong, "{:?}", cmd[0]);
        }
        assert_eq!(f.run(&[b"GET", b"s"]), "$1\r\nv\r\n");
    }

    /// The same churn the set, the string and the list get, because a sorted
    /// set that leaks a tree node per add looks exactly like one that does not
    /// until it has run for an afternoon.
    #[test]
    fn churning_sorted_sets_does_not_grow_the_server() {
        let mut f = Fixture::new();
        let members: Vec<Vec<u8>> = (0..200).map(|i| format!("m{i}").into_bytes()).collect();
        let scores: Vec<Vec<u8>> = (0..200).map(|i| format!("{i}").into_bytes()).collect();
        let mut args: Vec<&[u8]> = vec![b"ZADD", b"z"];
        for i in 0..200 {
            args.push(&scores[i]);
            args.push(&members[i]);
        }

        f.run(&args);
        f.run(&[b"DEL", b"z"]);
        f.server.compact_step();
        let after_first = f.server.memory_bytes();

        for _ in 0..200 {
            f.run(&args);
            f.run(&[b"DEL", b"z"]);
            f.server.compact_step();
        }
        assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
        assert!(
            f.server.memory_bytes() <= after_first * 2,
            "held {} after two hundred passes against {after_first} after one",
            f.server.memory_bytes()
        );
    }

    // ----------------------------------------------------------------- array

    #[test]
    fn an_array_writes_at_any_index_and_reads_back_what_it_sent() {
        let mut f = Fixture::new();
        // Three consecutive positions from a high index, and the reply is how
        // many of them were empty before rather than how many were written.
        assert_eq!(
            f.run(&[b"ARSET", b"a", b"1000", b"x", b"y", b"z"]),
            ":3\r\n"
        );
        assert_eq!(f.run(&[b"ARSET", b"a", b"1000", b"X", b"Y"]), ":0\r\n");
        assert_eq!(f.run(&[b"ARGET", b"a", b"1000"]), "$1\r\nX\r\n");
        assert_eq!(f.run(&[b"ARGET", b"a", b"1002"]), "$1\r\nz\r\n");
        // A hole and a key that is not there are the same answer.
        assert_eq!(f.run(&[b"ARGET", b"a", b"999"]), "$-1\r\n");
        assert_eq!(f.run(&[b"ARGET", b"nope", b"0"]), "$-1\r\n");
        assert_eq!(
            f.run(&[b"ARMGET", b"a", b"1002", b"999", b"1000"]),
            "*3\r\n$1\r\nz\r\n$-1\r\n$1\r\nX\r\n"
        );
        // Scattered pairs in one command, last write wins within it.
        assert_eq!(f.run(&[b"ARMSET", b"a", b"5", b"p", b"5", b"q"]), ":1\r\n");
        assert_eq!(f.run(&[b"ARGET", b"a", b"5"]), "$1\r\nq\r\n");
    }

    /// The two numbers an array reports are not the same number, and one of
    /// them does not fit a signed integer.
    #[test]
    fn the_length_is_the_high_water_mark_and_the_count_is_the_population() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"ARLEN", b"nope"]), ":0\r\n");
        assert_eq!(f.run(&[b"ARCOUNT", b"nope"]), ":0\r\n");
        f.run(&[b"ARMSET", b"a", b"0", b"x", b"9", b"y"]);
        assert_eq!(f.run(&[b"ARLEN", b"a"]), ":10\r\n");
        assert_eq!(f.run(&[b"ARCOUNT", b"a"]), ":2\r\n");
        // Deleting in the middle leaves the high water mark where it was.
        assert_eq!(f.run(&[b"ARDEL", b"a", b"0"]), ":1\r\n");
        assert_eq!(f.run(&[b"ARLEN", b"a"]), ":10\r\n");
        assert_eq!(f.run(&[b"ARCOUNT", b"a"]), ":1\r\n");

        // The top of the space is addressable, and its length is a number with
        // bit sixty three set, so the reply has to be unsigned or it comes back
        // negative.
        f.run(&[b"ARSET", b"top", b"18446744073709551614", b"z"]);
        assert_eq!(f.run(&[b"ARLEN", b"top"]), ":18446744073709551615\r\n");
        assert_eq!(f.run(&[b"ARCOUNT", b"top"]), ":1\r\n");
        // And one past it does not exist, so a write that would reach it fails
        // before any of it lands.
        assert_eq!(
            f.run(&[b"ARSET", b"over", b"18446744073709551614", b"a", b"b"]),
            "-ERR array index overflow\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"over"]), ":0\r\n");
    }

    /// One reply per position and not one per element, which is the whole
    /// reason the range is capped.
    #[test]
    fn a_range_read_answers_for_the_holes_too_and_is_capped_at_a_million() {
        let mut f = Fixture::new();
        f.run(&[b"ARSET", b"a", b"1", b"x"]);
        assert_eq!(
            f.run(&[b"ARGETRANGE", b"a", b"0", b"3"]),
            "*4\r\n$-1\r\n$1\r\nx\r\n$-1\r\n$-1\r\n"
        );
        // The two ends may come in either order, and the answer is reversed
        // rather than empty.
        assert_eq!(
            f.run(&[b"ARGETRANGE", b"a", b"3", b"0"]),
            "*4\r\n$-1\r\n$-1\r\n$1\r\nx\r\n$-1\r\n"
        );
        // A key that is not there reads like an array of nothing but holes.
        assert_eq!(
            f.run(&[b"ARGETRANGE", b"nope", b"0", b"1"]),
            "*2\r\n$-1\r\n$-1\r\n"
        );
        // A range wider than a million positions is refused and not trimmed,
        // because against a missing key it is a request for as many nulls as
        // the range is wide.
        assert_eq!(
            f.run(&[b"ARGETRANGE", b"nope", b"0", b"18446744073709551614"]),
            "-ERR range exceeds maximum of 1000000 items\r\n"
        );
    }

    /// Every index in the argument list is read before the key is touched, so
    /// a bad one at the end leaves nothing half written.
    #[test]
    fn a_bad_index_late_in_the_line_writes_none_of_the_earlier_ones() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"ARMSET", b"a", b"0", b"x", b"-1", b"y"]),
            "-ERR invalid array index\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"a"]), ":0\r\n");
        f.run(&[b"ARSET", b"a", b"0", b"x", b"y", b"z"]);
        assert_eq!(
            f.run(&[b"ARDEL", b"a", b"0", b"01"]),
            "-ERR invalid array index\r\n"
        );
        assert_eq!(f.run(&[b"ARCOUNT", b"a"]), ":3\r\n");
        // An index is unsigned here, so the numbers a list would take are not
        // the last element, they are errors.
        assert_eq!(
            f.run(&[b"ARGET", b"a", b"-1"]),
            "-ERR invalid array index\r\n"
        );
        // And a pair list with an odd tail is an arity error rather than a
        // syntax one.
        assert_eq!(
            f.run(&[b"ARMSET", b"a", b"0", b"x", b"1"]),
            "-ERR wrong number of arguments for 'armset' command\r\n"
        );
        assert_eq!(
            f.run(&[b"ARDELRANGE", b"a", b"0", b"1", b"2"]),
            "-ERR wrong number of arguments for 'ardelrange' command\r\n"
        );
    }

    #[test]
    fn a_range_delete_costs_the_elements_and_takes_the_key_when_it_empties() {
        let mut f = Fixture::new();
        f.run(&[b"ARSET", b"a", b"0", b"0", b"1", b"2", b"3", b"4"]);
        assert_eq!(f.run(&[b"ARDELRANGE", b"a", b"3", b"1"]), ":3\r\n");
        assert_eq!(f.run(&[b"ARCOUNT", b"a"]), ":2\r\n");
        // Two ranges in one command, and the second one covers the whole space
        // without walking it.
        assert_eq!(
            f.run(&[
                b"ARDELRANGE",
                b"a",
                b"100",
                b"200",
                b"0",
                b"18446744073709551614"
            ]),
            ":2\r\n"
        );
        assert_eq!(f.run(&[b"EXISTS", b"a"]), ":0\r\n");
        assert_eq!(f.run(&[b"ARDELRANGE", b"nope", b"0", b"1"]), ":0\r\n");
        assert_eq!(f.run(&[b"ARDEL", b"nope", b"0"]), ":0\r\n");
    }

    /// A value goes out as the bytes it came in as, whichever of the three ways
    /// the array found to store it.
    #[test]
    fn a_value_comes_back_byte_for_byte_however_it_was_packed() {
        let mut f = Fixture::new();
        let long = vec![b'v'; 200];
        f.run(&[
            b"ARMSET", b"a", b"0", b"42", b"1", b"007", b"2", b"3.5", b"3", b"3.14", b"4",
            b"short", b"5", &long, b"6", b"-0",
        ]);
        // 42 is an integer, 007 is not one because it does not print back the
        // same, 3.5 survives a double and 3.14 does not, and the last two are a
        // word packed string and a blob.
        assert_eq!(
            f.run(&[b"ARGETRANGE", b"a", b"0", b"6"]),
            format!(
                "*7\r\n$2\r\n42\r\n$3\r\n007\r\n$3\r\n3.5\r\n$4\r\n3.14\r\n$5\r\nshort\r\n$200\r\n{}\r\n$2\r\n-0\r\n",
                String::from_utf8_lossy(&long)
            )
        );
    }

    #[test]
    fn an_array_is_a_type_and_an_encoding_a_client_can_see() {
        let mut f = Fixture::new();
        f.run(&[b"ARSET", b"a", b"0", b"x"]);
        assert_eq!(f.run(&[b"TYPE", b"a"]), "+array\r\n");
        assert_eq!(
            f.run(&[b"OBJECT", b"ENCODING", b"a"]),
            "$12\r\nsliced-array\r\n"
        );
        // And it is a body like any other, so the key commands work on it.
        assert_eq!(f.run(&[b"EXPIRE", b"a", b"100"]), ":1\r\n");
        assert_eq!(f.run(&[b"PERSIST", b"a"]), ":1\r\n");
        assert_eq!(f.run(&[b"COPY", b"a", b"b"]), ":1\r\n");
        assert_eq!(f.run(&[b"ARGET", b"b", b"0"]), "$1\r\nx\r\n");
        assert_eq!(f.run(&[b"RENAME", b"a", b"c"]), "+OK\r\n");
        assert_eq!(f.run(&[b"ARCOUNT", b"c"]), ":1\r\n");
    }

    #[test]
    fn every_array_command_refuses_a_key_holding_something_else() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"s", b"v"]);
        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
        for cmd in [
            &[b"ARSET".as_ref(), b"s", b"0", b"x"][..],
            &[b"ARMSET".as_ref(), b"s", b"0", b"x"][..],
            &[b"ARGET".as_ref(), b"s", b"0"][..],
            &[b"ARMGET".as_ref(), b"s", b"0"][..],
            &[b"ARGETRANGE".as_ref(), b"s", b"0", b"1"][..],
            &[b"ARLEN".as_ref(), b"s"][..],
            &[b"ARCOUNT".as_ref(), b"s"][..],
            &[b"ARDEL".as_ref(), b"s", b"0"][..],
            &[b"ARDELRANGE".as_ref(), b"s", b"0", b"1"][..],
            &[b"ARINSERT".as_ref(), b"s", b"x"][..],
            &[b"ARRING".as_ref(), b"s", b"4", b"x"][..],
            &[b"ARNEXT".as_ref(), b"s"][..],
            &[b"ARSEEK".as_ref(), b"s", b"1"][..],
            &[b"ARLASTITEMS".as_ref(), b"s", b"1"][..],
            &[b"ARSCAN".as_ref(), b"s", b"0", b"1"][..],
            &[b"ARGREP".as_ref(), b"s", b"0", b"1", b"EXACT", b"v"][..],
            &[b"AROP".as_ref(), b"s", b"0", b"1", b"SUM"][..],
            &[b"ARINFO".as_ref(), b"s"][..],
        ] {
            assert_eq!(f.run(cmd), wrong, "{}", String::from_utf8_lossy(cmd[0]));
        }
    }

    /// Two of the array commands look the key up before they read the index and
    /// the rest read the index first, so the same broken argument gets two
    /// different errors depending on which command it went to.
    #[test]
    fn a_bad_index_reports_the_type_only_where_redis_reports_it() {
        let mut f = Fixture::new();
        f.run(&[b"SET", b"s", b"v"]);
        let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
        let bad = "-ERR invalid array index\r\n";
        assert_eq!(f.run(&[b"ARGET", b"s", b"-1"]), wrong);
        assert_eq!(f.run(&[b"ARMGET", b"s", b"0", b"-1"]), wrong);
        assert_eq!(f.run(&[b"ARSET", b"s", b"-1", b"x"]), bad);
        assert_eq!(f.run(&[b"ARDEL", b"s", b"-1"]), bad);
        assert_eq!(f.run(&[b"ARSCAN", b"s", b"-1", b"0"]), bad);
        assert_eq!(f.run(&[b"ARGREP", b"s", b"-1", b"0", b"EXACT", b"v"]), bad);
        // And on a key that is an array the index is just an index.
        f.run(&[b"ARSET", b"a", b"0", b"x"]);
        assert_eq!(f.run(&[b"ARGET", b"a", b"-1"]), bad);
        assert_eq!(f.run(&[b"ARGET", b"nope", b"-1"]), bad);
    }

    #[test]
    fn an_append_follows_a_cursor_the_client_can_move() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"ARNEXT", b"nope"]), ":0\r\n");
        assert_eq!(f.run(&[b"ARINSERT", b"a", b"x", b"y"]), ":1\r\n");
        assert_eq!(f.run(&[b"ARNEXT", b"a"]), ":2\r\n");
        assert_eq!(f.run(&[b"ARINSERT", b"a", b"z"]), ":2\r\n");
        assert_eq!(f.run(&[b"ARGET", b"a", b"2"]), "$1\r\nz\r\n");

        // A seek says where the next one goes, and a missing key has no cursor
        // to move and is not created by the asking.
        assert_eq!(f.run(&[b"ARSEEK", b"nope", b"5"]), ":0\r\n");
        assert_eq!(f.run(&[b"EXISTS", b"nope"]), ":0\r\n");
        assert_eq!(f.run(&[b"ARSEEK", b"a", b"100"]), ":1\r\n");
        assert_eq!(f.run(&[b"ARNEXT", b"a"]), ":100\r\n");
        assert_eq!(f.run(&[b"ARINSERT", b"a", b"far"]), ":100\r\n");
        assert_eq!(f.run(&[b"ARSEEK", b"a", b"0"]), ":1\r\n");
        assert_eq!(f.run(&[b"ARNEXT", b"a"]), ":0\r\n");

        // The top of the space is the one index only ARSEEK will take, and it
        // leaves the cursor with nowhere to go.
        assert_eq!(f.run(&[b"ARSEEK", b"a", b"18446744073709551615"]), ":1\r\n");
        assert_eq!(f.run(&[b"ARNEXT", b"a"]), "$-1\r\n");
        assert_eq!(
            f.run(&[b"ARINSERT", b"a", b"x"]),
            "-ERR insert index overflow\r\n"
        );
        assert_eq!(
            f.run(&[b"ARSET", b"a", b"18446744073709551615", b"x"]),
            "-ERR invalid array index\r\n"
        );
    }

    #[test]
    fn a_ring_keeps_the_newest_and_renumbers_them_when_it_is_resized() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"ARRING", b"r", b"3", b"a", b"b", b"c"]), ":2\r\n");
        assert_eq!(f.run(&[b"ARRING", b"r", b"3", b"d", b"e"]), ":1\r\n");
        assert_eq!(f.run(&[b"ARLEN", b"r"]), ":3\r\n");
        assert_eq!(
            f.run(&[b"ARGETRANGE", b"r", b"0", b"2"]),
            "*3\r\n$1\r\nd\r\n$1\r\ne\r\n$1\r\nc\r\n"
        );
        // Growing it after it has wrapped puts the survivors back in the order
        // they arrived, which is the whole point of paying for the rebuild.
        assert_eq!(f.run(&[b"ARRING", b"r", b"5", b"f"]), ":3\r\n");
        assert_eq!(
            f.run(&[b"ARGETRANGE", b"r", b"0", b"3"]),
            "*4\r\n$1\r\nc\r\n$1\r\nd\r\n$1\r\ne\r\n$1\r\nf\r\n"
        );
        // The size is read before the key, so a bad one is a bad size wherever
        // it is sent.
        assert_eq!(
            f.run(&[b"ARRING", b"r", b"0", b"x"]),
            "-ERR size must be positive\r\n"
        );
        assert_eq!(
            f.run(&[b"ARRING", b"r", b"big", b"x"]),
            "-ERR invalid size\r\n"
        );
    }

    #[test]
    fn the_last_items_walk_back_from_the_cursor_and_report_the_holes() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"ARLASTITEMS", b"nope", b"5"]), "*0\r\n");
        f.run(&[b"ARRING", b"r", b"4", b"a", b"b", b"c", b"d", b"e"]);
        assert_eq!(
            f.run(&[b"ARLASTITEMS", b"r", b"3"]),
            "*3\r\n$1\r\nc\r\n$1\r\nd\r\n$1\r\ne\r\n"
        );
        assert_eq!(
            f.run(&[b"ARLASTITEMS", b"r", b"3", b"rev"]),
            "*3\r\n$1\r\ne\r\n$1\r\nd\r\n$1\r\nc\r\n"
        );
        assert_eq!(
            f.run(&[b"ARLASTITEMS", b"r", b"99"]),
            "*4\r\n$1\r\nb\r\n$1\r\nc\r\n$1\r\nd\r\n$1\r\ne\r\n",
            "more than there is gets what there is"
        );
        // Nothing asked for is an empty reply, and Redis answers that before it
        // has read the option or looked at the key.
        assert_eq!(f.run(&[b"ARLASTITEMS", b"r", b"0", b"junk"]), "*0\r\n");
        assert_eq!(
            f.run(&[b"ARLASTITEMS", b"r", b"1", b"junk"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"ARLASTITEMS", b"r", b"nine"]),
            "-ERR invalid COUNT\r\n"
        );

        // With no cursor the tail of the array is the anchor, and a hole inside
        // the window is reported as one.
        f.run(&[b"ARMSET", b"h", b"0", b"x", b"2", b"z"]);
        assert_eq!(
            f.run(&[b"ARLASTITEMS", b"h", b"5"]),
            "*2\r\n$-1\r\n$1\r\nz\r\n"
        );
    }

    #[test]
    fn a_scan_answers_pairs_for_what_is_there_and_skips_what_is_not() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"ARSCAN", b"nope", b"0", b"10"]), "*0\r\n");
        f.run(&[b"ARMSET", b"a", b"0", b"x", b"7", b"y", b"1000000", b"z"]);
        // The whole index space, which ARGETRANGE refuses and this one answers
        // in three visits because holes cost nothing.
        assert_eq!(
            f.run(&[b"ARSCAN", b"a", b"0", b"18446744073709551614"]),
            "*3\r\n*2\r\n:0\r\n$1\r\nx\r\n*2\r\n:7\r\n$1\r\ny\r\n*2\r\n:1000000\r\n$1\r\nz\r\n"
        );
        assert_eq!(
            f.run(&[
                b"ARSCAN",
                b"a",
                b"18446744073709551614",
                b"0",
                b"LIMIT",
                b"1"
            ]),
            "*1\r\n*2\r\n:1000000\r\n$1\r\nz\r\n"
        );
        assert_eq!(f.run(&[b"ARSCAN", b"a", b"1", b"6"]), "*0\r\n");
        assert_eq!(
            f.run(&[b"ARSCAN", b"a", b"0", b"10", b"LIMIT", b"0"]),
            "-ERR LIMIT must be positive\r\n"
        );
        assert_eq!(
            f.run(&[b"ARSCAN", b"a", b"0", b"10", b"NOPE", b"1"]),
            "-ERR syntax error\r\n"
        );
        assert_eq!(
            f.run(&[b"ARSCAN", b"a", b"0", b"10", b"LIMIT"]),
            "-ERR wrong number of arguments for 'arscan' command\r\n"
        );
    }

    #[test]
    fn a_grep_answers_the_indexes_whose_elements_match() {
        let mut f = Fixture::new();
        assert_eq!(
            f.run(&[b"ARGREP", b"nope", b"0", b"10", b"EXACT", b"x"]),
            "*0\r\n"
        );
        f.run(&[b"ARSET", b"a", b"0", b"alpha", b"beta", b"gamma", b"ALPHA"]);

        // The two bounds take the ends of the array as well as an index, and a
        // reversed range is walked backwards the way ARSCAN walks one.
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"-", b"+", b"GLOB", b"*a"]),
            "*3\r\n:0\r\n:1\r\n:2\r\n"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"+", b"-", b"GLOB", b"*a"]),
            "*3\r\n:2\r\n:1\r\n:0\r\n"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"1", b"2", b"GLOB", b"*a"]),
            "*2\r\n:1\r\n:2\r\n"
        );

        // One test each. NOCASE reaches all four of them and it may be written
        // after the pattern it applies to.
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"-", b"+", b"EXACT", b"alpha"]),
            "*1\r\n:0\r\n"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"-", b"+", b"EXACT", b"alpha", b"NOCASE"]),
            "*2\r\n:0\r\n:3\r\n"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"-", b"+", b"MATCH", b"mm"]),
            "*1\r\n:2\r\n"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"-", b"+", b"RE", b"^[bg]"]),
            "*2\r\n:1\r\n:2\r\n"
        );

        // OR is the default and AND has to be asked for, and either way the
        // last of a repeated option wins.
        let both: &[&[u8]] = &[
            b"ARGREP", b"a", b"-", b"+", b"EXACT", b"beta", b"MATCH", b"al",
        ];
        assert_eq!(f.run(both), "*2\r\n:0\r\n:1\r\n");
        assert_eq!(
            f.run(&[
                b"ARGREP", b"a", b"-", b"+", b"EXACT", b"beta", b"MATCH", b"al", b"AND"
            ]),
            "*0\r\n"
        );
        assert_eq!(
            f.run(&[
                b"ARGREP", b"a", b"-", b"+", b"EXACT", b"beta", b"MATCH", b"al", b"AND", b"OR"
            ]),
            "*2\r\n:0\r\n:1\r\n"
        );

        // WITHVALUES turns each hit into a pair, and LIMIT counts the hits and
        // not the positions it had to look at.
        assert_eq!(
            f.run(&[
                b"ARGREP",
                b"a",
                b"-",
                b"+",
                b"MATCH",
                b"a",
                b"WITHVALUES",
                b"LIMIT",
                b"2"
            ]),
            "*2\r\n*2\r\n:0\r\n$5\r\nalpha\r\n*2\r\n:1\r\n$4\r\nbeta\r\n"
        );
        assert_eq!(
            f.run(&[
                b"ARGREP", b"a", b"-", b"+", b"EXACT", b"ALPHA", b"LIMIT", b"1"
            ]),
            "*1\r\n:3\r\n"
        );
    }

    /// Everything ARGREP refuses, in the order it refuses it.
    #[test]
    fn a_grep_reports_a_broken_command_the_way_redis_does() {
        let mut f = Fixture::new();
        f.run(&[b"ARSET", b"a", b"0", b"alpha"]);
        let syntax = "-ERR syntax error\r\n";

        // The bounds are read before the plan, so a bad index beats a bad
        // predicate whichever way round the two are written.
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"-1", b"0", b"NOPE", b"x"]),
            "-ERR invalid array index\r\n"
        );
        assert_eq!(f.run(&[b"ARGREP", b"a", b"0", b"1", b"NOPE", b"x"]), syntax);
        // A keyword with nothing after it, and a command that asks for nothing.
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"0", b"1", b"NOCASE", b"EXACT"]),
            syntax
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"0", b"1", b"EXACT", b"x", b"LIMIT"]),
            syntax
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"0", b"1", b"NOCASE", b"WITHVALUES"]),
            syntax,
            "a command with no predicate in it at all"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"0", b"1", b"EXACT", b"x", b"LIMIT", b"0"]),
            "-ERR LIMIT must be positive\r\n"
        );
        assert_eq!(
            f.run(&[
                b"ARGREP", b"a", b"0", b"1", b"EXACT", b"x", b"LIMIT", b"nine"
            ]),
            "-ERR value is not an integer or out of range\r\n"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"0", b"1", b"RE", b""]),
            "-ERR regular expression is empty\r\n"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"0", b"1", b"RE", b"(a"]),
            "-ERR invalid regular expression: Missing ')'\r\n"
        );
        assert_eq!(
            f.run(&[b"ARGREP", b"a", b"0", b"1", b"RE", br"(a)\1"]),
            "-ERR regular expression backreferences are not supported\r\n"
        );
        // The arity is minus six, so a predicate keyword with no pattern after
        // it is short by one and never reaches the parser.
        let arity = "-ERR wrong number of arguments for 'argrep' command\r\n";
        assert_eq!(f.run(&[b"ARGREP", b"a", b"0", b"1", b"EXACT"]), arity);
        assert_eq!(f.run(&[b"ARGREP", b"a", b"0", b"1"]), arity);
    }

    #[test]
    fn an_op_reduces_a_range_to_one_number() {
        let mut f = Fixture::new();
        f.run(&[b"ARSET", b"a", b"0", b"1", b"2.5", b"word", b"-4"]);
        assert_eq!(
            f.run(&[b"AROP", b"a", b"0", b"10", b"SUM"]),
            "$4\r\n-0.5\r\n"
        );
        assert_eq!(f.run(&[b"AROP", b"a", b"0", b"10", b"min"]), "$2\r\n-4\r\n");
        assert_eq!(
            f.run(&[b"AROP", b"a", b"0", b"10", b"MAX"]),
            "$3\r\n2.5\r\n"
        );
        assert_eq!(f.run(&[b"AROP", b"a", b"0", b"10", b"USED"]), ":4\r\n");
        assert_eq!(
            f.run(&[b"AROP", b"a", b"0", b"10", b"MATCH", b"word"]),
            ":1\r\n"
        );
        // An aggregate is written with seventeen significant digits, which is
        // Redis's own choice and not what a score comes back as.
        f.run(&[b"ARSET", b"t", b"0", b"0.1", b"0.2"]);
        assert_eq!(
            f.run(&[b"AROP", b"t", b"0", b"10", b"SUM"]),
            "$19\r\n0.30000000000000004\r\n"
        );
        assert_eq!(f.run(&[b"ZADD", b"z", b"0.3", b"m"]), ":1\r\n");
        assert_eq!(f.run(&[b"ZSCORE", b"z", b"m"]), "$3\r\n0.3\r\n");

        // Nothing to work with is a null, and a missing key is a null for the
        // aggregates and a zero for the two that count.
        f.run(&[b"ARSET", b"w", b"0", b"word"]);
        assert_eq!(f.run(&[b"AROP", b"w", b"0", b"10", b"SUM"]), "$-1\r\n");
        assert_eq!(f.run(&[b"AROP", b"nope", b"0", b"10", b"SUM"]), "$-1\r\n");
        assert_eq!(f.run(&[b"AROP", b"nope", b"0", b"10", b"USED"]), ":0\r\n");

        assert_eq!(
            f.run(&[b"AROP", b"a", b"0", b"10", b"NOPE"]),
            "-ERR unknown operation\r\n"
        );
        assert_eq!(
            f.run(&[b"AROP", b"a", b"0", b"10", b"MATCH"]),
            "-ERR MATCH requires a value argument\r\n"
        );
        assert_eq!(
            f.run(&[b"AROP", b"a", b"0", b"10", b"SUM", b"extra"]),
            "-ERR wrong number of arguments for 'arop' command\r\n"
        );
    }

    #[test]
    fn the_info_is_a_map_and_a_missing_key_is_an_error() {
        let mut f = Fixture::new();
        assert_eq!(f.run(&[b"ARINFO", b"nope"]), "-ERR no such key\r\n");
        f.run(&[b"ARINSERT", b"a", b"x", b"y"]);
        let short = f.run(&[b"ARINFO", b"a"]);
        assert!(
            short.starts_with("*14\r\n"),
            "seven pairs on RESP2: {short}"
        );
        assert!(short.contains("$5\r\ncount\r\n:2\r\n"), "{short}");
        assert!(
            short.contains("$17\r\nnext-insert-index\r\n:2\r\n"),
            "{short}"
        );
        assert!(short.contains("$10\r\nslice-size\r\n:4096\r\n"), "{short}");
        let full = f.run(&[b"ARINFO", b"a", b"full"]);
        assert!(full.starts_with("*24\r\n"), "twelve pairs: {full}");
        // Two values one apart are held sparsely, so the dense count is zero and
        // the two dense averages have nothing to average.
        assert!(full.contains("$12\r\ndense-slices\r\n:0\r\n"), "{full}");
        assert!(full.contains("$13\r\nsparse-slices\r\n:1\r\n"), "{full}");
        assert!(
            full.contains("$14\r\navg-dense-size\r\n$1\r\n0\r\n"),
            "{full}"
        );
        assert_eq!(f.run(&[b"ARINFO", b"a", b"nope"]), "-ERR syntax error\r\n");

        // On RESP3 the same reply is a map and the averages are doubles.
        let mut g = Fixture::new();
        g.run(&[b"HELLO", b"3"]);
        g.run(&[b"ARINSERT", b"a", b"x"]);
        let map = g.run(&[b"ARINFO", b"a", b"FULL"]);
        assert!(map.starts_with("%12\r\n"), "{map}");
        assert!(map.contains("$5\r\ncount\r\n:1\r\n"), "{map}");
        assert!(map.contains("$14\r\navg-dense-size\r\n,0\r\n"), "{map}");
    }

    #[test]
    fn a_double_on_the_wire_is_written_the_way_redis_writes_one() {
        let mut f = Fixture::new();
        // Whole numbers up to two to the sixty second come back as integers,
        // and past that the digit generator takes over and uses an exponent.
        for (score, want) in [
            ("3", "3"),
            ("3.5", "3.5"),
            ("0.3", "0.3"),
            ("1e30", "1e+30"),
            ("1e19", "1e+19"),
            ("1e-7", "1e-7"),
            ("0.000001", "0.000001"),
            ("4611686018427387904", "4611686018427387904"),
            ("-0", "-0"),
        ] {
            f.run(&[b"ZADD", b"z", score.as_bytes(), b"m"]);
            assert_eq!(
                f.run(&[b"ZSCORE", b"z", b"m"]),
                format!("${}\r\n{want}\r\n", want.len()),
                "score {score}"
            );
        }

        // The same bytes on RESP3, where the reply is a double rather than a
        // bulk string.
        let mut g = Fixture::new();
        g.run(&[b"HELLO", b"3"]);
        g.run(&[b"ZADD", b"z", b"1e30", b"m"]);
        assert_eq!(g.run(&[b"ZSCORE", b"z", b"m"]), ",1e+30\r\n");
        // The two float increments are not this printer. They go through
        // ld2string in its human mode, which is a fixed point conversion with
        // the trailing zeros taken off, so they never write an exponent, and
        // they reply with a bulk string on both protocols.
        assert_eq!(
            g.run(&[b"INCRBYFLOAT", b"s", b"1e30"]),
            "$31\r\n1000000000000000000000000000000\r\n"
        );
        assert_eq!(g.run(&[b"INCRBYFLOAT", b"t", b"0.1"]), "$3\r\n0.1\r\n");
        assert_eq!(
            g.run(&[b"HINCRBYFLOAT", b"h", b"f", b"1e19"]),
            "$20\r\n10000000000000000000\r\n"
        );
    }
}