liveBook · Manning

Offset

As explained in Refactoring to Rust

offset is a Rust pointer operation that produces a pointer displaced by a specified number of elements from a base pointer.

offset is a Rust pointer operation that returns a pointer displaced by a specified number of elements from a base pointer. It is useful when a foreign API needs the end of an allocated buffer. section 4.6

Use offset when you need to:

  • Move from a base pointer by N elements in a contiguous block. section 4.7
  • Compute the end of a copied response buffer by adding its byte length to the buffer pointer. section 4.6
  • Distinguish forward pointer calculation with offset from measuring the difference between two pointers with offset_from. section 4.6

Finding a response buffer's end

After copying response bytes into response_buffer, assign buf.pos to the buffer start and buf.last to response_buffer.offset(response_bytes.len() as isize), cast to a byte pointer. The resulting range can be placed in an NGINX output chain. section 4.6

buf.pos = response_buffer as *mut u8;
  buf.last = response_buffer.offset(
    response_bytes.len() as isize) as *mut u8;

  let mut out_chain = ngx_chain_t {
    buf,
    next: std::ptr::null_mut(),
  };

Inspect the pointer calculation beside the buffer fields and output-chain initialization. section 4.6

How Refactoring to Rust covers it

How deep it goes
Defines element displacement and demonstrates its use for byte-buffer boundaries, alongside offset_from as a contrasting operation.
Examples
Uses a copied HTTP response buffer whose final pointer is calculated before placing it in an NGINX chain.
What it assumes
Assumes pointers, contiguous memory, byte slices, and foreign-function buffers; distinguishes offset_from during the explanation.
What you can do after
Apply it via Rust pointer arithmetic to construct a foreign-function buffer range.
How it connects
Connects raw pointers, contiguous memory, slices, offset_from, and C-style buffer handling.

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.