1use aws_smithy_types::date_time::Format;
25use aws_smithy_types::primitive::Parse;
26use aws_smithy_types::DateTime;
27use std::borrow::Cow;
28use std::error::Error;
29use std::fmt;
30use std::str::FromStr;
31
32#[derive(Debug)]
34pub struct ParseError {
35 message: Cow<'static, str>,
36 source: Option<Box<dyn Error + Send + Sync + 'static>>,
37}
38
39impl ParseError {
40 pub fn new(message: impl Into<Cow<'static, str>>) -> Self {
42 Self {
43 message: message.into(),
44 source: None,
45 }
46 }
47
48 pub fn with_source(self, source: impl Into<Box<dyn Error + Send + Sync + 'static>>) -> Self {
50 Self {
51 source: Some(source.into()),
52 ..self
53 }
54 }
55}
56
57impl fmt::Display for ParseError {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 write!(f, "output failed to parse in headers: {}", self.message)
60 }
61}
62
63impl Error for ParseError {
64 fn source(&self) -> Option<&(dyn Error + 'static)> {
65 self.source.as_ref().map(|err| err.as_ref() as _)
66 }
67}
68
69pub(crate) const NON_UTF8_HEADER: &str = "header was not valid utf-8";
70
71fn str_from_utf8(bytes: &[u8]) -> Result<&str, ParseError> {
73 std::str::from_utf8(bytes).map_err(|_| ParseError::new(NON_UTF8_HEADER))
74}
75
76pub fn many_dates<'a>(
81 values: impl Iterator<Item = &'a str>,
82 format: Format,
83) -> Result<Vec<DateTime>, ParseError> {
84 many_dates_bytes(values.map(str::as_bytes), format)
85}
86
87pub fn many_dates_bytes<'a>(
93 values: impl Iterator<Item = &'a [u8]>,
94 format: Format,
95) -> Result<Vec<DateTime>, ParseError> {
96 let mut out = vec![];
97 for header in values {
98 let mut header = str_from_utf8(header)?;
99 while !header.is_empty() {
100 let (v, next) = DateTime::read(header, format, ',').map_err(|err| {
101 ParseError::new(format!("header could not be parsed as date: {err}"))
102 })?;
103 out.push(v);
104 header = next;
105 }
106 }
107 Ok(out)
108}
109
110pub fn headers_for_prefix<'a>(
122 header_names: impl Iterator<Item = &'a str>,
123 key: &'a str,
124) -> impl Iterator<Item = (&'a str, &'a str)> {
125 let prefix = key.as_bytes();
126 let has_uppercase = prefix.iter().any(u8::is_ascii_uppercase);
127 header_names
128 .filter(move |k| {
129 let Some(head) = k.as_bytes().get(..prefix.len()) else {
130 return false;
131 };
132 if has_uppercase {
133 head.iter()
134 .zip(prefix)
135 .all(|(h, p)| *h == p.to_ascii_lowercase())
136 } else {
137 head == prefix
138 }
139 })
140 .map(move |k| (&k[key.len()..], k))
143}
144
145pub fn read_many_from_str<'a, T: FromStr>(
147 values: impl Iterator<Item = &'a str>,
148) -> Result<Vec<T>, ParseError>
149where
150 T::Err: Error + Send + Sync + 'static,
151{
152 read_many_from_str_bytes(values.map(str::as_bytes))
153}
154
155pub fn read_many_from_str_bytes<'a, T: FromStr>(
160 values: impl Iterator<Item = &'a [u8]>,
161) -> Result<Vec<T>, ParseError>
162where
163 T::Err: Error + Send + Sync + 'static,
164{
165 read_many_bytes(values, |v: &str| {
166 v.parse().map_err(|err| {
167 ParseError::new("failed during `FromString` conversion").with_source(err)
168 })
169 })
170}
171
172pub fn read_many_primitive<'a, T: Parse>(
174 values: impl Iterator<Item = &'a str>,
175) -> Result<Vec<T>, ParseError> {
176 read_many_primitive_bytes(values.map(str::as_bytes))
177}
178
179pub fn read_many_primitive_bytes<'a, T: Parse>(
185 values: impl Iterator<Item = &'a [u8]>,
186) -> Result<Vec<T>, ParseError> {
187 read_many_bytes(values, |v: &str| {
188 T::parse_smithy_primitive(v)
189 .map_err(|err| ParseError::new("failed reading a list of primitives").with_source(err))
190 })
191}
192
193fn read_many_bytes<'a, T>(
195 values: impl Iterator<Item = &'a [u8]>,
196 f: impl Fn(&str) -> Result<T, ParseError>,
197) -> Result<Vec<T>, ParseError> {
198 let mut out = vec![];
199 for header in values {
200 let mut header = header;
201 while !header.is_empty() {
202 let (v, next) = read_one(header, &f)?;
203 out.push(v);
204 header = next;
205 }
206 }
207 Ok(out)
208}
209
210fn one_of_many_bytes<'a, T>(
221 values: impl Iterator<Item = &'a [u8]>,
222 f: impl Fn(&str) -> Result<T, ParseError>,
223) -> Result<Option<T>, ParseError> {
224 let mut first = None;
225 let mut count = 0usize;
226 for header in values {
227 let mut header = header;
228 while !header.is_empty() {
229 let (value, next) = read_one(header, &f)?;
230 count += 1;
231 if first.is_none() {
232 first = Some(value);
233 }
234 header = next;
235 }
236 }
237 if count > 1 {
238 return Err(ParseError::new(format!(
239 "expected one item but found {count}"
240 )));
241 }
242 Ok(first)
243}
244
245pub fn one_primitive_or_none_bytes<'a, T: Parse>(
252 values: impl Iterator<Item = &'a [u8]>,
253) -> Result<Option<T>, ParseError> {
254 one_of_many_bytes(values, |v: &str| {
255 T::parse_smithy_primitive(v)
256 .map_err(|err| ParseError::new("failed reading a list of primitives").with_source(err))
257 })
258}
259
260pub fn one_from_str_or_none_bytes<'a, T: FromStr>(
265 values: impl Iterator<Item = &'a [u8]>,
266) -> Result<Option<T>, ParseError>
267where
268 T::Err: Error + Send + Sync + 'static,
269{
270 one_of_many_bytes(values, |v: &str| {
271 v.parse().map_err(|err| {
272 ParseError::new("failed during `FromString` conversion").with_source(err)
273 })
274 })
275}
276
277pub fn one_date_or_none_bytes<'a>(
283 values: impl Iterator<Item = &'a [u8]>,
284 format: Format,
285) -> Result<Option<DateTime>, ParseError> {
286 let mut first = None;
287 let mut count = 0usize;
288 for header in values {
289 let mut header = str_from_utf8(header)?;
290 while !header.is_empty() {
291 let (value, next) = DateTime::read(header, format, ',').map_err(|err| {
292 ParseError::new(format!("header could not be parsed as date: {err}"))
293 })?;
294 count += 1;
295 if first.is_none() {
296 first = Some(value);
297 }
298 header = next;
299 }
300 }
301 if count > 1 {
302 return Err(ParseError::new(format!(
303 "expected one item but found {count}"
304 )));
305 }
306 Ok(first)
307}
308
309pub fn quote_header_value<'a>(value: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
311 let value = value.into();
312 if value.trim().len() != value.len()
313 || value.contains('"')
314 || value.contains(',')
315 || value.contains('(')
316 || value.contains(')')
317 {
318 Cow::Owned(format!(
319 "\"{}\"",
320 value.replace('\\', "\\\\").replace('"', "\\\"")
321 ))
322 } else {
323 value
324 }
325}
326
327pub fn one_or_none<'a, T: FromStr>(
331 values: impl Iterator<Item = &'a str>,
332) -> Result<Option<T>, ParseError>
333where
334 T::Err: Error + Send + Sync + 'static,
335{
336 one_or_none_bytes(values.map(str::as_bytes))
337}
338
339pub fn one_or_none_bytes<'a, T: FromStr>(
346 mut values: impl Iterator<Item = &'a [u8]>,
347) -> Result<Option<T>, ParseError>
348where
349 T::Err: Error + Send + Sync + 'static,
350{
351 let first = match values.next() {
352 Some(v) => v,
353 None => return Ok(None),
354 };
355 match values.next() {
356 None => T::from_str(str_from_utf8(first)?.trim())
359 .map_err(|err| ParseError::new("failed to parse string").with_source(err))
360 .map(Some),
361 Some(_) => Err(ParseError::new(
362 "expected a single value but found multiple",
363 )),
364 }
365}
366
367mod parse_multi_header {
371 use super::ParseError;
372 use std::borrow::Cow;
373
374 fn trim(s: Cow<'_, str>) -> Cow<'_, str> {
375 match s {
376 Cow::Owned(s) => Cow::Owned(s.trim().into()),
377 Cow::Borrowed(s) => Cow::Borrowed(s.trim()),
378 }
379 }
380
381 fn replace<'a>(value: Cow<'a, str>, pattern: &str, replacement: &str) -> Cow<'a, str> {
382 if value.contains(pattern) {
383 Cow::Owned(value.replace(pattern, replacement))
384 } else {
385 value
386 }
387 }
388
389 pub(crate) fn read_value(input: &[u8]) -> Result<(Cow<'_, str>, &[u8]), ParseError> {
393 for (index, &byte) in input.iter().enumerate() {
394 let current_slice = &input[index..];
395 match byte {
396 b' ' | b'\t' => { }
397 b'"' => return read_quoted_value(¤t_slice[1..]),
398 _ => {
399 let (value, rest) = read_unquoted_value(current_slice)?;
400 return Ok((trim(value), rest));
401 }
402 }
403 }
404
405 Ok((Cow::Borrowed(""), &[]))
407 }
408
409 fn read_unquoted_value(input: &[u8]) -> Result<(Cow<'_, str>, &[u8]), ParseError> {
410 let next_delim = input.iter().position(|&b| b == b',').unwrap_or(input.len());
411 let (first, next) = input.split_at(next_delim);
412 let first =
413 std::str::from_utf8(first).map_err(|_| ParseError::new(super::NON_UTF8_HEADER))?;
414 Ok((Cow::Borrowed(first), then_comma(next).unwrap()))
415 }
416
417 fn read_quoted_value(input: &[u8]) -> Result<(Cow<'_, str>, &[u8]), ParseError> {
420 let mut escaped = false;
421 for index in 0..input.len() {
422 match input[index] {
423 b'\\' if !escaped => escaped = true,
424 b'"' if !escaped => {
425 let mut inner = Cow::Borrowed(
426 std::str::from_utf8(&input[0..index])
427 .map_err(|_| ParseError::new(super::NON_UTF8_HEADER))?,
428 );
429 inner = replace(inner, "\\\"", "\"");
430 inner = replace(inner, "\\\\", "\\");
431 let rest = then_comma(&input[(index + 1)..])?;
432 return Ok((inner, rest));
433 }
434 _ => escaped = false,
435 }
436 }
437 Err(ParseError::new(
438 "header value had quoted value without end quote",
439 ))
440 }
441
442 fn then_comma(s: &[u8]) -> Result<&[u8], ParseError> {
443 if s.is_empty() {
444 Ok(s)
445 } else if s.starts_with(b",") {
446 Ok(&s[1..])
447 } else {
448 Err(ParseError::new("expected delimiter `,`"))
449 }
450 }
451}
452
453fn read_one<'a, T>(
455 s: &'a [u8],
456 f: &impl Fn(&str) -> Result<T, ParseError>,
457) -> Result<(T, &'a [u8]), ParseError> {
458 let (value, rest) = parse_multi_header::read_value(s)?;
459 Ok((f(&value)?, rest))
460}
461
462#[cfg(test)]
463mod test {
464 use super::{
469 headers_for_prefix, many_dates, many_dates_bytes, one_date_or_none_bytes,
470 one_from_str_or_none_bytes, one_or_none, one_or_none_bytes, one_primitive_or_none_bytes,
471 quote_header_value, read_many_from_str, read_many_from_str_bytes, read_many_primitive,
472 read_many_primitive_bytes, ParseError,
473 };
474 use aws_smithy_types::error::display::DisplayErrorContext;
475 use aws_smithy_types::{date_time::Format, DateTime};
476 use std::collections::HashMap;
477
478 #[test]
479 fn parse_floats() {
480 assert_eq!(
481 read_many_primitive::<f32>(["0.0,Infinity,-Infinity,5555.5"].into_iter())
482 .expect("valid"),
483 vec![0.0, f32::INFINITY, f32::NEG_INFINITY, 5555.5]
484 );
485 let message = format!(
486 "{}",
487 DisplayErrorContext(
488 read_many_primitive::<f32>(["notafloat"].into_iter()).expect_err("invalid")
489 )
490 );
491 let expected = "output failed to parse in headers: failed reading a list of primitives: failed to parse input as f32";
492 assert!(
493 message.starts_with(expected),
494 "expected '{message}' to start with '{expected}'"
495 );
496 }
497
498 #[test]
499 fn test_many_dates() {
500 assert_eq!(
501 many_dates([""].into_iter(), Format::DateTime).expect("valid"),
502 Vec::<DateTime>::new()
503 );
504 assert_eq!(
505 many_dates(
506 ["Wed, 21 Oct 2015 07:28:00 GMT"].into_iter(),
507 Format::HttpDate
508 )
509 .expect("valid"),
510 vec![DateTime::from_secs_and_nanos(1445412480, 0)]
511 );
512 assert_eq!(
513 many_dates(
514 ["Wed, 21 Oct 2015 07:28:00 GMT,Thu, 22 Oct 2015 07:28:00 GMT"].into_iter(),
515 Format::HttpDate
516 )
517 .expect("valid"),
518 vec![
519 DateTime::from_secs_and_nanos(1445412480, 0),
520 DateTime::from_secs_and_nanos(1445498880, 0)
521 ]
522 );
523 assert_eq!(
524 many_dates(["1234.5678"].into_iter(), Format::EpochSeconds).expect("valid"),
525 vec![DateTime::from_secs_and_nanos(1234, 567_800_000)]
526 );
527 assert_eq!(
528 many_dates(["1234.5678,9012.3456"].into_iter(), Format::EpochSeconds).expect("valid"),
529 vec![
530 DateTime::from_secs_and_nanos(1234, 567_800_000),
531 DateTime::from_secs_and_nanos(9012, 345_600_000)
532 ]
533 );
534 }
535
536 const NON_UTF8_VALUE: &[u8] = b"value-\xe9";
538
539 #[test]
540 fn bytes_helpers_agree_with_str_helpers_on_valid_utf8() {
541 assert_eq!(
542 one_or_none::<String>([" foo "].into_iter()).unwrap(),
543 one_or_none_bytes::<String>([b" foo ".as_slice()].into_iter()).unwrap(),
544 );
545 assert_eq!(
546 read_many_from_str::<String>(["\"foo,bar\",baz"].into_iter()).unwrap(),
547 read_many_from_str_bytes::<String>([b"\"foo,bar\",baz".as_slice()].into_iter())
548 .unwrap(),
549 );
550 assert_eq!(
551 read_many_primitive::<i16>(["1,2", "3"].into_iter()).unwrap(),
552 read_many_primitive_bytes::<i16>([b"1,2".as_slice(), b"3".as_slice()].into_iter())
553 .unwrap(),
554 );
555 assert_eq!(
556 many_dates(
557 ["Mon, 16 Dec 2019 23:48:18 GMT"].into_iter(),
558 Format::HttpDate
559 )
560 .unwrap(),
561 many_dates_bytes(
562 [b"Mon, 16 Dec 2019 23:48:18 GMT".as_slice()].into_iter(),
563 Format::HttpDate
564 )
565 .unwrap(),
566 );
567 }
568
569 #[test]
570 fn bytes_helpers_reject_non_utf8() {
571 let expected = "header was not valid utf-8";
572
573 let err = one_or_none_bytes::<String>([NON_UTF8_VALUE].into_iter()).expect_err("non-utf8");
574 assert!(err.to_string().contains(expected), "{err}");
575
576 let err =
577 read_many_from_str_bytes::<String>([NON_UTF8_VALUE].into_iter()).expect_err("non-utf8");
578 assert!(err.to_string().contains(expected), "{err}");
579
580 let err =
581 read_many_primitive_bytes::<i16>([NON_UTF8_VALUE].into_iter()).expect_err("non-utf8");
582 assert!(err.to_string().contains(expected), "{err}");
583
584 let err =
585 many_dates_bytes([NON_UTF8_VALUE].into_iter(), Format::HttpDate).expect_err("non-utf8");
586 assert!(err.to_string().contains(expected), "{err}");
587 }
588
589 #[test]
590 fn one_or_none_bytes_reports_multiple_before_non_utf8() {
591 let err = one_or_none_bytes::<String>([NON_UTF8_VALUE, b"second".as_slice()].into_iter())
594 .expect_err("multiple values");
595 assert!(
596 err.to_string()
597 .contains("expected a single value but found multiple"),
598 "{err}"
599 );
600 }
601
602 #[test]
603 fn quoted_values_ending_in_backslash_round_trip() {
604 let values = ["a,\\", ",b", "c\\", "x\\\"y", "\\\\,"];
605 let header = values
606 .iter()
607 .map(|v| quote_header_value(*v))
608 .collect::<Vec<_>>()
609 .join(",");
610 assert_eq!(
611 read_many_from_str::<String>([header.as_str()].into_iter()).unwrap(),
612 values
613 );
614 }
615
616 #[test]
617 fn read_many_strings() {
618 let read = |value: &str| read_many_from_str::<String>([value].into_iter());
619 let read_valid = |value: &str| read(value).expect("valid");
620 assert_eq!(read_valid(""), Vec::<String>::new());
621 assert_eq!(read_valid(" foo"), vec!["foo"]);
622 assert_eq!(read_valid("foo "), vec!["foo"]);
623 assert_eq!(read_valid("\" foo \""), vec![" foo "]);
624 assert_eq!(read_valid("\"foo,bar\",baz"), vec!["foo,bar", "baz"]);
625 assert_eq!(read_valid("\"foo,bar\",baz "), vec!["foo,bar", "baz"]);
626 assert_eq!(
627 read_valid("\"foo\\\",bar\",\"\\\"asdf\\\"\",baz"),
628 vec!["foo\",bar", "\"asdf\"", "baz"]
629 );
630 assert_eq!(
631 read_valid("\"foo\\\",bar\", \"\\\"asdf\\\"\", baz"),
632 vec!["foo\",bar", "\"asdf\"", "baz"]
633 );
634 assert!(read("\"\\\"asdf\\\"\"baz").is_err());
635 assert_eq!(read_valid("\"\",baz"), vec!["", "baz"]);
636 assert_eq!(
637 read_valid("foo, \"(foo\\\\bar)\""),
638 vec!["foo", "(foo\\bar)"]
639 );
640 }
641
642 #[test]
643 fn read_many_bools() {
644 assert_eq!(
645 read_many_primitive::<bool>(["true,false", "true"].into_iter()).expect("valid"),
646 vec![true, false, true]
647 );
648 assert_eq!(
649 read_many_primitive::<bool>(["true"].into_iter()).unwrap(),
650 vec![true]
651 );
652 assert_eq!(
653 read_many_primitive::<bool>(["true,false,true,true"].into_iter()).unwrap(),
654 vec![true, false, true, true]
655 );
656 assert_eq!(
657 read_many_primitive::<bool>(["true,\"false\",true,true"].into_iter()).unwrap(),
658 vec![true, false, true, true]
659 );
660 read_many_primitive::<bool>(["truth,falsy"].into_iter()).expect_err("invalid");
661 }
662
663 #[test]
664 fn check_read_many_i16() {
665 assert_eq!(
666 read_many_primitive::<i16>(["123,456", "789"].into_iter()).expect("valid"),
667 vec![123, 456, 789]
668 );
669 assert_eq!(
670 read_many_primitive::<i16>(["777"].into_iter()).unwrap(),
671 vec![777]
672 );
673 assert_eq!(
674 read_many_primitive::<i16>(["1,2,3,-4,5"].into_iter()).unwrap(),
675 vec![1, 2, 3, -4, 5]
676 );
677 assert_eq!(
678 read_many_primitive::<i16>(["1, \"2\",3,\"-4\",5"].into_iter()).unwrap(),
679 vec![1, 2, 3, -4, 5]
680 );
681 read_many_primitive::<i16>(["12ef3"].into_iter()).expect_err("invalid");
682 }
683
684 #[test]
685 fn test_prefix_headers() {
686 let names = ["x-prefix-a", "x-prefix-b", "x-prefix-c", "other"];
689 let values: HashMap<&str, Vec<&str>> = [
690 ("x-prefix-a", vec!["123,456"]),
691 ("x-prefix-b", vec!["789"]),
692 ("x-prefix-c", vec!["777", "777"]),
693 ("other", vec!["1"]),
694 ]
695 .into_iter()
696 .collect();
697 let resp: Result<HashMap<String, Vec<i16>>, ParseError> =
698 headers_for_prefix(names.into_iter(), "x-prefix-")
699 .map(|(key, header_name)| {
700 read_many_primitive(values[header_name].iter().copied())
701 .map(|v| (key.to_string(), v))
702 })
703 .collect();
704 let resp = resp.expect("valid");
705 assert_eq!(resp.get("a"), Some(&vec![123_i16, 456_i16]));
706 assert_eq!(resp.get("b"), Some(&vec![789_i16]));
707 assert_eq!(resp.get("c"), Some(&vec![777_i16, 777_i16]));
708 assert_eq!(resp.get("other"), None);
709 }
710
711 #[test]
712 fn prefix_matching_lowercases_the_modeled_prefix() {
713 let names = ["x-meta-foo", "x-meta-bar"];
714 let matched: Vec<_> = headers_for_prefix(names.into_iter(), "X-Meta-").collect();
715 assert_eq!(
716 matched,
717 vec![("foo", "x-meta-foo"), ("bar", "x-meta-bar")],
718 "a mixed-case modeled prefix must match normalized wire names"
719 );
720 }
721
722 #[test]
723 fn every_spelling_of_a_prefix_matches_the_same_normalized_names() {
724 for prefix in ["X-Meta-", "x-meta-", "X-META-", "x-Meta-"] {
728 let names = ["x-meta-foo", "x-meta-bar", "x-other", "x-me", "x-metadata"];
729 let matched: Vec<_> = headers_for_prefix(names.into_iter(), prefix).collect();
730 assert_eq!(
731 matched,
732 vec![("foo", "x-meta-foo"), ("bar", "x-meta-bar")],
733 "prefix {prefix:?} must match the same names"
734 );
735 }
736 }
737
738 #[test]
739 fn a_prefix_with_no_letters_matches_exactly() {
740 let names = ["1-2-a", "1-2-", "1-3-a"];
741 let matched: Vec<_> = headers_for_prefix(names.into_iter(), "1-2-").collect();
742 assert_eq!(matched, vec![("a", "1-2-a"), ("", "1-2-")]);
743 }
744
745 #[test]
746 fn a_prefix_matches_the_whole_name_and_yields_an_empty_key() {
747 let names = ["x-meta-"];
748 let matched: Vec<_> = headers_for_prefix(names.into_iter(), "x-meta-").collect();
749 assert_eq!(matched, vec![("", "x-meta-")]);
750 }
751
752 #[test]
756 fn scalar_helpers_agree_with_the_many_value_helpers() {
757 let cases: &[&[&[u8]]] = &[
758 &[],
759 &[b""],
760 &[b"", b""],
761 &[b"5"],
762 &[b" 5 "],
763 &[b"5", b""],
764 &[b"5,6"],
765 &[b"5", b"6"],
766 &[b"notanint"],
767 &[b"5,notanint"],
768 ];
769 for values in cases {
770 let many = read_many_primitive_bytes::<i32>(values.iter().copied());
771 let one = one_primitive_or_none_bytes::<i32>(values.iter().copied());
772 match many {
773 Ok(mut parsed) if parsed.len() <= 1 => assert_eq!(
774 one.as_ref().ok().and_then(|v| v.as_ref()),
775 parsed.pop().as_ref(),
776 "values {values:?} must produce the same single value"
777 ),
778 Ok(parsed) => {
779 let message = format!(
780 "{}",
781 DisplayErrorContext(&one.expect_err("cardinality must fail"))
782 );
783 assert!(
784 message.contains(&format!("expected one item but found {}", parsed.len())),
785 "values {values:?} must report the legacy cardinality message, got '{message}'"
786 );
787 }
788 Err(expected) => {
790 let expected = format!("{}", DisplayErrorContext(&expected));
791 let actual = format!(
792 "{}",
793 DisplayErrorContext(&one.expect_err("parse error must propagate"))
794 );
795 assert_eq!(
796 expected, actual,
797 "values {values:?} must report the same error"
798 );
799 }
800 }
801 }
802 }
803
804 #[test]
805 fn scalar_from_str_helper_agrees_with_the_many_value_helper() {
806 assert_eq!(
807 one_from_str_or_none_bytes::<String>([b"a".as_slice()].into_iter()).expect("valid"),
808 Some("a".to_string())
809 );
810 let err = one_from_str_or_none_bytes::<String>([b"a,b".as_slice()].into_iter())
813 .expect_err("two items");
814 assert!(
815 format!("{}", DisplayErrorContext(&err)).contains("expected one item but found 2"),
816 "expected a cardinality error"
817 );
818 assert_eq!(
819 one_from_str_or_none_bytes::<String>([b"".as_slice()].into_iter()).expect("valid"),
820 None,
821 "an empty value produces no tokens, which the legacy path reports as absent"
822 );
823 }
824
825 #[test]
826 fn scalar_date_helper_agrees_with_many_dates() {
827 let http_date = b"Wed, 21 Oct 2015 07:28:00 GMT".as_slice();
830 assert_eq!(
831 one_date_or_none_bytes([http_date].into_iter(), Format::HttpDate).expect("valid"),
832 Some(many_dates_bytes([http_date].into_iter(), Format::HttpDate).expect("valid")[0])
833 );
834 assert_eq!(
835 one_date_or_none_bytes([b"".as_slice()].into_iter(), Format::HttpDate).expect("valid"),
836 None
837 );
838 let two = b"Wed, 21 Oct 2015 07:28:00 GMT,Wed, 21 Oct 2015 07:28:01 GMT".as_slice();
839 assert_eq!(
840 many_dates_bytes([two].into_iter(), Format::HttpDate)
841 .expect("valid")
842 .len(),
843 2,
844 "precondition: this value really does hold two dates"
845 );
846 let err =
847 one_date_or_none_bytes([two].into_iter(), Format::HttpDate).expect_err("two items");
848 assert!(
849 format!("{}", DisplayErrorContext(&err)).contains("expected one item but found 2"),
850 "expected a cardinality error"
851 );
852 }
853
854 #[test]
855 fn scalar_helpers_reject_non_utf8() {
856 let non_utf8 = b"value-\xe9".as_slice();
857 for message in [
858 format!(
859 "{}",
860 DisplayErrorContext(
861 &one_primitive_or_none_bytes::<i32>([non_utf8].into_iter())
862 .expect_err("not utf-8")
863 )
864 ),
865 format!(
866 "{}",
867 DisplayErrorContext(
868 &one_from_str_or_none_bytes::<String>([non_utf8].into_iter())
869 .expect_err("not utf-8")
870 )
871 ),
872 format!(
873 "{}",
874 DisplayErrorContext(
875 &one_date_or_none_bytes([non_utf8].into_iter(), Format::HttpDate)
876 .expect_err("not utf-8")
877 )
878 ),
879 ] {
880 assert!(
881 message.contains(super::NON_UTF8_HEADER),
882 "expected '{message}' to report the non-UTF-8 reason"
883 );
884 }
885 }
886}