liveBook · Manning

Raw pointer

As explained in Refactoring to Rust

A raw pointer is a Rust pointer whose dereferencing and validity are not governed by the borrow checker and may require an unsafe context.

A raw pointer stores a memory address without the lifetime or ownership information attached to a Rust reference. Because the compiler cannot validate whether its target is valid, dereferencing it requires an unsafe block and leaves those safety checks to the programmer. section 3.1.1 section 3.1

Raw pointers support low-level operations needed at language boundaries:

  • Use *const T for an immutable target and *mut T for a mutable target, paralleling immutable and mutable references. section 3.1.1
  • Obtain a pointer to a Vec<u8> buffer with as_ptr; creating the pointer is safe, but reading through it is unsafe. section 3.1.1
  • Read successive elements with pointer offset arithmetic, while ensuring that the pointer and length describe valid memory. section 3.1.1
  • Use null checks, offset_from, and std::slice::from_raw_parts when interpreting nested C structures or externally owned buffers. section 4.4.2

Reading a byte buffer

A vector can pass its buffer pointer and length to a function such as read_u8_slice. The function loops over the length and dereferences slice_p.offset(index as isize) inside unsafe, printing each byte.

How Refactoring to Rust covers it

How deep it goes
Explains addresses, validity, constness, buffer traversal, null checks, and slices, but leaves validity guarantees to the programmer.
Examples
Uses a Vec<u8> reader, stack-memory diagrams, C-style struct access, nested null checks, and NGINX request buffers.
What it assumes
Assumes familiarity with Rust references and their validity, then contrasts their compiler guarantees with raw addresses.
What you can do after
Apply it via unsafe blocks to read buffers and access C structures while checking pointers, lengths, and slice boundaries.
How it connects
Ties raw pointers to unsafe Rust, references, lifetimes, ownership, pointer arithmetic, slices, and C FFI.

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.