rstango 0.4.0

Implementation of the Tango distributed control system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
//! Definition of a device model and of its interface: its commands and its attributes.

use std::time::{Duration, SystemTime};
use std::ops::{Bound, RangeBounds};
use std::fmt::{self, Debug};
use std::future::Future;
use std::borrow::Cow;
use std::sync::Arc;

use futures::future::BoxFuture;

use crate::dev::{AttrConfig, AttrDeltaConfig, AttrMemorized, AttrNumber, AttrQuality, AttrRangeConfig, AttrRead, DevState, DisplayLevel};
use crate::value::{AttrData, AttrDataFormat, AttrDataKind, CommandData, CommandDataKind, FromValue, IntoValue, Scalar, Value};
use crate::error::Result;
use crate::name;

use super::{reserved_name, Model, RESERVED_ATTRS, RESERVED_COMMANDS, STATE_NAME, STATUS_NAME};
use super::attr::{unsupported, unsupported_prop};
use super::dev::Dev;


/// Merge a data kind being defined with the one already defined, if any, and give the
/// kind to keep. Both are compatible when they are equal, which is what allows a kind to
/// be both derived from a handler and given explicitly, in any order. Anything else is a
/// contradiction in the definition and therefore panics.
#[track_caller]
fn merge_kind<K: PartialEq + Debug>(def: &str, what: &str, current: Option<K>, new: K) -> K {
    match current {
        Some(current) if current != new => panic!(
            "{def}: the {what} is already defined as {current:?}, incompatible with {new:?}"),
        _ => new,
    }
}

/// Merge a data format being defined with the one already defined, if any, and give the
/// format to keep. Both are compatible when they have the same layout, their maximum
/// dimensions being merged with [`merge_max`], anything else panics.
#[track_caller]
fn merge_format(def: &str, current: Option<AttrDataFormat>, new: AttrDataFormat) -> AttrDataFormat {
    let Some(current) = current else { return new };
    match (&current, &new) {
        (AttrDataFormat::Scalar, AttrDataFormat::Scalar) => AttrDataFormat::Scalar,
        (AttrDataFormat::Spectrum(cur), AttrDataFormat::Spectrum(new)) => {
            AttrDataFormat::Spectrum(merge_max(def, "maximum size", *cur, *new))
        }
        (AttrDataFormat::Image(cur_x, cur_y), AttrDataFormat::Image(new_x, new_y)) => {
            AttrDataFormat::Image(
                merge_max(def, "maximum width", *cur_x, *new_x),
                merge_max(def, "maximum height", *cur_y, *new_y),
            )
        }
        _ => panic!(
            "{def}: the data format is already defined as {current:?}, incompatible with {new:?}"),
    }
}

/// Merge two maximum dimensions of a data format, zero standing for an undefined maximum
/// and therefore being compatible with any other value. Two different defined maximums
/// are a contradiction in the definition and therefore panic.
#[track_caller]
fn merge_max(def: &str, what: &str, current: usize, new: usize) -> usize {
    match (current, new) {
        (0, new) => new,
        (current, 0) => current,
        (current, new) if current != new => panic!(
            "{def}: the {what} is already defined as {current}, incompatible with {new}"),
        (current, _) => current,
    }
}

/// The two bounds of a range being defined, either of which is absent for a bound that is
/// left open, which is how an attribute says it has no minimum or no maximum rather than
/// having one it never reaches.
#[track_caller]
fn range_config<T, R>(def: &str, what: &str, range: R) -> AttrRangeConfig
where
    T: Into<AttrNumber> + Copy,
    R: RangeBounds<T>,
{
    AttrRangeConfig {
        min: bound_value(def, what, range.start_bound()),
        max: bound_value(def, what, range.end_bound()),
    }
}

/// A single bound of such a range, as the number the attribute holds: a range written with
/// integer bounds gives integer limits, one written with floating bounds gives floating
/// ones, and it is up to the definition to bound an attribute with its own kind of number.
///
/// An exclusive bound has no representation in Tango, the bounds being values a client
/// compares against, so it is refused rather than silently taken for the inclusive one it
/// is not.
#[track_caller]
fn bound_value<T>(def: &str, what: &str, bound: Bound<&T>) -> Option<AttrNumber>
where
    T: Into<AttrNumber> + Copy,
{
    match bound {
        Bound::Included(value) => Some((*value).into()),
        Bound::Unbounded => None,
        Bound::Excluded(_) => panic!(
            "{def}: the {what} cannot have an exclusive bound, Tango only has inclusive ones"),
    }
}

/// A placeholder shown by [`Debug`] in place of a handler, a closure having nothing to
/// show about itself.
struct HandlerDebug;

impl Debug for HandlerDebug {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("..")
    }
}

/// Implement [`Debug`] for the handler enums, showing which access to the model the
/// handler takes and whether it is asynchronous, which is all there is to show about it.
macro_rules! impl_handler_debug {
    ($($handler:ident),* $(,)?) => { $(
        impl<M: Model> Debug for $handler<M> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(match self {
                    Self::SharedSync(_) => "SharedSync(..)",
                    Self::ExclusiveSync(_) => "ExclusiveSync(..)",
                    Self::SharedAsync(_) => "SharedAsync(..)",
                    Self::ExclusiveAsync(_) => "ExclusiveAsync(..)",
                })
            }
        }
    )* };
}

impl_handler_debug!(StateFn, StatusFn, ExecFn, ReadFn, WriteFn);

/// A builder for defining a device model and interface.
pub struct ClassDef<M: Model> {
    /// The name of the device class.
    pub(super) name: Cow<'static, str>,
    /// The description every device of that class gives of itself, which is what the
    /// description request of a device answers.
    pub(super) doc: Cow<'static, str>,
    /// Where the documentation of that class is, which is what a client browsing the
    /// control system opens when it is asked to show what a device is. Absent for a class
    /// that documents itself nowhere, which is what a client is then told.
    pub(super) doc_url: Option<Cow<'static, str>>,
    /// The function building the model when the device is initialized.
    pub(super) init: InitFn<M>,
    /// The function called when the device is deleted, given the model back.
    pub(super) delete: Option<DeleteFn<M>>,
    /// The function giving the state of the device, absent to always give [`DevState::On`].
    pub(super) state: Option<StateFn<M>>,
    /// The function giving the status of the device, absent to always give "Device is on".
    pub(super) status: Option<StatusFn<M>>,
    /// The commands every device of that class has, which is the usual way of defining
    /// one: a device is given all of them when it is initialized, and only adds to that
    /// what its own properties decide, see [`Dev::add_command`].
    ///
    /// Behind an [`Arc`] because a definition is fixed once the class is built and shared
    /// by every device of it, only the state the server keeps around it being per-device.
    pub(super) commands: Vec<Arc<CommandDef<M>>>,
    /// The attributes every device of that class has, see [`Self::commands`].
    pub(super) attrs: Vec<Arc<AttrDef<M>>>,
    /// The definition of the State attribute every device has, which is read through the
    /// state function but configured like any other, see [`Self::state_config`].
    pub(super) state_attr: Arc<AttrDef<M>>,
    /// The definition of the Status attribute every device has, see [`Self::state_attr`].
    pub(super) status_attr: Arc<AttrDef<M>>,
}

/// The function building the model of a device, either synchronous or asynchronous, see
/// [`ClassDef::new`] and [`ClassDef::new_async`].
pub enum InitFn<M: Model> {
    Sync(Box<dyn for<'ctx> Fn(&'ctx Dev<M>) -> Result<M> + Send + Sync>),
    Async(Box<dyn for<'a> Fn(&'a Dev<M>) -> BoxFuture<'a, Result<M>> + Send + Sync>),
}
/// The function called when the model of a device is deleted, see [`ClassDef::delete`],
/// either synchronous or asynchronous.
pub enum DeleteFn<M: Model> {
    Sync(Box<dyn for<'ctx> Fn(M, &'ctx Dev<M>) + Send + Sync>),
    Async(Box<dyn for<'a> Fn(M, &'a Dev<M>) -> BoxFuture<'a, ()> + Send + Sync>),
}

/// The state function of a device, with a shared or an exclusive access to the model,
/// either synchronous or asynchronous.
///
/// An asynchronous function borrows the model, the device and, for those that take one,
/// the argument for as long as its future runs, hence the single lifetime they share.
pub enum StateFn<M: Model> {
    SharedSync(Box<dyn for<'m, 'ctx> Fn(&'m M, &'ctx Dev<M>) -> Result<DevState> + Send + Sync>),
    ExclusiveSync(Box<dyn for<'m, 'ctx> Fn(&'m mut M, &'ctx Dev<M>) -> Result<DevState> + Send + Sync>),
    SharedAsync(Box<dyn for<'a> Fn(&'a M, &'a Dev<M>) -> BoxFuture<'a, Result<DevState>> + Send + Sync>),
    ExclusiveAsync(Box<dyn for<'a> Fn(&'a mut M, &'a Dev<M>) -> BoxFuture<'a, Result<DevState>> + Send + Sync>),
}

/// The status function of a device, see [`StateFn`].
pub enum StatusFn<M: Model> {
    SharedSync(Box<dyn for<'m, 'ctx> Fn(&'m M, &'ctx Dev<M>) -> Result<Scalar<str>> + Send + Sync>),
    ExclusiveSync(Box<dyn for<'m, 'ctx> Fn(&'m mut M, &'ctx Dev<M>) -> Result<Scalar<str>> + Send + Sync>),
    SharedAsync(Box<dyn for<'a> Fn(&'a M, &'a Dev<M>) -> BoxFuture<'a, Result<Scalar<str>>> + Send + Sync>),
    ExclusiveAsync(Box<dyn for<'a> Fn(&'a mut M, &'a Dev<M>) -> BoxFuture<'a, Result<Scalar<str>>> + Send + Sync>),
}

/// An asynchronous function of the model and of the device alone, whose result is given
/// as-is, which is what the state function is. See [`ClassDef::state_async`].
///
/// The model is taken as `R`, being either `&'a M` or `&'a mut M` depending on the access
/// the function asks for, and the future may borrow from both the model and the device,
/// which is what an `async fn` method of the model does.
pub trait HandlerAsync<'a, R, M: Model, O> {
    /// Call the function, giving the future of its result.
    fn call(&self, model: R, dev: &'a Dev<M>) -> BoxFuture<'a, Result<O>>;
}

impl<'a, R, M: Model, O, F, Fut> HandlerAsync<'a, R, M, O> for F
where
    F: Fn(R, &'a Dev<M>) -> Fut,
    Fut: Future<Output = Result<O>> + Send + 'a,
{
    #[inline]
    fn call(&self, model: R, dev: &'a Dev<M>) -> BoxFuture<'a, Result<O>> {
        Box::pin(self(model, dev))
    }
}

/// A status function, see [`ClassDef::status`].
///
/// The model is taken as `R`, being either `&M` or `&mut M` depending on the access the
/// function asks for, and the status is anything that converts into a [`Scalar`], which
/// may borrow from the model until it is converted, such as a `&str` the model holds.
pub trait StatusSync<R, M: Model> {
    /// Call the function and convert the status it gives.
    fn call(&self, model: R, dev: &Dev<M>) -> Result<Scalar<str>>;
}

impl<R, M: Model, O, F> StatusSync<R, M> for F
where
    F: Fn(R, &Dev<M>) -> Result<O>,
    O: Into<Scalar<str>>,
{
    #[inline]
    fn call(&self, model: R, dev: &Dev<M>) -> Result<Scalar<str>> {
        self(model, dev).map(Into::into)
    }
}

/// An asynchronous status function, see [`ClassDef::status_async`].
///
/// The model is taken as `R`, being either `&'a M` or `&'a mut M`, see [`HandlerAsync`],
/// and the status may borrow from the model, see [`StatusSync`].
pub trait StatusAsync<'a, R, M: Model> {
    /// Give the future of the status, converted.
    fn call(&self, model: R, dev: &'a Dev<M>) -> BoxFuture<'a, Result<Scalar<str>>>;
}

impl<'a, R, M: Model, O, F, Fut> StatusAsync<'a, R, M> for F
where
    F: Fn(R, &'a Dev<M>) -> Fut,
    Fut: Future<Output = Result<O>> + Send + 'a,
    O: Into<Scalar<str>>,
{
    #[inline]
    fn call(&self, model: R, dev: &'a Dev<M>) -> BoxFuture<'a, Result<Scalar<str>>> {
        let fut = self(model, dev);
        Box::pin(async move { fut.await.map(Into::into) })
    }
}

/// An asynchronous function building the model of a device, see [`ClassDef::new_async`].
///
/// The future may borrow the device, which is what an `async fn` taking it does.
pub trait InitAsync<'a, M: Model> {
    /// Call the function, giving the future of the model.
    fn call(&self, dev: &'a Dev<M>) -> BoxFuture<'a, Result<M>>;
}

impl<'a, M: Model, F, Fut> InitAsync<'a, M> for F
where
    F: Fn(&'a Dev<M>) -> Fut,
    Fut: Future<Output = Result<M>> + Send + 'a,
{
    #[inline]
    fn call(&self, dev: &'a Dev<M>) -> BoxFuture<'a, Result<M>> {
        Box::pin(self(dev))
    }
}

/// An asynchronous function deleting the model of a device, see [`ClassDef::delete_async`].
///
/// The future owns the model and may borrow the device, which is what an `async fn` taking
/// them does.
pub trait DeleteAsync<'a, M: Model> {
    /// Call the function, giving the future of the deletion.
    fn call(&self, model: M, dev: &'a Dev<M>) -> BoxFuture<'a, ()>;
}

impl<'a, M: Model, F, Fut> DeleteAsync<'a, M> for F
where
    F: Fn(M, &'a Dev<M>) -> Fut,
    Fut: Future<Output = ()> + Send + 'a,
{
    #[inline]
    fn call(&self, model: M, dev: &'a Dev<M>) -> BoxFuture<'a, ()> {
        Box::pin(self(model, dev))
    }
}

impl<M: Model> ClassDef<M> {

    /// Create a new class definition, the given function building the model of each
    /// device of that class when it is initialized.
    pub fn new<N, I>(name: N, init: I) -> Self
    where
        N: Into<Cow<'static, str>>,
        I: for<'ctx> Fn(&'ctx Dev<M>) -> Result<M> + Send + Sync + 'static,
    {
        Self::with_init(name.into(), InitFn::Sync(Box::new(init)))
    }

    /// Create a new class definition, the given function building the model of each
    /// device of that class asynchronously when it is initialized. This is the raw form of
    /// [`Self::new_async`], for a closure that boxes its future itself.
    pub fn new_async_with<N, I>(name: N, init: I) -> Self
    where
        N: Into<Cow<'static, str>>,
        I: for<'a> Fn(&'a Dev<M>) -> BoxFuture<'a, Result<M>> + Send + Sync + 'static,
    {
        Self::with_init(name.into(), InitFn::Async(Box::new(init)))
    }

    /// Create a new class definition, the given function building the model of each
    /// device of that class asynchronously when it is initialized, typically an `async fn`
    /// taking the device.
    ///
    /// The model of the device is locked exclusively until the future completes, as it is
    /// for a synchronous one. The future is polled by the server itself when nothing else
    /// of the initialization may block, so it must never block, see [`Self::state_async`].
    pub fn new_async<N, I>(name: N, init: I) -> Self
    where
        N: Into<Cow<'static, str>>,
        I: for<'a> InitAsync<'a, M> + Send + Sync + 'static,
    {
        Self::new_async_with(name, move |dev| init.call(dev))
    }

    fn with_init(name: Cow<'static, str>, init: InitFn<M>) -> Self {
        Self {
            name,
            doc: Cow::Borrowed("A Tango device"),
            doc_url: None,
            init,
            delete: None,
            state: None,
            status: None,
            commands: Vec::new(),
            attrs: Vec::new(),
            state_attr: state_attr(AttrConfig {
                doc: Some(Cow::Borrowed("The state of the device")),
                label: Some(Cow::Borrowed(STATE_NAME)),
                ..AttrConfig::default()
            }),
            status_attr: status_attr(AttrConfig {
                doc: Some(Cow::Borrowed("The status of the device")),
                label: Some(Cow::Borrowed(STATUS_NAME)),
                ..AttrConfig::default()
            }),
        }
    }

    /// Create a new class definition whose model is built with its default value.
    pub fn new_default<N>(name: N) -> Self
    where
        M: Default,
        N: Into<Cow<'static, str>>,
    {
        Self::new(name, |_ctx| Ok(M::default()))
    }

    /// Set the description the devices of that class give of themselves, which is what a
    /// client asking a device what it is gets back, and what a class defines once for all
    /// of its devices.
    pub fn doc<D>(mut self, doc: D) -> Self
    where
        D: Into<Cow<'static, str>>,
    {
        self.doc = doc.into();
        self
    }

    /// Set where the documentation of that class is, which is what a client shows as the
    /// documentation of every device of it: a page describing what the class does, not
    /// what one device of it is doing, which is its status.
    pub fn doc_url<U>(mut self, url: U) -> Self
    where
        U: Into<Cow<'static, str>>,
    {
        self.doc_url = Some(url.into());
        self
    }

    /// Define the function called when the model of a device of that class is deleted,
    /// which is given the model back so that it may release its resources: before every
    /// initialization but the first, which is what the Init command of a device is, and
    /// once the device is no longer served. This is the one place a model releases its
    /// resources, its [`Drop`] being only relied upon to free memory, see [`Model`].
    pub fn delete<F>(mut self, delete: F) -> Self
    where
        F: for<'ctx> Fn(M, &'ctx Dev<M>) + Send + Sync + 'static,
    {
        self.delete = Some(DeleteFn::Sync(Box::new(delete)));
        self
    }

    /// Define the function called when the model of a device of that class is deleted,
    /// asynchronously. This is the raw form of [`Self::delete_async`], for a closure that
    /// boxes its future itself.
    pub fn delete_async_with<F>(mut self, delete: F) -> Self
    where
        F: for<'a> Fn(M, &'a Dev<M>) -> BoxFuture<'a, ()> + Send + Sync + 'static,
    {
        self.delete = Some(DeleteFn::Async(Box::new(delete)));
        self
    }

    /// Define the function called when the model of a device of that class is deleted,
    /// asynchronously, typically an `async fn` taking the model and the device, see
    /// [`Self::delete`].
    ///
    /// The model of the device is locked exclusively until the future completes, as it is
    /// for a synchronous one. The future is polled by the server itself when nothing else
    /// of the deletion may block, so it must never block, see [`Self::state_async`].
    pub fn delete_async<F>(self, delete: F) -> Self
    where
        F: for<'a> DeleteAsync<'a, M> + Send + Sync + 'static,
    {
        self.delete_async_with(move |model, dev| delete.call(model, dev))
    }

    /// Define the function giving the state of the device, with a shared access to the
    /// model, which allows parallel execution of such functions.
    pub fn state<F>(mut self, state: F) -> Self
    where
        F: for<'m, 'ctx> Fn(&'m M, &'ctx Dev<M>) -> Result<DevState> + Send + Sync + 'static,
    {
        self.state = Some(StateFn::SharedSync(Box::new(state)));
        self
    }

    /// Define the function giving the state of the device, with an exclusive access to
    /// the model, therefore no other command or attribute can access it in parallel.
    pub fn state_exclusive<F>(mut self, state: F) -> Self
    where
        F: for<'m, 'ctx> Fn(&'m mut M, &'ctx Dev<M>) -> Result<DevState> + Send + Sync + 'static,
    {
        self.state = Some(StateFn::ExclusiveSync(Box::new(state)));
        self
    }

    /// Define the function giving the state of the device, asynchronously and with a
    /// shared access to the model. This is the raw form of [`Self::state_async`], for a
    /// closure that boxes its future itself.
    pub fn state_async_with<F>(mut self, state: F) -> Self
    where
        F: for<'a> Fn(&'a M, &'a Dev<M>) -> BoxFuture<'a, Result<DevState>> + Send + Sync + 'static,
    {
        self.state = Some(StateFn::SharedAsync(Box::new(state)));
        self
    }

    /// Define the function giving the state of the device, asynchronously and with a
    /// shared access to the model, typically an `async fn` method of the model.
    ///
    /// The model stays borrowed until the future completes, and the future is polled by
    /// the server itself, so it must never block: a function that has to wait on anything
    /// else than another future offloads that wait to a thread of its own.
    pub fn state_async<F>(self, state: F) -> Self
    where
        F: for<'a> HandlerAsync<'a, &'a M, M, DevState> + Send + Sync + 'static,
    {
        self.state_async_with(move |model, dev| state.call(model, dev))
    }

    /// Define the function giving the state of the device, asynchronously and with an
    /// exclusive access to the model. This is the raw form of [`Self::state_exclusive_async`],
    /// see [`Self::state_async_with`].
    pub fn state_exclusive_async_with<F>(mut self, state: F) -> Self
    where
        F: for<'a> Fn(&'a mut M, &'a Dev<M>) -> BoxFuture<'a, Result<DevState>> + Send + Sync + 'static,
    {
        self.state = Some(StateFn::ExclusiveAsync(Box::new(state)));
        self
    }

    /// Define the function giving the state of the device, asynchronously and with an
    /// exclusive access to the model, which no other command or attribute can then access
    /// until the future completes. See [`Self::state_async`].
    pub fn state_exclusive_async<F>(self, state: F) -> Self
    where
        F: for<'a> HandlerAsync<'a, &'a mut M, M, DevState> + Send + Sync + 'static,
    {
        self.state_exclusive_async_with(move |model, dev| state.call(model, dev))
    }

    /// Define the function giving the status of the device, with a shared access to the
    /// model. This is the raw form of [`Self::status`], for a closure that gives a
    /// [`Scalar`] itself.
    pub fn status_with<F>(mut self, status: F) -> Self
    where
        F: for<'m, 'ctx> Fn(&'m M, &'ctx Dev<M>) -> Result<Scalar<str>> + Send + Sync + 'static,
    {
        self.status = Some(StatusFn::SharedSync(Box::new(status)));
        self
    }

    /// Define the function giving the status of the device, with a shared access to the
    /// model.
    ///
    /// The status is anything that converts into a [`Scalar`], and may borrow from the
    /// model: it is then written as a function item generic over the model lifetime,
    /// typically an associated method of the model, which `StatusSync` describes.
    pub fn status<F>(self, status: F) -> Self
    where
        F: for<'m> StatusSync<&'m M, M> + Send + Sync + 'static,
    {
        self.status_with(move |model, dev| status.call(model, dev))
    }

    /// Define the function giving the status of the device, with an exclusive access to
    /// the model. This is the raw form of [`Self::status_exclusive`], see
    /// [`Self::status_with`].
    pub fn status_exclusive_with<F>(mut self, status: F) -> Self
    where
        F: for<'m, 'ctx> Fn(&'m mut M, &'ctx Dev<M>) -> Result<Scalar<str>> + Send + Sync + 'static,
    {
        self.status = Some(StatusFn::ExclusiveSync(Box::new(status)));
        self
    }

    /// Define the function giving the status of the device, with an exclusive access to
    /// the model, see [`Self::status`].
    pub fn status_exclusive<F>(self, status: F) -> Self
    where
        F: for<'m> StatusSync<&'m mut M, M> + Send + Sync + 'static,
    {
        self.status_exclusive_with(move |model, dev| status.call(model, dev))
    }

    /// Define the function giving the status of the device, asynchronously and with a
    /// shared access to the model. This is the raw form of [`Self::status_async`], see
    /// [`Self::state_async_with`].
    pub fn status_async_with<F>(mut self, status: F) -> Self
    where
        F: for<'a> Fn(&'a M, &'a Dev<M>) -> BoxFuture<'a, Result<Scalar<str>>> + Send + Sync + 'static,
    {
        self.status = Some(StatusFn::SharedAsync(Box::new(status)));
        self
    }

    /// Define the function giving the status of the device, asynchronously and with a
    /// shared access to the model, see [`Self::state_async`].
    pub fn status_async<F>(self, status: F) -> Self
    where
        F: for<'a> StatusAsync<'a, &'a M, M> + Send + Sync + 'static,
    {
        self.status_async_with(move |model, dev| status.call(model, dev))
    }

    /// Define the function giving the status of the device, asynchronously and with an
    /// exclusive access to the model. This is the raw form of
    /// [`Self::status_exclusive_async`], see [`Self::state_async_with`].
    pub fn status_exclusive_async_with<F>(mut self, status: F) -> Self
    where
        F: for<'a> Fn(&'a mut M, &'a Dev<M>) -> BoxFuture<'a, Result<Scalar<str>>> + Send + Sync + 'static,
    {
        self.status = Some(StatusFn::ExclusiveAsync(Box::new(status)));
        self
    }

    /// Define the function giving the status of the device, asynchronously and with an
    /// exclusive access to the model, see [`Self::state_exclusive_async`].
    pub fn status_exclusive_async<F>(self, status: F) -> Self
    where
        F: for<'a> StatusAsync<'a, &'a mut M, M> + Send + Sync + 'static,
    {
        self.status_exclusive_async_with(move |model, dev| status.call(model, dev))
    }

    /// Define a command every device of that class has, which is what defining a command
    /// usually means: the devices of a class have the same interface, and a device only
    /// adds to its own the part of it that its properties decide, see [`Dev::add_command`].
    ///
    /// # Panics
    ///
    /// If the class already defines a command of that name, if the name is invalid, see
    /// [`name::check_tango_command_name`], or if it is one of the commands the server
    /// answers itself, being `State`, `Status` and `Init`.
    #[track_caller]
    pub fn command(mut self, def: CommandDef<M>) -> Self {
        check_own_name(&self.name, "command", &def.name, name::check_tango_command_name, RESERVED_COMMANDS);
        if self.commands.iter().any(|other| other.name.eq_ignore_ascii_case(&def.name)) {
            panic!("{}: the command {} is already defined", self.name, def.name);
        }
        self.commands.push(Arc::new(def));
        self
    }

    /// Define an attribute every device of that class has, see [`Self::command`].
    ///
    /// # Panics
    ///
    /// If the class already defines an attribute of that name, if the name is invalid, see
    /// [`name::check_tango_attr_name`], if it is one of the attributes the server answers
    /// itself, being `State` and `Status`, or if the definition is inconsistent: memorized
    /// without being a writable scalar of a kind that can be memorized, see
    /// [`AttrDef::memorized`], or with a configuration giving a value to a property its kind
    /// does not support, see [`AttrConfig`].
    #[track_caller]
    pub fn attr(mut self, def: AttrDef<M>) -> Self {
        check_own_name(&self.name, "attribute", &def.name, name::check_tango_attr_name, RESERVED_ATTRS);
        if let Err(err) = def.check() {
            panic!("{}: {err}", self.name);
        }
        if self.attrs.iter().any(|other| other.name.eq_ignore_ascii_case(&def.name)) {
            panic!("{}: the attribute {} is already defined", self.name, def.name);
        }
        self.attrs.push(Arc::new(def));
        self
    }

    /// Set the configuration the State attribute of every device of that class starts
    /// from, which the database and clients then override like the one of any attribute.
    /// The default one only gives it a label and a description.
    ///
    /// # Panics
    ///
    /// If the configuration gives a value to a property a state does not support, such as
    /// a bound or an event criterion, see [`AttrConfig`].
    #[track_caller]
    pub fn state_config(mut self, config: AttrConfig) -> Self {
        self.state_attr = state_attr(config);
        self
    }

    /// Set the configuration the Status attribute of every device of that class starts
    /// from, see [`Self::state_config`].
    ///
    /// # Panics
    ///
    /// If the configuration gives a value to a property a string does not support, see
    /// [`Self::state_config`].
    #[track_caller]
    pub fn status_config(mut self, config: AttrConfig) -> Self {
        self.status_attr = status_attr(config);
        self
    }

    /// Declare that the devices of that class push the events of their State themselves,
    /// change and archive, see [`AttrDef::push_change_event`]. For each, `Some(detect)`
    /// declares the event pushed by the device, `detect` telling whether its criteria are
    /// checked against what is pushed, and `None` declares it not pushed.
    pub fn push_state_events(mut self, change: Option<bool>, archive: Option<bool>) -> Self {
        builtin_pushed(&mut self.state_attr, change, archive);
        self
    }

    /// Declare that the devices of that class push the events of their Status themselves,
    /// see [`Self::push_state_events`].
    pub fn push_status_events(mut self, change: Option<bool>, archive: Option<bool>) -> Self {
        builtin_pushed(&mut self.status_attr, change, archive);
        self
    }

}

/// The definition of the State attribute, with that configuration.
#[track_caller]
fn state_attr<M: Model>(config: AttrConfig) -> Arc<AttrDef<M>> {
    builtin_attr(STATE_NAME, AttrDataKind::State, config)
}

/// The definition of the Status attribute, with that configuration.
#[track_caller]
fn status_attr<M: Model>(config: AttrConfig) -> Arc<AttrDef<M>> {
    builtin_attr(STATUS_NAME, AttrDataKind::String, config)
}

/// Declare the events pushed for one of the attributes the server answers itself, whose
/// definition only its class holds while it is built.
fn builtin_pushed<M: Model>(def: &mut Arc<AttrDef<M>>, change: Option<bool>, archive: Option<bool>) {
    let def = Arc::get_mut(def).expect("a class being built is the only owner of its definitions");
    def.pushed.change = change;
    def.pushed.archive = archive;
}

/// The definition of one of the attributes the server answers itself, a read-only scalar
/// of that kind with that configuration.
#[track_caller]
fn builtin_attr<M: Model>(name: &'static str, kind: AttrDataKind, config: AttrConfig) -> Arc<AttrDef<M>> {
    let mut def = AttrDef::new(name).kind(kind).scalar();
    def.display_level = DisplayLevel::Operator;
    def.config = config;
    if let Err(err) = def.check() {
        panic!("{err}");
    }
    Arc::new(def)
}

/// Refuse a name that the given check finds invalid, or that belongs to the server rather
/// than to the class: the state, the status and the initialization of a device are
/// answered by the server itself, whatever its class, so a definition of that name would
/// never be reached and is a mistake worth pointing out where it is written rather than
/// leaving to be found at runtime.
#[track_caller]
fn check_own_name(class: &str, what: &str, name: &str, valid: fn(&str) -> bool, reserved: &[&str]) {
    if !valid(name) {
        panic!("{class}: the {what} name {name:?} is invalid");
    }
    if let Some(reserved) = reserved_name(name, reserved) {
        panic!("{class}: the {what} {name} cannot be defined by a class, \
            {reserved} is answered by the server itself");
    }
}

impl<M: Model> Debug for ClassDef<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClassDef")
            .field("name", &self.name)
            .field("doc", &self.doc)
            .field("doc_url", &self.doc_url)
            .field("init", &HandlerDebug)
            .field("delete", &self.delete.as_ref().map(|_| HandlerDebug))
            .field("state", &self.state)
            .field("status", &self.status)
            .field("commands", &self.commands)
            .field("attrs", &self.attrs)
            .field("state_attr", &self.state_attr)
            .field("status_attr", &self.status_attr)
            .finish()
    }
}

/// A builder for defining a command of a device.
pub struct CommandDef<M: Model> {
    /// The name of the command.
    pub(super) name: Cow<'static, str>,
    /// The function executing the command.
    pub(super) exec: Option<ExecFn<M>>,
    /// The advertised kind of the argument, derived from the execution function, absent
    /// until it is defined and then defaulting to [`CommandDataKind::Void`].
    pub(super) in_kind: Option<CommandDataKind>,
    /// The documentation of the argument.
    pub(super) in_doc: Cow<'static, str>,
    /// The advertised kind of the result, derived from the execution function, absent
    /// until it is defined and then defaulting to [`CommandDataKind::Void`].
    pub(super) out_kind: Option<CommandDataKind>,
    /// The documentation of the result.
    pub(super) out_doc: Cow<'static, str>,
    /// The display level of the command, which is all a command has of a configuration:
    /// unlike an attribute, nothing about it can be changed once the class is defined.
    pub(super) display_level: DisplayLevel,
    /// The polling period this command asks for, absent for one that is not polled unless
    /// the database says otherwise.
    pub(super) poll_period: Option<Duration>,
}

/// The execution function of a command, with a shared or an exclusive access to the model,
/// either synchronous or asynchronous, see [`StateFn`].
pub enum ExecFn<M: Model> {
    SharedSync(Box<dyn Fn(&M, &Dev<M>, Value) -> Result<Value> + Send + Sync>),
    ExclusiveSync(Box<dyn Fn(&mut M, &Dev<M>, Value) -> Result<Value> + Send + Sync>),
    SharedAsync(Box<dyn for<'a> Fn(&'a M, &'a Dev<M>, Value) -> BoxFuture<'a, Result<Value>> + Send + Sync>),
    ExclusiveAsync(Box<dyn for<'a> Fn(&'a mut M, &'a Dev<M>, Value) -> BoxFuture<'a, Result<Value>> + Send + Sync>),
}

/// An execution function of a command with a shared access to the model, whose result may
/// borrow from it until it is converted into a value. See [`CommandDef::exec`].
pub trait ExecShared<'m, M: Model, I> {
    /// The advertised kind of the argument, derived from its type.
    const IN_KIND: CommandDataKind;
    /// The advertised kind of the result, derived from its type.
    const OUT_KIND: CommandDataKind;
    /// Convert the given argument, execute the command and convert its result.
    fn exec(&self, model: &'m M, dev: &Dev<M>, input: Value) -> Result<Value>;
}

impl<'m, M: Model, I, O, F> ExecShared<'m, M, I> for F
where
    I: FromValue + CommandData,
    O: IntoValue + CommandData,
    F: Fn(&'m M, &Dev<M>, I) -> Result<O>,
{

    const IN_KIND: CommandDataKind = I::DATA_KIND;
    const OUT_KIND: CommandDataKind = O::DATA_KIND;

    #[inline]
    fn exec(&self, model: &'m M, dev: &Dev<M>, input: Value) -> Result<Value> {
        Ok(self(model, dev, I::from_value(input)?)?.into_value())
    }
    
}

/// The exclusive counterpart of [`ExecShared`], see [`CommandDef::exec_exclusive`].
pub trait ExecExclusive<'m, M: Model, I> {
    /// The advertised kind of the argument, derived from its type.
    const IN_KIND: CommandDataKind;
    /// The advertised kind of the result, derived from its type.
    const OUT_KIND: CommandDataKind;
    /// Convert the given argument, execute the command and convert its result.
    fn exec(&self, model: &'m mut M, dev: &Dev<M>, input: Value) -> Result<Value>;
}

impl<'m, M: Model, I, O, F> ExecExclusive<'m, M, I> for F
where
    I: FromValue + CommandData,
    O: IntoValue + CommandData,
    F: Fn(&'m mut M, &Dev<M>, I) -> Result<O>,
{

    const IN_KIND: CommandDataKind = I::DATA_KIND;
    const OUT_KIND: CommandDataKind = O::DATA_KIND;

    #[inline]
    fn exec(&self, model: &'m mut M, dev: &Dev<M>, input: Value) -> Result<Value> {
        Ok(self(model, dev, I::from_value(input)?)?.into_value())
    }

}

/// An asynchronous execution function of a command, see [`CommandDef::exec_async`].
///
/// The model is taken as `R`, being either `&'a M` or `&'a mut M`, see [`HandlerAsync`],
/// and the future may borrow from the model and the device, its result being allowed to
/// borrow from both until it is converted into a value.
pub trait ExecAsync<'a, R, M: Model, I> {
    /// The advertised kind of the argument, derived from its type.
    const IN_KIND: CommandDataKind;
    /// The advertised kind of the result, derived from its type.
    const OUT_KIND: CommandDataKind;
    /// Convert the given argument and give the future executing the command and
    /// converting its result.
    fn exec(&self, model: R, dev: &'a Dev<M>, input: Value) -> BoxFuture<'a, Result<Value>>;
}

impl<'a, R, M: Model, I, O, F, Fut> ExecAsync<'a, R, M, I> for F
where
    I: FromValue + CommandData,
    O: IntoValue + CommandData,
    F: Fn(R, &'a Dev<M>, I) -> Fut,
    Fut: Future<Output = Result<O>> + Send + 'a,
{

    const IN_KIND: CommandDataKind = I::DATA_KIND;
    const OUT_KIND: CommandDataKind = O::DATA_KIND;

    #[inline]
    fn exec(&self, model: R, dev: &'a Dev<M>, input: Value) -> BoxFuture<'a, Result<Value>> {
        // The function is called right away rather than on the first poll, so that
        // whatever it starts before its first await is started with the request.
        let fut = I::from_value(input).map(|input| self(model, dev, input));
        Box::pin(async move { Ok(fut?.await?.into_value()) })
    }

}

impl<M: Model> CommandDef<M> {

    /// Create a new command definition, without any execution function.
    pub fn new<N>(name: N) -> Self
    where
        N: Into<Cow<'static, str>>,
    {
        Self {
            name: name.into(),
            exec: None,
            in_kind: None,
            in_doc: Cow::Borrowed(""),
            out_kind: None,
            out_doc: Cow::Borrowed(""),
            display_level: DisplayLevel::default(),
            poll_period: None,
        }
    }

    /// Set the documentation of the command argument (argin).
    ///
    /// A command has no description of its own, Tango only telling a client what each
    /// side of it is, so what the command does has to be said in one of these two.
    pub fn in_doc<D>(mut self, doc: D) -> Self
    where
        D: Into<Cow<'static, str>>,
    {
        self.in_doc = doc.into();
        self
    }

    /// Set the documentation of the command result (argout).
    pub fn out_doc<D>(mut self, doc: D) -> Self
    where
        D: Into<Cow<'static, str>>,
    {
        self.out_doc = doc.into();
        self
    }

    /// Set the display level of the command, [`DisplayLevel::Expert`] keeping it out of
    /// the panels an operator is shown without keeping it from anyone who asks for it.
    pub fn display_level(mut self, level: DisplayLevel) -> Self {
        self.display_level = level;
        self
    }

    /// Ask for the command to be polled at that period, its result being recorded in its
    /// history, which a request from the cache is answered with, see [`super::Command`].
    ///
    /// Only a command that takes no argument can be polled, there being no argument for
    /// the server to invent.
    ///
    /// This period comes second: a command the `polled_cmd` property of the device lists
    /// is polled at the period the property gives, and one it does not list at this one.
    /// The admin device changes it while the device runs, writing the property along, but
    /// a command removed from the polling this way is polled at this period again from the
    /// next initialization of the device, the property having no way to say it is not.
    pub fn polled(mut self, period: Duration) -> Self {
        self.poll_period = Some(period);
        self
    }

    /// Set the advertised kind of the command argument (argin). This is only needed for
    /// the execution functions that take a raw [`Value`] argument, the typed ones derive
    /// it from their input type.
    ///
    /// # Panics
    ///
    /// If the argument kind has already been defined, explicitly or by an execution
    /// function, as a different kind.
    #[track_caller]
    pub fn in_kind(mut self, kind: CommandDataKind) -> Self {
        self.in_kind = Some(merge_kind(&self.name, "argument kind", self.in_kind.take(), kind));
        self
    }

    /// Set the advertised kind of the command result (argout). This is only needed for
    /// the execution functions that return a raw [`Value`], the typed ones derive it from
    /// their output type.
    ///
    /// # Panics
    ///
    /// If the result kind has already been defined, explicitly or by an execution
    /// function, as a different kind.
    #[track_caller]
    pub fn out_kind(mut self, kind: CommandDataKind) -> Self {
        self.out_kind = Some(merge_kind(&self.name, "result kind", self.out_kind.take(), kind));
        self
    }

    /// Define the execution function of this command, with a shared access to the model.
    ///
    /// This is the raw form of [`Self::exec`]: the closure is given the argument
    /// [`Value`] as-is and returns one, converting what it borrows from the model itself,
    /// which is what makes a closure usable for such a result. Because no input and output
    /// types are involved, the advertised kinds have to be given with [`Self::in_kind`]
    /// and [`Self::out_kind`].
    pub fn exec_with<F>(mut self, func: F) -> Self
    where
        F: Fn(&M, &Dev<M>, Value) -> Result<Value> + Send + Sync + 'static,
    {
        self.exec = Some(ExecFn::SharedSync(Box::new(func)));
        self
    }

    /// Define the execution function of this command, with a shared access to the model,
    /// which allows parallel execution of such functions.
    ///
    /// The argument and result types are taken from the `ExecShared` implementation of
    /// the function. The result may borrow from the model, being converted into a value
    /// before the model is released, which requires a function item generic over the
    /// model lifetime, typically an associated method of the model.
    ///
    /// # Panics
    ///
    /// If either advertised kind has already been defined as a different kind, see
    /// [`Self::in_kind`] and [`Self::out_kind`].
    #[track_caller]
    pub fn exec<F, I>(self, func: F) -> Self
    where
        F: for<'m> ExecShared<'m, M, I> + Send + Sync + 'static,
    {
        self.in_kind(F::IN_KIND)
            .out_kind(F::OUT_KIND)
            .exec_with(move |model, dev, value| func.exec(model, dev, value))
    }

    /// Define the execution function of this command, with an exclusive access to the
    /// model. This is the raw form of [`Self::exec_exclusive`], see [`Self::exec_with`].
    pub fn exec_exclusive_with<F>(mut self, func: F) -> Self
    where
        F: Fn(&mut M, &Dev<M>, Value) -> Result<Value> + Send + Sync + 'static,
    {
        self.exec = Some(ExecFn::ExclusiveSync(Box::new(func)));
        self
    }

    /// Define the execution function of this command, with an exclusive access to the
    /// model, therefore no other command or attribute can access it in parallel.
    ///
    /// See [`Self::exec`] for the constraints on the argument and result types, this one
    /// is only different in that its function item takes the model by exclusive reference.
    ///
    /// # Panics
    ///
    /// If either advertised kind has already been defined as a different kind, see
    /// [`Self::in_kind`] and [`Self::out_kind`].
    #[track_caller]
    pub fn exec_exclusive<F, I>(self, func: F) -> Self
    where
        F: for<'m> ExecExclusive<'m, M, I> + Send + Sync + 'static,
    {
        self.in_kind(F::IN_KIND)
            .out_kind(F::OUT_KIND)
            .exec_exclusive_with(move |model, dev, value| func.exec(model, dev, value))
    }

    /// Define the execution function of this command, asynchronously and with a shared
    /// access to the model. This is the raw form of [`Self::exec_async`], for a closure
    /// that boxes its future itself, see [`Self::exec_with`].
    pub fn exec_async_with<F>(mut self, func: F) -> Self
    where
        F: for<'a> Fn(&'a M, &'a Dev<M>, Value) -> BoxFuture<'a, Result<Value>> + Send + Sync + 'static,
    {
        self.exec = Some(ExecFn::SharedAsync(Box::new(func)));
        self
    }

    /// Define the execution function of this command, asynchronously and with a shared
    /// access to the model, typically an `async fn` method of the model.
    ///
    /// This is what a command forwarding its execution to other devices is written as:
    /// it holds no thread while it waits on them, and may wait on many of them at once.
    /// The future is polled by the server itself, so it must never block, see
    /// [`ClassDef::state_async`].
    ///
    /// # Panics
    ///
    /// If either advertised kind has already been defined as a different kind, see
    /// [`Self::in_kind`] and [`Self::out_kind`].
    #[track_caller]
    pub fn exec_async<F, I>(self, func: F) -> Self
    where
        F: for<'a> ExecAsync<'a, &'a M, M, I> + Send + Sync + 'static,
    {
        self.in_kind(F::IN_KIND)
            .out_kind(F::OUT_KIND)
            .exec_async_with(move |model, dev, value| func.exec(model, dev, value))
    }

    /// Define the execution function of this command, asynchronously and with an
    /// exclusive access to the model. This is the raw form of [`Self::exec_exclusive_async`],
    /// see [`Self::exec_async_with`].
    pub fn exec_exclusive_async_with<F>(mut self, func: F) -> Self
    where
        F: for<'a> Fn(&'a mut M, &'a Dev<M>, Value) -> BoxFuture<'a, Result<Value>> + Send + Sync + 'static,
    {
        self.exec = Some(ExecFn::ExclusiveAsync(Box::new(func)));
        self
    }

    /// Define the execution function of this command, asynchronously and with an
    /// exclusive access to the model, which no other command or attribute can then access
    /// until the future completes. See [`Self::exec_async`].
    ///
    /// # Panics
    ///
    /// If either advertised kind has already been defined as a different kind, see
    /// [`Self::in_kind`] and [`Self::out_kind`].
    #[track_caller]
    pub fn exec_exclusive_async<F, I>(self, func: F) -> Self
    where
        F: for<'a> ExecAsync<'a, &'a mut M, M, I> + Send + Sync + 'static,
    {
        self.in_kind(F::IN_KIND)
            .out_kind(F::OUT_KIND)
            .exec_exclusive_async_with(move |model, dev, value| func.exec(model, dev, value))
    }

}

impl<M: Model> Debug for CommandDef<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CommandDef")
            .field("name", &self.name)
            .field("exec", &self.exec)
            .field("in_kind", &self.in_kind)
            .field("in_doc", &self.in_doc)
            .field("out_kind", &self.out_kind)
            .field("out_doc", &self.out_doc)
            .field("display_level", &self.display_level)
            .field("poll_period", &self.poll_period)
            .finish()
    }
}

/// A builder for defining an attribute of a device.
pub struct AttrDef<M: Model> {
    /// The name of the attribute.
    pub(super) name: Cow<'static, str>,
    /// The function reading the attribute value, absent for a write-only attribute.
    pub(super) read: Option<ReadFn<M>>,
    /// The function writing the attribute value, absent for a read-only attribute.
    pub(super) write: Option<WriteFn<M>>,
    /// The advertised data kind, derived from the read and write functions.
    pub(super) kind: Option<AttrDataKind>,
    /// The advertised data format, derived from the read and write functions.
    pub(super) format: Option<AttrDataFormat>,
    /// The display level the attribute is shown at, which the class declares and a client
    /// cannot change, unlike the configuration below.
    pub(super) display_level: DisplayLevel,
    /// What the attribute does with the value of a write when the device is initialized
    /// again, absent for one that remembers nothing, which the class declares as well.
    pub(super) memorized: Option<AttrMemorized>,
    /// Everything a client may read about the attribute and, for most of it, change: its
    /// documentation, its units, its bounds and its event criteria. Every device of the
    /// class starts from this one and owns its copy from then on, because the database
    /// overrides it per device and a client changes it per device.
    pub(super) config: AttrConfig,
    /// The polling period this attribute asks for, absent for one that is not polled
    /// unless the database says otherwise.
    pub(super) poll_period: Option<Duration>,
    /// The events the device pushes itself for this attribute, see
    /// [`Self::push_change_event`].
    pub(super) pushed: PushedEvents,
}

/// The events a device declares it pushes itself for an attribute, each with whether the
/// criteria of its configuration are checked against what is pushed, see
/// [`AttrDef::push_change_event`], and whether it announces it ready to be read, see
/// [`AttrDef::push_data_ready_event`].
#[derive(Debug, Clone, Copy, Default)]
pub(super) struct PushedEvents {
    pub change: Option<bool>,
    pub archive: Option<bool>,
    pub data_ready: bool,
}

/// The read function of an attribute, with a shared or an exclusive access to the model,
/// either synchronous or asynchronous, see [`StateFn`].
pub enum ReadFn<M: Model> {
    SharedSync(Box<dyn Fn(&M, &Dev<M>) -> Result<AttrRead<Value>> + Send + Sync>),
    ExclusiveSync(Box<dyn Fn(&mut M, &Dev<M>) -> Result<AttrRead<Value>> + Send + Sync>),
    SharedAsync(Box<dyn for<'a> Fn(&'a M, &'a Dev<M>) -> BoxFuture<'a, Result<AttrRead<Value>>> + Send + Sync>),
    ExclusiveAsync(Box<dyn for<'a> Fn(&'a mut M, &'a Dev<M>) -> BoxFuture<'a, Result<AttrRead<Value>>> + Send + Sync>),
}

/// The write function of an attribute, with a shared or an exclusive access to the model,
/// either synchronous or asynchronous, see [`StateFn`].
pub enum WriteFn<M: Model> {
    SharedSync(Box<dyn Fn(&M, &Dev<M>, Value) -> Result<()> + Send + Sync>),
    ExclusiveSync(Box<dyn Fn(&mut M, &Dev<M>, Value) -> Result<()> + Send + Sync>),
    SharedAsync(Box<dyn for<'a> Fn(&'a M, &'a Dev<M>, Value) -> BoxFuture<'a, Result<()>> + Send + Sync>),
    ExclusiveAsync(Box<dyn for<'a> Fn(&'a mut M, &'a Dev<M>, Value) -> BoxFuture<'a, Result<()>> + Send + Sync>),
}

/// A trait for abstracting what output types are accepted by read attribute methods: a
/// value alone, its quality and timestamp then being implicit, or a whole [`AttrRead`].
pub trait ReadOutput {
    /// The advertised kind of the value, derived from its type.
    const DATA_KIND: AttrDataKind;
    /// The advertised format of the value, without any maximum dimension.
    const DATA_FORMAT: AttrDataFormat;
    /// Convert this output into a read result, an absent write value asking the server
    /// to fill it with the latest one it has written.
    fn into_read(self) -> AttrRead<Value>;
}

impl<O> ReadOutput for O
where
    O: IntoValue + AttrData,
{
    
    const DATA_KIND: AttrDataKind = O::DATA_KIND;
    const DATA_FORMAT: AttrDataFormat = O::DATA_FORMAT;

    fn into_read(self) -> AttrRead<Value> {
        AttrRead {
            value: Some(self.into_value()),
            // An absent write value asks the server to fill it with the latest one it
            // has written, which is the usual behaviour of a read function.
            w_value: None,
            quality: AttrQuality::Valid,
            time: SystemTime::now(),
        }
    }
    
}

impl<O> ReadOutput for AttrRead<O>
where
    O: IntoValue + AttrData,
{

    const DATA_KIND: AttrDataKind = O::DATA_KIND;
    const DATA_FORMAT: AttrDataFormat = O::DATA_FORMAT;

    fn into_read(self) -> AttrRead<Value> {
        AttrRead {
            value: self.value.map(IntoValue::into_value),
            // A write value given by the read function replaces the one the server keeps,
            // so a next read that gives none answers this one.
            w_value: self.w_value.map(IntoValue::into_value),
            quality: self.quality,
            time: self.time,
        }
    }

}

/// A read function with a shared access to the model, whose result may borrow from it
/// until it is converted into a value. See [`AttrDef::read`], the same constraints as
/// [`ExecShared`] apply to the result type.
pub trait ReadShared<'m, M: Model> {
    /// The advertised kind of the value, derived from its type.
    const DATA_KIND: AttrDataKind;
    /// The advertised format of the value, without any maximum dimension.
    const DATA_FORMAT: AttrDataFormat;
    /// Read the value of the attribute and convert it.
    fn read(&self, model: &'m M, dev: &Dev<M>) -> Result<AttrRead<Value>>;
}

impl<'m, M: Model, O, F> ReadShared<'m, M> for F
where
    F: Fn(&'m M, &Dev<M>) -> Result<O>,
    O: ReadOutput,
{
    const DATA_KIND: AttrDataKind = O::DATA_KIND;
    const DATA_FORMAT: AttrDataFormat = O::DATA_FORMAT;

    #[inline]
    fn read(&self, model: &'m M, dev: &Dev<M>) -> Result<AttrRead<Value>> {
        Ok(self(model, dev)?.into_read())
    }
}

/// The exclusive counterpart of [`ReadShared`], see [`AttrDef::read_exclusive`].
pub trait ReadExclusive<'m, M: Model> {
    /// The advertised kind of the value, derived from its type.
    const DATA_KIND: AttrDataKind;
    /// The advertised format of the value, without any maximum dimension.
    const DATA_FORMAT: AttrDataFormat;
    /// Read the value of the attribute and convert it.
    fn read(&self, model: &'m mut M, dev: &Dev<M>) -> Result<AttrRead<Value>>;
}

impl<'m, M: Model, O, F> ReadExclusive<'m, M> for F
where
    F: Fn(&'m mut M, &Dev<M>) -> Result<O>,
    O: ReadOutput,
{
    const DATA_KIND: AttrDataKind = O::DATA_KIND;
    const DATA_FORMAT: AttrDataFormat = O::DATA_FORMAT;

    #[inline]
    fn read(&self, model: &'m mut M, dev: &Dev<M>) -> Result<AttrRead<Value>> {
        Ok(self(model, dev)?.into_read())
    }
}

/// A write function with a shared access to the model. See [`AttrDef::write`].
pub trait WriteShared<M: Model, I> {
    /// The advertised kind of the value, derived from its type.
    const DATA_KIND: AttrDataKind;
    /// The advertised format of the value, without any maximum dimension.
    const DATA_FORMAT: AttrDataFormat;
    /// Convert the given value and write it to the attribute.
    fn write(&self, model: &M, dev: &Dev<M>, value: Value) -> Result<()>;
}

impl<M: Model, I, F> WriteShared<M, I> for F
where
    F: Fn(&M, &Dev<M>, I) -> Result<()>,
    I: FromValue + AttrData,
{
    const DATA_KIND: AttrDataKind = I::DATA_KIND;
    const DATA_FORMAT: AttrDataFormat = I::DATA_FORMAT;

    #[inline]
    fn write(&self, model: &M, dev: &Dev<M>, value: Value) -> Result<()> {
        self(model, dev, I::from_value(value)?)
    }
}

/// The exclusive counterpart of [`WriteShared`], see [`AttrDef::write_exclusive`].
pub trait WriteExclusive<M: Model, I> {
    /// The advertised kind of the value, derived from its type.
    const DATA_KIND: AttrDataKind;
    /// The advertised format of the value, without any maximum dimension.
    const DATA_FORMAT: AttrDataFormat;
    /// Convert the given value and write it to the attribute.
    fn write(&self, model: &mut M, dev: &Dev<M>, value: Value) -> Result<()>;
}

impl<M: Model, I, F> WriteExclusive<M, I> for F
where
    F: Fn(&mut M, &Dev<M>, I) -> Result<()>,
    I: FromValue + AttrData,
{
    const DATA_KIND: AttrDataKind = I::DATA_KIND;
    const DATA_FORMAT: AttrDataFormat = I::DATA_FORMAT;

    #[inline]
    fn write(&self, model: &mut M, dev: &Dev<M>, value: Value) -> Result<()> {
        self(model, dev, I::from_value(value)?)
    }
}

/// An asynchronous read function of an attribute, see [`AttrDef::read_async`].
///
/// The model is taken as `R`, being either `&'a M` or `&'a mut M`, see [`HandlerAsync`],
/// and the value may borrow from the model, with the same result types as [`ReadShared`].
pub trait ReadAsync<'a, R, M: Model> {
    /// The advertised kind of the value, derived from its type.
    const DATA_KIND: AttrDataKind;
    /// The advertised format of the value, without any maximum dimension.
    const DATA_FORMAT: AttrDataFormat;
    /// Give the future reading the value of the attribute and converting it.
    fn read(&self, model: R, dev: &'a Dev<M>) -> BoxFuture<'a, Result<AttrRead<Value>>>;
}

impl<'a, R, M: Model, O, F, Fut> ReadAsync<'a, R, M> for F
where
    F: Fn(R, &'a Dev<M>) -> Fut,
    Fut: Future<Output = Result<O>> + Send + 'a,
    O: ReadOutput,
{
    const DATA_KIND: AttrDataKind = O::DATA_KIND;
    const DATA_FORMAT: AttrDataFormat = O::DATA_FORMAT;

    #[inline]
    fn read(&self, model: R, dev: &'a Dev<M>) -> BoxFuture<'a, Result<AttrRead<Value>>> {
        let fut = self(model, dev);
        Box::pin(async move { Ok(fut.await?.into_read()) })
    }
}

/// An asynchronous write function of an attribute, see [`AttrDef::write_async`].
///
/// The model is taken as `R`, being either `&'a M` or `&'a mut M`, see [`HandlerAsync`].
pub trait WriteAsync<'a, R, M: Model, I> {
    /// The advertised kind of the value, derived from its type.
    const DATA_KIND: AttrDataKind;
    /// The advertised format of the value, without any maximum dimension.
    const DATA_FORMAT: AttrDataFormat;
    /// Convert the given value and give the future writing it to the attribute.
    fn write(&self, model: R, dev: &'a Dev<M>, value: Value) -> BoxFuture<'a, Result<()>>;
}

impl<'a, R, M: Model, I, F, Fut> WriteAsync<'a, R, M, I> for F
where
    F: Fn(R, &'a Dev<M>, I) -> Fut,
    Fut: Future<Output = Result<()>> + Send + 'a,
    I: FromValue + AttrData,
{
    const DATA_KIND: AttrDataKind = I::DATA_KIND;
    const DATA_FORMAT: AttrDataFormat = I::DATA_FORMAT;

    #[inline]
    fn write(&self, model: R, dev: &'a Dev<M>, value: Value) -> BoxFuture<'a, Result<()>> {
        let fut = I::from_value(value).map(|input| self(model, dev, input));
        Box::pin(async move { fut?.await })
    }
}

impl<M: Model> AttrDef<M> {

    /// Create a new attribute definition, without any read or write function.
    pub fn new<N>(name: N) -> Self
    where
        N: Into<Cow<'static, str>>,
    {
        Self {
            name: name.into(),
            read: None,
            write: None,
            kind: None,
            format: None,
            display_level: DisplayLevel::default(),
            memorized: None,
            config: AttrConfig::default(),
            poll_period: None,
            pushed: PushedEvents::default(),
        }
    }

    // --- Documentation --- //

    /// Set the description of the attribute, which every device of the class starts from;
    /// like the rest of its configuration, the database and clients may override it per
    /// device.
    pub fn doc<D>(mut self, doc: D) -> Self
    where
        D: Into<Cow<'static, str>>,
    {
        self.config.doc = Some(doc.into());
        self
    }

    /// Set the label of the attribute, the short name a client shows in place of its own,
    /// where "Position" reads better than "position" and "Δθ" than "delta_theta".
    pub fn label<L>(mut self, label: L) -> Self
    where
        L: Into<Cow<'static, str>>,
    {
        self.config.label = Some(label.into());
        self
    }

    /// Set the unit the value is expressed in, as it is shown next to it.
    pub fn unit<U>(mut self, unit: U) -> Self
    where
        U: Into<Cow<'static, str>>,
    {
        self.config.unit = Some(unit.into());
        self
    }

    /// Set the factor going from the value of the attribute to the same quantity in the
    /// international system, so that a client can convert without knowing the unit: 1e-3
    /// for a value in millimetres, the metre being the standard unit of a length.
    pub fn standard_unit(mut self, factor: f64) -> Self {
        self.config.standard_unit = Some(factor);
        self
    }

    /// Set the unit the value is *displayed* in, when it is not the one it is expressed
    /// in: a value in metres a client should show in millimetres.
    pub fn display_unit<U>(mut self, unit: U) -> Self
    where
        U: Into<Cow<'static, str>>,
    {
        self.config.display_unit = Some(unit.into());
        self
    }

    /// Set how the value is formatted for display, as a printf format such as `%8.3f`,
    /// which is what tells a client how many decimals of it are meaningful.
    pub fn display_format<F>(mut self, format: F) -> Self
    where
        F: Into<Cow<'static, str>>,
    {
        self.config.display_format = Some(format.into());
        self
    }

    /// Set the display level of the attribute, [`DisplayLevel::Expert`] hiding it from the
    /// panels an operator is shown without hiding it from anyone who asks for it.
    pub fn display_level(mut self, level: DisplayLevel) -> Self {
        self.display_level = level;
        self
    }

    // --- Bounds --- //

    /// Set the range of the values the attribute accepts being written, outside of which a
    /// write is refused by the server rather than by the device.
    ///
    /// The range is given as a Rust range, either bound of which may be left open for an
    /// attribute that is only bounded on one side:
    ///
    /// ```ignore
    /// AttrDef::new("position").range(-100.0..=100.0)
    /// AttrDef::new("pressure").range(0.0..)
    /// ```
    ///
    /// # Panics
    ///
    /// If a bound is exclusive, which Tango has no way to express.
    #[track_caller]
    pub fn range<T, R>(mut self, range: R) -> Self
    where
        T: Into<AttrNumber> + Copy,
        R: RangeBounds<T>,
    {
        self.config.range = range_config(&self.name, "value range", range);
        self
    }

    /// Set the range outside of which the attribute is in [`AttrQuality::Alarm`], and the
    /// device with it: an alarm is the reading being wrong, not the write being refused.
    ///
    /// # Panics
    ///
    /// If a bound is exclusive, see [`Self::range`].
    #[track_caller]
    pub fn alarm<T, R>(mut self, range: R) -> Self
    where
        T: Into<AttrNumber> + Copy,
        R: RangeBounds<T>,
    {
        self.config.alarm = range_config(&self.name, "alarm range", range);
        self
    }

    /// Set the range outside of which the attribute is in [`AttrQuality::Warning`]. Like an
    /// alarm, a warning puts the device in [`DevState::Alarm`], in the states given to
    /// [`Dev::set_auto_alarm_states`], the way cppTango does.
    ///
    /// # Panics
    ///
    /// If a bound is exclusive, see [`Self::range`].
    #[track_caller]
    pub fn warning<T, R>(mut self, range: R) -> Self
    where
        T: Into<AttrNumber> + Copy,
        R: RangeBounds<T>,
    {
        self.config.warning = range_config(&self.name, "warning range", range);
        self
    }

    /// Set the alarm on the read value drifting from the written one: how far apart the
    /// two may be, and for how long before it counts, absent for immediately.
    ///
    /// This is what says that a motor asked to go somewhere is not going there, which no
    /// bound on the value alone can express.
    pub fn delta<V, T>(mut self, value: V, time: T) -> Self
    where
        V: Into<AttrNumber>,
        T: Into<Option<Duration>>,
    {
        self.config.delta = Some(AttrDeltaConfig {
            value: value.into(),
            time: time.into(),
        });
        self
    }

    // --- Events --- //

    /// Set the criteria of the change event: how much the value has to move, absolutely
    /// and relatively, for the server to send one. Either may be left out with [`None`],
    /// and an attribute that declares neither only has the change events its device pushes
    /// by itself.
    ///
    /// ```ignore
    /// AttrDef::new("position").change_event(0.001, None)
    /// ```
    pub fn change_event<A, R>(mut self, abs: A, rel: R) -> Self
    where
        A: Into<Option<f64>>,
        R: Into<Option<f64>>,
    {
        self.config.change_event.abs_change = abs.into();
        self.config.change_event.rel_change = rel.into();
        self
    }

    /// Set the period of the periodic event, which is sent whether the value moved or not
    /// and is how a client tells a device that has nothing to say from one that is gone.
    pub fn periodic_event(mut self, period: Duration) -> Self {
        self.config.periodic_event.period = Some(period);
        self
    }

    /// Set the criteria of the archive event: the same two changes as
    /// [`Self::change_event`], and the longest an archiver may go without an event when
    /// the value does not move.
    pub fn archive_event<A, R, P>(mut self, abs: A, rel: R, period: P) -> Self
    where
        A: Into<Option<f64>>,
        R: Into<Option<f64>>,
        P: Into<Option<Duration>>,
    {
        self.config.archive_event.abs_change = abs.into();
        self.config.archive_event.rel_change = rel.into();
        self.config.archive_event.period = period.into();
        self
    }

    /// Declare that the device pushes the change events of this attribute itself, see
    /// [`Dev::push_change_event`], which is what a client may then subscribe to them for:
    /// with no polling, a subscription to the change events of an attribute that does not
    /// declare them is refused, the way cppTango refuses it.
    ///
    /// With `detect`, the criteria of the change event are to be checked against what is
    /// pushed, see [`Self::change_event`], as cppTango does.
    ///
    /// TODO: Check the criteria, every push being sent for now.
    pub fn push_change_event(mut self, detect: bool) -> Self {
        self.pushed.change = Some(detect);
        self
    }

    /// Declare that the device pushes the archive events of this attribute itself, see
    /// [`Self::push_change_event`].
    pub fn push_archive_event(mut self, detect: bool) -> Self {
        self.pushed.archive = Some(detect);
        self
    }

    /// Declare that the device announces this attribute ready to be read, see
    /// [`Dev::push_data_ready_event`]: without it, both the announcement and a subscription
    /// to it are refused, the way cppTango refuses them.
    pub fn push_data_ready_event(mut self) -> Self {
        self.pushed.data_ready = true;
        self
    }

    // --- Server behaviour --- //

    /// Make the attribute memorized: the server stores the value of every write in the
    /// database and restores it when the device is initialized, the mode saying whether it
    /// is only given back as the write value or written again for real.
    ///
    /// Only a writable scalar can be memorized, there being nothing to remember about a
    /// value the device computes, and a state or an encoded value cannot, which a class
    /// is told when the attribute is given to it, see [`ClassDef::attr`].
    pub fn memorized(mut self, mode: AttrMemorized) -> Self {
        self.memorized = Some(mode);
        self
    }

    /// Check what is only known once the whole definition is built: that this attribute
    /// can be memorized if it asks to be, see [`Self::memorized`], and that its kind
    /// supports every property its configuration gives a value to.
    pub(super) fn check(&self) -> std::result::Result<(), String> {

        if let Some(prop) = unsupported_prop(&self.config, self.kind) {
            return Err(format!("the attribute {} cannot have the property {:?}, {}",
                self.name, prop.name(), unsupported(self.kind)));
        }

        if self.memorized.is_none() {
            return Ok(());
        }

        let reason = if self.write.is_none() {
            "it is not writable"
        } else if !matches!(self.format, None | Some(AttrDataFormat::Scalar)) {
            "it is not a scalar"
        } else if matches!(self.kind, Some(AttrDataKind::State | AttrDataKind::Encoded)) {
            "a value of its kind cannot be memorized"
        } else {
            return Ok(());
        };

        Err(format!("the attribute {} cannot be memorized, {reason}", self.name))
        
    }

    /// Ask for the attribute to be polled at that period, each reading being recorded in
    /// its history, which a read from the cache is answered with, and sent as a periodic
    /// event, see [`Self::periodic_event`].
    ///
    /// This period comes second: an attribute the `polled_attr` property of the device
    /// lists is polled at the period the property gives, and one it does not list at this
    /// one. The admin device changes it while the device runs, writing the property along,
    /// but an attribute removed from the polling this way is polled at this period again
    /// from the next initialization of the device, the property having no way to say it
    /// is not.
    pub fn polled(mut self, period: Duration) -> Self {
        self.poll_period = Some(period);
        self
    }

    /// Set the advertised data kind of the attribute. This is only needed for the read
    /// and write functions that use a raw [`Value`], the typed ones derive it from their
    /// value type.
    ///
    /// # Panics
    ///
    /// If the data kind has already been defined, explicitly or by a read or a write
    /// function, as a different kind.
    #[track_caller]
    pub fn kind(mut self, kind: AttrDataKind) -> Self {
        self.kind = Some(merge_kind(&self.name, "data kind", self.kind.take(), kind));
        self
    }

    /// Set the advertised data format of the attribute, which also gives the maximum
    /// dimensions of a spectrum or an image. This is only needed for the read and write
    /// functions that use a raw [`Value`], the typed ones derive a format without any
    /// maximum dimension from their value type.
    ///
    /// A maximum dimension of zero being undefined, it is compatible with any other one,
    /// so the maximum dimensions of a typed read or write function can be completed by
    /// this method, in any order.
    ///
    /// # Panics
    ///
    /// If the data format has already been defined, explicitly or by a read or a write
    /// function, with a different layout or a different maximum dimension.
    #[track_caller]
    pub fn format(mut self, format: AttrDataFormat) -> Self {
        self.format = Some(merge_format(&self.name, self.format.take(), format));
        self
    }

    /// Declare the attribute to hold a single value, which is [`Self::format`] with the
    /// format written for you.
    ///
    /// # Panics
    ///
    /// If the format has already been defined as another layout, see [`Self::format`].
    #[track_caller]
    pub fn scalar(self) -> Self {
        self.format(AttrDataFormat::Scalar)
    }

    /// Declare the attribute to hold a one dimensional array of at most that many values.
    ///
    /// A typed read or write function already gives the layout, so this is usually only
    /// there for the maximum size, which no value type carries; a maximum of zero leaves
    /// it undeclared, an array of any size then being accepted.
    ///
    /// # Panics
    ///
    /// If the format has already been defined as another layout, or as a spectrum of a
    /// different maximum size, see [`Self::format`].
    #[track_caller]
    pub fn spectrum(self, max_size: usize) -> Self {
        self.format(AttrDataFormat::Spectrum(max_size))
    }

    /// Declare the attribute to hold a two dimensional array of at most that width and
    /// that height, see [`Self::spectrum`].
    ///
    /// # Panics
    ///
    /// If the format has already been defined as another layout, or as an image of
    /// different maximum dimensions, see [`Self::format`].
    #[track_caller]
    pub fn image(self, max_width: usize, max_height: usize) -> Self {
        self.format(AttrDataFormat::Image(max_width, max_height))
    }

    /// Define the read function of this attribute, with a shared access to the model.
    ///
    /// This is the raw form of [`Self::read`]: the closure returns a [`Value`], converting
    /// what it borrows from the model itself, which is what makes a closure usable for
    /// such a result. The advertised kind and format then have to be given with
    /// [`Self::kind`] and [`Self::format`].
    pub fn read_with<F>(mut self, func: F) -> Self
    where
        F: Fn(&M, &Dev<M>) -> Result<AttrRead<Value>> + Send + Sync + 'static,
    {
        self.read = Some(ReadFn::SharedSync(Box::new(func)));
        self
    }

    /// Define the read function of this attribute, with a shared access to the model,
    /// which allows parallel reading of such attributes.
    ///
    /// The value type is taken from the `ReadShared` implementation of the function,
    /// and may borrow from the model, with the same constraints as [`CommandDef::exec`]:
    /// it is then written as a function item generic over the model lifetime, typically
    /// an associated method of the model.
    ///
    /// # Panics
    ///
    /// If the advertised kind or format has already been defined incompatibly, see
    /// [`Self::kind`] and [`Self::format`].
    #[track_caller]
    pub fn read<F>(self, func: F) -> Self
    where
        F: for<'m> ReadShared<'m, M> + Send + Sync + 'static,
    {
        self.kind(F::DATA_KIND)
            .format(F::DATA_FORMAT)
            .read_with(move |model, dev| func.read(model, dev))
    }

    /// Define the read function of this attribute, with an exclusive access to the model.
    /// This is the raw form of [`Self::read_exclusive`], see [`Self::read_with`].
    pub fn read_exclusive_with<F>(mut self, func: F) -> Self
    where
        F: Fn(&mut M, &Dev<M>) -> Result<AttrRead<Value>> + Send + Sync + 'static,
    {
        self.read = Some(ReadFn::ExclusiveSync(Box::new(func)));
        self
    }

    /// Define the read function of this attribute, with an exclusive access to the model,
    /// therefore no other command or attribute can access it in parallel.
    ///
    /// # Panics
    ///
    /// If the advertised kind or format has already been defined incompatibly, see
    /// [`Self::kind`] and [`Self::format`].
    #[track_caller]
    pub fn read_exclusive<F>(self, func: F) -> Self
    where
        F: for<'m> ReadExclusive<'m, M> + Send + Sync + 'static,
    {
        self.kind(F::DATA_KIND)
            .format(F::DATA_FORMAT)
            .read_exclusive_with(move |model, dev| func.read(model, dev))
    }

    /// Define the read function of this attribute, asynchronously and with a shared access
    /// to the model. This is the raw form of [`Self::read_async`], for a closure that
    /// boxes its future itself, see [`Self::read_with`].
    pub fn read_async_with<F>(mut self, func: F) -> Self
    where
        F: for<'a> Fn(&'a M, &'a Dev<M>) -> BoxFuture<'a, Result<AttrRead<Value>>> + Send + Sync + 'static,
    {
        self.read = Some(ReadFn::SharedAsync(Box::new(func)));
        self
    }

    /// Define the read function of this attribute, asynchronously and with a shared access
    /// to the model, typically an `async fn` method of the model, see
    /// [`CommandDef::exec_async`] for what it is for and what it must not do.
    ///
    /// # Panics
    ///
    /// If the advertised kind or format has already been defined incompatibly, see
    /// [`Self::kind`] and [`Self::format`].
    #[track_caller]
    pub fn read_async<F>(self, func: F) -> Self
    where
        F: for<'a> ReadAsync<'a, &'a M, M> + Send + Sync + 'static,
    {
        self.kind(F::DATA_KIND)
            .format(F::DATA_FORMAT)
            .read_async_with(move |model, dev| func.read(model, dev))
    }

    /// Define the read function of this attribute, asynchronously and with an exclusive
    /// access to the model. This is the raw form of [`Self::read_exclusive_async`], see
    /// [`Self::read_async_with`].
    pub fn read_exclusive_async_with<F>(mut self, func: F) -> Self
    where
        F: for<'a> Fn(&'a mut M, &'a Dev<M>) -> BoxFuture<'a, Result<AttrRead<Value>>> + Send + Sync + 'static,
    {
        self.read = Some(ReadFn::ExclusiveAsync(Box::new(func)));
        self
    }

    /// Define the read function of this attribute, asynchronously and with an exclusive
    /// access to the model, which no other command or attribute can then access until the
    /// future completes. See [`Self::read_async`].
    ///
    /// # Panics
    ///
    /// If the advertised kind or format has already been defined incompatibly, see
    /// [`Self::kind`] and [`Self::format`].
    #[track_caller]
    pub fn read_exclusive_async<F>(self, func: F) -> Self
    where
        F: for<'a> ReadAsync<'a, &'a mut M, M> + Send + Sync + 'static,
    {
        self.kind(F::DATA_KIND)
            .format(F::DATA_FORMAT)
            .read_exclusive_async_with(move |model, dev| func.read(model, dev))
    }

    /// Define the write function of this attribute, with a shared access to the model.
    /// This is the raw form of [`Self::write`], the written [`Value`] being given as-is
    /// and the advertised kind and format having to be given with [`Self::kind`] and
    /// [`Self::format`].
    pub fn write_with<F>(mut self, func: F) -> Self
    where
        F: Fn(&M, &Dev<M>, Value) -> Result<()> + Send + Sync + 'static,
    {
        self.write = Some(WriteFn::SharedSync(Box::new(func)));
        self
    }

    /// Define the write function of this attribute, with a shared access to the model.
    ///
    /// The value type is taken from the `WriteShared` implementation of the function,
    /// any [`FromValue`] type, a [`Buf`](crate::buf::Buf) sharing the written value
    /// rather than copying it.
    ///
    /// # Panics
    ///
    /// If the advertised kind or format has already been defined incompatibly, which
    /// notably happens when the read function of the attribute does not use the same
    /// value type, see [`Self::kind`] and [`Self::format`].
    #[track_caller]
    pub fn write<F, I>(self, func: F) -> Self
    where
        F: WriteShared<M, I> + Send + Sync + 'static,
    {
        self.kind(F::DATA_KIND)
            .format(F::DATA_FORMAT)
            .write_with(move |model, dev, value| func.write(model, dev, value))
    }

    /// Define the write function of this attribute, with an exclusive access to the
    /// model. This is the raw form of [`Self::write_exclusive`], see [`Self::write_with`].
    pub fn write_exclusive_with<F>(mut self, func: F) -> Self
    where
        F: Fn(&mut M, &Dev<M>, Value) -> Result<()> + Send + Sync + 'static,
    {
        self.write = Some(WriteFn::ExclusiveSync(Box::new(func)));
        self
    }

    /// Define the write function of this attribute, with an exclusive access to the
    /// model, which is what a write usually needs in order to store the written value.
    ///
    /// # Panics
    ///
    /// If the advertised kind or format has already been defined incompatibly, which
    /// notably happens when the read function of the attribute does not use the same
    /// value type, see [`Self::kind`] and [`Self::format`].
    #[track_caller]
    pub fn write_exclusive<F, I>(self, func: F) -> Self
    where
        F: WriteExclusive<M, I> + Send + Sync + 'static,
    {
        self.kind(F::DATA_KIND)
            .format(F::DATA_FORMAT)
            .write_exclusive_with(move |model, dev, value| func.write(model, dev, value))
    }

    /// Define the write function of this attribute, asynchronously and with a shared
    /// access to the model. This is the raw form of [`Self::write_async`], see
    /// [`Self::read_async_with`].
    pub fn write_async_with<F>(mut self, func: F) -> Self
    where
        F: for<'a> Fn(&'a M, &'a Dev<M>, Value) -> BoxFuture<'a, Result<()>> + Send + Sync + 'static,
    {
        self.write = Some(WriteFn::SharedAsync(Box::new(func)));
        self
    }

    /// Define the write function of this attribute, asynchronously and with a shared
    /// access to the model, see [`Self::read_async`].
    ///
    /// # Panics
    ///
    /// If the advertised kind or format has already been defined incompatibly, see
    /// [`Self::write`].
    #[track_caller]
    pub fn write_async<F, I>(self, func: F) -> Self
    where
        F: for<'a> WriteAsync<'a, &'a M, M, I> + Send + Sync + 'static,
    {
        self.kind(F::DATA_KIND)
            .format(F::DATA_FORMAT)
            .write_async_with(move |model, dev, value| func.write(model, dev, value))
    }

    /// Define the write function of this attribute, asynchronously and with an exclusive
    /// access to the model. This is the raw form of [`Self::write_exclusive_async`], see
    /// [`Self::read_async_with`].
    pub fn write_exclusive_async_with<F>(mut self, func: F) -> Self
    where
        F: for<'a> Fn(&'a mut M, &'a Dev<M>, Value) -> BoxFuture<'a, Result<()>> + Send + Sync + 'static,
    {
        self.write = Some(WriteFn::ExclusiveAsync(Box::new(func)));
        self
    }

    /// Define the write function of this attribute, asynchronously and with an exclusive
    /// access to the model, which no other command or attribute can then access until the
    /// future completes. See [`Self::read_async`].
    ///
    /// # Panics
    ///
    /// If the advertised kind or format has already been defined incompatibly, see
    /// [`Self::write`].
    #[track_caller]
    pub fn write_exclusive_async<F, I>(self, func: F) -> Self
    where
        F: for<'a> WriteAsync<'a, &'a mut M, M, I> + Send + Sync + 'static,
    {
        self.kind(F::DATA_KIND)
            .format(F::DATA_FORMAT)
            .write_exclusive_async_with(move |model, dev, value| func.write(model, dev, value))
    }

}

impl<M: Model> Debug for AttrDef<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AttrDef")
            .field("name", &self.name)
            .field("read", &self.read)
            .field("write", &self.write)
            .field("kind", &self.kind)
            .field("format", &self.format)
            .field("config", &self.config)
            .field("poll_period", &self.poll_period)
            .field("pushed", &self.pushed)
            .finish()
    }
}


#[cfg(test)]
mod tests {

    use super::*;
    use crate::value::Spectrum;

    #[derive(Default)]
    struct Model { count: i32, label: String, values: Vec<f64>, labels: Vec<String> }

    impl Model {

        /// A result borrowed from the model, the lifetime elision binding it to the model
        /// borrow, see [`CommandDef::exec`].
        fn label(&self, _dev: &Dev<Self>, _arg: ()) -> Result<&str> {
            Ok(self.label.as_str())
        }

        fn values(&self, _dev: &Dev<Self>, _arg: ()) -> Result<&[f64]> {
            Ok(&self.values)
        }

        fn set_label(&mut self, _dev: &Dev<Self>, arg: String) -> Result<&str> {
            self.label = arg;
            Ok(self.label.as_str())
        }

        fn add(&self, _dev: &Dev<Self>, arg: i32) -> Result<i32> {
            Ok(self.count + arg)
        }

        fn incr(&mut self, _dev: &Dev<Self>, arg: i32) -> Result<i32> {
            self.count += arg;
            Ok(self.count)
        }

        // --- Attribute handlers, which are only given the device --- //

        fn count(&self, _dev: &Dev<Self>) -> Result<i32> {
            Ok(self.count)
        }

        fn set_count(&mut self, _dev: &Dev<Self>, arg: i32) -> Result<()> {
            self.count = arg;
            Ok(())
        }

        /// A read giving the quality and the timestamp of the value along with it.
        fn count_full(&self, _dev: &Dev<Self>) -> Result<AttrRead<i32>> {
            Ok(AttrRead {
                value: Some(self.count),
                w_value: None,
                quality: AttrQuality::Valid,
                time: SystemTime::now(),
            })
        }

        fn read_label(&self, _dev: &Dev<Self>) -> Result<&str> {
            Ok(self.label.as_str())
        }

        fn read_values(&self, _dev: &Dev<Self>) -> Result<&[f64]> {
            Ok(&self.values)
        }

        /// The handler shared by the commands of a dynamic set, the index of the command
        /// being captured by the closure forwarding to it.
        fn label_n(&self, _dev: &Dev<Self>, index: usize) -> Result<&str> {
            Ok(self.labels[index].as_str())
        }

        /// A read updating the model, therefore needing an exclusive access to it.
        fn tick(&mut self, _dev: &Dev<Self>) -> Result<i32> {
            self.count += 1;
            Ok(self.count)
        }

    }

    /// A result that does not borrow from the model at all.
    fn version(_model: &Model, _dev: &Dev<Model>, _arg: ()) -> Result<&'static str> {
        Ok("1.0.0")
    }

    /// Check that all the intended signatures are accepted, and that both kinds are
    /// always derived from the argument and result types.
    #[test]
    fn exec_signatures() {

        // Scalar in, scalar out, as an associated method of the model.
        let def = CommandDef::<Model>::new("Add").exec(Model::add);
        assert_eq!(def.in_kind, Some(CommandDataKind::Long));
        assert_eq!(def.out_kind, Some(CommandDataKind::Long));

        // Exclusive access to the model.
        let _ = CommandDef::<Model>::new("Incr").exec_exclusive(Model::incr);

        // A closure is still accepted as long as its result does not borrow from the
        // model, but it has to annotate the two reference parameters.
        let _ = CommandDef::<Model>::new("Status")
            .exec(|model: &Model, _dev: &Dev<Model>, (): ()| Ok(model.label.clone()));

        // A closure whose result borrows from the model is only accepted by the raw
        // form, see `closures_borrowing`.
        let def = CommandDef::<Model>::new("Label")
            .out_kind(CommandDataKind::String)
            .exec_with(|model: &Model, dev, value| {
                Ok(model.label(dev, <()>::from_value(value)?)?.into())
            });
        assert_eq!(def.out_kind, Some(CommandDataKind::String));

        // Spectrum in, scalar out.
        let def = CommandDef::<Model>::new("Sum")
            .exec(|_model: &Model, _dev: &Dev<Model>, arg: Vec<f64>| Ok(arg.iter().sum::<f64>()));
        assert_eq!(def.in_kind, Some(CommandDataKind::DoubleArray));
        assert_eq!(def.out_kind, Some(CommandDataKind::Double));

        // Spectrum in and out, owned or borrowed from the argument.
        let _ = CommandDef::<Model>::new("Scale")
            .exec(|_model: &Model, _dev: &Dev<Model>, arg: Vec<f64>| Ok(arg.iter().map(|v| v * 2.0).collect::<Vec<f64>>()));
        let _ = CommandDef::<Model>::new("Reverse")
            .exec(|_model: &Model, _dev: &Dev<Model>, arg: Vec<String>| Ok(arg.into_iter().rev().collect::<Vec<String>>()));
        let _ = CommandDef::<Model>::new("Zeros")
            .exec(|_model: &Model, _dev: &Dev<Model>, (): ()| Ok(Spectrum::<f64>::from(vec![0.0; 4])));

        // A `&'static str` result.
        let def = CommandDef::<Model>::new("Version").exec(version);
        assert_eq!(def.out_kind, Some(CommandDataKind::String));

        // A result borrowed from the model, both kinds still being derived.
        let def = CommandDef::<Model>::new("Label")
            .out_doc("The label of the device")
            .exec(Model::label);
        assert_eq!(def.in_kind, Some(CommandDataKind::Void));
        assert_eq!(def.out_kind, Some(CommandDataKind::String));

        let def = CommandDef::<Model>::new("Values").exec(Model::values);
        assert_eq!(def.out_kind, Some(CommandDataKind::DoubleArray));

        // Exclusive access to the model, with a result borrowed from it.
        let def = CommandDef::<Model>::new("SetLabel").exec_exclusive(Model::set_label);
        assert_eq!(def.in_kind, Some(CommandDataKind::String));
        assert_eq!(def.out_kind, Some(CommandDataKind::String));

        // Raw form, with a result borrowed from the model, the kinds being explicit
        // because they cannot be derived from a raw `Value`.
        let def = CommandDef::<Model>::new("Status")
            .out_kind(CommandDataKind::String)
            .exec_with(|model: &Model, _dev, _value| Ok(model.label.as_str().into()));
        assert_eq!(def.in_kind, None);
        assert_eq!(def.out_kind, Some(CommandDataKind::String));

        // Raw form, borrowing the argument value itself.
        let _ = CommandDef::<Model>::new("Echo")
            .in_kind(CommandDataKind::String)
            .out_kind(CommandDataKind::String)
            .exec_with(|model: &Model, _dev, value| {
                let arg = <&str>::try_from(&value)?;
                Ok(format!("{}{arg}", model.label).into())
            });

        // Raw form with an exclusive access to the model, returning a borrow of it.
        let _ = CommandDef::<Model>::new("SetLabel")
            .in_kind(CommandDataKind::String)
            .out_kind(CommandDataKind::String)
            .exec_exclusive_with(|model: &mut Model, _dev, value| {
                model.label = String::try_from(value)?;
                Ok(model.label.as_str().into())
            });

    }

    /// Check that all the intended read and write signatures are accepted, and that the
    /// kind and the format are always derived from the value type.
    #[test]
    fn attr_signatures() {

        // Scalar read and write, as associated methods of the model.
        let def = AttrDef::<Model>::new("Count")
            .read(Model::count)
            .write_exclusive(Model::set_count);
        assert_eq!(def.kind, Some(AttrDataKind::Long));
        assert_eq!(def.format, Some(AttrDataFormat::Scalar));

        // A value borrowed from the model, scalar or spectrum.
        let def = AttrDef::<Model>::new("Label").read(Model::read_label);
        assert_eq!(def.kind, Some(AttrDataKind::String));
        assert_eq!(def.format, Some(AttrDataFormat::Scalar));

        let def = AttrDef::<Model>::new("Values").read(Model::read_values);
        assert_eq!(def.kind, Some(AttrDataKind::Double));
        assert_eq!(def.format, Some(AttrDataFormat::Spectrum(0)));

        // A full read result, giving the quality and the timestamp.
        let def = AttrDef::<Model>::new("CountFull").read(Model::count_full);
        assert_eq!(def.kind, Some(AttrDataKind::Long));

        // Exclusive access to the model, for a read updating it.
        let _ = AttrDef::<Model>::new("Ticks").read_exclusive(Model::tick);

        // A closure is accepted as long as its result does not borrow from the model.
        let _ = AttrDef::<Model>::new("Double")
            .read(|model: &Model, _dev: &Dev<Model>| Ok(model.count * 2));

        // Raw form, the kind and the format having to be explicit.
        let _ = AttrDef::<Model>::new("Raw")
            .kind(AttrDataKind::Double)
            .format(AttrDataFormat::Spectrum(4096))
            .read_with(|model: &Model, _dev| Ok(AttrRead {
                value: Some(model.values.as_slice().into()),
                w_value: None,
                quality: AttrQuality::Valid,
                time: SystemTime::now(),
            }));

    }

    /// Check that every configuration builder writes the field of [`AttrConfig`] it is
    /// named after, which is what a device of the class then starts from.
    #[test]
    fn attr_config() {

        let def = AttrDef::<Model>::new("Position")
            .read(Model::count)
            .doc("The position of the axis")
            .label("Position")
            .unit("mm")
            .standard_unit(1e-3)
            .display_unit("mm")
            .display_format("%8.3f")
            .display_level(DisplayLevel::Expert)
            .delta(0.5, Duration::from_millis(200))
            .change_event(0.001, None)
            .periodic_event(Duration::from_secs(1))
            .archive_event(0.1, None, Duration::from_secs(10))
            .memorized(AttrMemorized::RestoreAndWrite)
            .polled(Duration::from_millis(100));

        assert_eq!(def.config.doc.as_deref(), Some("The position of the axis"));
        assert_eq!(def.config.label.as_deref(), Some("Position"));
        assert_eq!(def.config.unit.as_deref(), Some("mm"));
        assert_eq!(def.config.standard_unit, Some(1e-3));
        assert_eq!(def.config.display_unit.as_deref(), Some("mm"));
        assert_eq!(def.config.display_format.as_deref(), Some("%8.3f"));
        assert_eq!(def.display_level, DisplayLevel::Expert);

        // The delta is a limit like the bounds are, so it is the number of the attribute
        // and not a double the value would have to be converted to.
        assert_eq!(def.config.delta, Some(AttrDeltaConfig {
            value: AttrNumber::Double(0.5),
            time: Some(Duration::from_millis(200)),
        }));

        // The criteria of the events are not limits: an absolute change is a magnitude and
        // a relative one a percentage, so both stay doubles, and either may be left out.
        assert_eq!(def.config.change_event.abs_change, Some(0.001));
        assert_eq!(def.config.change_event.rel_change, None);
        assert_eq!(def.config.periodic_event.period, Some(Duration::from_secs(1)));
        assert_eq!(def.config.archive_event.abs_change, Some(0.1));
        assert_eq!(def.config.archive_event.period, Some(Duration::from_secs(10)));

        assert_eq!(def.memorized, Some(AttrMemorized::RestoreAndWrite));
        assert_eq!(def.poll_period, Some(Duration::from_millis(100)));

        // What is not defined stays absent rather than being given a value nobody asked
        // for, an attribute with no bound being the usual case.
        let def = AttrDef::<Model>::new("Count").read(Model::count);
        assert_eq!(def.config, AttrConfig::default());
        assert_eq!(def.poll_period, None);

    }

    /// Check the three ways a range is bounded, that a bound left open stays open, and
    /// that a range is the kind of number it was written with.
    #[test]
    fn attr_ranges() {

        let def = AttrDef::<Model>::new("Position")
            .read(Model::count)
            .range(-100.0..=100.0)
            .warning(-90.5..)
            .alarm(..=95.0);

        assert_eq!(def.config.range, AttrRangeConfig {
            min: Some(AttrNumber::Double(-100.0)),
            max: Some(AttrNumber::Double(100.0)),
        });

        // Only bounded below: an attribute that cannot go under that and has no ceiling.
        assert_eq!(def.config.warning, AttrRangeConfig {
            min: Some(AttrNumber::Double(-90.5)),
            max: None,
        });

        // And only bounded above.
        assert_eq!(def.config.alarm, AttrRangeConfig {
            min: None,
            max: Some(AttrNumber::Double(95.0)),
        });

        // An integer attribute is bounded with integers, which are held as such rather
        // than being rounded into a double: this is the whole point of the three kinds.
        let def = AttrDef::<Model>::new("Count")
            .read(Model::count)
            .range(-8..=8i32)
            .alarm(..=u64::MAX);

        assert_eq!(def.config.range, AttrRangeConfig {
            min: Some(AttrNumber::Long(-8)),
            max: Some(AttrNumber::Long(8)),
        });
        assert_eq!(def.config.alarm.max, Some(AttrNumber::ULong(u64::MAX)));

        // Two limits a double cannot tell apart, which is the whole reason they are not
        // doubles: kept as they are they differ, converted they are the same number.
        assert_ne!(AttrNumber::ULong(u64::MAX), AttrNumber::ULong(u64::MAX - 1));
        assert_eq!(AttrNumber::ULong(u64::MAX).as_f64(), AttrNumber::ULong(u64::MAX - 1).as_f64());

        // Two limits of different kinds are equal when they stand for the same number.
        assert_eq!(AttrNumber::Long(2), AttrNumber::Double(2.0));
        assert!(AttrNumber::Long(-1) < AttrNumber::ULong(0));
        assert!(AttrNumber::ULong(u64::MAX) > AttrNumber::ULong(u64::MAX - 1));
        assert_ne!(AttrNumber::Double(f64::NAN), AttrNumber::Double(f64::NAN));

    }

    #[test]
    #[should_panic(expected = "the value range cannot have an exclusive bound")]
    fn exclusive_range_bound() {
        let _ = AttrDef::<Model>::new("Position").range(-100.0..100.0);
    }

    /// Check that the three layout methods are the formats they stand for, and that they
    /// merge with what a handler derived the way [`AttrDef::format`] does.
    #[test]
    fn attr_layouts() {

        let def = AttrDef::<Model>::new("Count").read(Model::count).scalar();
        assert_eq!(def.format, Some(AttrDataFormat::Scalar));

        // The layout comes from the handler and only the maximum size from here, in
        // either order.
        let def = AttrDef::<Model>::new("Values").read(Model::read_values).spectrum(4096);
        assert_eq!(def.format, Some(AttrDataFormat::Spectrum(4096)));

        let def = AttrDef::<Model>::new("Values").spectrum(4096).read(Model::read_values);
        assert_eq!(def.kind, Some(AttrDataKind::Double));
        assert_eq!(def.format, Some(AttrDataFormat::Spectrum(4096)));

        // Nothing is derived from a raw handler, so both are stated outright.
        let def = AttrDef::<Model>::new("Frame")
            .kind(AttrDataKind::Double)
            .image(640, 480);
        assert_eq!(def.format, Some(AttrDataFormat::Image(640, 480)));

        // A maximum of zero is the undefined one, which any size then matches.
        let def = AttrDef::<Model>::new("Values").read(Model::read_values).spectrum(0);
        assert_eq!(def.format, Some(AttrDataFormat::Spectrum(0)));

    }

    #[test]
    #[should_panic(expected = "the data format is already defined as Scalar")]
    fn incompatible_layout() {
        let _ = AttrDef::<Model>::new("Count").read(Model::count).spectrum(8);
    }

    /// Check what a command has of a configuration, which is a good deal less than an
    /// attribute: Tango tells a client the display level and nothing else about it.
    #[test]
    fn command_config() {

        let def = CommandDef::<Model>::new("Add")
            .exec(Model::add)
            .display_level(DisplayLevel::Expert)
            .polled(Duration::from_secs(1));

        assert_eq!(def.display_level, DisplayLevel::Expert);
        assert_eq!(def.poll_period, Some(Duration::from_secs(1)));

        // The level everything is at unless it says otherwise.
        let def = CommandDef::<Model>::new("Add").exec(Model::add);
        assert_eq!(def.display_level, DisplayLevel::Operator);
        assert_eq!(def.poll_period, None);

    }

    /// The description of a class is the one every device of it gives of itself.
    #[test]
    fn class_doc() {
        let def = ClassDef::<Model>::new_default("Motor").doc("A single axis");
        assert_eq!(def.doc, "A single axis");
        let def = ClassDef::<Model>::new_default("Motor");
        assert_eq!(def.doc, "A Tango device");
    }

    /// Check that an explicit kind or format completes the one derived from a handler,
    /// in any order, as long as they do not contradict each other.
    #[test]
    fn compatible_kinds() {

        // The same kind given twice, before or after the execution function.
        let def = CommandDef::<Model>::new("Add")
            .in_kind(CommandDataKind::Long)
            .exec(Model::add)
            .out_kind(CommandDataKind::Long);
        assert_eq!(def.in_kind, Some(CommandDataKind::Long));
        assert_eq!(def.out_kind, Some(CommandDataKind::Long));

        // An undefined maximum size being completed by an explicit format, the derived
        // kind being kept in both orders.
        let def = AttrDef::<Model>::new("Values")
            .read(Model::read_values)
            .format(AttrDataFormat::Spectrum(4096));
        assert_eq!(def.kind, Some(AttrDataKind::Double));
        assert_eq!(def.format, Some(AttrDataFormat::Spectrum(4096)));

        let def = AttrDef::<Model>::new("Values")
            .format(AttrDataFormat::Spectrum(4096))
            .read(Model::read_values);
        assert_eq!(def.format, Some(AttrDataFormat::Spectrum(4096)));

    }

    #[test]
    #[should_panic(expected = "the argument kind is already defined as String")]
    fn incompatible_in_kind() {
        let _ = CommandDef::<Model>::new("Add")
            .in_kind(CommandDataKind::String)
            .exec(Model::add);
    }

    #[test]
    #[should_panic(expected = "the result kind is already defined as Long")]
    fn incompatible_out_kind() {
        let _ = CommandDef::<Model>::new("Add")
            .exec(Model::add)
            .out_kind(CommandDataKind::Long64);
    }

    #[test]
    #[should_panic(expected = "the data kind is already defined as String")]
    fn incompatible_attr_kind() {
        let _ = AttrDef::<Model>::new("Label")
            .read(Model::read_label)
            .write_exclusive(Model::set_count);
    }

    #[test]
    #[should_panic(expected = "the data format is already defined as Scalar")]
    fn incompatible_attr_format() {
        let _ = AttrDef::<Model>::new("Count")
            .read(Model::count)
            .format(AttrDataFormat::Spectrum(8));
    }

    #[test]
    #[should_panic(expected = "the maximum size is already defined as 8")]
    fn incompatible_attr_max() {
        let _ = AttrDef::<Model>::new("Values")
            .format(AttrDataFormat::Spectrum(8))
            .format(AttrDataFormat::Spectrum(4096));
    }


    #[test]
    #[should_panic(expected = "Test: the attribute Label cannot have the property \"max_alarm\", not supported by an attribute of type String")]
    fn unsupported_attr_prop() {
        let _ = ClassDef::<Model>::new_default("Test")
            .attr(AttrDef::new("Label")
                .read(Model::read_label)
                .alarm(..=5));
    }

    #[test]
    #[should_panic(expected = "Test: the command name \"Do it\" is invalid")]
    fn invalid_command_name() {
        let _ = ClassDef::<Model>::new_default("Test").command(CommandDef::new("Do it"));
    }

    #[test]
    #[should_panic(expected = "Test: the attribute name \"_Speed\" is invalid")]
    fn invalid_attr_name() {
        let _ = ClassDef::<Model>::new_default("Test").attr(AttrDef::new("_Speed").kind(AttrDataKind::Double).scalar());
    }

    #[test]
    #[should_panic(expected = "the attribute State cannot have the property \"min_value\", not supported by an attribute of type State")]
    fn unsupported_state_prop() {
        let _ = ClassDef::<Model>::new_default("Test")
            .state_config(AttrConfig { range: AttrRangeConfig { min: Some(AttrNumber::Long(0)), max: None }, ..AttrConfig::default() });
    }

    #[test]
    #[should_panic(expected = "the attribute Count cannot be memorized, it is not writable")]
    fn memorized_read_only() {
        let _ = ClassDef::<Model>::new_default("Test")
            .attr(AttrDef::new("Count")
                .read(Model::count)
                .memorized(AttrMemorized::RestoreSetPoint));
    }

    #[test]
    #[should_panic(expected = "the attribute Values cannot be memorized, it is not a scalar")]
    fn memorized_spectrum() {
        let _ = ClassDef::<Model>::new_default("Test")
            .attr(AttrDef::new("Values")
                .memorized(AttrMemorized::RestoreAndWrite)
                .kind(AttrDataKind::Double)
                .format(AttrDataFormat::Spectrum(8))
                .write_with(|_model: &Model, _dev, _value| Ok(())));
    }

    /// Check the way a closure borrowing from the model is defined: only the raw form
    /// accepts it, its result being converted into a [`Value`] before the borrow ends,
    /// and the advertised kinds then being explicit.
    #[test]
    fn closures_borrowing() {

        // The dynamic command case: several commands sharing a single handler, each
        // closure capturing the index of its own command.
        for index in 0..3 {
            let def = CommandDef::<Model>::new(format!("Label{index}"))
                .out_kind(CommandDataKind::String)
                .exec_with(move |model: &Model, dev, _value| {
                    Ok(model.label_n(dev, index)?.into())
                });
            assert_eq!(def.out_kind, Some(CommandDataKind::String));
        }

        // With an exclusive access to the model, the result borrowing what was written.
        let _ = CommandDef::<Model>::new("Push")
            .in_kind(CommandDataKind::String)
            .out_kind(CommandDataKind::String)
            .exec_exclusive_with(|model: &mut Model, _dev, value| {
                model.labels.push(String::try_from(value)?);
                Ok(model.labels.last().unwrap().as_str().into())
            });

        // The same for the read function of a dynamic attribute.
        for index in 0..3 {
            let def = AttrDef::<Model>::new(format!("Label{index}"))
                .kind(AttrDataKind::String)
                .format(AttrDataFormat::Scalar)
                .read_with(move |model: &Model, dev| {
                    Ok(AttrRead {
                        value: Some(model.label_n(dev, index)?.into()),
                        w_value: None,
                        quality: AttrQuality::Valid,
                        time: SystemTime::now(),
                    })
                });
            assert_eq!(def.kind, Some(AttrDataKind::String));
        }

    }

    /// A model owning what it borrowed from outside of the device, which is what the
    /// `'static` bound asks of it: a class lives as long as the server serving it, so a
    /// model borrowing from a shorter lifetime has nothing to be borrowed from by then.
    struct Owning { values: Vec<f64> }

    impl Owning {
        fn len(&self, _dev: &Dev<Self>, _arg: ()) -> Result<i32> { Ok(self.values.len() as i32) }
        fn first(&self, _dev: &Dev<Self>) -> Result<f64> { Ok(self.values[0]) }
    }

    /// The definitions of such a model are `'static` themselves, so they can be given to a
    /// class without being tied to the scope they were written in.
    fn owning_defs(prefix: &str) -> (CommandDef<Owning>, AttrDef<Owning>) {
        let command = CommandDef::<Owning>::new("Len")
            .exec(Owning::len)
            .out_doc(prefix.to_owned());
        let attr = AttrDef::<Owning>::new("First")
            .read(Owning::first)
            // A handler capturing what it needs by value, the definition outliving the
            // scope it was built in.
            .write_with({
                let prefix = prefix.to_owned();
                move |_model: &Owning, _dev, _value| {
                    let _ = &prefix;
                    Ok(())
                }
            });
        (command, attr)
    }

    #[test]
    fn model_owned() {
        let values = [1.0, 2.0, 3.0];
        let prefix = format!("{} values", values.len());
        let (command, attr) = owning_defs(&prefix);
        drop(prefix);
        assert_eq!(command.out_kind, Some(CommandDataKind::Long));
        assert_eq!(attr.kind, Some(AttrDataKind::Double));
    }

    /// The asynchronous counterparts of the handlers of [`Model`], written as `async fn`
    /// methods, which is what the typed async definitions are meant to take.
    struct AsyncModel { count: i32, label: String }

    impl AsyncModel {

        async fn add(&self, _dev: &Dev<Self>, arg: i32) -> Result<i32> {
            Ok(self.count + arg)
        }

        async fn label(&self, _dev: &Dev<Self>, _arg: ()) -> Result<&str> {
            Ok(self.label.as_str())
        }

        async fn incr(&mut self, _dev: &Dev<Self>, arg: i32) -> Result<i32> {
            self.count += arg;
            Ok(self.count)
        }

        async fn count(&self, _dev: &Dev<Self>) -> Result<i32> {
            Ok(self.count)
        }

        async fn set_count(&mut self, _dev: &Dev<Self>, arg: i32) -> Result<()> {
            self.count = arg;
            Ok(())
        }

        async fn read_label(&self, _dev: &Dev<Self>) -> Result<&str> {
            Ok(self.label.as_str())
        }

        async fn check_label(&self, _dev: &Dev<Self>, arg: String) -> Result<()> {
            let _ = arg.len();
            Ok(())
        }

        async fn tick(&mut self, _dev: &Dev<Self>) -> Result<i32> {
            self.count += 1;
            Ok(self.count)
        }

        async fn state(&self, _dev: &Dev<Self>) -> Result<DevState> {
            Ok(DevState::On)
        }

        async fn status(&mut self, _dev: &Dev<Self>) -> Result<&str> {
            Ok(&self.label)
        }

        fn status_label(&self, _dev: &Dev<Self>) -> Result<&str> {
            Ok(&self.label)
        }

    }

    /// Check that the async execution functions are accepted as `async fn` methods and as
    /// boxing closures, that both kinds are derived as for the sync ones, and that each
    /// definition is stored with the access it asked for.
    #[test]
    fn exec_async_signatures() {

        let def = CommandDef::<AsyncModel>::new("Add").exec_async(AsyncModel::add);
        assert_eq!(def.in_kind, Some(CommandDataKind::Long));
        assert_eq!(def.out_kind, Some(CommandDataKind::Long));
        assert!(matches!(def.exec, Some(ExecFn::SharedAsync(_))));

        // A result borrowed from the model across the future.
        let def = CommandDef::<AsyncModel>::new("Label").exec_async(AsyncModel::label);
        assert_eq!(def.in_kind, Some(CommandDataKind::Void));
        assert_eq!(def.out_kind, Some(CommandDataKind::String));

        let def = CommandDef::<AsyncModel>::new("Incr").exec_exclusive_async(AsyncModel::incr);
        assert_eq!(def.in_kind, Some(CommandDataKind::Long));
        assert!(matches!(def.exec, Some(ExecFn::ExclusiveAsync(_))));

        // Raw forms, whose closures box their future themselves and give no kind.
        let def = CommandDef::<AsyncModel>::new("Echo")
            .in_kind(CommandDataKind::String)
            .out_kind(CommandDataKind::String)
            .exec_async_with(|model: &AsyncModel, _dev, value| Box::pin(async move {
                let arg = <&str>::try_from(&value)?;
                Ok(format!("{}{arg}", model.label).into())
            }));
        assert_eq!(def.in_kind, Some(CommandDataKind::String));
        assert!(matches!(def.exec, Some(ExecFn::SharedAsync(_))));

        let def = CommandDef::<AsyncModel>::new("SetLabel")
            .exec_exclusive_async_with(|model: &mut AsyncModel, _dev, value| Box::pin(async move {
                model.label = String::try_from(value)?;
                Ok(model.label.as_str().into())
            }));
        assert_eq!(def.in_kind, None);
        assert_eq!(def.out_kind, None);
        assert!(matches!(def.exec, Some(ExecFn::ExclusiveAsync(_))));

    }

    /// Check the same for the async read and write functions of an attribute.
    #[test]
    fn attr_async_signatures() {

        let def = AttrDef::<AsyncModel>::new("Count")
            .read_async(AsyncModel::count)
            .write_exclusive_async(AsyncModel::set_count);
        assert_eq!(def.kind, Some(AttrDataKind::Long));
        assert_eq!(def.format, Some(AttrDataFormat::Scalar));
        assert!(matches!(def.read, Some(ReadFn::SharedAsync(_))));
        assert!(matches!(def.write, Some(WriteFn::ExclusiveAsync(_))));

        let def = AttrDef::<AsyncModel>::new("Label")
            .read_async(AsyncModel::read_label)
            .write_async(AsyncModel::check_label);
        assert_eq!(def.kind, Some(AttrDataKind::String));
        assert!(matches!(def.write, Some(WriteFn::SharedAsync(_))));

        let def = AttrDef::<AsyncModel>::new("Ticks").read_exclusive_async(AsyncModel::tick);
        assert!(matches!(def.read, Some(ReadFn::ExclusiveAsync(_))));

        let def = AttrDef::<AsyncModel>::new("Raw")
            .kind(AttrDataKind::Long)
            .scalar()
            .read_async_with(|model: &AsyncModel, _dev| Box::pin(async move {
                Ok(AttrRead {
                    value: Some(model.count.into()),
                    w_value: None,
                    quality: AttrQuality::Valid,
                    time: SystemTime::now(),
                })
            }))
            .write_exclusive_async_with(|model: &mut AsyncModel, _dev, value| Box::pin(async move {
                model.count = i32::try_from(value)?;
                Ok(())
            }));
        assert!(matches!(def.read, Some(ReadFn::SharedAsync(_))));
        assert!(matches!(def.write, Some(WriteFn::ExclusiveAsync(_))));

    }

    #[test]
    #[should_panic(expected = "the data kind is already defined as String")]
    fn incompatible_attr_async_kind() {
        let _ = AttrDef::<AsyncModel>::new("Label")
            .read_async(AsyncModel::read_label)
            .write_exclusive_async(AsyncModel::set_count);
    }

    /// Check that the async state and status functions are stored with the access they
    /// asked for, a later definition replacing an earlier one.
    #[test]
    fn class_async_handlers() {

        let def = ClassDef::<AsyncModel>::new("Motor", |_dev| Ok(AsyncModel { count: 0, label: String::new() }))
            .state_async(AsyncModel::state)
            .status_exclusive_async(AsyncModel::status);
        assert!(matches!(def.state, Some(StateFn::SharedAsync(_))));
        assert!(matches!(def.status, Some(StatusFn::ExclusiveAsync(_))));

        let def = def
            .state_exclusive_async_with(|_model: &mut AsyncModel, _dev| Box::pin(async { Ok(DevState::Moving) }))
            .status_async_with(|model: &AsyncModel, _dev| Box::pin(async move { Ok(Scalar::from(model.label.as_str())) }));
        assert!(matches!(def.state, Some(StateFn::ExclusiveAsync(_))));
        assert!(matches!(def.status, Some(StatusFn::SharedAsync(_))));

    }

    /// Check that the status functions convert what they give, a method borrowing it from
    /// the model as well as a closure giving an owned string.
    #[test]
    fn class_status_handlers() {

        let def = ClassDef::<AsyncModel>::new("Motor", |_dev| Ok(AsyncModel { count: 0, label: String::new() }))
            .status(AsyncModel::status_label);
        assert!(matches!(def.status, Some(StatusFn::SharedSync(_))));

        let def = def.status_exclusive(|model: &mut AsyncModel, _dev: &Dev<AsyncModel>| Ok(format!("Count is {}", model.count)));
        assert!(matches!(def.status, Some(StatusFn::ExclusiveSync(_))));

    }

}