Stateful pointer - Use unused bits in your pointer

Overview

Stateful Pointer Library

Sometimes space is tight! What if you could squeeze extra state into a pointer at (almost) no additional cost?

A pointer occupies 32 or 64 bit, which is 4 or 8 bytes just to remember a memory address. On common hardware-platforms, some bits of the address are not used, because the computer allocates aligned memory addresses which are multiples of an alignment value. The Stateful Pointer Library is a C++11 header-only library which provides safe access to those bits. It contains a smart pointer that mimics std::unique_ptr, but allows you to use up to 24 bits to store extra state inside the pointer in a safe way. These freely useable bits are encoded inside the pointer itself and occupy no extra space.

The library uses Boost.Align to allocate aligned memory. On most platforms (Windows, MacOS, Linux, Android, ...), special system calls are used to get aligned memory at no additional cost. On other platforms, extra memory is allocated to guarantee the alignment of the pointer. The amount grows with the number of bits in the pointer that are used to carry extra state. In either case, the pointers of the Stateful Pointer Library are guaranteed to have the same size as a normal pointer.

Platform dependence: The library relies on two platform-dependent aspects of memory handling.

  • Memory addresses map trivially to consecutive integral numbers.
  • The address of aligned memory, in its representation as an integral number, is an exact multiple of the alignment value.

The C++ standard not does guarantee these properties, as explained on StackOverflow. Nevertheless, common platforms in use today seem to support this simple memory addressing scheme. There is no guarantee, of course, that future platforms will do the same, so use this library with caution. Many thanks go to the knowledgable Redditors who pointed all this out.

Caveat: The library uses custom memory allocation to do its magic, so it does not work with classes/environments that also customize heap allocation.

Code is released under the Boost Software License v1.0 (see LICENSE file).

Tagged pointer

Like std::unique_ptr in interface and behavior, but encodes N extra bits of information inside the pointer, using no additional space.

#include "stateful_pointer/tagged_ptr.hpp"
#include "boost/utility/binary.hpp" // macro to make binary literals
#include <cassert>
#include <iostream>

using namespace stateful_pointer;

// class to be allocated on the heap
struct A {
    int a;
    A(int x) : a(x) {}
};

int main() {
    // tagged_ptr has the same size as a normal pointer
    assert(sizeof(tagged_ptr<A, 4>) == sizeof(void*));

    // make tagged_ptr to an instance of A with 4 bits of extra state
    auto p = make_tagged<A, 4>(3); // 3 is passed to the ctor of A

    // set the 4 bits to some values
    p.bits(BOOST_BINARY( 1010 )); // that's 10 in decimal

    std::cout << "a = " << p->a << ", bits = " << p.bits() << std::endl;

    // prints: "a = 3, bits = 10"
}

String

The World's most compact STL-compatible string with small string optimization. Has the size of a mere pointer and yet stores up to 7 characters (on a 64-bit system) without allocating extra memory on the heap.

#include "stateful_pointer/string.hpp"
#include <cassert>
#include <iostream>

using namespace stateful_pointer;

int main() {
    // string has the same size as a normal pointer
    assert(sizeof(string) == sizeof(void*));

    string s("foo bar"); // small string optimisation: no heap allocation
    std::cout << s << std::endl;

    // prints: "foo bar"
}

This one is still in development, a lot of the standard interface is still missing.

Performance

tagged_ptr vs std::unique_ptr

In optimized builds, the performance is similar. Most importantly, access is as fast. Pointer creation is at most 10 % slower and becomes negligible compared to the allocation and initialization cost of larger pointees.

Benchmark CPU [ns]
unique_ptr_creation<char> 29
tagged_ptr_creation<char> 32
unique_ptr_creation<std::array<char, 256>> 70
tagged_ptr_creation<std::array<char, 256>> 72
unique_ptr_access<char> 2
tagged_ptr_access<char> 2
unique_ptr_access<std::array<char, 256>> 2
tagged_ptr_access<std::array<char, 256>> 2

(Google benchmark library run on 4x3GHz CPUs, compiled with -O3)

You might also like...
A package to use Material side sheet into your Flutter project. Learn more about side sheet at Material.io
A package to use Material side sheet into your Flutter project. Learn more about side sheet at Material.io

Side Sheet A package to use Material side sheet into your Flutter project. Learn more about side sheet at Material.io Platform Support Android iOS Mac

Had a tough time playing Microsoft Wordament ? Well WORDament_Solver has your back. It suggests you meaningful words you can use while playing the game and help you top the leaderboard.
Had a tough time playing Microsoft Wordament ? Well WORDament_Solver has your back. It suggests you meaningful words you can use while playing the game and help you top the leaderboard.

WORDament_Solver Had a tough time playing Microsoft Wordament ? Well WORDament_Solver has your back. It suggests you meaningful words you can use whil

Use cmake with your stm32 project.
Use cmake with your stm32 project.

cmake bare metal (cbm) Overview This Repo is project using cmake to develop stm32fxx projects under the same repo. And thereby sharing commmon functio

Use this to speed up your final project and reduce code bloat
Use this to speed up your final project and reduce code bloat

224 Superior Serial.print statements Use this to speed up your final project and reduce code bloat! And we learn about printing formatted strings usin

The package allows to use H3 library directly in your Flutter application

The package allows to use H3 library directly in your Flutter application

Turn your ESP32 into a easy to use micro web-server allowing to interact with any GPIO by simple http(s) calls.

WebhooksTriggeredESP32WiFi Turn your ESP32 into an easy to use and manage wireless micro web-server allowing it to process reliably and asynchronouly

Program that allows you to get the source code of a website's home page without doing it manually. Use it at your own risk.

Website-Homepage-Grabber Install one of the folders x64 or x32 if the program doesn't work(probably because you don't have visual studio installed) If

Project to check which Nt/Zw functions your local EDR is hooking

Probatorum EDR Userland Hook Checker Probatorum will check which Nt/Zw functions your local EDR is hooking. Most credit for this code goes to SolomonS

A program that allows you to hide certain windows when sharing your full screen
A program that allows you to hide certain windows when sharing your full screen

Invisiwind Invisiwind (short for Invisible Window) is an application that allows you to hide certain windows when sharing your full screen.

Owner
Hans Dembinski
Particle physicist, C++ and Python expert, statistician. Author of boost::histogram.
Hans Dembinski
C-function for traversing files/directories effectively and calling a given function with each encountered file and a void-pointer as parameters

C-function for traversing files/directories effectively and calling a given function with each encountered file and a void-pointer as parameters

null 1 Jun 27, 2022
Learn how to connect your Flexispot (LoctekMotion) desk to the internet. This repository contains a collection of scripts to get your started, combined with research and instructions.

(image source: Windows Central) Turn your LoctekMotion/FlexiSpot desk into a smart desk Recently I acquired a new standing desk from FlexiSpot. During

Mick Vleeshouwer 216 Dec 28, 2022
emPOWer your commits. Pointlessly flex on your coworkers with bespoke commit hashes, all with the convenience of a single command.

git-power emPOWer your commits. Pointlessly flex on your coworkers with bespoke commit hashes, all with the convenience of a single command.

Glenn Smith 246 Dec 19, 2022
A header maker, this project will create your header file with all your declaration in

Headermaker Install: git clone https://github.com/rmechety42/Headermaker.git cd Headermaker make install Usage: Headermaker src_folder_you_want_to

Rayan Mechety 35 Dec 8, 2022
Lock you keyboard and clean your screen. A simple, and easy way to clean your computers.

Pristine Cleaner A screen and keyboard cleaning application made to turn screen black, and lock keyboard for easy cleaning. With features such as star

Rhino Inani 2 Jan 16, 2022
✨ Your best friend when it comes to making your output beautiful ✨

?? Fadey ✨ Your best friend when it comes to making your output beautiful ✨ ?? Content: About Requirements Installation Features Performance Shoutout

Fluffy 3 Nov 29, 2021
A program to backup all of your game savefiles on your system, neatly, and into a single folder.

Savefile Saver I created this project as a solution to a simple, but annoying problem: Backing up my game savefiles. I wanted to be able to copy all o

Dominic Esposito 6 Oct 24, 2022
Flutter app where you can find your information about your Favorite Super Cars ⚡❤

Super Cars App (Flutter) ⚡ Now you can freely discover and browse your Favourite Super Cars ❤ . Speed! ?? Getting Started This project is a starting p

Shehroz Ali 4 Apr 13, 2022
A continuation of FSund's pteron-keyboard project. Feel free to contribute, or use these files to make your own! Kits and PCBs are also available through my facebook page.

pteron-pcb Intro This project is the evolution of the Pteron-Keyboard project, an incredible ergonomic keyboard that was handwired only. I aimed to in

null 17 Oct 11, 2022
Bobby Cooke 328 Dec 25, 2022