Touch up the byteorder example

This commit is contained in:
David Tolnay 2017-05-03 20:08:28 -07:00
parent 3d066af1a5
commit 1ef3788132
No known key found for this signature in database
GPG key ID: F9BA143B95FF6D82

View file

@ -51,45 +51,37 @@ fn main() { run().unwrap() }
```rust
extern crate byteorder;
use std::io::Cursor;
use std::io;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
#[derive(Default, Eq, PartialEq, Debug)]
#[derive(Default, PartialEq, Debug)]
struct Payload {
kind: u8,
value: u16,
kind: u8,
value: u16,
}
fn run() -> Result<()> {
let original_payload = Payload::default();
let encoded_buf = encode(&original_payload)?;
let decoded_payload = decode(&encoded_buf)?;
assert_eq!(original_payload, decoded_payload);
Ok(())
fn run() -> io::Result<()> {
let original_payload = Payload::default();
let encoded_bytes = encode(&original_payload)?;
let decoded_payload = decode(&encoded_bytes)?;
assert_eq!(original_payload, decoded_payload);
Ok(())
}
fn encode(payload: &Payload) -> Result<Vec<u8>> {
let mut wtr = vec![];
wtr.write_u8(payload.kind)?;
wtr.write_u16::<LittleEndian>(payload.value)?;
Ok(wtr)
fn encode(payload: &Payload) -> io::Result<Vec<u8>> {
let mut bytes = vec![];
bytes.write_u8(payload.kind)?;
bytes.write_u16::<LittleEndian>(payload.value)?;
Ok(bytes)
}
fn decode(buf: &[u8]) -> Result<Payload> {
let mut rdr = Cursor::new(buf);
Ok(Payload {
kind: rdr.read_u8()?,
value: rdr.read_u16::<LittleEndian>()?,
})
}
#[macro_use]
extern crate error_chain;
error_chain! {
foreign_links {
Io(::std::io::Error);
}
fn decode(mut bytes: &[u8]) -> io::Result<Payload> {
let payload = Payload {
kind: bytes.read_u8()?,
value: bytes.read_u16::<LittleEndian>()?,
};
Ok(payload)
}
fn main() { run().unwrap() }