Type check for serialized data from a stream

Suppose I have a thread, that listens for incoming data. Data might be the serialization of two different types, say ‘request’ or ‘response’. However we can not know in advance, which one it is. So I’m not sure how to deserialize the stream properly. The following example illustrates the situation:

#[derive(Serialize, Deserialize, Debug)]
struct Request {
type : different_from_request_type

#[derive(Serialize, Deserialize, Debug)]
struct Response {
type: different_from_response_type

// function main listens for incomming data, where data can be the serialization of type request OR response, but main() doesn’t know which one it is…
fn main() {
let l = net::TcpListener::bind(“somewhere”).unwrap();
let l = l;
for stream in l.incoming() {
let mut stream = stream.unwrap();
let read_stream = stream.try_clone().unwrap();
let mut de = serde::json::Deserializer::new(read_stream.bytes()).unwrap();
// Ok. Now I would like to actually deserialize this either into request or
// response. But I don’t know if it is the serialization
// of response or request. They are different.
// IF I knew in advance, I would just write either
// let request = Request::deserialize(&mut de).unwrap();
// or
// let response = Response::deserialize(&mut de).unwrap();
// But I don’t know. So how can I handle this?

First, try to use


to include your code.

Nevertheless, what about something like

if let Some(request) = Request::deserialize(&mut de) {
  // ...
} else if let Some(response) == Response::deserialize(&mut de) {
  // ...

So if that works, then thats what I was hoping for. So you say, that
Request::deserialize() recognizes, if the stream encodes an object of request type? If yes it returns the object, if its a different type then none. Correct?

It should work if the structures are different enough.

IHMO one of the best thing could be having a serialized enum at the beginning of stream that tells you what you are going to get. This will probably avoid you some headaches.

One thing I am not sure about is the behaviour of the deserializer in case of failure: I expect it not to consume the buffer data, but I am not sure. Try to perform some tests before diving deeper.

Unfortunately the structures are pretty much the same in our example. So ok,we need an additional identifier to distinguish them.