mirror of
https://github.com/rust-lang-nursery/rust-cookbook
synced 2024-11-26 21:40:17 +00:00
Touch up the byteorder example
This commit is contained in:
parent
3d066af1a5
commit
1ef3788132
1 changed files with 22 additions and 30 deletions
|
@ -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() }
|
||||
|
|
Loading…
Reference in a new issue