Decode Frames With Opcode Patterns
Dispatch on a leading byte with slice patterns and byte literals, binding payload fields per opcode while unknown codes fall into a catch-all arm.
Code
#[derive(Debug)]
enum Frame {
Ping,
Set { key: u8, value: u8 },
Get { key: u8 },
Unknown(u8),
}
fn decode(bytes: &[u8]) -> Frame {
match bytes {
[] => Frame::Unknown(0),
[0x01] => Frame::Ping,
[0x02, key, value, ..] => Frame::Set { key: *key, value: *value },
[0x03, key, ..] => Frame::Get { key: *key },
[op, ..] => Frame::Unknown(*op),
}
}
fn main() {
let wire: [&[u8]; 5] = [
&[0x01][..],
&[0x02, 7, 200][..],
&[0x03, 9][..],
&[0x7F, 1, 2][..],
&[][..],
];
for frame in &wire {
println!("{:?} -> {:?}", frame, decode(frame));
}
}One match on the leading byte
decode(bytes) matches on the whole &[u8] with slice patterns: [] yields Frame::Unknown(0), [0x01] is Frame::Ping, [0x02, key, value, ..] binds two payload bytes into Frame::Set, [0x03, key, ..] binds one into Frame::Get, and the catch-all [op, ..] wraps any other opcode with its raw byte in Frame::Unknown(*op). The .. rest element is what lets payload length vary — a 3-byte Set and a longer frame both reach the same arm.
What the five wire arrays decode to
[1] -> Ping
[2, 7, 200] -> Set { key: 7, value: 200 }
[3, 9] -> Get { key: 9 }
[127, 1, 2] -> Unknown(127)
[] -> Unknown(0)
Each line is println!("{:?} -> {:?}", frame, decode(frame)) for one entry of wire: the raw byte slice on the left, the decoded enum on the right. 0x7F demonstrates the catch-all — it keeps its opcode byte and ignores its trailing payload, and the empty slice lands on the explicit [] arm rather than the catch-all.
The line that guards the shape
[0x02, key, value, ..] => Frame::Set { key: *key, value: *value },
key and value bind as &u8 inside the slice pattern, so the arm dereferences with * — the pattern guarantees at least two bytes exist before they are read.
Interactive Tools for This Topic
FAQ
- How do you run Decode Frames With Opcode Patterns?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.