Skip to main content

libdd_library_config/
io.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4//! Minimal stand-in for `core::io::{Error, ErrorKind, Result}`.
5//!
6//! These types are moving into `core` behind the unstable `core_io` feature
7//! (<https://github.com/rust-lang/rust/issues/154046>). This module mirrors the subset of that API
8//! available in `core`, so once it is stable and within our MSRV it can be replaced by
9//! `pub use core::io::{Error, ErrorKind, Result};` without changing [`ConfigRead`] implementations.
10//!
11//! [`ConfigRead`]: crate::ConfigRead
12
13use alloc::string::String;
14use core::fmt;
15
16pub type Result<T> = core::result::Result<T, Error>;
17
18/// Subset of `core::io::ErrorKind` relevant to reading configuration files.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum ErrorKind {
22    NotFound,
23    PermissionDenied,
24    InvalidData,
25    FileTooLarge,
26    Other,
27}
28
29impl fmt::Display for ErrorKind {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        f.write_str(match self {
32            ErrorKind::NotFound => "entity not found",
33            ErrorKind::PermissionDenied => "permission denied",
34            ErrorKind::InvalidData => "invalid data",
35            ErrorKind::FileTooLarge => "file too large",
36            ErrorKind::Other => "other error",
37        })
38    }
39}
40
41#[derive(Debug)]
42pub struct Error {
43    kind: ErrorKind,
44    /// The original message, when converted from a `std::io::Error`.
45    message: Option<String>,
46}
47
48impl Error {
49    pub fn kind(&self) -> ErrorKind {
50        self.kind
51    }
52}
53
54impl From<ErrorKind> for Error {
55    fn from(kind: ErrorKind) -> Self {
56        Self {
57            kind,
58            message: None,
59        }
60    }
61}
62
63impl fmt::Display for Error {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match &self.message {
66            Some(message) => f.write_str(message),
67            None => self.kind.fmt(f),
68        }
69    }
70}
71
72impl core::error::Error for Error {}
73
74#[cfg(feature = "std")]
75impl From<std::io::Error> for Error {
76    fn from(err: std::io::Error) -> Self {
77        let kind = match err.kind() {
78            std::io::ErrorKind::NotFound => ErrorKind::NotFound,
79            std::io::ErrorKind::PermissionDenied => ErrorKind::PermissionDenied,
80            std::io::ErrorKind::InvalidData => ErrorKind::InvalidData,
81            std::io::ErrorKind::FileTooLarge => ErrorKind::FileTooLarge,
82            _ => ErrorKind::Other,
83        };
84        Self {
85            kind,
86            message: Some(err.to_string()),
87        }
88    }
89}