menhirkv 0.4.5

MenhirKV is yet another local KV store based on RocksDB.
Documentation
// Copyright (C) 2024 Christian Mauduit <ufoot@ufoot.org>

use bincode;
use std::fmt;
use std::fmt::{Display, Formatter};

/// Error type used by MenhirKV.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Error {
    /// Database related error, very likely an underlying RocksDB error.
    Db(String),
    /// Invalid data, typically a serialization problem, or invalid input.
    InvalidData(String),
    /// Unexpected code path are behavior, please report issue on
    /// <https://gitlab.com/liberecofr/menhirkv/-/issues>.
    ReportBug(String),
    /// Feature is not implemented yet.
    NotImplemented,
}

/// URL to report bugs.
///
/// This is used internally to provide context when something unexpected happens,
/// so that users can find find out which piece of software fails,
/// and how to contact author(s).
///
/// Alternatively, send a direct email to <ufoot@ufoot.org>.
pub const BUG_REPORT_URL: &str = "https://gitlab.com/liberecofr/menhirkv/-/issues";

/// Result type used by MenhirKV.
pub type Result<T> = std::result::Result<T, Error>;

impl Error {
    pub(crate) fn db(why: &str) -> Error {
        Error::Db(why.to_string())
    }

    pub(crate) fn invalid_data(why: &str) -> Error {
        Error::InvalidData(why.to_string())
    }

    pub(crate) fn report_bug(why: &str) -> Error {
        Error::ReportBug(why.to_string())
    }

    pub(crate) fn not_implemented() -> Error {
        Error::NotImplemented
    }
}

/// Convert from a RocksDB error.
impl From<rocksdb::Error> for Error {
    fn from(e: rocksdb::Error) -> Error {
        Error::db(&format!("[rocksdb] {}", e))
    }
}

/// Convert from a bincode serialization error.
impl From<bincode::Error> for Error {
    fn from(e: bincode::Error) -> Error {
        Error::invalid_data(&format!("[bincode] {}", e))
    }
}

/// Convert from unit.
///
/// This returns "not implemented", it is just here to
/// make sure all the chain serving the "not implemented"
/// series of errors is here, and public API remains
/// stable.
impl From<()> for Error {
    fn from(_: ()) -> Error {
        Error::not_implemented()
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), fmt::Error> {
        match self {
            Error::Db(e) => write!(f, "DB error: {}", e),
            Error::InvalidData(e) => write!(f, "invalid data: {}", e),
            Error::ReportBug(e) => write!(
                f,
                "unexpected bug, please report issue on <{}>: {}",
                BUG_REPORT_URL, e
            ),
            Error::NotImplemented => write!(f, "not implemented"),
        }
    }
}