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 UnknownAnchor,
188 ExpectedNodeContent,
190 ExpectedBlockMappingKey,
192 ExpectedFlowMappingSeparator,
194 ExpectedFlowSequenceSeparator,
196 ExpectedBlockSequenceEntry,
198 UndeclaredTagHandle,
200 MissingIncludeResolver,
202 Custom(String),
204 MultipleDocumentsUnsupported,
206 InputOffsetsWithoutSlice,
208 InputSlicingUnavailable,
210 ExpectedTagBang,
212 ExpectedTagDirectiveBang,
214 InvalidGlobalTagCharacter,
216 SimpleKeyExpected,
218 InvalidSimpleKey,
220 InvalidDocumentEnd,
222 InvalidIndentation,
224 BomInsideDocument,
226 UnexpectedCharacter {
228 character: char,
230 },
231 TabNotAllowed,
233 TabInBlockIndentation,
235 CommentInterceptedScalar,
237 ExpectedWhitespace,
239 CommentNotSeparated,
241 InvalidDirectiveTerminator,
243 MissingYamlVersionSeparator,
245 MissingDirectiveName,
247 InvalidDirectiveName,
249 DirectiveByteLimitExceeded {
251 limit: usize,
253 },
254 TooManyReservedDirectiveParams {
256 limit: usize,
258 },
259 YamlVersionTooLong,
261 MissingYamlVersion,
263 InvalidTagDirectiveTerminator,
265 InvalidTagTerminator,
267 MissingTagUri,
269 UnclosedVerbatimTag,
271 InvalidTagEscape,
273 InvalidTagUtf8LeadingByte,
275 InvalidTagUtf8TrailingByte,
277 InvalidTagUtf8,
279 MissingAnchorOrAliasName,
281 MisplacedFlowCollectionEnd,
283 MismatchedFlowCollectionEnd {
285 open: char,
287 close: char,
289 },
290 UnclosedFlowCollection {
292 open: char,
294 },
295 RecursionLimitExceeded,
297 BlockEntryInFlowCollection,
299 BlockSequenceEntryNotAllowed,
301 InvalidBlockEntryWhitespace,
303 ZeroBlockScalarIndent,
305 InvalidBlockScalarHeader,
307 TabAtBlockScalarStart,
309 InvalidBlockScalarIndent,
311 DocumentIndicatorInQuotedScalar,
313 UnclosedQuotedScalar,
315 TabInIndentation,
317 InvalidQuotedScalarIndent,
319 InvalidTrailingSingleQuotedScalar,
321 InvalidTrailingDoubleQuotedScalar,
323 UnknownQuotedScalarEscape,
325 InvalidQuotedScalarHexEscape,
327 InvalidLowSurrogateHexEscape,
329 InvalidLowSurrogate,
331 MissingLowSurrogate,
333 UnpairedLowSurrogate,
335 InvalidUnicodeEscape,
337 InvalidFlowScalarIndent,
339 PlainScalarStartsWithDashFlowIndicator,
341 TabInPlainScalar,
343 UnexpectedEndOfPlainScalar,
345 MappingKeyNotAllowed,
347 FlowMappingValueAdjacentCollection,
349 InvalidMappingValueWhitespace,
351 InvalidColonPlacement,
353 MappingValueNotAllowed,
355}
356
357#[cfg(feature = "error_messages")]
358impl fmt::Display for ErrorKind {
359 #[allow(clippy::too_many_lines)]
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 match self {
362 #[cfg(feature = "comments")]
363 Self::TooManyComments => {
364 f.write_str("too many consecutive comments before resolving collection entry")
365 }
366 Self::InputIo { error } => write!(f, "input I/O error: {error}"),
367 Self::InputDecoding { message } => {
368 write!(f, "input decoding error: {message}")
369 }
370 Self::InputByteLimitExceeded { limit } => {
371 write!(f, "input exceeds the configured limit of {limit} bytes")
372 }
373 Self::UnexpectedEofFlowSequence => {
374 f.write_str("unexpected EOF while parsing a flow sequence")
375 }
376 Self::UnexpectedEofFlowMapping => {
377 f.write_str("unexpected EOF while parsing a flow mapping")
378 }
379 Self::UnexpectedEofImplicitFlowMapping => {
380 f.write_str("unexpected EOF while parsing an implicit flow mapping")
381 }
382 Self::UnexpectedEofBlockSequence => {
383 f.write_str("unexpected EOF while parsing a block sequence")
384 }
385 Self::UnexpectedEofBlockMapping => {
386 f.write_str("unexpected EOF while parsing a block mapping")
387 }
388 Self::UnexpectedEof => f.write_str("unexpected eof"),
389 Self::ExpectedStreamStart => f.write_str("did not find expected <stream-start>"),
390 Self::DuplicateVersionDirective => f.write_str("duplicate version directive"),
391 Self::UnsupportedYamlMajorVersion => {
392 f.write_str("unsupported YAML major version")
393 }
394 Self::DuplicateTagDirective => f.write_str(
395 "the TAG directive must only be given at most once per handle in the same document",
396 ),
397 Self::ExpectedDocumentStart => {
398 f.write_str("did not find expected <document start>")
399 }
400 Self::MissingDocumentEndBeforeDirective => {
401 f.write_str("missing explicit document end marker before directive")
402 }
403 Self::AnchorCountOverflow => {
404 f.write_str("while parsing anchor, anchor count exceeded supported limit")
405 }
406 Self::UnknownAnchor => f.write_str("while parsing node, found unknown anchor"),
407 Self::ExpectedNodeContent => {
408 f.write_str("while parsing a node, did not find expected node content")
409 }
410 Self::ExpectedBlockMappingKey => {
411 f.write_str("while parsing a block mapping, did not find expected key")
412 }
413 Self::ExpectedFlowMappingSeparator => {
414 f.write_str("while parsing a flow mapping, did not find expected ',' or '}'")
415 }
416 Self::ExpectedFlowSequenceSeparator => {
417 f.write_str("while parsing a flow sequence, expected ',' or ']'")
418 }
419 Self::ExpectedBlockSequenceEntry => f.write_str(
420 "while parsing a block collection, did not find expected '-' indicator",
421 ),
422 Self::UndeclaredTagHandle => f.write_str("the handle wasn't declared"),
423 Self::MissingIncludeResolver => {
424 f.write_str("No include resolver set for parser stack.")
425 }
426 Self::Custom(message) => f.write_str(message),
427 Self::MultipleDocumentsUnsupported => {
428 f.write_str("multiple documents not supported here")
429 }
430 Self::InputOffsetsWithoutSlice => f.write_str(
431 "internal error: input advertised offsets but did not provide a slice",
432 ),
433 Self::InputSlicingUnavailable => f.write_str(
434 "internal error: input advertised slicing but did not provide a slice",
435 ),
436 Self::ExpectedTagBang => {
437 f.write_str("while scanning a tag, did not find expected '!'")
438 }
439 Self::ExpectedTagDirectiveBang => {
440 f.write_str("while parsing a tag directive, did not find expected '!'")
441 }
442 Self::InvalidGlobalTagCharacter => f.write_str("invalid global tag character"),
443 Self::SimpleKeyExpected => f.write_str("simple key expected ':'"),
444 Self::InvalidSimpleKey => f.write_str("simple key is no longer valid"),
445 Self::InvalidDocumentEnd => {
446 f.write_str("invalid content after document end marker")
447 }
448 Self::InvalidIndentation => f.write_str("invalid indentation"),
449 Self::BomInsideDocument => {
450 f.write_str("a BOM must not appear inside a document")
451 }
452 Self::UnexpectedCharacter { character } => {
453 write!(f, "unexpected character: `{}'", character.escape_default())
454 }
455 Self::TabNotAllowed => f.write_str("tabs disallowed in this context"),
456 Self::TabInBlockIndentation => {
457 f.write_str("tabs disallowed within this context (block indentation)")
458 }
459 Self::CommentInterceptedScalar => {
460 f.write_str("comment intercepting the multiline text")
461 }
462 Self::ExpectedWhitespace => f.write_str("expected whitespace"),
463 Self::CommentNotSeparated => {
464 f.write_str("comments must be separated from other tokens by whitespace")
465 }
466 Self::InvalidDirectiveTerminator => f.write_str(
467 "while scanning a directive, did not find expected comment or line break",
468 ),
469 Self::MissingYamlVersionSeparator => f.write_str(
470 "while scanning a YAML directive, did not find expected digit or '.' character",
471 ),
472 Self::MissingDirectiveName => f.write_str(
473 "while scanning a directive, could not find expected directive name",
474 ),
475 Self::InvalidDirectiveName => f.write_str(
476 "while scanning a directive, found unexpected non-alphabetical character",
477 ),
478 Self::DirectiveByteLimitExceeded { limit } => write!(
479 f,
480 "directive exceeds the configured limit of {limit} bytes"
481 ),
482 Self::TooManyReservedDirectiveParams { limit } => write!(
483 f,
484 "reserved directive exceeds the configured limit of {limit} parameters"
485 ),
486 Self::YamlVersionTooLong => {
487 f.write_str("while scanning a YAML directive, found extremely long version number")
488 }
489 Self::MissingYamlVersion => f.write_str(
490 "while scanning a YAML directive, did not find expected version number",
491 ),
492 Self::InvalidTagDirectiveTerminator => {
493 f.write_str("while scanning TAG, did not find expected whitespace or line break")
494 }
495 Self::InvalidTagTerminator => f.write_str(
496 "while scanning a tag, did not find expected whitespace or line break",
497 ),
498 Self::MissingTagUri => {
499 f.write_str("while parsing a tag, did not find expected tag URI")
500 }
501 Self::UnclosedVerbatimTag => {
502 f.write_str("while scanning a verbatim tag, did not find the expected '>'")
503 }
504 Self::InvalidTagEscape => {
505 f.write_str("while parsing a tag, found an invalid escape sequence")
506 }
507 Self::InvalidTagUtf8LeadingByte => {
508 f.write_str("while parsing a tag, found an incorrect leading UTF-8 byte")
509 }
510 Self::InvalidTagUtf8TrailingByte => {
511 f.write_str("while parsing a tag, found an incorrect trailing UTF-8 byte")
512 }
513 Self::InvalidTagUtf8 => {
514 f.write_str("while parsing a tag, found an invalid UTF-8 codepoint")
515 }
516 Self::MissingAnchorOrAliasName => f.write_str(
517 "while scanning an anchor or alias, did not find expected alphabetic or numeric character",
518 ),
519 Self::MisplacedFlowCollectionEnd => f.write_str("misplaced bracket"),
520 Self::MismatchedFlowCollectionEnd { open, close } => {
521 write!(f, "mismatched bracket '{open}' closed by '{close}'")
522 }
523 Self::UnclosedFlowCollection { open } => {
524 write!(f, "unclosed bracket '{open}'")
525 }
526 Self::RecursionLimitExceeded => f.write_str("recursion limit exceeded"),
527 Self::BlockEntryInFlowCollection => {
528 f.write_str(r#""-" is only valid inside a block"#)
529 }
530 Self::BlockSequenceEntryNotAllowed => {
531 f.write_str("block sequence entries are not allowed in this context")
532 }
533 Self::InvalidBlockEntryWhitespace => {
534 f.write_str("'-' must be followed by a valid YAML whitespace")
535 }
536 Self::ZeroBlockScalarIndent => f.write_str(
537 "while scanning a block scalar, found an indentation indicator equal to 0",
538 ),
539 Self::InvalidBlockScalarHeader => f.write_str(
540 "while scanning a block scalar, did not find expected comment or line break",
541 ),
542 Self::TabAtBlockScalarStart => {
543 f.write_str("a block scalar content cannot start with a tab")
544 }
545 Self::InvalidBlockScalarIndent => {
546 f.write_str("wrongly indented line in block scalar")
547 }
548 Self::DocumentIndicatorInQuotedScalar => f.write_str(
549 "while scanning a quoted scalar, found unexpected document indicator",
550 ),
551 Self::UnclosedQuotedScalar => f.write_str("unclosed quote"),
552 Self::TabInIndentation => f.write_str("tab cannot be used as indentation"),
553 Self::InvalidQuotedScalarIndent => {
554 f.write_str("invalid indentation in multiline quoted scalar")
555 }
556 Self::InvalidTrailingSingleQuotedScalar => {
557 f.write_str("invalid trailing content after single-quoted scalar")
558 }
559 Self::InvalidTrailingDoubleQuotedScalar => {
560 f.write_str("invalid trailing content after double-quoted scalar")
561 }
562 Self::UnknownQuotedScalarEscape => {
563 f.write_str("while parsing a quoted scalar, found unknown escape character")
564 }
565 Self::InvalidQuotedScalarHexEscape => f.write_str(
566 "while parsing a quoted scalar, did not find expected hexadecimal number",
567 ),
568 Self::InvalidLowSurrogateHexEscape => f.write_str(
569 "while parsing a quoted scalar, did not find expected hexadecimal number for low surrogate",
570 ),
571 Self::InvalidLowSurrogate => {
572 f.write_str("while parsing a quoted scalar, found invalid low surrogate")
573 }
574 Self::MissingLowSurrogate => f.write_str(
575 "while parsing a quoted scalar, found high surrogate without following low surrogate",
576 ),
577 Self::UnpairedLowSurrogate => {
578 f.write_str("while parsing a quoted scalar, found unpaired low surrogate")
579 }
580 Self::InvalidUnicodeEscape => f.write_str(
581 "while parsing a quoted scalar, found invalid Unicode character escape code",
582 ),
583 Self::InvalidFlowScalarIndent => {
584 f.write_str("invalid indentation in flow construct")
585 }
586 Self::PlainScalarStartsWithDashFlowIndicator => {
587 f.write_str("plain scalar cannot start with '-' followed by ,[]{}")
588 }
589 Self::TabInPlainScalar => {
590 f.write_str("while scanning a plain scalar, found a tab")
591 }
592 Self::UnexpectedEndOfPlainScalar => f.write_str("unexpected end of plain scalar"),
593 Self::MappingKeyNotAllowed => {
594 f.write_str("mapping keys are not allowed in this context")
595 }
596 Self::FlowMappingValueAdjacentCollection => {
597 f.write_str("':' may not precede any of `[{` in flow mapping")
598 }
599 Self::InvalidMappingValueWhitespace => {
600 f.write_str("':' must be followed by a valid YAML whitespace")
601 }
602 Self::InvalidColonPlacement => f.write_str("illegal placement of ':' indicator"),
603 Self::MappingValueNotAllowed => {
604 f.write_str("mapping values are not allowed in this context")
605 }
606 }
607 }
608}
609
610#[cfg(not(feature = "error_messages"))]
611impl fmt::Display for ErrorKind {
612 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613 f.write_str("")
614 }
615}
616
617#[derive(Clone, PartialEq, Debug, Eq)]
619pub struct ScanError {
620 mark: Marker,
622 kind: ErrorKind,
624 source_stack: Vec<String>,
626}
627
628impl ScanError {
629 #[must_use]
635 #[cold]
636 pub fn new(loc: Marker, message: impl Into<String>) -> ScanError {
637 Self::from_kind(loc, ErrorKind::Custom(message.into()))
638 }
639
640 #[must_use]
641 #[cold]
642 pub(crate) fn from_kind(loc: Marker, kind: ErrorKind) -> ScanError {
643 ScanError {
644 mark: loc,
645 kind,
646 source_stack: Vec::new(),
647 }
648 }
649
650 #[must_use]
651 pub(crate) fn with_source_stack(mut self, source_stack: Vec<String>) -> Self {
652 self.source_stack = source_stack;
653 self
654 }
655
656 #[cold]
657 pub(crate) fn into_result<T>(self) -> Result<T, ScanError> {
658 Err(self)
659 }
660
661 #[must_use]
663 pub fn marker(&self) -> &Marker {
664 &self.mark
665 }
666
667 #[must_use]
669 pub fn kind(&self) -> &ErrorKind {
670 &self.kind
671 }
672
673 pub fn try_into_input_io_error(self) -> Result<InputIoError, Self> {
678 let Self {
679 mark,
680 kind,
681 source_stack,
682 } = self;
683
684 match kind {
685 ErrorKind::InputIo { error } => Ok(error),
686 kind => Err(Self {
687 mark,
688 kind,
689 source_stack,
690 }),
691 }
692 }
693
694 #[must_use]
696 pub fn source_stack(&self) -> &[String] {
697 &self.source_stack
698 }
699
700 #[must_use]
705 pub fn info(&self) -> String {
706 let mut info = self.kind.to_string();
707 if !info.is_empty() && self.source_stack().len() > 1 {
708 info.push_str("\nwhile parsing ");
709 info.push_str(&self.source_stack().join(" -> "));
710 }
711 info
712 }
713}
714
715impl fmt::Display for ScanError {
716 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
717 write!(
718 f,
719 "{} at char {} line {} column {}",
720 self.info(),
721 self.mark.index(),
722 self.mark.line(),
723 self.mark.col() + 1
724 )
725 }
726}
727
728impl core::error::Error for ScanError {
729 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
730 match &self.kind {
731 ErrorKind::InputIo { error } => Some(error),
732 _ => None,
733 }
734 }
735}
736
737#[cfg(test)]
738mod tests {
739 #[cfg(feature = "error_messages")]
740 use alloc::format;
741 #[cfg(feature = "error_messages")]
742 use alloc::string::String;
743 use alloc::string::ToString;
744
745 use super::{ErrorKind, InputIoError, ScanError};
746 use crate::scanner::Marker;
747
748 #[cfg(feature = "error_messages")]
749 #[test]
750 fn constructor_retains_kind_and_derives_info() {
751 let marker = Marker::new(3, 2, 1);
752 let error = ScanError::from_kind(marker, ErrorKind::ExpectedWhitespace);
753
754 assert_eq!(error.kind(), &ErrorKind::ExpectedWhitespace);
755 assert_eq!(error.kind().to_string(), "expected whitespace");
756 assert_eq!(error.info(), "expected whitespace");
757 }
758
759 #[cfg(feature = "error_messages")]
760 #[test]
761 fn parameterized_kind_constructs_info() {
762 let marker = Marker::new(3, 2, 1);
763 let error = ScanError::from_kind(
764 marker,
765 ErrorKind::MismatchedFlowCollectionEnd {
766 open: '[',
767 close: '}',
768 },
769 );
770
771 assert_eq!(error.info(), "mismatched bracket '[' closed by '}'");
772 assert_eq!(
773 format!("{error}"),
774 "mismatched bracket '[' closed by '}' at char 3 line 2 column 2"
775 );
776 }
777
778 #[cfg(feature = "error_messages")]
779 #[test]
780 fn input_error_kinds_construct_info() {
781 assert_eq!(
782 ErrorKind::InputIo {
783 error: InputIoError::from_message("connection reset")
784 }
785 .to_string(),
786 "input I/O error: connection reset"
787 );
788 assert_eq!(
789 ErrorKind::InputDecoding {
790 message: String::from("invalid utf-8")
791 }
792 .to_string(),
793 "input decoding error: invalid utf-8"
794 );
795 assert_eq!(
796 ErrorKind::InputByteLimitExceeded { limit: 4096 }.to_string(),
797 "input exceeds the configured limit of 4096 bytes"
798 );
799 }
800
801 #[test]
802 fn message_only_input_io_error_has_no_source() {
803 use core::error::Error as _;
804
805 let error = InputIoError::from_message("portable failure");
806
807 assert_eq!(error.message(), "portable failure");
808 assert!(error.source().is_none());
809 }
810
811 #[cfg(feature = "std")]
812 #[test]
813 fn std_input_io_error_is_retained_in_scan_error_source_chain() {
814 use core::error::Error as _;
815 use std::io;
816
817 let details = InputIoError::from(io::Error::new(io::ErrorKind::BrokenPipe, "pipe closed"));
818 assert_eq!(details.message(), "pipe closed");
819 assert_eq!(
820 details
821 .io_error()
822 .expect("std construction should retain io::Error")
823 .kind(),
824 io::ErrorKind::BrokenPipe
825 );
826
827 let error = ScanError::from_kind(
828 Marker::new(3, 2, 1),
829 ErrorKind::InputIo {
830 error: details.clone(),
831 },
832 );
833 let input_error = error
834 .source()
835 .and_then(|source| source.downcast_ref::<InputIoError>())
836 .expect("ScanError should expose InputIoError as its source");
837 let io_error = input_error
838 .source()
839 .and_then(|source| source.downcast_ref::<io::Error>())
840 .expect("InputIoError should expose the retained io::Error");
841
842 assert_eq!(io_error.kind(), io::ErrorKind::BrokenPipe);
843 assert_eq!(details, *input_error);
844 }
845
846 #[cfg(feature = "std")]
847 #[test]
848 fn unique_std_input_io_error_can_be_recovered() {
849 use std::io;
850
851 let details = InputIoError::from(io::Error::from_raw_os_error(12_345));
852 let error = details
853 .try_into_io_error()
854 .expect("a uniquely owned io::Error should be recoverable");
855
856 assert_eq!(error.raw_os_error(), Some(12_345));
857 }
858
859 #[cfg(feature = "std")]
860 #[test]
861 fn shared_std_input_io_error_can_be_recovered_after_other_clone_is_dropped() {
862 use std::io;
863
864 let details = InputIoError::from(io::Error::from_raw_os_error(12_345));
865 let other = details.clone();
866 let details = details
867 .try_into_io_error()
868 .expect_err("a shared io::Error cannot be moved out");
869
870 drop(other);
871
872 let error = details
873 .try_into_io_error()
874 .expect("the last owner should recover the io::Error");
875 assert_eq!(error.raw_os_error(), Some(12_345));
876 }
877
878 #[cfg(feature = "std")]
879 #[test]
880 fn scan_error_moves_input_io_error_out_without_cloning() {
881 use std::io;
882
883 let error = ScanError::from_kind(
884 Marker::new(3, 2, 1),
885 ErrorKind::InputIo {
886 error: InputIoError::from(io::Error::from_raw_os_error(12_345)),
887 },
888 );
889 let details = error
890 .try_into_input_io_error()
891 .expect("input I/O details should be extractable");
892 let error = details
893 .try_into_io_error()
894 .expect("extracting the scan error should retain unique ownership");
895
896 assert_eq!(error.raw_os_error(), Some(12_345));
897 }
898
899 #[test]
900 fn extracting_input_io_error_preserves_other_scan_errors() {
901 let error = ScanError::from_kind(Marker::new(3, 2, 1), ErrorKind::ExpectedWhitespace);
902 let error = error
903 .try_into_input_io_error()
904 .expect_err("a non-I/O scan error should be returned unchanged");
905
906 assert_eq!(error.marker(), &Marker::new(3, 2, 1));
907 assert_eq!(error.kind(), &ErrorKind::ExpectedWhitespace);
908 }
909
910 #[cfg(feature = "error_messages")]
911 #[test]
912 fn public_constructor_copies_custom_message() {
913 let marker = Marker::new(3, 2, 1);
914 let mut message = String::from("adapter failed");
915 let error = ScanError::new(marker, &message);
916 message.clear();
917
918 assert_eq!(
919 error.kind(),
920 &ErrorKind::Custom(String::from("adapter failed"))
921 );
922 assert_eq!(error.info(), "adapter failed");
923 }
924
925 #[cfg(not(feature = "error_messages"))]
926 #[test]
927 fn disabled_error_messages_are_empty() {
928 let marker = Marker::new(3, 2, 1);
929 let error = ScanError::from_kind(
930 marker,
931 ErrorKind::MismatchedFlowCollectionEnd {
932 open: '[',
933 close: '}',
934 },
935 );
936
937 assert_eq!(error.kind().to_string(), "");
938 assert_eq!(error.info(), "");
939 }
940}