soyokaze 0.6.3

HTTP/1/2/3 Library Crate
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
//! Carrying [`URL`] and [`Message`] across the boundary.
//!
//! A [`Message`] is reached as a handle, and its field section and body are
//! reached through it rather than as handles of their own — there is no way to
//! hold a section apart from the message it belongs to, and so no way to free
//! one twice.

use bytes::Bytes;

use crate::errors::Error;
use crate::ffi::errors::{ErrorHandle, Status};
use crate::ffi::{Buffer, Runtime, Slice};
use crate::models::{Body, Message, Method, Role, URL, Version};

/// Which transport a port names, and so which versions it can carry.
///
/// The C half of [`Port`], which cannot cross as an enum because one of its
/// variants carries a path.
///
/// [`Port`]: crate::models::Port
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PortKind {
    /// A Unix domain socket, named by `path`.
    UDS = 0,
    /// A TCP port, named by `number`.
    TCP = 1,
    /// A UDP port carrying QUIC, named by `number`.
    QUIC = 2,
}

/// A port to dial or bind.
///
/// `number` is read for [`PortKind::TCP`] and [`PortKind::QUIC`], and `path`
/// and `path_len` for [`PortKind::UDS`].
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Port {
    /// Which transport the port names, as a [`PortKind`] number.
    ///
    /// Held as its number rather than as the enum, so that a value naming no
    /// kind is a port that will not parse rather than a Rust enum holding
    /// something it has no variant for, which is undefined behaviour.
    pub kind: i32,
    /// The port number, for a TCP or QUIC port.
    pub number: u16,
    /// The socket path, for a Unix domain socket.
    pub path: *const u8,
    /// How long the socket path is.
    pub path_len: usize,
}

impl PortKind {
    /// The kind a `soyokaze_port_kind_t` names, or `None` when it names none.
    pub fn from_code(code: i32) -> Option<Self> {
        Some(match code {
            0 => Self::UDS,
            1 => Self::TCP,
            2 => Self::QUIC,
            _ => return None,
        })
    }
}

impl Port {
    /// The [`Port`] this names.
    ///
    /// Returns `None` when the kind names none, or when a Unix socket path is
    /// absent or is not UTF-8.
    ///
    /// [`Port`]: crate::models::Port
    ///
    /// # Safety
    ///
    /// `path` must either be null or point to `path_len` readable octets.
    pub unsafe fn parse(&self) -> Option<crate::models::Port> {
        match PortKind::from_code(self.kind)? {
            PortKind::TCP => Some(crate::models::Port::TCP(self.number)),
            PortKind::QUIC => Some(crate::models::Port::QUIC(self.number)),
            PortKind::UDS => Some(crate::models::Port::UDS(unsafe { Slice::borrow_text(self.path, self.path_len) }?.to_owned())),
        }
    }

    /// Reads `count` ports out of a C array.
    ///
    /// `None` when the array is null or any entry will not parse.
    ///
    /// # Safety
    ///
    /// `ports` must either be null or point to `count` readable [`Port`]
    /// values whose own pointers are valid.
    pub unsafe fn parse_all(ports: *const Port, count: usize) -> Option<Vec<crate::models::Port>> {
        if ports.is_null() {
            return None;
        }

        let mut parsed = Vec::with_capacity(count);
        for index in 0..count {
            parsed.push(unsafe { (*ports.add(index)).parse() }?);
        }

        Some(parsed)
    }
}

/// Parses an absolute URL.
///
/// # Safety
///
/// `url` must point to `url_len` readable octets, and `out` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_parse(url: *const u8, url_len: usize, out: *mut *mut URL, error: *mut *mut ErrorHandle) -> Status {
    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    let Some(text) = (unsafe { Slice::borrow_text(url, url_len) }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    match URL::parse(text) {
        Ok(url) => {
            unsafe { *out = Box::into_raw(Box::new(url)) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Releases a [`URL`].
///
/// # Safety
///
/// `url` must come from [`soyokaze_url_parse`] and not have been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_free(url: *mut URL) {
    if !url.is_null() {
        drop(unsafe { Box::from_raw(url) });
    }
}

/// The scheme, lowercased, borrowed from `url`.
///
/// # Safety
///
/// `url` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_scheme(url: *const URL) -> Slice {
    Slice::maybe(unsafe { url.as_ref() }.map(|url| url.scheme.as_str()))
}

/// The host, borrowed from `url`.
///
/// # Safety
///
/// As [`soyokaze_url_scheme`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_host(url: *const URL) -> Slice {
    Slice::maybe(unsafe { url.as_ref() }.map(|url| url.host.as_str()))
}

/// The request target — path, query and fragment — borrowed from `url`.
///
/// # Safety
///
/// As [`soyokaze_url_scheme`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_target(url: *const URL) -> Slice {
    Slice::maybe(unsafe { url.as_ref() }.map(|url| url.target.as_str()))
}

/// The port, or zero when `url` is null.
///
/// # Safety
///
/// As [`soyokaze_url_scheme`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_port(url: *const URL) -> u16 {
    unsafe { url.as_ref() }.map_or(0, |url| url.port)
}

/// Whether the scheme is a secure one.
///
/// # Safety
///
/// As [`soyokaze_url_scheme`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_secure(url: *const URL) -> bool {
    unsafe { url.as_ref() }.is_some_and(|url| url.secure())
}

/// The authority — host, and port when it is not the default for the scheme.
///
/// Owned by the caller, since it is assembled rather than stored. An empty
/// buffer comes back when `url` is null.
///
/// # Safety
///
/// As [`soyokaze_url_scheme`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_authority(url: *const URL) -> Buffer {
    match unsafe { url.as_ref() } {
        Some(url) => Buffer::new(url.authority().into_bytes()),
        None => Buffer::EMPTY,
    }
}

/// Builds an empty message, neither a request nor a response yet.
///
/// [`soyokaze_message_request`] and [`soyokaze_message_response`] are the
/// usual entry points; this is for the rare caller assembling one by hand.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_message_new(version: i32) -> *mut Message {
    Box::into_raw(Box::new(Message::new(Version::of(version))))
}

/// Builds a request.
///
/// # Safety
///
/// `target` must point to `target_len` readable octets. Returns null when it is
/// not UTF-8, or when `method` names no method.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_request(method: i32, target: *const u8, target_len: usize, version: i32) -> *mut Message {
    match (Method::from_code(method), unsafe { Slice::borrow_text(target, target_len) }) {
        (Some(method), Some(target)) => Box::into_raw(Box::new(Message::request(method, target, Version::of(version)))),
        _ => std::ptr::null_mut(),
    }
}

/// Builds a response.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_message_response(status_code: u16, version: i32) -> *mut Message {
    Box::into_raw(Box::new(Message::response(status_code, Version::of(version))))
}

/// Releases a [`Message`].
///
/// # Safety
///
/// `message` must be a handle the caller owns and has not freed. A message
/// handed to a call documented as consuming it must not be freed again.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_free(message: *mut Message) {
    if !message.is_null() {
        drop(unsafe { Box::from_raw(message) });
    }
}

/// The version that framed the message.
///
/// A null `message` reads as [`Version::V1_1`].
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_version(message: *const Message) -> Version {
    unsafe { message.as_ref() }.map_or(Version::V1_1, |message| message.version)
}

/// The method, or `-1` on a response.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_method(message: *const Message) -> i32 {
    match unsafe { message.as_ref() }.and_then(|message| message.method) {
        Some(method) => method as i32,
        None => -1,
    }
}

/// The status code, or `-1` on a request.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_status_code(message: *const Message) -> i32 {
    match unsafe { message.as_ref() }.and_then(|message| message.status_code) {
        Some(status_code) => status_code as i32,
        None => -1,
    }
}

/// The request target, borrowed from `message`, or absent on a response.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_target(message: *const Message) -> Slice {
    Slice::maybe(unsafe { message.as_ref() }.and_then(|message| message.target.as_deref()))
}

/// Whether the message is a request.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_is_request(message: *const Message) -> bool {
    unsafe { message.as_ref() }.is_some_and(|message| message.is_request())
}

/// Whether the message is a response.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_is_response(message: *const Message) -> bool {
    unsafe { message.as_ref() }.is_some_and(|message| message.is_response())
}

/// Whether the message is an informational (1xx) response.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_is_informational(message: *const Message) -> bool {
    unsafe { message.as_ref() }.is_some_and(|message| message.is_informational())
}

/// Whether the message travelled over a secure transport.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_secure(message: *const Message) -> bool {
    unsafe { message.as_ref() }.is_some_and(|message| message.security.secure)
}

/// How many fields the message's section holds.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_header_count(message: *const Message) -> usize {
    unsafe { message.as_ref() }.and_then(|message| message.headers.as_ref()).map_or(0, |headers| headers.len())
}

/// The name of the field at `index`, borrowed from `message`.
///
/// Absent when there is no such field. Names are stored lowercase.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_header_name(message: *const Message, index: usize) -> Slice {
    let field = unsafe { message.as_ref() }.and_then(|message| message.headers.as_ref()).and_then(|headers| headers.iter().nth(index)).map(|(name, _)| name);

    Slice::maybe(field)
}

/// The value of the field at `index`, borrowed from `message`.
///
/// Absent when there is no such field.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_header_value(message: *const Message, index: usize) -> Slice {
    let field = unsafe { message.as_ref() }.and_then(|message| message.headers.as_ref()).and_then(|headers| headers.iter().nth(index)).map(|(_, value)| value);

    Slice::maybe(field)
}

/// The first value stored under `name`, borrowed from `message`.
///
/// Absent when the field is not there, which is not the same as a field that is
/// there and empty. The name is matched case-insensitively.
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed, and
/// `name` must point to `name_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_header(message: *const Message, name: *const u8, name_len: usize) -> Slice {
    let Some(name) = (unsafe { Slice::borrow_text(name, name_len) }) else {
        return Slice::ABSENT;
    };

    Slice::maybe(unsafe { message.as_ref() }.and_then(|message| message.headers.as_ref()).and_then(|headers| headers.get(name)))
}

/// Adds a field, keeping any field already stored under the same name.
///
/// Returns whether it was added; it is refused when an argument is null or is
/// not UTF-8.
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed, and
/// `name` and `value` must point to their stated number of readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_append_header(message: *mut Message, name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> bool {
    let (Some(message), Some(name), Some(value)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) })
    else {
        return false;
    };

    message.headers.get_or_insert_default().append(name, value);
    true
}

/// Adds a field, dropping any field already stored under the same name.
///
/// Returns whether it was set, as [`soyokaze_message_append_header`].
///
/// # Safety
///
/// As [`soyokaze_message_append_header`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_insert_header(message: *mut Message, name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> bool {
    let (Some(message), Some(name), Some(value)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) })
    else {
        return false;
    };

    message.headers.get_or_insert_default().insert(name, value);
    true
}

/// Drops every field stored under `name`.
///
/// Returns whether anything was there to drop.
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed, and
/// `name` must point to `name_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_remove_header(message: *mut Message, name: *const u8, name_len: usize) -> bool {
    let (Some(message), Some(name)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return false;
    };

    message.headers.as_mut().is_some_and(|headers| headers.remove(name))
}

/// How many fields the message's trailer section holds.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_trailer_count(message: *const Message) -> usize {
    unsafe { message.as_ref() }.and_then(|message| message.trailers.as_ref()).map_or(0, |trailers| trailers.len())
}

/// The name of the trailer field at `index`, borrowed from `message`.
///
/// Absent when there is no such field. Names are stored lowercase.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_trailer_name(message: *const Message, index: usize) -> Slice {
    let field = unsafe { message.as_ref() }.and_then(|message| message.trailers.as_ref()).and_then(|trailers| trailers.iter().nth(index)).map(|(name, _)| name);

    Slice::maybe(field)
}

/// The value of the trailer field at `index`, borrowed from `message`.
///
/// Absent when there is no such field.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_trailer_value(message: *const Message, index: usize) -> Slice {
    let field = unsafe { message.as_ref() }.and_then(|message| message.trailers.as_ref()).and_then(|trailers| trailers.iter().nth(index)).map(|(_, value)| value);

    Slice::maybe(field)
}

/// The first trailer value stored under `name`, borrowed from `message`.
///
/// Absent when the field is not there. The name is matched case-insensitively.
///
/// # Safety
///
/// As [`soyokaze_message_header`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_trailer(message: *const Message, name: *const u8, name_len: usize) -> Slice {
    let Some(name) = (unsafe { Slice::borrow_text(name, name_len) }) else {
        return Slice::ABSENT;
    };

    Slice::maybe(unsafe { message.as_ref() }.and_then(|message| message.trailers.as_ref()).and_then(|trailers| trailers.get(name)))
}

/// Adds a trailer field, keeping any field already stored under the same name.
///
/// Returns whether it was added, as [`soyokaze_message_append_header`].
///
/// # Safety
///
/// As [`soyokaze_message_append_header`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_append_trailer(message: *mut Message, name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> bool {
    let (Some(message), Some(name), Some(value)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) })
    else {
        return false;
    };

    message.trailers.get_or_insert_default().append(name, value);
    true
}

/// Adds a trailer field, dropping any field already stored under the same name.
///
/// Returns whether it was set, as [`soyokaze_message_append_header`].
///
/// # Safety
///
/// As [`soyokaze_message_append_header`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_insert_trailer(message: *mut Message, name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> bool {
    let (Some(message), Some(name), Some(value)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) })
    else {
        return false;
    };

    message.trailers.get_or_insert_default().insert(name, value);
    true
}

/// Drops every trailer field stored under `name`.
///
/// Returns whether anything was there to drop.
///
/// # Safety
///
/// As [`soyokaze_message_remove_header`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_remove_trailer(message: *mut Message, name: *const u8, name_len: usize) -> bool {
    let (Some(message), Some(name)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return false;
    };

    message.trailers.as_mut().is_some_and(|trailers| trailers.remove(name))
}

/// The stream the message belongs to, or `-1` when it belongs to none.
///
/// HTTP/1.x has no streams; HTTP/2 and HTTP/3 stamp this on every message they
/// hand over.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_stream_id(message: *const Message) -> i64 {
    match unsafe { message.as_ref() }.and_then(|message| message.stream_id) {
        Some(stream_id) => stream_id.0 as i64,
        None => -1,
    }
}

/// Stamps the message with a stream, or clears it with a negative `stream_id`.
///
/// A server sending responses through `soyokaze_connection_send` must echo the
/// request's stream identifier this way; the serve callbacks do it themselves.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_stream_id(message: *mut Message, stream_id: i64) -> bool {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return false;
    };

    message.stream_id = u64::try_from(stream_id).ok().map(crate::models::StreamID);
    true
}

/// The identifier of the connection the message arrived on, borrowed from
/// `message`.
///
/// Absent when the message has not crossed a connection.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_connection_id(message: *const Message) -> Slice {
    match unsafe { message.as_ref() }.and_then(|message| message.connection_id.as_ref()) {
        Some(id) => Slice::new(&id.0),
        None => Slice::ABSENT,
    }
}

/// The address the request was received from, and its port, as text.
///
/// Empty on a response, on a message the caller built, and on a connection
/// over a Unix socket, whose accepted address names nothing. Free the result
/// with [`soyokaze_buffer_free`].
///
/// [`soyokaze_buffer_free`]: crate::ffi::soyokaze_buffer_free
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_client(message: *const Message) -> Buffer {
    match unsafe { message.as_ref() }.and_then(|message| message.client) {
        Some(client) => Buffer::new(client.to_string().into_bytes()),
        None => Buffer::EMPTY,
    }
}

/// The content coding the body is to go out in, or `-1` when there is none.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_compression(message: *const Message) -> i32 {
    match unsafe { message.as_ref() }.and_then(|message| message.compression) {
        Some(compression) => compression as i32,
        None => -1,
    }
}

/// Sets the content coding the body is to go out in; `-1` clears it.
///
/// Refuses a code that names no coding.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_compression(message: *mut Message, compression: i32) -> bool {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return false;
    };

    if compression < 0 {
        message.compression = None;
        return true;
    }

    let Some(compression) = crate::ffi::helpers::compression::coding(compression) else {
        return false;
    };

    message.compression = Some(compression);
    true
}

/// Whether the body is currently carried compressed, per `Content-Encoding`.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_compressed(message: *const Message) -> bool {
    unsafe { message.as_ref() }.is_some_and(Message::compressed)
}

/// The best coding the message's `Accept-Encoding` permits, or `-1` for none.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_accepted(message: *const Message) -> i32 {
    match unsafe { message.as_ref() }.and_then(Message::accepted) {
        Some(compression) => compression as i32,
        None => -1,
    }
}

/// Reads a body that is still a file into memory, so that it can be coded.
///
/// Needs a runtime because reading the file is asynchronous; every other body
/// is left alone and no I/O happens.
///
/// # Safety
///
/// As [`soyokaze_message_version`], and `runtime` must be a runtime that has
/// not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_materialize(message: *mut Message, runtime: *const crate::ffi::Runtime, error: *mut *mut ErrorHandle) -> Status {
    let (Some(message), Some(runtime)) = (unsafe { message.as_mut() }, unsafe { runtime.as_ref() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    match runtime.0.block_on(message.materialize()) {
        Ok(()) => Status::Ok,
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Encodes the body in the coding the message carries.
///
/// `accepted` is the coding the exchange permits, which is what
/// `SOYOKAZE_COMPRESSION_AUTO` settles on; `-1` permits none. The body must
/// already be in memory — see [`soyokaze_message_materialize`].
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_compress(message: *mut Message, accepted: i32, error: *mut *mut ErrorHandle) -> Status {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    let accepted = match accepted {
        ..0 => None,
        code => match crate::ffi::helpers::compression::coding(code) {
            Some(compression) => Some(compression),
            None => return unsafe { ErrorHandle::raise(error, Status::Invalid) },
        },
    };

    match message.compress(accepted) {
        Ok(()) => Status::Ok,
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Decodes a body that arrived coded, and takes `Content-Encoding` off it.
///
/// `max` bounds what the decoded body may reach; passing it is
/// [`Status::Limit`].
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_decompress(message: *mut Message, max: u64, error: *mut *mut ErrorHandle) -> Status {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    match message.decompress(max) {
        Ok(()) => Status::Ok,
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Marks the message as travelling over a secure transport, or not.
///
/// This is what the `:scheme` pseudo-header reflects on HTTP/2 and HTTP/3.
/// [`soyokaze_client_fetch`] sets it from the URL itself; this is for requests
/// sent through `soyokaze_connection_send`.
///
/// [`soyokaze_client_fetch`]: crate::ffi::api::client::soyokaze_client_fetch
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_secure(message: *mut Message, secure: bool) -> bool {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return false;
    };

    message.security.secure = secure;
    true
}

/// Whether the request arrived in TLS early data, and so may be a replay.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_early_data(message: *const Message) -> bool {
    unsafe { message.as_ref() }.is_some_and(|message| message.security.early_data)
}

/// Whether the transport underneath was TLS.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_tls(message: *const Message) -> bool {
    unsafe { message.as_ref() }.is_some_and(|message| message.security.tls)
}

/// The negotiated TLS version as its two-octet wire code, or `-1`.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_tls_version(message: *const Message) -> i32 {
    match unsafe { message.as_ref() }.and_then(|message| message.security.tls_version) {
        Some(version) => version.0 as i32,
        None => -1,
    }
}

/// The negotiated TLS named group as its two-octet wire code, or `-1`.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_tls_group(message: *const Message) -> i32 {
    match unsafe { message.as_ref() }.and_then(|message| message.security.tls_group) {
        Some(group) => group.0 as i32,
        None => -1,
    }
}

/// The negotiated TLS cipher suite as its two-octet wire code, or `-1`.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_tls_cipher(message: *const Message) -> i32 {
    match unsafe { message.as_ref() }.and_then(|message| message.security.tls_cipher) {
        Some(cipher) => cipher.0 as i32,
        None => -1,
    }
}

/// Whether the transport underneath was QUIC.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_quic(message: *const Message) -> bool {
    unsafe { message.as_ref() }.is_some_and(|message| message.security.quic)
}

/// The negotiated QUIC version, or `-1`.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_quic_version(message: *const Message) -> i64 {
    match unsafe { message.as_ref() }.and_then(|message| message.security.quic_version) {
        Some(version) => version as i64,
        None => -1,
    }
}

/// Sets the body to octets held in memory, copied out of `data`.
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed, and
/// `data` must point to `data_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_body_data(message: *mut Message, data: *const u8, data_len: usize) -> bool {
    let (Some(message), Some(data)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow(data, data_len) }) else {
        return false;
    };

    message.body = Some(Body::Data(Bytes::copy_from_slice(data)));
    true
}

/// Sets the body to UTF-8 text held in memory, copied out of `text`.
///
/// Refused when the octets are not UTF-8; [`soyokaze_message_set_body_data`]
/// takes octets that are not.
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed, and
/// `text` must point to `text_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_body_text(message: *mut Message, text: *const u8, text_len: usize) -> bool {
    let (Some(message), Some(text)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow_text(text, text_len) }) else {
        return false;
    };

    message.body = Some(Body::Text(text.to_owned()));
    true
}

/// Sets the body to a path, read only when the body is actually sent.
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed, and
/// `path` must point to `path_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_body_file(message: *mut Message, path: *const u8, path_len: usize) -> bool {
    let (Some(message), Some(path)) = (unsafe { message.as_mut() }, unsafe { Slice::borrow_text(path, path_len) }) else {
        return false;
    };

    message.body = Some(Body::File(path.to_owned()));
    true
}

/// How long the body is, or `-1` when there is none or it is a file that has
/// not been read.
///
/// # Safety
///
/// As [`soyokaze_message_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_body_len(message: *const Message) -> i64 {
    match unsafe { message.as_ref() }.and_then(|message| message.body.as_ref()).and_then(|body| body.len()) {
        Some(len) => len as i64,
        None => -1,
    }
}

/// Reads the body, reading the file behind it if there is one.
///
/// Writes an empty buffer when the message has no body. Needs a runtime because
/// a [`Body::File`] is read from the filesystem.
///
/// # Safety
///
/// `runtime` and `message` must be handles that have not been freed, and `out`
/// must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_body(runtime: *mut Runtime, message: *const Message, out: *mut Buffer, error: *mut *mut ErrorHandle) -> Status {
    let (Some(runtime), Some(message)) = (unsafe { runtime.as_ref() }, unsafe { message.as_ref() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    let Some(body) = message.body.as_ref() else {
        unsafe { *out = Buffer::EMPTY };
        return Status::Ok;
    };

    match runtime.0.block_on(body.bytes()) {
        Ok(octets) => {
            unsafe { *out = Buffer::new(octets.to_vec()) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &Error::IO(failure)) },
    }
}

/// What one connection is allowed to spend on the peer's behalf.
///
/// The C half of [`Limits`], field for field. Passing null wherever one of
/// these is asked for takes every default; a caller that wants to change one
/// ceiling starts from [`soyokaze_limits_default`] and adjusts it.
///
/// [`Limits`]: crate::models::Limits
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Limits {
    /// In bytes, the total size of the HTTP message allowed for reception.
    pub max_message_size: u64,
    /// In bytes, the size of the HTTP message body allowed for reception.
    pub max_message_body_size: u64,
    /// In bytes, the size a received body may reach once its content coding is undone.
    pub max_decompressed_body_size: u64,

    /// In bytes, the request/status line ceiling.
    pub max_startline_size: u32,
    /// In bytes, the whole header (or trailer) block.
    pub max_headers_size: u64,
    /// The number of header fields allowed in one block.
    pub max_header_count: u16,
    /// In bytes, the chunk-size line ceiling for chunked transfer encoding.
    pub max_chunk_header_size: u32,

    /// In bytes, how much room each read from a transport is given.
    pub read_chunk_size: u64,
    /// In bytes, the buffer size above which an idle connection gives memory back.
    pub idle_capacity: u64,

    /// The number of connections a listener may negotiate at once.
    pub max_pending_handshakes: u32,

    /// In seconds, how long one connection may take to negotiate. Zero waits forever.
    pub handshake_timeout: f64,
    /// In seconds, how long one read may wait. Zero waits forever.
    pub read_timeout: f64,
    /// In seconds, how long one write may wait. Zero waits forever.
    pub write_timeout: f64,
    /// In seconds, how long one whole message may take to arrive. Zero waits forever.
    pub receive_timeout: f64,
    /// In seconds, how long one whole message may take to send. Zero waits forever.
    pub send_timeout: f64,

    /// In bytes, the body size up to which an HTTP/1.x head and body go out as one write.
    pub inline_body_size: u64,

    /// The number of streams a peer may have open at once, per connection.
    pub max_concurrent_streams: u32,
    /// In bytes, the unread message data one connection may hold.
    pub max_connection_buffer_size: u64,
    /// The number of streams a peer may reset before a response was sent.
    pub max_premature_resets: u32,
    /// In bytes, the largest field compression encoder table this end will keep.
    pub max_encoder_table_size: u64,

    /// The number of frames a peer may send without advancing a stream.
    pub max_idle_frames: u32,
    /// In bytes, the buffered output size at which a body write flushes rather than growing.
    pub output_high_water: u64,

    /// The number of requests one connection may serve over its lifetime. Zero serves forever.
    pub max_requests_per_connection: u64,
    /// In seconds, how long to wait for a blocking QPACK reference.
    pub qpack_block_timeout: f64,
    /// The number of unidirectional streams a peer may open at once.
    pub max_peer_uni_streams: u32,
    /// The number of unacknowledged QPACK field sections the encoder may track.
    pub max_outstanding_sections: u32,
    /// The number of streams that may wait QPACK-blocked at once.
    pub max_blocked_streams: u32,
    /// The number of reads or writes a tunnel will hold before it applies back pressure.
    pub tunnel_backlog: u32,
    pub command_backlog: u32,

    /// In seconds, how long a WebSocket close waits for the peer's echo.
    pub ws_linger_timeout: f64,
    /// The number of continuation frames allowed in one WebSocket message.
    pub ws_max_fragments: u16,

    /// The number of cookies one jar may hold across all origins.
    pub max_cookies: u32,
    /// The number of cookies one jar may hold for a single domain.
    pub max_cookies_per_domain: u16,
    /// The number of hosts one HSTS store may remember.
    pub max_hsts_entries: u32,
}

impl Limits {
    /// The [`Limits`] this stands for.
    ///
    /// [`Limits`]: crate::models::Limits
    pub fn parse(&self) -> crate::models::Limits {
        crate::models::Limits {
            max_message_size: self.max_message_size,
            max_message_body_size: self.max_message_body_size,
            max_decompressed_body_size: self.max_decompressed_body_size,
            max_startline_size: self.max_startline_size,
            max_headers_size: self.max_headers_size,
            max_header_count: self.max_header_count,
            max_chunk_header_size: self.max_chunk_header_size,
            read_chunk_size: self.read_chunk_size,
            idle_capacity: self.idle_capacity,
            max_pending_handshakes: self.max_pending_handshakes,
            handshake_timeout: self.handshake_timeout,
            read_timeout: self.read_timeout,
            write_timeout: self.write_timeout,
            receive_timeout: self.receive_timeout,
            send_timeout: self.send_timeout,
            inline_body_size: self.inline_body_size,
            max_concurrent_streams: self.max_concurrent_streams,
            max_connection_buffer_size: self.max_connection_buffer_size,
            max_premature_resets: self.max_premature_resets,
            max_encoder_table_size: self.max_encoder_table_size,
            max_idle_frames: self.max_idle_frames,
            output_high_water: self.output_high_water,
            max_requests_per_connection: self.max_requests_per_connection,
            qpack_block_timeout: self.qpack_block_timeout,
            max_peer_uni_streams: self.max_peer_uni_streams,
            max_outstanding_sections: self.max_outstanding_sections,
            max_blocked_streams: self.max_blocked_streams,
            tunnel_backlog: self.tunnel_backlog,
            command_backlog: self.command_backlog,
            ws_linger_timeout: self.ws_linger_timeout,
            ws_max_fragments: self.ws_max_fragments,
            max_cookies: self.max_cookies,
            max_cookies_per_domain: self.max_cookies_per_domain,
            max_hsts_entries: self.max_hsts_entries,
        }
    }

    /// The C half of `limits`.
    pub fn build(limits: &crate::models::Limits) -> Self {
        Self {
            max_message_size: limits.max_message_size,
            max_message_body_size: limits.max_message_body_size,
            max_decompressed_body_size: limits.max_decompressed_body_size,
            max_startline_size: limits.max_startline_size,
            max_headers_size: limits.max_headers_size,
            max_header_count: limits.max_header_count,
            max_chunk_header_size: limits.max_chunk_header_size,
            read_chunk_size: limits.read_chunk_size,
            idle_capacity: limits.idle_capacity,
            max_pending_handshakes: limits.max_pending_handshakes,
            handshake_timeout: limits.handshake_timeout,
            read_timeout: limits.read_timeout,
            write_timeout: limits.write_timeout,
            receive_timeout: limits.receive_timeout,
            send_timeout: limits.send_timeout,
            inline_body_size: limits.inline_body_size,
            max_concurrent_streams: limits.max_concurrent_streams,
            max_connection_buffer_size: limits.max_connection_buffer_size,
            max_premature_resets: limits.max_premature_resets,
            max_encoder_table_size: limits.max_encoder_table_size,
            max_idle_frames: limits.max_idle_frames,
            output_high_water: limits.output_high_water,
            max_requests_per_connection: limits.max_requests_per_connection,
            qpack_block_timeout: limits.qpack_block_timeout,
            max_peer_uni_streams: limits.max_peer_uni_streams,
            max_outstanding_sections: limits.max_outstanding_sections,
            max_blocked_streams: limits.max_blocked_streams,
            tunnel_backlog: limits.tunnel_backlog,
            command_backlog: limits.command_backlog,
            ws_linger_timeout: limits.ws_linger_timeout,
            ws_max_fragments: limits.ws_max_fragments,
            max_cookies: limits.max_cookies,
            max_cookies_per_domain: limits.max_cookies_per_domain,
            max_hsts_entries: limits.max_hsts_entries,
        }
    }

    /// The [`Limits`] a pointer stands for: what it points at, or the defaults
    /// when it is null.
    ///
    /// [`Limits`]: crate::models::Limits
    ///
    /// # Safety
    ///
    /// `limits` must either be null or point to a readable [`Limits`].
    pub unsafe fn or_default(limits: *const Limits) -> crate::models::Limits {
        match unsafe { limits.as_ref() } {
            Some(limits) => limits.parse(),
            None => crate::models::Limits::default(),
        }
    }
}

/// The default [`Limits`], to be adjusted and passed back.
///
/// [`Limits`]: crate::models::Limits
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_limits_default() -> Limits {
    Limits::build(&crate::models::Limits::default())
}

impl Version {
    /// Reads a version list out of a C array of `soyokaze_version_t` values.
    ///
    /// A null `versions` means take the default list. `None` when an entry
    /// names no version.
    ///
    /// # Safety
    ///
    /// `versions` must either be null or point to `count` readable numbers.
    pub unsafe fn parse_all(versions: *const i32, count: usize) -> Option<Vec<Version>> {
        if versions.is_null() {
            return Some(Vec::new());
        }

        let mut parsed = Vec::with_capacity(count);

        for index in 0..count {
            parsed.push(match unsafe { *versions.add(index) } {
                0 => Version::V1_0,
                1 => Version::V1_1,
                2 => Version::V2_0,
                3 => Version::V3_0,
                _ => return None,
            });
        }

        Some(parsed)
    }
}

impl Role {
    /// The `soyokaze_role_t` number for a [`Role`].
    ///
    /// The two enums are kept in the same order, so this is the crate's own
    /// grading rather than a narrowing of it: a caller can still tell a proxy
    /// from a user agent, and a tunnel from either.
    pub fn build(role: Role) -> u32 {
        match role {
            Role::UserAgent => 0,
            Role::Origin => 1,
            Role::Proxy => 2,
            Role::Gateway => 3,
            Role::Tunnel => 4,
        }
    }
}

/// What a port or a version runs over.
///
/// The C half of [`TransportKind`]. Nothing keys on a particular version
/// number: a port carries exactly the versions whose transport matches its
/// own, so a future version is routed by what it runs over rather than by
/// name.
///
/// [`TransportKind`]: crate::models::TransportKind
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TransportKind {
    /// An ordered byte stream: TCP, or a Unix domain socket.
    Stream = 0,
    /// QUIC, over UDP.
    QUIC = 1,
}

impl TransportKind {
    /// The C half of `transport`.
    pub fn build(transport: crate::models::TransportKind) -> Self {
        match transport {
            crate::models::TransportKind::Stream => Self::Stream,
            crate::models::TransportKind::QUIC => Self::QUIC,
        }
    }
}

/// The transport family a port carries.
///
/// A null `port`, or one whose socket path will not read, reads as
/// [`TransportKind::Stream`].
///
/// # Safety
///
/// `port` must either be null or point to a readable [`Port`] whose own
/// pointers are valid.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_port_transport(port: *const Port) -> TransportKind {
    match unsafe { port.as_ref() }.and_then(|port| unsafe { port.parse() }) {
        Some(port) => TransportKind::build(port.transport()),
        None => TransportKind::Stream,
    }
}

/// Whether a port can carry a version at all.
///
/// # Safety
///
/// As [`soyokaze_port_transport`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_port_carries(port: *const Port, version: i32) -> bool {
    let Some(version) = Version::from_code(version) else {
        return false;
    };

    unsafe { port.as_ref() }.and_then(|port| unsafe { port.parse() }).is_some_and(|port| port.carries(version))
}

/// Which of `versions` a port can carry, in the order they were given.
///
/// Writes at most `count` versions through `out` and returns how many there
/// were. A null `out` counts without writing.
///
/// # Safety
///
/// As [`soyokaze_port_transport`], `versions` must point to `count` readable
/// versions, and `out` must either be null or be writable for `count` of them.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_port_offers(port: *const Port, versions: *const Version, count: usize, out: *mut Version) -> usize {
    let (Some(port), Some(versions)) = (unsafe { port.as_ref() }.and_then(|port| unsafe { port.parse() }), unsafe { Version::borrow_all(versions, count) }) else {
        return 0;
    };

    let offered = port.offers(versions);

    if !out.is_null() {
        for (index, version) in offered.iter().take(count).enumerate() {
            unsafe { *out.add(index) = *version };
        }
    }

    offered.len()
}

impl Version {
    /// Borrows `count` versions from a C array.
    ///
    /// A null array borrows nothing, which is how an absent argument is
    /// passed.
    ///
    /// # Safety
    ///
    /// `versions` must either be null or point to `count` readable versions.
    pub unsafe fn borrow_all<'a>(versions: *const Version, count: usize) -> Option<&'a [Version]> {
        if versions.is_null() {
            return (count == 0).then_some(&[][..]);
        }

        Some(unsafe { std::slice::from_raw_parts(versions, count) })
    }
}

/// The port a scheme is reached on when the URL does not say.
///
/// Zero for a scheme with no default.
///
/// # Safety
///
/// `scheme` must either be null or point to `scheme_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_default_port(scheme: *const u8, scheme_len: usize) -> u16 {
    match unsafe { Slice::borrow_text(scheme, scheme_len) } {
        Some(scheme) => URL::default_port(scheme),
        None => 0,
    }
}

/// The authority a scheme, host and port spell out, owned by the caller.
///
/// The port is left off when it is the scheme's default, which is what an
/// origin expects to see in `Host` or `:authority`.
///
/// # Safety
///
/// `scheme` and `host` must either be null or point to their stated number of
/// readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_url_authority_of(scheme: *const u8, scheme_len: usize, host: *const u8, host_len: usize, port: u16) -> Buffer {
    let (Some(scheme), Some(host)) = (unsafe { Slice::borrow_text(scheme, scheme_len) }, unsafe { Slice::borrow_text(host, host_len) }) else {
        return Buffer::EMPTY;
    };

    Buffer::new(URL::authority_of(scheme, host, port).into_bytes())
}

/// The ALPN identifier a version is negotiated under, borrowed from the
/// library.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_version_alpn(version: i32) -> Slice {
    Slice::maybe(Version::from_code(version).map(|version| version.alpn()))
}

/// The version an ALPN identifier names, or `-1` when it names none.
///
/// # Safety
///
/// `alpn` must either be null or point to `alpn_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_version_from_alpn(alpn: *const u8, alpn_len: usize) -> i32 {
    match unsafe { Slice::borrow(alpn, alpn_len) }.and_then(Version::from_alpn) {
        Some(version) => version as i32,
        None => -1,
    }
}

/// The major version number.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_version_major(version: i32) -> u8 {
    Version::from_code(version).map_or(0, |version| version.major())
}

/// What the version runs over.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_version_transport(version: i32) -> TransportKind {
    TransportKind::build(Version::of(version).transport())
}

/// How the version is written out, borrowed from the library.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_version_name(version: i32) -> Slice {
    Slice::maybe(Version::from_code(version).map(|version| version.as_str()))
}

/// The version a name spells out, or `-1` when it spells none.
///
/// Accepts what [`soyokaze_version_name`] produces, and the bare `1.0`, `1.1`,
/// `2` and `3` forms alongside them.
///
/// # Safety
///
/// `name` must either be null or point to `name_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_version_parse(name: *const u8, name_len: usize) -> i32 {
    match unsafe { Slice::borrow_text(name, name_len) }.and_then(|name| name.parse::<Version>().ok()) {
        Some(version) => version as i32,
        None => -1,
    }
}

/// The ALPN protocol list for `versions`, in the wire format a handshake
/// carries: each identifier preceded by its length.
///
/// # Safety
///
/// `versions` must either be null or point to `count` readable versions.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_alpn_wire(versions: *const Version, count: usize) -> Buffer {
    match unsafe { Version::borrow_all(versions, count) } {
        Some(versions) => Buffer::new(crate::models::ALPN::wire(versions)),
        None => Buffer::EMPTY,
    }
}

/// Picks the first identifier a client offered that this end also offers.
///
/// Both lists are in the wire format [`soyokaze_alpn_wire`] produces. The
/// answer is borrowed from `client`, and is absent when nothing matched.
///
/// # Safety
///
/// `versions` must either be null or point to `count` readable versions, and
/// `client` must either be null or point to `client_len` readable octets that
/// outlive the returned slice.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_alpn_select(versions: *const Version, count: usize, client: *const u8, client_len: usize) -> Slice {
    let (Some(versions), Some(client)) = (unsafe { Version::borrow_all(versions, count) }, unsafe { Slice::borrow(client, client_len) }) else {
        return Slice::ABSENT;
    };

    match crate::models::ALPN::select(&crate::models::ALPN::list(versions), client) {
        Some(chosen) => Slice::new(chosen),
        None => Slice::ABSENT,
    }
}

/// The version an agreed ALPN identifier settles on.
///
/// A null `alpn` stands for a handshake that agreed on nothing, which settles
/// on HTTP/1.1 when it is offered and fails otherwise.
///
/// # Safety
///
/// As [`soyokaze_alpn_select`], and `out` must either be null or be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_alpn_negotiated(alpn: *const u8, alpn_len: usize, versions: *const Version, count: usize, out: *mut Version, error: *mut *mut ErrorHandle) -> Status {
    let Some(versions) = (unsafe { Version::borrow_all(versions, count) }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    match crate::models::ALPN::negotiated(unsafe { Slice::borrow(alpn, alpn_len) }, versions) {
        Ok(version) => {
            if !out.is_null() {
                unsafe { *out = version };
            }

            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// The method as it is written on the wire, borrowed from the library.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_method_name(method: i32) -> Slice {
    Slice::maybe(Method::from_code(method).map(|method| method.as_str()))
}

/// The method a name spells out, or `-1` when it spells none.
///
/// # Safety
///
/// `name` must either be null or point to `name_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_method_parse(name: *const u8, name_len: usize) -> i32 {
    match unsafe { Slice::borrow_text(name, name_len) }.and_then(|name| name.parse::<Method>().ok()) {
        Some(method) => method as i32,
        None => -1,
    }
}

/// Whether the method is read-only, so that issuing it changes nothing.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_method_safe(method: i32) -> bool {
    Method::from_code(method).is_some_and(|method| method.safe())
}

/// Whether repeating the method has the same effect as issuing it once.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_method_idempotent(method: i32) -> bool {
    Method::from_code(method).is_some_and(|method| method.idempotent())
}

/// Whether this role sends requests and reads responses.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_role_is_client(role: i32) -> bool {
    Role::from_code(role).is_some_and(|role| role.is_client())
}

/// Whether this role reads requests and sends responses.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_role_is_server(role: i32) -> bool {
    Role::from_code(role).is_some_and(|role| role.is_server())
}

/// How field names are cased on the way out.
///
/// The C half of [`HeaderCase`]. Names are always stored lowercase and
/// re-cased as they are written.
///
/// [`HeaderCase`]: crate::models::HeaderCase
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HeaderCase {
    /// `Content-Length`: each dash-separated word capitalised.
    Title = 0,
    /// `content-length`: entirely lowercase.
    Lower = 1,
}

impl HeaderCase {
    /// The [`HeaderCase`] this stands for.
    ///
    /// [`HeaderCase`]: crate::models::HeaderCase
    pub fn parse(self) -> crate::models::HeaderCase {
        match self {
            Self::Title => crate::models::HeaderCase::Title,
            Self::Lower => crate::models::HeaderCase::Lower,
        }
    }

    /// The C half of `case`.
    pub fn build(case: crate::models::HeaderCase) -> Self {
        match case {
            crate::models::HeaderCase::Title => Self::Title,
            crate::models::HeaderCase::Lower => Self::Lower,
        }
    }

    /// The casing a `soyokaze_header_case_t` names, or `None` when it names
    /// none.
    ///
    /// As [`Version::from_code`].
    pub fn from_code(code: i32) -> Option<Self> {
        Some(match code {
            0 => Self::Title,
            1 => Self::Lower,
            _ => return None,
        })
    }

    /// The casing a code names, or [`HeaderCase::Lower`] when it names none.
    ///
    /// Lowercase is what every version accepts, so it is the safe reading of a
    /// code this end does not know.
    pub fn of(code: i32) -> Self {
        Self::from_code(code).unwrap_or(Self::Lower)
    }
}

/// The casing a version expects: title case for HTTP/1.x, lowercase above.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_header_case_from_version(version: i32) -> HeaderCase {
    HeaderCase::build(crate::models::HeaderCase::from_version(Version::of(version)))
}

/// A field name in this casing, owned by the caller.
///
/// # Safety
///
/// `name` must either be null or point to `name_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_header_case_apply(case: i32, name: *const u8, name_len: usize) -> Buffer {
    match unsafe { Slice::borrow_text(name, name_len) } {
        Some(name) => Buffer::new(HeaderCase::of(case).parse().apply(name).into_bytes()),
        None => Buffer::EMPTY,
    }
}

/// Re-cases a field name already written into `name`, in place.
///
/// # Safety
///
/// `name` must either be null or point to `name_len` writable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_header_case_apply_in_place(case: i32, name: *mut u8, name_len: usize) -> bool {
    if name.is_null() {
        return false;
    }

    HeaderCase::of(case).parse().apply_in_place(unsafe { std::slice::from_raw_parts_mut(name, name_len) });
    true
}

pub use crate::models::Headers;

/// The presence bit that stands for a well-known field name, or zero.
///
/// A [`Headers`] keeps the bitwise or of these over every field it holds,
/// which lets a lookup for one of these names rule itself out without walking
/// the list. The name must already be lowercase.
///
/// # Safety
///
/// `name` must either be null or point to `name_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_well_known(name: *const u8, name_len: usize) -> u32 {
    match unsafe { Slice::borrow_text(name, name_len) } {
        Some(name) => Headers::well_known(name),
        None => 0,
    }
}

/// `1 << index` when `matched`, and zero otherwise.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_headers_bit(matched: bool, index: u32) -> u32 {
    Headers::bit(matched, index)
}

/// Whether a stored lowercase name is the field `name` asks for.
///
/// # Safety
///
/// `stored` and `name` must either be null or point to their stated number of
/// readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_named(stored: *const u8, stored_len: usize, name: *const u8, name_len: usize) -> bool {
    let (Some(stored), Some(name)) = (unsafe { Slice::borrow_text(stored, stored_len) }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return false;
    };

    Headers::named(stored, name)
}

/// Builds an empty field section.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_headers_new() -> *mut Headers {
    Box::into_raw(Box::new(Headers::new()))
}

/// Builds an empty field section with room for `fields` entries.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_headers_with_capacity(fields: usize) -> *mut Headers {
    Box::into_raw(Box::new(Headers::with_capacity(fields)))
}

/// Releases a [`Headers`].
///
/// Only one built by [`soyokaze_headers_new`] or
/// [`soyokaze_headers_with_capacity`] is freed this way; one borrowed from a
/// message belongs to that message.
///
/// # Safety
///
/// `headers` must come from one of those two calls and not have been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_free(headers: *mut Headers) {
    if !headers.is_null() {
        drop(unsafe { Box::from_raw(headers) });
    }
}

/// How many fields the section holds.
///
/// # Safety
///
/// `headers` must either be null or be a section that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_len(headers: *const Headers) -> usize {
    unsafe { headers.as_ref() }.map_or(0, |headers| headers.len())
}

/// Whether the section holds nothing.
///
/// # Safety
///
/// As [`soyokaze_headers_len`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_is_empty(headers: *const Headers) -> bool {
    unsafe { headers.as_ref() }.is_none_or(|headers| headers.is_empty())
}

/// The name of the field at `index`, borrowed from the section.
///
/// # Safety
///
/// As [`soyokaze_headers_len`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_name(headers: *const Headers, index: usize) -> Slice {
    Slice::maybe(unsafe { headers.as_ref() }.and_then(|headers| headers.fields().get(index)).map(|field| field.name.as_str()))
}

/// The value of the field at `index`, borrowed from the section.
///
/// # Safety
///
/// As [`soyokaze_headers_len`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_value(headers: *const Headers, index: usize) -> Slice {
    Slice::maybe(unsafe { headers.as_ref() }.and_then(|headers| headers.fields().get(index)).map(|field| field.value.as_str()))
}

/// Whether the section carries `name` at all.
///
/// # Safety
///
/// As [`soyokaze_headers_len`], and `name` must either be null or point to
/// `name_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_contains(headers: *const Headers, name: *const u8, name_len: usize) -> bool {
    let (Some(headers), Some(name)) = (unsafe { headers.as_ref() }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return false;
    };

    headers.contains(name)
}

/// Whether the section carries no field named `name`.
///
/// # Safety
///
/// As [`soyokaze_headers_contains`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_absent(headers: *const Headers, name: *const u8, name_len: usize) -> bool {
    let (Some(headers), Some(name)) = (unsafe { headers.as_ref() }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return true;
    };

    headers.absent(name)
}

/// The first value stored under `name`, borrowed from the section.
///
/// # Safety
///
/// As [`soyokaze_headers_contains`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_get(headers: *const Headers, name: *const u8, name_len: usize) -> Slice {
    let (Some(headers), Some(name)) = (unsafe { headers.as_ref() }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return Slice::ABSENT;
    };

    Slice::maybe(headers.get(name))
}

/// How many values are stored under `name`.
///
/// # Safety
///
/// As [`soyokaze_headers_contains`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_get_all_count(headers: *const Headers, name: *const u8, name_len: usize) -> usize {
    let (Some(headers), Some(name)) = (unsafe { headers.as_ref() }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return 0;
    };

    headers.get_all(name).count()
}

/// The `index`th value stored under `name`, borrowed from the section.
///
/// # Safety
///
/// As [`soyokaze_headers_contains`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_get_all(headers: *const Headers, name: *const u8, name_len: usize, index: usize) -> Slice {
    let (Some(headers), Some(name)) = (unsafe { headers.as_ref() }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return Slice::ABSENT;
    };

    Slice::maybe(headers.get_all(name).nth(index))
}

/// Appends a field, keeping whatever is already stored under the name.
///
/// # Safety
///
/// As [`soyokaze_headers_contains`], and `value` must either be null or point
/// to `value_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_append(headers: *mut Headers, name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> bool {
    let (Some(headers), Some(name), Some(value)) = (unsafe { headers.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) }) else {
        return false;
    };

    headers.append(name, value);
    true
}

/// Appends a field whose name is already lowercase.
///
/// Skips the lowercasing [`soyokaze_headers_append`] does. A name that is not
/// already lowercase will never be found by a lookup.
///
/// # Safety
///
/// As [`soyokaze_headers_append`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_append_lowercase(headers: *mut Headers, name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> bool {
    let (Some(headers), Some(name), Some(value)) = (unsafe { headers.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) }) else {
        return false;
    };

    headers.append_lowercase(name, value);
    true
}

/// Stores a field, dropping whatever was already under the name.
///
/// # Safety
///
/// As [`soyokaze_headers_append`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_insert(headers: *mut Headers, name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> bool {
    let (Some(headers), Some(name), Some(value)) = (unsafe { headers.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) }) else {
        return false;
    };

    headers.insert(name, value);
    true
}

/// Drops every field stored under `name`, returning whether any was there.
///
/// # Safety
///
/// As [`soyokaze_headers_contains`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_headers_remove(headers: *mut Headers, name: *const u8, name_len: usize) -> bool {
    let (Some(headers), Some(name)) = (unsafe { headers.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }) else {
        return false;
    };

    headers.remove(name)
}

/// The message's field section, borrowed from it.
///
/// Built empty when the message has none yet, so the pointer is null only when
/// `message` is. It belongs to the message and must not be freed; it stays
/// valid until the message is freed or its section is replaced.
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_headers(message: *mut Message) -> *mut Headers {
    match unsafe { message.as_mut() } {
        Some(message) => message.headers.get_or_insert_with(Headers::new),
        None => std::ptr::null_mut(),
    }
}

/// The message's trailer section, borrowed from it.
///
/// As [`soyokaze_message_headers`], for the fields that follow the body.
///
/// # Safety
///
/// As [`soyokaze_message_headers`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_trailers(message: *mut Message) -> *mut Headers {
    match unsafe { message.as_mut() } {
        Some(message) => message.trailers.get_or_insert_with(Headers::new),
        None => std::ptr::null_mut(),
    }
}

/// Whether the message opens a tunnel rather than carrying a body.
///
/// `method` is the request method a response is being read against, and is
/// ignored on a request; pass `-1` when there is none.
///
/// # Safety
///
/// `message` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_tunneling(message: *const Message, method: i32) -> bool {
    let Some(message) = (unsafe { message.as_ref() }) else {
        return false;
    };

    message.tunneling(Method::from_code(method))
}

impl Version {
    /// The version a `soyokaze_version_t` names, or `None` when it names none.
    ///
    /// Every call that takes a version takes it as its number and comes
    /// through here. A Rust enum holding a value it has no variant for is
    /// undefined behaviour rather than a value to be matched, so nothing a C
    /// caller passes is ever taken for one until it has been read here.
    pub fn from_code(code: i32) -> Option<Self> {
        Some(match code {
            0 => Self::V1_0,
            1 => Self::V1_1,
            2 => Self::V2_0,
            3 => Self::V3_0,
            _ => return None,
        })
    }

    /// The version a code names, or [`Version::V1_1`] when it names none.
    ///
    /// For the calls that take a version alongside everything else they need
    /// and have no way to report one argument being wrong. HTTP/1.1 is what a
    /// message that was never told a version is framed as, so it is what an
    /// unreadable one falls back to.
    pub fn of(code: i32) -> Self {
        Self::from_code(code).unwrap_or(Self::V1_1)
    }
}

impl Role {
    /// The role a `soyokaze_role_t` names, or `None` when it names none.
    ///
    /// As [`Version::from_code`].
    pub fn from_code(code: i32) -> Option<Self> {
        Some(match code {
            0 => Self::UserAgent,
            1 => Self::Origin,
            2 => Self::Proxy,
            3 => Self::Gateway,
            4 => Self::Tunnel,
            _ => return None,
        })
    }
}

impl Method {
    /// The method a wire code names, or `None` when it names none.
    ///
    /// A negative code stands for an absent method, which is how a caller says
    /// it does not know which request a response answers.
    pub fn from_code(code: i32) -> Option<Self> {
        Some(match code {
            0 => Self::GET,
            1 => Self::HEAD,
            2 => Self::POST,
            3 => Self::PUT,
            4 => Self::DELETE,
            5 => Self::CONNECT,
            6 => Self::OPTIONS,
            7 => Self::TRACE,
            8 => Self::PATCH,
            _ => return None,
        })
    }
}

/// Sets which version framed the message.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_version(message: *mut Message, version: i32) -> bool {
    let (Some(message), Some(version)) = (unsafe { message.as_mut() }, Version::from_code(version)) else {
        return false;
    };

    message.version = version;
    true
}

/// Sets the request method, or clears it with a negative `method`.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_method(message: *mut Message, method: i32) -> bool {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return false;
    };

    message.method = Method::from_code(method);
    true
}

/// Sets the request target, or clears it with a null `target`.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`], and `target` must either be null or point
/// to `target_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_target(message: *mut Message, target: *const u8, target_len: usize) -> bool {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return false;
    };

    if target.is_null() {
        message.target = None;
        return true;
    }

    let Some(target) = (unsafe { Slice::borrow_text(target, target_len) }) else {
        return false;
    };

    message.target = Some(crate::helpers::text::Text::from_str(target));
    true
}

/// Sets the response status code, or clears it with a negative `status_code`.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_status_code(message: *mut Message, status_code: i32) -> bool {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return false;
    };

    message.status_code = u16::try_from(status_code).ok();
    true
}

/// Sets the connection the message belongs to, or clears it with a null `id`.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`], and `id` must either be null or point to
/// `id_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_set_connection_id(message: *mut Message, id: *const u8, id_len: usize) -> bool {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return false;
    };

    message.connection_id = unsafe { Slice::borrow(id, id_len) }.map(|id| crate::models::ConnectionID(Bytes::copy_from_slice(id)));
    true
}

/// Which kind of body a message carries.
///
/// The C half of [`Body`], with [`BodyKind::None`] added for the message that
/// carries none.
///
/// [`Body`]: crate::models::Body
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BodyKind {
    /// No body at all.
    None = 0,
    /// Octets held in memory.
    Data = 1,
    /// A UTF-8 string held in memory.
    Text = 2,
    /// A filesystem path, read when the body is needed.
    File = 3,
}

/// Which kind of body the message carries.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_body_kind(message: *const Message) -> BodyKind {
    match unsafe { message.as_ref() }.and_then(|message| message.body.as_ref()) {
        Some(Body::Data(_)) => BodyKind::Data,
        Some(Body::Text(_)) => BodyKind::Text,
        Some(Body::File(_)) => BodyKind::File,
        None => BodyKind::None,
    }
}

/// Whether the body is known to be empty.
///
/// A file that has not been read counts as non-empty, since its length is not
/// known until it is.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_body_is_empty(message: *const Message) -> bool {
    unsafe { message.as_ref() }.and_then(|message| message.body.as_ref()).is_none_or(|body| body.is_empty())
}

/// The body's octets when they are already in memory, borrowed from the
/// message.
///
/// Absent for a file that has not been read, which
/// `soyokaze_message_body` reads instead.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_body_inline(message: *const Message) -> Slice {
    match unsafe { message.as_ref() }.and_then(|message| message.body.as_ref()) {
        Some(Body::Data(data)) => Slice::new(data),
        Some(Body::Text(text)) => Slice::text(text),
        _ => Slice::ABSENT,
    }
}

/// The path a file body names, borrowed from the message.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_body_path(message: *const Message) -> Slice {
    match unsafe { message.as_ref() }.and_then(|message| message.body.as_ref()) {
        Some(Body::File(path)) => Slice::text(path),
        _ => Slice::ABSENT,
    }
}

/// Clears the body, returning whether there was a message.
///
/// # Safety
///
/// As [`soyokaze_message_tunneling`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_message_clear_body(message: *mut Message) -> bool {
    let Some(message) = (unsafe { message.as_mut() }) else {
        return false;
    };

    message.body = None;
    true
}