liveBook · Manning

Std::slice::from_raw_parts

As explained in Refactoring to Rust

std::slice::from_raw_parts is a Rust standard-library function that constructs a slice from a raw pointer and an element count.

std::slice::from_raw_parts constructs a borrowed slice from a raw pointer and an element count. A slice is a cheap view represented by a pointer and length, without reallocating the underlying memory. section 4.4.2 section 4.7

In an NGINX plugin, the function reads request-body buffers through C pointers, creates an &[u8] view, and then converts it to &str only after checking that the bytes are valid UTF-8. The returned string slice carries the request reference's lifetime, preventing it from outliving the request-owned memory. section 4.4.2

The operation fits into a small FFI pipeline:

  • Check that the request body, buffer chain, and buffer pointer are initialized before dereferencing them. section 4.4.2
  • Find the byte range by comparing the buffer's end pointer with its starting pointer, then use the resulting count. section 4.4.2
  • Construct a contiguous byte slice from the pointer and length, then validate UTF-8 before exposing a Rust string slice. section 4.4.2 section 4.7

Request-body view

An unsafe helper can return Result<&'a str, &'static str> while borrowing the request for 'a. The slice views NGINX's existing request buffer rather than copying it, so retaining the result after the request ends is invalid. section 4.4.2

unsafe fn request_body_as_str<'a>(
  request: &'a ngx_http_request_t,
) -> Result<&'a str, &'static str>

Inspect the complete helper signature to see how the request lifetime is connected to the returned string slice. section 4.4.2

How Refactoring to Rust covers it

How deep it goes
Explains slice representation, pointer-length construction, lifetime coupling, and UTF-8 validation, but not the function's full contract.
Examples
Uses an NGINX request-body helper, chained buffer structs, null checks, pointer offsets, and a curl request as concrete artifacts.
What it assumes
Assumes raw-pointer and C-FFI context, while introducing slices and explaining their relationship to owned strings and borrowed string views.
What you can do after
Apply it to construct a borrowed byte view over contiguous foreign memory before performing validated string conversion.
How it connects
Connects raw pointers with slices, lifetimes, UTF-8 validation, FFI, and pointer offset calculations.

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.