-
-
Save peterbudai/e7977a6c7b6e2db6aa3ef1e7582f3e43 to your computer and use it in GitHub Desktop.
Datagram codec for UdpFramed to extract JSON playload from incoming UDP datagrams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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