compressed-ptr guide

Everything about using compressed-ptr: how it works, every header, the allocators, persistence, the rules, and building and testing. For the numbers, see Benchmarks; for every type and function, the API reference.

Contents

Background

Most programs never need more than 4 GiB for one data structure. If every node lives in one 4 GiB region, a pointer to a node only needs its 32-bit offset into that region.

The idea comes from V8, Chrome's JavaScript engine. It keeps its whole heap in one 4 GiB "cage" and stores 32-bit offsets instead of full pointers. See Pointer Compression in V8 (Igor Sheludko and Santiago Aboy Solanes, 2020). V8 builds this into its garbage collector and JIT. This library offers the same addressing trick for ordinary C++ code: plain pointers with a null value, a malloc-style allocator, several independent cages, and containers. No V8 code is used.

It is not a magic bullet. Each compressed pointer saves 4 bytes, so the gain depends on how much of each object is pointers: a list node holding an int halves, a node with two pointers and 200 bytes of payload shrinks by 4%. It pays for many small linked objects: linked lists, trees and ordered indexes, chained hash tables, graphs, tries, syntax trees and object graphs. Why lists typical cases.

How it works

 address space
 ┌───────────────────────────────── cage: 4 GiB, aligned to 4 GiB ─────────────────────────────────┐
 │ span 0 (never used, │ slabs of 8, 16, 24 ... byte blocks │ large blocks │ ... reserved only ... │
 │ so offset 0 = null) │                                    │              │                       │
 └─────────────────────────────────────────────────────────────────────────────────────────────────┘
 ^ base                 ^ base + 0x00012340
                        cptr::ptr stores 0x00012340

Cage. At first use, a cage reserves 4 GiB of address space aligned to 4 GiB (mmap(PROT_NONE) or VirtualAlloc(MEM_RESERVE)). Nothing is allocated at that point. Reserved space costs no memory and no swap; it is a range of addresses that nothing else in the process will be given. Pages are committed in 1 MiB steps as the allocator needs them, and given back to the OS when they are free again (see trim() below).

What that looks like from outside, measured on Linux with one list:

virtual size (VIRT, VmSize) resident (RES, VmRSS)
before the first allocation 6.4 MiB 3.3 MiB
after three elements 4.0 GiB 3.6 MiB
after a million elements 4.0 GiB 18.8 MiB

Tools that show virtual size (VIRT in top, VSZ in ps) count the reservation; memory accounting (RES, cgroup and container limits, the OOM killer) counts only resident pages. The one limit that sees the reservation is a cap on virtual memory (ulimit -v, RLIMIT_AS): allow 4 GiB per cage, or make the cage smaller with SizeLog2. Linux's overcommit setting does not matter, because the reservation is not writable until pages are committed.

Compression. A pointer is stored as p - base in 32 bits. The cage is aligned to its own size, so that is the pointer's low bits: a mask and a shift.

Decompression. base + bits is one add. ptr maps 0 to nullptr, which compilers turn into a conditional move or a well-predicted branch. nonnull_ptr skips that check.

Allocator. Every object a compressed pointer refers to must come from the cage. The cage has a built-in allocator: segregated free lists of header-less blocks in size classes up to 32 KiB, plus whole 64 KiB spans for larger blocks, which are decommitted on free. Alignments above 64 KiB are not supported (std::bad_alloc). It also works as a standard allocator and as a std::pmr::memory_resource.

Several cages. Each cage is its own type with its own base, so a program can have several independent 4 GiB heaps:

struct mesh_heap : cptr::cage<mesh_heap> {};
cptr::ptr<vertex, mesh_heap> v = cptr::make<vertex, mesh_heap>();

More than 4 GiB. If every object is 8-byte aligned, a cage can be 32 GiB with the pointer still 4 bytes. Pointers are stored shifted right by 3, which is the JVM's "compressed oops" trick:

struct big_heap : cptr::cage<big_heap, 35, 3> {};  // 2^35 = 32 GiB

What is in the box

Header Contents
cptr/cage.hpp cage<Tag, SizeLog2 = 32, Shift = 0>, default_cage: reserve, allocate, compress, decompress, pmr resource, statistics
cptr/ptr.hpp ptr<T, Cage> (nullable, 4 B), strict_ptr<T, Cage> (compressing a T* is explicit), nonnull_ptr<T, Cage>, make<T>(), destroy(), make_array<T>(n), destroy_array(), deleter<T> for std::unique_ptr, std::hash, std::pointer_traits
cptr/pack.hpp ptr_pair (two pointers in 8 B), ptr_with_payload (pointer + 32-bit value in 8 B), tagged_ptr (pointer + tag bits in 4 B), atomic_ptr (lock-free CAS on 4 B)
cptr/allocator.hpp cptr::allocator<T>, so any std container's elements live in the cage
cptr/fancy_allocator.hpp cptr::fancy_allocator<T> with pointer = cptr::ptr<T>, for containers that support fancy pointers
cptr/list.hpp cptr::list<T>: doubly linked list with 4-byte links and the std::list interface
cptr/forward_list.hpp cptr::forward_list<T>: singly linked list with 4-byte links and the std::forward_list interface; 8-byte nodes for 4-byte values
cptr/unordered_map.hpp cptr::unordered_map<K, V>: hash map with separate chaining, 4-byte links and buckets, and the std::unordered_map interface without node handles and the bucket API; iterators are 16 bytes and survive move and swap
cptr/ordered_map.hpp cptr::ordered_map<K, V>: ordered map (red-black tree) with 4-byte links and the std::map interface, without node handles
cptr/user_cage.hpp user_cage<Tag, Allocator, SizeLog2 = 32, Shift = 0>: a cage whose blocks come from your own allocator; bump_allocator; cptr::vm commit helpers
cptr/mapped_cage.hpp mapped_cage<Tag, SizeLog2 = 32>: a cage whose memory is a file, with a root pointer; POSIX only
cptr/all.hpp All of the above except user_cage.hpp and mapped_cage.hpp

Operations that only touch the stored offset are constexpr: null, pointer arithmetic, comparisons, bits() and from_bits(), conversions that keep the address, and get() and conversions of a null pointer. Compressing and decompressing need the cage's base, which is only known at run time.

list and ordered_map keep a sentinel node in the cage, so their iterators are one 8-byte pointer and end() stays valid as elements come and go. Each container is an alias of a cptr::detail::basic_* class (for example cptr::detail::basic_list), whose page in the API reference lists every member. Its last template argument, Compressed = false, gives raw links with the same code and allocator; the benchmarks use it to separate the effect of compression from the effect of the allocator. That raw form is not part of the public interface.

The built-in allocator is fast, but you can supply your own. A user_cage reserves the region and compresses like cage; your allocator is constructed once with the usable part of the region (reserved, not yet committed) and serves allocate(bytes, align) and deallocate(p). Commit memory with cptr::vm::commit as you use it. cptr::bump_allocator is a ready-made monotonic allocator, and a building block for others:

struct my_allocator {
  explicit my_allocator(std::span<std::byte> region);
  void* allocate(std::size_t bytes, std::size_t align);  // nullptr if full
  void deallocate(void* p);  // no size: the containers do not pass one
};
struct my_tag {};
using my_cage = cptr::user_cage<my_tag, my_allocator>;
cptr::ordered_map<int, int, std::less<>, my_cage> map;

The allocator must be safe to call from every thread that uses the cage.

A compressed pointer is an offset from the cage's base, so a structure built in a mapped_cage is still valid when the file is mapped again, by another process, at another address. The containers store their sentinel as a compressed link too, so a cptr::list or cptr::ordered_map of plain values can live in the file. The allocator keeps its state in the file, behind a lock there, so several processes can allocate in one file at once; the containers themselves are not synchronised. The file is created sparse at the full cage size, and only pages written to use disk space.

struct store_tag {};
using store = cptr::mapped_cage<store_tag>;
store::open("data.cage");
auto* h = store::root<history>();  // nullptr in a new file

The packing helpers often matter more than ptr itself. A lone 4-byte field next to an 8-byte one is padded back to 8 bytes. Gains come from putting two 4-byte halves together:

struct tree_node {
  cptr::ptr_pair<tree_node> children;  // left + right: 8 bytes
  std::uint32_t key;
  std::uint32_t subtree_size;
};
static_assert(sizeof(tree_node) == 16);  // 32 with raw pointers

Examples

Each example is a short, self-contained program in examples/:

Example Shows
expect_gains.cpp Measures memory and time of each std container against its cptr counterpart on your machine
lru_cache.cpp An LRU cache from unordered_map plus list: only the type names change
pmr.cpp A cage as a std::pmr::memory_resource, with compressed pointers into it
minimal.cpp Two objects pointing at each other; what is stored
linked_list.cpp cptr::list as a drop-in for std::list
tree.cpp A hand-written order-statistics tree with ptr_pair; 16-byte nodes
graph.cpp BFS over a graph whose edges are 4 bytes and whose adjacency vectors live in the cage
std_containers.cpp std::deque and std::pmr containers in the cage, indexed by cptr::ptr
custom_allocator.cpp Your own allocator behind a cage: a pool of 16-byte slots for list nodes
persistent.cpp A list kept in a file and reopened at a new address on every run
use_after_free.cpp AddressSanitizer catching a dangling compressed pointer

With plf::list (fancy pointers)

Containers that take their internal pointer type from the allocator can switch to 4-byte links without changes to their code. cptr::fancy_allocator has pointer = cptr::ptr<T>, and cptr::ptr supports the arithmetic, null pointer constants (0, NULL) and casts such containers need. With plf::list:

using compressed_list =
    plf::list<std::uint32_t, cptr::fancy_allocator<std::uint32_t>>;

// The list's end sentinel is a member of the list object and nodes link to
// it, so the list object itself must be in the cage too.
cptr::ptr<compressed_list> l = cptr::make<compressed_list>();
l->push_back(1);

The list object must live in the cage (see above). No other change is needed: plf::list takes its node pointer type from the allocator.

This needs plf::list 7.6.50 or later (plf_tools 1.0.17), the first releases that accept a fancy pointer for their end node.

Measured with bench_runtime ... plf (4,194,304 uint32_t, sort of 262,144 random values per epoch) and bench_rss (2,000,000), on an i7-12700H; ns per element at p50, change against plain plf::list:

bytes/element push_back walk pop_front sort
plf::list, GCC 15 24.1 8.00 1.71 2.60 83.9
with cptr::fancy_allocator, GCC 15 12.2 5.09 (−36%) 1.49 (−13%) 2.17 (−17%) 80.1 (−4%)
plf::list, Clang 22 24.1 7.58 1.90 3.22 85.0
with cptr::fancy_allocator, Clang 22 12.2 6.37 (−16%) 1.54 (−19%) 2.57 (−20%) 81.9 (−4%)

For comparison, std::list takes 32.0 bytes per element and 19.4, 2.1, 5.4 and 188 ns for the same four operations (GCC).

Build it with -DCOMPRESSED_PTR_PLF_LIST_DIR=/path/to/plf_list; see examples/plf_list_minimal.cpp for the smallest program and examples/plf_list.cpp for the measurements.

Rules and limitations

cpp // Before any cptr header: use the project's own fatal-error path. #define CPTR_ON_FAILURE(what) my_fatal_error("cptr", what) #include "cptr/all.hpp"

Building

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build
ctest --test-dir build              # unit tests + examples
./build/bench_rss                   # memory, one child process per config
./build/bench_runtime [elements] [epochs] [list|map|hash|arithmetic|conversion|allocator|threads|chase]

To use an installed copy, cmake --install build, then in your project:

find_package(compressed_ptr 0.1 CONFIG REQUIRED)
target_link_libraries(your_target PRIVATE compressed_ptr::compressed_ptr)

Without CMake, cmake --install also installs compressed_ptr.pc (pkg-config --cflags --libs compressed_ptr) and the single header cptr.hpp, which is also committed as single_include/cptr.hpp (generated by scripts/amalgamate.py; CI checks it is current). It holds every header, including user_cage.hpp and mapped_cage.hpp, which cptr/all.hpp leaves out.

There are no vcpkg or Conan recipes yet: both pin a tagged release by its archive hash, and there is no tagged release.

CI runs the benchmarks on every push, shows the tables in the run summary and keeps them as an artifact. scripts/check_bench.py fails the run if a median delta between variants measured side by side regresses past a limit (for example compressed against raw links, or the cage against malloc on two threads); absolute times on shared runners are too noisy to gate on.

scripts/test_install.sh checks find_package, FetchContent, pkg-config and the installed single header, and CI runs it on Linux, macOS and Windows. cptr/version.hpp defines CPTR_VERSION. Sources are formatted with clang-format 22 (.clang-format); CI checks it. CI also builds with warnings as errors (-DCOMPRESSED_PTR_WERROR=ON) and runs clang-tidy (.clang-tidy, scripts/run_tidy.sh build, on a build configured with -DCMAKE_EXPORT_COMPILE_COMMANDS=ON), failing on any diagnostic in include/cptr.

The fuzzers (fuzz_allocator, and fuzz_containers, which checks every container against its std counterpart) need clang:

cmake -S . -B build-fuzz -DCMAKE_CXX_COMPILER=clang++ -DCOMPRESSED_PTR_BUILD_FUZZERS=ON
cmake --build build-fuzz
./build-fuzz/fuzz_containers -max_total_time=60

Coverage (clang and llvm-cov; HTML report in build-coverage/):

scripts/coverage.sh            # LLVM_SUFFIX=-18 for versioned tool names

The tests cover 95% of the header lines, 99% of the functions and 88% of the branches. A second test executable overrides CPTR_ASSERT to check misuse detection, injects commit failures with CPTR_FAULT_INJECTION, and runs out of address space under RLIMIT_AS. A third is built with -fno-exceptions and checks that failures reach CPTR_ON_FAILURE. The remaining gaps are assertion branches that cannot be taken safely (such as freeing a pointer from outside the cage), the compile-time size-class table, and out-of-memory inside the allocator's own bookkeeping.

To use the library from another CMake project:

add_subdirectory(compressed-ptr)   # or FetchContent, or find_package(compressed_ptr)
target_link_libraries(app PRIVATE compressed_ptr::compressed_ptr)

Supported platforms: Linux, macOS and Windows on x86-64 and arm64. CI runs the tests with:

GCC 11 compiles the library and the examples but crashes on the test suite, so it is not tested.

Using it in a larger code base

This library came out of an experiment adding V8-style pointer compression to SpiderMonkey, Firefox's JavaScript engine. That work cut the engine's memory by about 40% over a 12-site browsing session. The engine-specific parts of that work (GC tracing, write barriers, JIT code that loads compressed pointers) cannot be done by a library. The parts that can are the ones here: the aligned reservation, the compress and decompress arithmetic, and the packing helpers, which keep the bit layout in one place. For a code base with its own allocator, the reservation and the arithmetic can be used on their own, with the compress and decompress functions of a cage type and cptr::detail::reserve_aligned (an implementation detail, so it may change between versions).