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
//! The diagram: an ordered set of shapes, drawable into a sink the caller gives it. See
//! [`docs/diagram-model.md`](../../../docs/diagram-model.md).
//!
//! **The window is the caller's and the order is this crate's.** A buffer is a window with an
//! origin and a size, and stamping outside it does nothing, so somebody has to choose that window
//! and the question hides two: how much the diagram occupies, which is the diagram's to answer, and
//! which part of it is wanted, which is the caller's by nature — a terminal draws what fits at the
//! scroll position it is at, and no measurement of the content answers that. Since each kind answers
//! its own sides or answers none at all, the diagram holds nothing it could measure itself from even
//! if it were asked, so [`draw`](Diagram::draw) takes the window it is given.
//!
//! Within that window the shapes are drawn **front to back**, each stamped with `Below`, which is
//! the order that can stop early because a fully decided cell can no longer change. The other
//! direction is available and produces the same buffer; what it carries is not appearance but
//! ownership, because which figure reaches a position first is what decides the cell it decides.
use std::num::NonZeroU16;
use monospace_core::{FigureLayer, ShapeId, StampMode, StampSink};
use rpds::{HashTrieMapSync, VectorSync};
use crate::Shape;
use crate::utilities::{swapped, without};
/// A diagram: an ordered set of shapes, and nothing else — no buffer, no glyph catalog, no
/// rendered picture.
///
/// **The figures are held apart from the order that draws them.** A [`HashTrieMapSync`] from an
/// identity to a figure says which figure answers to a name, and a [`VectorSync`] of identities says
/// which of them draws first; neither says anything the other cannot, and a caller naming a shape
/// almost always means the first while rendering means the second. **The two are always written
/// together and they always agree**: one identity stands once in the order and names one figure, so
/// a lookup names a figure and the drawing walks the order alone.
///
/// **They are `Sync` and not the cheaper default, and the reason is a caller that does not exist
/// yet.** `rpds` ships a twin of each of its structures, and the only difference in memory is none
/// at all — a node is the same width either way — so the whole of what `Sync` costs is one atomic
/// refcount per node touched, measured at about 1% of what a command costs this crate's caller
/// pays. What it buys is that a diagram stays `Send`, and `docs/memory-cost.md` §8 names the
/// decision that would turn `!Send` from a cost into a blocker: rendering on a background thread.
///
/// **It is `Clone`, because a diagram is a value and copying one is sharing, not duplicating.** A
/// copy shares every figure and every place in the order with the original, so a copy is held,
/// drawn, changed and dropped without the first knowing it exists, and dropping it frees nothing
/// the original holds. **That is what a value buys and it is not a caveat to it:** nothing inside a
/// diagram refers to anything outside it, and nothing that is reachable by reference before this is
/// by alias after it.
///
/// The copy answers `add` with the ordinal the original would have answered, which is what keeps
/// two copies from handing out one identity. They are then two diagrams that both hold shapes under
/// identities that may coincide, and `add_under` already says what one of them does to the figure
/// already there.
///
/// It is `Clone` and not `Copy`: a diagram is as likely to be as long as it is wide, and sharing one
/// is a decision rather than a default.
#[derive(Clone)]
pub struct Diagram {
/// The figures this diagram holds, each under the identity it was added with. A figure is here
/// exactly once whatever place the order gives it, so two `add_under` calls carrying one
/// identity leave one figure and not two.
shapes: HashTrieMapSync<ShapeId, Shape>,
/// The order the shapes draw in, written as the identities themselves. The **last** element is
/// the front of the order: it is drawn first and decides a shared cell before anything behind
/// it. Nothing here says which figure a name belongs to — that is the map's, and every read of
/// this goes through it.
order: VectorSync<ShapeId>,
/// The ordinal the next `add` takes. It is the ordinal itself rather than the last one issued,
/// so seeding it is a plain assignment and no public method carries a subtraction. It is a
/// [`NonZeroU16`] rather than a `u16` because zero is not an identity, so a counter that could
/// stand at one would be a counter that could hand back nothing to name.
next_id: NonZeroU16,
}
impl Default for Diagram {
/// An empty diagram whose next `add` takes `1`, which is what `new` hands a caller with no
/// opinion. Written out rather than derived because a derived `Default` would leave `next_id` at
/// the `0` a zeroed field gives, and this slice changed what that field means.
fn default() -> Self {
Self {
shapes: HashTrieMapSync::new_sync(),
order: VectorSync::new_sync(),
next_id: NonZeroU16::MIN,
}
}
}
impl Diagram {
/// An empty diagram, holding no shapes, whose first addition is handed `1`.
#[must_use]
pub fn new() -> Self {
Self::numbered_from(NonZeroU16::MIN)
}
/// An empty diagram whose next `add` takes the first ordinal at or after `next_id` that names no
/// figure.
///
/// **The ordinal is a [`NonZeroU16`], so a zero is refused here rather than by `add`.** A
/// description saying `"next_id": 0` is turned away by the reader rather than seeded with an
/// identity nothing can carry, and there is no path through this crate that produces the `0` a
/// plain `u16` would have allowed.
///
/// **The ordinal it is given is not the ordinal the next addition gets**, and the difference is
/// the whole of what a stale value costs: a description whose second entry was deleted resumes
/// at `2` and steps over it to `3`.
#[must_use]
pub fn numbered_from(next_id: NonZeroU16) -> Self {
Self {
shapes: HashTrieMapSync::new_sync(),
order: VectorSync::new_sync(),
next_id,
}
}
/// Puts `shape` at the front of the order, in front of everything already there, and returns
/// the identity the diagram gave it.
///
/// **The ordinal is one no figure is already under, and the counter steps over anything that is.**
/// The counter is trusted rather than checked, so a diagram numbered from 3 by a description
/// whose third entry was deleted issues `3` to whatever comes next and takes the caller's figure
/// with it: the issued figure would be unreachable by identity and the caller's would be drawn,
/// which is the outcome §3 _Identity_ says a diagram that hands out an ordinal a figure already
/// sits under has not kept. **Replacing it is not the other answer** — a figure that vanishes
/// with no error, no report and no way back is the one outcome nothing in this crate does — so
/// the counter steps over every ordinal already taken and issues the first free one after it.
///
/// **This is the one operation that searches the figures**, and it searches them for an ordinal
/// rather than for a figure: what it asks is whether anything is held under the ordinal it is
/// about to issue, which the map answers without walking anything. A caller that never writes an
/// identity of its own never pays for it — the counter's own ordinals are consecutive, so the
/// first lookup misses and the addition is O(log n) rather than a scan.
///
/// **The counter is advanced past the ordinal it issued, and stops there when there is nowhere
/// to go.** A `u16` has no ordinal after `u16::MAX`, so the counter stands where it is rather
/// than wrapping — under the previous `+= 1` a release build would have wrapped into the `0` a
/// plain `u16` allows in silence, and `0` is the one value this crate's own identity type
/// cannot carry. **The refusal belongs to the next `add` rather than to this one**: the ordinal
/// just issued is free and this figure is named under it, and the addition after it is the one
/// with nothing to hand out.
///
/// **The pair is in that order because the identity is the reason for the call.** A caller that
/// had to look the identity up would be asking a question this diagram has just answered by
/// construction, and deriving it from the counter instead would publish a private field.
///
/// # Panics
///
/// When every ordinal at or after the counter is already taken, [`u16::MAX`] among them. A
/// `u16` ends there and nothing here reports what could not be drawn.
#[must_use]
pub fn add(&self, shape: Shape) -> (Self, ShapeId) {
let mut ordinal = self.next_id;
while self.shapes.contains_key(&ShapeId::new(ordinal)) {
ordinal = ordinal.checked_add(1).unwrap_or_else(|| {
let taken = ShapeId::new(ordinal);
panic!("a diagram has no ordinal left to issue: a u16 ends at {taken}")
});
}
let id = ShapeId::new(ordinal);
let next_id = ordinal.checked_add(1).unwrap_or(ordinal);
let next = Self {
shapes: self.shapes.insert(id, shape),
order: self.order.push_back(id),
next_id,
};
(next, id)
}
/// Puts `shape` at the front of the order, under the identity `id`.
///
/// `add` with the caller's identity in place of the diagram's, and it hands back nothing. It
/// does **not** touch the counter, so on a diagram numbered from 3 the next `add` is still handed
/// `4` whatever a caller writes here.
///
/// **A figure already held under `id` is replaced by this one, in the place it already had.**
/// One identity names one figure and one place in the order, so putting a second shape under a
/// name this diagram already carries is a change to what that name is rather than a second
/// entry: the map holds one figure per identity and the order is left alone, so the diagram
/// draws the identity once rather than twice.
///
/// **A refusal would be worse than the replacement.** This crate reports nothing anywhere, so
/// refusing in silence is a figure the caller asked for and did not get, with no way to tell it
/// from a figure that was never added.
#[must_use]
pub fn add_under(&self, id: ShapeId, shape: Shape) -> Self {
let already_held = self.order.iter().any(|held| *held == id);
Self {
shapes: self.shapes.insert(id, shape),
order: if already_held {
self.order.clone()
} else {
self.order.push_back(id)
},
next_id: self.next_id,
}
}
/// The place in the order the shape named by `id` stands, or `None` when this diagram holds
/// no such shape.
///
/// **The search every order question goes through, and it is a scan of the order rather than of
/// the figures**: which place an identity stands in is a question about the order, and the map
/// answers no position at all. `add_under`'s check is one comparison rather than a search
/// because it needs to know *whether* the identity stands in the order and not *where*.
///
/// `ShapeId`s are compared by value, so an identity issued by another diagram is a well-formed
/// value that matches nothing here — the same answer the model's _Positions_ gives a reference
/// to a shape that is not there.
fn find(&self, id: ShapeId) -> Option<usize> {
self.order.iter().position(|held| *held == id)
}
/// The place the shape named by `id` stands in the order, counting from zero at the back, or
/// `None` when this diagram holds no such shape.
///
/// **The read the order row asks for.** The place a person sees is this plus one, and the total
/// is [`shape_count`](Self::shape_count); the pair is what turns an index into
/// `Position: k of N`. The search is `find`'s, and the answer is the index rather than the
/// figure, so nothing about the figure is copied to report where it sits.
#[must_use]
pub fn place_of(&self, id: ShapeId) -> Option<usize> {
self.find(id)
}
/// Where `id` stands, when [`forward`](Self::forward) would move it.
///
/// **The one place the rule is written**: a figure this diagram does not hold and one already at
/// the front are the same answer, `None`, because neither would move.
fn place_to_forward(&self, id: ShapeId) -> Option<usize> {
self.find(id).filter(|index| index + 1 < self.order.len())
}
/// Where `id` stands, when [`backward`](Self::backward) would move it.
///
/// **The mirror of `place_to_forward`, at the other end.** A figure this diagram does not hold
/// and one already at the back are the same answer, `None`, because neither would move.
fn place_to_backward(&self, id: ShapeId) -> Option<usize> {
self.find(id).filter(|index| *index > 0)
}
/// Moves the shape named by `id` one place toward the front of the order. Does nothing when
/// `id` names no shape here, or when it is already the front-most.
#[must_use]
pub fn forward(&self, id: ShapeId) -> Self {
let Some(index) = self.place_to_forward(id) else {
return self.clone();
};
Self {
shapes: self.shapes.clone(),
order: swapped(&self.order, index, index + 1),
next_id: self.next_id,
}
}
/// Moves the shape named by `id` one place toward the back of the order. Does nothing when
/// `id` names no shape here, or when it is already the back-most.
#[must_use]
pub fn backward(&self, id: ShapeId) -> Self {
let Some(index) = self.place_to_backward(id) else {
return self.clone();
};
Self {
shapes: self.shapes.clone(),
order: swapped(&self.order, index, index - 1),
next_id: self.next_id,
}
}
/// Whether [`forward`](Self::forward) would move the shape `id` names: it is here, and it is not in
/// front of everything else already.
///
/// **Answerable without carrying it out**, as `Session::can_undo` is, and it is the same rule
/// `forward` guards itself with — written once in `place_to_forward` and read from both sides.
/// `Command::Forward` is what asks it (#285): a figure already at the front changes nothing, and a
/// command that changes nothing records no step.
#[must_use]
pub fn can_forward(&self, id: ShapeId) -> bool {
self.place_to_forward(id).is_some()
}
/// Whether [`backward`](Self::backward) would move the shape `id` names: it is here, and it is
/// not behind everything else already.
///
/// **Answerable without carrying it out**, as `can_forward` is, and it is the same rule
/// `backward` guards itself with — written once in `place_to_backward` and read from both sides.
/// `Command::Backward` and `Command::ToBack` ask it (#285): a figure already at the back changes
/// nothing, and a command that changes nothing records no step.
#[must_use]
pub fn can_backward(&self, id: ShapeId) -> bool {
self.place_to_backward(id).is_some()
}
/// Moves the shape named by `id` to the front of the order. Does nothing when `id` names no
/// shape here, or when it is already the front-most.
///
/// **One change rather than a walk.** The figure leaves the place it stood and is appended once,
/// so `Home` is one command and one step in the session's history (D2 of #305). A loop of
/// [`forward`](Self::forward) would record one step per place crossed.
///
/// **The guard is `place_of`, not `without`.** `without` on an identity the order does not hold
/// answers the same order, and appending it afterwards would insert a name the diagram never
/// held; asking `place_of` first is what keeps a missing figure silent.
#[must_use]
pub fn to_front(&self, id: ShapeId) -> Self {
if self.place_of(id).is_none() {
return self.clone();
}
Self {
shapes: self.shapes.clone(),
order: without(&self.order, &id).push_back(id),
next_id: self.next_id,
}
}
/// Moves the shape named by `id` to the back of the order. Does nothing when `id` names no
/// shape here, or when it is already the back-most.
///
/// **The mirror of [`to_front`](Self::to_front)**, and the same single change: the identity goes
/// first and every other place keeps the order it had. `rpds` has no `push_front`, so the new
/// sequence is built from the identity and the sequence without it.
#[must_use]
pub fn to_back(&self, id: ShapeId) -> Self {
if self.place_of(id).is_none() {
return self.clone();
}
Self {
shapes: self.shapes.clone(),
order: std::iter::once(id)
.chain(without(&self.order, &id).iter().copied())
.collect(),
next_id: self.next_id,
}
}
/// The figure named by `id`, or `None` when this diagram holds no such shape.
///
/// It borrows, and there is no `cloned()` beside it. What comes back is the bare figure the
/// caller added, with the identity and the place in the order held here in the diagram rather
/// than inside the figure, so nothing about what is returned says where it sits.
#[must_use]
pub fn get(&self, id: ShapeId) -> Option<&Shape> {
self.shapes.get(&id)
}
/// The shapes in this diagram, in drawing order from back to front, paired with their identities.
///
/// The iterator yields pairs of `(ShapeId, &Shape)` in the order shapes are added, which is the
/// drawing order that serializing and description formats read back.
pub fn shapes(&self) -> impl Iterator<Item = (ShapeId, &Shape)> {
self.order
.iter()
.filter_map(|id| self.shapes.get(id).map(|shape| (*id, shape)))
}
/// How many figures this diagram holds.
///
/// **The order is the count**, because the two are written together and always agree: one
/// identity stands once in the order and names one figure. Counting the map instead would be a
/// second answer to a question the order already answers.
#[must_use]
pub fn shape_count(&self) -> usize {
self.order.len()
}
/// The ordinal the next shape added takes.
#[must_use]
pub fn next_id(&self) -> NonZeroU16 {
self.next_id
}
/// Takes the shape named by `id` out of the diagram, and freezes what hung from it.
///
/// **Every position carrying a reference to the removed shape becomes the absolute point it was
/// resolving to at that moment, and nothing else changes.** A reference naming **another** shape
/// is left exactly as it was, and so is one naming an identity this diagram never held — a
/// broken reference the removal did not create and does not repair. §4 _Positions_ states the
/// rule and §4 is where a reader is sent for it; a frozen end is a `Position::Absolute` like
/// any other and there is no new name for it.
///
/// So what hung from the removed shape stays drawn exactly where it stood rather than being
/// re-routed, dropped or repaired. Nothing goes looking for the reference afterwards: a figure
/// put back under the removed identity leaves the arrow where it was rather than hanging from
/// it again.
///
/// An identity this diagram does not hold changes nothing, with no error, no report and no
/// panic, which is the same answer the model's _Positions_ gives a reference to a shape that is
/// not there. **What it hands back is a diagram equal to the one it was given**, sharing every
/// figure with it: there is no history and nothing to undo, so putting a figure back means
/// building it again. The counter is not touched either, so an identity is never handed out a
/// second time and a put-back is `add_under` with the identity the caller kept.
///
/// **The identity leaves the order everywhere it stood, not once.** An identity stands in the
/// order exactly once, so this is one place here rather than a search for every place it might
/// stand; `without` is written the other way because the sequence a caller reads is not this
/// one.
#[must_use]
pub fn remove(&self, id: ShapeId) -> Self {
if !self.shapes.contains_key(&id) {
return self.clone();
}
// The freezing is a fold rather than a loop over a mutable copy: every write is an
// `insert` handing back a map, so nothing here is written into either. The fold is over the
// **figures**, not over the order, because a figure is rewritten whatever place the order
// gives it and the order says nothing about what a figure refers to.
let shapes = (&self.shapes).into_iter().fold(
self.shapes.clone(),
|shapes, (held, shape)| match shape.with_frozen_references(id, self) {
Some(frozen) => shapes.insert(*held, frozen),
None => shapes,
},
);
Self {
shapes: shapes.remove(&id),
order: without(&self.order, &id),
next_id: self.next_id,
}
}
/// Puts `shape` where the shape named by `id` stands, in the same place in the order.
///
/// The identity and the place in the order survive, and everything the previous figure owned
/// is the new figure's: its kind, its parameters and its position. The diagram never reaches
/// into a box and widens it, and a replacement may change the kind outright, a box becoming a
/// line, with nothing of the previous figure surviving it.
///
/// An identity this diagram does not hold changes nothing, and the shape handed in is not
/// added either — the replacement is written into the map **only where an identity is already
/// there**, so there is still no way to name a shape into existence. What it hands back is a
/// diagram equal to the one it was given, and it takes the shape by value for the reason
/// [`Diagram::remove`] does.
#[must_use]
pub fn replace(&self, id: ShapeId, shape: Shape) -> Self {
if !self.shapes.contains_key(&id) {
return self.clone();
}
Self {
shapes: self.shapes.insert(id, shape),
order: self.order.clone(),
next_id: self.next_id,
}
}
/// Draws every shape into `sink`, front to back, stamping every cell with
/// [`StampMode::Below`] and **binding the shape's own identity** to each layer. Drawing changes
/// nothing about this diagram, so two drawings into equal windows produce equal drawings.
///
/// The diagram is what a connector's endpoints resolve through, which is why it is the one that
/// hands itself to each figure. A connector with an endpoint that does not resolve — an identity
/// this diagram does not hold, or a kind that answers no such anchor — is **not drawn at all**,
/// and every other shape draws exactly what it drew. There is no error, no report and no way
/// to ask which figures were dropped; see
/// [#88](https://github.com/andresmoschini/monospace/issues/88).
///
/// **The identity is not a parameter of the signature.** Whoever draws a diagram already holds
/// every shape's identity and knows which is which, so asking for it again would be asking a
/// question this method is the only one able to answer — and a caller that passed one in could
/// pass one that disagrees with the diagram. The record is a property of the drawing rather than
/// of the diagram, which is why changing the diagram changes nothing about a buffer already
/// drawn.
pub fn draw(&self, sink: &mut dyn StampSink) {
for id in self.order.iter().rev() {
// **Every place in the order names a figure, and the guard is here rather than a panic
// because the two are written together and nothing reaches into either.** It would not
// fire: `add` and `add_under` write a figure and a place at once, and `remove` takes both
// out.
let Some(shape) = self.shapes.get(id) else {
continue;
};
let mut layer = FigureLayer::stamped_by(&mut *sink, StampMode::Below, *id);
shape.draw(&mut layer, self);
}
}
}
#[cfg(test)]
mod tests {
use std::num::NonZeroU16;
use monospace_core::{
BoxShape, Buffer, Cell, CellReader, Connector, Direction, FigureLayer, Footprint,
FootprintSink, Glyph, GlyphCatalog, Line, Orientation, OwnerReader, Pos,
Shape as CoreShape, Size, StampMode, Stroke, Terminal, Window, render,
};
use super::{Diagram, ShapeId};
use crate::{Anchor, Delta, Endpoint, EndpointAt, Position, Reference, Shape};
fn light() -> Stroke {
Stroke::from("light")
}
/// The ordinal `ordinal`, which is what a diagram is seeded with.
fn nz(ordinal: u16) -> NonZeroU16 {
NonZeroU16::new(ordinal).expect("no test seeds a counter at zero")
}
/// An identity of the ordinal `ordinal`, which is how every test below names one.
fn identity(ordinal: u16) -> ShapeId {
ShapeId::new(nz(ordinal))
}
/// Collects every cell of `buffer` over its window, so two buffers can be compared by value
/// even though `Buffer` derives no `PartialEq`.
fn cells(buffer: &Buffer) -> Vec<Option<Cell>> {
let Window { origin, size } = buffer.window();
(0..size.height)
.flat_map(|dy| (0..size.width).map(move |dx| (dx, dy)))
.map(|(dx, dy)| {
let at = Pos {
x: origin.x + i16::try_from(dx).expect("width fits i16"),
y: origin.y + i16::try_from(dy).expect("height fits i16"),
};
buffer.cell(at).cloned()
})
.collect()
}
/// A diagram holding a box and a line, drawn twice into equal
/// windows, produces equal buffers.
#[test]
fn drawing_the_same_diagram_twice_produces_equal_buffers() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 10,
height: 5,
};
let mut diagram = Diagram::new();
diagram = diagram
.add(Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
})
.0;
diagram = diagram
.add(Shape::Line {
at: Pos { x: 0, y: 4 },
len: 5,
orientation: Orientation::Horizontal,
stroke: light(),
})
.0;
let mut first = Buffer::new(Window { origin, size });
diagram.draw(&mut first);
let mut second = Buffer::new(Window { origin, size });
diagram.draw(&mut second);
assert_eq!(cells(&first), cells(&second));
}
/// Every position of `buffer`'s window with the identity the record names there, so two records
/// can be compared by value even though `Buffer` derives no `PartialEq`.
fn owners(buffer: &Buffer) -> Vec<Option<ShapeId>> {
let Window { origin, size } = buffer.window();
(0..size.height)
.flat_map(|dy| (0..size.width).map(move |dx| (dx, dy)))
.map(|(dx, dy)| {
buffer.owner(Pos {
x: origin.x + i16::try_from(dx).expect("width fits i16"),
y: origin.y + i16::try_from(dy).expect("height fits i16"),
})
})
.collect()
}
/// Two filled boxes overlapping over two columns and two rows, the second written last and
/// therefore in front of the first.
///
/// **The arrangement the record is easiest to read against**, and the one whose geometry is
/// worth spelling out rather than leaving to be discovered: the back box fills `(1, 1)` and
/// `(2, 1)`, the front box fills `(3, 2)` and `(4, 2)`, and the front box's **left border** runs
/// down `(2, 1)`, `(2, 2)` and `(2, 3)` — so `(2, 1)` is a cell the shape behind filled and the
/// shape in front decided, which is the one cell where a record can be wrong in a way the
/// picture does not show.
fn two_overlapping_boxes() -> (Diagram, ShapeId, ShapeId) {
let diagram = Diagram::new();
let (diagram, back) = diagram.add(Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("one glyph")),
text: None,
});
let (diagram, front) = diagram.add(Shape::Box {
at: Pos { x: 2, y: 1 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("▓").expect("one glyph")),
text: None,
});
(diagram, back, front)
}
/// Not one of the eight operations changes the diagram it was given, and the picture it draws
/// and the figures it holds are the two readings of that.
///
/// **Every operation, over one arrangement, with the result dropped.** A diagram is a value
/// here, so a caller that forgets to keep what it was handed has changed nothing at all — which
/// is the whole of what the signatures buy and the one mistake a caller can make with them. The
/// results are dropped rather than bound so that the compiler's `#[must_use]` cannot stand in
/// for the assertion.
///
/// **Three readings rather than one, because one would be satisfied by a diagram that changed
/// nothing visible.** The cells it draws say the order did not move and no figure was rewritten,
/// the record says no cell changed owner, and `get` says both figures are still bound to what
/// they were bound to.
#[test]
fn no_operation_changes_the_diagram_it_was_given() {
let (diagram, back, front) = two_overlapping_boxes();
let Window { origin, size } = the_window();
let before = draw_of(&diagram, origin, size);
let cells_before = cells(&before);
let owners_before = owners(&before);
let figures_before = [diagram.get(back).cloned(), diagram.get(front).cloned()];
drop(diagram.add(Shape::Line {
at: Pos { x: 0, y: 3 },
len: 3,
orientation: Orientation::Horizontal,
stroke: light(),
}));
drop(diagram.add_under(identity(9), the_box()));
drop(diagram.forward(back));
drop(diagram.backward(front));
drop(diagram.to_front(back));
drop(diagram.to_back(front));
drop(diagram.replace(back, the_box()));
drop(diagram.remove(back));
assert_eq!(
cells(&draw_of(&diagram, origin, size)),
cells_before,
"every operation was asked and the diagram draws what it drew"
);
assert_eq!(
owners(&draw_of(&diagram, origin, size)),
owners_before,
"and no cell changed which figure owns it"
);
assert_eq!(
[diagram.get(back).cloned(), diagram.get(front).cloned()],
figures_before,
"and both figures are still bound to the identities they were added under"
);
}
/// `add` hands back **the diagram and then the identity**, in that order, and the identity is
/// bound to the figure that was added.
///
/// **The signature is taken as a value of its exact type**, which is the only way a test can
/// pin a pair rather than a drawing of it: a `Diagram` derives no `Debug` and no `PartialEq`,
/// so nothing here compares diagrams — it asks what the function has to return.
///
/// The second half is what the first is for: a caller that had to look the identity up would be
/// asking a question the diagram has just answered by construction, and the one thing a wrong
/// order would break is that the identity names the figure it was given.
#[test]
fn add_hands_back_the_diagram_and_the_identity_in_that_order() {
let add: for<'a> fn(&'a Diagram, Shape) -> (Diagram, ShapeId) = Diagram::add;
let (diagram, issued) = add(&Diagram::new(), the_box());
assert_eq!(
issued,
identity(1),
"the first addition is handed the ordinal the counter stands at"
);
assert_eq!(
diagram.get(issued),
Some(&the_box()),
"and the identity the caller was handed is what names the figure it was given"
);
assert!(
diagram.get(identity(2)).is_none(),
"so a caller that ignored the pair knows exactly what it cannot name"
);
}
/// An identity no figure is under names nothing, and every operation **looking for** it hands
/// back a diagram that changes no cell of the picture.
///
/// **Six operations rather than eight, and `add` and `add_under` are the two left out.** It does not look
/// for a figure under a name, it puts one there, so the premise does not survive it: an
/// identity no figure was under is what a caller hands it. `a_second_shape_under_one_identity_replaces_it_and_is_drawn_once`
/// is the case where there *is* a figure there already, and this is the other one.
///
/// `get` is asked first, because a caller that is told nothing is told so here and nowhere
/// else, and **an identity from another diagram is the same case**: identities are compared by
/// value, so `a_foreign_identity` names a well-formed ordinal this diagram never issued. Both
/// are asked because the answer is what the model's _Positions_ gives a reference to a shape
/// that is not there.
#[test]
fn an_identity_naming_no_figure_changes_no_cell_of_the_picture() {
let (diagram, _back, _front) = two_overlapping_boxes();
let Window { origin, size } = the_window();
let absent = identity(9);
let before = cells(&draw_of(&diagram, origin, size));
for named in [absent, a_foreign_identity()] {
assert!(
diagram.get(named).is_none(),
"an identity no figure is under answers nothing"
);
for (what, after) in [
("`forward`", draw_of(&diagram.forward(named), origin, size)),
(
"`backward`",
draw_of(&diagram.backward(named), origin, size),
),
(
"`to_front`",
draw_of(&diagram.to_front(named), origin, size),
),
("`to_back`", draw_of(&diagram.to_back(named), origin, size)),
(
"`replace`",
draw_of(&diagram.replace(named, the_box()), origin, size),
),
("`remove`", draw_of(&diagram.remove(named), origin, size)),
] {
assert_eq!(
cells(&after),
before,
"{what} on {named:?}, which this diagram holds nothing under, changed the picture"
);
}
}
}
/// The four moves are the only operations that change which figure decides a shared cell, and
/// what that is visible as is **that they are the only ones that change which figure decides a
/// cell two figures hold.**
///
/// A search is not observable and a timing is not a test, so this pins the consequence. A move
/// exchanges two places in the order, and the record follows: at the crossing cell the box
/// behind filled and the box in front decided, and whichever is in front owns it. Nothing else
/// in this crate's surface writes there, because nothing else reaches into the order.
///
/// **The crossing cell is named rather than searched for**, and the four operations that are not
/// moves are asked about it as well — an `add`, an `add_under`, a `replace` and a `remove` that
/// each change the picture and none of which moves anything.
#[test]
fn the_four_moves_are_the_only_operations_that_change_which_figure_decides_a_shared_cell() {
let (diagram, back, front) = two_overlapping_boxes();
let Window { origin, size } = the_window();
let crossing = Pos { x: 2, y: 1 };
assert_eq!(
draw_of(&diagram, origin, size).owner(crossing),
Some(front),
"the box in front of the two decides the cell they share"
);
for (what, moved) in [
("`forward`", draw_of(&diagram.forward(back), origin, size)),
(
"`backward`",
draw_of(&diagram.backward(front), origin, size),
),
("`to_front`", draw_of(&diagram.to_front(back), origin, size)),
("`to_back`", draw_of(&diagram.to_back(front), origin, size)),
] {
assert_eq!(
moved.owner(crossing),
Some(back),
"{what} exchanged two places in the order and the record did not follow"
);
}
for (what, after) in [
(
"`add`",
draw_of(
&diagram
.add(Shape::Line {
at: Pos { x: 0, y: 3 },
len: 2,
orientation: Orientation::Horizontal,
stroke: light(),
})
.0,
origin,
size,
),
),
(
"`add_under`",
draw_of(&diagram.add_under(identity(9), the_box()), origin, size),
),
(
"`replace`",
draw_of(
&diagram.replace(
back,
Shape::Line {
at: Pos { x: 0, y: 0 },
len: 4,
orientation: Orientation::Horizontal,
stroke: light(),
},
),
origin,
size,
),
),
("`remove`", draw_of(&diagram.remove(back), origin, size)),
] {
assert_eq!(
after.owner(crossing),
Some(front),
"{what} changed which figure decides the crossing cell, which only a search of the \
order does"
);
}
}
/// `remove` leaves the order **closed rather than gapped**: what is left draws what it drew and
/// nothing is left standing where the figure stood.
///
/// **The figure put back is the discriminator.** A place left behind would put it where it was,
/// behind the figure still there, and the crossing cell would still be the front box's; a closed
/// order puts it at the front of the order, which is the only place a fresh addition goes, and
/// the record follows. The drawing alone cannot tell the two apart for a figure that does not
/// overlap, which is why the assertion is about the record.
///
/// **Removing the same identity twice changes nothing**, which is the other half of "closed": a
/// second `remove` has no place to close.
#[test]
fn remove_leaves_the_order_closed_rather_than_gapped() {
let (diagram, back, front) = two_overlapping_boxes();
let Window { origin, size } = the_window();
let crossing = Pos { x: 2, y: 1 };
let without = diagram.remove(back);
assert!(
without.get(back).is_none(),
"the identity that was taken out names nothing"
);
assert_eq!(
cells(&draw_of(&without.remove(back), origin, size)),
cells(&draw_of(&without, origin, size)),
"taking out an identity that is already out changed the picture"
);
assert_eq!(
cells(&draw_of(&without, origin, size)),
cells(&draw_of(
&Diagram::new().add_under(
front,
diagram.get(front).cloned().expect("a figure it holds")
),
origin,
size
)),
"what is left draws what the same figure draws with the other never there"
);
// The place the figure stood in is gone rather than reserved: put back, it goes to the
// front of the order like any addition, and the crossing cell becomes its own.
assert_eq!(
draw_of(
&without.add_under(back, diagram.get(back).cloned().expect("a figure it holds")),
origin,
size
)
.owner(crossing),
Some(back),
"the figure put back under a removed identity is in front, so no place of its own was \
left behind"
);
}
/// What hung from a removed figure is frozen, and **nothing goes looking for the reference
/// afterwards**.
///
/// **The arrangement is the one `a_removal_freezes_what_hung_from_the_removed_shape` builds**,
/// so the freeze itself is not re-decided here: what this adds is the second half, which that
/// test does not reach because the figure is not put back.
///
/// **The point is resolved before the removal and held across it**, because "the point it was
/// resolving to" is a claim about a moment that is gone once the figure is out. And **the
/// second half is a claim about the endpoint rather than about the picture**: a frozen end
/// stands at the same point a reference to the figure would have resolved to, so the box put
/// back draws exactly what it drew before — which is why a drawing cannot tell the two apart
/// and only the endpoint can.
#[test]
fn what_hung_from_a_removed_figure_is_frozen_and_not_looked_for_afterwards() {
let Window { origin, size } = the_window();
let nothing = Delta { dx: 0, dy: 0 };
let the_far_end = Pos { x: 8, y: 1 };
let (diagram, box_id) = Diagram::new().add(the_box());
let diagram = diagram
.add(hanging_from(box_id, nothing, the_far_end))
.0
.add(the_unrelated_box())
.0;
let connector = identity(2);
let it_resolved_to = the_hanging_end(&diagram, connector)
.expect("the reference resolves while the figure it names is held")
.resolve(&diagram)
.expect("the box answers the side it names");
let removed = diagram.remove(box_id);
// Frozen: the end is the absolute point it was resolving to, and the picture is the one
// the same diagram draws with that point written out and the box never there.
assert_eq!(
the_hanging_end(&removed, connector)
.expect("the connector is still held")
.at,
EndpointAt::Absolute {
at: it_resolved_to,
leaving: Direction::Right,
},
"the end is the point it was resolving to rather than the reference to a figure that is gone"
);
let written_out = Diagram::new()
.add(the_unrelated_box())
.0
.add(arm_connector(it_resolved_to.into(), the_far_end.into()))
.0;
assert_eq!(
cells(&draw_of(&removed, origin, size)),
cells(&draw_of(&written_out, origin, size)),
"and the picture is what the same figure with that point spelled out draws"
);
// And nothing went looking for the reference: the box put back under the identity it had
// does not turn the absolute point back into one.
let put_back = removed.add_under(box_id, the_box());
assert_eq!(
the_hanging_end(&put_back, connector)
.expect("the connector is still held")
.at,
EndpointAt::Absolute {
at: it_resolved_to,
leaving: Direction::Right,
},
"with the figure standing again the end is still the frozen point"
);
assert_ne!(
the_hanging_end(&put_back, connector)
.expect("the connector is still held")
.at,
the_hanging_end(&diagram, connector)
.expect("the connector is held")
.at,
"and not the reference the connector was written with"
);
}
/// When a target shape is removed, an attached non-arm endpoint freezes at its resolved
/// effective position (one cell outward) so the symbol does not jump visually.
#[test]
fn removing_a_target_box_freezes_attached_symbol_endpoint_without_visual_jump() {
use monospace_core::SymbolStyleName;
let nothing = Delta { dx: 0, dy: 0 };
let symbol = Terminal::Symbol {
style: SymbolStyleName::from("solid"),
};
let catalog = GlyphCatalog::union([GlyphCatalog::light(), GlyphCatalog::solid()]);
let window = Window {
origin: Pos { x: 0, y: 0 },
size: Size {
width: 12,
height: 3,
},
};
let d = Diagram::new();
let (d, left_box) = d.add(Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 3,
height: 3,
},
stroke: light(),
fill: None,
text: None,
});
let (d, right_box) = d.add(Shape::Box {
at: Pos { x: 8, y: 0 },
size: Size {
width: 3,
height: 3,
},
stroke: light(),
fill: None,
text: None,
});
let (d, connector_id) = d.add(Shape::Connector {
from: Endpoint::reference(
Reference::new(left_box, Anchor::Right, nothing, 0),
Terminal::Arm,
),
to: Endpoint::reference(Reference::new(right_box, Anchor::Left, nothing, 0), symbol),
stroke: light(),
});
// The arrow head is at x=7 (one cell outward from right box's left border at x=8).
let mut buf_before = Buffer::new(window);
d.draw(&mut buf_before);
let rendered_before = render(&buf_before, &catalog, window);
assert_eq!(
rendered_before,
concat!("┌─┐ ┌─┐ \n", "│ ├────▶│ │ \n", "└─┘ └─┘ \n")
);
// Remove the right box. The arrow head freezes at x=7 (the resolved effective position).
let d_after = d.remove(right_box);
let Shape::Connector { to: frozen_to, .. } =
d_after.get(connector_id).expect("connector preserved")
else {
unreachable!()
};
assert_eq!(
frozen_to.at,
EndpointAt::Absolute {
at: Pos { x: 7, y: 1 },
leaving: Direction::Left,
}
);
let mut buf_after = Buffer::new(window);
d_after.draw(&mut buf_after);
let rendered_after = render(&buf_after, &catalog, window);
// The right box is gone, but the arrow head at x=7 did not move or jump!
assert_eq!(
rendered_after,
concat!("┌─┐ \n", "│ ├────▶ \n", "└─┘ \n")
);
}
/// A shape is drawn under whatever identity it was added under, so every cell it decided is
/// owned by it and no cell another shape decided is.
///
/// **The four kinds of cell the arrangement holds**, rather than one of them: a fill only the
/// back-most shape wrote, a fill only the one in front wrote, a cell the one in front decided over
/// a fill of the one behind, and a cell neither wrote. The third is the one worth a reader's
/// attention — at `(2, 1)` the back-most box filled the cell and the one in front put its border
/// on top of it, and the record names the front one because that is what is on the screen. A
/// record that named the shape behind would be indistinguishable from this one by looking.
#[test]
fn a_shape_is_drawn_under_the_identity_it_was_added_under() {
let (diagram, back, front) = two_overlapping_boxes();
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let mut buffer = Buffer::new(Window { origin, size });
diagram.draw(&mut buffer);
for (at, expected, what) in [
(
Pos { x: 1, y: 1 },
back,
"a fill only the back-most shape wrote",
),
(
Pos { x: 3, y: 2 },
front,
"a fill only the shape in front wrote",
),
(
Pos { x: 2, y: 1 },
front,
"a cell the shape in front decided over the one behind's fill",
),
(Pos { x: 0, y: 0 }, back, "the back-most shape's own corner"),
(
Pos { x: 5, y: 3 },
front,
"the front-most shape's own corner",
),
] {
assert!(buffer.cell(at).is_some(), "{at:?} holds a cell: {what}");
assert_eq!(
buffer.owner(at),
Some(expected),
"{what} belongs to {expected}"
);
}
// The two cells the arrangement leaves between and below the boxes, which is what makes the
// four above a claim about ownership rather than about a buffer that records everything.
for at in [Pos { x: 5, y: 0 }, Pos { x: 0, y: 3 }] {
assert_eq!(buffer.owner(at), None);
}
}
/// The record belongs to the drawing that produced it: changing the diagram changes nothing
/// about a buffer already drawn, and drawing again into it records nothing.
///
/// **The diagram really does change, or none of this says anything** — so the last assertion
/// draws the changed diagram into a *fresh* window and finds a different picture there. Without
/// it, "the record did not move" would be equally true of a diagram that had not changed at all.
///
/// **Drawing again into the same buffer records nothing anywhere**, and that is the half that
/// could plausibly be otherwise: every position already decided keeps the identity that decided
/// it, because under `Below` nothing takes a position somebody holds. So the cells stay as they
/// were too, and both the picture and the record describe the drawing before the change.
#[test]
fn a_diagram_changed_and_not_drawn_again_leaves_the_record_exactly_as_it_was() {
let (mut diagram, _back, front) = two_overlapping_boxes();
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let mut buffer = Buffer::new(Window { origin, size });
diagram.draw(&mut buffer);
let cells_before = cells(&buffer);
let owners_before = owners(&buffer);
assert!(
owners_before.contains(&Some(front)),
"the first drawing recorded something, so there is a record to leave alone"
);
diagram = diagram.remove(front);
assert_eq!(
cells(&buffer),
cells_before,
"taking a shape out of the diagram changes nothing about what was drawn"
);
assert_eq!(
owners(&buffer),
owners_before,
"and nothing about who owns it"
);
diagram.draw(&mut buffer);
assert_eq!(
owners(&buffer),
owners_before,
"drawing again into a buffer that already holds cells records nothing"
);
// And the change is real: the same diagram drawn into a window of its own is a different
// picture, with the removed shape's fill gone from it.
let mut fresh = Buffer::new(Window { origin, size });
diagram.draw(&mut fresh);
assert_ne!(
cells(&fresh),
cells_before,
"the diagram changed, so a window of its own draws something else"
);
}
/// A second shape under one identity **replaces** the first, and the identity is drawn once, in
/// the place it already had.
///
/// **Two boxes far enough apart to share no cell**, so every owner in the window is one figure's
/// and "drawn once" is a claim about cells rather than about which glyph is in front.
///
/// **The picture is the one a diagram holding only the second box draws**, which is the whole of
/// what replacing means: nothing of the figure that was replaced is left anywhere, and comparing
/// against a diagram built from that one figure is what says so rather than listing the cells it
/// does not reach. **Two places in the order would draw the figure twice** and pass every
/// assertion about which figure the identity names, which is why the whole picture is compared
/// rather than one cell of it.
///
/// This is what §3 _Identity_ now says, where it used to say that two shapes may carry one
/// identity, both are held, and the second is a shape no identity names until the first is
/// removed. Holding two figures under one name needs an identity for the _occurrence_, which the
/// model has no name for, and it turns the order into a sequence of occurrences rather than of
/// identities.
#[test]
fn a_second_shape_under_one_identity_replaces_it_and_is_drawn_once() {
let shared = identity(1);
let a_box_at = |x: i16| Shape::Box {
at: Pos { x, y: 0 },
size: Size {
width: 2,
height: 2,
},
stroke: light(),
fill: None,
text: None,
};
let diagram = Diagram::new()
.add_under(shared, a_box_at(0))
.add_under(shared, a_box_at(4));
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 2,
};
let mut buffer = Buffer::new(Window { origin, size });
diagram.draw(&mut buffer);
// `get` answers with the second of the two, which is the one the diagram kept, and there is
// no listing that would name the other — which is not a limitation but the whole of it.
assert!(
matches!(diagram.get(shared), Some(Shape::Box { at, .. }) if *at == Pos { x: 4, y: 0 }),
"get answers with the second of the two shapes added under the identity"
);
// What is on the screen is the one figure, where it stands, and nothing of the figure it
// replaced: the left box is gone rather than hidden behind the right one.
assert_eq!(
cells(&buffer),
cells(&drawn(vec![a_box_at(4)], origin, size)),
"the identity is drawn once, as the figure that replaced the first"
);
for at in [Pos { x: 4, y: 0 }, Pos { x: 5, y: 1 }] {
assert_eq!(
buffer.owner(at),
Some(shared),
"every cell the surviving figure wrote carries the one identity it is held under, at \
({}, {})",
at.x,
at.y
);
}
for at in [Pos { x: 0, y: 0 }, Pos { x: 1, y: 1 }, Pos { x: 2, y: 0 }] {
assert_eq!(
buffer.owner(at),
None,
"the figure that was replaced wrote nothing, at ({}, {})",
at.x,
at.y
);
}
}
/// Scenario 3: an empty diagram leaves its buffer exactly as it was.
#[test]
fn an_empty_diagram_leaves_its_buffer_untouched() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 3,
height: 3,
};
let mut buffer = Buffer::new(Window { origin, size });
Diagram::new().draw(&mut buffer);
assert_eq!(
cells(&buffer),
vec![None; (size.width * size.height) as usize]
);
}
/// A box partly outside the window draws what falls inside and nothing
/// else, with no error.
#[test]
fn a_box_partly_outside_the_window_draws_only_what_falls_inside() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 3,
height: 3,
};
let mut diagram = Diagram::new();
diagram = diagram
.add(Shape::Box {
at: Pos { x: 1, y: 1 },
size: Size {
width: 4,
height: 4,
},
stroke: light(),
fill: None,
text: None,
})
.0;
let mut buffer = Buffer::new(Window { origin, size });
diagram.draw(&mut buffer);
assert!(buffer.cell(Pos { x: 1, y: 1 }).is_some());
assert!(buffer.cell(Pos { x: 4, y: 4 }).is_none());
}
/// A box drawn through a diagram matches the same `BoxShape` drawn
/// directly.
#[test]
fn a_box_shape_matches_the_core_box_drawn_directly() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 3,
};
let mut diagram = Diagram::new();
diagram = diagram
.add(Shape::Box {
at: origin,
size,
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
text: None,
})
.0;
let mut actual = Buffer::new(Window { origin, size });
diagram.draw(&mut actual);
let mut expected = Buffer::new(Window { origin, size });
BoxShape {
at: origin,
size,
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
}
.draw(&mut FigureLayer::new(&mut expected, StampMode::Above));
assert_eq!(
render(&actual, &GlyphCatalog::light(), actual.window()),
render(&expected, &GlyphCatalog::light(), expected.window())
);
}
/// A line drawn through a diagram matches the same `Line` drawn directly.
#[test]
fn a_line_shape_matches_the_core_line_drawn_directly() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 5,
height: 1,
};
let mut diagram = Diagram::new();
diagram = diagram
.add(Shape::Line {
at: origin,
len: 5,
orientation: Orientation::Horizontal,
stroke: light(),
})
.0;
let mut actual = Buffer::new(Window { origin, size });
diagram.draw(&mut actual);
let mut expected = Buffer::new(Window { origin, size });
Line {
at: origin,
len: 5,
orientation: Orientation::Horizontal,
stroke: light(),
}
.draw(&mut FigureLayer::new(&mut expected, StampMode::Above));
assert_eq!(
render(&actual, &GlyphCatalog::light(), actual.window()),
render(&expected, &GlyphCatalog::light(), expected.window())
);
}
/// A connector drawn through a diagram matches the same `Connector` drawn directly, both
/// endpoints included.
#[test]
fn a_connector_shape_matches_the_core_connector_drawn_directly() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 5,
height: 4,
};
let from = || {
Endpoint::absolute(
Pos { x: 0, y: 0 },
Direction::Down,
Terminal::Glyph {
glyph: Glyph::new("▼").expect("one glyph"),
},
)
};
let to = || {
Endpoint::absolute(
Pos { x: 4, y: 3 },
Direction::Left,
Terminal::Glyph {
glyph: Glyph::new("►").expect("one glyph"),
},
)
};
let mut diagram = Diagram::new();
diagram = diagram
.add(Shape::Connector {
from: from(),
to: to(),
stroke: light(),
})
.0;
let mut actual = Buffer::new(Window { origin, size });
diagram.draw(&mut actual);
let mut expected = Buffer::new(Window { origin, size });
Connector {
from: monospace_core::Endpoint {
at: Pos { x: 0, y: 0 },
leaving: Direction::Down,
terminal: Terminal::Glyph {
glyph: Glyph::new("▼").expect("one glyph"),
},
},
to: monospace_core::Endpoint {
at: Pos { x: 4, y: 3 },
leaving: Direction::Left,
terminal: Terminal::Glyph {
glyph: Glyph::new("►").expect("one glyph"),
},
},
stroke: light(),
}
.draw(&mut FigureLayer::new(&mut expected, StampMode::Above));
assert_eq!(
render(&actual, &GlyphCatalog::light(), actual.window()),
render(&expected, &GlyphCatalog::light(), expected.window())
);
}
/// A diagram told where its numbering resumes hands the next `add` **that** ordinal, and a
/// further addition a different one. Asked by the identity's own text, because this is the one
/// rule in the slice no picture can show.
///
/// A counter holding the *last issued* ordinal would hand back `4` in the first half below,
/// which is the off-by-one `numbered_from` exists to make impossible rather than to document.
/// The ordinal is a `NonZeroU16` and `3` is read through it, so the seeding a file's `next_id`
/// arrives on is the same one this test writes.
#[test]
fn a_seeded_diagram_hands_back_the_ordinal_it_was_seeded_with_and_then_a_different_one() {
let a_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
};
let diagram = Diagram::numbered_from(nz(3));
let (diagram, first) = diagram.add(a_line());
let (_, second) = diagram.add(a_line());
assert_eq!(first.to_string(), "3");
assert_eq!(second.to_string(), "4");
assert_ne!(first, second);
}
/// The same rule, run against a diagram that was told where its numbering resumes rather than
/// one that started at `1`: taking `10` out of a diagram seeded at 10 still leaves the next
/// addition as `12`, so a seeded counter resumes rather than restarts.
///
/// **This is the test that holds an ordinal stable**, and it holds it in the direction a number
/// makes doubtful: `10` reads as a count far more readily than the old `#10` did, and a counter
/// that reused it would keep this assertion green until the drawing changed. It does not reuse
/// it, and nothing in the model forbade it — the answer today is this test rather than a rule.
#[test]
fn a_seeded_diagram_never_hands_out_an_identity_it_issued_before() {
let a_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
};
let diagram = Diagram::numbered_from(nz(10));
let (mut diagram, first) = diagram.add(a_line());
diagram = diagram.add(a_line()).0;
assert_eq!(first.to_string(), "10");
diagram = diagram.remove(first);
let (_, after_the_removal) = diagram.add(a_line());
assert_eq!(after_the_removal.to_string(), "12");
}
/// A shape put under a chosen identity is the one every change that names that identity acts
/// on, and by **any other** identity it is not a shape this diagram holds.
///
/// **"Chosen" is now an ordinal rather than a word, and the two are told apart by the same
/// thing.** `chosen` and `other` are the second and third ordinals and `absent` is the ninth:
/// three well-formed numbers that no diagram in this test issued, so "this identity names no
/// shape here" is a statement about the counter rather than about how an identity is spelled.
/// That is the cost of the change and it is a small one — three lines that read `identity(2)`
/// instead of `ShapeId::new("chosen")` — paid for an identity that is two bytes.
///
/// The second half is the one that is easy to leave out, and the one that keeps "unique" a
/// claim about what the diagram issues rather than a promise it keeps on a caller's behalf.
#[test]
fn a_chosen_identity_is_found_by_that_identity_and_by_no_other_one() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 14,
height: 3,
};
let a_box_at_zero = || Shape::Box {
at: origin,
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
};
let mut diagram = Diagram::new();
let chosen = identity(2);
let other = identity(3);
diagram = diagram.add_under(chosen, a_box_at_zero());
// `get` names the shape it was given.
assert!(matches!(diagram.get(chosen), Some(Shape::Box { .. })));
// An identity this diagram holds for a *different* shape changes nothing, and neither does
// one it holds for no shape at all: naming it draws nothing and adds nothing.
let absent = identity(9);
let mut with_both = Diagram::new();
with_both = with_both.add_under(chosen, a_box_at_zero());
with_both = with_both.add_under(other, a_box_at_zero());
assert!(matches!(with_both.get(other), Some(Shape::Box { .. })));
assert!(with_both.get(absent).is_none());
let before_naming = cells(&draw_of(&with_both, origin, size));
with_both = with_both.forward(absent);
with_both = with_both.backward(absent);
with_both = with_both.remove(absent);
with_both = with_both.replace(absent, a_box_at_zero());
assert_eq!(
cells(&draw_of(&with_both, origin, size)),
before_naming,
"an identity naming nothing must change no cell of the picture"
);
// `remove` takes out the shape the identity named and nothing else. The shape added here is
// the diagram's own first one, so it is `1` and the chosen `2` is not the same ordinal.
let mut to_remove_from = Diagram::new();
to_remove_from = to_remove_from.add_under(chosen, a_box_at_zero());
to_remove_from = to_remove_from.add(a_box_at_zero()).0;
to_remove_from = to_remove_from.remove(chosen);
assert!(to_remove_from.get(chosen).is_none());
assert!(matches!(
to_remove_from.get(identity(1)),
Some(Shape::Box { .. })
));
// `replace` puts the shape back under the identity it was given, and the identity it did
// not name is untouched.
let mut to_replace_in = Diagram::new();
to_replace_in = to_replace_in.add_under(chosen, a_box_at_zero());
let (mut to_replace_in, issued) = to_replace_in.add(a_box_at_zero());
to_replace_in = to_replace_in.replace(chosen, a_box_at_zero());
assert!(matches!(to_replace_in.get(chosen), Some(Shape::Box { .. })));
assert!(matches!(to_replace_in.get(issued), Some(Shape::Box { .. })));
// `forward` and `backward` move the shape the identity names, one place at a time, and
// the picture says which one moved. Three **filled** boxes overlapping one another, so
// which is in front decides the cells they share and the order is visible in the drawing
// rather than only in the order: `forward` on `chosen` puts it in front of the next one
// along, and `backward` puts it back.
//
// The fill is what makes the order visible. Unfilled boxes that share only their borders
// compose to the same junction whichever is in front, so a drawing of them cannot tell
// the two orders apart — measured, not assumed.
let a_filled_box = |x: i16, fill: &'static str| Shape::Box {
at: Pos { x, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new(fill).expect("one grapheme cluster")),
text: None,
};
// `add_under` pushes onto the back of the order and the back is the **front** of the
// order, so the last one added is the front-most and the first is the back-most. Added in
// this order, `chosen` is the back-most and a `forward` has somewhere to go.
//
// Two shapes, not three, and that is measured rather than chosen for tidiness: with three
// overlapping boxes the orders "other, chosen, third" and "other, third, chosen" draw
// **the same picture**, so a drawing cannot tell a chosen identity one place forward from
// two places forward. With two there is only one place to move, and the two orders are two
// different drawings.
let mut to_move = Diagram::new();
to_move = to_move.add_under(chosen, a_filled_box(0, "█"));
to_move = to_move.add_under(other, a_filled_box(2, "░"));
let at_the_back = cells(&draw_of(&to_move, origin, size));
to_move = to_move.forward(chosen);
let one_forward = cells(&draw_of(&to_move, origin, size));
assert_ne!(
one_forward, at_the_back,
"forward on a chosen identity must move that shape"
);
// The one place it moved is the one a diagram built with `chosen` in front draws — which
// is the claim, stated as a drawing rather than as a count of places.
let mut with_it_in_front = Diagram::new();
with_it_in_front = with_it_in_front.add_under(other, a_filled_box(2, "░"));
with_it_in_front = with_it_in_front.add_under(chosen, a_filled_box(0, "█"));
assert_eq!(
one_forward,
cells(&draw_of(&with_it_in_front, origin, size)),
"one forward on a chosen identity moves it exactly one place"
);
to_move = to_move.backward(chosen);
assert_eq!(
cells(&draw_of(&to_move, origin, size)),
at_the_back,
"forward then backward restores the drawing"
);
// A `forward` on the front-most shape has nowhere to go, and changes no cell.
to_move = to_move.forward(other);
assert_eq!(
cells(&draw_of(&to_move, origin, size)),
at_the_back,
"forward on the front-most shape changes nothing"
);
}
/// A diagram-issued identity **is** the counter's value, the counter advances by one, and a
/// shape added under a caller's identity does not move it.
///
/// **Both directions of the same counter, and one caller's identity well away from it.** The
/// `7` written under the caller's own identity is a digit away from the `3` the counter stands
/// at, so an `add_under` that moved the counter by one would hand back `4` rather than `3` and
/// a counter that advanced by two would hand back `5`; neither is what `3` says happened. The
/// second `add` then shows the advance itself: the counter's own ordinals are consecutive, which
/// is the whole of what "the numbering resumes" means.
#[test]
fn a_diagram_issues_the_counter_and_a_shape_added_under_a_callers_identity_does_not_move_it() {
let a_box = || Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
};
// Nothing a caller writes moves the numbering, and the counter advances by exactly one.
let mut diagram = Diagram::numbered_from(nz(3));
diagram = diagram.add_under(identity(7), a_box());
let (diagram, next) = diagram.add(a_box());
let (_, after_that) = diagram.add(a_box());
assert_eq!(next.to_string(), "3");
assert_eq!(
after_that.to_string(),
"4",
"the counter advanced by one, and the caller's 7 is not in the way"
);
}
/// A second shape under an identity the diagram already holds **replaces** the first, and taking
/// the identity out takes that one out: there is no shape underneath waiting to be named.
///
/// **Both directions of the same rule, because only one of them would pass by accident.** The
/// first is the replacement and the second is what `remove` finds — a diagram that still held
/// both would answer the first assertion and fail the second, and one that held neither would
/// fail both.
///
/// The boxes are told apart by their **fill**, so "the second replaced the first" is a claim
/// about which figure `get` names rather than about a value that cannot tell them apart.
#[test]
fn a_repeated_identity_holds_the_shape_added_last_and_removing_it_leaves_nothing_behind() {
let a_box_filled_with = |fill: &'static str| Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new(fill).expect("one grapheme cluster")),
text: None,
};
let repeated = Diagram::new()
.add_under(identity(1), a_box_filled_with("░"))
.add_under(identity(1), a_box_filled_with("▓"));
assert_eq!(
repeated.get(identity(1)),
Some(&a_box_filled_with("▓")),
"the second shape added under an identity is the one the diagram holds"
);
let taken_out = repeated.remove(identity(1));
assert!(
taken_out.get(identity(1)).is_none(),
"taking the identity out takes the one shape it held, and there is no second one under it"
);
}
/// **The two `add` calls above stop at `u16::MAX`, and the one after them has nothing to hand
/// back.** A `u16` has no ordinal after its largest one, and every value it could hold next is a
/// `0` — the one thing this crate's identity type cannot carry, and what the old `+= 1` wrapped
/// into in a release build without saying so. The last ordinal is issued because it is free, and
/// the addition after it is the one that says so rather than wrapping or handing it out twice.
#[test]
#[should_panic(expected = "a diagram has no ordinal left to issue")]
fn a_diagram_that_has_run_out_of_ordinals_says_so_rather_than_issuing_zero() {
let a_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
};
let diagram = Diagram::numbered_from(NonZeroU16::new(u16::MAX).expect("the largest"));
// The last ordinal there is: issued, and legal.
let (diagram, last) = diagram.add(a_line());
assert_eq!(last.to_string(), u16::MAX.to_string());
// And the one after it is not. Nothing wraps to zero and nothing hands back what it has
// already handed out.
let _ = diagram.add(a_line());
}
/// The last ordinal a `u16` can hold is **no different because a caller took it**: a diagram
/// numbered there with a figure already under that identity has nothing left to issue either,
/// and says so by name rather than replacing the caller's figure or naming it a second time.
///
/// **The caller's figure is what makes this case and not the one above.** Without one the
/// counter simply runs out; with one it runs out a step early, and the step-over is what finds
/// nothing. A diagram that replaced the caller here would take a figure away with no report and
/// no way back, which is the outcome this rule refuses.
#[test]
#[should_panic(expected = "a diagram has no ordinal left to issue")]
fn a_diagram_with_no_ordinal_left_says_so_rather_than_repeating_one() {
let the_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
};
let diagram = Diagram::numbered_from(NonZeroU16::new(u16::MAX).expect("the largest"))
.add_under(identity(u16::MAX), the_line());
let _ = diagram.add(the_line());
}
/// Adding three shapes to one diagram yields three identities that differ from one
/// another and read as `1`, `2`, `3` in the order added.
#[test]
fn adding_three_shapes_yields_three_identities_in_order() {
let diagram = Diagram::new();
let (diagram, first) = diagram.add(Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
});
let (diagram, second) = diagram.add(Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
});
let (_, third) = diagram.add(Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
});
assert_eq!(first.to_string(), "1");
assert_eq!(second.to_string(), "2");
assert_eq!(third.to_string(), "3");
assert_ne!(first, second);
assert_ne!(second, third);
assert_ne!(first, third);
}
/// Spec.md US1 scenario 3: adding the same shape value twice yields two different identities.
#[test]
fn adding_the_same_shape_value_twice_yields_two_different_identities() {
let shape = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
};
let diagram = Diagram::new();
let (diagram, first) = diagram.add(shape());
let (_, second) = diagram.add(shape());
assert_ne!(first, second);
}
/// Two overlapping boxes, each filled with its own glyph, so which one is front-most decides
/// the shared cells rather than leaving both interior sides open (as two unfilled boxes with
/// the same stroke do, order-independently).
fn overlapping_boxes() -> (Shape, Shape) {
(
Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
text: None,
},
Shape::Box {
at: Pos { x: 2, y: 1 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("▓").expect("\"▓\" is one glyph")),
text: None,
},
)
}
fn overlapping_core_boxes() -> (BoxShape, BoxShape) {
(
BoxShape {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
},
BoxShape {
at: Pos { x: 2, y: 1 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("▓").expect("\"▓\" is one glyph")),
},
)
}
/// Two overlapping boxes drawn front to back with `Below` produce the buffer that stamping
/// the same two core shapes back to front with `Above` produces.
#[test]
fn front_to_back_with_below_equals_back_to_front_with_above() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let mut diagram = Diagram::new();
diagram = diagram.add(a).0;
diagram = diagram.add(b).0;
let mut actual = Buffer::new(Window { origin, size });
diagram.draw(&mut actual);
let (core_a, core_b) = overlapping_core_boxes();
let mut expected = Buffer::new(Window { origin, size });
core_a.draw(&mut FigureLayer::new(&mut expected, StampMode::Above));
core_b.draw(&mut FigureLayer::new(&mut expected, StampMode::Above));
assert_eq!(cells(&actual), cells(&expected));
}
/// The same two overlapping boxes in opposite orders produce different buffers, and in each
/// the front-most shape's stroke decides the shared cells.
#[test]
fn opposite_orders_produce_different_buffers() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let mut a_then_b = Diagram::new();
a_then_b = a_then_b.add(a).0;
a_then_b = a_then_b.add(b).0;
let mut a_then_b_buffer = Buffer::new(Window { origin, size });
a_then_b.draw(&mut a_then_b_buffer);
let (a, b) = overlapping_boxes();
let mut b_then_a = Diagram::new();
b_then_a = b_then_a.add(b).0;
b_then_a = b_then_a.add(a).0;
let mut b_then_a_buffer = Buffer::new(Window { origin, size });
b_then_a.draw(&mut b_then_a_buffer);
assert_ne!(cells(&a_then_b_buffer), cells(&b_then_a_buffer));
}
/// Scenarios 3 and 4: a crossing is composition, not occlusion — a horizontal and a vertical
/// line that cross make a junction glyph, and a filled box in front of a line hides it
/// wherever the box's interior covers it, while the box's border still composes with the
/// line into a junction where the two meet.
#[test]
fn a_crossing_composes_and_a_filled_box_occludes() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 5,
height: 5,
};
let mut crossing = Diagram::new();
crossing = crossing
.add(Shape::Line {
at: Pos { x: 0, y: 2 },
len: 5,
orientation: Orientation::Horizontal,
stroke: light(),
})
.0;
crossing = crossing
.add(Shape::Line {
at: Pos { x: 2, y: 0 },
len: 5,
orientation: Orientation::Vertical,
stroke: light(),
})
.0;
let mut crossing_buffer = Buffer::new(Window { origin, size });
crossing.draw(&mut crossing_buffer);
assert_eq!(
render(
&crossing_buffer,
&GlyphCatalog::light(),
crossing_buffer.window()
),
" │ \n │ \n──┼──\n │ \n │ \n"
);
let mut occluding = Diagram::new();
occluding = occluding
.add(Shape::Line {
at: Pos { x: 2, y: 0 },
len: 5,
orientation: Orientation::Vertical,
stroke: light(),
})
.0;
occluding = occluding
.add(Shape::Box {
at: Pos { x: 1, y: 1 },
size: Size {
width: 3,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
text: None,
})
.0;
let mut occluding_buffer = Buffer::new(Window { origin, size });
occluding.draw(&mut occluding_buffer);
assert_eq!(
render(
&occluding_buffer,
&GlyphCatalog::light(),
occluding_buffer.window()
),
" │ \n ┌┴┐ \n │░│ \n └┬┘ \n │ \n"
);
}
/// Two partially overlapping opaque boxes, drawn before and after the back one moves
/// forward, produce different buffers, and the second equals what the same two boxes added in
/// the opposite order produce.
#[test]
fn moving_the_back_one_forward_matches_adding_them_in_the_opposite_order() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let diagram = Diagram::new();
let (mut diagram, back) = diagram.add(a);
diagram = diagram.add(b).0;
let mut before = Buffer::new(Window { origin, size });
diagram.draw(&mut before);
diagram = diagram.forward(back);
let mut after = Buffer::new(Window { origin, size });
diagram.draw(&mut after);
assert_ne!(cells(&before), cells(&after));
let (a, b) = overlapping_boxes();
let mut opposite = Diagram::new();
opposite = opposite.add(b).0;
opposite = opposite.add(a).0;
let mut opposite_buffer = Buffer::new(Window { origin, size });
opposite.draw(&mut opposite_buffer);
assert_eq!(cells(&after), cells(&opposite_buffer));
}
/// The same expected buffer comes from moving the front one backward instead, against
/// the same two boxes.
#[test]
fn moving_the_front_one_backward_matches_moving_the_back_one_forward() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let mut diagram = Diagram::new();
diagram = diagram.add(a).0;
let (mut diagram, front) = diagram.add(b);
diagram = diagram.backward(front);
let mut buffer = Buffer::new(Window { origin, size });
diagram.draw(&mut buffer);
let (a, b) = overlapping_boxes();
let mut opposite = Diagram::new();
opposite = opposite.add(b).0;
opposite = opposite.add(a).0;
let mut opposite_buffer = Buffer::new(Window { origin, size });
opposite.draw(&mut opposite_buffer);
assert_eq!(cells(&buffer), cells(&opposite_buffer));
}
/// Moving the front-most forward, and moving the back-most backward, each leave the
/// drawn buffer unchanged.
#[test]
fn moving_the_front_most_forward_or_the_back_most_backward_changes_nothing() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let diagram = Diagram::new();
let (diagram, back) = diagram.add(a);
let (mut diagram, front) = diagram.add(b);
let mut before = Buffer::new(Window { origin, size });
diagram.draw(&mut before);
diagram = diagram.forward(front);
let mut after_forward = Buffer::new(Window { origin, size });
diagram.draw(&mut after_forward);
assert_eq!(cells(&before), cells(&after_forward));
diagram = diagram.backward(back);
let mut after_backward = Buffer::new(Window { origin, size });
diagram.draw(&mut after_backward);
assert_eq!(cells(&before), cells(&after_backward));
}
/// Whether a figure can move forward is the answer `forward` obeys.
///
/// **Both sides of one rule**, as `Shape::can_resize` and `Shape::resized_by` are: the front-most
/// figure cannot, the one behind it can, and an identity the diagram does not hold cannot — and
/// each answer is checked against whether `forward` changed the drawing, so a predicate that was
/// right about the examples and wrong about the rule fails.
#[test]
fn the_answer_to_whether_a_figure_can_move_forward_is_the_answer_forward_obeys() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let (diagram, back) = Diagram::new().add(a);
let (diagram, front) = diagram.add(b);
let before = cells(&draw_of(&diagram, origin, size));
for (figure, expected) in [(back, true), (front, false), (identity(9), false)] {
let moved = cells(&draw_of(&diagram.forward(figure), origin, size)) != before;
assert_eq!(
diagram.can_forward(figure),
expected,
"the predicate's own answer"
);
assert_eq!(moved, expected, "which is the answer `forward` obeys");
}
}
/// `place_of` counts from the back and answers nothing for an identity the diagram does not
/// hold, which is the same `None` every other operation gives that identity.
#[test]
fn place_of_reports_where_a_figure_stands() {
let (diagram, back, front) = two_overlapping_boxes();
assert_eq!(
diagram.place_of(back),
Some(0),
"the back-most figure stands at zero"
);
assert_eq!(
diagram.place_of(front),
Some(1),
"the front-most stands one place along"
);
assert_eq!(
diagram.place_of(identity(9)),
None,
"an absent identity stands nowhere"
);
assert_eq!(
diagram.place_of(a_foreign_identity()),
None,
"an identity from another diagram is the same absence"
);
}
/// `shape_count` is the number of figures the order holds, and it follows a removal.
#[test]
fn shape_count_is_the_number_of_figures() {
let empty = Diagram::new();
assert_eq!(empty.shape_count(), 0, "an empty diagram holds no figures");
let (diagram, back, _front) = two_overlapping_boxes();
assert_eq!(diagram.shape_count(), 2, "two additions are two figures");
assert_eq!(
diagram.remove(back).shape_count(),
1,
"a removal leaves one figure behind"
);
}
/// Whether a figure can move backward is the answer `backward` obeys.
///
/// **The mirror of the forward test**, and the same three cases: the back-most figure cannot, the
/// one in front of it can, and an identity the diagram does not hold cannot. Each answer is
/// checked against whether `backward` changed the drawing, so a predicate that was right about
/// the examples and wrong about the rule fails.
#[test]
fn the_answer_to_whether_a_figure_can_move_backward_is_the_answer_backward_obeys() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let (diagram, back) = Diagram::new().add(a);
let (diagram, front) = diagram.add(b);
let before = cells(&draw_of(&diagram, origin, size));
for (figure, expected) in [(back, false), (front, true), (identity(9), false)] {
let moved = cells(&draw_of(&diagram.backward(figure), origin, size)) != before;
assert_eq!(
diagram.can_backward(figure),
expected,
"the predicate's own answer"
);
assert_eq!(moved, expected, "which is the answer `backward` obeys");
}
}
/// `to_front` puts the figure at the end of the order and the drawing follows.
#[test]
fn to_front_puts_the_figure_at_the_end_of_the_order() {
let (diagram, back, front) = two_overlapping_boxes();
let Window { origin, size } = the_window();
let crossing = Pos { x: 2, y: 1 };
let moved = diagram.to_front(back);
assert_eq!(
moved.place_of(back),
Some(1),
"the figure is now front-most"
);
assert_eq!(
moved.place_of(front),
Some(0),
"and the other one moved back"
);
assert_eq!(
draw_of(&moved, origin, size).owner(crossing),
Some(back),
"the figure that moved to the front decides the crossing cell"
);
}
/// `to_back` puts the figure at the start of the order and the drawing follows.
#[test]
fn to_back_puts_the_figure_at_the_start_of_the_order() {
let (diagram, back, front) = two_overlapping_boxes();
let Window { origin, size } = the_window();
let crossing = Pos { x: 2, y: 1 };
let moved = diagram.to_back(front);
assert_eq!(
moved.place_of(front),
Some(0),
"the figure is now back-most"
);
assert_eq!(
moved.place_of(back),
Some(1),
"and the other one moved forward"
);
assert_eq!(
draw_of(&moved, origin, size).owner(crossing),
Some(back),
"the figure that moved to the back no longer decides the crossing cell"
);
}
/// A figure already at the end it is sent to changes nothing.
#[test]
fn the_absolute_moves_at_the_end_they_are_already_at_change_nothing() {
let (diagram, back, front) = two_overlapping_boxes();
let Window { origin, size } = the_window();
let before = cells(&draw_of(&diagram, origin, size));
for (what, after) in [
("`to_front`", diagram.to_front(front)),
("`to_back`", diagram.to_back(back)),
] {
assert_eq!(
cells(&draw_of(&after, origin, size)),
before,
"{what} at the end it was already at changed the picture"
);
assert_eq!(
after.place_of(back),
Some(0),
"{what} moved the back figure"
);
assert_eq!(
after.place_of(front),
Some(1),
"{what} moved the front figure"
);
}
}
/// An identity the diagram does not hold is not inserted at an end.
#[test]
fn the_absolute_moves_of_an_identity_the_diagram_does_not_hold_change_nothing() {
let (diagram, back, front) = two_overlapping_boxes();
let Window { origin, size } = the_window();
let before = cells(&draw_of(&diagram, origin, size));
for named in [identity(9), a_foreign_identity()] {
for (what, after) in [
("`to_front`", diagram.to_front(named)),
("`to_back`", diagram.to_back(named)),
] {
assert_eq!(
cells(&draw_of(&after, origin, size)),
before,
"{what} on {named:?}, which this diagram holds nothing under, changed the picture"
);
assert_eq!(
after.shape_count(),
2,
"{what} inserted the missing identity"
);
assert_eq!(
after.place_of(back),
Some(0),
"{what} moved the back figure"
);
assert_eq!(
after.place_of(front),
Some(1),
"{what} moved the front figure"
);
}
}
}
/// A diagram holding one shape is unchanged by either move, since that
/// shape is both front-most and back-most.
#[test]
fn a_diagram_holding_one_shape_is_unchanged_by_either_move() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 4,
height: 3,
};
let diagram = Diagram::new();
let (mut diagram, only) = diagram.add(Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
text: None,
});
let mut before = Buffer::new(Window { origin, size });
diagram.draw(&mut before);
diagram = diagram.forward(only);
diagram = diagram.backward(only);
let mut after = Buffer::new(Window { origin, size });
diagram.draw(&mut after);
assert_eq!(cells(&before), cells(&after));
}
/// An identity kept from another diagram changes nothing through either
/// method, with no panic.
#[test]
fn an_identity_from_another_diagram_changes_nothing_and_does_not_panic() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let mut diagram = Diagram::new();
diagram = diagram.add(a).0;
diagram = diagram.add(b).0;
let mut before = Buffer::new(Window { origin, size });
diagram.draw(&mut before);
let other = Diagram::new();
let (_, foreign) = other.add(Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
});
diagram = diagram.forward(foreign);
diagram = diagram.backward(foreign);
let mut after = Buffer::new(Window { origin, size });
diagram.draw(&mut after);
assert_eq!(cells(&before), cells(&after));
}
/// An empty diagram is unchanged by either method, with no panic.
#[test]
fn an_empty_diagram_is_unchanged_by_either_move() {
let other = Diagram::new();
let (_, foreign) = other.add(Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
});
let mut diagram = Diagram::new();
diagram = diagram.forward(foreign);
diagram = diagram.backward(foreign);
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 3,
height: 3,
};
let mut buffer = Buffer::new(Window { origin, size });
diagram.draw(&mut buffer);
assert_eq!(
cells(&buffer),
vec![None; (size.width * size.height) as usize]
);
}
/// A shape moved forward and then backward by the same identity draws exactly what it
/// drew at the start.
#[test]
fn moving_a_shape_forward_then_backward_restores_the_original_drawing() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let diagram = Diagram::new();
let (mut diagram, back) = diagram.add(a);
diagram = diagram.add(b).0;
let mut before = Buffer::new(Window { origin, size });
diagram.draw(&mut before);
diagram = diagram.forward(back);
diagram = diagram.backward(back);
let mut after = Buffer::new(Window { origin, size });
diagram.draw(&mut after);
assert_eq!(cells(&before), cells(&after));
}
/// Edge case: two unfilled boxes with the same stroke whose shared cells every side leaves
/// `Unset` — an inner box entirely inside an outer box's interior, so their border cells never
/// coincide — draw identically before and after a reorder.
#[test]
fn two_unfilled_boxes_with_no_shared_cell_draw_identically_regardless_of_order() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 5,
};
let outer = || Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 6,
height: 5,
},
stroke: light(),
fill: None,
text: None,
};
let inner = || Shape::Box {
at: Pos { x: 2, y: 2 },
size: Size {
width: 2,
height: 2,
},
stroke: light(),
fill: None,
text: None,
};
let mut outer_then_inner = Diagram::new();
outer_then_inner = outer_then_inner.add(outer()).0;
outer_then_inner = outer_then_inner.add(inner()).0;
let mut a = Buffer::new(Window { origin, size });
outer_then_inner.draw(&mut a);
let mut inner_then_outer = Diagram::new();
inner_then_outer = inner_then_outer.add(inner()).0;
inner_then_outer = inner_then_outer.add(outer()).0;
let mut b = Buffer::new(Window { origin, size });
inner_then_outer.draw(&mut b);
assert_eq!(cells(&a), cells(&b));
}
// ------------------------------------------------------ a figure displaced by a delta
/// Draws `shapes` into a fresh window, in the order given, so that a figure is observed the
/// only way this crate lets it be observed. Both sides of every comparison below arrive
/// through here: the figure displaced, and the same figure added where it landed.
fn drawn(shapes: Vec<Shape>, origin: Pos, size: Size) -> Buffer {
let mut diagram = Diagram::new();
for shape in shapes {
diagram = diagram.add(shape).0;
}
draw_of(&diagram, origin, size)
}
/// Draws a diagram the caller already holds, for a claim about what a change to it did.
fn draw_of(diagram: &Diagram, origin: Pos, size: Size) -> Buffer {
let mut buffer = Buffer::new(Window { origin, size });
diagram.draw(&mut buffer);
buffer
}
/// The positions where two buffers of one window differ, so that a claim about which cells a
/// change reached can be made by coordinates rather than by reading two pictures side by side.
fn differing(before: &Buffer, after: &Buffer) -> Vec<Pos> {
let Window { origin, size } = before.window();
(0..size.height)
.flat_map(|dy| (0..size.width).map(move |dx| (dx, dy)))
.map(|(dx, dy)| Pos {
x: origin.x + i16::try_from(dx).expect("width fits i16"),
y: origin.y + i16::try_from(dy).expect("height fits i16"),
})
.filter(|at| before.cell(*at) != after.cell(*at))
.collect()
}
/// Three filled boxes that all overlap one another, so which of them is front-most decides the
/// cells they share and a change of order changes the picture. The first is the back-most and
/// the last the front-most, and the second overlaps both.
fn three_overlapping_boxes() -> (Shape, Shape, Shape) {
let filled_box = |at: Pos, fill: &str| Shape::Box {
at,
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new(fill).expect("one glyph")),
text: None,
};
(
filled_box(Pos { x: 0, y: 0 }, "░"),
filled_box(Pos { x: 2, y: 1 }, "▓"),
filled_box(Pos { x: 0, y: 1 }, "▒"),
)
}
/// An identity no diagram in these tests holds, and the one the specification's cases mean by
/// an identity from another diagram.
///
/// It is the **third** identity another diagram issued rather than its first, and the reason
/// inverts with the type. `ShapeId` was a string, so a foreign identity could not collide with
/// anything here as long as its text differed — and `1`, the first identity any diagram issues,
/// is exactly what the two-shape diagrams below have already used. **An ordinal now matches or
/// it does not**, so a foreign identity is a statement about the counter rather than about the
/// spelling: the third is one this diagram never reached, because adding three shapes to it
/// stops at `3`.
fn a_foreign_identity() -> ShapeId {
let a_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
};
let (mut other, _) = Diagram::new().add(a_line());
other = other.add(a_line()).0;
other.add(a_line()).1
}
/// A box displaced two cells right draws exactly what the same box added at the displaced
/// position draws.
///
/// The expected picture is built by adding the box where it landed rather than pinned as text,
/// so what is asserted is where a displacement puts a figure and not how a box draws. A
/// displacement that quietly did nothing would draw the box where it already stood, and the two
/// pictures would differ.
#[test]
fn a_displaced_box_draws_where_the_same_box_at_that_position_would_draw() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 9,
height: 3,
};
let box_at = |x: i16| Shape::Box {
at: Pos { x, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
};
let moved = box_at(1).displaced_by(Delta { dx: 2, dy: 0 });
assert_eq!(
cells(&drawn(vec![moved], origin, size)),
cells(&drawn(vec![box_at(3)], origin, size))
);
}
/// A connector displaced two cells down draws exactly what the same connector added with
/// **both** endpoints at `y + 2` draws.
///
/// Both endpoints is the whole claim, and it is why the expected picture is built from the two
/// positions rather than pinned as text. A displacement that moved one endpoint draws a
/// connector between two rows, and one that moved neither is the silent no-op the previous
/// system shipped along with a `// TODO: implement it`. Either passes a comparison against a
/// picture of a connector that never moved, so this is the one neither passes.
#[test]
fn a_displaced_connector_draws_with_both_endpoints_moved() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 7,
height: 5,
};
let connector = |from: Pos, to: Pos| Shape::Connector {
from: Endpoint::absolute(
from,
Direction::Right,
Terminal::Glyph {
glyph: Glyph::new("◄").expect("one glyph"),
},
),
to: Endpoint::absolute(
to,
Direction::Left,
Terminal::Glyph {
glyph: Glyph::new("►").expect("one glyph"),
},
),
stroke: light(),
};
let moved =
connector(Pos { x: 1, y: 1 }, Pos { x: 5, y: 1 }).displaced_by(Delta { dx: 0, dy: 2 });
assert_eq!(
cells(&drawn(vec![moved], origin, size)),
cells(&drawn(
vec![connector(Pos { x: 1, y: 3 }, Pos { x: 5, y: 3 })],
origin,
size
))
);
}
/// Displacing a figure a diagram holds changes no cell of it. A displacement builds a value;
/// putting that value back under an identity is what changes anything. The second half of the
/// rule is T026, which needs `replace` to exist.
///
/// The `assert_ne!` is what keeps the test honest: without it a `displaced_by` that moved
/// nothing would satisfy "changed no cell" by doing exactly that, and the rule would go
/// unchecked.
#[test]
fn displacing_a_figure_the_diagram_holds_changes_no_cell_of_it() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let mut diagram = Diagram::new();
diagram = diagram.add(a.clone()).0;
diagram = diagram.add(b).0;
let mut before = Buffer::new(Window { origin, size });
diagram.draw(&mut before);
let displaced = a.displaced_by(Delta { dx: 1, dy: 2 });
let mut after = Buffer::new(Window { origin, size });
diagram.draw(&mut after);
assert_eq!(cells(&before), cells(&after));
assert_ne!(displaced, a);
}
// ------------------------------------------- reading a figure back, and the two changes
/// `get` on the identity `add` handed back returns a figure equal by value to the one added.
///
/// Compared by value rather than by picture, because this is the only rule in the slice no
/// picture can show. The widened derives are what make it sayable at all, and what comes back
/// is the bare figure: the identity and the place in the order are the diagram's, held beside
/// the figure rather than inside it.
#[test]
fn get_returns_the_figure_the_addition_named() {
let (a, _b) = overlapping_boxes();
let diagram = Diagram::new();
let (diagram, id) = diagram.add(a.clone());
assert_eq!(diagram.get(id), Some(&a));
}
/// `get` on an identity this diagram does not hold gives nothing, and the picture it draws is
/// the one it drew before.
///
/// The identity is one another diagram issued rather than one never issued at all.
#[test]
fn get_on_an_identity_from_another_diagram_gives_nothing_and_changes_nothing() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let mut diagram = Diagram::new();
diagram = diagram.add(a).0;
diagram = diagram.add(b).0;
let before = draw_of(&diagram, origin, size);
assert_eq!(diagram.get(a_foreign_identity()), None);
assert_eq!(cells(&before), cells(&draw_of(&diagram, origin, size)));
}
/// A diagram of several figures, drawn before and after one is taken out, produces different
/// buffers, and the figures that stayed draw exactly what they drew on their own.
///
/// Three overlapping boxes rather than a row, and the one taken out is the first of the three
/// rather than a figure in the middle. That is what makes the test say something a swap with
/// the last entry could not pass: closing the gap leaves the survivors in the order they were,
/// so the one that was in front is still in front, and swapping the removed entry with the
/// back-most would hand the diagram the other two pictures instead.
#[test]
fn taking_a_shape_out_changes_the_picture_and_leaves_the_rest_drawing_what_they_drew() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (first, second, third) = three_overlapping_boxes();
let diagram = Diagram::new();
let (mut diagram, taken_out) = diagram.add(first.clone());
diagram = diagram.add(second.clone()).0;
diagram = diagram.add(third.clone()).0;
let before = draw_of(&diagram, origin, size);
diagram = diagram.remove(taken_out);
let after = draw_of(&diagram, origin, size);
assert_ne!(cells(&before), cells(&after));
assert_eq!(
cells(&after),
cells(&drawn(vec![second, third], origin, size))
);
}
/// Taking out an identity this diagram does not hold leaves the buffer exactly as it was,
/// with no error, no report and no panic. The identity is one another diagram issued, which is
/// the case worth running: a well-formed value that matches nothing here.
#[test]
fn taking_out_an_identity_from_another_diagram_changes_nothing_and_does_not_panic() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let mut diagram = Diagram::new();
diagram = diagram.add(a).0;
diagram = diagram.add(b).0;
let before = draw_of(&diagram, origin, size);
diagram = diagram.remove(a_foreign_identity());
assert_eq!(cells(&before), cells(&draw_of(&diagram, origin, size)));
}
/// Take `1` out, add a figure, and the identity handed back is `3` rather than `1`.
///
/// Asserted by the identity's own text rather than by a picture, and it needs no code beyond
/// the absence of a decrement, because `add` already increments before use.
#[test]
fn an_identity_is_never_handed_out_again_after_a_removal() {
let a_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
};
let diagram = Diagram::new();
let (mut diagram, first) = diagram.add(a_line());
diagram = diagram.add(a_line()).0;
assert_eq!(first.to_string(), "1");
diagram = diagram.remove(first);
let (_, after_the_removal) = diagram.add(a_line());
assert_eq!(after_the_removal.to_string(), "3");
}
/// Edge case: the last shape taken out leaves an empty diagram, and drawing an empty diagram
/// leaves the buffer as it was. The rule `an_empty_diagram_leaves_its_buffer_untouched` already
/// pins, reached here through a removal rather than through a diagram never given anything.
#[test]
fn taking_out_the_last_shape_leaves_an_empty_diagram() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, _b) = overlapping_boxes();
let diagram = Diagram::new();
let (mut diagram, only) = diagram.add(a);
diagram = diagram.remove(only);
assert_eq!(
cells(&draw_of(&diagram, origin, size)),
vec![None; (size.width * size.height) as usize]
);
}
/// A box put back as a wider box draws exactly what that wider box added on its own produces.
///
/// Pinned against the wider box's own picture rather than against the box it replaced, which is
/// what makes the claim about the figure handed in and not about a difference between two.
#[test]
fn a_box_put_back_as_a_wider_box_draws_that_wider_box() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 9,
height: 3,
};
let box_of = |width: u16| Shape::Box {
at: Pos { x: 1, y: 0 },
size: Size { width, height: 3 },
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
text: None,
};
let diagram = Diagram::new();
let (mut diagram, id) = diagram.add(box_of(4));
diagram = diagram.replace(id, box_of(7));
assert_eq!(
cells(&draw_of(&diagram, origin, size)),
cells(&drawn(vec![box_of(7)], origin, size))
);
}
/// A box put back as a line draws the line, kind included, and nothing of the previous figure
/// survives.
///
/// The pair the specification draws by hand and calls hypothetical, each side pinned against
/// the figure handed in rather than against the other, which is what turns "nothing of the
/// previous figure survives" into a checked claim rather than a comparison of two pictures.
#[test]
fn a_box_put_back_as_a_line_draws_the_line() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 4,
height: 3,
};
let the_box = || Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
text: None,
};
let the_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 4,
orientation: Orientation::Horizontal,
stroke: light(),
};
let diagram = Diagram::new();
let (mut diagram, id) = diagram.add(the_box());
diagram = diagram.replace(id, the_line());
assert_eq!(
cells(&draw_of(&diagram, origin, size)),
cells(&drawn(vec![the_line()], origin, size))
);
}
/// A figure overlapping another, put back under its own identity unchanged, resolves the
/// overlap as it did.
///
/// This is what shows a replacement is not a reorder, and the second assertion says so
/// directly: it holds up the order a remove-and-add would have produced as the picture that
/// replacement must **not** draw. Two figures would not have been enough, since removing the
/// front-most of two and adding it back leaves the order it was.
#[test]
fn a_figure_put_back_unchanged_resolves_its_overlap_as_it_did() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b, c) = three_overlapping_boxes();
let mut diagram = Diagram::new();
diagram = diagram.add(a.clone()).0;
let (mut diagram, middle) = diagram.add(b.clone());
diagram = diagram.add(c.clone()).0;
let before = draw_of(&diagram, origin, size);
diagram = diagram.replace(middle, b.clone());
let after = draw_of(&diagram, origin, size);
assert_eq!(cells(&before), cells(&after));
assert_ne!(cells(&after), cells(&drawn(vec![a, c, b], origin, size)));
}
/// A shape put under an identity this diagram does not hold leaves the picture alone **and
/// adds nothing**.
///
/// The figure handed in is placed where it would be plainly visible, so a `replace` that fell
/// back to removing the old entry and adding the new one would fail on the picture rather than
/// on a count. The identity assertion is the other half: `1` still names the figure it always
/// named, so there is no way to name a shape into existence.
#[test]
fn a_shape_put_under_a_foreign_identity_is_neither_drawn_nor_added() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 6,
height: 4,
};
let (a, b) = overlapping_boxes();
let mut diagram = Diagram::new();
diagram = diagram.add(a.clone()).0;
diagram = diagram.add(b).0;
let before = draw_of(&diagram, origin, size);
diagram = diagram.replace(
a_foreign_identity(),
Shape::Box {
at: Pos { x: 1, y: 1 },
size: Size {
width: 3,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("\"░\" is one glyph")),
text: None,
},
);
let after = draw_of(&diagram, origin, size);
assert_eq!(cells(&before), cells(&after));
assert_eq!(diagram.get(identity(1)), Some(&a));
}
/// Draw, displace, `replace`, and the picture is the one the same three figures draw with the
/// middle one standing where the displacement put it.
///
/// It lands beside the replacement rather than beside the displacement because it is the half
/// that needs `replace` to exist. The reach is then pinned by coordinates: the cells the
/// figure held before and the cells it holds now, and not one more. A change reaching a cell
/// of either box, which is what a move implemented as a removal and an addition would do, is
/// outside that set.
#[test]
fn putting_a_displaced_figure_back_reaches_only_the_cells_that_figure_holds() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 11,
height: 3,
};
let filled_box = |x: i16, fill: &str| Shape::Box {
at: Pos { x, y: 0 },
size: Size {
width: 3,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new(fill).expect("one glyph")),
text: None,
};
let the_line = |x: i16| Shape::Line {
at: Pos { x, y: 1 },
len: 5,
orientation: Orientation::Horizontal,
stroke: light(),
};
let mut diagram = Diagram::new();
diagram = diagram.add(filled_box(0, "░")).0;
let (mut diagram, middle) = diagram.add(the_line(3));
diagram = diagram.add(filled_box(8, "▓")).0;
let before = draw_of(&diagram, origin, size);
let moved = the_line(3).displaced_by(Delta { dx: 2, dy: 0 });
diagram = diagram.replace(middle, moved.clone());
let after = draw_of(&diagram, origin, size);
assert_eq!(
cells(&after),
cells(&drawn(
vec![filled_box(0, "░"), moved, filled_box(8, "▓")],
origin,
size
))
);
let held_by_the_line = |at: Pos| at.y == 1 && (3..=9).contains(&at.x);
let reached = differing(&before, &after);
assert!(
!reached.is_empty(),
"the displacement reached nothing at all"
);
assert!(
reached.iter().all(|at| held_by_the_line(*at)),
"the change reached outside the displaced figure: {reached:?}"
);
}
// ----------------------------------------- an endpoint that hangs from another figure's side
/// The box every case below hangs an endpoint from: four by three at the origin, so its right
/// side center is `{3, 1}` — the point the shipped demonstration's connector already holds, and
/// the one the model shows an endpoint attached at.
const THE_SIDE_CENTRE: Pos = Pos { x: 3, y: 1 };
fn the_box() -> Shape {
Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
}
}
fn endpoint_from_position(
position: Position,
leaving: Direction,
terminal: Terminal,
) -> Endpoint {
match position {
Position::Absolute(at) => Endpoint::absolute(at, leaving, terminal),
Position::Reference(reference) => Endpoint::reference(reference, terminal),
}
}
/// A connector with both ends as arms and the given positions, so a picture's difference is the
/// route and the two cells it starts and ends on, and nothing else about how a terminal draws.
///
/// The directions are the caller's rather than the anchor's (§6 _Attachment_), so a case that
/// puts the reference in the other slot has to name them the other way round rather than reuse
/// these: a connector leaving rightward from its far end takes a different route, and one that
/// did is testing the direction rather than the anchor.
fn arm_connector(from: Position, to: Position) -> Shape {
connector_leaving(from, Direction::Right, to, Direction::Left)
}
fn connector_leaving(
from: Position,
leaving: Direction,
to: Position,
arriving: Direction,
) -> Shape {
Shape::Connector {
from: endpoint_from_position(from, leaving, Terminal::Arm),
to: endpoint_from_position(to, arriving, Terminal::Arm),
stroke: light(),
}
}
/// A second box that has nothing to do with either end, placed clear of everything else so that
/// "this other figure drew exactly what it drew" is readable.
fn the_unrelated_box() -> Shape {
Shape::Box {
at: Pos { x: 9, y: 0 },
size: Size {
width: 3,
height: 3,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("one glyph")),
text: None,
}
}
/// The window the cases below are drawn in.
fn the_window() -> Window {
Window {
origin: Pos { x: 0, y: 0 },
size: Size {
width: 13,
height: 4,
},
}
}
/// The glyph the picture of `buffer` shows at `at`, so that a claim about a cell's character is
/// made against the light table rather than against the arms it composes from.
///
/// The two claims this crate's own pictures are made of — a junction where a border meets an
/// arm, and a run where an arm stands alone — are claims about glyphs, and a cell read as arms
/// would state them in the substrate's own vocabulary instead.
fn the_glyph_at(buffer: &Buffer, at: Pos) -> char {
let window = buffer.window();
let picture = render(buffer, &GlyphCatalog::light(), window);
picture
.lines()
.nth(at.y.cast_unsigned() as usize)
.and_then(|row| row.chars().nth(at.x.cast_unsigned() as usize))
.unwrap_or_else(|| panic!("{at:?} is inside the window {window:?}"))
}
/// The connector of _an endpoint hangs from a side_ with its `from` named as a **reference** to
/// the box's right side at the given offset and its `to` a plain point, which is the
/// arrangement the removal cases below all start from.
fn hanging_from(box_id: ShapeId, offset: Delta, to: Pos) -> Shape {
arm_connector(
Position::Reference(Reference::new(box_id, Anchor::Right, offset, 0)),
to.into(),
)
}
/// A connector whose `from` hangs from a box's right side draws exactly what the same
/// connector with `from` at that point draws.
///
/// Each side is pinned against the point rather than against the other, which is what keeps a
/// reference resolving to the wrong place from passing on a pair that are wrong together. So the
/// coordinates are asserted first and the picture second: `resolve` has to be `{3, 1}` on its
/// own account, and only then do the two drawings have to agree.
#[test]
fn a_hanging_endpoint_draws_what_the_point_it_resolves_to_draws() {
let Window { origin, size } = the_window();
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
let hanging = arm_connector(
Position::Reference(Reference::new(
box_id,
Anchor::Right,
Delta { dx: 0, dy: 0 },
0,
)),
Pos { x: 8, y: 1 }.into(),
);
diagram = diagram.add(hanging.clone()).0;
// Pinned by coordinates first: a reference that resolved anywhere else fails here.
let Shape::Connector { from, .. } = &hanging else {
unreachable!("the figure above is a connector")
};
assert_eq!(from.resolve(&diagram), Some(THE_SIDE_CENTRE));
let mut absolute = Diagram::new();
absolute = absolute.add(the_box()).0;
absolute = absolute
.add(arm_connector(
THE_SIDE_CENTRE.into(),
Pos { x: 8, y: 1 }.into(),
))
.0;
assert_eq!(
cells(&draw_of(&diagram, origin, size)),
cells(&draw_of(&absolute, origin, size))
);
}
/// A reference standing two cells clear of a side draws exactly what the same connector
/// standing at the point it resolves to draws.
///
/// The partner of the zero-offset test above rather than a replacement of it, and the reason is
/// what each one catches. That test's offset is zero on both axes, so a `resolve` that added
/// nothing at all would satisfy it; this one's offset is two cells on the x, so the same failure
/// draws its route from `{3, 1}` instead of `{5, 1}` and the two pictures stop agreeing.
///
/// The coordinates are asserted **before** the picture, each against the absolute point: `resolve`
/// has to be `{5, 1}` on its own account before the two drawings are asked to agree, so a
/// reference that resolved to the wrong place cannot pass on a pair that is wrong together.
#[test]
fn an_offset_endpoint_draws_what_the_point_it_resolves_to_draws() {
let Window { origin, size } = the_window();
let the_far_end = Pos { x: 8, y: 1 };
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
let offset = Delta { dx: 2, dy: 0 };
let hanging = arm_connector(
Position::Reference(Reference::new(box_id, Anchor::Right, offset, 0)),
the_far_end.into(),
);
diagram = diagram.add(hanging.clone()).0;
// Pinned by coordinates first: `{3, 1}` is the side centre and the offset is two cells right
// of it, so a `resolve` that ignored the field fails here rather than in the picture below.
let Shape::Connector { from, .. } = &hanging else {
unreachable!("the figure above is a connector")
};
assert_eq!(from.resolve(&diagram), Some(Pos { x: 5, y: 1 }));
assert_ne!(from.resolve(&diagram), Some(THE_SIDE_CENTRE));
assert_ne!(
from.at,
EndpointAt::Absolute {
at: Pos { x: 5, y: 1 },
leaving: Direction::Right,
}
);
let mut absolute = Diagram::new();
absolute = absolute.add(the_box()).0;
absolute = absolute
.add(arm_connector(Pos { x: 5, y: 1 }.into(), the_far_end.into()))
.0;
assert_eq!(
cells(&draw_of(&diagram, origin, size)),
cells(&draw_of(&absolute, origin, size))
);
}
/// The offset is a gap **from the side**, so displacing the figure a reference hangs from
/// carries the endpoint with it and the gap does not change.
///
/// The expected picture is built from the two positions — the box where it landed and the
/// connector starting at the point the reference resolves to *there* — rather than pinned as
/// text, so what is claimed is where a displacement puts a figure and not how a connector draws.
/// With the box four cells right its right side centre is `{7, 1}`, and the unchanged offset of
/// two carries the endpoint to `{9, 1}`: the same two cells of gap as before, not the same two
/// columns of the canvas.
///
/// The `assert_ne!`s are what make the picture comparison mean anything here. A `resolve` that
/// ignored the field would still draw a valid connector in this window, because `{7, 1}` is
/// still a cell a route can start from — the picture alone would let it pass.
#[test]
fn a_displaced_box_carries_an_offset_endpoint_with_it_and_the_gap_does_not_change() {
let Window { origin, size } = the_window();
let the_far_end = Pos { x: 11, y: 1 };
let offset = Delta { dx: 2, dy: 0 };
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
let hanging = arm_connector(
Position::Reference(Reference::new(box_id, Anchor::Right, offset, 0)),
the_far_end.into(),
);
diagram = diagram.add(hanging).0;
// Which endpoint the hanging connector resolves to, asked the way the drawing asks it.
let the_hanging_end = |d: &Diagram| {
let Shape::Connector { from, .. } = d
.get(identity(2))
.expect("the connector is the second figure")
else {
unreachable!("the figure under test is a connector")
};
from.resolve(d)
};
assert_eq!(the_hanging_end(&diagram), Some(Pos { x: 5, y: 1 }));
assert_ne!(the_hanging_end(&diagram), Some(THE_SIDE_CENTRE));
let before = draw_of(&diagram, origin, size);
let moved = the_box().displaced_by(Delta { dx: 4, dy: 0 });
diagram = diagram.replace(box_id, moved);
let after = draw_of(&diagram, origin, size);
// The same two figures with the box where it landed and the endpoint at the point the
// reference resolves to now: `{7, 1}` plus the unchanged two cells.
let mut expected = Diagram::new();
expected = expected
.add(the_box().displaced_by(Delta { dx: 4, dy: 0 }))
.0;
expected = expected
.add(arm_connector(Pos { x: 9, y: 1 }.into(), the_far_end.into()))
.0;
assert_eq!(cells(&after), cells(&draw_of(&expected, origin, size)));
// The gap, pinned by coordinate rather than by eye: the endpoint moved by the same four
// cells the box did, and it is not where the side centre alone would leave it.
assert_eq!(the_hanging_end(&diagram), Some(Pos { x: 9, y: 1 }));
assert_ne!(the_hanging_end(&diagram), Some(Pos { x: 7, y: 1 }));
let reached = differing(&before, &after);
assert!(
!reached.is_empty(),
"the displacement reached nothing at all"
);
assert!(
reached.iter().all(|at| at.x <= the_far_end.x),
"the change reached past the endpoint that did not move: {reached:?}"
);
}
/// A box **replaced by a line** under an offset adds it to the line's own side middle, not to
/// the place the box stood.
///
/// It takes a non-zero `dy` to tell the two apart. A horizontal line read as a flat box is one
/// cell tall, so its top and bottom centres are **the same point asked twice** — the offset is
/// added to that one answer and not to two — and with `dy: 0` the endpoint would land on the
/// line's own row, where a `resolve` that had used the *box's* old bottom centre `{1, 2}` would
/// differ. So the two candidate answers are `{2, 1}` and `{1, 2}`: different cells, neither the
/// other, and the assertion cannot pass on a pair that is wrong together.
#[test]
fn an_offset_on_a_line_is_added_to_the_lines_own_middle_not_where_the_box_stood() {
let Window { origin, size } = the_window();
let the_far_end = Pos { x: 8, y: 2 };
let offset = Delta { dx: 0, dy: 1 };
let the_box_s_own_bottom = Pos { x: 1, y: 2 };
let the_line = Shape::Line {
at: Pos { x: 0, y: 0 },
len: 5,
orientation: Orientation::Horizontal,
stroke: light(),
};
// The line's own bottom centre is `{2, 0}`, and the offset makes it `{2, 1}`.
assert_eq!(the_line.anchor(Anchor::Bottom), Some(Pos { x: 2, y: 0 }));
assert_eq!(the_line.anchor(Anchor::Top), Some(Pos { x: 2, y: 0 }));
let the_line_endpoint = offset.apply(
the_line
.anchor(Anchor::Bottom)
.expect("a line answers every anchor"),
);
assert_eq!(the_line_endpoint, Pos { x: 2, y: 1 });
assert_ne!(the_line_endpoint, the_box_s_own_bottom);
// The same line, three ways, and no two of them against each other: the reference a line
// holds, the point that reference resolves to, and the diagram where a box was replaced.
let with_the_reference = || {
let d = Diagram::new();
let (mut d, id) = d.add(the_line.clone());
d = d
.add(arm_connector(
Position::Reference(Reference::new(id, Anchor::Bottom, offset, 0)),
the_far_end.into(),
))
.0;
d
};
let mut with_the_point = Diagram::new();
with_the_point = with_the_point.add(the_line.clone()).0;
with_the_point = with_the_point
.add(connector_leaving(
the_line_endpoint.into(),
Direction::Down,
the_far_end.into(),
Direction::Left,
))
.0;
let replaced = Diagram::new();
let (mut replaced, identity) = replaced.add(the_box());
replaced = replaced
.add(arm_connector(
Position::Reference(Reference::new(identity, Anchor::Bottom, offset, 0)),
the_far_end.into(),
))
.0;
// `replace` swaps the kind under the identity the reference already names, so the offset is
// held unchanged across a change of what stands there.
replaced = replaced.replace(identity, the_line.clone());
assert_eq!(
cells(&draw_of(&with_the_reference(), origin, size)),
cells(&draw_of(&with_the_point, origin, size)),
"a reference on a line drew something other than the point it resolves to"
);
assert_eq!(
cells(&draw_of(&replaced, origin, size)),
cells(&draw_of(&with_the_point, origin, size)),
"a replaced box left the offset on the box's old side middle"
);
}
/// A large offset on a reference that resolves to nothing is still nothing — asked twice,
/// and by drawing.
///
/// Twice because there are two different ways not to resolve and they are not the same code: an
/// identity no `add` ever issued, and an anchor a kind does not answer — here a connector, which
/// is the answer that keeps a chain of references one link long. Each carries an offset big
/// enough to be somewhere, because an offset of nothing is the case the zero-offset tests above
/// already hold.
///
/// Each asserts two things together and the second is what makes the first mean anything: the
/// connector is **absent from the output**, and every other figure's cells are unchanged. That
/// second half is what distinguishes "the connector is not drawn" from "the drawing stopped", and
/// a connector drawn partly passes the first alone.
#[test]
fn a_large_offset_on_a_reference_that_resolves_to_nothing_draws_nothing_either() {
let Window { origin, size } = the_window();
let large = Delta { dx: 6, dy: 2 };
let the_other_end: Position = Pos { x: 8, y: 1 }.into();
let unrelated = the_unrelated_box();
let cases = [
(
"an identity nothing holds",
Position::Reference(Reference::new(
a_foreign_identity(),
Anchor::Right,
large,
0,
)),
),
(
"a kind that answers no anchor",
Position::Reference(Reference::new(identity(3), Anchor::Right, large, 0)),
),
];
for (what, hanging) in cases {
let mut with_it = Diagram::new();
with_it = with_it.add(the_box()).0;
with_it = with_it.add(unrelated.clone()).0;
// A connector, so that a reference naming it asks a kind that answers no anchor.
with_it = with_it
.add(arm_connector(
Pos { x: 0, y: 3 }.into(),
Pos { x: 12, y: 3 }.into(),
))
.0;
with_it = with_it.add(arm_connector(hanging, the_other_end)).0;
let mut without_it = Diagram::new();
without_it = without_it.add(the_box()).0;
without_it = without_it.add(unrelated.clone()).0;
without_it = without_it
.add(arm_connector(
Pos { x: 0, y: 3 }.into(),
Pos { x: 12, y: 3 }.into(),
))
.0;
assert_eq!(
cells(&draw_of(&with_it, origin, size)),
cells(&draw_of(&without_it, origin, size)),
"{what} drew something, or drew something else"
);
}
// The other figure's cells are still there, which is the half that tells a whole figure
// missing from a drawing that stopped.
let drawing = draw_of(
&{
let mut d = Diagram::new();
d = d.add(the_box()).0;
d = d.add(unrelated.clone()).0;
d = d
.add(arm_connector(
Pos { x: 0, y: 3 }.into(),
Pos { x: 12, y: 3 }.into(),
))
.0;
d = d
.add(arm_connector(
Position::Reference(Reference::new(
a_foreign_identity(),
Anchor::Right,
large,
0,
)),
the_other_end,
))
.0;
d
},
origin,
size,
);
assert!(
drawing
.cell(
the_unrelated_box()
.anchor(Anchor::Top)
.expect("a box answers every anchor")
)
.is_some(),
"the drawing stopped rather than the connector being skipped"
);
}
/// A box **one cell wide** with an offset — its two coincident side centres get the offset
/// added once, and the offset is what separates them afterwards.
///
/// The degenerate figure is what an implementation that special-cased the ordinary box gets
/// wrong, and `a_box_one_cell_wide_or_one_cell_tall_answers_the_same_rule` in `position.rs`
/// is why the general rule is the claim rather than the coincidence. At width 1 the left and
/// right centres are the same cell, so a `resolve` that added the offset once per *side* rather
/// than once per *reference* would land two cells out; and an implementation that measured the
/// offset against the side it is named for would find two sides and no way to tell them apart.
#[test]
fn a_box_one_cell_wide_takes_the_offset_once_and_the_offset_separates_its_two_sides() {
let Window { origin, size } = the_window();
let the_far_end = Pos { x: 8, y: 2 };
let offset = Delta { dx: 3, dy: 1 };
let one_wide = Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 1,
height: 3,
},
stroke: light(),
fill: None,
text: None,
};
// The two centres coincide before the offset, and the offset is added to that one answer.
assert_eq!(one_wide.anchor(Anchor::Left), Some(Pos { x: 0, y: 1 }));
assert_eq!(one_wide.anchor(Anchor::Right), Some(Pos { x: 0, y: 1 }));
assert_eq!(offset.apply(Pos { x: 0, y: 1 }), Pos { x: 3, y: 2 });
for (what, anchor) in [("left", Anchor::Left), ("right", Anchor::Right)] {
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(one_wide.clone());
let hanging = arm_connector(
Position::Reference(Reference::new(box_id, anchor, offset, 0)),
the_far_end.into(),
);
diagram = diagram.add(hanging.clone()).0;
let Shape::Connector { from, .. } = &hanging else {
unreachable!("the figure above is a connector")
};
assert_eq!(
from.resolve(&diagram),
Some(Pos { x: 3, y: 2 }),
"the {what} side of a one-cell-wide box resolves to the offset once, not twice"
);
let mut absolute = Diagram::new();
absolute = absolute.add(one_wide.clone()).0;
absolute = absolute
.add(connector_leaving(
Pos { x: 3, y: 2 }.into(),
anchor.leaving(),
the_far_end.into(),
Direction::Left,
))
.0;
assert_eq!(
cells(&draw_of(&diagram, origin, size)),
cells(&draw_of(&absolute, origin, size)),
"the {what} side drew something else"
);
}
}
/// Displacing the box four cells right takes the hanging end with it, re-routes the connector
/// to the end that did not move, and touches nothing else.
///
/// The expected picture is built from the two positions rather than pinned as text, so what is
/// claimed is where a displacement puts a figure and not how a connector draws. The reach is
/// then pinned by coordinates: no column past the far endpoint moved, and that endpoint's own
/// cell is byte-identical before and after. A resolution cached when the diagram was built
/// rather than asked when it is drawn passes the first comparison and fails both of these.
#[test]
fn a_displaced_box_takes_the_endpoint_hanging_from_it_along() {
let Window { origin, size } = the_window();
let the_far_end = Pos { x: 11, y: 1 };
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
diagram = diagram
.add(arm_connector(
Position::Reference(Reference::new(
box_id,
Anchor::Right,
Delta { dx: 0, dy: 0 },
0,
)),
the_far_end.into(),
))
.0;
let before = draw_of(&diagram, origin, size);
let moved = the_box().displaced_by(Delta { dx: 4, dy: 0 });
diagram = diagram.replace(box_id, moved);
let after = draw_of(&diagram, origin, size);
// The same two figures with the box where it landed and the endpoint at the point the
// reference now resolves to: `{7, 1}`, four cells right of where it resolved before.
let mut expected = Diagram::new();
expected = expected
.add(Shape::Box {
at: Pos { x: 4, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
})
.0;
expected = expected
.add(arm_connector(Pos { x: 7, y: 1 }.into(), the_far_end.into()))
.0;
assert_eq!(cells(&after), cells(&draw_of(&expected, origin, size)));
let reached = differing(&before, &after);
assert!(
!reached.is_empty(),
"the displacement reached nothing at all"
);
assert!(
reached.iter().all(|at| at.x <= the_far_end.x),
"the change reached past the endpoint that did not move: {reached:?}"
);
assert_eq!(
before.cell(the_far_end),
after.cell(the_far_end),
"the endpoint that did not move was drawn differently"
);
}
/// A connector with one endpoint absolute and one hanging, each placed by its own rule.
///
/// Both orders, because the two positions are the same field with different rules and a match
/// written to suit one of them is the failure this case is for. Nothing here is pinned against
/// the other arrangement: each is pinned against the same connector with both points absolute.
#[test]
fn a_connector_places_each_of_its_ends_by_its_own_rule() {
let Window { origin, size } = the_window();
// A box whose **bottom** side center is `{7, 2}`, so the two ends of the route below are
// `{0, 2}` and `{7, 2}` and neither is the other.
let the_held_box = || Shape::Box {
at: Pos { x: 6, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
};
let the_far_end = Pos { x: 0, y: 2 };
let the_hanging_end = Pos { x: 7, y: 2 };
// Each case is pinned against the same route with both ends named as points, and never
// against the other case: a connector with its reference in the other slot leaves and
// arrives the other way round, so the two are different routes and saying so is the point.
let expected = |origin: Pos, size: Size| {
let mut diagram = Diagram::new();
diagram = diagram.add(the_held_box()).0;
diagram = diagram
.add(connector_leaving(
the_far_end.into(),
Direction::Right,
the_hanging_end.into(),
Direction::Down,
))
.0;
cells(&draw_of(&diagram, origin, size))
};
let expected_reversed = |origin: Pos, size: Size| {
let mut diagram = Diagram::new();
diagram = diagram.add(the_held_box()).0;
diagram = diagram
.add(connector_leaving(
the_hanging_end.into(),
Direction::Down,
the_far_end.into(),
Direction::Left,
))
.0;
cells(&draw_of(&diagram, origin, size))
};
let hanging_to = Diagram::new();
let (mut hanging_to, box_id) = hanging_to.add(the_held_box());
hanging_to = hanging_to
.add(arm_connector(
the_far_end.into(),
Position::Reference(Reference::new(
box_id,
Anchor::Bottom,
Delta { dx: 0, dy: 0 },
0,
)),
))
.0;
let hanging_from = Diagram::new();
let (mut hanging_from, box_id) = hanging_from.add(the_held_box());
hanging_from = hanging_from
.add(arm_connector(
Position::Reference(Reference::new(
box_id,
Anchor::Bottom,
Delta { dx: 0, dy: 0 },
0,
)),
the_far_end.into(),
))
.0;
assert_eq!(
cells(&draw_of(&hanging_to, origin, size)),
expected(origin, size)
);
assert_eq!(
cells(&draw_of(&hanging_from, origin, size)),
expected_reversed(origin, size)
);
}
/// The three ways a reference can fail to resolve: a reference to an identity this diagram
/// does not hold, a reference to a kind that answers no anchor, and a connector with one
/// endpoint that resolves and one that does not.
///
/// Each case asserts two things together, and the second is what makes the first mean anything.
/// The connector is **absent from the output**, and every other figure's cells are unchanged —
/// which is what distinguishes "the connector is not drawn" from "the drawing stopped". The
/// third case is the one a connector drawn partly would pass on the first half alone: half an
/// arm is a route with no head, and only the whole-picture comparison rules it out.
///
/// The three figures the endpoints do not touch are the same in every case, and the one the
/// third case's unresolvable reference names is a connector, which answers no anchor at all.
fn a_diagram_of_three_figures_and_maybe_a_fourth(under_test: Option<Shape>) -> Diagram {
let mut diagram = Diagram::new();
diagram = diagram.add(the_box()).0;
diagram = diagram.add(the_unrelated_box()).0;
// A connector, so that a reference naming it asks a kind that answers no anchor.
diagram = diagram
.add(arm_connector(
Pos { x: 0, y: 3 }.into(),
Pos { x: 12, y: 3 }.into(),
))
.0;
if let Some(shape) = under_test {
diagram = diagram.add(shape).0;
}
diagram
}
#[test]
fn a_connector_with_an_endpoint_that_does_not_resolve_is_not_drawn_at_all() {
let Window { origin, size } = the_window();
let unresolvable = Position::Reference(Reference::new(
a_foreign_identity(),
Anchor::Right,
Delta { dx: 0, dy: 0 },
0,
));
let answers_nothing = Position::Reference(Reference::new(
identity(3),
Anchor::Right,
Delta { dx: 0, dy: 0 },
0,
));
let the_other_end: Position = Pos { x: 8, y: 1 }.into();
let cases = [
("an identity nothing holds", unresolvable, the_other_end),
(
"a kind that answers no anchor",
Pos { x: 5, y: 2 }.into(),
answers_nothing,
),
(
"one end that resolves and one that does not",
unresolvable,
the_other_end,
),
];
for (what, from, to) in cases {
let with_it =
a_diagram_of_three_figures_and_maybe_a_fourth(Some(arm_connector(from, to)));
let without_it = a_diagram_of_three_figures_and_maybe_a_fourth(None);
assert_eq!(
cells(&draw_of(&with_it, origin, size)),
cells(&draw_of(&without_it, origin, size)),
"{what} drew something, or drew something else"
);
}
}
/// A reference to an identity nothing holds yet, and then a figure added under it — three
/// kinds, because a kind answers anchors differently.
///
/// The identity is spelled rather than read back, and **the connector is the first figure
/// added** so that the figure under test is the one the counter names next. That is what makes
/// the case reachable at all: a diagram offers no way to name a shape into existence, so a
/// spelled identity can only ever be the one an `add` is about to issue. Nothing holds it at
/// first and the hanging connector draws nothing; then a figure arrives and the same reference
/// finds it.
///
/// A `Box` answers, a `Line` answers as a flat box, and a `Connector` does not answer at all —
/// which is the same picture as a reference to a shape that was never there.
#[test]
fn a_figure_added_under_a_spelled_identity_is_what_a_hanging_endpoint_finds() {
let Window { origin, size } = the_window();
let spelled = identity(2);
let the_far_end: Position = Pos { x: 11, y: 1 }.into();
let the_filler = || arm_connector(Pos { x: 0, y: 0 }.into(), Pos { x: 1, y: 0 }.into());
let hanging = |anchor| {
arm_connector(
Position::Reference(Reference::new(spelled, anchor, Delta { dx: 0, dy: 0 }, 0)),
the_far_end,
)
};
// Nothing holds `2` yet, so the hanging connector draws nothing at all.
let mut nothing_under_it = Diagram::new();
nothing_under_it = nothing_under_it.add(hanging(Anchor::Right)).0;
nothing_under_it = nothing_under_it.add(the_filler()).0;
let mut just_the_filler = Diagram::new();
just_the_filler = just_the_filler.add(the_filler()).0;
assert_eq!(
cells(&draw_of(¬hing_under_it, origin, size)),
cells(&draw_of(&just_the_filler, origin, size)),
"a reference to nothing drew something"
);
// A box takes `2`, and the connector hangs from its right side.
let mut with_a_box = Diagram::new();
with_a_box = with_a_box.add(hanging(Anchor::Right)).0;
with_a_box = with_a_box.add(the_box()).0;
with_a_box = with_a_box.add(the_filler()).0;
let mut absolute_after_a_box = Diagram::new();
absolute_after_a_box = absolute_after_a_box.add(the_filler()).0;
absolute_after_a_box = absolute_after_a_box.add(the_box()).0;
absolute_after_a_box = absolute_after_a_box
.add(arm_connector(THE_SIDE_CENTRE.into(), the_far_end))
.0;
assert_eq!(
cells(&draw_of(&with_a_box, origin, size)),
cells(&draw_of(&absolute_after_a_box, origin, size)),
"a box under a spelled identity is not where a reference finds it"
);
// A line takes `2` instead, and the connector lands on the line's own far end — read as a
// box one cell thick, a five-cell line's right side center is its last cell.
let the_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 5,
orientation: Orientation::Horizontal,
stroke: light(),
};
let mut with_a_line = Diagram::new();
with_a_line = with_a_line.add(hanging(Anchor::Right)).0;
with_a_line = with_a_line.add(the_line()).0;
with_a_line = with_a_line.add(the_filler()).0;
let mut absolute_after_a_line = Diagram::new();
absolute_after_a_line = absolute_after_a_line.add(the_filler()).0;
absolute_after_a_line = absolute_after_a_line.add(the_line()).0;
absolute_after_a_line = absolute_after_a_line
.add(arm_connector(Pos { x: 4, y: 0 }.into(), the_far_end))
.0;
assert_eq!(
cells(&draw_of(&with_a_line, origin, size)),
cells(&draw_of(&absolute_after_a_line, origin, size)),
"a line under a spelled identity is not where a reference finds it"
);
// A connector takes `2`, and the hanging connector stops drawing — the same answer as
// before there was anything under the identity at all.
let mut with_a_connector = Diagram::new();
with_a_connector = with_a_connector.add(hanging(Anchor::Right)).0;
with_a_connector = with_a_connector.add(the_filler()).0;
assert_eq!(
cells(&draw_of(&with_a_connector, origin, size)),
cells(&draw_of(&just_the_filler, origin, size)),
"a connector under a spelled identity still answered an anchor"
);
}
/// The claim the conversion's own test used to carry: a connector with a glyph terminal and a
/// connector with an arm, each drawn through a diagram, produce the buffer the same core
/// `Connector` drawn directly produces.
///
/// A stronger pin than the conversion was, because it goes through the four lines that built it
/// rather than naming them: a terminal or a direction dropped on the way would change the
/// drawing, and the drawing is what is compared.
#[test]
fn a_connector_with_either_terminal_reaches_the_core_whole() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 8,
height: 3,
};
let glyph = |text: &str| Terminal::Glyph {
glyph: Glyph::new(text).expect("one glyph"),
};
for (from_terminal, to_terminal) in
[(glyph("◄"), glyph("►")), (Terminal::Arm, Terminal::Arm)]
{
let endpoint = |at: Pos, leaving: Direction, terminal: Terminal| {
Endpoint::absolute(at, leaving, terminal)
};
let from = endpoint(Pos { x: 0, y: 0 }, Direction::Down, from_terminal.clone());
let to = endpoint(Pos { x: 7, y: 2 }, Direction::Up, to_terminal.clone());
let mut diagram = Diagram::new();
diagram = diagram
.add(Shape::Connector {
from: from.clone(),
to: to.clone(),
stroke: light(),
})
.0;
let mut actual = Buffer::new(Window { origin, size });
diagram.draw(&mut actual);
let mut expected = Buffer::new(Window { origin, size });
Connector {
from: monospace_core::Endpoint {
at: Pos { x: 0, y: 0 },
leaving: Direction::Down,
terminal: from_terminal,
},
to: monospace_core::Endpoint {
at: Pos { x: 7, y: 2 },
leaving: Direction::Up,
terminal: to_terminal,
},
stroke: light(),
}
.draw(&mut FigureLayer::new(&mut expected, StampMode::Above));
assert_eq!(cells(&actual), cells(&expected));
}
}
/// Taking the referenced box out leaves the connector drawing **exactly what it drew**, and
/// leaves the figure that had nothing to do with either drawing exactly what it drew **on its
/// own**.
///
/// **This test used to say the opposite of both halves of its own name, and it was not among the
/// places the specification named.** It read `…_stops_the_connector_…` and asserted that the
/// connector drew nothing, which is true of the rule 142 reverses and false of the rule it
/// lands; and it pinned the whole picture against a diagram of the unrelated box alone, so the
/// second half of the name could not be said about the connector at all. It escaped the
/// inventory because it cited a rule by number and never named this issue, so `grep` for the
/// behavior rather than for the issue's number found the prose and not the test. 143 paid for
/// the same gap a fifth time in a different file. **It is rewritten rather than deleted**, and
/// the arrangement and `the_unrelated_box()` are kept: the box that had nothing to do with
/// either end is what makes the second half of the name mean something.
///
/// **Why this cannot be `assert_eq!` on the buffer and cannot be "nothing moved" either.** One
/// cell is the whole difference between the two pictures, and it is not one of the box's going
/// blank: `{3, 1}` is where the box's own right border used to compose with the arrow's arm into
/// one junction, so it read `├` while the box stood and reads `─` with the box gone — a cell
/// carrying one arm renders as the run through it. The box's other nine drawn cells go blank.
/// Measured, not derived: measurement corrected the specification's own `15 − 6 = 9` because
/// this cell changes glyph rather than going blank, and an asserted count in a test is what a
/// hand-drawn picture gets wrong.
///
/// The second half is pinned against that box's **own** picture rather than against the first
/// one, which is what makes the claim about the figures that stayed rather than a difference
/// between two drawings. It is also the part that is **accepted with nothing verifying it**:
/// "every other figure is byte for byte" is a claim about the whole diagram, and no single
/// arrangement establishes it for every diagram — which is why it is named here rather than
/// described as tested, which is what CONTRIBUTING.md asks for in that case.
#[test]
fn taking_the_referenced_figure_out_leaves_the_connector_where_it_was_and_changes_nothing_else()
{
let Window { origin, size } = the_window();
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
diagram = diagram
.add(hanging_from(
box_id,
Delta { dx: 0, dy: 0 },
Pos { x: 8, y: 1 },
))
.0;
diagram = diagram.add(the_unrelated_box()).0;
let before = draw_of(&diagram, origin, size);
assert_eq!(
the_glyph_at(&before, THE_SIDE_CENTRE),
'├',
"the box's border and the arrow's arm did not compose where they met"
);
diagram = diagram.remove(box_id);
let after = draw_of(&diagram, origin, size);
// The route is byte for byte what it was, and the ten cells the box held are the whole
// difference — nine of them blank and `{3, 1}` a different glyph.
assert_eq!(
differing(&before, &after),
vec![
Pos { x: 0, y: 0 },
Pos { x: 1, y: 0 },
Pos { x: 2, y: 0 },
Pos { x: 3, y: 0 },
Pos { x: 0, y: 1 },
THE_SIDE_CENTRE,
Pos { x: 0, y: 2 },
Pos { x: 1, y: 2 },
Pos { x: 2, y: 2 },
Pos { x: 3, y: 2 },
],
"the removal reached a cell the box did not hold, or left one of its own holding"
);
for x in 4..=8 {
let on_the_route = Pos { x, y: 1 };
assert_eq!(
before.cell(on_the_route),
after.cell(on_the_route),
"the route moved at {on_the_route:?}"
);
}
assert_eq!(
the_glyph_at(&after, THE_SIDE_CENTRE),
'─',
"the arm still standing on its own did not render as the run through it"
);
// The second half of the name: the figure that had nothing to do with either end drew
// **exactly** what it drew, and the whole picture is the arrow standing where it stood
// beside it. Built from the two figures rather than pinned as text, and the arrow is named
// at the point the reference resolved to rather than as a reference — which is the claim in
// one comparison, and is what this test could not say before the rule landed.
assert_eq!(
cells(&after),
cells(&drawn(
vec![
the_unrelated_box(),
arm_connector(THE_SIDE_CENTRE.into(), Pos { x: 8, y: 1 }.into()),
],
origin,
size
))
);
}
/// The endpoint the connector named by `id` hangs **from**, or `None` when the diagram holds no
/// such connector.
///
/// Borrowed rather than cloned, so a caller can hold the **resolved** point across a `remove`
/// and then ask what the end says afterwards — which is the only way "the point it was resolving
/// to" can be claimed about a moment that is gone once the figure is out.
fn the_hanging_end(diagram: &Diagram, id: ShapeId) -> Option<&Endpoint> {
let Shape::Connector { from, .. } = diagram.get(id)? else {
return None;
};
Some(from)
}
/// Taking the shape a reference names out leaves that end standing at the point it was
/// resolving to — **asked and then drawn**, in that order.
///
/// **By value first**, and the `assert_ne!` is what makes it mean anything: a body that froze
/// nothing leaves the endpoint holding the reference it already held, which is exactly what it
/// did before, so the first assertion alone would be satisfied by doing precisely nothing. The
/// point is resolved *before* the removal and held across it, because "the point it was
/// resolving to" is a claim about a moment that is gone once the figure is out.
///
/// **By picture, and the last claim is asserted as a difference rather than as a count.** The
/// cells the removed box held are **discovered** — every cell inside the box's own rectangle
/// that held something while it stood — and the cells the arrow writes are **discovered against
/// a no-connector baseline**, which is how the six-cell footprint was measured. The two
/// together say the whole picture in two comparisons without a number written down: the box's
/// cells are gone, nothing else moved, and every cell the arrow writes outside that rectangle
/// is byte for byte what it was. A quoted **10** would be the thing measurement found wrong —
/// it is `15 − 6` only for the nine that go blank, because `{3, 1}` changes glyph rather than
/// going blank, which is why the glyph is asserted rather than left to be counted.
#[test]
fn a_removal_freezes_what_hung_from_the_removed_shape() {
let Window { origin, size } = the_window();
let nothing = Delta { dx: 0, dy: 0 };
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
diagram = diagram
.add(hanging_from(box_id, nothing, Pos { x: 8, y: 1 }))
.0;
diagram = diagram.add(the_unrelated_box()).0;
let before = draw_of(&diagram, origin, size);
let it_resolved_to = the_hanging_end(&diagram, identity(2))
.expect("the reference resolves while the figure it names is held")
.resolve(&diagram)
.expect("the box answers the anchor the reference names");
assert_eq!(it_resolved_to, THE_SIDE_CENTRE);
diagram = diagram.remove(box_id);
let after = draw_of(&diagram, origin, size);
// By value: the end stands at the point it was resolving to, and is no longer a reference.
let frozen = the_hanging_end(&diagram, identity(2))
.expect("the connector is still held, so it is still drawn");
assert_eq!(
frozen.at,
EndpointAt::Absolute {
at: it_resolved_to,
leaving: Direction::Right,
},
"the end was not frozen at the point the reference was resolving to"
);
assert_ne!(
frozen.at,
EndpointAt::Reference(Reference::new(box_id, Anchor::Right, nothing, 0)),
"the end is still a reference, so nothing was frozen"
);
// By picture. What the box held is discovered rather than quoted, and what the arrow writes
// is discovered against a diagram holding no connector at all.
let in_the_box = |at: &Pos| (0..4).contains(&at.x) && (0..3).contains(&at.y);
let the_box_held: Vec<Pos> = differing(&before, &draw_of(&Diagram::new(), origin, size))
.into_iter()
.filter(in_the_box)
.collect();
assert!(
!the_box_held.is_empty(),
"the box held no cell, so nothing here is a claim about a removal"
);
for at in the_box_held.iter().filter(|at| **at != THE_SIDE_CENTRE) {
assert_eq!(
after.cell(*at),
None,
"a cell the removed box held is still written: {at:?}"
);
}
assert_eq!(
the_glyph_at(&after, THE_SIDE_CENTRE),
'─',
"the arm standing on its own did not render as the run through it"
);
let the_arrow_wrote = differing(&after, &drawn(vec![the_unrelated_box()], origin, size));
assert!(
!the_arrow_wrote.is_empty(),
"the arrow draws nothing at all, so this is not looking at a freeze"
);
for at in the_arrow_wrote.iter().filter(|at| !in_the_box(at)) {
assert_eq!(
before.cell(*at),
after.cell(*at),
"a cell of the arrow's route outside the box moved: {at:?}"
);
}
// And nothing else moved at all: the cells that differ are the box's own, and no others.
assert_eq!(
differing(&before, &after),
the_box_held,
"the removal reached a cell the removed box did not hold, or left one of its own holding"
);
}
/// A figure put back under the removed identity is **not re-hung from** — what hung from the
/// removed one stays where it was, and the identity stays the diagram's to issue.
///
/// Both behaviors in one test because both are about what comes back. The first half puts the
/// box back **in place** and the picture comes back byte for byte — the frozen point is the
/// point the reference was resolving to, so the same composition recurs — while `get` answers an
/// endpoint holding a plain point. **Nothing went looking for the reference it was**, and that
/// is the half a picture alone cannot say: a re-attachment that re-routed to the same place
/// would draw the same picture.
///
/// The second half is what a frozen position costs. A figure put back **displaced** under the
/// same identity does **not** take the arrow with it, because a frozen end is a point and a
/// displacement reaches any absolute position's coordinates — the very displacement that carries
/// a reference's endpoint. Nothing is broken by it and nothing is repaired; §4's rule is one-way
/// by construction rather than by a decision.
#[test]
fn a_shape_put_back_under_the_removed_identity_is_not_re_attached() {
let Window { origin, size } = the_window();
let the_far_end = Pos { x: 8, y: 1 };
let diagram = Diagram::new();
let (mut diagram, the_removed) = diagram.add(the_box());
diagram = diagram
.add(hanging_from(
the_removed,
Delta { dx: 0, dy: 0 },
the_far_end,
))
.0;
diagram = diagram.add(the_unrelated_box()).0;
let before = draw_of(&diagram, origin, size);
diagram = diagram.remove(the_removed);
diagram = diagram.add_under(the_removed, the_box());
let put_back = draw_of(&diagram, origin, size);
assert_eq!(
cells(&before),
cells(&put_back),
"putting the box back in place did not give back the whole picture"
);
assert_eq!(
the_hanging_end(&diagram, identity(2))
.expect("the connector is still held")
.at,
EndpointAt::Absolute {
at: THE_SIDE_CENTRE,
leaving: Direction::Right,
}
);
assert_ne!(
the_hanging_end(&diagram, identity(2))
.expect("the connector is still held")
.at,
EndpointAt::Reference(Reference::new(
the_removed,
Anchor::Right,
Delta { dx: 0, dy: 0 },
0,
)),
"the arrow was re-hung from a figure put back under the same identity"
);
diagram = diagram.replace(the_removed, the_box().displaced_by(Delta { dx: 0, dy: 2 }));
let displaced = draw_of(&diagram, origin, size);
// Two rows **down** rather than four right, and the direction is the point rather than
// taste: it puts the whole figure clear of the row the arrow runs along, so "the arrow did
// not go and find it" can be asked of a picture and not only of a value. Four right would
// stand the box across the route and answer a different question.
// The arm proper, from `{4, 1}` to `{8, 1}`. `{3, 1}` is excluded and deliberately so: it is the
// box's **own** border cell, what it composes into there is a property of both figures, and
// the box moving is exactly what the arrow must not be blamed for.
for x in 4..=8 {
let on_the_route = Pos { x, y: 1 };
assert_eq!(
put_back.cell(on_the_route),
displaced.cell(on_the_route),
"the arrow went and found the figure put back under the same identity at \
{on_the_route:?}"
);
}
assert_eq!(
the_hanging_end(&diagram, identity(2))
.expect("the connector is still held")
.at,
EndpointAt::Absolute {
at: THE_SIDE_CENTRE,
leaving: Direction::Right,
},
"the frozen end followed the figure put back under the same identity"
);
// And the identity is the diagram's to issue: `add_under` does not touch the counter, so a
// put-back does not un-issue what was taken out.
let (diagram, issued) = diagram.add(the_unrelated_box());
assert_eq!(
issued,
identity(4),
"a put-back under the removed identity handed that identity out again"
);
assert!(
draw_of(&diagram, origin, size)
.cell(THE_SIDE_CENTRE)
.is_some(),
"the arrow is no longer drawn, so nothing here is a claim about a freeze"
);
}
/// The three routes reach **three** pictures, and the reason is **not** the freeze any more: the
/// counter issues the identity the caller had already chosen, so two of the three diagrams lost
/// the figure they were built around before anything was removed.
///
/// **The issued identity is `1` in all three diagrams**, because `add` starts at `1` and the
/// caller's own `add_under(identity(1), …)` does not move the counter — so the box the last `add`
/// issued lands **on** the figure the hanging connector names, and that figure is not held
/// afterwards. It is the same collision as the repeated-identity case and the same one the model
/// does not mention: the counter issues an ordinal a caller is free to have chosen already.
///
/// An ordinal `add` issues is **one no figure is already under**, so the counter steps over
/// everything taken rather than naming a figure twice.
///
/// **The caller's figure is still there afterwards, and it is still what its identity names.**
/// That is the whole of the difference from naming it anyway: replacing would leave the issued
/// figure unreachable by identity and the caller's figure gone, with no error, no report and no
/// way to ask for it back, which is the one outcome nothing in this crate does.
///
/// **The counter steps over one and over two, rather than one.** A diagram with a single
/// ordinal taken would pass a loop that gave up after the first, and the picture below is the
/// same either way — so what is asserted is the identity handed back and what it is bound to.
/// **And the counter is left past the one it issued**, which is the last assertion and the one
/// that says the step is not repeated on every later addition.
///
/// The case this replaces held that the three routes to one picture reach three now, because an
/// issued identity replaced a caller's figure — the behavior this rule refuses, and the map
/// makes the search behind it a lookup rather than a scan. The freeze it was the control for is
/// held by `a_removal_freezes_what_hung_from_the_removed_shape` and
/// `two_connectors_from_one_figure_both_freeze_at_their_own_points`.
#[test]
fn add_steps_over_an_ordinal_a_figure_already_sits_under() {
let the_line = || Shape::Line {
at: Pos { x: 0, y: 0 },
len: 1,
orientation: Orientation::Horizontal,
stroke: light(),
};
// The specification's own case: seeded at 1, the caller has already written 1, and the
// addition is named 2 rather than nothing at all.
let (one_taken, issued) = Diagram::numbered_from(nz(1))
.add_under(identity(1), the_box())
.add(the_line());
assert_eq!(
issued.to_string(),
"2",
"the counter stepped over the ordinal a figure was already under"
);
assert_eq!(
one_taken.get(identity(1)),
Some(&the_box()),
"the caller's figure is still what its identity names, and it was not replaced"
);
assert_eq!(
one_taken.get(issued),
Some(&the_line()),
"and the issued figure is under the ordinal it was given rather than under nothing"
);
// The picture is the one a diagram holding both figures draws, which is the "rather than
// nothing at all" half of the rule said about cells rather than about identities.
let Window { origin, size } = the_window();
assert_eq!(
cells(&draw_of(&one_taken, origin, size)),
cells(&drawn(vec![the_box(), the_line()], origin, size)),
"both figures are drawn, each under the identity it was added with"
);
// Two taken, one added, and then the counter is past the one it issued: 1 and 2 are the
// caller's, 3 is the first free ordinal, and 4 is what comes after it.
let (two_taken, third) = Diagram::numbered_from(nz(1))
.add_under(identity(1), the_box())
.add_under(identity(2), the_line())
.add(the_box());
let (_, fourth) = two_taken.add(the_line());
assert_eq!(
third.to_string(),
"3",
"two ordinals were taken and one was stepped over"
);
assert_eq!(
fourth.to_string(),
"4",
"the counter is past the ordinal it issued rather than stepping over it again"
);
}
/// The specification's _Edge cases_, and **P1 applied twice rather than a cascade**: two
/// connectors hang from the same figure at different anchors with different offsets, so the two
/// points they freeze at are different, and each freezes at its own.
///
/// A body that resolved once and wrote twice would pass `a_removal_freezes_what_hung_from_the_removed_shape`
/// and fail here, which is the reason the arrangement is not the one that test already builds.
/// A **cascade** — walking from the box to the first connector and on — would fail it too, since
/// a connector answers no anchor and so there is nowhere to walk to; the fold visits each figure
/// once and that is the whole of it.
#[test]
fn two_connectors_from_one_figure_both_freeze_at_their_own_points() {
let Window { origin, size } = the_window();
let nothing = Delta { dx: 0, dy: 0 };
let (at_the_top, at_the_bottom) = (Pos { x: 8, y: 1 }, Pos { x: 8, y: 2 });
let from_the_right = |id: ShapeId| {
arm_connector(
Position::Reference(Reference::new(id, Anchor::Right, nothing, 0)),
at_the_top.into(),
)
};
let from_the_bottom = |id: ShapeId| {
arm_connector(
Position::Reference(Reference::new(
id,
Anchor::Bottom,
Delta { dx: 2, dy: 0 },
0,
)),
at_the_bottom.into(),
)
};
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
diagram = diagram.add(from_the_right(box_id)).0;
diagram = diagram.add(from_the_bottom(box_id)).0;
diagram = diagram.add(the_unrelated_box()).0;
let before = draw_of(&diagram, origin, size);
// Each end's own point, resolved before the removal and held across it.
let (top, bottom) = (
the_hanging_end(&diagram, identity(2))
.and_then(|end| end.resolve(&diagram))
.expect("the first connector's reference resolves while the box is held"),
the_hanging_end(&diagram, identity(3))
.and_then(|end| end.resolve(&diagram))
.expect("the second connector's reference resolves while the box is held"),
);
assert_ne!(
top, bottom,
"the two ends resolved to the same point, so this is not the arrangement that tells two \
apart"
);
diagram = diagram.remove(box_id);
assert_eq!(
the_hanging_end(&diagram, identity(2))
.expect("the first connector is still held")
.at,
EndpointAt::Absolute {
at: top,
leaving: Direction::Right,
}
);
assert_eq!(
the_hanging_end(&diagram, identity(3))
.expect("the second connector is still held")
.at,
EndpointAt::Absolute {
at: bottom,
leaving: Direction::Down,
}
);
// And drawn: the picture holds two arrows where the removal took the figure they hung from.
let after = draw_of(&diagram, origin, size);
let mut expected = Diagram::new();
expected = expected.add(arm_connector(top.into(), at_the_top.into())).0;
expected = expected
.add(connector_leaving(
bottom.into(),
Direction::Down,
at_the_bottom.into(),
Direction::Left,
))
.0;
expected = expected.add(the_unrelated_box()).0;
assert_eq!(
cells(&after),
cells(&draw_of(&expected, origin, size)),
"the two arrows did not both stand where they stood"
);
assert_ne!(
differing(&before, &after),
Vec::new(),
"the removal changed nothing at all, so no arrow was standing there to freeze"
);
}
/// D3's "**and nothing else**", which is a claim about the whole diagram and so deserves a test
/// of its own: three diagrams, one assertion each, and each is a way the rule could be wrong.
///
/// **(1) A reference the removal did not create is not repaired**, in both of the forms it can
/// take. The first is an identity **never added** at all: the removal names it, finds nothing,
/// and returns before the freeze, so nothing is touched — which is a removal of an identity this
/// diagram does not hold rather than a freeze, and is asserted because a body that reached the
/// freeze anyway would be inventing a repair nobody asked for. The second is an identity **held
/// by a figure that answers no side**, so the reference **does not resolve** while the freeze
/// runs:
/// this is the one the `Some(point)` guard in `Endpoint::frozen_position` exists for, because
/// freezing it to nothing or dropping it would each be a second rule about removals. The second
/// is the one that earns the guard; the first is the one a reader imagines.
///
/// **(2) The asymmetry is the rule.** A connector with `from` naming a figure that **stays** and
/// `to` naming the one taken out keeps a `Reference` in `from` while `to` is frozen — and a body
/// that rewrote *every* reference naming the identity would pass every other test in this crate.
///
/// **(3) One connector with both ends on the same figure gets two different points**, which is
/// the arrangement an implementation that asks once and writes twice gets wrong. Measured, they
/// are `{3, 1}` and `{2, 2}` for a four-by-three box at the origin, and the method has no such
/// failure because it computes both answers before it builds either endpoint.
#[test]
fn a_removal_touches_nothing_else() {
let nothing = Delta { dx: 0, dy: 0 };
let the_far_end = Pos { x: 8, y: 1 };
let naming =
|id: ShapeId, anchor: Anchor, offset: Delta| Reference::new(id, anchor, offset, 0);
let abs = |x, y, leaving| EndpointAt::Absolute {
at: Pos { x, y },
leaving,
};
let ends_of = |d: &Diagram, id| match d.get(id) {
Some(Shape::Connector { from, to, .. }) => (from.at, to.at),
_ => unreachable!("the figure under test is a connector"),
};
// (1a) An identity that was never there, and a removal naming exactly that identity.
let never_there = Diagram::new()
.add_under(
identity(2),
arm_connector(
Position::Reference(naming(identity(1), Anchor::Right, nothing)),
the_far_end.into(),
),
)
.remove(identity(1));
assert_eq!(
ends_of(&never_there, identity(2)).0,
EndpointAt::Reference(naming(identity(1), Anchor::Right, nothing)),
"the removal repaired a reference to an identity it never held"
);
// (1b) The same unresolved reference, over an identity a figure answering no side holds — so
// the freeze runs, `resolve` answers nothing, and the `Some(point)` guard is what is left.
let held_and_unresolvable = Diagram::new()
.add_under(
identity(1),
connector_leaving(
Pos { x: 0, y: 0 }.into(),
Direction::Down,
Pos { x: 0, y: 2 }.into(),
Direction::Up,
),
)
.add_under(
identity(2),
arm_connector(
Position::Reference(naming(identity(1), Anchor::Right, nothing)),
the_far_end.into(),
),
)
.remove(identity(1));
assert_eq!(
ends_of(&held_and_unresolvable, identity(2)).0,
EndpointAt::Reference(naming(identity(1), Anchor::Right, nothing)),
"an unresolved reference was frozen or dropped, which is a second rule"
);
// (2) One end naming a figure that stays, the other the one taken out.
let (one_end, stays) = Diagram::new().add(the_box());
let (one_end, goes) = one_end.add(the_unrelated_box());
let one_end = one_end
.add(arm_connector(
Position::Reference(naming(stays, Anchor::Right, nothing)),
Position::Reference(naming(goes, Anchor::Bottom, Delta { dx: 1, dy: 0 })),
))
.0
.remove(goes);
let (from, to) = ends_of(&one_end, identity(3));
assert_eq!(
from,
EndpointAt::Reference(naming(stays, Anchor::Right, nothing)),
"a reference naming a figure that stayed was rewritten"
);
assert_eq!(
to,
abs(11, 2, Direction::Down),
"the end naming the removed figure did not freeze at the point it was resolving to"
);
// (3) Both ends on the same figure, at two different anchors.
let (both_ends, id) = Diagram::new().add(the_box());
let both_ends = both_ends
.add(arm_connector(
Position::Reference(naming(id, Anchor::Right, nothing)),
Position::Reference(naming(id, Anchor::Bottom, Delta { dx: 1, dy: 0 })),
))
.0
.remove(identity(1));
let (from, to) = ends_of(&both_ends, identity(2));
assert_eq!(from, abs(3, 1, Direction::Right));
assert_eq!(to, abs(2, 2, Direction::Down));
assert_ne!(
from, to,
"both ends came back at the same point, so one answer was written into both"
);
}
/// A figure put back under the referenced identity makes the connector draw again, hanging
/// from the **new** figure's side rather than where the old one stood.
///
/// The case is put through `replace` rather than through `remove` followed by an addition, and
/// the reason is the model's rather than a convenience: `replace` answers the same resolution
/// **from the other side** — the identity is found, the kind answers the anchor, and the
/// connector is drawn from wherever the figure now stands.
///
/// **This paragraph used to say a diagram offers no way to name a shape into existence, and both
/// halves of that were false before 142 was written.** `add_under` is `pub` and has been since
/// 148, so a removal *can* be followed by an addition under the removed identity; and since 142 a
/// removal **freezes** the reference rather than leaving it unresolved, so the state the old
/// sentence described — a reference that resolves to nothing for good — can no longer be reached
/// by this route. What a removal does now is in [`Diagram::remove`]: the end becomes the point
/// it was resolving to, and a put-back under the same identity leaves the arrow where it was
/// rather than hanging from it again, which is `a_shape_put_back_under_the_removed_identity_is_not_re_attached`'s
/// claim. [#142](https://github.com/andresmoschini/monospace/issues/142) answered the question this
/// comment used to carry.
///
/// A **line** is what goes back, not a second box, so a kind change is covered by the same case:
/// read as a box one cell thick, a five-cell line's right side center is its last cell, which is
/// neither where the removed box answered nor the connector's own far end.
#[test]
fn a_figure_put_back_under_the_referenced_identity_draws_the_connector_again() {
let Window { origin, size } = the_window();
let the_far_end = Pos { x: 11, y: 1 };
let diagram = Diagram::new();
let (mut diagram, identity) = diagram.add(the_box());
diagram = diagram
.add(arm_connector(
Position::Reference(Reference::new(
identity,
Anchor::Right,
Delta { dx: 0, dy: 0 },
0,
)),
the_far_end.into(),
))
.0;
let before = draw_of(&diagram, origin, size);
let the_line = Shape::Line {
at: Pos { x: 0, y: 0 },
len: 5,
orientation: Orientation::Horizontal,
stroke: light(),
};
diagram = diagram.replace(identity, the_line.clone());
let after = draw_of(&diagram, origin, size);
let mut expected = Diagram::new();
expected = expected.add(the_line).0;
expected = expected
.add(arm_connector(Pos { x: 4, y: 0 }.into(), the_far_end.into()))
.0;
assert_eq!(cells(&after), cells(&draw_of(&expected, origin, size)));
assert_ne!(
cells(&before),
cells(&after),
"the replacement did not reach the picture at all"
);
}
/// A connector with one endpoint absolute and one hanging, displaced, moves **both** of them
/// — and what the hanging one moved is its gap.
///
/// **This test used to say the opposite, and it was not among the four places the
/// specification named.** It read `…_leaves_its_hanging_one` and asserted that the cell the
/// hanging end stood on was byte-identical before and after, which is true of the rule this
/// slice reverses and false of the rule it lands. It escaped the inventory because it cited a
/// rule by number and never named this issue, so `grep -rn "143"` — the measurement behind
/// that inventory — did not return it. The count was four and the truth is five.
///
/// **It is rewritten rather than deleted, and the case is kept** because this is the arrangement
/// its sibling does not reach: the reference sits in the **`to`** slot with an absolute in
/// `from`, where the test beside it puts it in `from`. A `match` written to suit one slot and
/// read wrongly in the other passes each of them alone, which is the reason both exist.
///
/// The two halves of the claim are separate assertions rather than one picture. The gap grew by
/// the delta — the hanging end stands at `{3, 3}` while the side it hangs from is still `{3, 1}`
/// — and the figure that side belongs to did not move, which is what makes it a gap growing
/// rather than a route following. The `assert_ne!` is what keeps it honest: a `displaced_by` that
/// changed nothing at all would satisfy a comparison of before against after by doing exactly
/// what the old rule did.
#[test]
fn a_displaced_connector_moves_its_absolute_end_and_its_hanging_one_too() {
let Window { origin, size } = the_window();
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
diagram = diagram
.add(arm_connector(
Pos { x: 0, y: 1 }.into(),
Position::Reference(Reference::new(
box_id,
Anchor::Right,
Delta { dx: 0, dy: 0 },
0,
)),
))
.0;
// Which endpoint the hanging one resolves to, asked the way the drawing asks it. Before the
// displacement it stands on the border, and the side it is measured from is there too.
let the_hanging_end = |d: &Diagram| {
let Shape::Connector { to, .. } = d
.get(identity(2))
.expect("the connector is the second figure")
else {
unreachable!("the figure under test is a connector")
};
to.resolve(d)
};
assert_eq!(the_hanging_end(&diagram), Some(THE_SIDE_CENTRE));
let before = draw_of(&diagram, origin, size);
let id = identity(2);
let moved = diagram
.get(id)
.expect("the connector is in the diagram")
.displaced_by(Delta { dx: 0, dy: 2 });
assert_ne!(
moved,
diagram.get(id).expect("the connector is held").clone()
);
diagram = diagram.replace(id, moved);
let after = draw_of(&diagram, origin, size);
// The same two figures with the connector standing where the rule put it: the absolute end
// at `{0, 3}` and the hanging one at `{3, 1}` plus the two cells its gap grew by. Built
// from the two positions rather than pinned as text, so what is claimed is where a
// displacement puts a figure and not how a connector draws.
let mut expected = Diagram::new();
expected = expected.add(the_box()).0;
expected = expected
.add(connector_leaving(
Pos { x: 0, y: 3 }.into(),
Direction::Right,
Pos { x: 3, y: 3 }.into(),
Direction::Right,
))
.0;
assert_eq!(cells(&after), cells(&draw_of(&expected, origin, size)));
// The gap grew by the delta, and the figure the gap is measured from is exactly where it
// was: the two are separate claims, and only the pair says the endpoint slid rather than
// followed.
assert_eq!(the_hanging_end(&diagram), Some(Pos { x: 3, y: 3 }));
assert_ne!(the_hanging_end(&diagram), Some(THE_SIDE_CENTRE));
assert_eq!(
the_box().anchor(Anchor::Right),
Some(THE_SIDE_CENTRE),
"the box the endpoint hangs from moved, so this would be a following endpoint"
);
// The cell the old rule pinned — the one the hanging end stood on before — is no longer
// written, which is the assertion this test used to make the other way round.
assert_ne!(
before.cell(THE_SIDE_CENTRE),
after.cell(THE_SIDE_CENTRE),
"the hanging end did not move off the border it hangs from"
);
}
/// Displacing a box or a line takes all four of its side centers with it, and a connector
/// hanging from any of them goes with them.
///
/// The other half of the rule above, and what makes a displacement a property of a position
/// rather than of a figure. All four anchors rather than one, each with a destination
/// of its own so that no two arms share a cell and no wrong answer can hide behind a right one:
/// an implementation that moved three centers and left the fourth would draw three correct
/// routes and one that goes nowhere.
#[test]
fn a_displaced_figure_takes_every_anchor_and_every_hanging_end_with_it() {
let origin = Pos { x: 0, y: 0 };
let size = Size {
width: 14,
height: 6,
};
let by = Delta { dx: 2, dy: 0 };
let the_anchors = [Anchor::Top, Anchor::Right, Anchor::Bottom, Anchor::Left];
let the_destinations = [
Pos { x: 12, y: 0 },
Pos { x: 13, y: 1 },
Pos { x: 13, y: 2 },
Pos { x: 12, y: 5 },
];
let a_box_at = |x: i16| Shape::Box {
at: Pos { x, y: 0 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
};
let a_line_at = |x: i16| Shape::Line {
at: Pos { x, y: 0 },
len: 6,
orientation: Orientation::Horizontal,
stroke: light(),
};
for (what, figure_at) in [
("a box", &a_box_at as &dyn Fn(i16) -> Shape),
("a line", &a_line_at as &dyn Fn(i16) -> Shape),
] {
let diagram = Diagram::new();
let (mut diagram, identity) = diagram.add(figure_at(0));
for (anchor, to) in the_anchors.into_iter().zip(the_destinations) {
diagram = diagram
.add(arm_connector(
Position::Reference(Reference::new(
identity,
anchor,
Delta { dx: 0, dy: 0 },
0,
)),
to.into(),
))
.0;
}
let before = draw_of(&diagram, origin, size);
let moved = figure_at(0).displaced_by(by);
diagram = diagram.replace(identity, moved.clone());
let after = draw_of(&diagram, origin, size);
// The same five figures with every anchor named as the point it resolved to before the
// displacement, and again as the point it resolves to after.
let mut expected_before = Diagram::new();
expected_before = expected_before.add(figure_at(0)).0;
for (anchor, to) in the_anchors.into_iter().zip(the_destinations) {
expected_before = expected_before
.add(connector_leaving(
figure_at(0)
.anchor(anchor)
.expect("a box and a line answer every anchor")
.into(),
anchor.leaving(),
to.into(),
Direction::Left,
))
.0;
}
assert_eq!(
cells(&before),
cells(&draw_of(&expected_before, origin, size)),
"{what} before"
);
let mut expected_after = Diagram::new();
expected_after = expected_after.add(moved.clone()).0;
for (anchor, to) in the_anchors.into_iter().zip(the_destinations) {
expected_after = expected_after
.add(connector_leaving(
moved
.anchor(anchor)
.expect("a box and a line answer every anchor")
.into(),
anchor.leaving(),
to.into(),
Direction::Left,
))
.0;
}
assert_eq!(
cells(&after),
cells(&draw_of(&expected_after, origin, size)),
"{what} after"
);
}
}
// -------------------------- displacing the figure that holds a reference, rather than the one
/// The arrangement the specification's scenarios are about, with the two identities it holds:
/// the four-by-three box at the origin, and the connector whose `from` hangs from that box's
/// right side with a gap of nothing and reaches `{7, 1}`. Both terminals are arms and both
/// directions are the caller's, so what a picture shows is the route and nothing else.
///
/// A fresh diagram per call rather than one shared, because every case below displaces a figure
/// **in place** and the two figures are the only things that can be displaced — a case that
/// started from a diagram the case before had already changed would be asking about both at
/// once, which is what the last test below is for and what the rest are not.
fn the_arrangement() -> (Diagram, ShapeId, ShapeId) {
let diagram = Diagram::new();
let (diagram, box_id) = diagram.add(the_box());
let (diagram, connector_id) = diagram.add(arm_connector(
Position::Reference(Reference::new(
box_id,
Anchor::Right,
Delta { dx: 0, dy: 0 },
0,
)),
Pos { x: 7, y: 1 }.into(),
));
(diagram, box_id, connector_id)
}
/// The arrangement the two directions are asked in, carrying **a gap of two cells** and a free
/// end well clear of the border — which the specification's own arrangement does not, since
/// there displacing the box four cells right lands the endpoint exactly on the free end and the
/// connector becomes degenerate, and a degenerate case cannot tell the two rules apart.
///
/// The two directions are the two directions this rule has: displacing the box (which the
/// reference hangs from) carries the endpoint and leaves the gap, and displacing the connector
/// (which holds the reference) slides the endpoint and grows the gap. The helper exists so the
/// two halves of `both_directions_move_the_endpoint_differently` cannot drift apart by
/// construction — they are the same arrangement by definition, not by agreement.
fn the_arrangement_with_a_gap(gap: Delta, far_end: Pos) -> (Diagram, ShapeId, ShapeId) {
let diagram = Diagram::new();
let (diagram, box_id) = diagram.add(the_box());
let (diagram, connector_id) = diagram.add(arm_connector(
Position::Reference(Reference::new(box_id, Anchor::Right, gap, 0)),
far_end.into(),
));
(diagram, box_id, connector_id)
}
/// The middle of a box's right side, asked through the crate-private query the drawing itself
/// goes through, so a test cannot disagree with the picture about where the border is.
fn the_right_side(d: &Diagram, box_id: ShapeId) -> Option<Pos> {
d.get(box_id).and_then(|shape| shape.anchor(Anchor::Right))
}
/// The gap a connector's `from` holds from the side it hangs from, read off the reference
/// rather than measured off the drawing — the offset is the gap, and the drawing can only show
/// where the two ended up rather than what was between them.
fn the_gap(d: &Diagram, connector: ShapeId) -> Delta {
let Shape::Connector { from, .. } = d.get(connector).expect("the connector is held") else {
unreachable!("the figure named is a connector")
};
match from.at {
EndpointAt::Reference(reference) => reference.offset,
EndpointAt::Absolute { .. } => unreachable!("the `from` above is a reference"),
}
}
/// Where a connector's two endpoints stand right now, asked the way the drawing asks it. Both
/// halves separately rather than as a pair against each other, so a `resolve` that answered
/// both wrongly cannot pass on the two being wrong together.
fn the_ends(d: &Diagram, connector: ShapeId) -> (Option<Pos>, Option<Pos>) {
let Shape::Connector { from, to, .. } = d.get(connector).expect("the connector is held")
else {
unreachable!("the figure named is a connector")
};
(from.resolve(d), to.resolve(d))
}
/// Displacing the connector grows the reference's offset and moves the absolute end, **asked
/// by value and then drawn** — which is the order the two halves are only worth anything in.
///
/// The value half catches a rule that grew the wrong field: `id` and `anchor` are held equal to
/// what went in, and each is asked on its own rather than as a pair. The drawn half catches one
/// that grew nothing, which the value half would also catch but that a reader cannot see, and it
/// is the half that says the figure draws as a translation of itself rather than bending its
/// route to reach a side that stayed put.
///
/// **The expected picture is built from the two positions the rule yields** — a reference to the
/// same side carrying the grown offset, and a `to` at the moved point — rather than pinned as
/// text and rather than read back out of the displaced value, so what the two drawings are asked
/// to agree about is the rule and not itself.
#[test]
fn a_displacement_grows_a_references_offsets() {
let Window { origin, size } = the_window();
let (mut diagram, box_id, connector_id) = the_arrangement();
let as_written = diagram
.get(connector_id)
.expect("the connector is held")
.clone();
let by = Delta { dx: 0, dy: 2 };
let moved = as_written.displaced_by(by);
let Shape::Connector { from, to, .. } = &moved else {
unreachable!("the figure above is a connector")
};
let Shape::Connector {
from: was_from,
to: was_to,
..
} = &as_written
else {
unreachable!("the figure above is a connector")
};
let EndpointAt::Reference(grown) = from.at else {
unreachable!("the `from` above is a reference")
};
let EndpointAt::Reference(was) = was_from.at else {
unreachable!("the `from` above is a reference")
};
// The one field that grew, on its own, and not equal to what it was.
assert_eq!(grown.offset, by);
assert_ne!(grown.offset, was.offset);
// The two that name, each equal to what went in — and the identity is the one `add` issued,
// so a rule that reached some other figure's side cannot pass on the anchor being right.
assert_eq!(grown.id, was.id);
assert_eq!(grown.id, box_id);
assert_eq!(grown.anchor, Anchor::Right);
assert_eq!(grown.anchor, was.anchor);
// The absolute end moved by the same delta, and the figure as a whole is not what it was.
assert_eq!(
to.at,
EndpointAt::Absolute {
at: Pos { x: 7, y: 3 },
leaving: Direction::Left,
}
);
assert_ne!(to.at, was_to.at);
assert_ne!(moved, as_written);
// And then the drawing: the same two figures with the connector standing where the rule put
// it, reached by a second diagram that never displaced anything.
diagram = diagram.replace(connector_id, moved);
let after = draw_of(&diagram, origin, size);
let expected = Diagram::new();
let (mut expected, expected_box) = expected.add(the_box());
expected = expected
.add(arm_connector(
Position::Reference(Reference::new(expected_box, Anchor::Right, by, 0)),
Pos { x: 7, y: 3 }.into(),
))
.0;
assert_eq!(
cells(&after),
cells(&draw_of(&expected, origin, size)),
"the displaced connector drew something other than a translation of itself"
);
// The displacement reached cells, which is the half that says the two pictures above are two
// pictures rather than one drawn twice.
let as_written_diagram = the_arrangement().0;
let reached = differing(&draw_of(&as_written_diagram, origin, size), &after);
assert!(
!reached.is_empty(),
"the displacement reached nothing at all"
);
}
/// A figure holding **two** references grows both offsets by the same amount and is
/// translated rigidly — the rule above, twice, and one test.
///
/// A diagram of **two** boxes rather than one, because a shape holding a single reference cannot
/// ask this and an implementation that moved only the first endpoint would pass the test above.
/// The two offsets start out **different** from each other — one cell out and one cell in — so
/// "grew by the same amount" is a claim about the delta rather than two equal values that happen
/// to add up, and the two identities are different figures rather than the same one twice.
///
/// The drawn half is what "rigidly" means as cells: the same two boxes and the same connector
/// with both offsets written at their grown values, built by a diagram that never displaced
/// anything, so the comparison is against the values rather than against the value under test.
#[test]
fn a_displacement_grows_both_offsets_of_one_connector() {
let Window { origin, size } = the_window();
let by = Delta { dx: 3, dy: 2 };
// Box A's right side center is `{3, 1}` and box B's left side center is `{9, 1}`, so the two
// hanging ends start on cells six apart and neither answer can be the other.
let second_box = || Shape::Box {
at: Pos { x: 9, y: 0 },
size: Size {
width: 3,
height: 3,
},
stroke: light(),
fill: None,
text: None,
};
let hanging_from_both = |from_offset: Delta, to_offset: Delta| {
let diagram = Diagram::new();
let (diagram, a) = diagram.add(the_box());
let (mut diagram, b) = diagram.add(second_box());
diagram = diagram
.add(arm_connector(
Position::Reference(Reference::new(a, Anchor::Right, from_offset, 0)),
Position::Reference(Reference::new(b, Anchor::Left, to_offset, 0)),
))
.0;
diagram
};
let written = Delta { dx: 1, dy: 0 };
let inward = Delta { dx: -1, dy: 0 };
let mut diagram = hanging_from_both(written, inward);
let connector_id = identity(3);
let before = draw_of(&diagram, origin, size);
assert_eq!(the_gap(&diagram, connector_id), written);
let moved = diagram
.get(connector_id)
.expect("the connector is held")
.displaced_by(by);
diagram = diagram.replace(connector_id, moved);
let after = draw_of(&diagram, origin, size);
// Both grew by the delta, on both axes, and each is not what it was. The second offset is
// asserted as a value of its own rather than read off the drawing below, because "both" is
// the claim and reading one of them off a picture is how a test stops being about it.
assert_eq!(the_gap(&diagram, connector_id), Delta { dx: 4, dy: 2 });
assert_ne!(the_gap(&diagram, connector_id), written);
let Shape::Connector { from, to, .. } =
diagram.get(connector_id).expect("the connector is held")
else {
unreachable!("the figure above is a connector")
};
let (EndpointAt::Reference(from), EndpointAt::Reference(to)) = (from.at, to.at) else {
unreachable!("both ends of this connector are references")
};
assert_eq!(from.offset, Delta { dx: 4, dy: 2 });
assert_ne!(from.offset, written);
assert_eq!(to.offset, Delta { dx: 2, dy: 2 });
assert_ne!(to.offset, inward);
assert_eq!(from.anchor, Anchor::Right);
assert_eq!(to.anchor, Anchor::Left);
assert_ne!(from.id, to.id, "both ends hang from the same figure");
assert_ne!(
from.offset, to.offset,
"the two offsets were the same to begin with"
);
// The two resolved ends, each against the point its own reference and anchor name, so a
// `resolve` that answered both wrongly cannot pass on the two being wrong together.
assert_eq!(
the_ends(&diagram, connector_id),
(Some(Pos { x: 7, y: 3 }), Some(Pos { x: 11, y: 3 }))
);
assert_eq!(
cells(&after),
cells(&draw_of(
&hanging_from_both(Delta { dx: 4, dy: 2 }, Delta { dx: 2, dy: 2 }),
origin,
size
)),
"the connector was not translated rigidly: both offsets did not grow together"
);
// Neither box moved, which is the other half of "rigidly": every cell either one holds is
// byte for byte what it was. Their footprints are quoted rather than derived, and the route
// is excluded from the claim on purpose — it ran along row 1 before and row 3 after, so
// those cells are the connector's and the claim is about the two boxes alone.
let a_box_holds = |at: &Pos| {
let in_the_first = (0..=3).contains(&at.x) && (0..=2).contains(&at.y);
let in_the_second = (9..=11).contains(&at.x) && (0..=2).contains(&at.y);
in_the_first || in_the_second
};
let reached = differing(&before, &after);
assert!(
!reached.is_empty(),
"the displacement reached nothing at all"
);
assert!(
!reached.iter().any(a_box_holds),
"a box moved when only the connector was displaced: {reached:?}"
);
}
/// The first of the specification's two **derived** arrangements, derived from the rule rather
/// than decided by it, and pinned so that a later slice which changes it has to say so.
///
/// The arithmetic is three assertions and all three are about the value. The drawing is a fourth
/// and it is the half that is **measured rather than derived**, because the specification's own
/// sentence about it turned out to be false on this branch: it claims that "an absolute position
/// that saturates draws nothing and an offset that saturating draws a very far away endpoint",
/// and that the two differ. Built and drawn, **the two draw the same thing** — the route is
/// clipped to whatever of it falls inside the window, whichever of the two positions was
/// saturated. What does differ from a saturated coordinate is an **unresolved** reference, which
/// takes the whole figure out of the output, and that is the assertion this test holds.
#[test]
fn an_offset_that_saturated_stays_saturated() {
let Window { origin, size } = the_window();
let the_other_end: Position = Pos { x: 8, y: 1 }.into();
let at_the_end = Delta {
dx: i16::MAX,
dy: 0,
};
// The figure that has nothing to do with either end is in this diagram from the start, so
// the three drawings compared below differ only in the connector and not in what is beside
// it — otherwise "the connector is still there" would be the same claim as "the drawing
// stopped".
let hanging_from = |offset: Delta| {
let diagram = Diagram::new();
let (mut diagram, box_id) = diagram.add(the_box());
diagram = diagram.add(the_unrelated_box()).0;
let (diagram, connector_id) = diagram.add(arm_connector(
Position::Reference(Reference::new(box_id, Anchor::Right, offset, 0)),
the_other_end,
));
(diagram, connector_id)
};
let (mut diagram, connector_id) = hanging_from(at_the_end);
assert_eq!(the_gap(&diagram, connector_id), at_the_end);
// One displacement too large for the room left: the offset is already at the end of the
// coordinates, so it stays there. The wrapped value is named rather than left implicit,
// because wrapping is exactly what a plain `+` would do here and it would land back inside
// a window a caller could hold.
let moved = diagram
.get(connector_id)
.expect("the connector is held")
.displaced_by(Delta { dx: 5, dy: 0 });
diagram = diagram.replace(connector_id, moved);
assert_eq!(the_gap(&diagram, connector_id), at_the_end);
assert_ne!(
the_gap(&diagram, connector_id),
Delta {
dx: i16::MIN + 4,
dy: 0
}
);
// And a displacement back does **not** undo it, because the addition that saturated is not
// remembered. Four of the five cells are gone, so one back leaves the offset one cell short
// of the end rather than at the end: a displacement of nothing, or of a delta the offset
// had room for, is the only way the value comes back to where it started.
let back = diagram
.get(connector_id)
.expect("the connector is held")
.displaced_by(Delta { dx: -1, dy: 0 });
diagram = diagram.replace(connector_id, back);
assert_eq!(
the_gap(&diagram, connector_id),
Delta {
dx: i16::MAX - 1,
dy: 0
}
);
assert_ne!(
the_gap(&diagram, connector_id),
at_the_end,
"the displacement back undid a saturating one, so the arithmetic kept a memory"
);
// Drawn from a diagram **built** at that offset rather than from the one the three
// displacements above ran on, and the reason is worth stating: a displacement moves **both**
// endpoints, so the free end has walked `+5`, `-1`, `+1` and now stands at `{13, 1}` — one
// column past the right edge of a thirteen-wide window. What the drawing below is about is
// what an offset *at the end of the coordinates* draws, and the value assertions above
// already say this arrangement holds one. Drawing the mutated figure would have measured
// the free end's drift as well, and measured it as though it were about the offset.
let (built_at_the_end, _) = hanging_from(at_the_end);
let with_the_offset = draw_of(&built_at_the_end, origin, size);
// The same two figures and the same connector with the far end named outright, so the only
// difference between the two drawings is whether the saturated point was reached through an
// offset or written as a point.
let mut with_the_point = Diagram::new();
with_the_point = with_the_point.add(the_box()).0;
with_the_point = with_the_point.add(the_unrelated_box()).0;
with_the_point = with_the_point
.add(arm_connector(
Pos { x: i16::MAX, y: 1 }.into(),
the_other_end,
))
.0;
assert_eq!(
cells(&with_the_offset),
cells(&draw_of(&with_the_point, origin, size)),
"a saturated offset drew something other than the same connector with an absolute \
endpoint at the saturated point"
);
// And the distinction that is real: a saturated offset is not a reference that resolves to
// nothing. The figure stays in the output, where an unresolved one would be gone from it.
let mut without_the_connector = Diagram::new();
without_the_connector = without_the_connector.add(the_box()).0;
without_the_connector = without_the_connector.add(the_unrelated_box()).0;
assert_ne!(
cells(&with_the_offset),
cells(&draw_of(&without_the_connector, origin, size)),
"a saturated offset took the connector out of the output, which is what an unresolved \
reference does and not what a saturated coordinate does"
);
}
/// The two directions are distinguishable from outside, and **both of them are asked in one
/// test**.
///
/// One test is the specification's own reason and it is the whole of the reason: an
/// implementation that reached the same place in both directions — by rewriting the shape a
/// reference names, say, so that displacing the box moved the endpoint and displacing the
/// connector moved the box — would satisfy each half on its own and draw neither picture. The
/// contrast is therefore drawn **across** the two halves rather than inside either.
///
/// **The arrangement carries a gap of two cells and its free end is well clear of the border**,
/// which the specification's own arrangement does not: there, displacing the box four cells
/// right lands the endpoint exactly on the free end and the connector becomes degenerate, and a
/// degenerate case cannot tell the two rules apart. The gap is read off the reference rather
/// than measured off the drawing, because the drawing can only show where the two ends landed
/// and not what was between them and the border.
#[test]
fn both_directions_move_the_endpoint_differently() {
let Window { origin, size } = the_window();
let gap = Delta { dx: 2, dy: 0 };
let far_end = Pos { x: 11, y: 1 };
let the_arrangement = || the_arrangement_with_a_gap(gap, far_end);
// ---- the figure the reference hangs from: the endpoint follows and the gap does not move
let (mut box_moved, box_id, connector_id) = the_arrangement();
let ends_before = the_ends(&box_moved, connector_id);
let before_box = draw_of(&box_moved, origin, size);
let moved_box = box_moved
.get(box_id)
.expect("the box is held")
.displaced_by(Delta { dx: 4, dy: 0 });
assert_ne!(
moved_box,
box_moved.get(box_id).expect("the box is held").clone()
);
box_moved = box_moved.replace(box_id, moved_box);
let after_box = draw_of(&box_moved, origin, size);
assert_eq!(the_right_side(&box_moved, box_id), Some(Pos { x: 7, y: 1 }));
assert_eq!(
the_ends(&box_moved, connector_id),
(Some(Pos { x: 9, y: 1 }), Some(far_end)),
"the endpoint did not follow the side it hangs from"
);
assert_ne!(the_ends(&box_moved, connector_id), ends_before);
assert_eq!(
the_gap(&box_moved, connector_id),
gap,
"displacing the figure the reference hangs from changed the gap"
);
let mut expected_box = Diagram::new();
expected_box = expected_box
.add(the_box().displaced_by(Delta { dx: 4, dy: 0 }))
.0;
expected_box = expected_box
.add(arm_connector(Pos { x: 9, y: 1 }.into(), far_end.into()))
.0;
assert_eq!(
cells(&after_box),
cells(&draw_of(&expected_box, origin, size))
);
// ---- the figure that holds the reference: the endpoint slides and the box stands still
let (mut connector_moved, box_id, connector_id) = the_arrangement();
let side_before = the_right_side(&connector_moved, box_id);
let ends_before = the_ends(&connector_moved, connector_id);
let before_connector = draw_of(&connector_moved, origin, size);
let moved_connector = connector_moved
.get(connector_id)
.expect("the connector is held")
.displaced_by(Delta { dx: 0, dy: 2 });
assert_ne!(
moved_connector,
connector_moved
.get(connector_id)
.expect("the connector is held")
.clone()
);
connector_moved = connector_moved.replace(connector_id, moved_connector);
let after_connector = draw_of(&connector_moved, origin, size);
assert_eq!(
the_right_side(&connector_moved, box_id),
side_before,
"the box moved when only the connector was displaced"
);
assert_eq!(
the_ends(&connector_moved, connector_id),
(Some(Pos { x: 5, y: 3 }), Some(Pos { x: 11, y: 3 }))
);
assert_ne!(the_ends(&connector_moved, connector_id), ends_before);
assert_eq!(
the_gap(&connector_moved, connector_id),
Delta { dx: 2, dy: 2 },
"the gap did not grow, so the endpoint moved with the figure rather than sliding off it"
);
let mut expected_connector = Diagram::new();
expected_connector = expected_connector.add(the_box()).0;
expected_connector = expected_connector
.add(arm_connector(
Pos { x: 5, y: 3 }.into(),
Pos { x: 11, y: 3 }.into(),
))
.0;
assert_eq!(
cells(&after_connector),
cells(&draw_of(&expected_connector, origin, size))
);
// ---- and the contrast, across the two halves rather than inside either. **The two gaps
// are not the same number**, and that is the claim: the same arrangement, the same
// connector, two different figures displaced, and the gap is untouched in one and grown in
// the other. An implementation that reached one place in both directions would have them
// equal.
assert_ne!(
the_gap(&connector_moved, connector_id),
the_gap(&box_moved, connector_id),
"the two halves left the same gap, so the two directions are one rule"
);
assert_ne!(
the_ends(&connector_moved, connector_id).0,
the_ends(&box_moved, connector_id).0,
"the endpoint landed in the same cell whichever figure was displaced"
);
assert!(
!differing(&before_box, &after_box).is_empty()
&& !differing(&before_connector, &after_connector).is_empty(),
"one of the two displacements reached nothing at all"
);
}
/// A reference that resolves to nothing still resolves to nothing after a displacement —
/// **and its offsets grew anyway**.
///
/// That second half is the assertion that makes this test worth writing, and it is why the
/// test is not simply the one beside it with a displacement added. A `displaced_by` that grew
/// nothing would satisfy "still resolves to nothing" by doing exactly what the code did before
/// this rule, and the first half alone cannot tell the two apart.
///
/// **Two cases, and they are two different pieces of code.** An identity this diagram does not
/// hold, and an anchor whose kind does not answer — a connector, which is the answer that keeps
/// a chain of references one link long. The identity in the first case is **spelled** rather than
/// taken from `a_foreign_identity()`, and the reason is worth recording: that helper hands back
/// `3`, which a diagram of four figures *does* hold, so naming it would have been the second
/// case twice and the first would never have run.
///
/// **What this does not check, named rather than described as tested.** It compares the whole
/// picture against a diagram of the three figures it did not name, so for *those three* it does
/// check that a displaced figure leaves every other shape byte for byte. What it does **not**
/// check is the general claim — that a displacement reaches no shape the caller did not name —
/// which is a claim about the whole diagram rather than about the value that moved, and no
/// single fixture can establish it for every diagram. The same is true of an endpoint pushed
/// outside the window by the gap growing: it is clipped without a report, which is the model's
/// own rule for any figure and nothing this slice adds, and it is left where §4 and §9 state it.
#[test]
fn a_reference_that_resolves_to_nothing_still_does() {
let Window { origin, size } = the_window();
let large = Delta { dx: 6, dy: 2 };
let by = Delta { dx: 1, dy: 1 };
let the_other_end: Position = Pos { x: 8, y: 1 }.into();
let the_figure_under_test = identity(4);
let cases = [
(
"an identity nothing holds",
Position::Reference(Reference::new(identity(9), Anchor::Right, large, 0)),
),
(
"a kind that answers no anchor",
Position::Reference(Reference::new(identity(3), Anchor::Right, large, 0)),
),
];
for (what, hanging) in cases {
let mut diagram = a_diagram_of_three_figures_and_maybe_a_fourth(Some(arm_connector(
hanging,
the_other_end,
)));
let without_it = a_diagram_of_three_figures_and_maybe_a_fourth(None);
// Sanity: the figure under test resolves to nothing before the displacement too, or the
// case is asking about something other than what it says.
assert_eq!(
the_ends(&diagram, the_figure_under_test).0,
None,
"{what} resolved before the displacement, so this is not that case"
);
let before = draw_of(&diagram, origin, size);
let moved = diagram
.get(the_figure_under_test)
.expect("the figure under test is held")
.displaced_by(by);
diagram = diagram.replace(the_figure_under_test, moved);
let after = draw_of(&diagram, origin, size);
// The offsets grew, on both axes, and this one is asked by value rather than by
// drawing because a figure that draws nothing cannot show that anything changed.
assert_eq!(
the_gap(&diagram, the_figure_under_test),
Delta { dx: 7, dy: 3 },
"{what}: the offsets did not grow"
);
assert_ne!(the_gap(&diagram, the_figure_under_test), large);
// Still nothing, and every other figure drew exactly what it drew — which is what
// distinguishes "this figure is not drawn" from "the drawing stopped".
assert_eq!(
the_ends(&diagram, the_figure_under_test).0,
None,
"{what} resolved after the displacement"
);
assert_eq!(
cells(&after),
cells(&draw_of(&without_it, origin, size)),
"{what} drew something, or drew something else"
);
assert_eq!(
cells(&before),
cells(&draw_of(&without_it, origin, size)),
"{what} drew something before the displacement either"
);
// The three figures the connector did not name are still in the output, cell by cell —
// and the displacement reached **nothing at all**, which is what a figure that draws
// nothing means. Without this the two assertions above would also be satisfied by a
// drawing that stopped halfway, so it is what makes them mean what they say.
assert_eq!(
differing(&before, &after),
Vec::new(),
"a figure that draws nothing changed the drawing, so something else did"
);
}
}
/// The **second** derived arrangement: the box displaced two cells down and then the connector
/// displaced two cells down.
///
/// **Derived from the rule rather than decided by it**, and stated so a reader is not surprised
/// by it and so a later slice that changes it has to say so rather than discover it in a
/// picture: no displacement moves an anchor and its holder together and keeps the gap. Moving
/// the box carries the endpoint, and moving the endpoint grows the gap, so one caller asking
/// for two figures gets two displacements and the arrangement that follows from them.
///
/// Asserted by resolved coordinate rather than by picture, and the coordinates are written out
/// rather than computed, because what is being claimed is arithmetic. Measured on this branch:
/// the hanging end is at `{3, 5}` — four down from where it started, one move of the side and
/// two cells of gap — the free end is at `{7, 3}`, two down, because the box was not the figure
/// that was displaced and a displacement reaches one figure rather than the diagram. The box
/// itself is at `{0, 2}`, so nothing in the arrangement cascaded.
#[test]
fn displacing_the_box_and_then_the_connector() {
let (mut diagram, box_id, connector_id) = the_arrangement();
let ends_before = the_ends(&diagram, connector_id);
assert_eq!(
ends_before,
(Some(Pos { x: 3, y: 1 }), Some(Pos { x: 7, y: 1 }))
);
// First the box, which the reference hangs from: the endpoint goes with it and the gap is
// what it was.
let moved_box = diagram
.get(box_id)
.expect("the box is held")
.displaced_by(Delta { dx: 0, dy: 2 });
diagram = diagram.replace(box_id, moved_box);
assert_eq!(
the_ends(&diagram, connector_id),
(Some(Pos { x: 3, y: 3 }), Some(Pos { x: 7, y: 1 }))
);
assert_eq!(the_gap(&diagram, connector_id), Delta { dx: 0, dy: 0 });
// Then the connector itself, which holds the reference: the endpoint slides off the side and
// the free end moves with it.
let moved_connector = diagram
.get(connector_id)
.expect("the connector is held")
.displaced_by(Delta { dx: 0, dy: 2 });
diagram = diagram.replace(connector_id, moved_connector);
assert_eq!(
the_ends(&diagram, connector_id),
(Some(Pos { x: 3, y: 5 }), Some(Pos { x: 7, y: 3 }))
);
assert_eq!(
the_gap(&diagram, connector_id),
Delta { dx: 0, dy: 2 },
"the gap did not grow by the second displacement"
);
assert_eq!(
diagram
.get(box_id)
.and_then(|shape| shape.anchor(Anchor::Top)),
Some(Pos { x: 1, y: 2 }),
"the box moved a second time, so the two displacements were not one each"
);
// The two displacements belonged to two figures, so each was applied once: the gap is the
// one that grew and not the two that would have come from a cascading displacement.
assert_ne!(the_ends(&diagram, connector_id), ends_before);
}
// ------------------------------------------------------------ how far a drawing reaches
/// The footprint a diagram reaches when drawn into the window the cases below share, so a claim
/// about a footprint is written the way the claims about pictures are.
///
/// The window is deliberately **not** fitted to the diagram: every diagram below is measured
/// through the same window, and the point of the cases is that the window takes no part.
fn footprint_of(diagram: &Diagram) -> Option<Footprint> {
let Window { origin, size } = the_window();
let mut buffer = Buffer::new(Window { origin, size });
let mut sink = FootprintSink::new(&mut buffer);
diagram.draw(&mut sink);
sink.footprint()
}
/// The same diagram drawn into three windows — one that holds nothing, one that holds a corner,
/// one that holds all of it — reaches the same rectangle, **in the plane and not in the
/// window**.
///
/// This is the case the measurement exists for: a minimum and maximum taken from the cells
/// would be the intersection with the window, and the three answers below would be three
/// different rectangles.
#[test]
fn the_footprint_is_the_same_whatever_window_the_diagram_is_drawn_into() {
let (diagram, _back, _front) = two_overlapping_boxes();
let windows = [
(
Pos { x: 0, y: 0 },
Size {
width: 0,
height: 0,
},
),
(
Pos { x: 4, y: 2 },
Size {
width: 1,
height: 1,
},
),
(
Pos { x: -9, y: -7 },
Size {
width: 30,
height: 20,
},
),
];
let footprints: Vec<_> = windows
.into_iter()
.map(|(origin, size)| {
let mut buffer = Buffer::new(Window { origin, size });
let mut sink = FootprintSink::new(&mut buffer);
diagram.draw(&mut sink);
sink.footprint()
})
.collect();
assert_eq!(
footprints,
vec![
Some(Footprint {
min: Pos { x: 0, y: 0 },
max: Pos { x: 5, y: 3 },
});
3
],
"the window decided how far the drawing reaches"
);
}
/// A diagram at negative coordinates starts at its top-left corner, which is a `Pos` and not an
/// offset: `min` is signed and `y` grows down.
///
/// The window the case draws into holds none of the figure, so this is the same rule as the case
/// above seen from the other side: the record is taken before the window is consulted.
#[test]
fn the_footprint_starts_at_the_top_left_of_a_figure_at_negative_coordinates() {
let diagram = Diagram::new()
.add(Shape::Box {
at: Pos { x: -4, y: -3 },
size: Size {
width: 4,
height: 3,
},
stroke: light(),
fill: None,
text: None,
})
.0;
assert_eq!(
footprint_of(&diagram),
Some(Footprint {
min: Pos { x: -4, y: -3 },
max: Pos { x: -1, y: -1 },
})
);
}
/// A figure wholly behind another **still counts**, which is what makes the footprint the
/// drawing's footprint rather than its picture: the back box owns no cell at all and is
/// measured anyway.
///
/// The arrangement is the one that would make a record taken from `owners` shrink: the front box
/// is filled and covers the back one exactly, so the back one writes nothing under `Below` and
/// owns nothing. A footprint that followed the cells would report the front box alone.
#[test]
fn a_figure_wholly_behind_another_still_counts() {
let diagram = Diagram::new();
let (diagram, back) = diagram.add(Shape::Box {
at: Pos { x: 1, y: 1 },
size: Size {
width: 2,
height: 2,
},
stroke: light(),
fill: Some(Glyph::new("░").expect("one glyph")),
text: None,
});
let (diagram, front) = diagram.add(Shape::Box {
at: Pos { x: 0, y: 0 },
size: Size {
width: 6,
height: 4,
},
stroke: light(),
fill: Some(Glyph::new("▓").expect("one glyph")),
text: None,
});
let Window { origin, size } = the_window();
let mut buffer = Buffer::new(Window { origin, size });
let footprint = {
let mut sink = FootprintSink::new(&mut buffer);
diagram.draw(&mut sink);
sink.footprint()
};
assert_eq!(
buffer.owner(Pos { x: 1, y: 1 }),
Some(front),
"the box in front did not cover the one behind"
);
assert!(
!owners(&buffer).contains(&Some(back)),
"the box behind owns a cell, so it is not hidden and this is not the case"
);
assert_eq!(
footprint,
Some(Footprint {
min: Pos { x: 0, y: 0 },
max: Pos { x: 5, y: 3 },
})
);
}
/// Sending a figure behind another changes the picture and **does not move the footprint**,
/// which is the claim the footprint is chosen for: where the drawing reaches is a fact about
/// the figures, not about which of them won a cell.
#[test]
fn moving_a_figure_through_the_order_does_not_move_the_footprint() {
let (diagram, back, _front) = two_overlapping_boxes();
let before = footprint_of(&diagram);
assert_eq!(
before,
Some(Footprint {
min: Pos { x: 0, y: 0 },
max: Pos { x: 5, y: 3 },
})
);
assert_eq!(
footprint_of(&diagram.forward(back)),
before,
"the order decided how far the drawing reaches"
);
}
/// An empty diagram reaches nothing: `None` rather than a rectangle at the origin, because
/// "stamped nothing" and "stamped one cell at `(0, 0)`" are different drawings.
#[test]
fn an_empty_diagram_has_no_footprint() {
assert_eq!(footprint_of(&Diagram::new()), None);
}
#[test]
fn shapes_yields_shapes_in_drawing_order() {
let (diagram, back, front) = two_overlapping_boxes();
let ids: Vec<ShapeId> = diagram.shapes().map(|(id, _)| id).collect();
assert_eq!(ids, vec![back, front]);
}
#[test]
fn next_id_reports_the_resuming_ordinal() {
let diagram = Diagram::numbered_from(NonZeroU16::new(42).expect("nonzero"));
assert_eq!(diagram.next_id(), NonZeroU16::new(42).expect("nonzero"));
}
}