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
