Skip to content
ImagineWorld

Data Serialization, Deserialization, and Parsing

node_idnode-book_network-programming-with-rust_chapter-04-data-serialization-deserialization-and-parsing
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleData Serialization, Deserialization, and Parsing
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 4 — Data Serialization, Deserialization, and Parsing

Section titled “Chapter 4 — Data Serialization, Deserialization, and Parsing”

In the previous chapter, we covered writing simple socket servers in Rust. Transport protocols such as TCP and UDP only provide mechanisms to transport messages, so it is up to a higher-level protocol to actually craft and send those messages. Also, TCP and UDP protocols always deal with bytes; we saw this when we called as_bytes on our strings before sending those out on the socket. This process of converting a piece of data into a format that can be stored or transmitted (a stream of bytes in the case of networking) is called serialization. The reverse process is deserialization, which turns a raw data format into a data structure. Any networking software must deal with serializing and deserializing data that has been received, or is about to be sent out. This simple conversion is not always possible for more complex types such as user-defined types, or even simple collection types. The Rust ecosystem has special crates that can handle these in a wide range of cases.

In this chapter, we will cover the following topics:

  • Serialization and deserialization using Serde. We will start with basic usage and then move on to writing custom serializers using Serde.
  • Parsing textual data using nom.
  • The last topic will be on parsing binary data, a very frequently used technique in networking.

Serde is the de-facto standard way of serializing and deserializing data in Rust. Serde supports a number of data structures that it can serialize out of the box to a number of given data formats (including JSON, and TOML, CSV). The easiest way to understand Serde is to think of it as an invertible function that transforms a given data structure into a stream of bytes. Other than standard data types, Serde also provides a few macros that can be implemented on user defined data types, making them (de)serializable.

In Chapter 2, Introduction to Rust and its Ecosystem, we discussed how procedural macros can be used to implement custom derives for given data types. Serde uses that mechanism to provide two custom derives, named Serialize and Deserialize, that can be implemented for user-defined data types that are composed of data types that Serde supports. Let us look at a small example of how this works. We start with creating the empty project using Cargo:

$ cargo new --bin serde-basic

Here is what the Cargo manifest should look like:

[package]
name = "serde-basic"
version = "0.1.0"
authors = ["Foo<[email protected]>"]
[dependencies]
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
serde_yaml = "0.7.1"

The serde crate is the core of the Serde ecosystem. The serde_derive crate provides necessary instrumentation that uses procedural macros for deriving Serialize and Deserialize. The next two crates provide Serde-specific functionality to and from JSON and YAML, respectively:

chapter4/serde-basic/src/main.rs
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate serde_yaml;
// We will serialize and deserialize instances of
// this struct
#[derive(Serialize, Deserialize, Debug)]
struct ServerConfig {
workers: u64,
ignore: bool,
auth_server: Option<String>
}
fn main() {
let config = ServerConfig {
workers: 100,
ignore: false,
auth_server: Some("auth.server.io".to_string())
};
{
println!("To and from YAML");
let serialized = serde_yaml::to_string(&config).unwrap();
println!("{}", serialized);
let deserialized: ServerConfig =
serde_yaml::from_str(&serialized).unwrap();
println!("{:?}", deserialized);
}
println!("\n\n");
{
println!("To and from JSON");
let serialized = serde_json::to_string(&config).unwrap();
println!("{}", serialized);
let deserialized: ServerConfig =
serde_json::from_str(&serialized).unwrap();
println!("{:?}", deserialized);
}
}

Since the serde_derive crate exports macros, we will need to mark it with a macro_use declaration; we then declare all our dependencies as extern crates. Having set this up, we can define our custom data type. In this case, we are interested in a config for a server that has a bunch of parameters of different types. The auth_server parameter is optional and that is why it is wrapped in an Option. Our struct derives the two traits from Serde, and also the compiler-provided Debug trait that we will use later to display after deserialization. In our main function, we instantiate our class and call serde_yaml::to_string on it to serialize it to a string; the reverse of this is serde_yaml::from_str.

A sample run should look like this:

$ cargo run
Compiling serde-basic v0.1.0 (file:///Users/Abhishek/Desktop/rust-book/src/chapter4/serde-basic)
Finished dev [unoptimized + debuginfo] target(s) in 1.88 secs
Running \`target/debug/serde-basic\`
To and from YAML
---
workers: 100
ignore: false
auth_server: auth.server.io
ServerConfig { workers: 100, ignore: false, auth_server: Some("auth.server.io") }
To and from JSON
{"workers":100,"ignore":false,"auth_server":"auth.server.io"}
ServerConfig { workers: 100, ignore: false, auth_server: Some("auth.server.io") }

Let us move on to a more advanced example of using Serde over a network. In this example, we will set up a TCP server and a client. This part will be exactly the same as how we did it in the last chapter. But this time, our TCP server will function as a calculator that takes in a point in a 3D space with three components along the three axes, and returns its distance from the origin in the same reference frame. Let us set up our Cargo project like this:

$ cargo new --bin serde-server

The manifest should look like this:

$ cat Cargo.toml
[package]
name = "serde-server"
version = "0.1.0"
authors = ["Foo <[email protected]>"]
[dependencies]
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"

With this, we can then move on to defining our code. In this example, the server and the client will be in the same binary. The application will take in a flag that dictates whether it should run as the server or the client. As we did in the last chapter, in the server case, we will bind to all local interfaces on a known port and listen for incoming connections. The client case will connect to the server on that known port and wait for user input on the console. The client expects input as a comma-separated list of three integers, one for each axis. On getting the input, the client constructs a struct of a given definition, serializes it using Serde, and sends the stream of bytes to the server. The server deserializes the stream into a struct of the same type. It then computes the distance and sends back the result, which the client then displays. The code is as follows:

chapter4/serde-server/src/main.rs
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use std::net::{TcpListener, TcpStream};
use std::io::{stdin, BufRead, BufReader, Error, Write};
use std::{env, str, thread};
#[derive(Serialize, Deserialize, Debug)]
struct Point3D {
x: u32,
y: u32,
z: u32,
}
// Like previous examples of vanilla TCP servers, this function handles
// a single client.
fn handle_client(stream: TcpStream) -> Result<(), Error> {
println!("Incoming connection from: {}", stream.peer_addr()?);
let mut data = Vec::new();
let mut stream = BufReader::new(stream);
loop {
data.clear();
let bytes_read = stream.read_until(b'\n', &mut data)?;
if bytes_read == 0 {
return Ok(());
}
let input: Point3D = serde_json::from_slice(&data)?;
let value = input.x.pow(2) + input.y.pow(2) + input.z.pow(2);
write!(stream.get_mut(), "{}", f64::from(value).sqrt())?;
write!(stream.get_mut(), "{}", "\n")?;
}
}
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
eprintln!("Please provide --client or --server as argument");
std::process::exit(1);
}
// The server case
if args[1] == "--server" {
let listener = TcpListener::bind("0.0.0.0:8888").expect("Could
not bind");
for stream in listener.incoming() {
match stream {
Err(e) => eprintln!("failed: {}", e),
Ok(stream) => {
thread::spawn(move || {
handle_client(stream).unwrap_or_else(|error|
eprintln!("{:?}", error));
});
}
}
}
}
// Client case begins here
else if args[1] == "--client" {
let mut stream = TcpStream::connect("127.0.0.1:8888").expect("Could not connect to server");
println!("Please provide a 3D point as three comma separated
integers");
loop {
let mut input = String::new();
let mut buffer: Vec<u8> = Vec::new();
stdin()
.read_line(&mut input)
.expect("Failed to read from stdin");
let parts: Vec<&str> = input
.trim_matches('\n')
.split(',')
.collect();
let point = Point3D {
x: parts[0].parse().unwrap(),
y: parts[1].parse().unwrap(),
z: parts[2].parse().unwrap(),
};
stream
.write_all(serde_json::to_string(&point).unwrap().as_bytes())
.expect("Failed to write to server");
stream.write_all(b"\n").expect("Failed to write to
server");
let mut reader = BufReader::new(&stream);
reader
.read_until(b'\n', &mut buffer)
.expect("Could not read into buffer");
let input = str::from_utf8(&buffer).expect("Could not write
buffer as string");
if input == "" {
eprintln!("Empty response from server");
}
print!("Response from server {}", input);
}
}
}

We start with setting up Serde as we did in the last example. We then define our 3D point as a struct of three elements. In our main function, we handle CLI arguments and branch out to the client or the server, depending on what was passed. In both cases, we signal the end of transmission by sending a newline character. The client reads a line from stdin, cleans it, and creates an instance of the struct in a loop. In both cases, we wrap our streams in a BufReader for easier handling. We run our code using Cargo. An example session on the server is as follows:

server$ cargo run -- --server
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running \`target/debug/serde-server --server\`
Incoming connection from: 127.0.0.1:49630

And, on the client side, we see the following interaction with the server. As expected, the client reads input, serializes that, and sends it to the server. It then waits for a response and, when it gets one, prints the result to standard output:

client$ cargo run -- --client
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running \`target/debug/serde-server --client\`
Please provide a 3D point as three comma separated integers
1,2,3
Response from server 3.7416573867739413
3,4,5
Response from server 7.0710678118654755
4,5,6
Response from server 8.774964387392123

As we saw before, Serde provides built-in serialization and deserialization for all primitive data types, and a number of complex data types, via macros. In some cases, however, Serde might fail to auto-implement. This might happen for more complex data types. In those cases, you will need to implement these manually. These cases demonstrate advanced usage of Serde, which also allows renaming fields in the output. For everyday usage, using these advanced feature is almost never necessary. These might be more common for networking, to handle a new protocol, and more.

Let’s say we have a struct of three fields. We will just assume that Serde fails to implement Serialize and Deserialize on this, and so we will need to implement those manually. We initialize our project using Cargo:

$ cargo new --bin serde-custom

We then declare our dependencies; the resulting Cargo config file should look like this:

[package]
name = "serde-custom"
version = "0.1.0"
authors = ["Foo <[email protected]>"]
[dependencies]
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
serde_test = "1.0"

Our struct looks like this:

chapter4/serde-custom/src/main.rs
// We will implement custom serialization and deserialization
// for this struct
#[derive(Debug, PartialEq)]
struct KubeConfig {
port: u8,
healthz_port: u8,
max_pods: u8,
}

We need to derive Debug and PartialEq for Serde to use internally. In the real world, it might be necessary to manually implement those as well. Now, we will need to implement the Serialize trait for kubeconfig. This trait looks like this:

pub trait Serialize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer;
}

The basic workflow for serializing our struct will simply be to serialize the struct name, then each of the elements, and then signal the end of serialization, in that order. Serde has built-in methods to serialize that can work with all basic types, therefore an implementation does not need to worry about handling built-in types. Let’s look at how we can serialize our struct:

chapter4/serde-custom/src/main.rs
// Implementing Serialize for our custom struct defines
// how instances of that struct should be serialized.
// In essence, serialization of an object is equal to
// sum of the serializations of it's components
impl Serialize for KubeConfig {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
let mut state = serializer.serialize_struct("KubeConfig", 3)?;
state.serialize_field("port", &self.port)?;
state.serialize_field("healthz_port", &self.healthz_port)?;
state.serialize_field("max_pods", &self.max_pods)?;
state.end()
}
}

Serialization of a struct will always begin with a call of serialize_struct with the struct name and number of fields as parameter (there are similarly named methods for other types). We then serialize each field in the order they appear while passing a key name that will be used in the resultant json. Once done, we call the special end method as a signal.

Implementing deserialization is a bit more involved, with a bit of boilerplate code. The related trait looks like this:

pub trait Deserialize<'de>: Sized {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>;
}

Implementing this for a type requires implementing the visitor pattern. Serde defines a special Visitor trait, as shown in the following sample. Note that this has visit_* methods for all built-in types, those are not shown here. Also, in the following sample, we use the symbol … to indicate that there are more methods here that are not important for our discussion.

pub trait Visitor<'de>: Sized {
type Value;
fn expecting(&self, formatter: &mut Formatter) -> Result;
fn visit_bool<E>(self, v: bool) -> Result<Self::Value,
E>
where
E: Error,
{ }
...
}

An implementation of this trait is used internally by the deserializer to construct the resultant type. In our case, it will look like this:

chapter4/serde-custom/src/main.rs
// Implementing Deserialize for our struct defines how
// an instance of the struct should be created from an
// input stream of bytes
impl<'de> Deserialize<'de> for KubeConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
enum Field { Port, HealthzPort, MaxPods };
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) ->
Result<Field,
D::Error>
where D: Deserializer<'de>
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter)
-> fmt::Result {
formatter.write_str("\`port\` or \`healthz_port\`
or \`max_pods\`")
}
fn visit_str<E>(self, value: &str) ->
Result<Field,
E>
where E: de::Error
{
match value {
"port" => Ok(Field::Port),
"healthz_port" =>
Ok(Field::HealthzPort),
"max_pods" => Ok(Field::MaxPods),
_ => Err(de::Error::unknown_field(value,
FIELDS)),
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
}

Now, the input to the deserializer is json, which can be treated as a map. Thus, we will only need to implement visit_map from the Visitor trait. If any non-json data is passed to our deserializer, it will error out on a call to some other function from that trait. Most of the previous implementation is boilerplate. It boils down to a few parts: implementing Visitor for the fields, and implementing visit_str (since all of our fields are strings). At this point, we should be able to deserialize individual fields. The second part is to implement Visitor for the overall struct, and to implement visit_map. Errors must be handled appropriately in all cases. In the end, we can call deserializer.deserialize_struct and pass the name of the struct, the list of fields, and the visitor implementation for the whole struct.

This implementation will look like this:

chapter4/serde-custom/src/main.rs
impl<'de> Deserialize<'de> for KubeConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
struct KubeConfigVisitor;
impl<'de> Visitor<'de> for KubeConfigVisitor {
type Value = KubeConfig;
fn expecting(&self, formatter: &mut fmt::Formatter) ->
fmt::Result {
formatter.write_str("struct KubeConfig")
}
fn visit_map<V>(self, mut map: V) ->
Result<KubeConfig,
V::Error>
where V: MapAccess<'de>
{
let mut port = None;
let mut hport = None;
let mut max = None;
while let Some(key) = map.next_key()? {
match key {
Field::Port => {
if port.is_some() {
return
Err(de::Error::duplicate_field("port"));
}
port = Some(map.next_value()?);
}
Field::HealthzPort => {
if hport.is_some() {
return
Err(de::Error::duplicate_field
("healthz_port"));
}
hport = Some(map.next_value()?);
}
Field::MaxPods => {
if max.is_some() {
return
Err(de::Error::duplicate_field
("max_pods"));
}
max = Some(map.next_value()?);
}
}
}
let port = port.ok_or_else(||
de::Error::missing_field("port"))?;
let hport = hport.ok_or_else(||
de::Error::missing_field("healthz_port"))?;
let max = max.ok_or_else(||
de::Error::missing_field("max_pods"))?;
Ok(KubeConfig {port: port, healthz_port: hport,
max_pods: max})
}
}
const FIELDS: &'static [&'static str] = &["port",
"healthz_port", "max_pods"];
deserializer.deserialize_struct("KubeConfig", FIELDS,
KubeConfigVisitor)
}
}

Serde also provides a crate that can be used to unit test custom serializers and deserializers using a token-stream-like interface. To use it, we will need to add serde_test to our Cargo.toml and declare it as an extern crate in our main file. Here is a test for our deserializer:

chapter4/serde-custom/src/main.rs
#[test]
fn test_ser_de() {
let c = KubeConfig { port: 10, healthz_port: 11, max_pods: 12};
assert_de_tokens(&c, &[
Token::Struct { name: "KubeConfig", len: 3 },
Token::Str("port"),
Token::U8(10),
Token::Str("healthz_port"),
Token::U8(11),
Token::Str("max_pods"),
Token::U8(12),
Token::StructEnd,
]);
}

The assert_de_tokens call checks if the given stream of tokens deserializes to our struct or not, thereby testing our deserializer. We can also add a main function to drive the serializer, like this:

chapter4/serde-custom/src/main.rs
fn main() {
let c = KubeConfig { port: 10, healthz_port: 11, max_pods: 12};
let serialized = serde_json::to_string(&c).unwrap();
println!("{:?}", serialized);
}

All this can now be run using Cargo. Using cargo test should run the test we just wrote, which should pass. cargo run should run the main function and print the serialized json:

$ cargo test
Compiling serde-custom v0.1.0 (file:///serde-custom)
Finished dev [unoptimized + debuginfo] target(s) in 0.61 secs
Running target/debug/deps/serde_custom-81ee5105cf257563
running 1 test
test test_ser_de ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
$ cargo run
Compiling serde-custom v0.1.0 (file:///serde-custom)
Finished dev [unoptimized + debuginfo] target(s) in 0.54 secs
Running \`target/debug/serde-custom\`
"{\"port\":10,\"healthz_port\":11,\"max_pods\":12}"

Data parsing is a problem closely related to that of deserialization. The most common way of thinking about parsing is to start with a formal grammar and construct parsers based on that. This results in a bottom-up parser where smaller rules parse smaller components of the whole input. A final combinatorial rule combines all smaller rules in a given order to form the final parser. This way of formally defining a finite set of rules is called a Parsing Expression Grammar (PEG). This ensures that parsing is unambiguous; that there is only one valid parse tree if parsing succeeds. In the Rust ecosystem, there are a few distinct ways of implementing PEGs, and each of those have their own strengths and weaknesses. The first way is using macros to define a domain-specific language for parsing.

This method integrates well with the compiler through the new macro system, and can produce fast code. However, this is often harder to debug and maintain. Since this method does not allow overloading operators, the implementation must define a DSL, which might be more of a cognitive load for a learner. The second method is using the trait system. This method helps in defining custom operators and is often easier to debug and maintain. An example of a parser that uses the first approach is nom; examples of parsers using the second approach are pom and pest.

Our use case for parsing is mostly in the context of networking applications. In these cases, sometimes it is more useful to deal with raw strings (or byte streams) and parse required information instead of deserializing to a complex data structure. A common case for this is any text-based protocol, such as HTTP. A server might receive a raw request as a stream of bytes over a socket and parse it to extract information. In this section, we will study some common parsing techniques in the Rust ecosystem.

Now, nom is a parser combinator framework, which means it can combine smaller parsers to build more powerful parsers. This is a bottom-up approach that usually starts with writing very specific parsers that parse a well-defined thing from the input. The framework then provides methods to chain these small parsers into a complete one. This approach is in contrast to a top-down approach in the case of lex and yacc, where one would start with defining the grammar. It can handle both byte streams (binary data) or strings, and provides all of Rust’s usual guarantees. Let us start with parsing a simple string, which in this case is an HTTP GET or POST request. Like all cargo projects, we will first set up the structure:

$ cargo new --bin nom-http

Then we will add our dependencies (nom in this case). The resultant manifest should look like this:

$ cat Cargo.toml
[package]
name = "nom-http"
version = "0.1.0"
authors = ["Foo<[email protected]>"]
[dependencies.nom]
version = "3.2.1"
features = ["verbose-errors", "nightly"]

The crate provides a few extra features that are often useful for debugging; these are disabled by default and can be turned on by passing the list to the features flag, as shown in the preceding sample. Now, let’s move on to our main file:

chapter4/nom-http/src/main.rs
#[macro_use]
extern crate nom;
use std::str;
use nom::{ErrorKind, IResult};
#[derive(Debug)]
enum Method {
GET,
POST,
}
#[derive(Debug)]
struct Request {
method: Method,
url: String,
version: String,
}
// A parser that parses method out of a HTT request
named!(parse_method<&[u8], Method>,
return_error!(ErrorKind::Custom(12), alt!(map!(tag!("GET"), |_| Method::GET) | map!(tag!("POST"), |_| Method::POST))));
// A parser that parses the request part
named!(parse_request<&[u8], Request>, ws!(do_parse!(
method: parse_method >>
url: map_res!(take_until!(" "), str::from_utf8) >>
tag!("HTTP/") >>
version: map_res!(take_until!("\r"), str::from_utf8) >>
(Request { method: method, url: url.into(), version: version.into() })
)));
// Driver function for running the overall parser
fn run_parser(input: &str) {
match parse_request(input.as_bytes()) {
IResult::Done(rest, value) => println!("Rest: {:?} Value: {:?}",
rest, value),
IResult::Error(err) => println!("{:?}", err),
IResult::Incomplete(needed) => println!("{:?}", needed)
}
}
fn main() {
let get = "GET /home/ HTTP/1.1\r\n";
run_parser(get);
let post = "POST /update/ HTTP/1.1\r\n";
run_parser(post);
let wrong = "WRONG /wrong/ HTTP/1.1\r\n";
run_parser(wrong);
}

As might be obvious, nom makes heavy use of macros for code generation, the most important one being named!, which takes in a function signature and defines a parser based on that. A nom parser returns an instance of the IResult type; this is defined as an enum and has three variants:

  • The Done(rest, value) variant represents the case where the current parser was successful. In this case, the value will have the current parsed value and the rest will have the remaining input to be parsed.
  • The Error(Err<E>) variant represents an error during parsing. The underlying error will have the error code, position in error, and more. In a large parse tree, this can also hold pointers to more errors.
  • The last variant, Incomplete(needed), represents the case where parsing was incomplete for some reason. Needed is an enum that again has two variants; the first one represents the case where it is not known how much data is needed. The second one represents the exact size of data needed.

We start with representations for HTTP methods and the full request as structs. In our toy example, we will only deal with GET and POST, and ignore everything else. We then define a parser for the HTTP method; our parser will take in a slice of bytes and return the Method enum. This is simply done by reading the input and looking for the strings GET or POST. In each case, the base parser is constructed using the tag! macro, which parses input to extract the given string. And, if the parsing was successful, we convert the result to Method using the map! macro, which maps the result of a parser to a function. Now, for parsing the method, we will either have a POST or a GET, but never both. We use the alt! macro to express the logical OR of both the parsers we constructed before. The alt! macro will construct a parser that parses the input if any one of it’s constituent macros can parse the given input. Finally, all this is wrapped in the return_error! macro, which returns early if parsing fails in the current parser, instead of passing onto the next parser in the tree.

We then move on to parsing the whole request by defining parse_request. We start with trimming extra whitespace from the input using the ws! macro. We then invoke the do_parse! macro that chains multiple sub-parsers. This one is different from other combinators because this allows storing results from intermediate parsers. This is useful in constructing instances of our structs while returning results. In do_parse!, we first call parse_method and store its result in a variable. Having removed the method from a request, we should encounter empty whitespace before we find the location of the object. This is handled by the take_until!(” ”) call, which consumes input till it finds an empty space. The result is converted to a str using map_res!. The next parser in the list is one that removes the sequence HTTP/ using the tag! macro. Next, we parse the HTTP version by reading input till we see a \r, and map it back to a str. Once we are done with all the parsing, we construct a Request object and return it. Note the use of the >> symbol as a separator between parsers in the sequence.

We also define a helper function called run_parser to run our parsers in a given input and print the result. This function calls the parser and matches on the result to display either the resultant structure or error. We then define our main function with three HTTP requests, the first two being valid, and the last one being invalid since the method is wrong. On running this, the output is as follows:

$ cargo run
Compiling nom-http v0.1.0 (file:///Users/Abhishek/Desktop/rust-book/src/ch4/nom-http)
Finished dev [unoptimized + debuginfo] target(s) in 0.60 secs
Running \`target/debug/nom-http\`
Rest: [] Value: Request { method: GET, url: "/home/", version: "1.1" }
Rest: [] Value: Request { method: POST, url: "/update/", version: "1.1" }
NodePosition(Custom(128), [87, 82, 79, 78, 71, 32, 47, 119, 114, 111, 110, 103, 47, 32, 72, 84, 84, 80, 47, 49, 46, 49, 13, 10], [Position(Alt, [87, 82, 79, 78, 71, 32, 47, 119, 114, 111, 110, 103, 47, 32, 72, 84, 84, 80, 47, 49, 46, 49, 13, 10])])

In the first two cases, everything was parsed as expected and we got the result back. As expected, parsing failed in the last case with the custom error being returned.

As we discussed before, a common problem with nom is debugging, since it is much harder to debug macros. Macros also encourage the use of specific DSLs (like using the >> separator), which some people might find difficult to work with. At the time of writing, some error messages from nom are not helpful enough in finding what is wrong with a given parser. These will definitely improve in the future, but in the meantime, nom provides a few helper macros for debugging.

For instance, dbg! prints the result and the input if the underlying parser did not return a Done. The dbg_dump! macro is similar but also prints out a hex dump of the input buffer. In our experience, a few techniques can be used for debugging:

  • Expanding the macro by passing compiler options to rustc. Cargo enables this using the following invocations: cargo rustc — -Z unstable-options —pretty=expanded expands and pretty prints all macros in the given project. One might find it useful to expand the macros to trace execution and debug. A related command in Cargo, rustc — -Z trace-macros, only expands the macros.
  • Running smaller parsers in isolation. Given a series of parsers and another one combining those, it might be easier to run each of the sub-parsers till one of those errors out. Then, one can go on to debug only the small parser that is failing. This is very useful in isolating faults.
  • Using the provided debugging macros dbg! and dbg_dump!. These can be used like debugging print statements to trace execution.

pretty=expanded is an unstable compiler option right now. Sometime in the future, it will be stabilized (or removed). In that case, one will not need to pass the -Z unstable-options flag to use it.

Let us look at an example of another parser combinator called pom. As we discussed before, this one relies heavily on traits and operator-overloading to implement parser combinations. As the time of writing, the current version is 1.1.0, and we will use that for our example project. Like always, the first step is to set up our project and add pom to our dependencies:

$ cargo new --bin pom-string

The Cargo.toml file will look like this:

[package]
name = "pom-string"
version = "0.1.0"
authors = ["Foo<[email protected]>"]
[dependencies]
pom = "1.1.0"

In this example, we will parse an example HTTP request, like last time. This is how it will look:

chapter4/pom-string/src/main.rs
extern crate pom;
use pom::DataInput;
use pom::parser::{sym, one_of, seq};
use pom::parser::*;
use std::str;
// Represents one or more occurrence of an empty whitespace
fn space() -> Parser<'static, u8, ()> {
one_of(b" \t\r\n").repeat(0..).discard()
}
// Represents a string in all lower case
fn string() -> Parser<'static, u8, String> {
one_of(b"abcdefghijklmnopqrstuvwxyz").repeat(0..).convert(String::from_utf8)
}
fn main() {
let get = b"GET /home/ HTTP/1.1\r\n";
let mut input = DataInput::new(get);
let parser = (seq(b"GET") | seq(b"POST")) * space() * sym(b'/') *
string() * sym(b'/') * space() * seq(b"HTTP/1.1");
let output = parser.parse(&mut input);
println!("{:?}", str::from_utf8(&output.unwrap()));
}

We start with declaring our dependency on pom. In our main function, we define the final parser as a sequence of multiple sub-parsers. The * operator has been overloaded to make it apply multiple parsers in sequence. The seq operator is a built-in parser that matches the given string from input. The | operator does a logical OR of the two operands. We define a function called space() that represents empty white spaces in input. This function takes one of each empty whitespace characters, repeats it 0 or more times, and then discards it. Consequently, the function returns a Parser with no return type, indicated by (). The string function is similarly defined to be one of the characters in the English alphabet, repeated 0 or more times, and then converted to an std::String.

The return type of this function is a Parser that has a String, as expected. Having set those up, our main parser will have a space, followed by the symbol /, followed by a string, a symbol /, a space again, and ending with the sequence HTTP/1.1. And, as expected, when we parse an example string with the parser we wrote, it produces an Ok:

$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running \`target/debug/pom-string\`
Ok("HTTP/1.1")

PEG-based parser combinators can be easier to debug and to work with. They also tend to produce better error messages, but, unfortunately, those are not mature enough right now. The community around them is not as large as the community around nom. Consequently, it is often easier to get help with nom issues. At the end of the day, it is up to the programmer to choose something that works for them.

A related problem is that of parsing binary data. Common cases where this is applicable include parsing binary files and binary protocols. Let us look at how nom can be used to parse binary data. In our toy example, we will write a parser for the IPv6 header. Our Cargo.toml will look exactly the same as last time. Set up the project using the CLI:

$ cargo new --bin nom-ipv6

Our main file will look like this:

chapter4/nom-ipv6/src/main.rs
#[macro_use]
extern crate nom;
use std::net::Ipv6Addr;
use nom::IResult;
// Struct representing an IPv6 header
#[derive(Debug, PartialEq, Eq)]
pub struct IPv6Header {
version: u8,
traffic_class: u8,
flow_label: u32,
payload_length: u16,
next_header: u8,
hop_limit: u8,
source_addr: Ipv6Addr,
dest_addr: Ipv6Addr,
}
// Converts a given slice of [u8] to an array of 16 u8 given by
// [u8; 16]
fn slice_to_array(input: &[u8]) -> [u8; 16] {
let mut array = [0u8; 16];
for (&x, p) in input.iter().zip(array.iter_mut()) {
*p = x;
}
array
}
// Converts a reference to a slice [u8] to an instance of
// std::net::Ipv6Addr
fn to_ipv6_address(i: &[u8]) -> Ipv6Addr {
let arr = slice_to_array(i);
Ipv6Addr::from(arr)
}
// Parsers for each individual section of the header
named!(parse_version<&[u8], u8>, bits!(take_bits!(u8, 4)));
named!(parse_traffic_class<&[u8], u8>, bits!(take_bits!(u8, 8)));
named!(parse_flow_label<&[u8], u32>, bits!(take_bits!(u32, 20)));
named!(parse_payload_length<&[u8], u16>, bits!(take_bits!(u16, 16)));
named!(parse_next_header<&[u8], u8>, bits!(take_bits!(u8, 8)));
named!(parse_hop_limit<&[u8], u8>, bits!(take_bits!(u8, 8)));
named!(parse_address<&[u8], Ipv6Addr>, map!(take!(16), to_ipv6_address));
// The primary parser
named!(ipparse<&[u8], IPv6Header>,
do_parse!(
ver: parse_version >>
cls: parse_traffic_class >>
lbl: parse_flow_label >>
len: parse_payload_length >>
hdr: parse_next_header >>
lim: parse_hop_limit >>
src: parse_address >>
dst: parse_address >>
(IPv6Header {
version: ver,
traffic_class: cls,
flow_label: lbl,
payload_length: len,
next_header: hdr,
hop_limit: lim,
source_addr: src,
dest_addr : dst
})
));
// Wrapper for the parser
pub fn parse_ipv6_header(i: &[u8]) -> IResult<&[u8], IPv6Header> {
ipparse(i)
}
fn main() {
const EMPTY_SLICE: &'static [u8] = &[];
let bytes = [0x60,
0x00,
0x08, 0x19,
0x80, 0x00, 0x14, 0x06,
0x40,
0x2a, 0x02, 0x0c, 0x7d, 0x2e, 0x5d, 0x5d, 0x00,
0x24, 0xec, 0x4d, 0xd1, 0xc8, 0xdf, 0xbe, 0x75,
0x2a, 0x00, 0x14, 0x50, 0x40, 0x0c, 0x0c, 0x0b,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xbd
];
let expected = IPv6Header {
version: 6,
traffic_class: 0,
flow_label: 33176,
payload_length: 20,
next_header: 6,
hop_limit: 64,
source_addr:
"2a02:c7d:2e5d:5d00:24ec:4dd1:c8df:be75".parse().unwrap(),
dest_addr: "2a00:1450:400c:c0b::bd".parse().unwrap(),
};
assert_eq!(ipparse(&bytes), IResult::Done(EMPTY_SLICE, expected));
}

Here, we start with declaring a struct for the IPv6 fixed header, as defined in RFC 2460 (https://tools.ietf.org/html/rfc2460). We first define a helper function called to_ipv6_address that takes in a slice of u8 and converts to an IPv6 address. To do that, we need another helper function that converts a slice to a fixed-size array (16 in this case). Having set those up, we define a number of parsers for parsing each of the members of the struct using the named! macro.

The parse_version function takes in a slice of bytes and returns the version as a u8. This is done by reading 4 bits from the input as a u8, using the take_bits! macro. That is then wrapped in the bits! macro which transforms the input to a bit stream for the underlying parser. In the same way, we go on to define parsers for all the other fields in the header structure. For each one, we take the number of bits they occupy according to the RFC and convert to a type large enough to hold it. The last case of parsing the address is different. Here, we read 16 bytes using the take! macro and map it to the to_ipv6_address function to convert the byte stream, using the map! macro.

At this point, all small pieces to parse the whole struct are ready, and we can define a function using the do_parse! macro. In there, we accumulate results in temporary variables and construct an instance of the IPv6Header struct, which is then returned. In our main function, we have an array of bytes that was taken from a IPv6 packet dump and should represent a valid IPv6 header. We parse that using the parser we defined and assert that the output matches what is expected. Thus, a successful run of our parser previously will not throw an exception.

Let us recap all the macros from nom that we used so far:

MacroPurpose
named!Creates a parsing function by combining smaller functions. This (or a variant) is always the top-level call in a chain.
ws!Enables a parser to consume all whitespaces (\t, \r and \n) between tokens.
do_parse!Applies subparsers in a given sequence, can store intermediate results.
tag!Declares a static sequence of bytes that the enclosing parser should recognize.
take_until!Consumes input till the given tag.
take_bits!Consumes the given number of bits from the input and casts them to the given type.
take!Consumes the specified number of bytes from input.
map_res!Maps a function (returning a result) on the output of a parser.
map!Maps a function to the output of a parser.
bits!Transforms the given slice to a bit stream.

In this section, we studied handling data in more detail. Specifically, (de)serializing and parsing. At the time of writing, Serde and related crates are the community-supported way of (de)serializing data in Rust, while nom is the most frequently used parser combinator. These tools tend to produce better error messages on the nightly compiler, and with a few feature flags turned on, since they often depend on a few cutting edge night-only features. With time, these features will be available in the stable compiler, and these tools will work seamlessly.

In the next chapter, we will talk about the next steps after having made sense of incoming data on a socket. More often than not, this involves dealing with application-level protocols.