Radish alpha
h
rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5
Radicle Heartwood Protocol & Stack
Radicle
Git
protocol/wire: Log before panicking serialize
Archived lorenz opened 8 months ago
3 files changed +28 -6 a670b6e6 a8a38b91
modified crates/radicle-protocol/Cargo.toml
@@ -17,7 +17,7 @@ bytes = { workspace = true }
crossbeam-channel = { workspace = true }
cyphernet = { workspace = true, features = ["tor"] }
fastrand = { workspace = true }
-
log = { workspace = true, features = ["std"] }
+
log = { workspace = true, features = ["kv", "std"] }
localtime = { workspace = true }
nonempty = { workspace = true, features = ["serialize"] }
qcheck = { workspace = true, optional = true }
modified crates/radicle-protocol/src/wire.rs
@@ -7,6 +7,7 @@ pub use message::{AddressType, MessageType};

use std::collections::BTreeMap;
use std::convert::TryFrom;
+
use std::fmt::Debug;
use std::mem;
use std::ops::Deref;
use std::str::FromStr;
@@ -106,10 +107,31 @@ pub trait Decode: Sized {
///
/// # Panics
///
-
/// If the encoded object exceeds [`Size::MAX`].
-
pub fn serialize<E: Encode + ?Sized>(data: &E) -> Vec<u8> {
-
    let mut buffer = Vec::new().limit(Size::MAX as usize);
+
/// If the encoded object exceeds [`Size::MAX`]. If `-C debug-assertions` is
+
/// passed to the compiler,  also log and panic with a more helpful message
+
/// (similar to the behaviour of [`debug_assert`]).
+
pub fn serialize<E: Encode + ?Sized + Debug>(data: &E) -> Vec<u8> {
+
    let mut buffer = Vec::new();
+

+
    #[cfg(not(debug_assertions))]
+
    let mut buffer = buffer.limit(Size::MAX as usize);
+

    data.encode(&mut buffer);
+

+
    #[cfg(debug_assertions)]
+
    if buffer.len() > Size::MAX as usize {
+
        let message = format!(
+
            "Data encodes to {} bytes, but the limit is {} bytes",
+
            buffer.len(),
+
            Size::MAX
+
        );
+
        log::error!(target = "wire", data:debug; "{message}.");
+
        panic!("{message}: {data:#?}");
+
    } else {
+
        buffer
+
    }
+

+
    #[cfg(not(debug_assertions))]
    buffer.into_inner()
}

modified crates/radicle-protocol/src/wire/frame.rs
@@ -234,7 +234,7 @@ impl<M> Frame<M> {
    }
}

-
impl<M: wire::Encode> Frame<M> {
+
impl<M: wire::Encode + std::fmt::Debug> Frame<M> {
    /// Serialize frame to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        wire::serialize(self)
@@ -356,7 +356,7 @@ impl<M: wire::Decode> wire::Decode for Frame<M> {
    }
}

-
impl<M: wire::Encode> wire::Encode for Frame<M> {
+
impl<M: wire::Encode + std::fmt::Debug> wire::Encode for Frame<M> {
    fn encode(&self, buf: &mut impl BufMut) {
        self.version.encode(buf);
        self.stream.encode(buf);