sip-header 1.0.0-beta.2

SIP header field parsers: Via, Warning, Auth, Accept, Contact, Call-Info, History-Info, Geolocation, Security, and full IANA header catalog
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
//! SIP message text extraction utilities.
//!
//! - [`SipMessageHeaders`]: the header rows of a raw message, a
//!   [`SipHeaderRows`] store every typed accessor reads
//! - [`extract_header`], [`extract_all_headers`], [`extract_header_block`]:
//!   the same rows as owned strings
//! - [`extract_request_line`]: the request line's parts as received, which
//!   parses its Request-URI, and [`extract_request_uri`]: that URI alone
//!   (RFC 3261 §7.1)
//! - [`extract_body`]: the message body following the header block
//!   (RFC 3261 §7.4)
//!
//! Gated behind the `message` feature (enabled by default).

use std::borrow::Cow;

use sip_header_catalog::{NameMatcher, RowError, SipHeader, SipHeaderFields, SipHeaderRows};
use sip_uri::UriParse;

use crate::diagnostic::{Field, ParseWarning, Parsed, WarningCode};
use crate::error::{Fault, FaultCode, ParseError};
use crate::span::Span;

/// Split at the first empty line (after `\r` stripping) per RFC 3261 §7.3.1.
///
/// Returns the header block (blank line excluded) and the byte offset of
/// the first body byte, or `None` when the message has no blank line.
fn split_at_blank_line(message: &str) -> (&str, Option<usize>) {
    let mut offset = 0;
    for line in message.split('\n') {
        let stripped = line
            .strip_suffix('\r')
            .unwrap_or(line);
        if stripped.is_empty() {
            let body_start = offset + line.len() + 1;
            return (
                &message[..offset],
                (body_start <= message.len()).then_some(body_start),
            );
        }
        offset += line.len() + 1;
    }
    (message, None)
}

/// Extract the message body — everything after the blank line that ends
/// the header block.
///
/// Uses the same boundary rule as [`SipMessageHeaders`]: the first empty
/// line after `\r` stripping, so bare-`\n` messages behave the same as CRLF
/// ones. The body is returned verbatim — no trimming, unfolding, or
/// decoding — and `Content-Length` is not consulted; the body is the rest
/// of the given text. Returns `None` when the message has no blank line or
/// nothing follows it.
///
/// # Examples
///
/// ```
/// let msg = "INVITE sip:bob@example.com SIP/2.0\r\n\
///            Content-Type: application/sdp\r\n\
///            \r\n\
///            v=0\r\n";
/// assert_eq!(sip_header::extract_body(msg), Some("v=0\r\n"));
/// ```
pub fn extract_body(message: &str) -> Option<&str> {
    let (_, body_start) = split_at_blank_line(message);
    let body = &message[body_start?..];
    (!body.is_empty()).then_some(body)
}

/// The header rows of a raw SIP message, in wire order.
///
/// Reads the lines up to the blank line that ends the header block. A
/// continuation line (starting with SP or HTAB) unfolds into the row above
/// it with one SP (RFC 3261 §7.3.1); only such rows are held owned, every
/// other row borrows the message. Values are trimmed; names are kept as
/// sent, compact forms included.
///
/// As a [`SipHeaderRows`] store it matches names as
/// [`SipHeader::name_matches`] does, returning every spelling's rows in wire
/// order, so every [`SipHeaderLookup`](crate::SipHeaderLookup) accessor
/// reads it. The rows a parsed value's positions point into are these
/// trimmed, unfolded rows, not the lines of the message.
///
/// A line that is neither a header nor a continuation of one is skipped,
/// and its byte offset reported by [`skipped`](Self::skipped), unless it is
/// the request or status line [`new`](Self::new) exempts.
///
/// The rows are a [`SipHeaderFields`], which [`fields`](Self::fields) and
/// [`into_fields`](Self::into_fields) hand out.
///
/// ```
/// use sip_header::{SipHeaderLookup, SipMessageHeaders};
///
/// let msg = "INVITE sip:bob@example.com SIP/2.0\r\n\
///            Via: SIP/2.0/UDP 198.51.100.1\r\n\
///            v: SIP/2.0/TCP 203.0.113.5\r\n\
///            \r\n";
/// let headers = SipMessageHeaders::new(msg);
/// assert_eq!(headers.via()?.unwrap().len(), 2);
/// assert!(headers.skipped().is_empty());
/// assert_eq!(headers.fields().iter().nth(1), Some(("v", "SIP/2.0/TCP 203.0.113.5")));
/// # Ok::<(), sip_header::ParseError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SipMessageHeaders<'a> {
    fields: SipHeaderFields<'a>,
    skipped: Vec<usize>,
}

impl<'a> SipMessageHeaders<'a> {
    /// Read the header block of `message`, exempting a first line that is a
    /// request or status line (RFC 3261 §7.1, §7.2).
    pub fn new(message: &'a str) -> Self {
        Self::read(message, true)
    }

    /// Read `block`, header lines with no start line, up to its first blank
    /// line; every line that is not a row is [`skipped`](Self::skipped).
    pub fn from_header_block(block: &'a str) -> Self {
        Self::read(block, false)
    }

    fn read(message: &'a str, start_line: bool) -> Self {
        let (block, _) = split_at_blank_line(message);
        let mut fields = SipHeaderFields::new();
        let mut skipped = Vec::new();
        // The last header row, still open to continuation lines.
        let mut open: Option<(&'a str, Cow<'a, str>)> = None;
        let mut offset = 0;
        for (i, raw_line) in block
            .split('\n')
            .enumerate()
        {
            let at = offset;
            offset += raw_line.len() + 1;
            let line = raw_line
                .strip_suffix('\r')
                .unwrap_or(raw_line);
            if line.is_empty() {
                continue;
            }
            if line.starts_with([' ', '\t']) {
                match &mut open {
                    Some((_, value)) => append_folded(value, line),
                    None => skipped.push(at),
                }
                continue;
            }
            if let Some((name, value)) = open.take() {
                fields.push(name, value);
            }
            match header_line(line) {
                Some((name, value)) => open = Some((name, Cow::Borrowed(value))),
                None if i == 0 && start_line && is_start_line(line) => {}
                None => skipped.push(at),
            }
        }
        if let Some((name, value)) = open {
            fields.push(name, value);
        }
        SipMessageHeaders { fields, skipped }
    }

    /// Every row as `(name as sent, value)`, in wire order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&str, &str)> + '_ {
        self.fields
            .iter()
    }

    /// Number of rows.
    pub fn len(&self) -> usize {
        self.fields
            .len()
    }

    /// Whether the message holds no header row.
    pub fn is_empty(&self) -> bool {
        self.fields
            .is_empty()
    }

    /// The rows.
    pub fn fields(&self) -> &SipHeaderFields<'a> {
        &self.fields
    }

    /// The rows, without the skipped offsets.
    pub fn into_fields(self) -> SipHeaderFields<'a> {
        self.fields
    }

    /// Byte offsets into the message of the lines that were skipped, in
    /// order: a line without a `:` after a `token` name (RFC 3261 §7.3
    /// `header-name = token`) other than a start line [`new`](Self::new)
    /// exempts, or a continuation with no header above it.
    pub fn skipped(&self) -> &[usize] {
        &self.skipped
    }
}

impl SipHeaderRows for SipMessageHeaders<'_> {
    fn sip_header_rows_str<'a>(&'a self, name: &str) -> Result<Vec<&'a str>, RowError> {
        self.fields
            .sip_header_rows_str(name)
    }
}

/// `name: value` with a `token` name, SWS before the colon allowed.
fn header_line(line: &str) -> Option<(&str, &str)> {
    let (name, value) = line.split_once(':')?;
    let name = name.trim_end_matches([' ', '\t']);
    crate::is_token(name).then(|| (name, value.trim()))
}

/// Unfold a continuation line into `value`, replacing the folding LWS with
/// one SP (RFC 3261 §7.3.1).
fn append_folded(value: &mut Cow<'_, str>, line: &str) {
    let line = line.trim();
    if line.is_empty() {
        return;
    }
    let value = value.to_mut();
    if !value.is_empty() {
        value.push(' ');
    }
    value.push_str(line);
}

/// Extract all occurrences of a header from a raw SIP message, one string
/// per occurrence, as [`SipMessageHeaders`] reads them.
///
/// Header name matching is case-insensitive (RFC 3261 §7.3.5) and
/// recognizes compact header forms (RFC 3261 §7.3.3): searching for `"From"`
/// also matches `f:`, and searching for `"f"` also matches `From:`. Values
/// are **not** comma-joined, per RFC 3261 §7.3.1, which forbids joining for
/// Authorization, Proxy-Authorization, WWW-Authenticate, and
/// Proxy-Authenticate.
///
/// Returns an empty `Vec` if no header with the given name is found.
pub fn extract_header(message: &str, name: &str) -> Vec<String> {
    let matcher = NameMatcher::new(name);
    SipMessageHeaders::new(message)
        .iter()
        .filter(|(wire, _)| matcher.matches(wire))
        .map(|(_, value)| value.to_string())
        .collect()
}

/// Every header row of a message, owned, with the lines that were skipped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtractedHeaders {
    /// `(name as sent, value)` in wire order; compact names stay compact.
    pub headers: SipHeaderFields<'static>,
    /// Byte offsets of the skipped lines, as
    /// [`SipMessageHeaders::skipped`] reports them.
    pub skipped: Vec<usize>,
}

/// Extract all headers from a raw SIP message as owned name-value pairs,
/// as [`SipMessageHeaders::new`] reads them, exempting its start line.
///
/// ```
/// use sip_header::extract_all_headers;
///
/// let msg = "INVITE sip:bob@example.com SIP/2.0\r\n\
///            f: Alice <sip:alice@example.com>\r\n\
///            not a header\r\n\
///            \r\n";
/// let all = extract_all_headers(msg);
/// assert_eq!(all.headers.iter().next(), Some(("f", "Alice <sip:alice@example.com>")));
/// assert_eq!(all.skipped, [msg.find("not").unwrap()]);
/// ```
pub fn extract_all_headers(message: &str) -> ExtractedHeaders {
    owned(SipMessageHeaders::new(message))
}

/// Extract all headers from a header block with no start line as owned
/// name-value pairs, as [`SipMessageHeaders::from_header_block`] reads
/// them, reporting every line that is not a row.
///
/// ```
/// use sip_header::extract_header_block;
///
/// let all = extract_header_block("X-A/B: 1\r\nCall-ID: a@example.com\r\n");
/// assert_eq!(all.headers.iter().next(), Some(("Call-ID", "a@example.com")));
/// assert_eq!(all.skipped, [0]);
/// ```
pub fn extract_header_block(block: &str) -> ExtractedHeaders {
    owned(SipMessageHeaders::from_header_block(block))
}

fn owned(headers: SipMessageHeaders<'_>) -> ExtractedHeaders {
    let SipMessageHeaders { fields, skipped } = headers;
    ExtractedHeaders {
        headers: fields.into_owned(),
        skipped,
    }
}

/// The Request-URI of a SIP request (RFC 3261 §7.1
/// `Method SP Request-URI SP SIP-Version`), parsed leniently:
/// [`RequestLine::uri`] on [`extract_request_line`]'s line.
///
/// `Ok(None)` for a status line (`SIP/2.0 200 OK`). Errors as
/// [`extract_request_line`] does, and when the URI yields no value; error
/// positions are byte offsets into the first line.
///
/// ```
/// let msg = "INVITE sip:bob@example.com SIP/2.0\r\n\r\n";
/// let uri = sip_header::extract_request_uri(msg)?.unwrap();
/// assert_eq!(uri.to_string(), "sip:bob@example.com");
/// # Ok::<(), sip_header::ParseError>(())
/// ```
pub fn extract_request_uri(message: &str) -> Result<Option<sip_uri::Uri>, ParseError> {
    extract_request_line(message)?
        .map(|line| line.uri())
        .transpose()
}

/// [`RequestLine::uri_strict`] on [`extract_request_line`]'s line.
pub fn extract_request_uri_strict(message: &str) -> Result<Option<sip_uri::Uri>, ParseError> {
    extract_request_line(message)?
        .map(|line| line.uri_strict())
        .transpose()
}

/// [`RequestLine::uri_with_warnings`] on [`extract_request_line`]'s line;
/// call those two to keep the line's spans as well.
///
/// ```
/// use sip_header::WarningCode;
///
/// let msg = "INVITE  sip:bob@example.com SIP/2.0\r\n\r\n";
/// let parsed = sip_header::extract_request_uri_with_warnings(msg)?.unwrap();
/// assert_eq!(parsed.value.to_string(), "sip:bob@example.com");
/// assert_eq!(parsed.warnings[0].code, WarningCode::RequestLineWhitespace);
/// assert_eq!(parsed.warnings[0].position, Some(6));
/// # Ok::<(), sip_header::ParseError>(())
/// ```
pub fn extract_request_uri_with_warnings(
    message: &str,
) -> Result<Option<Parsed<sip_uri::Uri>>, ParseError> {
    extract_request_line(message)?
        .map(|line| line.uri_with_warnings())
        .transpose()
}

/// The request line of a SIP request (RFC 3261 §7.1 `Method SP Request-URI
/// SP SIP-Version`), its three parts borrowed as received.
///
/// Spans and positions are byte offsets into the message, whose first line
/// this is; they carry no row index.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RequestLine<'a> {
    method: &'a str,
    uri_text: &'a str,
    version: &'a str,
    method_span: Span,
    uri_span: Span,
    version_span: Span,
    warnings: Vec<ParseWarning>,
}

impl<'a> RequestLine<'a> {
    /// The method, a `token`.
    pub fn method(&self) -> &'a str {
        self.method
    }

    /// The Request-URI's text between its separators, unparsed.
    pub fn uri_text(&self) -> &'a str {
        self.uri_text
    }

    /// The version, starting `SIP/`.
    pub fn version(&self) -> &'a str {
        self.version
    }

    /// Where the method is in the message.
    pub fn method_span(&self) -> Span {
        self.method_span
    }

    /// Where the Request-URI is in the message.
    pub fn uri_span(&self) -> Span {
        self.uri_span
    }

    /// Where the version is in the message.
    pub fn version_span(&self) -> Span {
        self.version_span
    }

    /// [`WarningCode::RequestLineWhitespace`] at each gap between or
    /// around the parts other than the one SP each allows, in line order.
    pub fn warnings(&self) -> &[ParseWarning] {
        &self.warnings
    }

    /// The Request-URI parsed leniently: the value
    /// [`uri_with_warnings`](Self::uri_with_warnings) returns, without its
    /// warnings.
    pub fn uri(&self) -> Result<sip_uri::Uri, ParseError> {
        self.uri_with_warnings()
            .map(|p| p.value)
    }

    /// [`uri`](Self::uri), refusing the first warning
    /// [`uri_with_warnings`](Self::uri_with_warnings) reports.
    pub fn uri_strict(&self) -> Result<sip_uri::Uri, ParseError> {
        self.uri_with_warnings()?
            .into_strict()
    }

    /// The Request-URI parsed, with the line's [`warnings`](Self::warnings)
    /// and the URI's own, in line order; errors when the URI yields no
    /// value. Positions are byte offsets into the message.
    ///
    /// ```
    /// use sip_header::{extract_request_line, WarningCode};
    ///
    /// let msg = "INVITE  sip:bob@example.com SIP/2.0\r\n\r\n";
    /// let line = extract_request_line(msg)?.unwrap();
    /// let parsed = line.uri_with_warnings()?;
    /// assert_eq!(parsed.value.to_string(), "sip:bob@example.com");
    /// assert_eq!(parsed.warnings[0].code, WarningCode::RequestLineWhitespace);
    /// assert_eq!(parsed.warnings[0].position, Some(6));
    /// assert_eq!(line.uri_span().get(msg), Ok("sip:bob@example.com"));
    /// # Ok::<(), sip_header::ParseError>(())
    /// ```
    pub fn uri_with_warnings(&self) -> Result<Parsed<sip_uri::Uri>, ParseError> {
        let uri_at = self
            .uri_span
            .range()
            .start;
        let parsed = sip_uri::Uri::parse_with_warnings(self.uri_text).map_err(|e| {
            ParseError::uri(
                e,
                uri_at,
                self.uri_text
                    .len(),
            )
        })?;
        let warnings = self
            .warnings
            .iter()
            .copied()
            .chain(
                parsed
                    .warnings
                    .into_iter()
                    .map(|w| ParseWarning::from_uri(w, uri_at)),
            )
            .collect();
        Ok(Parsed::new(parsed.value, warnings))
    }
}

/// The request line of `message`, its parts borrowed as received.
///
/// `Ok(None)` for a status line (`SIP/2.0 200 OK`). Errors when the message
/// is empty, the method is not a `token` or the version does not start
/// `SIP/`; a first line without three parts is
/// [`FaultCode::Missing`] spanning the whole line, so its text stays
/// reachable through [`ParseError::span`].
///
/// ```
/// let msg = "INVITE  sip:bob@example.com SIP/2.0\r\n\r\n";
/// let line = sip_header::extract_request_line(msg)?.unwrap();
/// assert_eq!(line.uri_text(), "sip:bob@example.com");
/// assert_eq!(line.uri_span().get(msg), Ok("sip:bob@example.com"));
/// assert_eq!(line.warnings()[0].position, Some(6));
///
/// let e = sip_header::extract_request_line("INVITE sip:a b@example.com SIP/2.0\r\n").unwrap_err();
/// assert_eq!(e.span().unwrap().range(), 0..34);
/// # Ok::<(), sip_header::ParseError>(())
/// ```
pub fn extract_request_line(message: &str) -> Result<Option<RequestLine<'_>>, ParseError> {
    let first = message
        .split('\n')
        .next()
        .unwrap_or_default();
    request_line(
        first
            .strip_suffix('\r')
            .unwrap_or(first),
    )
}

/// A request line's (RFC 3261 §7.1) or status line's (§7.2) shape, as
/// [`extract_request_line`] splits it.
fn is_start_line(line: &str) -> bool {
    let mut parts = line.split_whitespace();
    let status = parts
        .next()
        .is_some_and(|v| v.starts_with("SIP/"))
        && parts
            .next()
            .is_some_and(|code| {
                code.len() == 3
                    && code
                        .bytes()
                        .all(|b| b.is_ascii_digit())
            });
    status || matches!(request_line(line), Ok(Some(_)))
}

fn request_line(first: &str) -> Result<Option<RequestLine<'_>>, ParseError> {
    if first.is_empty() {
        return Err(ParseError::empty(Field::Value));
    }
    let parts: Vec<&str> = first
        .split_whitespace()
        .collect();
    if parts
        .first()
        .is_some_and(|p| p.starts_with("SIP/"))
    {
        return Ok(None);
    }
    let [method, uri_text, version] = parts.as_slice() else {
        return Err(ParseError::Malformed(
            Fault::new(Field::Value, FaultCode::Missing)
                .at(0)
                .to(first.len()),
        ));
    };
    if !crate::is_token(method) {
        return Err(ParseError::malformed(
            Field::Value,
            FaultCode::InvalidChar,
            Some(0),
        ));
    }
    if !version.starts_with("SIP/") {
        return Err(ParseError::malformed(
            Field::Value,
            FaultCode::Missing,
            Some(crate::offset_in(first, version)),
        ));
    }
    let span = |part: &str| {
        let at = crate::offset_in(first, part);
        Span::new(at..at + part.len())
    };
    Ok(Some(RequestLine {
        method,
        uri_text,
        version,
        method_span: span(method),
        uri_span: span(uri_text),
        version_span: span(version),
        warnings: spacing_breaches(first, &parts),
    }))
}

/// A [`WarningCode::RequestLineWhitespace`] at each gap around `parts`, the
/// words of `line`, that is not the one SP the request line allows.
fn spacing_breaches(line: &str, parts: &[&str]) -> Vec<ParseWarning> {
    let mut warnings = Vec::new();
    let mut end = 0;
    for (i, part) in parts
        .iter()
        .enumerate()
    {
        let start = crate::offset_in(line, part);
        let gap = &line[end..start];
        if gap != if i == 0 { "" } else { " " } {
            warnings
                .push(ParseWarning::new(Field::Value, WarningCode::RequestLineWhitespace).at(end));
        }
        end = start + part.len();
    }
    if end < line.len() {
        warnings.push(ParseWarning::new(Field::Value, WarningCode::RequestLineWhitespace).at(end));
    }
    warnings
}

mod sealed {
    pub trait Sealed {}
}

impl sealed::Sealed for SipHeader {}

/// Extraction of a catalog header from raw SIP message text.
pub trait SipHeaderExtract: sealed::Sealed {
    /// Extract all occurrences of this header from a raw SIP message.
    ///
    /// Recognizes both the canonical header name and its compact form
    /// (RFC 3261 §7.3.3). For example, `SipHeader::From.extract_from(msg)`
    /// matches both `From:` and `f:` lines.
    fn extract_from(&self, message: &str) -> Vec<String>;
}

impl SipHeaderExtract for SipHeader {
    fn extract_from(&self, message: &str) -> Vec<String> {
        extract_header(message, self.as_str())
    }
}

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

    const SAMPLE_INVITE: &str = "\
INVITE sip:bob@biloxi.example.com SIP/2.0\r\n\
Via: SIP/2.0/UDP pc33.atlanta.example.com;branch=z9hG4bK776asdhds\r\n\
Via: SIP/2.0/UDP bigbox3.site3.atlanta.example.com;branch=z9hG4bKnashds8\r\n\
Max-Forwards: 70\r\n\
To: Bob <sip:bob@biloxi.example.com>\r\n\
From: Alice <sip:alice@atlanta.example.com>;tag=1928301774\r\n\
Call-ID: a84b4c76e66710@pc33.atlanta.example.com\r\n\
CSeq: 314159 INVITE\r\n\
Contact: <sip:alice@pc33.atlanta.example.com>\r\n\
Content-Type: application/sdp\r\n\
Content-Length: 142\r\n\
\r\n\
v=0\r\n\
o=alice 2890844526 2890844526 IN IP4 pc33.atlanta.example.com\r\n";

    #[test]
    fn basic_extraction() {
        let from = extract_header(SAMPLE_INVITE, "From");
        assert_eq!(from.len(), 1);
        assert_eq!(
            from[0],
            "Alice <sip:alice@atlanta.example.com>;tag=1928301774"
        );

        let call_id = extract_header(SAMPLE_INVITE, "Call-ID");
        assert_eq!(call_id.len(), 1);
        assert_eq!(call_id[0], "a84b4c76e66710@pc33.atlanta.example.com");

        let cseq = extract_header(SAMPLE_INVITE, "CSeq");
        assert_eq!(cseq.len(), 1);
        assert_eq!(cseq[0], "314159 INVITE");
    }

    #[test]
    fn case_insensitive_name() {
        let expected = "Alice <sip:alice@atlanta.example.com>;tag=1928301774";
        assert_eq!(extract_header(SAMPLE_INVITE, "from")[0], expected);
        assert_eq!(extract_header(SAMPLE_INVITE, "FROM")[0], expected);
        assert_eq!(extract_header(SAMPLE_INVITE, "From")[0], expected);
    }

    #[test]
    fn header_folding() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Subject: I know you're there,\r\n",
            " pick up the phone\r\n",
            " and talk to me!\r\n",
            "\r\n",
        );
        let result = extract_header(msg, "Subject");
        assert_eq!(result.len(), 1);
        assert_eq!(
            result[0],
            "I know you're there, pick up the phone and talk to me!"
        );
    }

    #[test]
    fn multiple_occurrences_separate() {
        let via = extract_header(SAMPLE_INVITE, "Via");
        assert_eq!(via.len(), 2);
        assert_eq!(
            via[0],
            "SIP/2.0/UDP pc33.atlanta.example.com;branch=z9hG4bK776asdhds"
        );
        assert_eq!(
            via[1],
            "SIP/2.0/UDP bigbox3.site3.atlanta.example.com;branch=z9hG4bKnashds8"
        );
    }

    #[test]
    fn stops_at_blank_line() {
        assert!(extract_header(SAMPLE_INVITE, "o").is_empty());
    }

    #[test]
    fn bare_lf_line_endings() {
        let msg = "SIP/2.0 200 OK\n\
                   From: Alice <sip:alice@host>\n\
                   To: Bob <sip:bob@host>\n\
                   \n\
                   body\n";
        let from = extract_header(msg, "From");
        assert_eq!(from.len(), 1);
        assert_eq!(from[0], "Alice <sip:alice@host>");
    }

    #[test]
    fn missing_header_returns_empty() {
        assert!(extract_header(SAMPLE_INVITE, "X-Custom").is_empty());
    }

    #[test]
    fn empty_message() {
        assert!(extract_header("", "From").is_empty());
    }

    #[test]
    fn request_line_not_matched() {
        assert!(extract_header(SAMPLE_INVITE, "INVITE sip").is_empty());
    }

    #[test]
    fn value_leading_whitespace_trimmed() {
        let msg = "SIP/2.0 200 OK\r\n\
                   From:   Alice <sip:alice@host>\r\n\
                   \r\n";
        let from = extract_header(msg, "From");
        assert_eq!(from.len(), 1);
        assert_eq!(from[0], "Alice <sip:alice@host>");
    }

    #[test]
    fn folding_on_multiple_occurrence() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Via: SIP/2.0/UDP first.example.com\r\n",
            " ;branch=z9hG4bKaaa\r\n",
            "Via: SIP/2.0/UDP second.example.com;branch=z9hG4bKbbb\r\n",
            "\r\n",
        );
        let via = extract_header(msg, "Via");
        assert_eq!(via.len(), 2);
        assert_eq!(via[0], "SIP/2.0/UDP first.example.com ;branch=z9hG4bKaaa");
        assert_eq!(via[1], "SIP/2.0/UDP second.example.com;branch=z9hG4bKbbb");
    }

    #[test]
    fn empty_header_value() {
        let msg = "SIP/2.0 200 OK\r\n\
                   Subject:\r\n\
                   From: Alice <sip:alice@host>\r\n\
                   \r\n";
        let subject = extract_header(msg, "Subject");
        assert_eq!(subject.len(), 1);
        assert_eq!(subject[0], "");
    }

    #[test]
    fn tab_folding() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Subject: hello\r\n",
            "\tworld\r\n",
            "\r\n",
        );
        let subject = extract_header(msg, "Subject");
        assert_eq!(subject.len(), 1);
        assert_eq!(subject[0], "hello world");
    }

    // -- Compact form tests (RFC 3261 §7.3.3) --

    #[test]
    fn compact_form_from() {
        let msg = "SIP/2.0 200 OK\r\nf: Alice <sip:alice@host>\r\n\r\n";
        assert_eq!(extract_header(msg, "From")[0], "Alice <sip:alice@host>");
        assert_eq!(extract_header(msg, "f")[0], "Alice <sip:alice@host>");
    }

    #[test]
    fn compact_form_via() {
        let msg = "SIP/2.0 200 OK\r\nv: SIP/2.0/UDP host\r\n\r\n";
        assert_eq!(extract_header(msg, "Via")[0], "SIP/2.0/UDP host");
        assert_eq!(extract_header(msg, "v")[0], "SIP/2.0/UDP host");
    }

    #[test]
    fn compact_form_mixed_with_full() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "f: Alice <sip:alice@host>;tag=a\r\n",
            "t: Bob <sip:bob@host>;tag=b\r\n",
            "i: call-1@host\r\n",
            "m: <sip:alice@192.0.2.1>\r\n",
            "Content-Type: application/sdp\r\n",
            "\r\n",
        );
        assert_eq!(
            extract_header(msg, "From")[0],
            "Alice <sip:alice@host>;tag=a"
        );
        assert_eq!(extract_header(msg, "To")[0], "Bob <sip:bob@host>;tag=b");
        assert_eq!(extract_header(msg, "Call-ID")[0], "call-1@host");
        assert_eq!(extract_header(msg, "Contact")[0], "<sip:alice@192.0.2.1>");
        assert_eq!(extract_header(msg, "Content-Type")[0], "application/sdp");
        assert_eq!(extract_header(msg, "c")[0], "application/sdp");
    }

    #[test]
    fn compact_form_case_insensitive() {
        let msg = "SIP/2.0 200 OK\r\nF: Alice <sip:alice@host>\r\n\r\n";
        assert_eq!(extract_header(msg, "From")[0], "Alice <sip:alice@host>");
    }

    #[test]
    fn compact_form_unknown_single_char() {
        let msg = "SIP/2.0 200 OK\r\nz: something\r\n\r\n";
        assert_eq!(extract_header(msg, "z")[0], "something");
        assert!(extract_header(msg, "From").is_empty());
    }

    // -- Integration pipeline tests: extract_header → existing parsers --

    const NG911_INVITE: &str = concat!(
        "INVITE sip:urn:service:sos@bcf.example.com SIP/2.0\r\n",
        "Via: SIP/2.0/TLS proxy.example.com;branch=z9hG4bK776\r\n",
        "From: \"Caller Name\" <sip:+15551234567@orig.example.com>;tag=abc123\r\n",
        "To: <sip:urn:service:sos@bcf.example.com>\r\n",
        "Call-ID: ng911-call-42@orig.example.com\r\n",
        "P-Asserted-Identity: \"EXAMPLE CO\" <sip:+15551234567@198.51.100.1>\r\n",
        "Call-Info: <urn:emergency:uid:callid:abc:bcf.example.com>;purpose=emergency-CallId,",
        "<https://adr.example.com/serviceInfo?t=x>;purpose=EmergencyCallData.ServiceInfo\r\n",
        "Geolocation: <cid:loc-id-1234>, <https://lis.example.com/held/test>\r\n",
        "Content-Type: application/sdp\r\n",
        "\r\n",
        "v=0\r\n",
    );

    #[test]
    fn extract_and_parse_call_info() {
        use crate::uri_info::UriInfo;

        let raw = extract_header(NG911_INVITE, "Call-Info");
        assert_eq!(raw.len(), 1);
        let ci = UriInfo::parse(&raw[0]).unwrap();
        assert_eq!(ci.len(), 2);
        assert_eq!(ci.entries()[0].purpose(), Some("emergency-CallId"));
        assert!(ci
            .entries()
            .iter()
            .any(|e| e.purpose() == Some("EmergencyCallData.ServiceInfo")));
    }

    #[test]
    fn extract_and_parse_p_asserted_identity() {
        use crate::header_addr::SipHeaderAddr;

        let raw = extract_header(NG911_INVITE, "P-Asserted-Identity");
        assert_eq!(raw.len(), 1);
        let pai = SipHeaderAddr::parse(&raw[0]).unwrap();
        assert_eq!(pai.display_name(), Some("EXAMPLE CO"));
        assert!(pai
            .uri()
            .to_string()
            .contains("+15551234567"));
    }

    #[test]
    fn extract_and_parse_multi_pai() {
        use crate::header_addr::SipHeaderAddr;

        let msg = concat!(
            "INVITE sip:sos@psap.example.com SIP/2.0\r\n",
            "P-Asserted-Identity: \"EXAMPLE CO\" <sip:+15551234567@198.51.100.1>\r\n",
            "P-Asserted-Identity: <tel:+15551234567>\r\n",
            "\r\n",
        );
        let raw = extract_header(msg, "P-Asserted-Identity");
        assert_eq!(raw.len(), 2);
        let pai0 = SipHeaderAddr::parse(&raw[0]).unwrap();
        assert_eq!(pai0.display_name(), Some("EXAMPLE CO"));
        let pai1 = SipHeaderAddr::parse(&raw[1]).unwrap();
        assert!(pai1
            .uri()
            .to_string()
            .contains("+15551234567"));
    }

    #[test]
    fn extract_and_parse_geolocation() {
        use crate::geolocation::SipGeolocation;

        let raw = extract_header(NG911_INVITE, "Geolocation");
        assert_eq!(raw.len(), 1);
        let geo = SipGeolocation::parse(&raw[0]).unwrap();
        assert_eq!(geo.len(), 2);
        assert_eq!(geo.cid(), Some("loc-id-1234"));
        assert!(geo
            .url()
            .unwrap()
            .to_string()
            .contains("lis.example.com"));
    }

    #[test]
    fn extract_and_parse_from_to() {
        use crate::header_addr::SipHeaderAddr;

        let from_raw = extract_header(NG911_INVITE, "From");
        assert_eq!(from_raw.len(), 1);
        let from = SipHeaderAddr::parse(&from_raw[0]).unwrap();
        assert_eq!(from.display_name(), Some("Caller Name"));
        assert_eq!(from.tag(), Some("abc123"));

        let to_raw = extract_header(NG911_INVITE, "To");
        assert_eq!(to_raw.len(), 1);
        let to = SipHeaderAddr::parse(&to_raw[0]).unwrap();
        assert_eq!(
            to.uri()
                .to_string(),
            "sip:urn:service%3Asos@bcf.example.com"
        );
    }

    // -- extract_request_uri tests (RFC 3261 §7.1) --

    fn request_uri(msg: &str) -> Option<String> {
        extract_request_uri(msg)
            .unwrap()
            .map(|u| u.to_string())
    }

    #[test]
    fn extract_request_uri_invite() {
        let msg = "INVITE urn:service:sos SIP/2.0\r\nTo: <urn:service:sos>\r\n\r\n";
        assert_eq!(request_uri(msg), Some("urn:service:sos".into()));
    }

    #[test]
    fn extract_request_uri_sip() {
        let msg = "INVITE sip:+15550001234@198.51.100.1:5060 SIP/2.0\r\n\r\n";
        assert_eq!(
            request_uri(msg),
            Some("sip:+15550001234@198.51.100.1:5060".into()),
        );
    }

    #[test]
    fn extract_request_uri_status_line() {
        assert_eq!(request_uri("SIP/2.0 200 OK\r\n\r\n"), None);
    }

    #[test]
    fn extract_request_uri_malformed_line() {
        assert_eq!(
            extract_request_uri(""),
            Err(ParseError::empty(Field::Value))
        );
        let line = "INVITE sip:a@example.com SIP/2.0 x";
        assert_eq!(
            extract_request_uri(&format!("{line}\r\n")),
            Err(ParseError::Malformed(
                Fault::new(Field::Value, FaultCode::Missing)
                    .at(0)
                    .to(line.len())
            ))
        );
        assert_eq!(
            extract_request_uri("INVITE sip:a@example.com HTTP/1.1\r\n"),
            Err(ParseError::malformed(
                Field::Value,
                FaultCode::Missing,
                Some(25)
            ))
        );
    }

    fn spacing(at: usize) -> ParseWarning {
        ParseWarning::new(Field::Value, WarningCode::RequestLineWhitespace).at(at)
    }

    #[test]
    fn request_line_spacing_is_warned_and_strictly_refused() {
        let msg = "INVITE  sip:a@example.com\tSIP/2.0 \r\n\r\n";
        let parsed = extract_request_uri_with_warnings(msg)
            .unwrap()
            .unwrap();
        assert_eq!(
            parsed
                .value
                .to_string(),
            "sip:a@example.com"
        );
        assert_eq!(parsed.warnings, [spacing(6), spacing(25), spacing(33)]);
        assert_eq!(extract_request_uri(msg), Ok(Some(parsed.value)));
        assert_eq!(
            extract_request_uri_strict(msg),
            Err(ParseError::NonConformant(spacing(6)))
        );
        let msg = " INVITE sip:a@example.com SIP/2.0\r\n";
        assert_eq!(
            extract_request_uri_with_warnings(msg)
                .unwrap()
                .unwrap()
                .warnings,
            [spacing(0)]
        );
        let msg = "INVITE sip:a@example.com SIP/2.0\r\n";
        assert!(extract_request_uri_strict(msg).is_ok());
        let status = "SIP/2.0  200 OK\r\n";
        assert_eq!(extract_request_uri_with_warnings(status), Ok(None));
        assert_eq!(extract_request_uri_strict(status), Ok(None));
    }

    #[test]
    fn request_uri_warnings_pass_through_at_line_positions() {
        let uri = "sip:a@example.com:";
        let own = sip_uri::Uri::parse_with_warnings(uri).unwrap();
        assert!(!own
            .warnings
            .is_empty());
        let msg = format!("OPTIONS {uri} SIP/2.0\r\n");
        let parsed = extract_request_uri_with_warnings(&msg)
            .unwrap()
            .unwrap();
        let shifted: Vec<_> = own
            .warnings
            .into_iter()
            .map(|w| ParseWarning::from_uri(w, "OPTIONS ".len()))
            .collect();
        assert_eq!(parsed.warnings, shifted);
        assert!(extract_request_uri_strict(&msg).is_err());
    }

    // -- extract_all_headers tests --

    fn all_pairs(msg: &str) -> Vec<(String, String)> {
        extract_all_headers(msg)
            .headers
            .iter()
            .map(|(name, value)| (name.to_string(), value.to_string()))
            .collect()
    }

    #[test]
    fn extract_all_headers_basic() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Via: SIP/2.0/UDP host\r\n",
            "From: Alice <sip:alice@example.com>\r\n",
            "To: Bob <sip:bob@example.com>\r\n",
            "\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 3);
        assert_eq!(headers[0], ("Via".into(), "SIP/2.0/UDP host".into()));
        assert_eq!(
            headers[1],
            ("From".into(), "Alice <sip:alice@example.com>".into())
        );
        assert_eq!(
            headers[2],
            ("To".into(), "Bob <sip:bob@example.com>".into())
        );
    }

    #[test]
    fn extract_all_headers_folding() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Subject: I know you're there,\r\n",
            " pick up the phone\r\n",
            " and talk to me!\r\n",
            "From: Alice <sip:alice@example.com>\r\n",
            "\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 2);
        assert_eq!(
            headers[0].1,
            "I know you're there, pick up the phone and talk to me!"
        );
    }

    #[test]
    fn extract_all_headers_compact_forms_verbatim() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "f: Alice <sip:alice@example.com>\r\n",
            "t: Bob <sip:bob@example.com>\r\n",
            "i: call-1@host\r\n",
            "\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 3);
        assert_eq!(headers[0].0, "f");
        assert_eq!(headers[1].0, "t");
        assert_eq!(headers[2].0, "i");
    }

    #[test]
    fn extract_all_headers_stops_at_blank_line() {
        let msg = concat!(
            "INVITE sip:bob@example.com SIP/2.0\r\n",
            "From: Alice <sip:alice@example.com>\r\n",
            "\r\n",
            "v=0\r\n",
            "o=alice 123 456 IN IP4 198.51.100.1\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].0, "From");
    }

    #[test]
    fn extract_all_headers_multiple_same_name() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Via: SIP/2.0/UDP first.example.com\r\n",
            "Via: SIP/2.0/UDP second.example.com\r\n",
            "\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 2);
        assert_eq!(
            headers[0],
            ("Via".into(), "SIP/2.0/UDP first.example.com".into())
        );
        assert_eq!(
            headers[1],
            ("Via".into(), "SIP/2.0/UDP second.example.com".into())
        );
    }

    #[test]
    fn extract_all_headers_empty_message() {
        assert!(extract_all_headers("")
            .headers
            .is_empty());
    }

    #[test]
    fn extract_all_headers_skips_request_line() {
        let msg = concat!(
            "INVITE sip:bob@example.com SIP/2.0\r\n",
            "From: Alice <sip:alice@example.com>\r\n",
            "\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].0, "From");
    }

    #[test]
    fn extract_all_headers_skips_status_line() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "From: Alice <sip:alice@example.com>\r\n",
            "\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].0, "From");
    }

    #[test]
    fn extract_all_headers_tab_folding() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Subject: hello\r\n",
            "\tworld\r\n",
            "\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0].1, "hello world");
    }

    #[test]
    fn extract_all_headers_empty_value() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Subject:\r\n",
            "From: Alice <sip:alice@example.com>\r\n",
            "\r\n",
        );
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 2);
        assert_eq!(headers[0], ("Subject".into(), "".into()));
    }

    #[test]
    fn value_trailing_whitespace_trimmed() {
        let msg = "SIP/2.0 200 OK\r\nSubject: hi   \r\nFrom: <sip:a@example.com>\t\r\n\r\n";
        assert_eq!(extract_header(msg, "Subject"), vec!["hi"]);
        let headers = all_pairs(msg);
        assert_eq!(headers[0].1, "hi");
        assert_eq!(headers[1].1, "<sip:a@example.com>");
    }

    #[test]
    fn folded_value_trailing_whitespace_trimmed() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Subject: hello  \r\n",
            " world  \r\n",
            "\r\n",
        );
        assert_eq!(extract_header(msg, "Subject"), vec!["hello world"]);
        assert_eq!(all_pairs(msg)[0].1, "hello world");
    }

    // -- extract_body tests --

    #[test]
    fn extract_body_crlf() {
        assert_eq!(
            extract_body(SAMPLE_INVITE),
            Some("v=0\r\no=alice 2890844526 2890844526 IN IP4 pc33.atlanta.example.com\r\n")
        );
    }

    #[test]
    fn extract_body_bare_lf() {
        let msg = "SIP/2.0 200 OK\n\
                   From: Alice <sip:alice@host>\n\
                   \n\
                   v=0\no=alice 123 456 IN IP4 198.51.100.1\n";
        assert_eq!(
            extract_body(msg),
            Some("v=0\no=alice 123 456 IN IP4 198.51.100.1\n")
        );
    }

    #[test]
    fn extract_body_folded_headers() {
        let msg = concat!(
            "SIP/2.0 200 OK\r\n",
            "Subject: I know you're there,\r\n",
            " pick up the phone\r\n",
            "\r\n",
            "body text\r\n",
        );
        assert_eq!(extract_body(msg), Some("body text\r\n"));
    }

    #[test]
    fn extract_body_no_blank_line() {
        let msg = "INVITE sip:bob@example.com SIP/2.0\r\n\
                   From: Alice <sip:alice@example.com>\r\n";
        assert_eq!(extract_body(msg), None);
    }

    #[test]
    fn extract_body_blank_line_nothing_after() {
        let msg = "SIP/2.0 200 OK\r\n\
                   From: Alice <sip:alice@host>\r\n\
                   \r\n";
        assert_eq!(extract_body(msg), None);
    }

    #[test]
    fn extract_body_empty_message() {
        assert_eq!(extract_body(""), None);
    }

    #[test]
    fn extract_body_multipart_blank_lines_kept() {
        let msg = concat!(
            "INVITE sip:sos@psap.example.com SIP/2.0\r\n",
            "Content-Type: multipart/mixed;boundary=b1\r\n",
            "\r\n",
            "--b1\r\n",
            "Content-Type: application/sdp\r\n",
            "\r\n",
            "v=0\r\n",
            "--b1--\r\n",
        );
        assert_eq!(
            extract_body(msg),
            Some("--b1\r\nContent-Type: application/sdp\r\n\r\nv=0\r\n--b1--\r\n")
        );
    }

    #[test]
    fn extract_body_header_looking_line_in_body() {
        let msg = "SIP/2.0 200 OK\r\n\
                   \r\n\
                   From: not a header\r\n";
        assert_eq!(extract_body(msg), Some("From: not a header\r\n"));
    }

    #[test]
    fn extract_body_after_request_line() {
        let msg = "INVITE sip:bob@example.com SIP/2.0\r\n\
                   \r\n\
                   v=0\r\n";
        assert_eq!(extract_body(msg), Some("v=0\r\n"));
    }

    #[test]
    fn extract_all_headers_bare_lf() {
        let msg = "SIP/2.0 200 OK\n\
                   From: Alice <sip:alice@example.com>\n\
                   \n\
                   body\n";
        let headers = all_pairs(msg);
        assert_eq!(headers.len(), 1);
        assert_eq!(
            headers[0],
            ("From".into(), "Alice <sip:alice@example.com>".into())
        );
    }

    #[test]
    fn continuation_after_non_header_line_not_folded() {
        let msg = "INVITE sip:bob@example.com SIP/2.0\r\n\
                   From: <sip:alice@example.com>\r\n\
                   not a header\r\n\
                   \x20continued\r\n\
                   \r\n";
        let all = extract_all_headers(msg);
        assert_eq!(
            all.headers,
            SipHeaderFields::from(vec![("From", "<sip:alice@example.com>")])
        );
        let at = |s: &str| {
            msg.find(s)
                .unwrap()
        };
        assert_eq!(all.skipped, [at("not a header"), at(" continued")]);
        assert_eq!(extract_header(msg, "f"), vec!["<sip:alice@example.com>"]);
    }

    #[test]
    fn folded_rows_alone_are_owned() {
        let msg = "SIP/2.0 200 OK\r\nSubject: a\r\n b\r\nFrom: <sip:a@example.com>\r\n\r\n";
        let borrowed = |value: &str| {
            msg.as_bytes()
                .as_ptr_range()
                .contains(&value.as_ptr())
        };
        let headers = SipMessageHeaders::new(msg);
        let values: Vec<&str> = headers
            .iter()
            .map(|(_, value)| value)
            .collect();
        assert_eq!(values, ["a b", "<sip:a@example.com>"]);
        assert!(!borrowed(values[0]));
        assert!(borrowed(values[1]));
    }

    #[test]
    fn a_name_that_is_not_a_token_is_skipped() {
        let msg = "SIP/2.0 200 OK\r\nX Bad: a\r\nVia : SIP/2.0/UDP h\r\n\r\n";
        let headers = SipMessageHeaders::new(msg);
        assert_eq!(headers.skipped(), [16]);
        assert_eq!(
            headers
                .iter()
                .collect::<Vec<_>>(),
            [("Via", "SIP/2.0/UDP h")]
        );
    }

    #[test]
    fn extract_from_sip_message() {
        let msg = concat!(
            "INVITE sip:bob@host SIP/2.0\r\n",
            "Call-Info: <urn:emergency:uid:callid:abc>;purpose=emergency-CallId\r\n",
            "History-Info: <sip:esrp@example.com>;index=1\r\n",
            "P-Asserted-Identity: \"Corp\" <sip:+15551234567@198.51.100.1>\r\n",
            "\r\n",
        );
        let ci = SipHeader::CallInfo.extract_from(msg);
        assert_eq!(ci.len(), 1);
        assert_eq!(
            ci[0],
            "<urn:emergency:uid:callid:abc>;purpose=emergency-CallId"
        );

        let hi = SipHeader::HistoryInfo.extract_from(msg);
        assert_eq!(hi.len(), 1);
        assert_eq!(hi[0], "<sip:esrp@example.com>;index=1");

        let pai = SipHeader::PAssertedIdentity.extract_from(msg);
        assert_eq!(pai.len(), 1);
        assert_eq!(pai[0], "\"Corp\" <sip:+15551234567@198.51.100.1>");
    }
}