liveBook · Manning

Std::str::from_utf8

As explained in Refactoring to Rust

std::str::from_utf8 is a Rust standard-library function that validates UTF-8 bytes and returns a string slice when they are valid.

std::str::from_utf8 validates a byte slice as UTF-8 and returns a Rust string slice when validation succeeds. In an NGINX HTTP handler, it turns the received request-body bytes into usable text while preserving error handling for invalid input. section 4.4.2

Reading an NGINX request body

After extracting the request-body buffer, validate it with std::str::from_utf8. A successful conversion produces a string slice containing the body, such as "3 4 * 2 -"; if errors are raised, the handler does not obtain valid text. section 4.4.2

How Refactoring to Rust covers it

How deep it goes
Explains validation and successful conversion, while leaving byte-buffer extraction and pointer arithmetic to surrounding code.
Examples
Demonstrates conversion of an NGINX request body containing "3 4 * 2 -" and verification through curl.
What it assumes
Assumes byte-slice extraction from FFI buffers and teaches the UTF-8 validity check that produces text.
What you can do after
Apply it in an NGINX HTTP handler to obtain validated request text from a byte slice.
How it connects
Connects UTF-8 validation with byte slices, string slices, raw pointers, lifetimes, and NGINX HTTP handlers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.