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
- How it works
- What is in the box
- Examples
- With plf::list (fancy pointers)
- Rules and limitations
- Building
- Using it in a larger code base
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
- Only cage memory can be compressed. Compressing a stack or
mallocpointer is a bug. Debug builds catch it with an assertion. DefineCPTR_CHECKEDto keep that check (and the checks ondeallocateandnonnull_ptr) in release builds, where a failure prints a message and aborts. The cost is one compare and branch per compression, which did not show in the list benchmark (p50 to p95 unchanged). ptrconverts implicitly both ways betweenT*andptr<T>, so it can replace a raw pointer member with few other changes. The cost is that anyT*compresses without notice, andcond ? p : rawwith aptrand aT*is ambiguous.strict_ptr<T>is the same type with an explicitstrict_ptr<T>(raw)constructor and no assignment fromT*; it still converts toT*and toptr<T>implicitly, while aptr<T>becomes astrict_ptr<T>only explicitly.- Heterogeneous erase is opt-in. C++23 lets
erasetake any key type a transparent hash and comparator accept (m.erase(std::string_view(k))). The maps have it whenCPTR_HETEROGENEOUS_ERASEis defined. Define it for the whole program (on the command line, not in one source file), because it changes the class. - 64-bit only. A 32-bit target already has 4-byte pointers.
- Thread safety is that of the std containers. Allocating and freeing in a cage is thread-safe. A container may be read from several threads at once, but any thread that modifies it needs exclusive access.
- A cage is a type.
cptr::default_cageserves everything that does not name a cage. For a separate heap, declare a tag and a cage for it, eitherstruct mesh_heap : cptr::cage<mesh_heap> {};orstruct mesh_tag {}; using mesh_heap = cptr::cage<mesh_tag>;, and pass it as the containers' andptr'sCageargument. Pointers from different cages do not mix. Across shared libraries, mark your tagCPTR_VISIBLE(see below). - Freeing. Free what
cptr::makecreated withcptr::destroy, or letstd::unique_ptr<T, cptr::deleter<T>>(4 bytes) do it; freecptr::make_array<T>(n)withcptr::destroy_array(p, n). The containers free their own nodes. LeakSanitizer cannot see cage memory, so checkallocated_bytes()on the cage if you suspect a leak. - Standard library containers mostly ignore fancy pointers for their
internal links, so
cptr::fancy_allocatordoes not shrinkstd::listorstd::mapnodes. Use the bundled containers or a container that honours the allocator's pointer type (such as plf::list). Otherwise, put std containers' storage in the cage withcptr::allocatorand refer to their elements withcptr::ptr. - Allocator. Small blocks (up to 32 KiB) come from size-class slabs.
Each thread keeps a small cache of free blocks per size class, so most
allocations and frees take no lock; the cage-wide lock is taken once per
batch of blocks and for large allocations. Slabs whose blocks are all
free are kept for reuse for a quarter of a second (at most 64 MiB of
them), then their pages are given back to the OS.
default_cage::trim()does that at once and also returns the calling thread's cached blocks; other threads' cached blocks go back when they exit. Large blocks are decommitted on free, and adjacent free runs are merged.fork()is safe: the child can allocate even if another thread held the lock. - Shared libraries. A cage's base and bookkeeping are static members
of a header-only template, so every shared library gets its own copy
unless the dynamic linker merges them. The cage templates and
default_cageare markedCPTR_VISIBLE(default visibility), so on Linux and macOS they are merged even when libraries are built with-fvisibility=hidden; mark your own tags the same way:struct CPTR_VISIBLE my_cage : cptr::cage<my_cage> {};. Libraries loaded withdlopen(RTLD_LOCAL)may still get their own copy. Windows DLLs never share one: each DLL that uses a cage has its own, so keep everything that compresses or decompresses a given cage in one module. Debug builds assert when a module decompresses in a cage it never initialised, which is how this usually shows. - The cage's bookkeeping is never destroyed, so containers with static storage duration can still free into it during program exit.
- The cage size is fixed when the cage is reserved. The default is
4 GiB. Allocation fails with
std::bad_allocwhen the cage is full. - Misuse checks use
CPTR_ASSERT(cond, msg), which defaults toassert. Define it before including a cage header to log or count misuse instead; it is called fromnoexceptfunctions, so throwing from it ends instd::terminate. The checks that catch a pointer from outside the cage go throughCPTR_CHECK, which isCPTR_ASSERTunlessCPTR_CHECKEDis defined and you have not defined your ownCPTR_ASSERT: then it stays active in release builds and aborts with a message. - AddressSanitizer understands the cage: freed blocks are poisoned. LeakSanitizer does not see cage memory.
- Builds without exceptions (
-fno-exceptions, or MSVC without/EH) are supported. Where the library would throw (std::bad_allocwhen a cage is full,std::out_of_rangefromat(),std::length_errorfor too many buckets) it callsCPTR_ON_FAILURE(what)instead, which printswhatand aborts. DefineCPTR_ON_FAILUREbefore including any cptr header to report the failure your own way; it must not return. The containers' rollback code, which only runs when an element's constructor or comparator throws, compiles away. DefineCPTR_NO_EXCEPTIONSto get this behaviour in a build that has exceptions.
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 12, 13, 14, 15 and 16, and Clang 16 to 22 (with libstdc++, and Clang 22 also with libc++), on Linux x86-64;
- GCC 14 on Linux arm64, Apple Clang on macOS arm64 and x86-64, and MSVC 2022 and clang-cl on Windows (MSVC on x86-64 and arm64);
- AddressSanitizer, UBSan, ThreadSanitizer, a release build with
CPTR_CHECKED, and coverage, on Linux.
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).