Skip to content

Commit e2d375f

Browse files
authored
nit: change an unexpected error condition to panic (#175)
`NetworkMessage::to_slice()` is only used in testing. Even when we start using it in production, I do not imagine us writing code to handle the situation that the buffer was too small and calling the function again with a larger buffer so I think it is cleaner for the function to panic if the buffer is not big enough.
1 parent c4aa729 commit e2d375f

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

src/network.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -96,21 +96,22 @@ impl NetworkMessage {
9696

9797
/// Serializes this message into an existing buffer using [`bincode`].
9898
///
99-
/// # Errors
99+
/// # Returns
100+
///
101+
/// Number of bytes used in `buf`.
100102
///
101-
/// Returns [`bincode::error::EncodeError`] if bincode encoding fails.
102-
/// This includes the case where `buf` is to small to fit this message.
103-
pub fn to_slice(&self, buf: &mut [u8]) -> Result<usize, bincode::error::EncodeError> {
103+
/// # Panics
104+
///
105+
/// Panics if encoding returns an error, including if `buf` was not big enough.
106+
/// Panics if encoding used more than [`MTU_BYTES`].
107+
pub fn to_slice(&self, buf: &mut [u8]) -> usize {
104108
let res = bincode::serde::encode_into_slice(self, buf, BINCODE_CONFIG);
105109
match res {
106110
Ok(written) => {
107111
assert!(written <= MTU_BYTES, "each message should fit in MTU");
108-
Ok(written)
109-
}
110-
Err(bincode::error::EncodeError::UnexpectedEnd) => {
111-
Err(bincode::error::EncodeError::UnexpectedEnd)
112+
written
112113
}
113-
_ => panic!("unexpected serialization error"),
114+
Err(err) => panic!("serialization failed with {err:?}"),
114115
}
115116
}
116117
}
@@ -207,7 +208,7 @@ mod tests {
207208
let mut buf = [0u8; MTU_BYTES];
208209
for _ in 0..10 {
209210
let msg = NetworkMessage::Ping;
210-
let num_bytes = msg.to_slice(&mut buf).unwrap();
211+
let num_bytes = msg.to_slice(&mut buf);
211212
let deserialized = NetworkMessage::from_bytes(&buf[..num_bytes]).unwrap();
212213
assert!(matches!(deserialized, NetworkMessage::Ping));
213214
}
@@ -223,9 +224,11 @@ mod tests {
223224
}
224225

225226
#[tokio::test]
227+
#[should_panic]
226228
async fn serialize_buffer_too_small() {
227229
let mut buf = [0u8; 1];
228230
let msg = NetworkMessage::Transaction(Transaction(vec![1; MAX_TRANSACTION_SIZE]));
229-
assert!(msg.to_slice(&mut buf).is_err());
231+
// this should panic
232+
msg.to_slice(&mut buf);
230233
}
231234
}

0 commit comments

Comments
 (0)