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
//! Proxy to database devices.

use std::ops::{Deref, DerefMut};
use std::future::Future;
use std::borrow::Cow;
use std::fmt::Debug;
use std::sync::Arc;

use crate::dev::{All, DevProxy, Named, NamedResult, ProxyTarget, ToNames, ToNamesNotAll, unexpected_len_err};
use crate::error::{Error, ErrorKind, Result, reason};
use crate::backend::{default_backend, Backend};
use crate::prop::{FromProp, IntoProp};
use crate::value::{Scalar, Spectrum};


/// Proxy to a database with easy abstraction for commands that request devices.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct DatabaseProxy {
    dev: DevProxy,
}

impl DatabaseProxy {

    // -- Constructors --

    /// New handle to the environment database.
    pub fn new_from_env() -> Self {
        Self::new_from_env_with_backend(default_backend())
    }

    /// New handle to specific host/port.
    pub fn new(host: &str, port: u16) -> Self {
        Self::new_with_backend(default_backend(), host, port)
    }

    /// New handle to the environment database, with backend.
    pub fn new_from_env_with_backend(backend: Arc<dyn Backend>) -> Self {
        Self {
            dev: DevProxy::new_from_target_with_backend(backend, ProxyTarget::DatabaseFromEnv),
        }
    }

    /// New handle to specific host/port, with backend.
    pub fn new_with_backend(backend: Arc<dyn Backend>, host: &str, port: u16) -> Self {
        Self {
            dev: DevProxy::new_from_target_with_backend(backend, ProxyTarget::DatabaseAt { 
                host: Arc::from(host), 
                port,
            }),
        }
    }

    /// Internal function to reinterpret a device proxy reference as a database proxy.
    pub(crate) fn from_dev(dev: &DevProxy) -> &DatabaseProxy {
        // SAFETY: DatabaseProxy is transparent over DevProxy
        unsafe { &*(dev as *const _ as *const DatabaseProxy) }
    }

    /// Internal function to manually create a database proxy by assuming that the given
    /// device proxy is such device.
    pub(crate) fn with_dev(dev: DevProxy) -> Self {
        Self {
            dev,
        }
    }

    /// The host and port this database is reached at, connecting it if that has not
    /// happened yet, which is the one of `TANGO_HOST` that answered when it is taken from
    /// the environment.
    pub(crate) async fn host_and_port_async(&self) -> Result<(Arc<str>, u16)> {
        let host_and_port = self.dev.database_host_and_port_async().await?;
        Ok(host_and_port.expect("This should be defined if the target is a database"))
    }

    // -- Info --

    /// Get the description of the database server and of what it holds, line by line.
    #[doc(alias = "DbInfo")]
    pub async fn database_info_async(&self) -> Result<Spectrum<str>> {
        self.command_async("DbInfo", ()).await
    }

    /// The blocking form of [`Self::database_info_async`].
    #[doc(alias = "DbInfo")]
    pub fn database_info(&self) -> Result<Spectrum<str>> {
        self.block_on(self.database_info_async())?
    }

    // -- Dev Add/Delete --

    /// Define a device of the given class in a server, named `exe/inst`.
    #[doc(alias = "DbAddDevice")]
    pub async fn add_dev_async(&self, name: &str, class: &str, server: &str) -> Result<()> {
        self.command_async("DbAddDevice", [server, name, class]).await
    }

    /// The blocking form of [`Self::add_dev_async`].
    #[doc(alias = "DbAddDevice")]
    pub fn add_dev(&self, name: &str, class: &str, server: &str) -> Result<()> {
        self.block_on(self.add_dev_async(name, class, server))?
    }

    /// Delete a device.
    #[doc(alias = "DbDeleteDevice")]
    pub async fn delete_dev_async(&self, name: &str) -> Result<()> {
        self.command_async("DbDeleteDevice", name).await
    }

    /// The blocking form of [`Self::delete_dev_async`].
    #[doc(alias = "DbDeleteDevice")]
    pub fn delete_dev(&self, name: &str) -> Result<()> {
        self.block_on(self.delete_dev_async(name))?
    }

    // -- Server --

    /// Define a server, named `exe/inst`, along with its devices, each given with its class,
    /// a device already defined in another server being moved to this one.
    #[doc(alias = "DbAddServer")]
    pub async fn add_server_async(&self, server: &str, devs: &[(&str, &str)]) -> Result<()> {
        let mut args = Vec::with_capacity(1 + devs.len() * 2);
        args.push(server);
        args.extend(devs.iter().flat_map(|&(name, class)| [name, class]));
        self.command_async("DbAddServer", &args[..]).await
    }

    /// The blocking form of [`Self::add_server_async`].
    #[doc(alias = "DbAddServer")]
    pub fn add_server(&self, server: &str, devs: &[(&str, &str)]) -> Result<()> {
        self.block_on(self.add_server_async(server, devs))?
    }

    /// Delete a server, named `exe/inst`, along with every device of it.
    #[doc(alias = "DbDeleteServer")]
    pub async fn delete_server_async(&self, server: &str) -> Result<()> {
        self.command_async("DbDeleteServer", server).await
    }

    /// The blocking form of [`Self::delete_server_async`].
    #[doc(alias = "DbDeleteServer")]
    pub fn delete_server(&self, server: &str) -> Result<()> {
        self.block_on(self.delete_server_async(server))?
    }

    /// Rename a server, named `exe/inst`, its devices following it.
    #[doc(alias = "DbRenameServer")]
    pub async fn rename_server_async(&self, name: &str, new_name: &str) -> Result<()> {
        self.command_async("DbRenameServer", [name, new_name]).await
    }

    /// The blocking form of [`Self::rename_server_async`].
    #[doc(alias = "DbRenameServer")]
    pub fn rename_server(&self, name: &str, new_name: &str) -> Result<()> {
        self.block_on(self.rename_server_async(name, new_name))?
    }

    /// List the devices a server, named `exe/inst`, should run, the class each device is an
    /// instance of being named by that device. This is what a server queries when booting
    /// in order to know which devices to create and export.
    #[doc(alias = "DbGetDeviceClassList")]
    pub async fn list_server_dev_async(&self, server: &str) -> Result<Vec<Named<Scalar<str>>>> {

        let flat: Spectrum<str> = self.command_async("DbGetDeviceClassList", server).await?;

        let mut pairs = Vec::with_capacity(flat.len() / 2);
        let mut index = 0;

        while let Some(dev_name) = flat.get_scalar([index]) {
            let Some(class_name) = flat.get_scalar([index + 1]) else {
                return Err(Error::new(ErrorKind::InvalidData)
                    .with_description(format!("Database answered device {:?} of server {server:?} without its class", dev_name.value()))
                    .with_append_description("Expected: a string spectrum of device/class pairs"));
            };
            pairs.push(Named::new(dev_name, class_name));
            index += 2;
        }

        Ok(pairs)

    }

    /// The blocking form of [`Self::list_server_dev_async`].
    #[doc(alias = "DbGetDeviceClassList")]
    pub fn list_server_dev(&self, server: &str) -> Result<Vec<Named<Scalar<str>>>> {
        self.block_on(self.list_server_dev_async(server))?
    }

    // -- Dev List --

    /// List all existing devices, filtering using a filter, using a pattern for 
    /// matching with domain/family/member pattern, supporting one '*' per member.
    #[doc(alias = "DbGetDeviceWideList")]
    pub async fn list_dev_async(&self, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetDeviceWideList", filter).await
    }

    /// The blocking form of [`Self::list_dev_async`].
    #[doc(alias = "DbGetDeviceWideList")]
    pub fn list_dev(&self, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_dev_async(filter))?
    }

    /// Same as [`Self::list_dev`] but returns only the member part of the
    /// device names (in domain/family/member).
    #[doc(alias = "DbGetDeviceMemberList")]
    pub async fn list_dev_member_async(&self, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetDeviceMemberList", filter).await
    }

    /// The blocking form of [`Self::list_dev_member_async`].
    #[doc(alias = "DbGetDeviceMemberList")]
    pub fn list_dev_member(&self, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_dev_member_async(filter))?
    }

    /// Same as [`Self::list_dev`] but returns only the family part of the
    /// device names (in domain/family/member).
    #[doc(alias = "DbGetDeviceFamilyList")]
    pub async fn list_dev_family_async(&self, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetDeviceFamilyList", filter).await
    }

    /// The blocking form of [`Self::list_dev_family_async`].
    #[doc(alias = "DbGetDeviceFamilyList")]
    pub fn list_dev_family(&self, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_dev_family_async(filter))?
    }

    /// Same as [`Self::list_dev`] but returns only the domain part of the
    /// device names (in domain/family/member).
    #[doc(alias = "DbGetDeviceDomainList")]
    pub async fn list_dev_domain_async(&self, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetDeviceDomainList", filter).await
    }

    /// The blocking form of [`Self::list_dev_domain_async`].
    #[doc(alias = "DbGetDeviceDomainList")]
    pub fn list_dev_domain(&self, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_dev_domain_async(filter))?
    }

    // -- Export --

    /// Mark a device as exported, recording how to reach it.
    #[doc(alias = "DbExportDevice")]
    pub async fn export_dev_async(&self, info: ExportDevInfo<'_>) -> Result<()> {
        self.command_async("DbExportDevice", data_from_export_dev_info(&[info][..])).await
    }

    /// The blocking form of [`Self::export_dev_async`].
    #[doc(alias = "DbExportDevice")]
    pub fn export_dev(&self, info: ExportDevInfo<'_>) -> Result<()> {
        self.block_on(self.export_dev_async(info))?
    }

    /// Mark a device as no longer exported.
    #[doc(alias = "DbUnExportDevice")]
    pub async fn unexport_dev_async(&self, dev_name: &str) -> Result<()> {
        self.command_async("DbUnExportDevice", dev_name).await
    }

    /// The blocking form of [`Self::unexport_dev_async`].
    #[doc(alias = "DbUnExportDevice")]
    pub fn unexport_dev(&self, dev_name: &str) -> Result<()> {
        self.block_on(self.unexport_dev_async(dev_name))?
    }

    /// Mark the devices of a server as exported, see [`Self::export_dev_async`].
    #[doc(alias = "DbExportServer")]
    pub async fn export_server_async(&self, infos: &[ExportDevInfo<'_>]) -> Result<()> {
        self.command_async("DbExportServer", data_from_export_dev_info(infos)).await
    }

    /// The blocking form of [`Self::export_server_async`].
    #[doc(alias = "DbExportServer")]
    pub fn export_server(&self, infos: &[ExportDevInfo<'_>]) -> Result<()> {
        self.block_on(self.export_server_async(infos))?
    }

    /// Mark every device of a server, named `exe/inst`, as no longer exported.
    #[doc(alias = "DbUnExportServer")]
    pub async fn unexport_server_async(&self, server: &str) -> Result<()> {
        self.command_async("DbUnExportServer", server).await
    }

    /// The blocking form of [`Self::unexport_server_async`].
    #[doc(alias = "DbUnExportServer")]
    pub fn unexport_server(&self, server: &str) -> Result<()> {
        self.block_on(self.unexport_server_async(server))?
    }

    /// Same input as [`Self::list_dev`], but returns only devices that should
    /// currently be exported.
    #[doc(alias = "DbGetDeviceExportedList")]
    pub async fn list_exported_dev_async(&self, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetDeviceExportedList", filter).await
    }

    /// The blocking form of [`Self::list_exported_dev_async`].
    #[doc(alias = "DbGetDeviceExportedList")]
    pub fn list_exported_dev(&self, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_exported_dev_async(filter))?
    }

    // -- Import --

    /// Get how to reach a device, failing with [`ErrorKind::DevNotFound`] if not defined.
    #[doc(alias = "DbImportDevice")]
    pub async fn import_dev_async(&self, dev_name: &str) -> Result<ImportDevInfo> {

        let (
            [exported, pid],
            svalue,
        ) = match self.command_async("DbImportDevice", dev_name).await.and_then(long2_string) {
            Ok(ret) => ret,
            Err(err) => {
                if let ErrorKind::Reason(reason::DB_DeviceNotDefined) = err.kind() {
                    return Err(Error::new(ErrorKind::DevNotFound)
                        .with_description(format!("Device {dev_name:?} is not defined in the database"))
                        .with_parent(err));
                } else {
                    return Err(err);
                }
            }
        };

        if svalue.len() != 5 && svalue.len() != 6 {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answered {} strings for device {dev_name:?} where 5 or 6 were expected", svalue.len()))
                .with_append_description(format_args!("Got: {svalue:?}")));
        }

        // Each within the length just checked.
        let field = |index| svalue.get_scalar([index]).unwrap();

        Ok(ImportDevInfo {
            name: field(0),
            itr: field(1),
            host: field(4),
            version: field(2),
            server: field(3),
            class: svalue.get_scalar([5]),
            exported: exported == 1,
            pid,
        })

    }

    /// The blocking form of [`Self::import_dev_async`].
    #[doc(alias = "DbImportDevice")]
    pub fn import_dev(&self, dev_name: &str) -> Result<ImportDevInfo> {
        self.block_on(self.import_dev_async(dev_name))?
    }

    // -- Dev Info --

    /// Get what the database knows of a device, failing with [`ErrorKind::DevNotFound`] if
    /// not defined.
    #[doc(alias = "DbGetDeviceInfo")]
    pub async fn get_dev_info_async(&self, dev_name: &str) -> Result<DbDevInfo> {
        
        let (
            [exported, pid],
            svalue,
        ) = match self.command_async("DbGetDeviceInfo", dev_name).await.and_then(long2_string) {
            Ok(ret) => ret,
            Err(err) => {
                if let ErrorKind::Reason(reason::DB_DeviceNotDefined) = err.kind() {
                    return Err(Error::new(ErrorKind::DevNotFound)
                        .with_description(format!("Device {dev_name:?} is not defined in the database"))
                        .with_parent(err));
                } else {
                    return Err(err);
                }
            }
        };

        if svalue.len() != 7 && svalue.len() != 8 {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answered {} strings for device {dev_name:?} where 7 or 8 were expected", svalue.len()))
                .with_append_description(format_args!("Got: {svalue:?}")));
        }

        // Each within the length just checked.
        let field = |index| svalue.get_scalar([index]).unwrap();

        Ok(DbDevInfo {
            name: field(0),
            itr: field(1),
            host: Some(field(4)).filter(|host| host.value() != "nada"),
            version: field(2),
            server: field(3),
            class: svalue.get_scalar([7]),
            last_exported: Some(field(5)).filter(|time| time.value() != "?"),
            last_unexported: Some(field(6)).filter(|time| time.value() != "?"),
            exported: exported == 1,
            pid: Some(pid).filter(|&pid| pid != 0),
        })

    }

    /// The blocking form of [`Self::get_dev_info_async`].
    #[doc(alias = "DbGetDeviceInfo")]
    pub fn get_dev_info(&self, dev_name: &str) -> Result<DbDevInfo> {
        self.block_on(self.get_dev_info_async(dev_name))?
    }
    
    // -- Dev Alias --

    /// Get alias for a given device.
    #[doc(alias = "DbGetDeviceAlias")]
    pub async fn get_dev_alias_async(&self, dev_name: &str) -> Result<Option<Scalar<str>>> {
        match self.command_async::<_, Scalar<str>>("DbGetDeviceAlias", dev_name).await {
            Ok(ret) => Ok(Some(ret)),
            Err(err) => {
                if let ErrorKind::Reason(reason::DB_AliasNotDefined) = err.kind() {
                    Ok(None)
                } else {
                    Err(err)
                }
            }
        }
    }

    /// The blocking form of [`Self::get_dev_alias_async`].
    #[doc(alias = "DbGetDeviceAlias")]
    pub fn get_dev_alias(&self, dev_name: &str) -> Result<Option<Scalar<str>>> {
        self.block_on(self.get_dev_alias_async(dev_name))?
    }

    /// Resolve a device alias, failing with [`ErrorKind::AliasNotFound`] if not found.
    #[doc(alias = "DbGetAliasDevice")]
    pub async fn resolve_dev_alias_async(&self, alias: &str) -> Result<Scalar<str>> {
        match self.command_async("DbGetAliasDevice", alias).await {
            Ok(ret) => Ok(ret),
            Err(err) => {
                if let ErrorKind::Reason(reason::DB_AliasNotDefined) = err.kind() {
                    Err(Error::new(ErrorKind::AliasNotFound)
                        .with_description(format!("Device alias {alias:?} is not defined in the database"))
                        .with_parent(err))
                } else {
                    Err(err)
                }
            }
        }
    }

    /// The blocking form of [`Self::resolve_dev_alias_async`].
    #[doc(alias = "DbGetAliasDevice")]
    pub fn resolve_dev_alias(&self, alias: &str) -> Result<Scalar<str>> {
        self.block_on(self.resolve_dev_alias_async(alias))?
    }

    /// List all device aliases matching the given filter (using at most one '*').
    #[doc(alias = "DbGetDeviceAliasList")]
    pub async fn list_dev_aliases_async(&self, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetDeviceAliasList", filter).await
    }

    /// The blocking form of [`Self::list_dev_aliases_async`].
    #[doc(alias = "DbGetDeviceAliasList")]
    pub fn list_dev_aliases(&self, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_dev_aliases_async(filter))?
    }

    // -- Attr Alias --

    /// Get alias for a given attribute.
    #[doc(alias = "DbGetAttributeAlias")]
    pub async fn get_attr_alias_async(&self, attr_name: &str) -> Result<Option<Scalar<str>>> {
        match self.command_async::<_, Scalar<str>>("DbGetAttributeAlias", attr_name).await {
            Ok(ret) => Ok(Some(ret)),
            Err(err) => {
                if let ErrorKind::Reason(reason::DB_AliasNotDefined) = err.kind() {
                    Ok(None)
                } else {
                    Err(err)
                }
            }
        }
    }

    /// The blocking form of [`Self::get_attr_alias_async`].
    #[doc(alias = "DbGetAttributeAlias")]
    pub fn get_attr_alias(&self, attr_name: &str) -> Result<Option<Scalar<str>>> {
        self.block_on(self.get_attr_alias_async(attr_name))?
    }

    /// Resolve an attribute alias, failing with [`ErrorKind::AliasNotFound`] if not found.
    #[doc(alias = "DbGetAliasAttribute")]
    pub async fn resolve_attr_alias_async(&self, alias: &str) -> Result<Scalar<str>> {
        match self.command_async("DbGetAliasAttribute", alias).await {
            Ok(ret) => Ok(ret),
            Err(err) => {
                if let ErrorKind::Reason(reason::DB_AliasNotDefined) = err.kind() {
                    Err(Error::new(ErrorKind::AliasNotFound)
                        .with_description(format!("Attribute alias {alias:?} is not defined in the database"))
                        .with_parent(err))
                } else {
                    Err(err)
                }
            }
        }
    }

    /// The blocking form of [`Self::resolve_attr_alias_async`].
    #[doc(alias = "DbGetAliasAttribute")]
    pub fn resolve_attr_alias(&self, alias: &str) -> Result<Scalar<str>> {
        self.block_on(self.resolve_attr_alias_async(alias))?
    }

    /// List all attribute aliases matching the given filter (using at most one '*').
    #[doc(alias = "DbGetAttributeAliasList")]
    pub async fn list_attr_aliases_async(&self, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetAttributeAliasList", filter).await
    }

    /// The blocking form of [`Self::list_attr_aliases_async`].
    #[doc(alias = "DbGetAttributeAliasList")]
    pub fn list_attr_aliases(&self, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_attr_aliases_async(filter))?
    }

    // -- Free Prop List --

    /// List the names of the free properties of an object matching the given filter.
    #[doc(alias = "DbGetPropertyList")]
    pub async fn list_free_prop_async(&self, obj_name: &str, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetPropertyList", [obj_name, filter]).await
    }

    /// The blocking form of [`Self::list_free_prop_async`].
    #[doc(alias = "DbGetPropertyList")]
    pub fn list_free_prop(&self, obj_name: &str, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_free_prop_async(obj_name, filter))?
    }

    // -- Class Prop List --

    /// List the names of the properties of a class matching the given filter.
    #[doc(alias = "DbGetClassPropertyList")]
    #[doc(alias = "DbGetClassPropertyListWildcard")]
    pub async fn list_class_prop_async(&self, obj_name: &str, filter: &str) -> Result<Spectrum<str>> {
        if filter == "*" {
            self.command_async("DbGetClassPropertyList", [obj_name]).await
        } else {
            self.command_async("DbGetClassPropertyListWildcard", [obj_name, filter]).await
        }
    }

    /// The blocking form of [`Self::list_class_prop_async`].
    #[doc(alias = "DbGetClassPropertyList")]
    #[doc(alias = "DbGetClassPropertyListWildcard")]
    pub fn list_class_prop(&self, obj_name: &str, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_class_prop_async(obj_name, filter))?
    }

    // -- Dev Prop List --

    /// List the names of the properties of a device matching the given filter.
    #[doc(alias = "DbGetDevicePropertyList")]
    pub async fn list_dev_prop_async(&self, obj_name: &str, filter: &str) -> Result<Spectrum<str>> {
        self.command_async("DbGetDevicePropertyList", [obj_name, filter]).await
    }

    /// The blocking form of [`Self::list_dev_prop_async`].
    #[doc(alias = "DbGetDevicePropertyList")]
    pub fn list_dev_prop(&self, obj_name: &str, filter: &str) -> Result<Spectrum<str>> {
        self.block_on(self.list_dev_prop_async(obj_name, filter))?
    }

    // -- Common Prop Get --

    /// The reply to a read of the properties of that object, which is what every property
    /// read comes down to, see [`PropCommands`]: the parameters are the object and the
    /// names of the properties, see [`prop_params`], or absent for every property it has.
    ///
    /// The names are what the answer is checked against once it comes back, so the reply
    /// keeps them, sharing the parameters they were sent in.
    pub(crate) async fn get_raw_prop_async(&self,
        commands: PropCommands,
        obj_name: &str,
        params: Option<Spectrum<str>>,
    ) -> Result<get_prop::PropReply> {

        let params = match params {
            Some(params) => params,
            None => {
                let list_params = [obj_name, "*"];
                let list_params = if commands.list_wildcard { &list_params[..] } else { &list_params[0..1] };
                let names: Spectrum<str> = self.command_async(commands.list, list_params).await?;
                prop_params(obj_name, names.iter())
            }
        };

        let names = params.slice(1..);

        // The database rejects a request carrying no property name at all, answering that
        // it needs at least the object and one property, so it is simply not sent: there is
        // nothing to report, which is what an object having no property at all gives, the
        // property list command having then answered with an empty list.
        if names.is_empty() {
            return Ok(get_prop::PropReply::empty());
        }

        let listing: Spectrum<str> = self.command_async(commands.get, params).await?;
        get_prop::PropReply::new(obj_name, listing, names)

    }

    /// Read properties of that object, parsed into the shape the given names ask for.
    fn get_any_prop_async<Spec, Names: ToNames>(&self,
        commands: PropCommands,
        obj_name: &str,
        names: Names,
    ) -> impl Future<Output = Result<Spec::Output>> + Send
    where
        Spec: GetPropSpec<Names>,
    {
        let params = names.iter_names().map(|names| prop_params(obj_name, names));
        async move {
            let mut reply = self.get_raw_prop_async(commands, obj_name, params).await?;
            Spec::collect(&mut reply)
        }
    }

    // -- Free Prop Get --

    /// The properties of that free object, parsed into the shape the given names ask for,
    /// see [`Self::get_dev_prop_async`] for the accepted signatures.
    #[doc(alias = "DbGetProperty")]
    pub fn get_free_prop_async<Spec, Names: ToNames>(&self, obj_name: &str, names: Names) -> impl Future<Output = Result<Spec::Output>> + Send
    where
        Spec: GetPropSpec<Names>,
    {
        self.get_any_prop_async::<Spec, Names>(PropCommands::FREE, obj_name, names)
    }

    /// The properties of that free object, see [`Self::get_free_prop_async`].
    #[doc(alias = "DbGetProperty")]
    pub fn get_free_prop<Spec, Names: ToNames>(&self, obj_name: &str, names: Names) -> Result<Spec::Output>
    where
        Spec: GetPropSpec<Names>,
    {
        self.block_on(self.get_free_prop_async::<Spec, Names>(obj_name, names))?
    }

    // -- Class Prop Get --

    /// The properties of that class, parsed into the shape the given names ask for, see
    /// [`Self::get_dev_prop_async`] for the accepted signatures.
    #[doc(alias = "DbGetClassProperty")]
    pub fn get_class_prop_async<Spec, Names: ToNames>(&self, class_name: &str, names: Names) -> impl Future<Output = Result<Spec::Output>> + Send
    where
        Spec: GetPropSpec<Names>,
    {
        self.get_any_prop_async::<Spec, Names>(PropCommands::CLASS, class_name, names)
    }

    /// The properties of that class, see [`Self::get_class_prop_async`].
    #[doc(alias = "DbGetClassProperty")]
    pub fn get_class_prop<Spec, Names: ToNames>(&self, class_name: &str, names: Names) -> Result<Spec::Output>
    where
        Spec: GetPropSpec<Names>,
    {
        self.block_on(self.get_class_prop_async::<Spec, Names>(class_name, names))?
    }

    // -- Dev Prop Get --

    /// The properties of that device, parsed into the shape the given names ask for. This
    /// specification is really flexible and allows various signatures for the function:
    /// 1. `get_dev_prop<T>(&str, &str) -> Result<T>`
    /// 2. `get_dev_prop<T>(&str, &[&str]) -> Result<Vec<Result<T>>>`
    /// 3. `get_dev_prop<T>(&str, [&str; N]) -> Result<[Result<T>; N]>`
    /// 4. `get_dev_prop<(A, B, ...)>(&str, (&str, &str, ...)) -> Result<(Result<A>, Result<B>, ...)>`
    /// 5. `get_dev_prop<Spectrum<str>>(&str, All) -> Result<Vec<Named<Spectrum<str>>>>`
    ///
    /// Form 2 also takes the names as a [`Spectrum<str>`], owned or borrowed. Every value
    /// is parsed with [`FromProp`]: a [`String`], a [`Vec<String>`], a [`Spectrum<str>`]
    /// sharing the reply, a [`bool`] or a number. Like for [`DevProxy::read_attr`], the
    /// type has to come from a turbofish, as in `get_dev_prop::<f64, _>(dev, "speed")`,
    /// or from the binding the output is assigned to.
    ///
    /// A property the database holds nothing for has no value, which the text forms read
    /// as empty and the others fail with [`ErrorKind::InvalidProp`]. Form 5 gives every
    /// property the device has, each with its name, as the raw values it holds.
    ///
    /// All the properties are read within a single request. Note that, unlike the
    /// many-properties forms, form 1 has no per-property slot in its output and therefore
    /// returns that property's error directly.
    #[doc(alias = "DbGetDeviceProperty")]
    pub fn get_dev_prop_async<Spec, Names: ToNames>(&self, dev_name: &str, names: Names) -> impl Future<Output = Result<Spec::Output>> + Send
    where
        Spec: GetPropSpec<Names>,
    {
        self.get_any_prop_async::<Spec, Names>(PropCommands::DEV, dev_name, names)
    }

    /// The properties of that device, see [`Self::get_dev_prop_async`].
    #[doc(alias = "DbGetDeviceProperty")]
    pub fn get_dev_prop<Spec, Names: ToNames>(&self, dev_name: &str, names: Names) -> Result<Spec::Output>
    where
        Spec: GetPropSpec<Names>,
    {
        self.block_on(self.get_dev_prop_async::<Spec, Names>(dev_name, names))?
    }

    // -- Common Prop Command --

    /// Send a property command with those parameters, which every property write and
    /// deletion comes down to, see [`prop_params`].
    pub(crate) async fn prop_command_async(&self, cmd_name: &'static str, params: Spectrum<str>) -> Result<()> {
        self.command_async(cmd_name, params).await
    }

    // -- Free Prop Set --

    /// Write the given properties of that free object, see [`Self::set_dev_prop_async`]
    /// for the accepted signatures.
    #[doc(alias = "DbPutProperty")]
    pub fn set_free_prop_async<'a, Spec>(&self, obj_name: &'a str, spec: Spec) -> impl Future<Output = Result<()>> + Send
    where
        Spec: SetPropSpec<'a>,
    {
        self.prop_command_async("DbPutProperty", prop_params(obj_name, set_prop_params(spec).iter().map(|param| &**param)))
    }

    /// Write the given properties of that free object, see [`Self::set_free_prop_async`].
    #[doc(alias = "DbPutProperty")]
    pub fn set_free_prop<'a, Spec>(&self, obj_name: &'a str, spec: Spec) -> Result<()>
    where
        Spec: SetPropSpec<'a>,
    {
        self.block_on(self.set_free_prop_async(obj_name, spec))?
    }

    // -- Class Prop Set --

    /// Write the given properties of that class, see [`Self::set_dev_prop_async`] for the
    /// accepted signatures.
    #[doc(alias = "DbPutClassProperty")]
    pub fn set_class_prop_async<'a, Spec>(&self, class_name: &'a str, spec: Spec) -> impl Future<Output = Result<()>> + Send
    where
        Spec: SetPropSpec<'a>,
    {
        self.prop_command_async("DbPutClassProperty", prop_params(class_name, set_prop_params(spec).iter().map(|param| &**param)))
    }

    /// Write the given properties of that class, see [`Self::set_class_prop_async`].
    #[doc(alias = "DbPutClassProperty")]
    pub fn set_class_prop<'a, Spec>(&self, class_name: &'a str, spec: Spec) -> Result<()>
    where
        Spec: SetPropSpec<'a>,
    {
        self.block_on(self.set_class_prop_async(class_name, spec))?
    }

    // -- Dev Prop Set --

    /// Write the given properties of that device, given as pairs of a name and a value.
    /// Like for [`Self::get_dev_prop`], this specification is really flexible and allows
    /// various signatures for the function:
    /// 1. `set_dev_prop(&str, (&str, T)) -> Result<()>`
    /// 2. `set_dev_prop(&str, [(&str, T); N]) -> Result<()>`
    /// 3. `set_dev_prop(&str, Vec<(&str, T)>) -> Result<()>`
    /// 4. `set_dev_prop(&str, ((&str, A), (&str, B), ...)) -> Result<()>`
    ///
    /// Each value only needs to implement [`IntoProp`], a [`bool`], a number or a string,
    /// so the value types are inferred from the specification and never have to be named,
    /// form 4 giving each property its own type, as in
    /// `set_dev_prop(dev, (("speed", 2.5), ("unit", "mm")))`.
    ///
    /// All the properties are written within a single request, a property that was
    /// already there being overwritten.
    #[doc(alias = "DbPutDeviceProperty")]
    pub fn set_dev_prop_async<'a, Spec>(&self, dev_name: &'a str, spec: Spec) -> impl Future<Output = Result<()>> + Send
    where
        Spec: SetPropSpec<'a>,
    {
        self.prop_command_async("DbPutDeviceProperty", prop_params(dev_name, set_prop_params(spec).iter().map(|param| &**param)))
    }

    /// Write the given properties of that device, see [`Self::set_dev_prop_async`].
    #[doc(alias = "DbPutDeviceProperty")]
    pub fn set_dev_prop<'a, Spec>(&self, dev_name: &'a str, spec: Spec) -> Result<()>
    where
        Spec: SetPropSpec<'a>,
    {
        self.block_on(self.set_dev_prop_async(dev_name, spec))?
    }

    // -- Free Prop Del --

    /// Delete the given properties of that free object, see [`Self::delete_dev_prop_async`]
    /// for the accepted signatures.
    #[doc(alias = "DbDeleteProperty")]
    pub fn delete_free_prop_async<Names: ToNamesNotAll>(&self, obj_name: &str, names: Names) -> impl Future<Output = Result<()>> + Send {
        self.prop_command_async("DbDeleteProperty", prop_params(obj_name, names.iter_names_not_all()))
    }

    /// Delete the given properties of that free object, see [`Self::delete_free_prop_async`].
    #[doc(alias = "DbDeleteProperty")]
    pub fn delete_free_prop<Names: ToNamesNotAll>(&self, obj_name: &str, names: Names) -> Result<()> {
        self.block_on(self.delete_free_prop_async(obj_name, names))?
    }

    // -- Class Prop Del --

    /// Delete the given properties of that class, see [`Self::delete_dev_prop_async`] for the
    /// accepted signatures.
    #[doc(alias = "DbDeleteClassProperty")]
    pub fn delete_class_prop_async<Names: ToNamesNotAll>(&self, class_name: &str, names: Names) -> impl Future<Output = Result<()>> + Send {
        self.prop_command_async("DbDeleteClassProperty", prop_params(class_name, names.iter_names_not_all()))
    }

    /// Delete the given properties of that class, see [`Self::delete_class_prop_async`].
    #[doc(alias = "DbDeleteClassProperty")]
    pub fn delete_class_prop<Names: ToNamesNotAll>(&self, class_name: &str, names: Names) -> Result<()> {
        self.block_on(self.delete_class_prop_async(class_name, names))?
    }

    // -- Dev Prop Del --

    /// Delete the given properties of that device, which allows various signatures for the
    /// function:
    /// 1. `delete_dev_prop(&str, &str) -> Result<()>`
    /// 2. `delete_dev_prop(&str, &[&str]) -> Result<()>`
    /// 3. `delete_dev_prop(&str, [&str; N]) -> Result<()>`
    /// 4. `delete_dev_prop(&str, (&str, &str, ...)) -> Result<()>`
    ///
    /// Form 2 also takes the names as a [`Spectrum<str>`], owned or borrowed. Every name
    /// has to be given, [`All`] not being accepted, and deleting a property the database
    /// holds nothing for is not an error.
    #[doc(alias = "DbDeleteDeviceProperty")]
    pub fn delete_dev_prop_async<Names: ToNamesNotAll>(&self, dev_name: &str, names: Names) -> impl Future<Output = Result<()>> + Send {
        self.prop_command_async("DbDeleteDeviceProperty", prop_params(dev_name, names.iter_names_not_all()))
    }

    /// Delete the given properties of that device, see [`Self::delete_dev_prop_async`].
    #[doc(alias = "DbDeleteDeviceProperty")]
    pub fn delete_dev_prop<Names: ToNamesNotAll>(&self, dev_name: &str, names: Names) -> Result<()> {
        self.block_on(self.delete_dev_prop_async(dev_name, names))?
    }

    // -- Common Attr Prop Get --

    /// The reply to a read of the properties of attributes of that object, which is what
    /// every attribute property read comes down to, see [`AttrPropCommands`]: the parameters
    /// are the object and the names of the attributes, see [`prop_params`], or absent for
    /// every attribute that has any property, and the properties are those of the given
    /// names of every attribute, or absent for every property each one has.
    ///
    /// The database answers with every property it holds of each attribute, there being no
    /// asking it for some of them only, so the properties asked for are looked up in what it
    /// answered, and one it does not hold is given with no value, see
    /// [`get_prop::PropReply::Attr`].
    pub(crate) async fn get_raw_attr_prop_async(&self,
        commands: AttrPropCommands,
        obj_name: &str,
        params: Option<Spectrum<str>>,
        prop_names: Option<Spectrum<str>>,
    ) -> Result<get_prop::AttrPropReply> {

        let params = match params {
            Some(params) => params,
            None => {
                let attr_names: Spectrum<str> = self.command_async(commands.list, [obj_name, "*"]).await?;
                prop_params(obj_name, attr_names.iter())
            }
        };

        // The names the answer is checked against, sharing the parameters.
        let attr_names = params.slice(1..);

        // A request carrying no attribute at all is not worth sending, there being nothing
        // it could answer with.
        if attr_names.is_empty() {
            return Ok(get_prop::AttrPropReply::empty());
        }

        let listing: Spectrum<str> = self.command_async(commands.get, params).await?;
        get_prop::AttrPropReply::new(obj_name, listing, attr_names, prop_names)

    }

    /// Read the properties of attributes of that object, parsed into the shape the names of
    /// the attributes and the names of the properties ask for, see [`GetAttrPropSpec`].
    fn get_any_attr_prop_async<Spec, AttrNames, Names>(&self,
        commands: AttrPropCommands,
        obj_name: &str,
        attr_names: AttrNames,
        prop_names: Names,
    ) -> impl Future<Output = Result<Spec::Output>> + Send
    where
        Spec: GetAttrPropSpec<AttrNames, Names>,
        AttrNames: ToNames,
        Names: ToNames,
    {
        let params = attr_names.iter_names().map(|attr_names| prop_params(obj_name, attr_names));
        let prop_names = prop_names.to_names();
        async move {
            let mut reply = self.get_raw_attr_prop_async(commands, obj_name, params, prop_names).await?;
            Spec::collect(&mut reply)
        }
    }

    // -- Class Attr Prop Get --

    /// The properties of the given attributes of that class, parsed into the shape the names
    /// of the attributes and of the properties ask for, see [`Self::get_dev_attr_prop_async`]
    /// for the accepted signatures.
    #[doc(alias = "DbGetClassAttributeProperty2")]
    pub fn get_class_attr_prop_async<Spec, AttrNames, Names>(&self, class_name: &str, attr_names: AttrNames, prop_names: Names) -> impl Future<Output = Result<Spec::Output>> + Send
    where
        Spec: GetAttrPropSpec<AttrNames, Names>,
        AttrNames: ToNames,
        Names: ToNames,
    {
        self.get_any_attr_prop_async::<Spec, AttrNames, Names>(AttrPropCommands::CLASS, class_name, attr_names, prop_names)
    }

    /// The properties of the given attributes of that class, see
    /// [`Self::get_class_attr_prop_async`].
    #[doc(alias = "DbGetClassAttributeProperty2")]
    pub fn get_class_attr_prop<Spec, AttrNames, Names>(&self, class_name: &str, attr_names: AttrNames, prop_names: Names) -> Result<Spec::Output>
    where
        Spec: GetAttrPropSpec<AttrNames, Names>,
        AttrNames: ToNames,
        Names: ToNames,
    {
        self.block_on(self.get_class_attr_prop_async::<Spec, AttrNames, Names>(class_name, attr_names, prop_names))?
    }

    // -- Dev Attr Prop Get --

    /// The properties of the given attributes of that device, or of every attribute of it
    /// that has any, parsed into the shape the names of the attributes and of the properties
    /// ask for. The names of the properties are given the way they are to
    /// [`Self::get_dev_prop`], and give the same output for every attribute, written `P`
    /// below, which the names of the attributes then shape in the same way:
    /// 1. `get_dev_attr_prop<T>(&str, &str, Names) -> Result<P>`
    /// 2. `get_dev_attr_prop<T>(&str, &[&str], Names) -> Result<Vec<Result<P>>>`
    /// 3. `get_dev_attr_prop<T>(&str, [&str; N], Names) -> Result<[Result<P>; N]>`
    /// 4. `get_dev_attr_prop<T>(&str, (&str, &str, ...), Names) -> Result<(Result<P>, Result<P>, ...)>`
    /// 5. `get_dev_attr_prop<T>(&str, All, Names) -> Result<Vec<NamedResult<P>>>`
    ///
    /// Form 2 also takes the names as a [`Spectrum<str>`], owned or borrowed, and form 5
    /// gives every attribute the device holds any property for, each with its name. For
    /// instance:
    /// - `get_dev_attr_prop::<String, _, _>(dev, "Position", "unit") -> Result<String>`
    /// - `get_dev_attr_prop::<String, _, _>(dev, ["Position", "Speed"], "unit") -> Result<[Result<String>; 2]>`
    /// - `get_dev_attr_prop::<(String, f64), _, _>(dev, "Position", ("label", "__value")) -> Result<(Result<String>, Result<f64>)>`
    /// - `get_dev_attr_prop::<Spectrum<str>, _, _>(dev, All, All) -> Result<Vec<NamedResult<Vec<Named<Spectrum<str>>>>>>`
    ///
    /// All the attributes are read within a single request. Note that form 1 has no
    /// per-attribute slot in its output and therefore returns that attribute's error
    /// directly, the same way form 1 of the properties does.
    #[doc(alias = "DbGetDeviceAttributeProperty2")]
    pub fn get_dev_attr_prop_async<Spec, AttrNames, Names>(&self, dev_name: &str, attr_names: AttrNames, prop_names: Names) -> impl Future<Output = Result<Spec::Output>> + Send
    where
        Spec: GetAttrPropSpec<AttrNames, Names>,
        AttrNames: ToNames,
        Names: ToNames,
    {
        self.get_any_attr_prop_async::<Spec, AttrNames, Names>(AttrPropCommands::DEV, dev_name, attr_names, prop_names)
    }

    /// The properties of the given attributes of that device, see
    /// [`Self::get_dev_attr_prop_async`].
    #[doc(alias = "DbGetDeviceAttributeProperty2")]
    pub fn get_dev_attr_prop<Spec, AttrNames, Names>(&self, dev_name: &str, attr_names: AttrNames, prop_names: Names) -> Result<Spec::Output>
    where
        Spec: GetAttrPropSpec<AttrNames, Names>,
        AttrNames: ToNames,
        Names: ToNames,
    {
        self.block_on(self.get_dev_attr_prop_async::<Spec, AttrNames, Names>(dev_name, attr_names, prop_names))?
    }

    // -- Class Attr Prop Set --

    /// Write the given properties of attributes of that class, see
    /// [`Self::set_dev_attr_prop_async`] for the accepted signatures.
    #[doc(alias = "DbPutClassAttributeProperty2")]
    pub fn set_class_attr_prop_async<'a, Spec>(&self, class_name: &'a str, spec: Spec) -> impl Future<Output = Result<()>> + Send
    where
        Spec: SetAttrPropSpec<'a>,
    {
        self.prop_command_async("DbPutClassAttributeProperty2", attr_prop_params(class_name, spec))
    }

    /// Write the given properties of attributes of that class, see
    /// [`Self::set_class_attr_prop_async`].
    #[doc(alias = "DbPutClassAttributeProperty2")]
    pub fn set_class_attr_prop<'a, Spec>(&self, class_name: &'a str, spec: Spec) -> Result<()>
    where
        Spec: SetAttrPropSpec<'a>,
    {
        self.block_on(self.set_class_attr_prop_async(class_name, spec))?
    }

    // -- Dev Attr Prop Set --

    /// Write the given properties of attributes of that device, each attribute given as a
    /// pair of its name and of its properties, the latter in any of the forms
    /// [`Self::set_dev_prop`] accepts, written `S` below:
    /// 1. `set_dev_attr_prop(&str, (&str, S)) -> Result<()>`
    /// 2. `set_dev_attr_prop(&str, [(&str, S); N]) -> Result<()>`
    /// 3. `set_dev_attr_prop(&str, Vec<(&str, S)>) -> Result<()>`
    ///
    /// Forms 2 and 3 give every attribute the same form of properties. For instance:
    /// - `set_dev_attr_prop(dev, ("Position", ("unit", "mm")))`
    /// - `set_dev_attr_prop(dev, ("Position", (("unit", "mm"), ("min_value", -5))))`
    /// - `set_dev_attr_prop(dev, [("Position", vec![("label", "Pos")]), ("Speed", vec![("rel_change", "1")])])`
    ///
    /// All the attributes are written within a single request.
    #[doc(alias = "DbPutDeviceAttributeProperty2")]
    pub fn set_dev_attr_prop_async<'a, Spec>(&self, dev_name: &'a str, spec: Spec) -> impl Future<Output = Result<()>> + Send
    where
        Spec: SetAttrPropSpec<'a>,
    {
        self.prop_command_async("DbPutDeviceAttributeProperty2", attr_prop_params(dev_name, spec))
    }

    /// Write the given properties of attributes of that device, see
    /// [`Self::set_dev_attr_prop_async`].
    #[doc(alias = "DbPutDeviceAttributeProperty2")]
    pub fn set_dev_attr_prop<'a, Spec>(&self, dev_name: &'a str, spec: Spec) -> Result<()>
    where
        Spec: SetAttrPropSpec<'a>,
    {
        self.block_on(self.set_dev_attr_prop_async(dev_name, spec))?
    }

    // -- Class Attr Prop Del --

    /// Delete the given properties of one attribute of that class, see
    /// [`Self::delete_dev_attr_prop_async`] for the accepted signatures.
    #[doc(alias = "DbDeleteClassAttributeProperty")]
    pub fn delete_class_attr_prop_async<Names: ToNamesNotAll>(&self, class_name: &str, attr_name: &str, names: Names) -> impl Future<Output = Result<()>> + Send {
        let params = prop_params(class_name, Some(attr_name).into_iter().chain(names.iter_names_not_all()));
        self.prop_command_async("DbDeleteClassAttributeProperty", params)
    }

    /// Delete the given properties of one attribute of that class, see
    /// [`Self::delete_class_attr_prop_async`].
    #[doc(alias = "DbDeleteClassAttributeProperty")]
    pub fn delete_class_attr_prop<Names: ToNamesNotAll>(&self, class_name: &str, attr_name: &str, names: Names) -> Result<()> {
        self.block_on(self.delete_class_attr_prop_async(class_name, attr_name, names))?
    }

    // -- Dev Attr Prop Del --

    /// Delete the given properties of one attribute of that device, the names of the
    /// properties being given the way they are to [`Self::delete_dev_prop`]:
    /// 1. `delete_dev_attr_prop(&str, &str, &str) -> Result<()>`
    /// 2. `delete_dev_attr_prop(&str, &str, &[&str]) -> Result<()>`
    /// 3. `delete_dev_attr_prop(&str, &str, [&str; N]) -> Result<()>`
    /// 4. `delete_dev_attr_prop(&str, &str, (&str, &str, ...)) -> Result<()>`
    ///
    /// Only one attribute is deleted from per request, the database having no command
    /// deleting from several at once.
    #[doc(alias = "DbDeleteDeviceAttributeProperty")]
    pub fn delete_dev_attr_prop_async<Names: ToNamesNotAll>(&self, dev_name: &str, attr_name: &str, names: Names) -> impl Future<Output = Result<()>> + Send {
        let params = prop_params(dev_name, Some(attr_name).into_iter().chain(names.iter_names_not_all()));
        self.prop_command_async("DbDeleteDeviceAttributeProperty", params)
    }

    /// Delete the given properties of one attribute of that device, see
    /// [`Self::delete_dev_attr_prop_async`].
    #[doc(alias = "DbDeleteDeviceAttributeProperty")]
    pub fn delete_dev_attr_prop<Names: ToNamesNotAll>(&self, dev_name: &str, attr_name: &str, names: Names) -> Result<()> {
        self.block_on(self.delete_dev_attr_prop_async(dev_name, attr_name, names))?
    }

}

impl Deref for DatabaseProxy {
    type Target = DevProxy;
    fn deref(&self) -> &Self::Target {
        &self.dev
    }
}

impl DerefMut for DatabaseProxy {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.dev
    }
}

// =========================== //
//    Device import/export     //
// =========================== //

/// The information required to export a device.
#[derive(Debug, Clone)]
pub struct ExportDevInfo<'a> {
    /// The name of the device.
    pub name: Cow<'a, str>,
    /// The Interoperable Tango Reference to reach the device.
    pub itr: Cow<'a, str>,
    /// The host the device is served on.
    pub host: Cow<'a, str>,
    /// The version of the protocol the device is served with.
    pub version: Cow<'a, str>,
    /// The Process ID of the device's server.
    pub pid: i32,
}

fn data_from_export_dev_info(infos: &[ExportDevInfo<'_>]) -> Spectrum<str> {

    let mut vec = Vec::with_capacity(infos.len() * 5);

    for info in infos {
        vec.push(Cow::Borrowed(&*info.name));
        vec.push(Cow::Borrowed(&*info.itr));
        vec.push(Cow::Borrowed(&*info.host));
        vec.push(Cow::Owned(format!("{}", info.pid)));
        vec.push(Cow::Borrowed(&*info.version));
    }

    Spectrum::from(&vec[..])

}

/// The two members of what the database answers about a device with, which are the
/// exported flag and the process ID, and then its strings.
fn long2_string((longs, strings): (Spectrum<i32>, Spectrum<str>)) -> Result<([i32; 2], Spectrum<str>)> {
    let longs = <[i32; 2]>::try_from(longs.as_slice())
        .map_err(|_| Error::new(ErrorKind::InvalidData)
            .with_description(format!("Database answered {} longs where 2 were expected", longs.len()))
            .with_append_description(format_args!("Got: {longs:?}")))?;
    Ok((longs, strings))
}

/// Information for how to import a device from the database.
#[derive(Debug, Clone)]
pub struct ImportDevInfo {
    /// The name of the device.
    pub name: Scalar<str>,
    /// The Interoperable Tango Reference to reach the device.
    pub itr: Scalar<str>,
    /// The device host.
    pub host: Scalar<str>,
    /// The device version.
    pub version: Scalar<str>,
    /// The device server.
    pub server: Scalar<str>,
    /// Class of this device.
    pub class: Option<Scalar<str>>,
    /// True if the device is currently exported by a server.
    pub exported: bool,
    /// The last known Process ID of the device's server.
    pub pid: i32,
}

/// What the database knows of a device, see [`DatabaseProxy::get_dev_info`].
#[derive(Debug, Clone)]
pub struct DbDevInfo {
    /// The name of the device.
    pub name: Scalar<str>,
    /// The Interoperable Tango Reference to reach the device.
    pub itr: Scalar<str>,
    /// The device host.
    pub host: Option<Scalar<str>>,
    /// The device version.
    pub version: Scalar<str>,
    /// The device server.
    pub server: Scalar<str>,
    /// Class of this device.
    pub class: Option<Scalar<str>>,
    /// When the device was last exported, as the database writes it, if it ever was.
    pub last_exported: Option<Scalar<str>>,    // TODO: Convert to chrono DateTime
    /// When the device was last unexported, as the database writes it, if it ever was.
    pub last_unexported: Option<Scalar<str>>,  // TODO: Convert to chrono DateTime
    /// True if the device is currently exported by a server.
    pub exported: bool,
    /// The last known Process ID of the device's server.
    pub pid: Option<i32>,
}

// =========================== //
//      Property requests      //
// =========================== //

// The property requests give back futures declared `Send`, which hold nothing of what they
// were given but what is taken out of it before anything is awaited: the names, and the
// values to write, so that they are `Send` whatever the names and the values are, which is
// what an asynchronous handler boxing them needs.

/// What a property write carries behind the object: how many properties, then each
/// property with how many values it has and those values, the names and the values staying
/// borrowed.
pub(crate) fn set_prop_params<'a, Spec: SetPropSpec<'a>>(spec: Spec) -> Vec<Cow<'a, str>> {
    let mut builder = set_prop::Builder::new();
    spec.push_to_builder(&mut builder);
    builder.finalize()
}

/// The parameters of a property command, the object first, copied together into the one
/// buffer the command is given.
pub(crate) fn prop_params<'a>(obj_name: &'a str, rest: impl Iterator<Item = &'a str>) -> Spectrum<str> {
    Spectrum::from_strs(Some(obj_name).into_iter().chain(rest)).expect("property parameters of more than 4 GiB")
}

// =========================== //
//       Get properties        //
// =========================== //

/// The commands reading the properties of one kind of object.
#[derive(Debug, Clone, Copy)]
pub(crate) struct PropCommands {
    /// The command reading properties by name.
    get: &'static str,
    /// The command listing the names of the properties.
    list: &'static str,
    /// Whether that listing command takes a filter, the class one taking none.
    list_wildcard: bool,
}

impl PropCommands {
    const FREE: Self = Self { get: "DbGetProperty", list: "DbGetPropertyList", list_wildcard: true };
    const CLASS: Self = Self { get: "DbGetClassProperty", list: "DbGetClassPropertyList", list_wildcard: false };
    pub(crate) const DEV: Self = Self { get: "DbGetDeviceProperty", list: "DbGetDevicePropertyList", list_wildcard: true };
}

/// Sealing module for the reply structure.
mod get_prop {

    use super::{Error, ErrorKind, Named, Result, Scalar, Spectrum};

    /// The properties the database answered a request with, one entry per property and in
    /// the order they were requested, taken one at a time, see [`super::GetPropSpec::collect`].
    ///
    /// Every name and every value shares the octets the answer was decoded out of, so nothing
    /// of them is copied before a caller parses them.
    #[derive(Debug)]
    pub enum PropReply {
        /// The properties of an object, still in the flat sequence of strings the database
        /// speaks in, read one at a time.
        Listing {
            /// The listing, empty when nothing was asked: a request carrying no property name
            /// at all is one the database refuses, so it is not sent, and an object that has no
            /// property gives exactly that.
            listing: Spectrum<str>,
            /// The names that were asked for, in the order they were, which the order of the
            /// answer is checked against.
            names: Spectrum<str>,
            /// Which property is taken next.
            index: usize,
            /// Where in the listing that property starts.
            cursor: usize,
        },
        /// The properties of one attribute, read out of the listing of an attribute property
        /// request, see [`AttrPropReply`].
        ///
        /// The database answers with every property it holds of an attribute, there being no
        /// asking it for some of them only, so the ones asked for are looked up among those
        /// ignoring the case, which is how Tango compares them, and one it does not hold is
        /// given with no value, which is what it answers for a property of an object.
        Attr {
            /// The listing of the whole request, every attribute in it.
            listing: Spectrum<str>,
            /// Where the first property of the attribute starts.
            begin: usize,
            /// How many properties the attribute has.
            count: usize,
            /// The names that were asked for, or none for every property the attribute has,
            /// in the order the database gave them.
            names: Option<Spectrum<str>>,
            /// Which property is taken next.
            index: usize,
            /// Where in the listing that property starts, when every one is taken.
            cursor: usize,
        },
    }

    impl PropReply {

        /// The reply to a request that asked for nothing, which is not sent: it carries no
        /// property and never looks at a listing.
        pub(super) fn empty() -> Self {
            Self::Listing { listing: Spectrum::new(), names: Spectrum::new(), index: 0, cursor: 0 }
        }

        /// The reply to a request for the properties of that object of the given names,
        /// answered with that listing, whose head is read here, see [`read_head`], so that
        /// what is left to take is the properties themselves.
        pub(super) fn new(obj_name: &str, listing: Spectrum<str>, names: Spectrum<str>) -> Result<Self> {
            let cursor = read_head(&listing, obj_name, names.len(), "property count", "properties")?;
            Ok(Self::Listing { listing, names, index: 0, cursor })
        }

        /// How many properties are left to be taken: what was asked for, minus what has already
        /// been taken.
        pub fn len(&self) -> usize {
            match self {
                Self::Listing { names, index, .. } => names.len() - index,
                Self::Attr { names: Some(names), index, .. } => names.len() - index,
                Self::Attr { names: None, count, index, .. } => count - index,
            }
        }

        /// Whether every property has been taken, or nothing was asked for at all.
        pub fn is_empty(&self) -> bool {
            self.len() == 0
        }

        /// Take the next property, which is its name as the database gave it back and the
        /// values it holds, both sharing the listing.
        ///
        /// A property carries a list of values and not one value: what a single value looks
        /// like is what [`crate::prop::FromProp`] makes of that list, an empty one being a property that is
        /// defined and holds nothing.
        ///
        /// A listing that does not add up ends the iteration rather than failing that one
        /// property: where a property starts is where the one before it ended, so nothing
        /// behind a broken one can be read either.
        pub fn next(&mut self) -> Option<Result<Named<Spectrum<str>>>> {

            let (listing, names, index, cursor) = match self {
                Self::Listing { listing, names, index, cursor } => (listing, names, index, cursor),
                Self::Attr { listing, begin, count, names, index, cursor } => {
                    return next_attr_prop(listing, *begin, *count, names.as_ref(), index, cursor);
                }
            };

            let expected = names.get([*index])?;
            *index += 1;

            match next_prop(listing, expected, cursor) {
                Ok(prop) => Some(Ok(prop)),
                Err(err) => {
                    *index = names.len();
                    Some(Err(err))
                }
            }

        }

    }

    /// Read one property out of the listing, starting at `cursor` and leaving it where the next
    /// property starts, see [`PropReply::next`].
    ///
    /// This is where the shape the database speaks in is read: a property is its name, how many
    /// values it holds, and then those values.
    fn next_prop(listing: &Spectrum<str>, expected: &str, cursor: &mut usize) -> Result<Named<Spectrum<str>>> {

        let (Some(name), Some(count_raw)) = (listing.get([*cursor]), listing.get([*cursor + 1])) else {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answer is missing the name and values count of property {expected:?}"))
                .with_append_description(format_args!("Got: {listing:?}")));
        };

        if !name.eq_ignore_ascii_case(expected) {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answered property {name:?} where {expected:?} was requested")));
        }

        let Ok(count) = count_raw.parse::<usize>() else {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answered values count {count_raw:?} of property {name:?}, which is not a number")));
        };

        let name_index = *cursor;
        let begin = *cursor + 2;
        *cursor = begin + count;

        if *cursor > listing.len() {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answer is missing values of property {name:?}"))
                .with_append_description(format_args!("Got: {listing:?}")));
        }

        let name = listing.slice(name_index..name_index + 1).into_scalar().expect("one name");
        Ok(Named::new(name, listing.slice(begin..*cursor)))

    }

    /// Take the next property of an attribute, see [`PropReply::Attr`]: the next one of the
    /// names asked for, looked up among every property of the attribute, or the next one the
    /// attribute has when none was asked for in particular.
    ///
    /// The properties of the attribute were walked once already, by [`AttrPropReply::next`],
    /// so that the next attribute could be found behind them, which a broken one fails.
    fn next_attr_prop(
        listing: &Spectrum<str>,
        begin: usize,
        count: usize,
        names: Option<&Spectrum<str>>,
        index: &mut usize,
        cursor: &mut usize,
    ) -> Option<Result<Named<Spectrum<str>>>> {

        let Some(names) = names else {
            if *index >= count {
                return None;
            }
            *index += 1;
            return Some(next_value_prop(listing, cursor));
        };

        let name = names.get_scalar([*index])?;
        *index += 1;

        let mut lookup = begin;
        for _ in 0..count {
            match next_value_prop(listing, &mut lookup) {
                Ok(prop) if prop.name.value().eq_ignore_ascii_case(name.value()) => {
                    return Some(Ok(prop));
                }
                Ok(_) => {}
                Err(err) => {
                    *index = names.len();
                    return Some(Err(err));
                }
            }
        }

        Some(Ok(Named::new(name, Spectrum::new())))

    }

    /// Read one property of an attribute out of the listing, starting at `cursor` and leaving
    /// it where the next property starts: its name, how many values it holds, and then those
    /// values, a property holding no value being followed by a single placeholder all the
    /// same, which is not one of its values.
    fn next_value_prop(listing: &Spectrum<str>, cursor: &mut usize) -> Result<Named<Spectrum<str>>> {

        let name = next_str(listing, cursor, "property name")?;
        let count = next_count(listing, cursor, "property values count")?;

        let begin = *cursor;
        *cursor += count.max(1);
        if *cursor > listing.len() {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answer is missing values of property {:?}", name.value()))
                .with_append_description(format_args!("Got: {listing:?}")));
        }

        Ok(Named::new(name, listing.slice(begin..begin + count)))

    }

    /// The properties of attributes the database answered a request with, one entry per
    /// attribute and in the order they were requested, taken one at a time, each being the
    /// properties of that attribute, see [`PropReply::Attr`].
    ///
    /// The listing is the flat sequence of strings the database speaks in: every attribute is
    /// its name, how many properties it has, and then those properties.
    #[derive(Debug)]
    pub struct AttrPropReply {
        /// The listing, empty when nothing was asked.
        listing: Spectrum<str>,
        /// The names of the attributes that were asked for, in the order they were, which the
        /// order of the answer is checked against.
        attr_names: Spectrum<str>,
        /// The names of the properties asked for of every attribute, or none for every one.
        prop_names: Option<Spectrum<str>>,
        /// Which attribute is taken next.
        index: usize,
        /// Where in the listing that attribute starts.
        cursor: usize,
    }

    impl AttrPropReply {

        /// The reply to a request that asked for no attribute, which is not sent: it carries
        /// no attribute and never looks at a listing.
        pub(super) fn empty() -> Self {
            Self { listing: Spectrum::new(), attr_names: Spectrum::new(), prop_names: None, index: 0, cursor: 0 }
        }

        /// The reply to a request for the properties of the given names of the attributes of
        /// that object of the given names, answered with that listing, whose head is read
        /// here, see [`read_head`], so that what is left to take is the attributes themselves.
        pub(super) fn new(
            obj_name: &str,
            listing: Spectrum<str>,
            attr_names: Spectrum<str>,
            prop_names: Option<Spectrum<str>>,
        ) -> Result<Self> {
            let cursor = read_head(&listing, obj_name, attr_names.len(), "attribute count", "attributes")?;
            Ok(Self { listing, attr_names, prop_names, index: 0, cursor })
        }

        /// How many attributes are left to be taken.
        pub fn len(&self) -> usize {
            self.attr_names.len() - self.index
        }

        /// Take the next attribute, which is its name as the database gave it back and its
        /// properties.
        ///
        /// A listing that does not add up ends the iteration, an attribute starting where the
        /// one before it ended.
        pub fn next(&mut self) -> Option<Result<Named<PropReply>>> {

            let Self { listing, attr_names, prop_names, index, cursor } = self;

            let expected = attr_names.get([*index])?;
            *index += 1;

            let res = (|| {

                let name = next_str(listing, cursor, "attribute name")?;
                if !name.value().eq_ignore_ascii_case(expected) {
                    return Err(Error::new(ErrorKind::InvalidData)
                        .with_description(format!("Database answered attribute {:?} where {expected:?} was requested",
                            name.value())));
                }

                // The properties are walked here, so that the next attribute is found behind
                // them, and read again as they are taken.
                let count = next_count(listing, cursor, "property count")?;
                let begin = *cursor;
                for _ in 0..count {
                    next_value_prop(listing, cursor)?;
                }

                Ok(Named::new(name, PropReply::Attr {
                    listing: listing.clone(),
                    begin,
                    count,
                    names: prop_names.clone(),
                    index: 0,
                    cursor: begin,
                }))

            })();

            if res.is_err() {
                *index = attr_names.len();
            }

            Some(res)

        }

    }

    /// Read the head of a listing, which is the object it is of and how many entries follow,
    /// checked against what was asked for, giving back where the first entry starts.
    fn read_head(listing: &Spectrum<str>, obj_name: &str, expected: usize, what: &str, entries: &str) -> Result<usize> {

        let mut cursor = 0;

        let output_obj_name = next_str(listing, &mut cursor, "object name")?;
        if !output_obj_name.value().eq_ignore_ascii_case(obj_name) {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answered for object {:?} where {obj_name:?} was requested",
                    output_obj_name.value())));
        }

        let count = next_count(listing, &mut cursor, what)?;
        if count != expected {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answered {count} {entries} of object {obj_name:?} where {expected} were requested")));
        }

        Ok(cursor)

    }

    /// The string at the cursor of a listing, moving the cursor past it.
    fn next_str(listing: &Spectrum<str>, cursor: &mut usize, what: &str) -> Result<Scalar<str>> {
        let Some(value) = listing.get_scalar([*cursor]) else {
            return Err(Error::new(ErrorKind::InvalidData)
                .with_description(format!("Database answer is missing the {what}"))
                .with_append_description(format_args!("Got: {listing:?}")));
        };
        *cursor += 1;
        Ok(value)
    }

    /// The count at the cursor of a listing, moving the cursor past it, see [`next_str`].
    fn next_count(listing: &Spectrum<str>, cursor: &mut usize, what: &str) -> Result<usize> {
        let raw = next_str(listing, cursor, what)?;
        raw.value().trim().parse::<usize>().map_err(|_| Error::new(ErrorKind::InvalidData)
            .with_description(format!("Database answered {what} {:?}, which is not a number", raw.value())))
    }

}

/// A trait for property specifiers, which allows a great flexibility in how
/// [`DatabaseProxy::get_dev_prop`] works.
///
/// **Supporting trait**: it is only there to make this crate's API easier to use, it is
/// implemented for everything that API accepts and is not one to implement anywhere else.
pub trait GetPropSpec<Names> {

    /// Kind of output type returned.
    type Output;

    /// Build the output out of the properties, taking them one at a time.
    ///
    /// The shape of the output is what the names that were given say it is, and what every
    /// property is parsed into is what this is implemented on.
    fn collect(props: &mut get_prop::PropReply) -> Result<Self::Output>;

}

/// One name, one property: that property *is* the output, and its failure is the output's
/// own since there is no slot of its own to carry it in.
impl<T> GetPropSpec<&'_ str> for T
where
    T: FromProp,
{

    type Output = T;

    fn collect(props: &mut get_prop::PropReply) -> Result<Self::Output> {
        match props.next() {
            Some(entry) => T::from_prop(&entry?.value),
            None => Err(unexpected_len_err(1)),
        }
    }

}

impl<T> GetPropSpec<&'_ [&'_ str]> for T
where
    T: FromProp,
{

    type Output = Vec<Result<T>>;

    fn collect(props: &mut get_prop::PropReply) -> Result<Self::Output> {

        // How many properties there are is known before the first one is taken, so the room
        // for them is made once.
        let mut values = Vec::with_capacity(props.len());

        while let Some(entry) = props.next() {
            values.push(T::from_prop(&entry?.value));
        }

        Ok(values)

    }

}

impl<T> GetPropSpec<Spectrum<str>> for T
where
    T: FromProp,
{

    type Output = Vec<Result<T>>;

    fn collect(props: &mut get_prop::PropReply) -> Result<Self::Output> {
        <T as GetPropSpec<&[&str]>>::collect(props)
    }

}

impl<T> GetPropSpec<&Spectrum<str>> for T
where
    T: FromProp,
{

    type Output = Vec<Result<T>>;

    fn collect(props: &mut get_prop::PropReply) -> Result<Self::Output> {
        <T as GetPropSpec<&[&str]>>::collect(props)
    }

}

impl<T, const N: usize> GetPropSpec<[&'_ str; N]> for T
where
    T: FromProp,
{

    type Output = [Result<T>; N];

    fn collect(props: &mut get_prop::PropReply) -> Result<Self::Output> {

        // One property per slot, a last one behind them being a broken reply as much as one
        // of them missing, see [`crate::dev::take_array`].
        let mut slots = [const { None }; N];
        for slot in &mut slots {
            let entry = props.next().ok_or_else(|| unexpected_len_err(N))?;
            *slot = Some(T::from_prop(&entry?.value));
        }
        if props.next().is_some() {
            return Err(unexpected_len_err(N));
        }

        Ok(slots.map(|slot| slot.expect("every slot is filled")))

    }
    
}

impl GetPropSpec<All> for Spectrum<str> {

    type Output = Vec<Named<Spectrum<str>>>;

    fn collect(props: &mut get_prop::PropReply) -> Result<Self::Output> {

        // Nothing was named here, so every property carries its own name, both sharing the
        // listing they were read out of.
        let mut values = Vec::with_capacity(props.len());

        while let Some(entry) = props.next() {
            values.push(entry?);
        }

        Ok(values)

    }

}

macro_rules! impl_get_prop_spec_tuple {
    ( @one: $comp:ident ) => { 1 };
    ( @name: $comp:ident ) => { &'name str };
    ( $( $comp:ident )* ) => {

        #[allow(non_snake_case)]
        impl<'name, $($comp,)* > GetPropSpec<( $( impl_get_prop_spec_tuple!(@name: $comp), )* )> for ( $($comp,)* )
        where
            $(
            $comp: FromProp,
            )*
        {

            type Output = ( $( Result<$comp>,)* );

            fn collect(props: &mut get_prop::PropReply) -> Result<Self::Output> {

                const LEN: usize = 0 $( + impl_get_prop_spec_tuple!(@one: $comp) )*;

                // The properties are taken in the order the names were given, which is the
                // order the components of a tuple are built in, and every one of them is
                // parsed into the type of its own component.
                let output = ( $( {
                    let entry = props.next().ok_or_else(|| unexpected_len_err(LEN))?;
                    $comp::from_prop(&entry?.value)
                }, )* );
                if props.next().is_some() {
                    return Err(unexpected_len_err(LEN));
                }

                Ok(output)

            }

        }

    };
}

impl_get_prop_spec_tuple!(A);
impl_get_prop_spec_tuple!(A B);
impl_get_prop_spec_tuple!(A B C);
impl_get_prop_spec_tuple!(A B C D);
impl_get_prop_spec_tuple!(A B C D E);
impl_get_prop_spec_tuple!(A B C D E F);

// =========================== //
//       Set properties        //
// =========================== //

/// Sealing module for the Builder structure.
mod set_prop {

    use super::{Cow, IntoProp, SetPropSpec};

    pub struct Builder<'a> {
        array: Vec<Cow<'a, str>>,
        count: usize,
    }

    impl<'a> Builder<'a> {

        pub fn new() -> Self {
            Self {
                array: vec![Cow::Borrowed("")],  // Properties count is set when finalized.
                count: 0,
            }
        }

        pub fn push<T>(&mut self, name: &'a str, value: T)
        where
            T: IntoProp<'a>,
        {
            self.array.push(Cow::Borrowed(name));
            self.array.push(Cow::Borrowed(""));  // Will be written just after...
            let len = self.array.len();
            self.array.extend(value.into_prop());
            let count = self.array.len() - len;
            self.array[len - 1] = Cow::Owned(format!("{count}"));  // Actually write count!
            self.count += 1;
        }

        pub fn finalize(mut self) -> Vec<Cow<'a, str>> {
            // Write the number of properties ahead of the array.
            self.array[0] = Cow::Owned(format!("{}", self.count));
            self.array
        }

    }

    /// The counterpart of [`Builder`] for the properties of attributes: every attribute
    /// is its name followed by what a [`Builder`] makes of its properties.
    pub struct AttrBuilder<'a> {
        array: Vec<Cow<'a, str>>,
        count: usize,
    }

    impl<'a> AttrBuilder<'a> {

        pub fn new() -> Self {
            Self {
                array: vec![Cow::Borrowed("")],  // Attributes count is set when finalized.
                count: 0,
            }
        }

        pub fn push<S>(&mut self, attr_name: &'a str, spec: S)
        where
            S: SetPropSpec<'a>,
        {
            let mut builder = Builder::new();
            spec.push_to_builder(&mut builder);
            self.array.push(Cow::Borrowed(attr_name));
            self.array.extend(builder.finalize());
            self.count += 1;
        }

        pub fn finalize(mut self) -> Vec<Cow<'a, str>> {
            self.array[0] = Cow::Owned(format!("{}", self.count));
            self.array
        }

    }

}

/// The properties to write, as name/value pairs, see [`DatabaseProxy::set_dev_prop`].
///
/// **Supporting trait**: it is only there to make this crate's API easier to use, it is
/// implemented for everything that API accepts and is not one to implement anywhere else.
pub trait SetPropSpec<'a>: Sized {
    /// Make this write specification into the params for the set property command.
    fn push_to_builder(self, builder: &mut set_prop::Builder<'a>);
}

/// For a single property.
impl<'a, T> SetPropSpec<'a> for (&'a str, T)
where
    T: IntoProp<'a>,
{

    #[inline]
    fn push_to_builder(self, builder: &mut set_prop::Builder<'a>) {
        builder.push(self.0, self.1);
    }

}

/// For an array of properties.
impl<'a, T, const N: usize> SetPropSpec<'a> for [(&'a str, T); N]
where
    T: IntoProp<'a>,
{

    #[inline]
    fn push_to_builder(self, builder: &mut set_prop::Builder<'a>) {
        for (name, value) in self {
            builder.push(name, value);
        }
    }

}

/// For a vector of properties.
impl<'a, 'aa: 'a, T> SetPropSpec<'a> for Vec<(&'aa str, T)>
where
    T: IntoProp<'a>,
{

    #[inline]
    fn push_to_builder(self, builder: &mut set_prop::Builder<'a>) {
        for (name, value) in self {
            builder.push(name, value);
        }
    }

}

macro_rules! impl_set_prop_spec_tuple {
    ( @name: $comp:ident ) => { &'a str };
    ( $( $comp:ident )* ) => {

        #[allow(non_snake_case, unused_assignments)]
        impl<'a, $($comp,)*> SetPropSpec<'a> for ( $( (impl_set_prop_spec_tuple!(@name: $comp), $comp), )* )
        where
            $(
                $comp: IntoProp<'a>,
            )*
        {

            #[inline]
            fn push_to_builder(self, builder: &mut set_prop::Builder<'a>) {
                let ( $($comp,)* ) = self;
                $(
                    builder.push($comp.0, $comp.1);
                )*
            }

        }

    };
}

impl_set_prop_spec_tuple!(A);
impl_set_prop_spec_tuple!(A B);
impl_set_prop_spec_tuple!(A B C);
impl_set_prop_spec_tuple!(A B C D);
impl_set_prop_spec_tuple!(A B C D E);
impl_set_prop_spec_tuple!(A B C D E F);

// =========================== //
//  Get attribute properties   //
// =========================== //

/// The commands reading the properties of the attributes of one kind of object.
#[derive(Debug, Clone, Copy)]
pub(crate) struct AttrPropCommands {
    /// The command reading the properties of attributes by name.
    get: &'static str,
    /// The command listing the attributes that have any property.
    list: &'static str,
}

impl AttrPropCommands {
    pub(crate) const CLASS: Self = Self { get: "DbGetClassAttributeProperty2", list: "DbGetClassAttributeList" };
    pub(crate) const DEV: Self = Self { get: "DbGetDeviceAttributeProperty2", list: "DbGetDeviceAttributeList" };
}

/// A trait for attribute property specifiers, which allows a great flexibility in how
/// [`DatabaseProxy::get_dev_attr_prop`] works: the attributes are shaped by their names, the
/// way any request on names is, see [`crate::dev::ToNamesSpec`], and the properties of every
/// one of them by the names of the properties, see [`GetPropSpec`], which is what this is
/// implemented on.
///
/// **Supporting trait**: it is only there to make this crate's API easier to use, it is
/// implemented for everything that API accepts and is not one to implement anywhere else.
pub trait GetAttrPropSpec<AttrNames, Names> {

    /// Kind of output type returned.
    type Output;

    /// Build the output out of the attributes, taking them one at a time, and the properties
    /// of every one of them.
    fn collect(attrs: &mut get_prop::AttrPropReply) -> Result<Self::Output>;

}

/// The properties of the next attribute, parsed, the listing not adding up failing the
/// whole output, see [`get_prop::AttrPropReply::next`].
fn next_attr<T: GetPropSpec<Names>, Names>(attrs: &mut get_prop::AttrPropReply) -> Option<Result<NamedResult<T::Output>>> {
    Some(attrs.next()?.map(|attr| attr.map(|mut props| T::collect(&mut props))))
}

/// One attribute: its properties *are* the output, and their failure is the output's own
/// since there is no slot of its own to carry it in.
impl<T: GetPropSpec<Names>, Names> GetAttrPropSpec<&'_ str, Names> for T {

    type Output = T::Output;

    fn collect(attrs: &mut get_prop::AttrPropReply) -> Result<Self::Output> {
        match next_attr::<T, Names>(attrs) {
            Some(attr) => attr?.value,
            None => Err(unexpected_len_err(1)),
        }
    }

}

/// Every attribute of a list, each with the outcome of its own properties.
fn collect_attr_list<T: GetPropSpec<Names>, Names>(attrs: &mut get_prop::AttrPropReply) -> Result<Vec<Result<T::Output>>> {
    let mut outputs = Vec::with_capacity(attrs.len());
    while let Some(attr) = next_attr::<T, Names>(attrs) {
        outputs.push(attr?.value);
    }
    Ok(outputs)
}

impl<T: GetPropSpec<Names>, Names> GetAttrPropSpec<&'_ [&'_ str], Names> for T {
    type Output = Vec<Result<T::Output>>;
    fn collect(attrs: &mut get_prop::AttrPropReply) -> Result<Self::Output> {
        collect_attr_list::<T, Names>(attrs)
    }
}

impl<T: GetPropSpec<Names>, Names> GetAttrPropSpec<Spectrum<str>, Names> for T {
    type Output = Vec<Result<T::Output>>;
    fn collect(attrs: &mut get_prop::AttrPropReply) -> Result<Self::Output> {
        collect_attr_list::<T, Names>(attrs)
    }
}

impl<T: GetPropSpec<Names>, Names> GetAttrPropSpec<&'_ Spectrum<str>, Names> for T {
    type Output = Vec<Result<T::Output>>;
    fn collect(attrs: &mut get_prop::AttrPropReply) -> Result<Self::Output> {
        collect_attr_list::<T, Names>(attrs)
    }
}

impl<T: GetPropSpec<Names>, Names, const N: usize> GetAttrPropSpec<[&'_ str; N], Names> for T {

    type Output = [Result<T::Output>; N];

    fn collect(attrs: &mut get_prop::AttrPropReply) -> Result<Self::Output> {
        // One attribute per slot, a last one behind them being a broken reply as much as one
        // of them missing, see [`crate::dev::take_array`].
        let mut slots = [const { None }; N];
        for slot in &mut slots {
            *slot = Some(next_attr::<T, Names>(attrs).ok_or_else(|| unexpected_len_err(N))??.value);
        }
        if attrs.next().is_some() {
            return Err(unexpected_len_err(N));
        }
        Ok(slots.map(|slot| slot.expect("every slot is filled")))
    }

}

/// Nothing was named here, so every attribute carries its own name.
impl<T: GetPropSpec<Names>, Names> GetAttrPropSpec<All, Names> for T {

    type Output = Vec<NamedResult<T::Output>>;

    fn collect(attrs: &mut get_prop::AttrPropReply) -> Result<Self::Output> {
        let mut outputs = Vec::with_capacity(attrs.len());
        while let Some(attr) = next_attr::<T, Names>(attrs) {
            outputs.push(attr?);
        }
        Ok(outputs)
    }

}

macro_rules! impl_get_attr_prop_spec_tuple {
    ( @one: $index:tt ) => { 1 };
    ( @name: $index:tt ) => { &'name str };
    ( @output: $index:tt ) => { Result<T::Output> };
    ( @next: $index:tt, $attrs:ident ) => { next_attr::<T, Names>($attrs).ok_or_else(|| unexpected_len_err(LEN))??.value };
    ( $( $index:tt )* ) => {

        impl<'name, T: GetPropSpec<Names>, Names> GetAttrPropSpec<( $( impl_get_attr_prop_spec_tuple!(@name: $index), )* ), Names> for T {

            type Output = ( $( impl_get_attr_prop_spec_tuple!(@output: $index), )* );

            fn collect(attrs: &mut get_prop::AttrPropReply) -> Result<Self::Output> {
                const LEN: usize = 0 $( + impl_get_attr_prop_spec_tuple!(@one: $index) )*;
                // The attributes come in the order the names were given, which is the order
                // the components of a tuple are built in.
                let output = ( $( impl_get_attr_prop_spec_tuple!(@next: $index, attrs), )* );
                if attrs.next().is_some() {
                    return Err(unexpected_len_err(LEN));
                }
                Ok(output)
            }

        }

    };
}

impl_get_attr_prop_spec_tuple!(0);
impl_get_attr_prop_spec_tuple!(0 1);
impl_get_attr_prop_spec_tuple!(0 1 2);
impl_get_attr_prop_spec_tuple!(0 1 2 3);
impl_get_attr_prop_spec_tuple!(0 1 2 3 4);
impl_get_attr_prop_spec_tuple!(0 1 2 3 4 5);

// =========================== //
//  Set attribute properties   //
// =========================== //

/// An abstract specification of the properties to write of one to many attributes, every
/// attribute being given what [`SetPropSpec`] takes for the properties of an object, see
/// [`DatabaseProxy::set_dev_attr_prop`].
///
/// **Supporting trait**: it is only there to make this crate's API easier to use, it is
/// implemented for everything that API accepts and is not one to implement anywhere else.
pub trait SetAttrPropSpec<'a>: Sized {
    /// Make this write specification into the params for the set property command.
    fn push_to_builder(self, builder: &mut set_prop::AttrBuilder<'a>);
}

/// For the properties of a single attribute.
impl<'a, S> SetAttrPropSpec<'a> for (&'a str, S)
where
    S: SetPropSpec<'a>,
{

    #[inline]
    fn push_to_builder(self, builder: &mut set_prop::AttrBuilder<'a>) {
        builder.push(self.0, self.1);
    }

}

/// For an array of attributes.
impl<'a, S, const N: usize> SetAttrPropSpec<'a> for [(&'a str, S); N]
where
    S: SetPropSpec<'a>,
{

    #[inline]
    fn push_to_builder(self, builder: &mut set_prop::AttrBuilder<'a>) {
        for (attr_name, spec) in self {
            builder.push(attr_name, spec);
        }
    }

}

/// For a vector of attributes.
impl<'a, S> SetAttrPropSpec<'a> for Vec<(&'a str, S)>
where
    S: SetPropSpec<'a>,
{

    #[inline]
    fn push_to_builder(self, builder: &mut set_prop::AttrBuilder<'a>) {
        for (attr_name, spec) in self {
            builder.push(attr_name, spec);
        }
    }

}

/// The parameters of an attribute property write, the object first.
fn attr_prop_params<'a, Spec: SetAttrPropSpec<'a>>(obj_name: &str, spec: Spec) -> Spectrum<str> {
    let mut builder = set_prop::AttrBuilder::new();
    spec.push_to_builder(&mut builder);
    prop_params(obj_name, builder.finalize().iter().map(|param| &**param))
}

#[cfg(test)]
mod tests {

    use futures::future::BoxFuture;

    use super::*;

    /// The attribute property reads, awaited within a future boxed as `Send`, which is what
    /// an asynchronous handler is: this only has to compile.
    #[allow(dead_code)]
    fn attr_props_in_send_future(db: &DatabaseProxy) -> BoxFuture<'_, Result<()>> {
        Box::pin(async move {
            let _ = db.get_dev_attr_prop_async::<f64, _, _>("motor/dev/1", "Position", "max_value").await?;
            let _ = db.get_class_attr_prop_async::<(String, f64), _, _>("Motor", ["Position"], ("label", "max_value")).await?;
            let _ = db.get_dev_attr_prop_async::<Spectrum<str>, _, _>("motor/dev/1", All, All).await?;
            Ok(())
        })
    }

    /// The reply to a property request that was asked for the given names and answered
    /// with the given listing, which is the flat list the database speaks in: the object,
    /// how many properties follow, and then every property as its name, how many values it
    /// holds, and those values.
    fn reply(names: &[&str], listing: &[&str]) -> get_prop::PropReply {
        get_prop::PropReply::new(listing[0], Spectrum::from(listing), Spectrum::from(names)).unwrap()
    }

    /// The reply to an attribute property request that was asked for the given attributes
    /// and properties, and answered with the given listing, the flat list the database
    /// speaks in.
    fn attr_reply(attr_names: &[&str], prop_names: Option<&[&str]>, listing: &[&str]) -> get_prop::AttrPropReply {
        get_prop::AttrPropReply::new(listing[0], Spectrum::from(listing), Spectrum::from(attr_names), prop_names.map(Spectrum::from)).unwrap()
    }

    /// The database answering for another object than the one asked about, or with another
    /// count than what was asked for, fails the whole reply before anything is read out of
    /// it, and a request that asks for nothing carries nothing.
    #[test]
    fn listing_head() {

        let names = || Spectrum::from(&["prop"][..]);

        let err = get_prop::PropReply::new("obj", Spectrum::from(&["another", "1", "prop", "0"][..]), names()).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);
        let err = get_prop::PropReply::new("obj", Spectrum::from(&["obj", "2", "prop", "0"][..]), names()).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);
        let err = get_prop::AttrPropReply::new("obj", Spectrum::from(&["obj", "2", "prop", "0"][..]), names(), None).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);

        let mut props = get_prop::PropReply::empty();
        assert!(props.is_empty());
        assert!(props.next().is_none());
        let mut attrs = get_prop::AttrPropReply::empty();
        assert_eq!(attrs.len(), 0);
        assert!(attrs.next().is_none());

    }

    /// The properties of an attribute, as they are taken out of its reply.
    fn attr_props(props: &mut get_prop::PropReply) -> Vec<(String, Vec<String>)> {
        let mut taken = Vec::new();
        while let Some(prop) = props.next() {
            let prop = prop.unwrap();
            taken.push((prop.name.value().to_string(), prop.value.iter().map(str::to_string).collect()));
        }
        taken
    }

    const ATTR_LISTING: &[&str] = &[
        "sys/tg_test/1", "3",
        "first", "2", "label", "1", "First", "rel_change", "2", "-1", "2",
        "empty", "1", "unit", "0", " ",
        "none", "0",
    ];

    /// The attributes come back one entry per attribute asked for, in the order they were,
    /// an attribute the database holds nothing of included, every one with every property
    /// it has when none is asked for in particular, and a property holding no value
    /// followed by a placeholder that is not one of its values.
    #[test]
    fn attr_props_in_order() {

        let mut reply = attr_reply(&["first", "empty", "none"], None, ATTR_LISTING);
        assert_eq!(reply.len(), 3);

        let Named { name, value: mut props } = reply.next().unwrap().unwrap();
        assert_eq!(name.value(), "first");
        assert_eq!(props.len(), 2);
        assert_eq!(attr_props(&mut props), [
            ("label".to_string(), vec!["First".to_string()]),
            ("rel_change".to_string(), vec!["-1".to_string(), "2".to_string()]),
        ]);

        let mut props = reply.next().unwrap().unwrap().value;
        assert_eq!(attr_props(&mut props), [("unit".to_string(), vec![])]);

        let mut props = reply.next().unwrap().unwrap().value;
        assert!(attr_props(&mut props).is_empty());

        assert!(reply.next().is_none());

    }

    /// The properties asked for are looked up among every one an attribute has ignoring the
    /// case, in the order they were asked for, one it does not have coming with no value.
    #[test]
    fn attr_prop_lookup() {

        let mut reply = attr_reply(&["first", "empty", "none"], Some(&["REL_CHANGE", "unit"]), ATTR_LISTING);

        let mut props = reply.next().unwrap().unwrap().value;
        assert_eq!(props.len(), 2);
        assert_eq!(attr_props(&mut props), [
            ("rel_change".to_string(), vec!["-1".to_string(), "2".to_string()]),
            ("unit".to_string(), vec![]),
        ]);

        let mut props = reply.next().unwrap().unwrap().value;
        assert_eq!(attr_props(&mut props), [
            ("REL_CHANGE".to_string(), vec![]),
            ("unit".to_string(), vec![]),
        ]);

    }

    /// The database naming back another attribute than the one asked for fails that
    /// attribute, as does one announcing more values than it carries, and nothing is read
    /// behind either, an attribute starting where the one before it ended.
    #[test]
    fn incoherent_attr_props() {

        let mut reply = attr_reply(&["asked", "behind"], None, &["obj", "2", "another", "0", "behind", "0"]);
        assert_eq!(reply.next().unwrap().unwrap_err().kind(), ErrorKind::InvalidData);
        assert!(reply.next().is_none());

        let mut reply = attr_reply(&["asked"], None, &["obj", "1", "asked", "1", "label", "2", "one"]);
        assert_eq!(reply.next().unwrap().unwrap_err().kind(), ErrorKind::InvalidData);

    }

    /// What an attribute property write carries: the object, how many attributes, then
    /// every attribute with how many properties it has, and every property with how many
    /// values it has and those values.
    #[test]
    fn attr_prop_write() {
        let params = attr_prop_params("obj", [
            ("first", vec![("label", "First"), ("unit", "mm")]),
            ("second", vec![("label", "Second")]),
        ]);
        assert_eq!(params.iter().collect::<Vec<_>>(), [
            "obj", "2",
            "first", "2", "label", "1", "First", "unit", "1", "mm",
            "second", "1", "label", "1", "Second",
        ]);
    }

    /// The properties come back in the order they were asked for, each with the values it
    /// holds and nothing of the ones around it.
    #[test]
    fn props_in_order() {

        let mut props = reply(&["first", "second"],
            &["sys/tg_test/1", "2", "first", "1", "one", "second", "2", "two", "three"]);

        assert_eq!(props.len(), 2);

        let Named { name, value: values } = props.next().unwrap().unwrap();
        assert_eq!(name.value(), "first");
        assert_eq!(values.iter().collect::<Vec<_>>(), ["one"]);

        let Named { name, value: values } = props.next().unwrap().unwrap();
        assert_eq!(name.value(), "second");
        assert_eq!(values.iter().collect::<Vec<_>>(), ["two", "three"]);

        assert!(props.next().is_none());

    }

    /// A property that is defined and holds nothing comes back with no value at all, which
    /// is not the same as it not being there.
    #[test]
    fn prop_without_value() {
        let mut props = reply(&["empty"], &["obj", "1", "empty", "0"]);
        let Named { name, value: values } = props.next().unwrap().unwrap();
        assert_eq!(name.value(), "empty");
        assert!(values.is_empty());
    }

    /// The database naming another property back than the one that was asked for is it
    /// breaking the order the answer is read in, which that one property fails with.
    #[test]
    fn incoherent_prop_name() {
        let mut props = reply(&["asked"], &["obj", "1", "another", "1", "one"]);
        let err = props.next().unwrap().unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);
    }

    /// A property announcing more values than the listing carries fails: the values are a
    /// slice of the listing and there is nothing there to slice.
    ///
    /// Nothing is read behind it either, a property starting where the one before it ended.
    #[test]
    fn missing_prop_values() {
        let mut props = reply(&["prop", "behind"], &["obj", "2", "prop", "2", "one"]);
        let err = props.next().unwrap().unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);
        assert!(props.next().is_none());
    }

    /// One name asks for one property, which is parsed into the type the caller expects of
    /// it and is the output itself.
    #[test]
    fn single_prop_parsed() {
        let mut props = reply(&["prop"], &["obj", "1", "prop", "1", "3.5"]);
        let value = <f64 as GetPropSpec<&str>>::collect(&mut props).unwrap();
        assert_eq!(value, 3.5);
    }

}