Skip to content

Commit d0897a6

Browse files
committed
Add msg! helper macro for generating types impl Encode
1 parent 914115c commit d0897a6

File tree

1 file changed

+36
-11
lines changed

1 file changed

+36
-11
lines changed

rust/bufferfish/src/lib.rs

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,41 @@ pub use bufferfish_derive::{Decode, Encode};
77
#[cfg(feature = "derive")]
88
pub use compiler::generate;
99

10+
/// Helper macro for defining packets with reduced boilerplate.
11+
///
12+
/// # Examples
13+
///
14+
/// ```rust
15+
/// # use bufferfish::packet;
16+
/// # enum ClientEventId { HeartbeatAck, ChatMessage }
17+
/// // Empty packet
18+
/// packet!(HeartbeatAckPacket, ClientEventId::HeartbeatAck);
19+
///
20+
/// // Packet with fields
21+
/// packet!(SendChatMessagePacket, ClientEventId::ChatMessage, {
22+
/// pub content: String,
23+
/// });
24+
/// ```
25+
#[cfg(feature = "derive")]
26+
#[macro_export]
27+
macro_rules! msg {
28+
// Empty message
29+
($name:ident, $id:expr) => {
30+
#[derive(Debug, Encode)]
31+
#[bufferfish($id)]
32+
pub struct $name;
33+
};
34+
35+
// Message with fields
36+
($name:ident, $id:expr, { $($field:vis $field_name:ident: $field_type:ty),* $(,)? }) => {
37+
#[derive(Debug, Encode)]
38+
#[bufferfish($id)]
39+
pub struct $name {
40+
$($field $field_name: $field_type,)*
41+
}
42+
};
43+
}
44+
1045
#[cfg(feature = "derive")]
1146
#[cfg(test)]
1247
mod tests {
@@ -342,16 +377,6 @@ mod tests {
342377
assert_eq!(bf.read_i128().unwrap(), i128::MIN);
343378
}
344379

345-
#[test]
346-
fn test_read_reset() {
347-
let mut bf = Bufferfish::new();
348-
bf.write_u8(0).unwrap();
349-
bf.read_u8().unwrap();
350-
bf.write_u8(255).unwrap();
351-
352-
assert_eq!(bf.read_u8().unwrap(), 0);
353-
}
354-
355380
#[test]
356381
fn test_bufferfish_overflow() {
357382
let mut bf = Bufferfish::new();
@@ -1021,6 +1046,6 @@ mod tests {
10211046
bf.reset();
10221047

10231048
assert_eq!(bf.len(), 0);
1024-
assert_eq!(bf.as_ref(), &[]);
1049+
assert_eq!(bf.as_ref(), &[] as &[u8]);
10251050
}
10261051
}

0 commit comments

Comments
 (0)