How it works...

First things first, we need a binary source. In our example, we simply use a vector. Then, we wrap it into a Cursor, as it provides us with a Seek implementation and some methods for our convenience.

The Cursor has an internal position count that keeps track of which byte we are accessing at the moment. As expected, it starts at zero. With read_u8 and read_i8, we can read the current byte as an unsigned or signed number. This will advance the position by one. Both do the same thing, but return a different type.

Did you notice that we printed the returned byte by using {:b} as the formatting parameter [11]?

println!("first byte in binary: {:b}", first_byte);

By doing so, we tell the underlying format! macro to interpret our byte as binary, which is why it will print 10 instead of 2. If you want to, try replacing {} in our other printing calls with  {:b} and compare the results.

The current position can be read with position() [25] and set with set_position(). You can also manipulate your position with the more verbose Seek API we introduced in the last recipe [30]. When using SeekFrom::End, keep in mind that this will not count backward from the end. For example, SeekFrom::End(1) will point to one byte after the end of the buffer and not before. The behavior is defined in this way because, maybe somewhat surprisingly, it is legal to seek past a buffer. This can be useful when writing, as it will simply pad the space between the end of the buffer and the cursor position with zeros.

When dealing with more then one byte, you will need to specify the endianness of the bytes via type annotation. Reading or writing will then advance the position by the number of bytes read or written, which is why, in our example code, we need to frequently reset the position with set_position(0). Note that when you write past the end, you will always simply extend the buffer [48].

If you know that you want to read a very specific amount of bytes, like when parsing a well-defined protocol,  you can do so by providing a fixed-size array and filling it by post-fixing your read with _into, like this:

// Read exactly five bytes
let mut read_buffer = [0; 5];
buff.read_u16_into::<LittleEndian>(&mut read_buffer).expect("Failed to fill buffer");

When doing so, the read will return an error if the buffer was not filled completely, in which case its contents are undefined.

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

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