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
//! Cookies, from C.
//!
//! [`Cookie`] and [`SetCookie`] are the two sides of the exchange — what a
//! client sends and what a server sets — and [`CookieJar`] is the client-side
//! store that turns one into the other across requests, exactly as
//! [`crate::cookies`] arranges them. The jar reads the clock itself, so the
//! caller never passes a timestamp.

use std::time::Instant;

use crate::ffi::models::Limits;
use crate::ffi::errors::{ErrorHandle, Status};
use crate::ffi::{Buffer, Slice};
use crate::cookies::{Cookie, CookieJar, SameSite, SetCookie};
use crate::models::URL;

/// Builds an empty `Cookie` field: no pairs yet.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_cookie_new() -> *mut Cookie {
    Box::into_raw(Box::new(Cookie::new()))
}

/// Reads a `Cookie` field value.
///
/// Parsing never fails — a malformed field yields whatever pairs could be read
/// from it. Returns null only when `value` is null or not UTF-8.
///
/// # Safety
///
/// `value` must either be null or point to `value_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookie_parse(value: *const u8, value_len: usize) -> *mut Cookie {
    match unsafe { Slice::borrow_text(value, value_len) } {
        Some(value) => Box::into_raw(Box::new(Cookie::parse(value))),
        None => std::ptr::null_mut(),
    }
}

/// Releases a [`Cookie`].
///
/// # Safety
///
/// `cookie` must come from `soyokaze_cookie_new` or `soyokaze_cookie_parse`
/// and not have been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookie_free(cookie: *mut Cookie) {
    if !cookie.is_null() {
        drop(unsafe { Box::from_raw(cookie) });
    }
}

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

/// The name of the pair at `index`, borrowed from `cookie`.
///
/// # Safety
///
/// As [`soyokaze_cookie_count`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookie_name(cookie: *const Cookie, index: usize) -> Slice {
    Slice::maybe(unsafe { cookie.as_ref() }.and_then(|cookie| cookie.pairs.get(index)).map(|(name, _)| name.as_str()))
}

/// The value of the pair at `index`, borrowed from `cookie`.
///
/// # Safety
///
/// As [`soyokaze_cookie_count`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookie_value(cookie: *const Cookie, index: usize) -> Slice {
    Slice::maybe(unsafe { cookie.as_ref() }.and_then(|cookie| cookie.pairs.get(index)).map(|(_, value)| value.as_str()))
}

/// The value stored under this exact name, borrowed from `cookie`.
///
/// Absent when no pair carries the name.
///
/// # Safety
///
/// `cookie` 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_cookie_get(cookie: *const Cookie, name: *const u8, name_len: usize) -> Slice {
    let Some(name) = (unsafe { Slice::borrow_text(name, name_len) }) else {
        return Slice::ABSENT;
    };

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

/// Adds a pair at the end.
///
/// Returns whether it was added; it is refused when an argument is null or is
/// not UTF-8.
///
/// # Safety
///
/// `cookie` 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_cookie_append(cookie: *mut Cookie, name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> bool {
    let (Some(cookie), Some(name), Some(value)) = (unsafe { cookie.as_mut() }, unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) })
    else {
        return false;
    };

    cookie.pairs.push((name.to_owned(), value.to_owned()));
    true
}

/// Writes the pairs back out as a `Cookie` field value, owned by the caller.
///
/// # Safety
///
/// As [`soyokaze_cookie_count`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookie_build(cookie: *const Cookie) -> Buffer {
    match unsafe { cookie.as_ref() } {
        Some(cookie) => Buffer::new(cookie.build().into_bytes()),
        None => Buffer::EMPTY,
    }
}

/// Builds a cookie with no attributes set.
///
/// Returns null when an argument is null or not UTF-8.
///
/// # Safety
///
/// `name` and `value` must point to their stated number of readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_new(name: *const u8, name_len: usize, value: *const u8, value_len: usize) -> *mut SetCookie {
    let (Some(name), Some(value)) = (unsafe { Slice::borrow_text(name, name_len) }, unsafe { Slice::borrow_text(value, value_len) }) else {
        return std::ptr::null_mut();
    };

    Box::into_raw(Box::new(SetCookie::new(name, value)))
}

/// Reads a `Set-Cookie` field value.
///
/// # Safety
///
/// `value` must point to `value_len` readable octets, and `out` must be
/// writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_parse(value: *const u8, value_len: usize, out: *mut *mut SetCookie, error: *mut *mut ErrorHandle) -> Status {
    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

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

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

/// Releases a [`SetCookie`].
///
/// # Safety
///
/// `cookie` must come from `soyokaze_setcookie_new` or
/// `soyokaze_setcookie_parse` and not have been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_free(cookie: *mut SetCookie) {
    if !cookie.is_null() {
        drop(unsafe { Box::from_raw(cookie) });
    }
}

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

/// The cookie value, borrowed from `cookie`.
///
/// # Safety
///
/// As [`soyokaze_setcookie_name`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_value(cookie: *const SetCookie) -> Slice {
    Slice::maybe(unsafe { cookie.as_ref() }.map(|cookie| cookie.value.as_str()))
}

/// The `Expires` attribute, verbatim, or absent when there is none.
///
/// # Safety
///
/// As [`soyokaze_setcookie_name`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_expires(cookie: *const SetCookie) -> Slice {
    Slice::maybe(unsafe { cookie.as_ref() }.and_then(|cookie| cookie.expires.as_deref()))
}

/// Reads the `Max-Age` attribute through `out`, returning whether it is set.
///
/// `out` is written only when the attribute is there, so a caller may pass
/// null just to test for its presence.
///
/// # Safety
///
/// `cookie` must either be null or be a handle that has not been freed, and
/// `out` must either be null or be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_max_age(cookie: *const SetCookie, out: *mut i64) -> bool {
    let Some(max_age) = unsafe { cookie.as_ref() }.and_then(|cookie| cookie.max_age) else {
        return false;
    };

    if !out.is_null() {
        unsafe { *out = max_age };
    }

    true
}

/// The `Domain` attribute, or absent when the cookie is host-only.
///
/// # Safety
///
/// As [`soyokaze_setcookie_name`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_domain(cookie: *const SetCookie) -> Slice {
    Slice::maybe(unsafe { cookie.as_ref() }.and_then(|cookie| cookie.domain.as_deref()))
}

/// The `Path` attribute, or absent when the default path applies.
///
/// # Safety
///
/// As [`soyokaze_setcookie_name`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_path(cookie: *const SetCookie) -> Slice {
    Slice::maybe(unsafe { cookie.as_ref() }.and_then(|cookie| cookie.path.as_deref()))
}

/// Whether the `Secure` attribute is set.
///
/// # Safety
///
/// As [`soyokaze_setcookie_name`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_secure(cookie: *const SetCookie) -> bool {
    unsafe { cookie.as_ref() }.is_some_and(|cookie| cookie.secure)
}

/// Whether the `HttpOnly` attribute is set.
///
/// # Safety
///
/// As [`soyokaze_setcookie_name`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_httponly(cookie: *const SetCookie) -> bool {
    unsafe { cookie.as_ref() }.is_some_and(|cookie| cookie.httponly)
}

/// The `SameSite` attribute: `0` Strict, `1` Lax, `2` None, `-1` unset.
///
/// # Safety
///
/// As [`soyokaze_setcookie_name`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_samesite(cookie: *const SetCookie) -> i32 {
    match unsafe { cookie.as_ref() }.and_then(|cookie| cookie.samesite) {
        Some(SameSite::Strict) => 0,
        Some(SameSite::Lax) => 1,
        Some(SameSite::None) => 2,
        None => -1,
    }
}

/// Replaces the cookie value.
///
/// # Safety
///
/// `cookie` must either be null or be a handle that has not been freed, and
/// `value` must point to `value_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_set_value(cookie: *mut SetCookie, value: *const u8, value_len: usize) -> bool {
    let (Some(cookie), Some(value)) = (unsafe { cookie.as_mut() }, unsafe { Slice::borrow_text(value, value_len) }) else {
        return false;
    };

    cookie.value = value.to_owned();
    true
}

/// Sets the `Expires` attribute, or clears it with a null `value`.
///
/// # Safety
///
/// As [`soyokaze_setcookie_set_value`], except that a null `value` is allowed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_set_expires(cookie: *mut SetCookie, value: *const u8, value_len: usize) -> bool {
    let Some(cookie) = (unsafe { cookie.as_mut() }) else {
        return false;
    };

    if value.is_null() {
        cookie.expires = None;
        return true;
    }

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

    cookie.expires = Some(value.to_owned());
    true
}

/// Sets the `Max-Age` attribute, or clears it when `present` is false.
///
/// # Safety
///
/// `cookie` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_set_max_age(cookie: *mut SetCookie, present: bool, max_age: i64) -> bool {
    let Some(cookie) = (unsafe { cookie.as_mut() }) else {
        return false;
    };

    cookie.max_age = present.then_some(max_age);
    true
}

/// Sets the `Domain` attribute, or clears it with a null `value`.
///
/// # Safety
///
/// As [`soyokaze_setcookie_set_expires`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_set_domain(cookie: *mut SetCookie, value: *const u8, value_len: usize) -> bool {
    let Some(cookie) = (unsafe { cookie.as_mut() }) else {
        return false;
    };

    if value.is_null() {
        cookie.domain = None;
        return true;
    }

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

    cookie.domain = Some(value.to_owned());
    true
}

/// Sets the `Path` attribute, or clears it with a null `value`.
///
/// # Safety
///
/// As [`soyokaze_setcookie_set_expires`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_set_path(cookie: *mut SetCookie, value: *const u8, value_len: usize) -> bool {
    let Some(cookie) = (unsafe { cookie.as_mut() }) else {
        return false;
    };

    if value.is_null() {
        cookie.path = None;
        return true;
    }

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

    cookie.path = Some(value.to_owned());
    true
}

/// Sets or clears the `Secure` attribute.
///
/// # Safety
///
/// As [`soyokaze_setcookie_set_max_age`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_set_secure(cookie: *mut SetCookie, secure: bool) -> bool {
    let Some(cookie) = (unsafe { cookie.as_mut() }) else {
        return false;
    };

    cookie.secure = secure;
    true
}

/// Sets or clears the `HttpOnly` attribute.
///
/// # Safety
///
/// As [`soyokaze_setcookie_set_max_age`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_set_httponly(cookie: *mut SetCookie, httponly: bool) -> bool {
    let Some(cookie) = (unsafe { cookie.as_mut() }) else {
        return false;
    };

    cookie.httponly = httponly;
    true
}

/// Sets the `SameSite` attribute: `0` Strict, `1` Lax, `2` None, `-1` unset.
///
/// Any other number is refused.
///
/// # Safety
///
/// As [`soyokaze_setcookie_set_max_age`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_set_samesite(cookie: *mut SetCookie, samesite: i32) -> bool {
    let Some(cookie) = (unsafe { cookie.as_mut() }) else {
        return false;
    };

    cookie.samesite = match samesite {
        0 => Some(SameSite::Strict),
        1 => Some(SameSite::Lax),
        2 => Some(SameSite::None),
        -1 => None,
        _ => return false,
    };

    true
}

/// Writes the cookie out as a `Set-Cookie` field value, owned by the caller.
///
/// # Safety
///
/// `cookie` must be a handle that has not been freed, and `out` must be
/// writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_build(cookie: *const SetCookie, out: *mut Buffer, error: *mut *mut ErrorHandle) -> Status {
    let Some(cookie) = (unsafe { cookie.as_ref() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

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

    match cookie.build() {
        Ok(value) => {
            unsafe { *out = Buffer::new(value.into_bytes()) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Builds an empty [`CookieJar`].
///
/// A null `limits` takes every default. The jar reads the clock itself, so
/// lifetimes count from the moment a cookie is learned.
///
/// # Safety
///
/// `limits` must either be null or point to a readable [`Limits`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookiejar_new(limits: *const Limits) -> *mut CookieJar {
    Box::into_raw(Box::new(CookieJar::new().with_limits(unsafe { Limits::or_default(limits) })))
}

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

/// Takes in the `Set-Cookie` values a response for `url` carried.
///
/// Values that do not parse are skipped rather than failing the whole batch.
/// Returns whether the arguments were usable at all.
///
/// # Safety
///
/// `jar` and `url` must be handles that have not been freed, and `values`
/// must point to `value_count` readable slices whose own pointers are valid
/// UTF-8 text.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookiejar_learn(jar: *const CookieJar, url: *const URL, values: *const Slice, value_count: usize) -> bool {
    let (Some(jar), Some(url)) = (unsafe { jar.as_ref() }, unsafe { url.as_ref() }) else {
        return false;
    };

    if values.is_null() && value_count > 0 {
        return false;
    }

    let mut parsed = Vec::with_capacity(value_count);
    for index in 0..value_count {
        let slice = unsafe { *values.add(index) };
        let Some(value) = (unsafe { Slice::borrow_text(slice.data, slice.len) }) else {
            return false;
        };
        parsed.push(value);
    }

    jar.learn(url, &parsed, Instant::now());
    true
}

/// The `Cookie` field value for a request to `url`, owned by the caller.
///
/// An empty buffer with a null pointer means no cookie matched.
///
/// # Safety
///
/// `jar` and `url` must each either be null or be handles that have not been
/// freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookiejar_cookie(jar: *const CookieJar, url: *const URL) -> Buffer {
    let (Some(jar), Some(url)) = (unsafe { jar.as_ref() }, unsafe { url.as_ref() }) else {
        return Buffer::EMPTY;
    };

    match jar.cookie(url, Instant::now()) {
        Some(value) => Buffer::new(value.into_bytes()),
        None => Buffer::EMPTY,
    }
}

/// Drops every cookie that has expired.
///
/// # Safety
///
/// `jar` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookiejar_prune(jar: *const CookieJar) {
    if let Some(jar) = unsafe { jar.as_ref() } {
        jar.prune(Instant::now());
    }
}

/// How many cookies one jar may hold unless told otherwise.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_cookie_default_max_cookies() -> u32 {
    crate::cookies::CookieLimits::default().max_cookies
}

/// How many cookies one jar may hold per domain unless told otherwise.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_cookie_default_max_cookies_per_domain() -> u16 {
    crate::cookies::CookieLimits::default().max_cookies_per_domain
}

/// Whether an octet separates cookie pairs rather than belonging to one.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_cookie_is_separator(octet: u8) -> bool {
    Cookie::is_separator(octet)
}

/// How a `SameSite` attribute is written out, borrowed from the library.
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_samesite_name(samesite: i32) -> Slice {
    match SameSite::from_code(samesite) {
        Some(samesite) => Slice::text(samesite.as_str()),
        None => Slice::ABSENT,
    }
}

/// The `SameSite` attribute a name spells out, or `-1` when it spells none.
///
/// The name is matched case-insensitively, as the attribute is written.
///
/// # Safety
///
/// `name` must either be null or point to `name_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_samesite_parse(name: *const u8, name_len: usize) -> i32 {
    match unsafe { Slice::borrow_text(name, name_len) }.and_then(SameSite::parse) {
        Some(samesite) => samesite as i32,
        None => -1,
    }
}

impl SameSite {
    /// The attribute a wire code names, or `None` when it names none.
    ///
    /// A negative code stands for an absent attribute, which is how a caller
    /// says the cookie carries none.
    pub fn from_code(code: i32) -> Option<Self> {
        Some(match code {
            0 => Self::Strict,
            1 => Self::Lax,
            2 => Self::None,
            _ => return None,
        })
    }
}

/// Reads a `Max-Age` attribute, writing the seconds through `out`.
///
/// Returns whether it parsed. A value that is not a run of digits, optionally
/// signed, is refused; one too large to hold saturates rather than wrapping.
///
/// # Safety
///
/// `text` must either be null or point to `text_len` readable octets, and
/// `out` must either be null or be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_setcookie_age(text: *const u8, text_len: usize, out: *mut i64) -> bool {
    let Some(age) = unsafe { Slice::borrow_text(text, text_len) }.and_then(SetCookie::age) else {
        return false;
    };

    if !out.is_null() {
        unsafe { *out = age };
    }

    true
}

/// Whether a cookie's `Path` covers a request target.
///
/// # Safety
///
/// `target` and `path` must either be null or point to their stated number of
/// readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookie_path_matches(target: *const u8, target_len: usize, path: *const u8, path_len: usize) -> bool {
    let (Some(target), Some(path)) = (unsafe { Slice::borrow_text(target, target_len) }, unsafe { Slice::borrow_text(path, path_len) }) else {
        return false;
    };

    crate::cookies::StoredCookie::path_matches(target, path)
}

/// The `Path` a cookie takes when the attribute is absent, owned by the
/// caller.
///
/// # Safety
///
/// `target` must either be null or point to `target_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookie_default_path(target: *const u8, target_len: usize) -> Buffer {
    match unsafe { Slice::borrow_text(target, target_len) } {
        Some(target) => Buffer::new(crate::cookies::StoredCookie::default_path(target).into_bytes()),
        None => Buffer::EMPTY,
    }
}

/// How many cookies the jar is holding.
///
/// # Safety
///
/// `jar` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookiejar_count(jar: *const CookieJar) -> usize {
    match unsafe { jar.as_ref() } {
        Some(jar) => crate::helpers::sync::Lock::on(&jar.entries).len(),
        None => 0,
    }
}

/// How many cookies the jar may hold.
///
/// # Safety
///
/// As [`soyokaze_cookiejar_count`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookiejar_max_cookies(jar: *const CookieJar) -> u32 {
    unsafe { jar.as_ref() }.map_or(0, |jar| jar.limits.max_cookies)
}

/// How many cookies the jar may hold for one domain.
///
/// # Safety
///
/// As [`soyokaze_cookiejar_count`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookiejar_max_cookies_per_domain(jar: *const CookieJar) -> u16 {
    unsafe { jar.as_ref() }.map_or(0, |jar| jar.limits.max_cookies_per_domain)
}

/// A stored cookie, as the jar holds it.
///
/// The C half of [`StoredCookie`]. The text points into a buffer the caller
/// owns, filled by [`soyokaze_cookiejar_entry`] and freed with
/// `soyokaze_buffer_free`.
///
/// [`StoredCookie`]: crate::cookies::StoredCookie
#[repr(C)]
#[derive(Clone, Copy)]
pub struct StoredCookie {
    /// The cookie name.
    pub name: Slice,
    /// The cookie value.
    pub value: Slice,
    /// The domain the cookie is sent to.
    pub domain: Slice,
    /// Whether it is sent to that host alone rather than its subdomains too.
    pub host_only: bool,
    /// The path prefix the cookie is sent under.
    pub path: Slice,
    /// Whether it is sent over secure transports only.
    pub secure: bool,
    /// How many seconds until it expires, or `-1` when it lasts the session.
    pub expires_in: f64,
}

/// Reads the cookie at `index` out of the jar.
///
/// The four pieces of text are written into one buffer, handed back through
/// `storage`, which the caller frees with `soyokaze_buffer_free` once it is
/// done with the entry. Returns whether there was a cookie at `index`.
///
/// # Safety
///
/// As [`soyokaze_cookiejar_count`], and `out` and `storage` must either be
/// null or be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_cookiejar_entry(jar: *const CookieJar, index: usize, out: *mut StoredCookie, storage: *mut Buffer) -> bool {
    let Some(jar) = (unsafe { jar.as_ref() }) else {
        return false;
    };

    let entries = crate::helpers::sync::Lock::on(&jar.entries);

    let Some(entry) = entries.get(index) else {
        return false;
    };

    let mut octets = Vec::with_capacity(entry.name.len() + entry.value.len() + entry.domain.len() + entry.path.len());
    let mut spans = Vec::with_capacity(4);

    for part in [&entry.name, &entry.value, &entry.domain, &entry.path] {
        spans.push((octets.len(), part.len()));
        octets.extend_from_slice(part.as_bytes());
    }

    let expires_in = match entry.expires {
        Some(expires) => expires.saturating_duration_since(Instant::now()).as_secs_f64(),
        None => -1.0,
    };

    let buffer = Buffer::new(octets);
    let view = |(at, len): (usize, usize)| Slice { data: unsafe { buffer.data.add(at) }, len };

    if !out.is_null() {
        unsafe {
            *out = StoredCookie {
                name: view(spans[0]),
                value: view(spans[1]),
                domain: view(spans[2]),
                host_only: entry.host_only,
                path: view(spans[3]),
                secure: entry.secure,
                expires_in,
            }
        };
    }

    match storage.is_null() {
        true => unsafe { crate::ffi::soyokaze_buffer_free(buffer) },
        false => unsafe { *storage = buffer },
    }

    true
}