Book Image

Rust Standard Library Cookbook

By : Jan Hohenheim, Daniel Durante
Book Image

Rust Standard Library Cookbook

By: Jan Hohenheim, Daniel Durante

Overview of this book

Mozilla’s Rust is gaining much attention with amazing features and a powerful library. This book will take you through varied recipes to teach you how to leverage the Standard library to implement efficient solutions. The book begins with a brief look at the basic modules of the Standard library and collections. From here, the recipes will cover packages that support file/directory handling and interaction through parsing. You will learn about packages related to advanced data structures, error handling, and networking. You will also learn to work with futures and experimental nightly features. The book also covers the most relevant external crates in Rust. By the end of the book, you will be proficient at using the Rust Standard library.
Table of Contents (12 chapters)

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...