feat: add tables_to_generic! macro to convert between table values and types (#8518)

This commit is contained in:
DaniPopes
2024-05-30 21:30:20 +03:00
committed by GitHub
parent 80c0d618b4
commit 2a8a69384a
5 changed files with 55 additions and 152 deletions

View File

@ -78,6 +78,7 @@ pub mod mdbx;
pub use abstraction::*;
pub use reth_storage_errors::db::{DatabaseError, DatabaseWriteOperation};
pub use table::*;
pub use tables::*;
pub use utils::is_database_empty;

View File

@ -90,6 +90,11 @@ pub trait TableViewer<R> {
/// The error type returned by the viewer.
type Error;
/// Calls `view` with the correct table type.
fn view_rt(&self, table: Tables) -> Result<R, Self::Error> {
table.view(self)
}
/// Operate on the table in a generic way.
fn view<T: Table>(&self) -> Result<R, Self::Error>;
@ -101,8 +106,8 @@ pub trait TableViewer<R> {
}
}
#[macro_export]
/// Defines all the tables in the database.
#[macro_export]
macro_rules! tables {
(@bool) => { false };
(@bool $($t:tt)+) => { true };
@ -196,7 +201,7 @@ macro_rules! tables {
/// Allows to operate on specific table type
pub fn view<T, R>(&self, visitor: &T) -> Result<R, T::Error>
where
T: TableViewer<R>,
T: ?Sized + TableViewer<R>,
{
match self {
$(
@ -240,6 +245,33 @@ macro_rules! tables {
pub(super) const $name: &'static str = stringify!($name);
)*
}
/// Maps a run-time [`Tables`] enum value to its corresponding compile-time [`Table`] type.
///
/// This is a simpler alternative to [`TableViewer`].
///
/// # Examples
///
/// ```
/// use reth_db::{Table, Tables, tables_to_generic};
///
/// let table = Tables::Headers;
/// let result = tables_to_generic!(table, |GenericTable| GenericTable::TABLE);
/// assert_eq!(result, table);
/// ```
#[macro_export]
macro_rules! tables_to_generic {
($table:expr, |$generic_name:ident| $e:expr) => {
match $table {
$(
Tables::$name => {
use $crate::tables::$name as $generic_name;
$e
},
)*
}
};
}
};
}