Skip to main content

decode

Function decode 

Source
pub fn decode(input: &[u8]) -> Result<Frame<'_>, DecodeError>
Expand description

Decodes one frame from bytes, borrowing from input.

The bytes are parsed exactly once. serde_json walks the document and the borrowed fields point straight into input, so no sub-tree is re-serialised or re-parsed on the way out.

§Errors

DecodeError::Json if the bytes are not JSON, or the top-level value is neither an object nor an array. Otherwise DecodeError::InvalidRequest for every shape problem, and DecodeError::EmptyBatch for an empty array.

§Examples

use protocol_droid::domain::jsonrpc::{DecodeError, Frame, MessageKind, decode};

let frame = decode(br#"{"jsonrpc":"2.0","id":7,"method":"ping"}"#)
    .expect("a well-formed request decodes");
let Frame::Single(envelope) = frame else {
    panic!("a lone object is not a batch");
};
assert_eq!(envelope.kind(), MessageKind::Request);
assert_eq!(envelope.method_str(), Some("ping"));