Deserializing requests

The service will support complex requests in which you can specify a distribution and parameters. Let's add this enumeration to the source file:

#[derive(Deserialize)]
enum RngRequest {
Uniform {
range: Range<i32>,
},
Normal {
mean: f64,
std_dev: f64,
},
Bernoulli {
p: f64,
},
}

You may want to know what the serialized value looks like. serde_derive provides extra attributes, which you can use to tweak the serialization format. The current deserializer expects a RngRequest instance, as follows:

RngRequest::Uniform {
range: 1..10,
}

This will be represented as the string:

{ "Uniform": { "range": { "start": 1, "end": 10 } } }

If you create your own protocol from scratch, there won't be any problems with the layout, because you can easily make it conform to any restrictions specified by serializers that are automatically generated by the serde crate. If you have to use an existing protocol, however, you can try to add extra attributes to a declaration. If this doesn't help, you can implement the Serialize or Deserialize traits manually. For example, let's say we want to use the following request format:

{ "distribution": "uniform", "parameters": { "start": 1, "end": 10 } } }

Add the serde attributes to the RngRequest declaration, which transform the deserializer to support the preceding format. The code will look as follows:

#[derive(Deserialize)]
#[serde(tag = "distribution", content = "parameters", rename_all = "lowercase")]
enum RngRequest {
Uniform {
#[serde(flatten)]
range: Range<i32>,
},
Normal {
mean: f64,
std_dev: f64,
},
Bernoulli {
p: f64,
},
}

Now, the enumeration uses the aforementioned request format. There are a lot of attributes in the serde_derive crate and it's important to explore them in more detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.237.29