1#![forbid(unsafe_code)]
12
13mod fields;
14#[macro_use]
15mod macros;
16mod rows;
17#[cfg(feature = "serde")]
18mod serde_name;
19
20#[cfg(doctest)]
21#[doc = include_str!("../README.md")]
22struct ReadmeDoctests;
23
24pub use fields::{
25 SipHeaderField, SipHeaderFieldRows, SipHeaderFields, SipHeaderFieldsIntoIter,
26 SipHeaderFieldsIter,
27};
28pub use macros::HeaderName;
29pub use rows::{RowError, RowErrorKind, SipHeaderRows, SipHeaderRowsExt};
30
31#[doc(hidden)]
33pub mod __private {
34 pub trait HeaderNameSealed {}
36
37 #[cfg(feature = "serde")]
38 pub use crate::serde_name::{deserialize_name, serialize_name};
39 #[cfg(feature = "serde")]
40 pub use serde;
41}
42
43define_header_enum! {
44 tests_mod: sip_header_generated_tests,
45 error_type: ParseSipHeaderError => "unknown SIP header",
46 pub enum SipHeader {
60 Accept => "Accept",
62 AcceptContact => "Accept-Contact",
63 AcceptEncoding => "Accept-Encoding",
65 AcceptLanguage => "Accept-Language",
67 AcceptResourcePriority => "Accept-Resource-Priority",
68 AdditionalIdentity => "Additional-Identity",
69 AlertInfo => "Alert-Info",
71 AlertmsgError => "AlertMsg-Error",
72 Allow => "Allow",
74 AllowEvents => "Allow-Events",
76 AnswerMode => "Answer-Mode",
77 AttestationInfo => "Attestation-Info",
78 AuthenticationInfo => "Authentication-Info",
79 Authorization => "Authorization",
81 CallId => "Call-ID",
83 CallInfo => "Call-Info",
85 CellularNetworkInfo => "Cellular-Network-Info",
86 Contact => "Contact",
88 ContentDisposition => "Content-Disposition",
90 ContentEncoding => "Content-Encoding",
92 ContentId => "Content-ID",
93 ContentLanguage => "Content-Language",
95 ContentLength => "Content-Length",
97 ContentType => "Content-Type",
99 Cseq => "CSeq",
101 Date => "Date",
103 DcInfo => "DC-Info",
104 Encryption => "Encryption",
106 ErrorInfo => "Error-Info",
108 Event => "Event",
110 Expires => "Expires",
112 FeatureCaps => "Feature-Caps",
113 FlowTimer => "Flow-Timer",
114 From => "From",
116 Geolocation => "Geolocation",
118 GeolocationError => "Geolocation-Error",
120 GeolocationRouting => "Geolocation-Routing",
122 Hide => "Hide",
124 HistoryInfo => "History-Info",
126 Identity => "Identity",
128 IdentityInfo => "Identity-Info",
129 InfoPackage => "Info-Package",
130 InReplyTo => "In-Reply-To",
132 Join => "Join",
134 MaxBreadth => "Max-Breadth",
135 MaxForwards => "Max-Forwards",
137 MimeVersion => "MIME-Version",
139 MinExpires => "Min-Expires",
141 MinSe => "Min-SE",
143 Organization => "Organization",
145 OriginationId => "Origination-Id",
146 PAccessNetworkInfo => "P-Access-Network-Info",
147 PAnswerState => "P-Answer-State",
148 PAssertedIdentity => "P-Asserted-Identity",
150 PAssertedService => "P-Asserted-Service",
151 PAssociatedUri => "P-Associated-URI",
152 PCalledPartyId => "P-Called-Party-ID",
153 PChargeInfo => "P-Charge-Info",
154 PChargingFunctionAddresses => "P-Charging-Function-Addresses",
155 PChargingVector => "P-Charging-Vector",
156 PDcsTracePartyId => "P-DCS-Trace-Party-ID",
157 PDcsOsps => "P-DCS-OSPS",
158 PDcsBillingInfo => "P-DCS-Billing-Info",
159 PDcsLaes => "P-DCS-LAES",
160 PDcsRedirect => "P-DCS-Redirect",
161 PEarlyMedia => "P-Early-Media",
162 PMediaAuthorization => "P-Media-Authorization",
163 PPreferredIdentity => "P-Preferred-Identity",
165 PPreferredService => "P-Preferred-Service",
166 PPrivateNetworkIndication => "P-Private-Network-Indication",
167 PProfileKey => "P-Profile-Key",
168 PRefusedUriList => "P-Refused-URI-List",
169 PServedUser => "P-Served-User",
170 PUserDatabase => "P-User-Database",
171 PVisitedNetworkId => "P-Visited-Network-ID",
172 Path => "Path",
174 PermissionMissing => "Permission-Missing",
175 PolicyContact => "Policy-Contact",
176 PolicyId => "Policy-ID",
177 Priority => "Priority",
179 PriorityShare => "Priority-Share",
180 PriorityVerstat => "Priority-Verstat",
181 PrivAnswerMode => "Priv-Answer-Mode",
182 Privacy => "Privacy",
184 ProxyAuthenticate => "Proxy-Authenticate",
186 ProxyAuthorization => "Proxy-Authorization",
188 ProxyRequire => "Proxy-Require",
190 Rack => "RAck",
191 Reason => "Reason",
193 ReasonPhrase => "Reason-Phrase",
194 RecordRoute => "Record-Route",
196 RecvInfo => "Recv-Info",
197 ReferEventsAt => "Refer-Events-At",
198 ReferSub => "Refer-Sub",
199 ReferTo => "Refer-To",
201 ReferredBy => "Referred-By",
203 RejectContact => "Reject-Contact",
204 RelayedCharge => "Relayed-Charge",
205 Replaces => "Replaces",
207 ReplyTo => "Reply-To",
209 RequestDisposition => "Request-Disposition",
210 Require => "Require",
212 ResourcePriority => "Resource-Priority",
213 ResourceShare => "Resource-Share",
214 ResponseKey => "Response-Key",
216 ResponseSource => "Response-Source",
217 RestorationInfo => "Restoration-Info",
218 RetryAfter => "Retry-After",
220 Route => "Route",
222 Rseq => "RSeq",
223 SecurityClient => "Security-Client",
225 SecurityServer => "Security-Server",
227 SecurityVerify => "Security-Verify",
229 Server => "Server",
231 ServiceInteractInfo => "Service-Interact-Info",
232 ServiceRoute => "Service-Route",
234 SessionExpires => "Session-Expires",
236 SessionId => "Session-ID",
237 SipEtag => "SIP-ETag",
238 SipIfMatch => "SIP-If-Match",
239 Subject => "Subject",
241 SubscriptionState => "Subscription-State",
243 Supported => "Supported",
245 SuppressIfMatch => "Suppress-If-Match",
246 TargetDialog => "Target-Dialog",
248 Timestamp => "Timestamp",
250 To => "To",
252 TriggerConsent => "Trigger-Consent",
253 Unsupported => "Unsupported",
255 UserAgent => "User-Agent",
257 UserToUser => "User-to-User",
259 Via => "Via",
261 Warning => "Warning",
263 WwwAuthenticate => "WWW-Authenticate",
265 Diversion => "Diversion",
267 RemotePartyId => "Remote-Party-ID",
269 }
270}
271
272const COMPACT_FORMS: &[(char, SipHeader)] = &[
277 ('a', SipHeader::AcceptContact),
278 ('b', SipHeader::ReferredBy),
279 ('c', SipHeader::ContentType),
280 ('d', SipHeader::RequestDisposition),
281 ('e', SipHeader::ContentEncoding),
282 ('f', SipHeader::From),
283 ('i', SipHeader::CallId),
284 ('j', SipHeader::RejectContact),
285 ('k', SipHeader::Supported),
286 ('l', SipHeader::ContentLength),
287 ('m', SipHeader::Contact),
288 ('o', SipHeader::Event),
289 ('r', SipHeader::ReferTo),
290 ('s', SipHeader::Subject),
291 ('t', SipHeader::To),
292 ('u', SipHeader::AllowEvents),
293 ('v', SipHeader::Via),
294 ('x', SipHeader::SessionExpires),
295 ('y', SipHeader::Identity),
296];
297
298impl SipHeader {
299 pub fn from_compact(ch: char) -> Option<Self> {
303 let lower = ch.to_ascii_lowercase();
304 COMPACT_FORMS
305 .iter()
306 .find(|(c, _)| *c == lower)
307 .map(|(_, h)| *h)
308 }
309
310 #[inline]
312 pub fn compact_form(&self) -> Option<char> {
313 COMPACT_FORMS
314 .iter()
315 .find(|(_, h)| h == self)
316 .map(|(c, _)| *c)
317 }
318
319 pub fn is_list(&self) -> bool {
322 self.occurrence() == Occurrence::List
323 }
324
325 pub fn may_repeat(&self) -> bool {
332 self.occurrence() != Occurrence::Single
333 }
334
335 fn occurrence(&self) -> Occurrence {
337 use Occurrence::{List, Repeated, Single};
338 match self {
339 Self::Accept
341 | Self::AcceptEncoding
342 | Self::AcceptLanguage
343 | Self::AlertInfo
344 | Self::Allow
345 | Self::CallInfo
346 | Self::Contact
347 | Self::ContentEncoding
348 | Self::ContentLanguage
349 | Self::ErrorInfo
350 | Self::InReplyTo
351 | Self::ProxyRequire
352 | Self::RecordRoute
353 | Self::Require
354 | Self::Route
355 | Self::Supported
356 | Self::Unsupported
357 | Self::Via
358 | Self::Warning => List,
359 Self::Authorization
361 | Self::ProxyAuthorization
362 | Self::ProxyAuthenticate
363 | Self::WwwAuthenticate => Repeated,
364 Self::AuthenticationInfo
366 | Self::CallId
367 | Self::ContentDisposition
368 | Self::ContentLength
369 | Self::ContentType
370 | Self::Cseq
371 | Self::Date
372 | Self::Expires
373 | Self::From
374 | Self::MaxForwards
375 | Self::MimeVersion
376 | Self::MinExpires
377 | Self::Organization
378 | Self::Priority
379 | Self::ReplyTo
380 | Self::RetryAfter
381 | Self::Server
382 | Self::Subject
383 | Self::Timestamp
384 | Self::To
385 | Self::UserAgent => Single,
386 Self::Encryption | Self::Hide | Self::ResponseKey => Single,
388 Self::AcceptContact | Self::RejectContact | Self::RequestDisposition => List,
390 Self::AcceptResourcePriority | Self::ResourcePriority => List,
392 Self::AllowEvents => List,
394 Self::Event | Self::SubscriptionState => Single,
395 Self::FeatureCaps => List,
397 Self::Geolocation => List,
399 Self::GeolocationError | Self::GeolocationRouting => Single,
400 Self::HistoryInfo => List,
402 Self::RecvInfo => List,
404 Self::InfoPackage => Single,
405 Self::PAccessNetworkInfo
407 | Self::PAssociatedUri
408 | Self::PChargingFunctionAddresses
409 | Self::PVisitedNetworkId => List,
410 Self::PCalledPartyId | Self::PChargingVector => Single,
411 Self::PAssertedIdentity | Self::PPreferredIdentity => List,
413 Self::PAssertedService | Self::PPreferredService => List,
415 Self::PEarlyMedia => List,
417 Self::PMediaAuthorization => List,
419 Self::PRefusedUriList => List,
421 Self::Path | Self::ServiceRoute => List,
423 Self::PermissionMissing | Self::TriggerConsent => List,
425 Self::PolicyContact | Self::PolicyId => List,
427 Self::Reason => List,
429 Self::SecurityClient | Self::SecurityServer | Self::SecurityVerify => List,
431 Self::UserToUser => List,
433 Self::Diversion => List,
435 Self::Identity => Repeated,
437 Self::RemotePartyId => Repeated,
439 Self::Privacy => Single,
441 Self::AlertmsgError
445 | Self::AnswerMode
446 | Self::PrivAnswerMode
447 | Self::ContentId
448 | Self::FlowTimer
449 | Self::IdentityInfo
450 | Self::Join
451 | Self::MaxBreadth
452 | Self::MinSe
453 | Self::SessionExpires
454 | Self::PAnswerState
455 | Self::PChargeInfo
456 | Self::PDcsTracePartyId
457 | Self::PDcsOsps
458 | Self::PDcsBillingInfo
459 | Self::PDcsLaes
460 | Self::PDcsRedirect
461 | Self::PPrivateNetworkIndication
462 | Self::PProfileKey
463 | Self::PServedUser
464 | Self::PUserDatabase
465 | Self::Rack
466 | Self::Rseq
467 | Self::ReferEventsAt
468 | Self::ReferSub
469 | Self::ReferTo
470 | Self::ReferredBy
471 | Self::Replaces
472 | Self::SessionId
473 | Self::SipEtag
474 | Self::SipIfMatch
475 | Self::SuppressIfMatch
476 | Self::TargetDialog => Single,
477 Self::AdditionalIdentity
479 | Self::AttestationInfo
480 | Self::CellularNetworkInfo
481 | Self::DcInfo
482 | Self::OriginationId
483 | Self::PriorityShare
484 | Self::PriorityVerstat
485 | Self::RelayedCharge
486 | Self::ResourceShare
487 | Self::ResponseSource
488 | Self::RestorationInfo
489 | Self::ServiceInteractInfo => Single,
490 Self::ReasonPhrase => Single,
492 }
493 }
494
495 pub fn registry(&self) -> Registry {
497 match self {
498 Self::Diversion | Self::RemotePartyId => Registry::Draft,
499 _ => Registry::Iana,
500 }
501 }
502
503 #[inline]
509 pub fn matches(&self, wire_name: &str) -> bool {
510 NameMatcher::from(*self).matches(wire_name)
511 }
512
513 pub fn name_matches(name: &str, wire_name: &str) -> bool {
518 NameMatcher::new(name).matches(wire_name)
519 }
520
521 pub fn parse_name(name: &str) -> Result<Self, ParseSipHeaderError> {
526 Self::lookup(name).ok_or_else(|| ParseSipHeaderError(name.to_string()))
527 }
528
529 fn lookup(name: &str) -> Option<Self> {
530 match name.as_bytes() {
531 [c] => Self::from_compact(char::from(*c)),
532 _ => Self::ALL
533 .iter()
534 .copied()
535 .find(|h| name.eq_ignore_ascii_case(h.as_str())),
536 }
537 }
538}
539
540#[derive(Debug, Clone, Copy)]
558pub struct NameMatcher<'a> {
559 name: &'a str,
560 header: Option<SipHeader>,
561 compact: Option<u8>,
563}
564
565impl<'a> NameMatcher<'a> {
566 pub fn new(name: &'a str) -> Self {
569 match SipHeader::lookup(name) {
570 Some(h) => h.into(),
571 None => NameMatcher {
572 name,
573 header: None,
574 compact: None,
575 },
576 }
577 }
578
579 #[inline]
582 pub fn matches(&self, wire_name: &str) -> bool {
583 wire_name.eq_ignore_ascii_case(self.name)
584 || matches!(
585 (self.compact, wire_name.as_bytes()),
586 (Some(letter), [c]) if c.to_ascii_lowercase() == letter
587 )
588 }
589}
590
591impl From<SipHeader> for NameMatcher<'_> {
592 #[inline]
593 fn from(header: SipHeader) -> Self {
594 NameMatcher {
595 name: header.as_str(),
596 header: Some(header),
597 compact: header
599 .compact_form()
600 .map(|c| c as u8),
601 }
602 }
603}
604
605impl Ord for SipHeader {
608 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
609 let fold = |h: &Self| {
610 h.as_str()
611 .bytes()
612 .map(|b| b.to_ascii_lowercase())
613 };
614 fold(self).cmp(fold(other))
615 }
616}
617
618impl PartialOrd for SipHeader {
619 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
620 Some(self.cmp(other))
621 }
622}
623
624#[derive(Clone, Copy, PartialEq, Eq)]
625enum Occurrence {
626 Single,
627 List,
628 Repeated,
629}
630
631#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
633#[non_exhaustive]
634pub enum Registry {
635 Iana,
637 Draft,
639}
640
641#[cfg(feature = "serde")]
642impl serde::Serialize for SipHeader {
643 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
644 serde_name::serialize_name(self.as_str(), serializer)
645 }
646}
647
648#[cfg(feature = "serde")]
649impl<'de> serde::Deserialize<'de> for SipHeader {
650 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
651 serde_name::deserialize_name(deserializer, "SIP header name", SipHeader::parse_name)
652 }
653}
654
655#[cfg(test)]
656mod tests {
657 use super::*;
658
659 #[test]
660 fn no_two_wire_names_differ_only_by_case() {
661 for a in SipHeader::ALL {
662 for b in SipHeader::ALL {
663 assert_eq!(
664 a.as_str()
665 .eq_ignore_ascii_case(b.as_str()),
666 a == b,
667 "{a} {b}"
668 );
669 }
670 }
671 }
672
673 #[test]
674 fn ord_is_wire_name_order_ignoring_case() {
675 for a in SipHeader::ALL {
676 for b in SipHeader::ALL {
677 assert_eq!(
678 a.cmp(b),
679 a.as_str()
680 .to_ascii_lowercase()
681 .cmp(
682 &b.as_str()
683 .to_ascii_lowercase()
684 ),
685 "{a} {b}"
686 );
687 assert_eq!(a.partial_cmp(b), Some(a.cmp(b)));
688 assert_eq!(
689 a.cmp(b)
690 .is_eq(),
691 a == b,
692 "{a} {b}"
693 );
694 }
695 }
696 }
697}
698
699#[cfg(test)]
700mod compact_form_tests {
701 use super::*;
702
703 #[test]
704 fn from_compact_unknown() {
705 assert_eq!(SipHeader::from_compact('z'), None);
706 assert_eq!(SipHeader::from_compact('g'), None);
707 }
708
709 #[test]
710 fn parse_name_full() {
711 assert_eq!(SipHeader::parse_name("From"), Ok(SipHeader::From));
712 assert_eq!(SipHeader::parse_name("Via"), Ok(SipHeader::Via));
713 }
714
715 #[test]
716 fn parse_name_unknown() {
717 assert!(SipHeader::parse_name("X-Custom").is_err());
718 }
719
720 #[test]
721 fn compact_form_round_trips_through_from_compact() {
722 for h in SipHeader::ALL {
723 let back = h
724 .compact_form()
725 .and_then(SipHeader::from_compact);
726 assert_eq!(
727 back,
728 h.compact_form()
729 .map(|_| *h),
730 "{h}"
731 );
732 }
733 }
734
735 #[test]
736 fn from_compact_resolves_exactly_the_compact_forms() {
737 for ch in (0..=0x2ff).filter_map(char::from_u32) {
738 let expected = SipHeader::ALL
739 .iter()
740 .copied()
741 .find(|h| h.compact_form() == Some(ch.to_ascii_lowercase()));
742 assert_eq!(SipHeader::from_compact(ch), expected, "{ch:?}");
743 }
744 }
745
746 fn wire_names() -> Vec<String> {
747 let mut names: Vec<String> = [
748 "é",
749 "L",
750 "",
751 "Content-Lengt",
752 "Content-Lengths",
753 "l ",
754 " l",
755 ]
756 .map(String::from)
757 .into();
758 names.extend((0u8..=0x7f).map(|b| char::from(b).to_string()));
759 for h in SipHeader::ALL {
760 let name = h.as_str();
761 names.extend([
762 name.into(),
763 name.to_ascii_uppercase(),
764 name.to_ascii_lowercase(),
765 ]);
766 if let Some(ch) = h.compact_form() {
767 names.extend([
768 ch.to_string(),
769 ch.to_ascii_uppercase()
770 .to_string(),
771 ]);
772 }
773 }
774 names
775 }
776
777 fn reference(h: Option<SipHeader>, name: &str, wire: &str) -> bool {
778 match h {
779 Some(h) => {
780 wire.eq_ignore_ascii_case(h.as_str())
781 || matches!(wire.as_bytes(), [c] if SipHeader::from_compact(char::from(*c)) == Some(h))
782 }
783 None => wire.eq_ignore_ascii_case(name),
784 }
785 }
786
787 #[test]
788 fn matches_agrees_with_the_resolving_definition() {
789 let names = wire_names();
790 for h in SipHeader::ALL {
791 let matcher = NameMatcher::from(*h);
792 for w in &names {
793 let want = reference(Some(*h), h.as_str(), w);
794 assert_eq!(matcher.matches(w), want, "{h} {w:?}");
795 assert_eq!(h.matches(w), want, "{h} {w:?}");
796 }
797 }
798 }
799
800 #[test]
801 fn name_matcher_new_agrees_with_the_resolving_definition() {
802 let names = wire_names();
803 for query in names
804 .iter()
805 .map(String::as_str)
806 .chain(["X-Custom", "x-custom"])
807 {
808 let matcher = NameMatcher::new(query);
809 let resolved = SipHeader::parse_name(query).ok();
810 for w in &names {
811 let want = reference(resolved, query, w);
812 assert_eq!(matcher.matches(w), want, "{query:?} {w:?}");
813 assert_eq!(SipHeader::name_matches(query, w), want, "{query:?} {w:?}");
814 }
815 }
816 }
817
818 #[test]
819 fn parse_name_takes_compact_forms_in_either_case() {
820 for h in SipHeader::ALL {
821 if let Some(ch) = h.compact_form() {
822 for spelling in [ch, ch.to_ascii_uppercase()] {
823 assert_eq!(
824 SipHeader::parse_name(&spelling.to_string()),
825 Ok(*h),
826 "{spelling}"
827 );
828 }
829 }
830 }
831 }
832}
833
834#[cfg(test)]
835mod occurrence_tests {
836 use super::*;
837
838 #[test]
839 fn authentication_headers_repeat_but_never_split() {
840 for h in [
841 SipHeader::Authorization,
842 SipHeader::ProxyAuthorization,
843 SipHeader::WwwAuthenticate,
844 SipHeader::ProxyAuthenticate,
845 ] {
846 assert!(h.may_repeat() && !h.is_list(), "{h}");
847 }
848 assert!(!SipHeader::AuthenticationInfo.is_list());
849 assert!(!SipHeader::AuthenticationInfo.may_repeat());
850 }
851
852 #[test]
853 fn single_values() {
854 for h in [
855 SipHeader::From,
856 SipHeader::To,
857 SipHeader::CallId,
858 SipHeader::Cseq,
859 SipHeader::Privacy,
860 SipHeader::Server,
861 SipHeader::UserAgent,
862 SipHeader::Replaces,
863 ] {
864 assert!(!h.is_list() && !h.may_repeat(), "{h}");
865 }
866 }
867}
868
869#[cfg(test)]
870mod registry_tests {
871 use super::*;
872
873 fn listed(file: &str) -> Vec<(&str, Option<char>)> {
875 let mut rows: Vec<(&str, Option<char>)> = file
876 .lines()
877 .filter_map(|l| {
878 let mut cols = l
879 .split('#')
880 .next()?
881 .split_whitespace();
882 let name = cols.next()?;
883 let compact = cols
884 .next()
885 .map(|c| {
886 let mut chars = c.chars();
887 match (chars.next(), chars.next()) {
888 (Some(ch), None) => ch,
889 _ => panic!("{name}: compact form {c:?} is not one letter"),
890 }
891 });
892 assert_eq!(cols.next(), None, "{name}: extra column");
893 Some((name, compact))
894 })
895 .collect();
896 rows.sort_unstable();
897 rows
898 }
899
900 fn catalog(registry: Registry) -> Vec<(&'static str, Option<char>)> {
901 let mut rows: Vec<(&str, Option<char>)> = SipHeader::ALL
902 .iter()
903 .filter(|h| h.registry() == registry)
904 .map(|h| (h.as_str(), h.compact_form()))
905 .collect();
906 rows.sort_unstable();
907 rows
908 }
909
910 #[test]
911 fn iana_list_matches_catalog() {
912 assert_eq!(
913 catalog(Registry::Iana),
914 listed(include_str!("../iana-sip-headers.txt"))
915 );
916 }
917
918 #[test]
919 fn draft_list_matches_catalog() {
920 assert_eq!(
921 catalog(Registry::Draft),
922 listed(include_str!("../draft-sip-headers.txt"))
923 );
924 }
925
926 #[test]
927 fn from_str_takes_canonical_names_only() {
928 assert!("v"
929 .parse::<SipHeader>()
930 .is_err());
931 assert_eq!(SipHeader::parse_name("v"), Ok(SipHeader::Via));
932 }
933}
934
935#[cfg(all(test, feature = "serde"))]
936mod serde_tests {
937 use super::*;
938
939 #[test]
940 fn serializes_as_the_wire_name() {
941 for h in SipHeader::ALL {
942 assert_eq!(
943 serde_json::to_string(h).unwrap(),
944 format!("\"{}\"", h.as_str())
945 );
946 }
947 }
948
949 #[test]
950 fn deserializes_any_spelling_parse_name_accepts() {
951 for h in SipHeader::ALL {
952 for spelling in [
953 h.as_str()
954 .to_string(),
955 h.as_str()
956 .to_lowercase(),
957 h.as_str()
958 .to_uppercase(),
959 ] {
960 let json = format!("\"{spelling}\"");
961 assert_eq!(serde_json::from_str::<SipHeader>(&json).unwrap(), *h);
962 }
963 }
964 assert_eq!(
965 serde_json::from_str::<Vec<SipHeader>>(r#"["v","F","call-id"]"#).unwrap(),
966 vec![SipHeader::Via, SipHeader::From, SipHeader::CallId]
967 );
968 }
969
970 #[test]
971 fn unknown_name_error_omits_the_input() {
972 let e = serde_json::from_str::<SipHeader>(r#""X-Secret-Token""#).unwrap_err();
973 let msg = e.to_string();
974 assert!(msg.contains("unknown SIP header name"), "{msg}");
975 assert!(!msg.contains("Secret"), "{msg}");
976 }
977}