Skip to content

Commit

Permalink
Replace hand-written Debug impls with custom_debug_derive.
Browse files Browse the repository at this point in the history
  • Loading branch information
afck committed Nov 13, 2024
1 parent 7c20047 commit ea6eaaf
Show file tree
Hide file tree
Showing 9 changed files with 123 additions and 363 deletions.
22 changes: 8 additions & 14 deletions linera-base/src/data_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -970,25 +970,19 @@ impl Hash for BlobBytes {
}

/// A blob of binary data.
#[derive(Hash, Clone, Serialize, Deserialize, WitType, WitStore)]
#[derive(Hash, Clone, Debug, Serialize, Deserialize, WitType, WitStore)]
#[cfg_attr(with_testing, derive(Eq, PartialEq))]
pub enum BlobContent {
/// A generic data blob.
Data(#[serde(with = "serde_bytes")] Vec<u8>),
Data(
#[serde(with = "serde_bytes")]
#[debug(skip)]
Vec<u8>,
),
/// A blob containing contract bytecode.
ContractBytecode(CompressedBytecode),
ContractBytecode(#[debug(skip)] CompressedBytecode),
/// A blob containing service bytecode.
ServiceBytecode(CompressedBytecode),
}

impl fmt::Debug for BlobContent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BlobContent::Data(_) => write!(f, "BlobContent::Data"),
BlobContent::ContractBytecode(_) => write!(f, "BlobContent::ContractBytecode"),
BlobContent::ServiceBytecode(_) => write!(f, "BlobContent::ServiceBytecode"),
}
}
ServiceBytecode(#[debug(skip)] CompressedBytecode),
}

impl BlobContent {
Expand Down
34 changes: 3 additions & 31 deletions linera-base/src/identifiers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ pub struct MessageId {
}

/// A unique identifier for a user application.
#[derive(WitLoad, WitStore, WitType)]
#[derive(Debug, WitLoad, WitStore, WitType)]
#[cfg_attr(with_testing, derive(Default))]
pub struct ApplicationId<A = ()> {
/// The bytecode to use for the application.
Expand Down Expand Up @@ -357,14 +357,15 @@ impl From<ApplicationId> for GenericApplicationId {
}

/// A unique identifier for an application bytecode.
#[derive(WitLoad, WitStore, WitType)]
#[derive(Debug, WitLoad, WitStore, WitType)]
#[cfg_attr(with_testing, derive(Default))]
pub struct BytecodeId<Abi = (), Parameters = (), InstantiationArgument = ()> {
/// The hash of the blob containing the contract bytecode.
pub contract_blob_hash: CryptoHash,
/// The hash of the blob containing the service bytecode.
pub service_blob_hash: CryptoHash,
#[witty(skip)]
#[debug(skip)]
_phantom: PhantomData<(Abi, Parameters, InstantiationArgument)>,
}

Expand Down Expand Up @@ -569,22 +570,6 @@ impl<Abi, Parameters, InstantiationArgument> Hash
}
}

impl<Abi, Parameters, InstantiationArgument> fmt::Debug
for BytecodeId<Abi, Parameters, InstantiationArgument>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let BytecodeId {
contract_blob_hash: contract_blob_id,
service_blob_hash: service_blob_id,
_phantom,
} = self;
f.debug_struct("BytecodeId")
.field("contract_blob_id", contract_blob_id)
.field("service_blob_id", service_blob_id)
.finish_non_exhaustive()
}
}

#[derive(Serialize, Deserialize)]
#[serde(rename = "BytecodeId")]
struct SerializableBytecodeId {
Expand Down Expand Up @@ -741,19 +726,6 @@ impl<A> Hash for ApplicationId<A> {
}
}

impl<A> fmt::Debug for ApplicationId<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ApplicationId {
bytecode_id,
creation,
} = self;
f.debug_struct("ApplicationId")
.field("bytecode_id", bytecode_id)
.field("creation", creation)
.finish()
}
}

#[derive(Serialize, Deserialize)]
#[serde(rename = "ApplicationId")]
struct SerializableApplicationId {
Expand Down
39 changes: 38 additions & 1 deletion linera-base/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#![deny(missing_docs)]
#![deny(clippy::large_futures)]

use std::fmt;

#[doc(hidden)]
pub use async_trait::async_trait;

Expand Down Expand Up @@ -93,7 +95,7 @@ macro_rules! ensure {
/// "Message { bytes: 20202020202020203130202020202020..20202020343020202020202020203530 }"
/// );
/// ```
pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut std::fmt::Formatter) -> std::fmt::Result {
pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut fmt::Formatter) -> fmt::Result {
const ELIDE_AFTER: usize = 16;
let bytes = bytes.as_ref();
if bytes.len() <= 2 * ELIDE_AFTER {
Expand All @@ -108,3 +110,38 @@ pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut std::fmt::Formatter) -> std:
}
Ok(())
}

/// Applies `hex_debug` to a slice of byte vectors.
///
/// # Examples
///
/// ```
/// # use linera_base::hex_vec_debug;
/// use custom_debug_derive::Debug;
///
/// #[derive(Debug)]
/// struct Messages {
/// #[debug(with = "hex_vec_debug")]
/// byte_vecs: Vec<Vec<u8>>,
/// }
///
/// let msgs = Messages {
/// byte_vecs: vec![vec![0x12, 0x34, 0x56, 0x78], vec![0x9A]],
/// };
///
/// assert_eq!(
/// format!("{:?}", msgs),
/// "Messages { byte_vecs: [12345678, 9a] }"
/// );
/// ```
#[allow(clippy::ptr_arg)] // This only works with custom_debug_derive if it's &Vec.
pub fn hex_vec_debug(list: &Vec<Vec<u8>>, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
for (i, bytes) in list.iter().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
hex_debug(bytes, f)?;
}
write!(f, "]")
}
27 changes: 4 additions & 23 deletions linera-chain/src/certificate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
borrow::Cow,
fmt::{Debug, Formatter},
};
use std::borrow::Cow;

use custom_debug_derive::Debug;
use linera_base::{
crypto::{BcsHashable, CryptoHash, Signature},
data_types::Round,
Expand Down Expand Up @@ -37,6 +35,7 @@ pub type ConfirmedBlockCertificate = GenericCertificate<ConfirmedBlock>;
pub type TimeoutCertificate = GenericCertificate<Timeout>;

/// Generic type representing a certificate for `value` of type `T`.
#[derive(Debug)]
pub struct GenericCertificate<T> {
value: Hashed<T>,
pub round: Round,
Expand Down Expand Up @@ -65,16 +64,6 @@ impl<T: Clone> Clone for GenericCertificate<T> {
}
}

impl<T: Debug> Debug for GenericCertificate<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CertificateT")
.field("value", &self.value)
.field("round", &self.round)
.field("signatures", &self.signatures)
.finish()
}
}

impl Serialize for ValidatedBlockCertificate {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let ValidatedBlockCertificate {
Expand Down Expand Up @@ -207,6 +196,7 @@ impl From<TimeoutCertificate> for Certificate {
}

/// Wrapper type around hashed instance of `T` type.
#[derive(Debug)]
pub struct Hashed<T> {
value: T,
/// Hash of the value (used as key for storage).
Expand Down Expand Up @@ -248,15 +238,6 @@ impl<T> Hashed<T> {
}
}

impl<T: Debug> Debug for Hashed<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HashedT")
.field("value", &self.value)
.field("hash", &self.hash())
.finish()
}
}

impl<T: Clone> Clone for Hashed<T> {
fn clone(&self) -> Self {
Self {
Expand Down
15 changes: 4 additions & 11 deletions linera-client/src/persistent/indexed_db.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use custom_debug_derive::Debug;

Check failure on line 4 in linera-client/src/persistent/indexed_db.rs

View workflow job for this annotation

GitHub Actions / lint-cargo-clippy

unresolved import `custom_debug_derive`

Check failure on line 4 in linera-client/src/persistent/indexed_db.rs

View workflow job for this annotation

GitHub Actions / web

unresolved import `custom_debug_derive`
use indexed_db_futures::prelude::*;
use tracing::instrument;
use wasm_bindgen::JsValue;
Expand All @@ -10,25 +11,17 @@ use web_sys::DomException;
use super::{dirty::Dirty, LocalPersist};

/// An implementation of [`Persist`] based on an IndexedDB record with a given key.
#[derive(derive_more::Deref)]
#[derive(derive_more::Deref, Debug)]
pub struct IndexedDb<T> {
key: String,
#[deref]
#[debug(with = serde_json::to_string)]

Check failure on line 18 in linera-client/src/persistent/indexed_db.rs

View workflow job for this annotation

GitHub Actions / lint-cargo-clippy

cannot find attribute `debug` in this scope

Check failure on line 18 in linera-client/src/persistent/indexed_db.rs

View workflow job for this annotation

GitHub Actions / web

cannot find attribute `debug` in this scope
value: T,
#[debug(skip)]

Check failure on line 20 in linera-client/src/persistent/indexed_db.rs

View workflow job for this annotation

GitHub Actions / lint-cargo-clippy

cannot find attribute `debug` in this scope

Check failure on line 20 in linera-client/src/persistent/indexed_db.rs

View workflow job for this annotation

GitHub Actions / web

cannot find attribute `debug` in this scope
database: IdbDatabase,
dirty: Dirty,
}

impl<T: serde::Serialize> std::fmt::Debug for IndexedDb<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("persistent::IndexedDb")
.field("key", &self.key)
.field("value", &serde_json::to_string(&self.value))
.field("dirty", &*self.dirty)
.finish_non_exhaustive()
}
}

const DATABASE_NAME: &str = "linera-client";
const STORE_NAME: &str = "linera-wallet";

Expand Down
Loading

0 comments on commit ea6eaaf

Please sign in to comment.