Skip to content

Instantly share code, notes, and snippets.

@peterbudai
Last active June 25, 2019 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterbudai/e7977a6c7b6e2db6aa3ef1e7582f3e43 to your computer and use it in GitHub Desktop.
Save peterbudai/e7977a6c7b6e2db6aa3ef1e7582f3e43 to your computer and use it in GitHub Desktop.
Datagram codec for UdpFramed to extract JSON playload from incoming UDP datagrams
struct BeaconCodec;
impl Decoder for BeaconCodec {
// To keep decoded packets flowing, even malformed packets need to be handled, therefore we use
// None to signal a datagram that possibly does not belong to the protocol.
type Item = Option<BeaconPacket>;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if buf.is_empty() {
// If an empty datagram were received, we signal that more data is needed.
Ok(None)
} else {
// Here we assume that a single UDP datagram will be passed to decode() as a whole
// If we cannot parse it into a valid JSON BeaconPacket, we assume that it is not a
// half packet, but belongs to a different protocol.
let packet = serde_json::from_slice(buf).map(Some).unwrap_or(None);
// According to the docs, it is our responsibility to drop used bytes from the buffer
buf.clear();
// We never return an Err as it would close the socket, but we would like to listen
// for more BeaconPackets even if a malformed one is received.
Ok(Some(packet))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment