1#[cfg(feature = "std")]
4use alloc::sync::Arc;
5use alloc::{
6 string::{String, ToString},
7 vec::Vec,
8};
9use core::fmt;
10
11use crate::scanner::Marker;
12
13#[derive(Clone, Debug)]
28pub struct InputIoError {
29 message: String,
30 #[cfg(feature = "std")]
31 source: Option<Arc<std::io::Error>>,
32}
33
34impl InputIoError {
35 #[must_use]
39 pub fn from_message(message: impl Into<String>) -> Self {
40 Self {
41 message: message.into(),
42 #[cfg(feature = "std")]
43 source: None,
44 }
45 }
46
47 #[cfg(feature = "std")]
49 #[must_use]
50 pub fn from_io(error: std::io::Error) -> Self {
51 Self {
52 message: error.to_string(),
53 source: Some(Arc::new(error)),
54 }
55 }
56
57 #[must_use]
59 pub fn message(&self) -> &str {
60 &self.message
61 }
62
63 #[cfg(feature = "std")]
65 #[must_use]
66 pub fn io_error(&self) -> Option<&std::io::Error> {
67 self.source.as_deref()
68 }
69
70 #[cfg(feature = "std")]
76 pub fn try_into_io_error(self) -> Result<std::io::Error, Self> {
77 let Self { message, source } = self;
78 let Some(source) = source else {
79 return Err(Self {
80 message,
81 source: None,
82 });
83 };
84
85 match Arc::try_unwrap(source) {
86 Ok(error) => Ok(error),
87 Err(source) => Err(Self {
88 message,
89 source: Some(source),
90 }),
91 }
92 }
93}
94
95#[cfg(feature = "std")]
96impl From<std::io::Error> for InputIoError {
97 fn from(error: std::io::Error) -> Self {
98 Self::from_io(error)
99 }
100}
101
102impl PartialEq for InputIoError {
103 fn eq(&self, other: &Self) -> bool {
104 self.message == other.message
105 }
106}
107
108impl Eq for InputIoError {}
109
110impl core::hash::Hash for InputIoError {
111 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
112 core::hash::Hash::hash(&self.message, state);
113 }
114}
115
116impl fmt::Display for InputIoError {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.write_str(&self.message)
119 }
120}
121
122impl core::error::Error for InputIoError {
123 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
124 #[cfg(feature = "std")]
125 {
126 self.source
127 .as_deref()
128 .map(|error| error as &(dyn core::error::Error + 'static))
129 }
130
131 #[cfg(not(feature = "std"))]
132 {
133 None
134 }
135 }
136}
137
138#[derive(Clone, PartialEq, Debug, Eq, Hash)]
140#[non_exhaustive]
141pub enum ErrorKind {
142 #[cfg(feature = "comments")]
144 TooManyComments,
145 InputIo {
147 error: InputIoError,
149 },
150 InputDecoding {
152 message: String,
154 },
155 InputByteLimitExceeded {
157 limit: usize,
159 },
160 UnexpectedEofFlowSequence,
162 UnexpectedEofFlowMapping,
164 UnexpectedEofImplicitFlowMapping,
166 UnexpectedEofBlockSequence,
168 UnexpectedEofBlockMapping,
170 UnexpectedEof,
172 ExpectedStreamStart,
174 DuplicateVersionDirective,
176 UnsupportedYamlMajorVersion,
178 DuplicateTagDirective,
180 ExpectedDocumentStart,
182 MissingDocumentEndBeforeDirective,
184 AnchorCountOverflow,
186 AnchorIdCollision {
188 anchor_id: usize,
190 first_free_id: usize,
192 },
193 UnknownAnchor,
195 ExpectedNodeContent,
197 ExpectedBlockMappingKey,
199 ExpectedFlowMappingSeparator,
201 ExpectedFlowSequenceSeparator,
203 ExpectedBlockSequenceEntry,
205 UndeclaredTagHandle,
207 MissingIncludeResolver,
209 Custom(String),
211 MultipleDocumentsUnsupported,
213 InputOffsetsWithoutSlice,
215 InputSlicingUnavailable,
217 ExpectedTagBang,
219 ExpectedTagDirectiveBang,
221 InvalidGlobalTagCharacter,
223 SimpleKeyExpected,
225 InvalidSimpleKey,
227 InvalidDocumentEnd,
229 InvalidIndentation,
231 BomInsideDocument,
233 UnexpectedCharacter {
235 character: char,
237 },
238 TabNotAllowed,
240 TabInBlockIndentation,
242 CommentInterceptedScalar,
244 ExpectedWhitespace,
246 CommentNotSeparated,
248 InvalidDirectiveTerminator,
250 DirectiveDisallowed,
252 MissingYamlVersionSeparator,
254 MissingDirectiveName,
256 InvalidDirectiveName,
258 DirectiveByteLimitExceeded {
260 limit: usize,
262 },
263 TooManyReservedDirectiveParams {
265 limit: usize,
267 },
268 YamlVersionTooLong,
270 MissingYamlVersion,
272 InvalidTagDirectiveTerminator,
274 InvalidTagTerminator,
276 MissingTagUri,
278 UnclosedVerbatimTag,
280 InvalidTagEscape,
282 InvalidTagUtf8LeadingByte,
284 InvalidTagUtf8TrailingByte,
286 InvalidTagUtf8,
288 MissingAnchorOrAliasName,
290 MisplacedFlowCollectionEnd,
292 MismatchedFlowCollectionEnd {
294 open: char,
296 close: char,
298 },
299 UnclosedFlowCollection {
301 open: char,
303 },
304 RecursionLimitExceeded,
306 BlockEntryInFlowCollection,
308 BlockSequenceEntryNotAllowed,
310 InvalidBlockEntryWhitespace,
312 ZeroBlockScalarIndent,
314 InvalidBlockScalarHeader,
316 TabAtBlockScalarStart,
318 InvalidBlockScalarIndent,
320 DocumentIndicatorInQuotedScalar,
322 UnclosedQuotedScalar,
324 TabInIndentation,
326 InvalidQuotedScalarIndent,
328 InvalidTrailingSingleQuotedScalar,
330 InvalidTrailingDoubleQuotedScalar,
332 UnknownQuotedScalarEscape,
334 InvalidQuotedScalarHexEscape,
336 InvalidLowSurrogateHexEscape,
338 InvalidLowSurrogate,
340 MissingLowSurrogate,
342 UnpairedLowSurrogate,
344 InvalidUnicodeEscape,
346 InvalidFlowScalarIndent,
348 PlainScalarStartsWithDashFlowIndicator,
350 TabInPlainScalar,
352 UnexpectedEndOfPlainScalar,
354 MappingKeyNotAllowed,
356 FlowMappingValueAdjacentCollection,
358 InvalidMappingValueWhitespace,
360 InvalidColonPlacement,
362 MappingValueNotAllowed,
364}
365
366#[cfg(feature = "error_messages")]
367impl fmt::Display for ErrorKind {
368 #[allow(clippy::too_many_lines)]
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 match self {
371 #[cfg(feature = "comments")]
372 Self::TooManyComments => {
373 f.write_str("too many buffered comments while looking ahead")
374 }
375 Self::InputIo { error } => write!(f, "input I/O error: {error}"),
376 Self::InputDecoding { message } => {
377 write!(f, "input decoding error: {message}")
378 }
379 Self::InputByteLimitExceeded { limit } => {
380 write!(f, "input exceeds the configured limit of {limit} bytes")
381 }
382 Self::UnexpectedEofFlowSequence => {
383 f.write_str("unexpected EOF while parsing a flow sequence")
384 }
385 Self::UnexpectedEofFlowMapping => {
386 f.write_str("unexpected EOF while parsing a flow mapping")
387 }
388 Self::UnexpectedEofImplicitFlowMapping => {
389 f.write_str("unexpected EOF while parsing an implicit flow mapping")
390 }
391 Self::UnexpectedEofBlockSequence => {
392 f.write_str("unexpected EOF while parsing a block sequence")
393 }
394 Self::UnexpectedEofBlockMapping => {
395 f.write_str("unexpected EOF while parsing a block mapping")
396 }
397 Self::UnexpectedEof => f.write_str("unexpected eof"),
398 Self::ExpectedStreamStart => f.write_str("did not find expected <stream-start>"),
399 Self::DuplicateVersionDirective => f.write_str("duplicate version directive"),
400 Self::UnsupportedYamlMajorVersion => {
401 f.write_str("unsupported YAML major version")
402 }
403 Self::DuplicateTagDirective => f.write_str(
404 "the TAG directive must only be given at most once per handle in the same document",
405 ),
406 Self::ExpectedDocumentStart => {
407 f.write_str("did not find expected <document start>")
408 }
409 Self::MissingDocumentEndBeforeDirective => {
410 f.write_str("missing explicit document end marker before directive")
411 }
412 Self::AnchorCountOverflow => {
413 f.write_str("while parsing anchor, anchor count exceeded supported limit")
414 }
415 Self::AnchorIdCollision {
416 anchor_id,
417 first_free_id,
418 } => write!(
419 f,
420 "anchor ID {anchor_id} is below the stack's first free ID {first_free_id}. \
421 Seed the child parser with the stack's anchor offset before reading from it"
422 ),
423 Self::UnknownAnchor => f.write_str("while parsing node, found unknown anchor"),
424 Self::ExpectedNodeContent => {
425 f.write_str("while parsing a node, did not find expected node content")
426 }
427 Self::ExpectedBlockMappingKey => {
428 f.write_str("while parsing a block mapping, did not find expected key")
429 }
430 Self::ExpectedFlowMappingSeparator => {
431 f.write_str("while parsing a flow mapping, did not find expected ',' or '}'")
432 }
433 Self::ExpectedFlowSequenceSeparator => {
434 f.write_str("while parsing a flow sequence, expected ',' or ']'")
435 }
436 Self::ExpectedBlockSequenceEntry => f.write_str(
437 "while parsing a block collection, did not find expected '-' indicator",
438 ),
439 Self::UndeclaredTagHandle => f.write_str("the handle wasn't declared"),
440 Self::MissingIncludeResolver => {
441 f.write_str("No include resolver set for parser stack.")
442 }
443 Self::Custom(message) => f.write_str(message),
444 Self::MultipleDocumentsUnsupported => {
445 f.write_str("multiple documents not supported here")
446 }
447 Self::InputOffsetsWithoutSlice => f.write_str(
448 "internal error: input advertised offsets but did not provide a slice",
449 ),
450 Self::InputSlicingUnavailable => f.write_str(
451 "internal error: input advertised slicing but did not provide a slice",
452 ),
453 Self::ExpectedTagBang => {
454 f.write_str("while scanning a tag, did not find expected '!'")
455 }
456 Self::ExpectedTagDirectiveBang => {
457 f.write_str("while parsing a tag directive, did not find expected '!'")
458 }
459 Self::InvalidGlobalTagCharacter => f.write_str("invalid global tag character"),
460 Self::SimpleKeyExpected => f.write_str("simple key expected ':'"),
461 Self::InvalidSimpleKey => f.write_str("simple key is no longer valid"),
462 Self::InvalidDocumentEnd => {
463 f.write_str("invalid content after document end marker")
464 }
465 Self::InvalidIndentation => f.write_str("invalid indentation"),
466 Self::BomInsideDocument => {
467 f.write_str("a BOM must not appear inside a document")
468 }
469 Self::UnexpectedCharacter { character } => {
470 write!(f, "unexpected character: `{}'", character.escape_default())
471 }
472 Self::TabNotAllowed => f.write_str("tabs disallowed in this context"),
473 Self::TabInBlockIndentation => {
474 f.write_str("tabs disallowed within this context (block indentation)")
475 }
476 Self::CommentInterceptedScalar => {
477 f.write_str("comment intercepting the multiline text")
478 }
479 Self::ExpectedWhitespace => f.write_str("expected whitespace"),
480 Self::CommentNotSeparated => {
481 f.write_str("comments must be separated from other tokens by whitespace")
482 }
483 Self::InvalidDirectiveTerminator => f.write_str(
484 "while scanning a directive, did not find expected comment or line break",
485 ),
486 Self::DirectiveDisallowed => f.write_str("YAML directives are disallowed"),
487 Self::MissingYamlVersionSeparator => f.write_str(
488 "while scanning a YAML directive, did not find expected digit or '.' character",
489 ),
490 Self::MissingDirectiveName => f.write_str(
491 "while scanning a directive, could not find expected directive name",
492 ),
493 Self::InvalidDirectiveName => f.write_str(
494 "while scanning a directive, found unexpected non-alphabetical character",
495 ),
496 Self::DirectiveByteLimitExceeded { limit } => write!(
497 f,
498 "directive exceeds the configured limit of {limit} bytes"
499 ),
500 Self::TooManyReservedDirectiveParams { limit } => write!(
501 f,
502 "reserved directive exceeds the configured limit of {limit} parameters"
503 ),
504 Self::YamlVersionTooLong => {
505 f.write_str("while scanning a YAML directive, found extremely long version number")
506 }
507 Self::MissingYamlVersion => f.write_str(
508 "while scanning a YAML directive, did not find expected version number",
509 ),
510 Self::InvalidTagDirectiveTerminator => {
511 f.write_str("while scanning TAG, did not find expected whitespace or line break")
512 }
513 Self::InvalidTagTerminator => f.write_str(
514 "while scanning a tag, did not find expected whitespace or line break",
515 ),
516 Self::MissingTagUri => {
517 f.write_str("while parsing a tag, did not find expected tag URI")
518 }
519 Self::UnclosedVerbatimTag => {
520 f.write_str("while scanning a verbatim tag, did not find the expected '>'")
521 }
522 Self::InvalidTagEscape => {
523 f.write_str("while parsing a tag, found an invalid escape sequence")
524 }
525 Self::InvalidTagUtf8LeadingByte => {
526 f.write_str("while parsing a tag, found an incorrect leading UTF-8 byte")
527 }
528 Self::InvalidTagUtf8TrailingByte => {
529 f.write_str("while parsing a tag, found an incorrect trailing UTF-8 byte")
530 }
531 Self::InvalidTagUtf8 => {
532 f.write_str("while parsing a tag, found an invalid UTF-8 codepoint")
533 }
534 Self::MissingAnchorOrAliasName => f.write_str(
535 "while scanning an anchor or alias, did not find expected alphabetic or numeric character",
536 ),
537 Self::MisplacedFlowCollectionEnd => f.write_str("misplaced bracket"),
538 Self::MismatchedFlowCollectionEnd { open, close } => {
539 write!(f, "mismatched bracket '{open}' closed by '{close}'")
540 }
541 Self::UnclosedFlowCollection { open } => {
542 write!(f, "unclosed bracket '{open}'")
543 }
544 Self::RecursionLimitExceeded => f.write_str("recursion limit exceeded"),
545 Self::BlockEntryInFlowCollection => {
546 f.write_str(r#""-" is only valid inside a block"#)
547 }
548 Self::BlockSequenceEntryNotAllowed => {
549 f.write_str("block sequence entries are not allowed in this context")
550 }
551 Self::InvalidBlockEntryWhitespace => {
552 f.write_str("'-' must be followed by a valid YAML whitespace")
553 }
554 Self::ZeroBlockScalarIndent => f.write_str(
555 "while scanning a block scalar, found an indentation indicator equal to 0",
556 ),
557 Self::InvalidBlockScalarHeader => f.write_str(
558 "while scanning a block scalar, did not find expected comment or line break",
559 ),
560 Self::TabAtBlockScalarStart => {
561 f.write_str("a tab cannot be used to indent a block scalar line")
562 }
563 Self::InvalidBlockScalarIndent => {
564 f.write_str("wrongly indented line in block scalar")
565 }
566 Self::DocumentIndicatorInQuotedScalar => f.write_str(
567 "while scanning a quoted scalar, found unexpected document indicator",
568 ),
569 Self::UnclosedQuotedScalar => f.write_str("unclosed quote"),
570 Self::TabInIndentation => f.write_str("tab cannot be used as indentation"),
571 Self::InvalidQuotedScalarIndent => {
572 f.write_str("invalid indentation in multiline quoted scalar")
573 }
574 Self::InvalidTrailingSingleQuotedScalar => {
575 f.write_str("invalid trailing content after single-quoted scalar")
576 }
577 Self::InvalidTrailingDoubleQuotedScalar => {
578 f.write_str("invalid trailing content after double-quoted scalar")
579 }
580 Self::UnknownQuotedScalarEscape => {
581 f.write_str("while parsing a quoted scalar, found unknown escape character")
582 }
583 Self::InvalidQuotedScalarHexEscape => f.write_str(
584 "while parsing a quoted scalar, did not find expected hexadecimal number",
585 ),
586 Self::InvalidLowSurrogateHexEscape => f.write_str(
587 "while parsing a quoted scalar, did not find expected hexadecimal number for low surrogate",
588 ),
589 Self::InvalidLowSurrogate => {
590 f.write_str("while parsing a quoted scalar, found invalid low surrogate")
591 }
592 Self::MissingLowSurrogate => f.write_str(
593 "while parsing a quoted scalar, found high surrogate without following low surrogate",
594 ),
595 Self::UnpairedLowSurrogate => {
596 f.write_str("while parsing a quoted scalar, found unpaired low surrogate")
597 }
598 Self::InvalidUnicodeEscape => f.write_str(
599 "while parsing a quoted scalar, found invalid Unicode character escape code",
600 ),
601 Self::InvalidFlowScalarIndent => {
602 f.write_str("invalid indentation in flow construct")
603 }
604 Self::PlainScalarStartsWithDashFlowIndicator => {
605 f.write_str("plain scalar cannot start with '-' followed by ,[]{}")
606 }
607 Self::TabInPlainScalar => {
608 f.write_str("while scanning a plain scalar, found a tab")
609 }
610 Self::UnexpectedEndOfPlainScalar => f.write_str("unexpected end of plain scalar"),
611 Self::MappingKeyNotAllowed => {
612 f.write_str("mapping keys are not allowed in this context")
613 }
614 Self::FlowMappingValueAdjacentCollection => {
615 f.write_str("':' may not precede any of `[{` in flow mapping")
616 }
617 Self::InvalidMappingValueWhitespace => {
618 f.write_str("':' must be followed by a valid YAML whitespace")
619 }
620 Self::InvalidColonPlacement => f.write_str("illegal placement of ':' indicator"),
621 Self::MappingValueNotAllowed => {
622 f.write_str("mapping values are not allowed in this context")
623 }
624 }
625 }
626}
627
628#[cfg(not(feature = "error_messages"))]
629impl fmt::Display for ErrorKind {
630 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631 f.write_str("")
632 }
633}
634
635#[derive(Clone, PartialEq, Debug, Eq)]
637pub struct ScanError {
638 mark: Marker,
640 kind: ErrorKind,
642 source_stack: Vec<String>,
644}
645
646impl ScanError {
647 #[must_use]
653 #[cold]
654 pub fn new(loc: Marker, message: impl Into<String>) -> ScanError {
655 Self::from_kind(loc, ErrorKind::Custom(message.into()))
656 }
657
658 #[must_use]
659 #[cold]
660 pub(crate) fn from_kind(loc: Marker, kind: ErrorKind) -> ScanError {
661 ScanError {
662 mark: loc,
663 kind,
664 source_stack: Vec::new(),
665 }
666 }
667
668 #[must_use]
669 pub(crate) fn with_source_stack(mut self, source_stack: Vec<String>) -> Self {
670 self.source_stack = source_stack;
671 self
672 }
673
674 #[cold]
675 pub(crate) fn into_result<T>(self) -> Result<T, ScanError> {
676 Err(self)
677 }
678
679 #[must_use]
681 pub fn marker(&self) -> &Marker {
682 &self.mark
683 }
684
685 #[must_use]
687 pub fn kind(&self) -> &ErrorKind {
688 &self.kind
689 }
690
691 pub fn try_into_input_io_error(self) -> Result<InputIoError, Self> {
696 let Self {
697 mark,
698 kind,
699 source_stack,
700 } = self;
701
702 match kind {
703 ErrorKind::InputIo { error } => Ok(error),
704 kind => Err(Self {
705 mark,
706 kind,
707 source_stack,
708 }),
709 }
710 }
711
712 #[must_use]
714 pub fn source_stack(&self) -> &[String] {
715 &self.source_stack
716 }
717
718 #[must_use]
723 pub fn info(&self) -> String {
724 let mut info = self.kind.to_string();
725 if !info.is_empty() && self.source_stack().len() > 1 {
726 info.push_str("\nwhile parsing ");
727 info.push_str(&self.source_stack().join(" -> "));
728 }
729 info
730 }
731}
732
733impl fmt::Display for ScanError {
734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735 write!(
736 f,
737 "{} at char {} line {} column {}",
738 self.info(),
739 self.mark.index(),
740 self.mark.line(),
741 self.mark.col() + 1
742 )
743 }
744}
745
746impl core::error::Error for ScanError {
747 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
748 match &self.kind {
749 ErrorKind::InputIo { error } => Some(error),
750 _ => None,
751 }
752 }
753}
754
755#[cfg(test)]
756mod tests {
757 #[cfg(feature = "error_messages")]
758 use alloc::format;
759 #[cfg(feature = "error_messages")]
760 use alloc::string::String;
761 use alloc::string::ToString;
762
763 use super::{ErrorKind, InputIoError, ScanError};
764 use crate::scanner::Marker;
765
766 #[cfg(feature = "error_messages")]
767 #[test]
768 fn constructor_retains_kind_and_derives_info() {
769 let marker = Marker::new(3, 2, 1);
770 let error = ScanError::from_kind(marker, ErrorKind::ExpectedWhitespace);
771
772 assert_eq!(error.kind(), &ErrorKind::ExpectedWhitespace);
773 assert_eq!(error.kind().to_string(), "expected whitespace");
774 assert_eq!(error.info(), "expected whitespace");
775 }
776
777 #[cfg(feature = "error_messages")]
778 #[test]
779 fn parameterized_kind_constructs_info() {
780 let marker = Marker::new(3, 2, 1);
781 let error = ScanError::from_kind(
782 marker,
783 ErrorKind::MismatchedFlowCollectionEnd {
784 open: '[',
785 close: '}',
786 },
787 );
788
789 assert_eq!(error.info(), "mismatched bracket '[' closed by '}'");
790 assert_eq!(
791 format!("{error}"),
792 "mismatched bracket '[' closed by '}' at char 3 line 2 column 2"
793 );
794 }
795
796 #[cfg(feature = "error_messages")]
797 #[test]
798 fn input_error_kinds_construct_info() {
799 assert_eq!(
800 ErrorKind::InputIo {
801 error: InputIoError::from_message("connection reset")
802 }
803 .to_string(),
804 "input I/O error: connection reset"
805 );
806 assert_eq!(
807 ErrorKind::InputDecoding {
808 message: String::from("invalid utf-8")
809 }
810 .to_string(),
811 "input decoding error: invalid utf-8"
812 );
813 assert_eq!(
814 ErrorKind::InputByteLimitExceeded { limit: 4096 }.to_string(),
815 "input exceeds the configured limit of 4096 bytes"
816 );
817 }
818
819 #[test]
820 fn message_only_input_io_error_has_no_source() {
821 use core::error::Error as _;
822
823 let error = InputIoError::from_message("portable failure");
824
825 assert_eq!(error.message(), "portable failure");
826 assert!(error.source().is_none());
827 }
828
829 #[cfg(feature = "std")]
830 #[test]
831 fn std_input_io_error_is_retained_in_scan_error_source_chain() {
832 use core::error::Error as _;
833 use std::io;
834
835 let details = InputIoError::from(io::Error::new(io::ErrorKind::BrokenPipe, "pipe closed"));
836 assert_eq!(details.message(), "pipe closed");
837 assert_eq!(
838 details
839 .io_error()
840 .expect("std construction should retain io::Error")
841 .kind(),
842 io::ErrorKind::BrokenPipe
843 );
844
845 let error = ScanError::from_kind(
846 Marker::new(3, 2, 1),
847 ErrorKind::InputIo {
848 error: details.clone(),
849 },
850 );
851 let input_error = error
852 .source()
853 .and_then(|source| source.downcast_ref::<InputIoError>())
854 .expect("ScanError should expose InputIoError as its source");
855 let io_error = input_error
856 .source()
857 .and_then(|source| source.downcast_ref::<io::Error>())
858 .expect("InputIoError should expose the retained io::Error");
859
860 assert_eq!(io_error.kind(), io::ErrorKind::BrokenPipe);
861 assert_eq!(details, *input_error);
862 }
863
864 #[cfg(feature = "std")]
865 #[test]
866 fn unique_std_input_io_error_can_be_recovered() {
867 use std::io;
868
869 let details = InputIoError::from(io::Error::from_raw_os_error(12_345));
870 let error = details
871 .try_into_io_error()
872 .expect("a uniquely owned io::Error should be recoverable");
873
874 assert_eq!(error.raw_os_error(), Some(12_345));
875 }
876
877 #[cfg(feature = "std")]
878 #[test]
879 fn shared_std_input_io_error_can_be_recovered_after_other_clone_is_dropped() {
880 use std::io;
881
882 let details = InputIoError::from(io::Error::from_raw_os_error(12_345));
883 let other = details.clone();
884 let details = details
885 .try_into_io_error()
886 .expect_err("a shared io::Error cannot be moved out");
887
888 drop(other);
889
890 let error = details
891 .try_into_io_error()
892 .expect("the last owner should recover the io::Error");
893 assert_eq!(error.raw_os_error(), Some(12_345));
894 }
895
896 #[cfg(feature = "std")]
897 #[test]
898 fn scan_error_moves_input_io_error_out_without_cloning() {
899 use std::io;
900
901 let error = ScanError::from_kind(
902 Marker::new(3, 2, 1),
903 ErrorKind::InputIo {
904 error: InputIoError::from(io::Error::from_raw_os_error(12_345)),
905 },
906 );
907 let details = error
908 .try_into_input_io_error()
909 .expect("input I/O details should be extractable");
910 let error = details
911 .try_into_io_error()
912 .expect("extracting the scan error should retain unique ownership");
913
914 assert_eq!(error.raw_os_error(), Some(12_345));
915 }
916
917 #[test]
918 fn extracting_input_io_error_preserves_other_scan_errors() {
919 let error = ScanError::from_kind(Marker::new(3, 2, 1), ErrorKind::ExpectedWhitespace);
920 let error = error
921 .try_into_input_io_error()
922 .expect_err("a non-I/O scan error should be returned unchanged");
923
924 assert_eq!(error.marker(), &Marker::new(3, 2, 1));
925 assert_eq!(error.kind(), &ErrorKind::ExpectedWhitespace);
926 }
927
928 #[cfg(feature = "error_messages")]
929 #[test]
930 fn public_constructor_copies_custom_message() {
931 let marker = Marker::new(3, 2, 1);
932 let mut message = String::from("adapter failed");
933 let error = ScanError::new(marker, &message);
934 message.clear();
935
936 assert_eq!(
937 error.kind(),
938 &ErrorKind::Custom(String::from("adapter failed"))
939 );
940 assert_eq!(error.info(), "adapter failed");
941 }
942
943 #[cfg(not(feature = "error_messages"))]
944 #[test]
945 fn disabled_error_messages_are_empty() {
946 let marker = Marker::new(3, 2, 1);
947 let error = ScanError::from_kind(
948 marker,
949 ErrorKind::MismatchedFlowCollectionEnd {
950 open: '[',
951 close: '}',
952 },
953 );
954
955 assert_eq!(error.kind().to_string(), "");
956 assert_eq!(error.info(), "");
957 }
958}