Skip to main content

inc_complete/db/
debug_with_db.rs

1use crate::Db;
2
3/// Format `Self` into a debug string similar to the `Debug` trait but
4/// with a `Db` to provide additional context. This is helpful to format
5/// id-based types into a more human readable format by grabbing additional
6/// data stored elsewhere.
7pub trait DebugWithDb<Storage>: Sized {
8    fn debug_with_db<'a>(&'a self, db: &'a Db<Storage>) -> DebugWithDbWrapper<'a, Self, Storage> {
9        DebugWithDbWrapper { obj: self, db }
10    }
11
12    fn fmt_with_db(&self, _db: &Db<Storage>, f: &mut std::fmt::Formatter) -> std::fmt::Result;
13}
14
15pub fn debug_with_db<'a, T, Storage>(obj: &'a T, db: &'a Db<Storage>) -> DebugWithDbWrapper<'a, T, Storage> {
16    DebugWithDbWrapper { obj, db }
17}
18
19/// Wrapper type returned by [DebugWithDb::debug_with_db] used for formatting
20pub struct DebugWithDbWrapper<'a, T, S> {
21    obj: &'a T,
22    db: &'a Db<S>,
23}
24
25impl<T, S> std::fmt::Debug for DebugWithDbWrapper<'_, T, S>
26    where
27        T: DebugWithDb<S>
28{
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        self.obj.fmt_with_db(self.db, f)
31    }
32}
33
34impl<T: std::fmt::Debug, S> DebugWithDb<S> for T {
35    fn fmt_with_db(&self, _db: &Db<S>, f: &mut std::fmt::Formatter) -> std::fmt::Result {
36        write!(f, "{self:?}")
37    }
38}