liveBook · Manning

Ptr::copy_nonoverlapping

As explained in Refactoring to Rust

std::ptr::copy_nonoverlapping is a Rust standard-library function that copies a specified number of elements between non-overlapping memory regions.

std::ptr::copy_nonoverlapping copies a specified number of elements from one non-overlapping memory region to another. In FFI response handling, it transfers Rust string bytes into a buffer allocated and owned by NGINX, avoiding a pointer to temporary Rust data that would become invalid after its scope ends. section 4.6

The response-buffer operation follows a small sequence:

  • Convert the response string slice to bytes and obtain its starting pointer with .as_ptr(). section 4.6 section 4.7
  • Allocate a destination buffer with the required byte length. section 4.6
  • Call std::ptr::copy_nonoverlapping with the source pointer, destination pointer, and byte count. section 4.6
  • Use the allocated buffer’s start and offset-derived end pointers to configure the NGINX buffer and output chain. section 4.6

Copying an HTTP response body

Given response_bytes and an allocated response_buffer, pass response_bytes.as_ptr(), response_buffer as *mut u8, and response_bytes.len() to copy the bytes into NGINX-owned memory. Unlike C memcpy, the Rust function places the destination pointer after the source pointer. section 4.6

let response_buffer =
    ngx_pcalloc(request.pool, response_bytes.len() as size_t);
  if response_buffer.is_null() {
    return Err("Failed to allocate response buffer");
  }

  std::ptr::copy_nonoverlapping(
    response_bytes.as_ptr(),  #1
    response_buffer as *mut u8,
    response_bytes.len(),
  );

Shows the allocation check and the complete copy_nonoverlapping call used for the response bytes. section 4.6

How Refactoring to Rust covers it

How deep it goes
Defines memcpy equivalence, reversed pointer order, and a concrete allocation-and-copy sequence, but does not explore ownership coordination.
Examples
Uses response_bytes, response_buffer, ngx_buf_t, and an NGINX output chain to demonstrate byte copying.
What it assumes
Requires familiarity with slices, byte views, raw pointers, and FFI allocation.
What you can do after
Apply it via raw pointers to transfer response bytes into an allocated FFI buffer.
How it connects
Connects slices, as_ptr, raw pointers, NGINX memory allocation, pointer offsets, and HTTP response buffers.

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.