aws_smithy_types/byte_stream/
error.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Errors related to bytestreams.
7
8use std::error::Error as StdError;
9use std::fmt;
10use std::io::{Error as IoError, ErrorKind as IoErrorKind};
11
12#[derive(Debug)]
13pub(super) enum ErrorKind {
14    #[cfg(feature = "rt-tokio")]
15    OffsetLargerThanFileSize,
16    #[cfg(feature = "rt-tokio")]
17    LengthLargerThanFileSizeMinusReadOffset,
18    IoError(IoError),
19    StreamingError(Box<dyn StdError + Send + Sync + 'static>),
20}
21
22/// An error occurred in the byte stream
23#[derive(Debug)]
24pub struct Error {
25    kind: ErrorKind,
26}
27
28impl Error {
29    pub(super) fn streaming(err: impl Into<Box<dyn StdError + Send + Sync + 'static>>) -> Self {
30        ErrorKind::StreamingError(err.into()).into()
31    }
32}
33
34impl From<ErrorKind> for Error {
35    fn from(kind: ErrorKind) -> Self {
36        Self { kind }
37    }
38}
39
40impl From<IoError> for Error {
41    fn from(err: IoError) -> Self {
42        ErrorKind::IoError(err).into()
43    }
44}
45
46impl fmt::Display for Error {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self.kind {
49            #[cfg(feature = "rt-tokio")]
50            ErrorKind::OffsetLargerThanFileSize => write!(
51                f,
52                "offset must be less than or equal to file size but was greater than"
53            ),
54            #[cfg(feature = "rt-tokio")]
55            ErrorKind::LengthLargerThanFileSizeMinusReadOffset => write!(
56                f,
57                "`Length::Exact` was larger than file size minus read offset"
58            ),
59            ErrorKind::IoError(_) => write!(f, "IO error"),
60            ErrorKind::StreamingError(_) => write!(f, "streaming error"),
61        }
62    }
63}
64
65impl StdError for Error {
66    fn source(&self) -> Option<&(dyn StdError + 'static)> {
67        match &self.kind {
68            ErrorKind::IoError(err) => Some(err as _),
69            ErrorKind::StreamingError(err) => Some(err.as_ref() as _),
70            #[cfg(feature = "rt-tokio")]
71            ErrorKind::OffsetLargerThanFileSize
72            | ErrorKind::LengthLargerThanFileSizeMinusReadOffset => None,
73        }
74    }
75}
76
77impl From<Error> for IoError {
78    fn from(err: Error) -> Self {
79        IoError::new(IoErrorKind::Other, err)
80    }
81}