blob_stream/
err.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/nimble-rust/nimble
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5#[derive(Debug)]
6pub enum BlobError {
7    InvalidChunkIndex(usize, usize),
8    UnexpectedChunkSize(usize, usize, usize),
9    OutOfBounds,
10    RedundantContentDiffers(ChunkIndex),
11}
12
13impl fmt::Display for BlobError {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        match self {
16            Self::InvalidChunkIndex(index, max) => {
17                write!(f, "illegal chunk index: {index} (max: {max})")
18            }
19            Self::UnexpectedChunkSize(expected, found, id) => write!(
20                f,
21                "unexpected chunk size. expected {expected} but encountered {found} for chunk {id}"
22            ),
23            Self::OutOfBounds => write!(f, "calculated slice range is out of bounds"),
24            Self::RedundantContentDiffers(chunk_index) => write!(f, "chunk {chunk_index} has already been received, but now received different content for that chunk. this is serious"),
25        }
26    }
27}
28
29impl Error for BlobError {} // it implements Debug and Display
30
31use crate::ChunkIndex;
32use core::fmt;
33use std::error::Error;
34use std::io;
35
36impl From<BlobError> for io::Error {
37    fn from(err: BlobError) -> Self {
38        match err {
39            // Map your custom error to an appropriate io::Error kind
40            BlobError::InvalidChunkIndex(_, _) => {
41                Self::new(io::ErrorKind::InvalidInput, err.to_string())
42            }
43            BlobError::OutOfBounds => Self::new(io::ErrorKind::UnexpectedEof, err.to_string()),
44            BlobError::RedundantContentDiffers(_) | BlobError::UnexpectedChunkSize(_, _, _) => {
45                Self::new(io::ErrorKind::InvalidData, err.to_string())
46            }
47        }
48    }
49}