zenkey-model 0.24.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
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
//! The zk2c envelope (core §7.5, 0.72; #976, epic #975): the bytes that
//! carry an owner's run and sequence number with a sample, before its
//! record, and a call's forms of the same shape (core 0.92, #980's C4a).
//!
//! ```text
//! mutation, a put's payload        CH · run · seq · record
//! delete, a delete's attachment    CH · run · seq
//! event, a put's payload           CH · t32 · ms16 · record     (core 0.101, #980's C2a)
//! heartbeat, a put's payload       CH · run · seq · body        (core 0.81, #978's F1)
//! owner heartbeat, a put's payload CH · run · seq · body        (core 0.108, #1110's H1)
//! frame, a put's payload           CH · run · seq · body        (core 0.83, #981's K1)
//! snapshot, a GET reply's payload  CH · run · asof · body       (core 0.97, #977's E1)
//! held stamp, a state GET's payload and its reply's
//!                                  CH · run · seq               (core 0.110, #986's J1)
//! request, a query's payload       CH · record                  (core 0.92, C4a)
//! value, a reply's payload         CH · run · seq · record      (core 0.92, C4a)
//! error, a reply error's payload   CH · run · seq · error       (core 0.92, C4a)
//! CH                               form (bits 7–5) · run width (bit 4) · tag (bits 3–0)
//! run                              16 or 32 bits unsigned, big-endian, as CH's width bit says
//! seq                              24 bits unsigned, big-endian
//! record                           every byte after the seq, read as the resource's type says
//! ```
//!
//! **Adopted by core §4.3** (0.73, #976's flip): an owner writes the
//! envelope on every put of a `stream`, `state`, `@state` or `events` key
//! and every delete of a state member, an `@stream` sample's excepted. What
//! a run names and how a seq counts are §4.3's, and the order of two
//! in-band stamps [`crate::seed`]'s; this module fixes the bytes, a
//! descriptor's spelling of a run ([`Run::hex`]), and which samples carry
//! an envelope.
//!
//! **A call's forms** (core 0.92 §7.5, adopted by core 0.94, #985's C4c,
//! the only wire of a call since core 0.99's C4d): a request ([`Request`],
//! [`read_query`]), a value ([`Envelope::value`], [`read_reply`],
//! [`read_value`]) and an error ([`crate::envelope::ErrorForm`],
//! [`read_reply_err`]). A value's and an error's stamp is the replying
//! instance's as-of mark (§5.1); a request carries none. Each travels under
//! `zenoh/bytes` ([`ENCODING`]), and under any other `Encoding` a call's
//! sample carries no form.
//!
//! **Parsing reads no contract,** as parsing a key does (§1.1): it knows
//! the sample ([`SampleKind`]) and nothing more: a put ([`Envelope::parse`]),
//! a delete ([`DeleteStamp::parse`]), or a call's query, reply or reply
//! error. So the tag of every form but a delete is reported, never checked
//! against a type; `packed` (#979) is the first type kind to define one. A
//! put carries a mutation, a heartbeat, a frame or a snapshot
//! ([`Envelope::form`]); a heartbeat's body is read with its covered
//! revision ([`crate::heartbeat`]), its tag that revision's (an owner
//! heartbeat is form 6 too, its tag 0 and its body
//! [`crate::heartbeat::OwnerHeartbeat::parse`]'s: the key says which of
//! the two a put carries, never the bytes), and a frame's
//! with its declaration ([`crate::frame`]), its tag that declaration's. A
//! snapshot's body (core 0.97, #977's E1) is taken unread, its asof in the
//! seq's place, and read by [`crate::collection`], its tag its
//! collection's type's. An event (core 0.101, #980's C2a) carries its
//! time where the stamp would be, and its stamp is its key's occurrence
//! chunk ([`crate::chunk::occurrence`]): [`Event`], which [`read_event`]
//! and [`read_put`] read with the key, `key_stamp` and `time` among their
//! refusals; read without one ([`Envelope::parse`]) it is `key_stamp`. [`read_put`] refuses a frame on a key whose kind
//! token is not `stream`, and a snapshot on one that is neither `state`
//! nor `@state` (`key_kind`), which [`Envelope::parse_on`] reads. Only a
//! GET's reply carries a snapshot, but the parser cannot tell how a put
//! came, so it reads one either way. An error's detail is taken unread.
//! The first refusal that applies is reported, in §7.5's order, with the
//! token `spec/conformance/envelope/` pins ([`Refusal::token`]). Every
//! envelope and form accepted writes back to its bytes.
//!
//! **A held stamp** (core 0.110 §7.5, #986's J1; adopted by no profile
//! until `desired.v2`): a snapshot's header with no body, form 7 with tag
//! 0, which names one mutation of one state member. A reader sends it on a
//! state GET ([`read_get`], a fourth sample, [`SampleKind::Get`]) and an
//! owner whose member is unchanged sends it back as that GET's reply
//! ([`read_get_reply`], which tells it from a page by its length alone).
//! [`Envelope::parse`] and [`read_put`] are unchanged: they cannot tell how
//! a put came, and read the same bytes as a snapshot's envelope with no
//! body. Who sends one and what each concludes is core §4.2's
//! ([`crate::seed::Asked`]).
//!
//! Not the error envelope of an earlier core's call (§5.2 before 0.99),
//! which travelled with no form and which nothing here reads.
//!
//! **Reading** (observer §7.3, "the envelope first"): a reader tells a
//! sample that carries an envelope by its key and its Encoding alone
//! ([`carries`]), reads a put's payload through [`read_put`] and a
//! delete's attachment through [`read_delete`], and reads every other
//! sample as one with no envelope: an `@stream` sample, a foreign key's
//! (§1.7), or one whose owner broke §4.3. The order of two in-band stamps
//! is [`crate::seed`]'s, by the key's kind ([`enveloped_kind`]), and a
//! sample with no envelope is ordered by its Zenoh timestamp (core §4.2).

use thiserror::Error;

use crate::envelope::{Cause, Code, ErrorForm, FormRefusal};
use crate::grammar::{KindToken, ZkKey, parse};

/// A form: CH's three high bits. This version defines all eight: a
/// mutation, a delete, a value, an error, an event (core 0.101), a frame,
/// a heartbeat and a snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Form {
    /// Code 0: a put's run and seq, then its record.
    Mutation,
    /// Code 1: a delete's run and seq, as its attachment, and no record.
    Delete,
    /// Code 2: a call's request, as its query's payload, with no stamp;
    /// and a reply's run and seq, then its record (core 0.92).
    Value,
    /// Code 3: a reply error's run and seq, then §5.2's error in bytes
    /// (core 0.92, [`crate::envelope::ErrorForm`]).
    Error,
    /// Code 4: an event's occurrence, a put's payload on an `events` key,
    /// its time then its record, its stamp its key's (core 0.101, #980's
    /// C2a, [`Event`]).
    Event,
    /// Code 5: a stream's records under one header, a put's payload on a
    /// plain stream's key (core 0.83 §7.7, [`crate::frame`]).
    Frame,
    /// Code 6: an owner's confirmation of the state it holds for one
    /// interface, a put's payload (core 0.81, [`crate::heartbeat`]), or,
    /// on an owner heartbeat's key, for several (core 0.108,
    /// [`crate::heartbeat::OwnerHeartbeat`]).
    Heartbeat,
    /// Code 7: a collection's state, a GET reply's payload, in pages
    /// (core 0.97, [`crate::collection`]).
    Snapshot,
}

impl Form {
    /// Every form, in code order.
    pub const ALL: [Form; 8] = [
        Form::Mutation,
        Form::Delete,
        Form::Value,
        Form::Error,
        Form::Event,
        Form::Frame,
        Form::Heartbeat,
        Form::Snapshot,
    ];

    /// The form's code, from 0 to 7.
    #[must_use]
    pub const fn code(self) -> u8 {
        match self {
            Form::Mutation => 0,
            Form::Delete => 1,
            Form::Value => 2,
            Form::Error => 3,
            Form::Event => 4,
            Form::Frame => 5,
            Form::Heartbeat => 6,
            Form::Snapshot => 7,
        }
    }

    /// The form of a code, `None` above 7.
    #[must_use]
    pub const fn from_code(code: u8) -> Option<Form> {
        if code < 8 {
            Some(Form::ALL[code as usize])
        } else {
            None
        }
    }

    /// Whether this version defines the form; a reserved one is refused.
    /// Every form is defined since core 0.101, so none is: the check stays
    /// for a later version's.
    #[must_use]
    pub const fn is_defined(self) -> bool {
        true
    }

    /// The form's name, as §7.5's table and the fixtures spell it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Form::Mutation => "mutation",
            Form::Delete => "delete",
            Form::Value => "value",
            Form::Error => "error",
            Form::Event => "event",
            Form::Frame => "frame",
            Form::Heartbeat => "heartbeat",
            Form::Snapshot => "snapshot",
        }
    }
}

impl std::fmt::Display for Form {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// What carries an envelope or a form, its **sample** (core §7.5): the
/// parser knows it, and nothing more.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SampleKind {
    /// A put's payload, or the payload of a GET's reply that represents a
    /// put (S2) or carries a snapshot: a mutation, a heartbeat, a frame or
    /// a snapshot.
    Put,
    /// A delete's attachment, or a `reply_del`'s (S2): a delete.
    Delete,
    /// A call's query, its payload: a value with no stamp, a request.
    Query,
    /// A call's reply, its payload: a value. Never a GET's reply that
    /// represents a put, which is a [`SampleKind::Put`].
    Reply,
    /// A call's `reply_err`, its payload: an error.
    ReplyErr,
    /// A state GET's query, its payload (core 0.110): a held stamp, form
    /// 7 with no body ([`HeldStamp::parse`]). Never a call's query, which
    /// is a [`SampleKind::Query`].
    Get,
}

impl SampleKind {
    /// Every sample, in §7.5's order: a put, a delete and a call's three,
    /// then a state GET's payload, which core 0.110 added. A loop over it
    /// meets [`SampleKind::Get`], which carries a snapshot's form alone, as
    /// a held stamp, and is parsed by [`HeldStamp::parse`], never by
    /// [`Envelope::parse`] or a call's readers.
    pub const ALL: [SampleKind; 6] = [
        SampleKind::Put,
        SampleKind::Delete,
        SampleKind::Query,
        SampleKind::Reply,
        SampleKind::ReplyErr,
        SampleKind::Get,
    ];

    /// `put`, `delete`, `query`, `reply` or `reply_err`, as the fixtures
    /// spell it, and `get` for a state GET's payload.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            SampleKind::Put => "put",
            SampleKind::Delete => "delete",
            SampleKind::Query => "query",
            SampleKind::Reply => "reply",
            SampleKind::ReplyErr => "reply_err",
            SampleKind::Get => "get",
        }
    }

    /// Whether the sample carries the form: a put a mutation, an event, a
    /// heartbeat, a frame or a snapshot, a delete's attachment a delete, a
    /// query and a reply a value, a `reply_err` an error, and a state GET
    /// a snapshot's form, as a held stamp. No sample carries a reserved
    /// one.
    #[must_use]
    pub const fn carries(self, form: Form) -> bool {
        match self {
            SampleKind::Put => matches!(
                form,
                Form::Mutation | Form::Event | Form::Frame | Form::Heartbeat | Form::Snapshot
            ),
            SampleKind::Delete => matches!(form, Form::Delete),
            SampleKind::Query | SampleKind::Reply => matches!(form, Form::Value),
            SampleKind::ReplyErr => matches!(form, Form::Error),
            SampleKind::Get => matches!(form, Form::Snapshot),
        }
    }
}

impl std::fmt::Display for SampleKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// CH's four low bits: 0 unless the record's type kind defines a tag. A
/// value from 0 to 15, by construction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Tag(u8);

impl Tag {
    /// Tag 0: every record whose type kind defines no tag, and every delete.
    pub const NONE: Tag = Tag(0);

    /// A tag, `None` above 15.
    #[must_use]
    pub const fn new(value: u8) -> Option<Tag> {
        if value <= 0x0f {
            Some(Tag(value))
        } else {
            None
        }
    }

    /// The tag's value, from 0 to 15.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// CH, the header byte, read as its three fields. Every byte reads as a
/// header, a reserved form's included, and writes back to itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Header {
    /// Bits 7–5.
    pub form: Form,
    /// Bit 4: a 32-bit run when set, a 16-bit run when clear.
    pub wide: bool,
    /// Bits 3–0.
    pub tag: Tag,
}

impl Header {
    /// CH's fields: the form's code × 32, plus the width bit × 16, plus the
    /// tag. `0x1b` is `000 1 1011`: a mutation, a 32-bit run, tag 11.
    #[must_use]
    pub const fn from_byte(ch: u8) -> Header {
        Header {
            form: Form::ALL[(ch >> 5) as usize],
            wide: ch & 0x10 != 0,
            tag: Tag(ch & 0x0f),
        }
    }

    /// The byte.
    #[must_use]
    pub const fn byte(self) -> u8 {
        (self.form.code() << 5) | ((self.wide as u8) << 4) | self.tag.0
    }
}

/// A run: 16 or 32 bits unsigned, written big-endian, as CH's width bit
/// says. An instance's ordering epoch (core §4.3): a 16-bit run is a
/// counter in the owner's record, a 32-bit run a random draw. Two runs of
/// different widths are two runs, whatever their values, and nothing
/// orders two runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Run {
    U16(u16),
    U32(u32),
}

impl std::fmt::Display for Run {
    /// Its descriptor spelling ([`Run::hex`]).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Run::U16(v) => write!(f, "{v:04x}"),
            Run::U32(v) => write!(f, "{v:08x}"),
        }
    }
}

impl Run {
    /// Whether CH's width bit is set for this run.
    #[must_use]
    pub const fn is_wide(self) -> bool {
        matches!(self, Run::U32(_))
    }

    /// The run's value.
    #[must_use]
    pub const fn value(self) -> u32 {
        match self {
            Run::U16(v) => v as u32,
            Run::U32(v) => v,
        }
    }

    /// Its bytes on the wire: 2 or 4.
    #[must_use]
    pub const fn width_bytes(self) -> usize {
        if self.is_wide() { 4 } else { 2 }
    }

    /// The run as a descriptor states it (core §3.3): its bytes in
    /// lowercase hexadecimal, 4 digits for a 16-bit run and 8 for a 32-bit
    /// one. So `00a1` and `000000a1` are two runs.
    #[must_use]
    pub fn hex(self) -> String {
        self.to_string()
    }

    /// A descriptor's `run` read back: exactly 4 or 8 lowercase hex
    /// digits, the width from their count. `None` for any other spelling,
    /// which a descriptor checker reports as D002.
    #[must_use]
    pub fn from_hex(text: &str) -> Option<Run> {
        let lower_hex = text
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
        if !lower_hex {
            return None;
        }
        match text.len() {
            4 => u16::from_str_radix(text, 16).ok().map(Run::U16),
            8 => u32::from_str_radix(text, 16).ok().map(Run::U32),
            _ => None,
        }
    }
}

/// A seq: 24 bits unsigned, written big-endian. A value from 0 to
/// 16,777,215, by construction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Seq(u32);

impl Seq {
    /// 16,777,215, the greatest seq.
    pub const MAX: Seq = Seq(0x00ff_ffff);

    /// A seq, `None` above [`Seq::MAX`].
    #[must_use]
    pub const fn new(value: u32) -> Option<Seq> {
        if value <= Seq::MAX.0 {
            Some(Seq(value))
        } else {
            None
        }
    }

    /// The seq's value.
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0
    }
}

/// An envelope's stamp, the sample's in-band stamp (core §4.3): its run
/// and its seq, which order a key's values within one run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Stamp {
    pub run: Run,
    pub seq: Seq,
}

impl Stamp {
    /// CH and the stamp: 6 bytes with a 16-bit run, 8 with a 32-bit one.
    #[must_use]
    pub const fn envelope_bytes(self) -> usize {
        1 + self.run.width_bytes() + 3
    }

    pub(crate) fn write_to(self, out: &mut Vec<u8>) {
        match self.run {
            Run::U16(v) => out.extend_from_slice(&v.to_be_bytes()),
            Run::U32(v) => out.extend_from_slice(&v.to_be_bytes()),
        }
        out.extend_from_slice(&self.seq.0.to_be_bytes()[1..]);
    }
}

/// Why bytes are not an envelope or a form of their sample. The variants
/// are in §7.5's order, which is the order they are found in: CH's checks,
/// the stamp, a delete's end, then an error's byte and what follows it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum Refusal {
    /// No byte at all, so no CH.
    #[error("no byte, so no header byte")]
    Empty,
    /// A form this version reserves: an event.
    #[error("the form {0} is reserved")]
    Reserved(Form),
    /// A form the sample does not carry ([`SampleKind::carries`]).
    #[error("the form {form} on a {sample}, which does not carry it")]
    WrongSample { form: Form, sample: SampleKind },
    /// A frame on a key whose kind token is not `stream` (core 0.83), or a
    /// snapshot on one that is neither `state` nor `@state` (core 0.97).
    #[error("a {form} on a {kind} key, which does not carry it")]
    KeyKind { form: Form, kind: KindToken },
    /// A delete whose tag is not 0.
    #[error("a delete's tag is {}, not 0", .0.get())]
    DeleteTag(Tag),
    /// A held stamp whose tag is not 0 (core 0.110): on a state GET, or on
    /// a GET's reply that is a snapshot's envelope with no byte after its
    /// seq.
    #[error("a held stamp's tag is {}, not 0", .0.get())]
    HeldTag(Tag),
    /// A request whose width bit is 1: a request carries no run (core
    /// 0.92).
    #[error("a request's width bit is 1, and a request carries no run")]
    RequestRun,
    /// An event whose key's last chunk is not an occurrence chunk of CH's
    /// width (core 0.101): the other width's, any other chunk, or no key at
    /// all.
    #[error("an event's key ends in no occurrence chunk of a {} run", if *.wide { "32-bit" } else { "16-bit" })]
    KeyStamp { wide: bool },
    /// Fewer bytes than CH, the run and the seq need, and an error's byte
    /// after them.
    #[error("{have} bytes, short of the {need} that the header, the stamp and what follows need")]
    Short { need: usize, have: usize },
    /// Bytes after a delete's seq, or after an error that ends with its
    /// message or its byte, where no detail follows.
    #[error("{0} bytes after the form's end")]
    Trailing(usize),
    /// An error's cause on a code other than `unavailable`, or none on
    /// `unavailable` (core 0.92).
    #[error("{}", cause_text(*.code, *.cause))]
    Cause { code: Code, cause: Option<Cause> },
    /// An error's detail on a code other than `app`.
    #[error("a detail on {0}, where only app carries one")]
    Detail(Code),
    /// An error's extension bit set, which this version leaves 0.
    #[error("the error's extension bit is set")]
    Extension,
    /// An error's message cut short: no length byte, or fewer bytes than
    /// it states.
    #[error("a message of {need} bytes, {have} given")]
    MessageShort { need: usize, have: usize },
    /// An error's message that is not UTF-8, as RFC 3629 defines it.
    #[error("the message is not UTF-8")]
    Utf8,
    /// An event's time with an unused code (core 0.101): an ms16 above
    /// 999, or any but 0 under a t32 of all ones.
    #[error("the event's time is an unused code")]
    Time,
    /// A held stamp that is no owner's answer to its reader (core 0.110
    /// §4.2, "A held stamp in answer"): one that differs from the stamp
    /// its GET carried, one in reply to a GET that carried none, one on
    /// another key, or one heard on a subscription. Its bytes parse (§7.5);
    /// it establishes nothing, merges nothing, and is counted undecodable.
    /// Not a refusal of §7.5's parse: the reader's, which knows what it
    /// asked ([`crate::seed::Asked::read`]).
    #[error(
        "a held stamp (run {}, seq {}), not in answer to a GET of this reader's that carried it",
        .0.run,
        .0.seq.get()
    )]
    Held(Stamp),
}

fn cause_text(code: Code, cause: Option<Cause>) -> String {
    match cause {
        None => format!("{code} without a cause"),
        Some(c) => format!("a cause, {c}, on {code}"),
    }
}

impl Refusal {
    /// The reason token `spec/conformance/envelope/vectors.json`,
    /// `carries.json` and `spec/conformance/errors/forms.json` pin:
    /// `short`, `form`, `sample_kind`, `key_kind`, `tag`, `request_run`,
    /// `key_stamp`, `trailing`, `time`, `cause`, `detail`, `extension` or
    /// `utf8`; and `held`, `seed/held.json`'s, for a held stamp that is no
    /// answer.
    #[must_use]
    pub const fn token(&self) -> &'static str {
        match self {
            Refusal::Empty | Refusal::Short { .. } | Refusal::MessageShort { .. } => "short",
            Refusal::Reserved(_) => "form",
            Refusal::WrongSample { .. } => "sample_kind",
            Refusal::KeyKind { .. } => "key_kind",
            Refusal::DeleteTag(_) | Refusal::HeldTag(_) => "tag",
            Refusal::Held(_) => "held",
            Refusal::RequestRun => "request_run",
            Refusal::KeyStamp { .. } => "key_stamp",
            Refusal::Time => "time",
            Refusal::Trailing(_) => "trailing",
            Refusal::Cause { .. } => "cause",
            Refusal::Detail(_) => "detail",
            Refusal::Extension => "extension",
            Refusal::Utf8 => "utf8",
        }
    }
}

/// §7.5's checks on CH, in its order: CH itself, its form, the sample, a
/// frame's or a snapshot's key kind (when `kind` is known), a delete's tag,
/// a held stamp's on a state GET, and a request's width bit. Returns CH and
/// every byte after it.
fn read_header(
    bytes: &[u8],
    sample: SampleKind,
    kind: Option<KindToken>,
) -> Result<(Header, &[u8]), Refusal> {
    let (&ch, rest) = bytes.split_first().ok_or(Refusal::Empty)?;
    let header = Header::from_byte(ch);
    if !header.form.is_defined() {
        return Err(Refusal::Reserved(header.form));
    }
    if !sample.carries(header.form) {
        return Err(Refusal::WrongSample {
            form: header.form,
            sample,
        });
    }
    if let Some(k) = kind
        && !key_carries(header.form, k)
    {
        return Err(Refusal::KeyKind {
            form: header.form,
            kind: k,
        });
    }
    if header.form == Form::Delete && header.tag != Tag::NONE {
        return Err(Refusal::DeleteTag(header.tag));
    }
    if sample == SampleKind::Get && header.tag != Tag::NONE {
        return Err(Refusal::HeldTag(header.tag));
    }
    if sample == SampleKind::Query && header.wide {
        return Err(Refusal::RequestRun);
    }
    Ok((header, rest))
}

/// Whether a key of the kind `kind` carries the form, by its kind alone: a
/// frame only a `stream` key, an event only an `events` key, a snapshot
/// only a `state` or `@state` key, and every other form any key (core
/// §7.5's `key_kind`).
const fn key_carries(form: Form, kind: KindToken) -> bool {
    match form {
        Form::Frame => matches!(kind, KindToken::Stream),
        Form::Event => matches!(kind, KindToken::Events),
        Form::Snapshot => matches!(kind, KindToken::State | KindToken::ExplicitState),
        _ => true,
    }
}

/// §7.5's parse of a form with a stamp, in its order: CH's checks
/// ([`read_header`]), then the stamp, and an error's byte after it.
/// Returns CH, the stamp and every byte after it.
fn read(
    bytes: &[u8],
    sample: SampleKind,
    kind: Option<KindToken>,
) -> Result<(Header, Stamp, &[u8]), Refusal> {
    let (header, rest) = read_header(bytes, sample, kind)?;
    let run_bytes = if header.wide { 4 } else { 2 };
    let need = 1 + run_bytes + 3 + usize::from(header.form == Form::Error);
    if bytes.len() < need {
        return Err(Refusal::Short {
            need,
            have: bytes.len(),
        });
    }
    let (run, rest) = rest.split_at(run_bytes);
    let run = match *run {
        [a, b] => Run::U16(u16::from_be_bytes([a, b])),
        [a, b, c, d] => Run::U32(u32::from_be_bytes([a, b, c, d])),
        _ => unreachable!("a run is 2 or 4 bytes"),
    };
    let (seq, rest) = rest.split_at(3);
    let seq = Seq(u32::from_be_bytes([0, seq[0], seq[1], seq[2]]));
    Ok((header, Stamp { run, seq }, rest))
}

/// A put's payload under the envelope, or a call's reply in its value
/// form. This version defines four forms for a put: the mutation,
/// `CH · run · seq · record`, the frame, `CH · run · seq · body` (core
/// 0.83), the heartbeat, `CH · run · seq · body` (core 0.81), and the
/// snapshot, `CH · run · asof · body` (core 0.97), a GET reply's. A reply's
/// value has a mutation's shape, `CH · run · seq · record` (core 0.92).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Envelope<'a> {
    /// [`Form::Mutation`], [`Form::Frame`], [`Form::Heartbeat`] or
    /// [`Form::Snapshot`] on a put, [`Form::Value`] on a reply.
    pub form: Form,
    /// A mutation's: 0 unless the record's type kind defines a tag. A
    /// frame's: its declaration's ([`crate::frame::Layout::tag`]). A
    /// heartbeat's: its covered revision's, and 0 for an owner
    /// heartbeat, whose groups each carry one. A snapshot's: its collection's
    /// type's. A value's: its operation's `response` type's, or its
    /// `summary` type's on a summary reply.
    pub tag: Tag,
    /// A value's is the replying instance's as-of mark (core §5.1). A
    /// snapshot's is the owner's run and its asof, in the seq's place.
    pub stamp: Stamp,
    /// Every byte after the seq, possibly none: a mutation's or a value's
    /// record, read as the resource's type says (§7.1), or a frame's, a
    /// heartbeat's or a snapshot's body, a snapshot's unread
    /// ([`crate::collection::Page::read`] reads it).
    pub record: &'a [u8],
}

impl<'a> Envelope<'a> {
    /// A mutation: a put's record under its stamp.
    #[must_use]
    pub const fn mutation(tag: Tag, stamp: Stamp, record: &'a [u8]) -> Envelope<'a> {
        Envelope {
            form: Form::Mutation,
            tag,
            stamp,
            record,
        }
    }

    /// A value: a call's reply, its record under the replying instance's
    /// as-of mark (core 0.92 §5.1, §7.5).
    #[must_use]
    pub const fn value(tag: Tag, stamp: Stamp, record: &'a [u8]) -> Envelope<'a> {
        Envelope {
            form: Form::Value,
            tag,
            stamp,
            record,
        }
    }

    /// A frame: a body under the stamp of its record 0 (core §7.7).
    #[must_use]
    pub const fn frame(tag: Tag, stamp: Stamp, body: &'a [u8]) -> Envelope<'a> {
        Envelope {
            form: Form::Frame,
            tag,
            stamp,
            record: body,
        }
    }

    /// A snapshot's page: its body under the owner's run and its asof, in
    /// the seq's place (core 0.97 §7.5, [`crate::collection`]).
    #[must_use]
    pub const fn snapshot(tag: Tag, run: Run, asof: Seq, body: &'a [u8]) -> Envelope<'a> {
        Envelope {
            form: Form::Snapshot,
            tag,
            stamp: Stamp { run, seq: asof },
            record: body,
        }
    }

    /// Whether it is a frame's: its bytes after the seq are a body, never a
    /// record.
    #[must_use]
    pub const fn is_frame(&self) -> bool {
        matches!(self.form, Form::Frame)
    }

    /// Whether it is a heartbeat's: its bytes after the seq are a body,
    /// never a record.
    #[must_use]
    pub const fn is_heartbeat(&self) -> bool {
        matches!(self.form, Form::Heartbeat)
    }

    /// Whether it is a snapshot's page: its bytes after the asof are a
    /// body, never a record.
    #[must_use]
    pub const fn is_snapshot(&self) -> bool {
        matches!(self.form, Form::Snapshot)
    }

    /// A put's payload read as an envelope, or the first refusal that
    /// applies. The key is not read, so a frame or a snapshot is accepted
    /// on any key: [`Envelope::parse_on`] reads its key's kind.
    ///
    /// # Errors
    ///
    /// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
    /// for a form a put does not carry, or [`Refusal::Short`], in that
    /// order.
    pub fn parse(bytes: &'a [u8]) -> Result<Envelope<'a>, Refusal> {
        Self::read_with(bytes, None)
    }

    /// [`Envelope::parse`] for a put on a key of the kind `kind`: a frame on
    /// a key whose kind is not `stream`, or a snapshot on one that is
    /// neither `state` nor `@state`, is [`Refusal::KeyKind`], after the
    /// sample's kind and before the stamp (core §7.5).
    ///
    /// # Errors
    ///
    /// [`Envelope::parse`]'s, and [`Refusal::KeyKind`] after
    /// [`Refusal::WrongSample`].
    pub fn parse_on(bytes: &'a [u8], kind: KindToken) -> Result<Envelope<'a>, Refusal> {
        Self::read_with(bytes, Some(kind))
    }

    fn read_with(bytes: &'a [u8], kind: Option<KindToken>) -> Result<Envelope<'a>, Refusal> {
        // An event's stamp is its key's (core 0.101): with none here, the
        // key gives no occurrence chunk. [`read_event`] reads one.
        if let Some(&ch) = bytes.first() {
            let header = Header::from_byte(ch);
            if header.form == Form::Event {
                read_header(bytes, SampleKind::Put, kind)?;
                return Err(Refusal::KeyStamp { wide: header.wide });
            }
        }
        let (header, stamp, record) = read(bytes, SampleKind::Put, kind)?;
        Ok(Envelope {
            form: header.form,
            tag: header.tag,
            stamp,
            record,
        })
    }

    /// Its CH: its form, the width the run takes, and its tag.
    #[must_use]
    pub const fn header(&self) -> Header {
        Header {
            form: self.form,
            wide: self.stamp.run.is_wide(),
            tag: self.tag,
        }
    }

    /// Its bytes: 6 over the record or the body, or 8 with a 32-bit run.
    /// A value's write as a mutation's do.
    #[must_use]
    pub fn write(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(self.stamp.envelope_bytes() + self.record.len());
        out.push(self.header().byte());
        self.stamp.write_to(&mut out);
        out.extend_from_slice(self.record);
        out
    }
}

/// A delete's attachment under the envelope: `CH · run · seq`, with tag 0
/// and no record. It keeps CH, which states the run's width and lets a
/// reader refuse an attachment that is not an envelope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DeleteStamp {
    pub stamp: Stamp,
}

impl DeleteStamp {
    /// A delete's attachment read as an envelope, or the first refusal
    /// that applies.
    ///
    /// # Errors
    ///
    /// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
    /// for any form but a delete, [`Refusal::DeleteTag`], [`Refusal::Short`]
    /// or [`Refusal::Trailing`], in that order.
    pub fn parse(bytes: &[u8]) -> Result<DeleteStamp, Refusal> {
        let (_, stamp, rest) = read(bytes, SampleKind::Delete, None)?;
        if !rest.is_empty() {
            return Err(Refusal::Trailing(rest.len()));
        }
        Ok(DeleteStamp { stamp })
    }

    /// Its CH: a delete, the width the run takes, and tag 0.
    #[must_use]
    pub const fn header(&self) -> Header {
        Header {
            form: Form::Delete,
            wide: self.stamp.run.is_wide(),
            tag: Tag::NONE,
        }
    }

    /// Its bytes: 6, or 8 with a 32-bit run.
    #[must_use]
    pub fn write(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(self.stamp.envelope_bytes());
        out.push(self.header().byte());
        self.stamp.write_to(&mut out);
        out
    }
}

/// A held stamp (core 0.110 §7.5; #986's J1): `CH · run · seq`, a
/// snapshot's header with no body. CH is form 7, the run's width bit and
/// tag 0: `0xe0` with a 16-bit run, `0xf0` with a 32-bit one. It names one
/// mutation of one state member by its in-band stamp; the seq's place holds
/// the mutation's seq, never an asof. The same bytes ride a state GET, "I
/// hold this member at (run, seq)", and that GET's reply, "its last
/// mutation is (run, seq)", each under `zenoh/bytes` ([`ENCODING`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HeldStamp {
    /// The in-band stamp of the mutation it names: its owner's run, in
    /// width and value, and the mutation's seq. On a GET, the mutation its
    /// reader holds for the member; on a reply, the member's last.
    pub stamp: Stamp,
}

impl HeldStamp {
    /// The held stamp of the mutation `stamp` names.
    #[must_use]
    pub const fn new(stamp: Stamp) -> HeldStamp {
        HeldStamp { stamp }
    }

    /// A state GET's payload read as a held stamp (§7.5, "A held stamp on
    /// a state GET", step 3), without the contract and without the GET's
    /// key, or the first refusal that applies. The `Encoding` is not read,
    /// nor is a payload of no byte told apart: [`read_get`] reads both
    /// first.
    ///
    /// # Errors
    ///
    /// [`Refusal::WrongSample`] for a form other than 7 (`sample_kind`),
    /// [`Refusal::HeldTag`] (`tag`), [`Refusal::Short`] or
    /// [`Refusal::Trailing`], in that order; [`Refusal::Empty`] for no
    /// byte.
    pub fn parse(bytes: &[u8]) -> Result<HeldStamp, Refusal> {
        let (_, stamp, rest) = read(bytes, SampleKind::Get, None)?;
        if !rest.is_empty() {
            return Err(Refusal::Trailing(rest.len()));
        }
        Ok(HeldStamp { stamp })
    }

    /// Its CH: a snapshot's form, the width the run takes, and tag 0.
    #[must_use]
    pub const fn header(&self) -> Header {
        Header {
            form: Form::Snapshot,
            wide: self.stamp.run.is_wide(),
            tag: Tag::NONE,
        }
    }

    /// Its bytes: 6, or 8 with a 32-bit run, and no byte after.
    #[must_use]
    pub fn write(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(self.stamp.envelope_bytes());
        out.push(self.header().byte());
        self.stamp.write_to(&mut out);
        out
    }
}

/// Why a state GET's payload carries no held stamp (core 0.110 §7.5): its
/// `Encoding` (step 2), or the parse's first refusal (step 3). Either way
/// its owner answers the GET as it answers one with no payload (§4.2): a
/// state GET has no error form.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum GetRefusal {
    /// Any `Encoding` but exactly `zenoh/bytes`, a schema suffix on it
    /// included: no held stamp, whatever the bytes.
    #[error("under {0:?}, which carries no held stamp")]
    Encoding(String),
    /// §7.5's first refusal of the payload: `sample_kind`, `tag`, `short`
    /// or `trailing`.
    #[error(transparent)]
    Form(Refusal),
}

impl GetRefusal {
    /// `encoding`, or the parse's token ([`Refusal::token`]), as
    /// `spec/conformance/envelope/held.json`'s `gets` spell it.
    #[must_use]
    pub const fn token(&self) -> &'static str {
        match self {
            GetRefusal::Encoding(_) => "encoding",
            GetRefusal::Form(r) => r.token(),
        }
    }
}

/// A state GET's payload read (core 0.110 §7.5, "A held stamp on a state
/// GET"), in the text's three steps: no payload, or one of no byte, carries
/// no held stamp, `Ok(None)`, whatever its `Encoding`; a payload under any
/// `Encoding` but exactly `zenoh/bytes` is refused `encoding`, whatever its
/// bytes; any other is parsed ([`HeldStamp::parse`]). `encoding` is the
/// payload's, as zenoh writes it.
///
/// # Errors
///
/// [`GetRefusal::Encoding`], else [`GetRefusal::Form`] with
/// [`HeldStamp::parse`]'s refusal. A GET refused carries no held stamp:
/// its owner answers it whole.
pub fn read_get(encoding: &str, payload: Option<&[u8]>) -> Result<Option<HeldStamp>, GetRefusal> {
    let Some(bytes) = payload.filter(|b| !b.is_empty()) else {
        return Ok(None);
    };
    if encoding != ENCODING {
        return Err(GetRefusal::Encoding(encoding.to_owned()));
    }
    HeldStamp::parse(bytes).map(Some).map_err(GetRefusal::Form)
}

/// What a state GET's reply carries ([`read_get_reply`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GetReply<'a> {
    /// A held stamp: a snapshot's envelope with no byte after its seq, and
    /// tag 0. Whether it answers the GET that drew it is §4.2's: its reader
    /// compares it with the one that GET carried
    /// ([`crate::seed::Asked::read`]).
    Held(HeldStamp),
    /// A snapshot's page: form 7 with a byte or more after its seq, its
    /// tag its collection's type's and its body
    /// [`crate::collection::Page::read`]'s, unread here.
    Page(Envelope<'a>),
    /// Another form a put carries: a per-key resource's reply, the bytes
    /// its mutation put, whatever its length.
    Other(Envelope<'a>),
}

/// A state GET's reply payload read (core 0.110 §7.5, "A held stamp on a
/// reply"): parsed as a put's payload is, with no key in hand
/// ([`Envelope::parse`]); a snapshot's envelope with no byte after its seq
/// is a held stamp, never a page, and its body is not read. The bytes
/// decide which: a page's body is 10 bytes or more. The `Encoding` is not
/// read: a reply under another carries no envelope ([`carries`]).
///
/// # Errors
///
/// [`Envelope::parse`]'s refusal, then [`Refusal::HeldTag`] for a held
/// stamp whose tag is not 0.
pub fn read_get_reply(payload: &[u8]) -> Result<GetReply<'_>, Refusal> {
    let e = Envelope::parse(payload)?;
    if !e.is_snapshot() {
        return Ok(GetReply::Other(e));
    }
    if !e.record.is_empty() {
        return Ok(GetReply::Page(e));
    }
    if e.tag != Tag::NONE {
        return Err(Refusal::HeldTag(e.tag));
    }
    Ok(GetReply::Held(HeldStamp { stamp: e.stamp }))
}

/// A call's request, a query's payload: `CH · record` (core 0.92 §7.5).
/// CH is a value's, form 2, with its width bit 0 and its operation's
/// `request` type's tag. It carries no run and no seq: its caller need not
/// be an owner.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Request<'a> {
    /// Its operation's `request` type's tag: 0 unless that type's kind
    /// defines one.
    pub tag: Tag,
    /// Every byte after CH, possibly none, read as the `request` type says.
    pub record: &'a [u8],
}

impl<'a> Request<'a> {
    /// A request: its record under CH.
    #[must_use]
    pub const fn new(tag: Tag, record: &'a [u8]) -> Request<'a> {
        Request { tag, record }
    }

    /// Its CH: a value, width bit 0, and its tag.
    #[must_use]
    pub const fn header(&self) -> Header {
        Header {
            form: Form::Value,
            wide: false,
            tag: self.tag,
        }
    }

    /// Its bytes: 1 over the record.
    #[must_use]
    pub fn write(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(1 + self.record.len());
        out.push(self.header().byte());
        out.extend_from_slice(self.record);
        out
    }
}

/// A call's query payload read as a request, or the first refusal that
/// applies (core 0.92 §7.5). The `Encoding` is not read: a form travels
/// under `zenoh/bytes` ([`ENCODING`]), which the caller tells.
///
/// # Errors
///
/// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
/// for any form but a value, or [`Refusal::RequestRun`], in that order.
pub fn read_query(payload: &[u8]) -> Result<Request<'_>, Refusal> {
    let (header, record) = read_header(payload, SampleKind::Query, None)?;
    Ok(Request {
        tag: header.tag,
        record,
    })
}

/// A call's reply payload read as a value, or the first refusal that
/// applies (core 0.92 §7.5). A GET's reply that represents a put is a put
/// ([`Envelope::parse`]), never this. The `Encoding` is not read.
///
/// # Errors
///
/// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
/// for any form but a value, or [`Refusal::Short`], in that order.
pub fn read_reply(payload: &[u8]) -> Result<Envelope<'_>, Refusal> {
    let (header, stamp, record) = read(payload, SampleKind::Reply, None)?;
    Ok(Envelope {
        form: header.form,
        tag: header.tag,
        stamp,
        record,
    })
}

/// A call's `reply_err` payload read as an error, or the first refusal
/// that applies (core 0.92 §7.5): CH, the stamp, then the error's byte, its
/// message and its detail, the detail's bytes unread. The `Encoding` is not
/// read: [`ErrorForm::read`] gates on it.
///
/// # Errors
///
/// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
/// for any form but an error, [`Refusal::Short`], then on the error's byte
/// [`Refusal::Cause`], [`Refusal::Detail`], [`Refusal::Extension`],
/// [`Refusal::MessageShort`], [`Refusal::Utf8`] or [`Refusal::Trailing`],
/// in that order.
pub fn read_reply_err(payload: &[u8]) -> Result<ErrorForm<'_>, Refusal> {
    let (header, stamp, rest) = read(payload, SampleKind::ReplyErr, None)?;
    ErrorForm::after_stamp(header.tag, stamp, rest)
}

/// The Encoding a sample that carries an envelope or a call's form has
/// (§7.5), as zenoh writes it: its default, with no schema. A raw media
/// type zenoh does not predefine travels as its custom encoding, which
/// zenoh writes as the media type itself (§7.2), so it is never this.
pub const ENCODING: &str = "zenoh/bytes";

/// A call's reply payload read by its `Encoding` (observer §7.3, "A call's
/// forms first"): under `zenoh/bytes` ([`ENCODING`], exactly) as the value
/// form ([`read_reply`]). A reply refused, by its bytes or by another
/// `Encoding`, is malformed, undecodable and never read as a record with
/// no form, and an answer all the same: it came on the call's key (core
/// §5.1, "Reading a value", "Retries").
///
/// # Errors
///
/// [`FormRefusal::Encoding`] under any other `Encoding`, a schema suffix
/// included (core 0.99 removed the bare wire, #985's C4d), else
/// [`read_reply`]'s refusal.
pub fn read_value<'a>(encoding: &str, payload: &'a [u8]) -> Result<Envelope<'a>, FormRefusal> {
    if encoding != ENCODING {
        return Err(FormRefusal::Encoding(encoding.to_owned()));
    }
    read_reply(payload).map_err(FormRefusal::Form)
}

/// Whether `key` is a zk2 data key whose kind is a stream, state or an
/// event (§1.1, by the grammar alone, with no contract): the keys whose
/// samples may carry an envelope ([`enveloped_kind`]). An operation's
/// (`@op`) and every control key (`@zk`) keep their wire.
#[must_use]
pub fn enveloped_key(key: &str) -> bool {
    enveloped_kind(key).is_some()
}

/// The kind token of a key whose samples may carry an envelope: a zk2 data
/// key whose kind is a stream, state or an event, by the grammar alone.
/// `None` for an operation's key, every control key (`@zk`), a foreign key
/// and a key the grammar refuses. The kind picks how two seqs of one run
/// compare ([`crate::seed::Order::of_kind`]).
///
/// A session in a namespace hears a key base-relative, and one in none
/// hears it with the namespace in front (§1.6), which is any chunks: the
/// key is read from its first `zk2` chunk from which the grammar parses a
/// zk2 key, so another deployment's key reads as its own.
#[must_use]
pub fn enveloped_kind(key: &str) -> Option<KindToken> {
    let mut rest = Some(key);
    while let Some(k) = rest {
        if k.starts_with("zk2/") {
            match parse(k) {
                Ok(ZkKey::Data { kind, .. }) => {
                    return (kind != KindToken::Op).then_some(kind);
                }
                Ok(_) => return None,
                Err(_) => {}
            }
        }
        rest = k.split_once('/').map(|(_, r)| r);
    }
    None
}

/// Whether a sample carries an envelope: its key is a zk2 data key whose
/// kind is a stream, state or an event ([`enveloped_key`]), and its
/// Encoding is `zenoh/bytes` ([`ENCODING`]). An owner sends `zenoh/bytes`
/// on such a key only with an envelope (core §7.2 asks the predefined
/// Encoding of every other sample, and a raw type keeps its media type), so
/// the test tells the two wires apart. Every other sample is read as one
/// with no envelope (observer §7.3, "Every other sample").
#[must_use]
pub fn carries(key: &str, encoding: &str) -> bool {
    encoding == ENCODING && enveloped_key(key)
}

/// What a put's payload reads as ([`read_put`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reading<'a> {
    /// The sample carries no envelope ([`carries`]): its payload is read as
    /// it arrived, by observer §7.3's decode order.
    Plain,
    /// A mutation's envelope: its stamp orders the sample, and its record is
    /// the payload every later step reads (decode, a schema check, a
    /// rendering, a profile's reader).
    Enveloped(Envelope<'a>),
    /// A frame (core 0.83 §7.7, form 5) on a plain stream's key: its body
    /// is read with its frame resource's declaration
    /// ([`crate::frame::Frame::parse`]), never decoded as a record of the
    /// key's type. Its stamp is its record 0's.
    Framed(Envelope<'a>),
    /// A heartbeat (core 0.81, form 6): its body is read with its covered
    /// revision ([`crate::heartbeat::Heartbeat::parse`]), never decoded as
    /// a record of the key's type. Its stamp is its key's. An owner
    /// heartbeat (core 0.108) reads so too, and its body is
    /// [`crate::heartbeat::OwnerHeartbeat::parse`]'s: the caller knows
    /// which of the two its key carries.
    Heartbeat(Envelope<'a>),
    /// An event (core 0.101, form 4) on an `events` key whose last chunk
    /// is an occurrence chunk: its time, then its record, which every later
    /// step reads as a mutation's; its stamp is its key's.
    Event(Event<'a>),
    /// A snapshot's page (core 0.97, form 7) on a `state` or `@state`
    /// key, a GET reply's: its body is read by
    /// [`crate::collection::Page::read`], never decoded as a record of the
    /// key's type. Its stamp is the owner's run and the snapshot's asof.
    Snapshot(Envelope<'a>),
    /// An envelope refused: the sample is undecodable, with the refusal's
    /// token as its reason ([`Refusal::reason`]). It is counted and shown
    /// as such, never decoded or sniffed as a payload with no envelope
    /// (observer §7.3's MUST NOT), and never ordered.
    Refused(Refusal),
}

/// A put's payload read as its key and Encoding say ([`carries`]).
#[must_use]
pub fn read_put<'a>(key: &str, encoding: &str, payload: &'a [u8]) -> Reading<'a> {
    if !carries(key, encoding) {
        return Reading::Plain;
    }
    if let Some(event) = read_event(key, payload) {
        return match event {
            Ok(e) => Reading::Event(e),
            Err(r) => Reading::Refused(r),
        };
    }
    let parsed = match enveloped_kind(key) {
        Some(kind) => Envelope::parse_on(payload, kind),
        None => Envelope::parse(payload),
    };
    match parsed {
        Ok(e) if e.is_frame() => Reading::Framed(e),
        Ok(e) if e.is_heartbeat() => Reading::Heartbeat(e),
        Ok(e) if e.is_snapshot() => Reading::Snapshot(e),
        Ok(e) => Reading::Enveloped(e),
        Err(r) => Reading::Refused(r),
    }
}

/// An event, a put's payload on an `events` key (core 0.101 §7.5's form
/// 4; #980's C2a): `CH · t32 · ms16 · record`. Its stamp is its key's
/// occurrence chunk ([`crate::chunk::occurrence`]), CH's width bit the
/// chunk's, and it carries the occurrence's time in the stamp's place.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Event<'a> {
    /// The record's type's: 0 unless its type kind defines a tag.
    pub tag: Tag,
    /// Its key's occurrence chunk.
    pub stamp: Stamp,
    /// The occurrence's time, from the deployment epoch (§7.6), or unknown.
    pub time: crate::collection::Time,
    /// Every byte after the time, possibly none, read as the resource's
    /// type says.
    pub record: &'a [u8],
}

impl Event<'_> {
    /// Its CH: an event's form, its stamp's width, and its tag.
    #[must_use]
    pub const fn header(&self) -> Header {
        Header {
            form: Form::Event,
            wide: self.stamp.run.is_wide(),
            tag: self.tag,
        }
    }

    /// Its key's last chunk: its stamp's occurrence chunk.
    #[must_use]
    pub fn chunk(&self) -> String {
        crate::chunk::write_occurrence(self.stamp)
    }

    /// Its bytes: 7 over the record. `None` for a time no reading accepts
    /// (an ms above 999, or a t32 of all ones known).
    #[must_use]
    pub fn write(&self) -> Option<Vec<u8>> {
        let (s, ms) = self.time.fields().ok()?;
        let mut out = Vec::with_capacity(7 + self.record.len());
        out.push(self.header().byte());
        out.extend_from_slice(&s.to_be_bytes());
        out.extend_from_slice(&ms.to_be_bytes());
        out.extend_from_slice(self.record);
        Some(out)
    }
}

/// A put's payload on `key` read as an event (core 0.101 §7.5's form 4),
/// or the first refusal that applies, in §7.5's order: CH's checks
/// (`short`, `sample_kind`, `key_kind` on a key whose kind token is not
/// `events`), then `key_stamp` (the key's last chunk is no occurrence
/// chunk of CH's width), `short` (fewer than 7 bytes) and `time`. `None`
/// for a payload whose CH is not form 4's, or that has no byte, which
/// [`Envelope::parse_on`] reads.
#[must_use]
pub fn read_event<'a>(key: &str, bytes: &'a [u8]) -> Option<Result<Event<'a>, Refusal>> {
    let &ch = bytes.first()?;
    if Header::from_byte(ch).form != Form::Event {
        return None;
    }
    Some(event(key, bytes))
}

fn event<'a>(key: &str, bytes: &'a [u8]) -> Result<Event<'a>, Refusal> {
    let (header, rest) = read_header(bytes, SampleKind::Put, enveloped_kind(key))?;
    let stamp = key
        .rsplit('/')
        .next()
        .and_then(crate::chunk::occurrence)
        .filter(|s| s.run.is_wide() == header.wide)
        .ok_or(Refusal::KeyStamp { wide: header.wide })?;
    if rest.len() < 6 {
        return Err(Refusal::Short {
            need: 7,
            have: bytes.len(),
        });
    }
    let (t, record) = rest.split_at(6);
    let time = crate::collection::Time::of_fields(
        u32::from_be_bytes([t[0], t[1], t[2], t[3]]),
        u16::from_be_bytes([t[4], t[5]]),
    )
    .map_err(|_| Refusal::Time)?;
    Ok(Event {
        tag: header.tag,
        stamp,
        time,
        record,
    })
}

/// A delete's in-band stamp: on a key whose samples may carry an envelope
/// ([`enveloped_key`]), an attachment that parses as a delete's envelope.
/// A delete whose attachment is absent or does not parse is read as one
/// with no envelope, by its Zenoh timestamp (core §4.2): an archive's or a
/// profile's attachment (`telemetry.v1`'s Epoch) is never refused here.
#[must_use]
pub fn read_delete(key: &str, attachment: Option<&[u8]>) -> Option<Stamp> {
    let a = attachment?;
    if !enveloped_key(key) {
        return None;
    }
    DeleteStamp::parse(a).ok().map(|d| d.stamp)
}

impl Refusal {
    /// Why a refused envelope's sample is undecodable, for a person and a
    /// script alike: the refusal's token after a fixed prefix,
    /// `zk2c envelope refused: short`. A held stamp that is no answer
    /// ([`Refusal::Held`]) is named as what it is, with its stamp, before
    /// its token, `held`: its bytes parse, and it is no page cut short.
    #[must_use]
    pub fn reason(&self) -> String {
        match self {
            Refusal::Held(s) => format!(
                "zk2c held stamp (run {}, seq {}), unchanged only to the GET that carried it, \
                 and no answer here: held",
                s.run,
                s.seq.get()
            ),
            _ => format!("zk2c envelope refused: {}", self.token()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_byte_is_a_header_and_writes_back() {
        for ch in 0..=u8::MAX {
            let h = Header::from_byte(ch);
            assert_eq!(h.byte(), ch);
            assert_eq!(h.form.code(), ch >> 5);
            assert_eq!(Form::from_code(h.form.code()), Some(h.form));
        }
        assert_eq!(Form::from_code(8), None);
    }

    #[test]
    fn the_worked_bytes() {
        let h = Header::from_byte(0x1b);
        assert_eq!((h.form, h.wide, h.tag.get()), (Form::Mutation, true, 11));
        assert_eq!(Header::from_byte(0x20).form, Form::Delete);
        assert!(!Header::from_byte(0x20).wide);
    }

    #[test]
    fn bounds_by_construction() {
        assert_eq!(Tag::new(15).map(Tag::get), Some(15));
        assert_eq!(Tag::new(16), None);
        assert_eq!(Seq::new(0x00ff_ffff), Some(Seq::MAX));
        assert_eq!(Seq::new(0x0100_0000), None);
    }

    #[test]
    fn sizes() {
        let narrow = Stamp {
            run: Run::U16(7),
            seq: Seq::MAX,
        };
        let wide = Stamp {
            run: Run::U32(7),
            seq: Seq::MAX,
        };
        let record = [1, 2, 3];
        for (stamp, over) in [(narrow, 6), (wide, 8)] {
            let e = Envelope {
                form: Form::Mutation,
                tag: Tag::NONE,
                stamp,
                record: &record,
            };
            let bytes = e.write();
            assert_eq!(bytes.len(), over + record.len());
            assert_eq!(Envelope::parse(&bytes), Ok(e));
            let d = DeleteStamp { stamp };
            let bytes = d.write();
            assert_eq!(bytes.len(), over);
            assert_eq!(DeleteStamp::parse(&bytes), Ok(d));
        }
    }

    /// A run as a descriptor states it (core §3.3): 4 lowercase hex digits
    /// for a 16-bit run, 8 for a 32-bit one, and nothing else read back.
    #[test]
    fn a_run_as_a_descriptor_states_it() {
        assert_eq!(Run::U16(3).hex(), "0003");
        assert_eq!(Run::U16(0xa1).hex(), "00a1");
        assert_eq!(Run::U32(0xa1).hex(), "000000a1");
        assert_eq!(Run::U32(u32::MAX).hex(), "ffffffff");
        for r in [
            Run::U16(0),
            Run::U16(u16::MAX),
            Run::U32(0),
            Run::U32(0xdead_beef),
        ] {
            assert_eq!(Run::from_hex(&r.hex()), Some(r));
        }
        assert_eq!(Run::from_hex("00a1"), Some(Run::U16(0xa1)));
        assert_eq!(Run::from_hex("000000a1"), Some(Run::U32(0xa1)));
        for bad in [
            "",
            "1a2b3",
            "ABCD",
            "00A1",
            "abc",
            "+0a1",
            "-001",
            "000000a1f",
            " 0a1",
            "g000",
        ] {
            assert_eq!(Run::from_hex(bad), None, "{bad:?}");
        }
    }

    /// Every sample of [`SampleKind::ALL`] against every form: each
    /// carries the forms §7.5 gives it and no other, a state GET's payload
    /// (core 0.110) a snapshot's form alone; each has a name of its own;
    /// and a state GET's parse refuses every form but 7 as `sample_kind`,
    /// before a tag or a length is read.
    #[test]
    fn every_sample_carries_its_forms_and_a_state_get_form_7_alone() {
        use std::collections::BTreeSet;
        let names: BTreeSet<&str> = SampleKind::ALL.iter().map(|s| s.as_str()).collect();
        assert_eq!(
            names.into_iter().collect::<Vec<_>>(),
            ["delete", "get", "put", "query", "reply", "reply_err"]
        );
        for sample in SampleKind::ALL {
            let carried: Vec<Form> = Form::ALL
                .into_iter()
                .filter(|f| sample.carries(*f))
                .collect();
            let want: &[Form] = match sample {
                SampleKind::Put => &[
                    Form::Mutation,
                    Form::Event,
                    Form::Frame,
                    Form::Heartbeat,
                    Form::Snapshot,
                ],
                SampleKind::Delete => &[Form::Delete],
                SampleKind::Query | SampleKind::Reply => &[Form::Value],
                SampleKind::ReplyErr => &[Form::Error],
                SampleKind::Get => &[Form::Snapshot],
            };
            assert_eq!(carried, want, "{sample}");
        }
        for form in Form::ALL {
            // CH alone, with tag 5: the form is judged first.
            let ch = Header {
                form,
                wide: false,
                tag: Tag::new(5).unwrap(),
            }
            .byte();
            let got = HeldStamp::parse(&[ch]);
            if form == Form::Snapshot {
                assert_eq!(got, Err(Refusal::HeldTag(Tag::new(5).unwrap())));
            } else {
                assert_eq!(
                    got,
                    Err(Refusal::WrongSample {
                        form,
                        sample: SampleKind::Get
                    }),
                    "{form}"
                );
            }
        }
    }

    #[test]
    fn each_kind_refuses_the_others_form() {
        let d = DeleteStamp {
            stamp: Stamp {
                run: Run::U16(1),
                seq: Seq::default(),
            },
        }
        .write();
        assert_eq!(
            Envelope::parse(&d),
            Err(Refusal::WrongSample {
                form: Form::Delete,
                sample: SampleKind::Put
            })
        );
        let m = Envelope {
            form: Form::Mutation,
            tag: Tag::NONE,
            stamp: Stamp {
                run: Run::U16(1),
                seq: Seq::default(),
            },
            record: &[],
        }
        .write();
        assert_eq!(
            DeleteStamp::parse(&m).map_err(|r| r.token()),
            Err("sample_kind")
        );
    }

    /// Rule 1 (#976's A2): a stream, state or event key of the grammar,
    /// under `zenoh/bytes`, and nothing else.
    #[test]
    fn a_sample_carries_an_envelope_by_its_key_kind_and_its_encoding() {
        for key in [
            "zk2/h/s/i.v1/stream/pose",
            "zk2/h/s/i.v1/@stream/frames/f1",
            "zk2/h/s/i.v1/state/mode",
            "zk2/h/s/i.v1/@state/tracks/t1",
            "zk2/h/s/i.v1/events/fault/002g0009",
            // A session in no namespace hears the namespace in front.
            "prod/zk2/h/s/i.v1/state/mode",
            "site/a/zk2/h/s/i.v1/stream/pose",
            // A namespace whose own chunk is `zk2`: the first suffix the
            // grammar parses decides.
            "zk2/zk2/h/s/i.v1/state/mode",
        ] {
            assert!(enveloped_key(key), "{key}");
            assert!(enveloped_kind(key).is_some(), "{key}");
            assert!(carries(key, ENCODING), "{key}");
            for other in [
                "application/json",
                "application/cbor",
                "application/protobuf",
                "zenoh/bytes;x",
                "image/x-portable-anymap",
                "",
            ] {
                assert!(!carries(key, other), "{key} under {other:?}");
            }
        }
        for key in [
            "zk2/h/s/i.v1/@op/reset",
            "zk2/h/s/@zk/instance/0a1b2c3d4e5f6071",
            "zk2/@zk/contract/i.v1/0000000000000000000000000000000000000000000000000000000000000000",
            "demo/tick",
            "seedtest/state/health",
            "zk2/h/s/i.v1",
            "zk2",
            "",
        ] {
            assert!(!enveloped_key(key), "{key}");
            assert_eq!(enveloped_kind(key), None, "{key}");
            assert!(!carries(key, ENCODING), "{key}");
        }
        assert_eq!(
            enveloped_kind("prod/zk2/h/s/i.v1/@stream/frames/f1"),
            Some(KindToken::ExplicitStream)
        );
        assert_eq!(
            enveloped_kind("zk2/h/s/i.v1/events/fault/002g0009"),
            Some(KindToken::Events)
        );
        assert_eq!(
            enveloped_kind("zk2/h/s/i.v1/events/fault/01arz3ndektsv4rrffq69g5fav"),
            None,
            "a ULID's key is no zk2 key (core 0.103 §1.2)"
        );
    }

    #[test]
    fn a_put_reads_plain_enveloped_or_refused() {
        let key = "zk2/h/s/i.v1/state/mode";
        let stamp = Stamp {
            run: Run::U16(7),
            seq: Seq::new(3).unwrap(),
        };
        let bytes = Envelope {
            form: Form::Mutation,
            tag: Tag::NONE,
            stamp,
            record: br#"{"up":true}"#,
        }
        .write();
        // Today's wire: the predefined Encoding, read as it is.
        assert_eq!(read_put(key, "application/json", &bytes), Reading::Plain);
        let Reading::Enveloped(e) = read_put(key, ENCODING, &bytes) else {
            panic!("an envelope")
        };
        assert_eq!((e.stamp, e.record), (stamp, &br#"{"up":true}"#[..]));
        // A legacy payload under `zenoh/bytes` is refused, never read: `{`
        // is form 3, an error, which a put does not carry (core 0.92).
        let refused = read_put(key, ENCODING, br#"{"up":true}"#);
        assert_eq!(
            refused,
            Reading::Refused(Refusal::WrongSample {
                form: Form::Error,
                sample: SampleKind::Put
            })
        );
        let Reading::Refused(r) = refused else {
            unreachable!()
        };
        assert_eq!(r.reason(), "zk2c envelope refused: sample_kind");
        assert_eq!(
            read_put(key, ENCODING, &[]),
            Reading::Refused(Refusal::Empty)
        );
        // A foreign key under `zenoh/bytes` is its own bytes.
        assert_eq!(read_put("demo/tick", ENCODING, &bytes), Reading::Plain);
    }

    /// Rule 3: a delete's attachment that parses carries its stamp; any
    /// other is read as one with no envelope.
    #[test]
    fn a_delete_carries_its_stamp_in_its_attachment_or_none() {
        let key = "zk2/h/s/i.v1/state/mode";
        let stamp = Stamp {
            run: Run::U32(0xdead_beef),
            seq: Seq::new(9).unwrap(),
        };
        let att = DeleteStamp { stamp }.write();
        assert_eq!(read_delete(key, Some(&att)), Some(stamp));
        assert_eq!(read_delete(key, None), None);
        // An archive's JSON, or a mutation's bytes, is no delete stamp.
        assert_eq!(read_delete(key, Some(br#"{"confirmed":true}"#)), None);
        assert_eq!(read_delete(key, Some(&[0x00, 0, 7, 0, 0, 9])), None);
        assert_eq!(read_delete("demo/tick", Some(&att)), None);
        assert_eq!(read_delete("zk2/h/s/i.v1/@op/reset", Some(&att)), None);
    }

    /// A call's reply by its `Encoding` (observer §7.3, "A call's forms
    /// first"; core §5.1, "Reading a value"): under `zenoh/bytes` the
    /// value form, refused by its bytes alone, and under any other no
    /// form, however its bytes would parse.
    #[test]
    fn a_reply_is_a_value_form_under_zenoh_bytes_alone() {
        let stamp = Stamp {
            run: Run::U16(1),
            seq: Seq::new(7).unwrap(),
        };
        let bytes = Envelope::value(Tag::NONE, stamp, br#"{"up":true}"#).write();
        let v = read_value(ENCODING, &bytes).expect("a value");
        assert_eq!(
            (v.form, v.stamp, v.record),
            (Form::Value, stamp, &br#"{"up":true}"#[..])
        );
        // `{` is 0x7b, form 3: an error, which a reply does not carry.
        assert_eq!(
            read_value(ENCODING, br#"{"up":true}"#),
            Err(FormRefusal::Form(Refusal::WrongSample {
                form: Form::Error,
                sample: SampleKind::Reply
            }))
        );
        // The same bytes on another Encoding, a schema suffix included,
        // carry no form.
        for other in ["application/json", "zenoh/bytes;x", "zenoh/string"] {
            let r = read_value(other, &bytes);
            assert_eq!(r, Err(FormRefusal::Encoding(other.to_owned())), "{other}");
            assert_eq!(r.unwrap_err().token(), "encoding");
        }
    }
}