Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Atom

String interning library in C++. Identical strings share a single pointer, making equality checks O(1). Includes arena allocator and O(1) length lookup via inline headers.

Author: Fernando A.

What is string interning?

Without interning, two strings with the same content have different addresses in memory:

const char *a = "Test";
const char *b = "Test";
a == b // false

With interning, identical strings always return the same pointer:

const char *a = CAtom::NewAtom( "Test" );
const char *b = CAtom::NewAtom( "Test" );
a == b // true

This turns string equality from O(n) to O(1).

How it works

CAtom maintains a hash table of 2048 buckets. Each entry (atom_t) is allocated contiguously with its string in a single arena block:

[ atom_t header | s t r i n g \0 ]

This layout allows GetLength() to recover the length in O(1) by walking back one atom_t from the string pointer, with no iteration:

int32_t CAtom::GetLength( const char *string )
{
    atom_t *ptr = (atom_t *)string - 1;
    return ptr->length;
}

Memory is managed by CArena, an arena allocator that grows in 64KB blocks. All atoms live in arena 0.

Usage

#include "Atom.h"
#include <stdio.h>

static inline void Print( const char *str, const char *strr )
{
    if ( str == strr ) {
        printf( "They're the same [%s == %s]\n", str, strr );
        return;
    }
    printf( "They're not the same [%s != %s]\n", str, strr );
}

int main( void )
{
    const char *a = CAtom::NewAtom( "Test" );
    const char *b = CAtom::NewAtom( "Test2" );
    const char *c = CAtom::NewAtom( "Test" );  // same address as a

    Print( a, b );  // not the same
    Print( b, c );  // not the same
    Print( a, c );  // same

    printf( "[%s] length = %d", a, CAtom::GetLength(a) );
    return 0;
}

Output:

They're not the same [Test != Test2]
They're not the same [Test2 != Test]
They're the same [Test == Test]
[Test] length = 4

Files

File Description
Atom.h / Atom.cpp String interning implementation
Arena.h / Arena.cpp Arena allocator used internally
main.cpp Usage example

About

String interning library in C++. Deduplicates strings by pointer, with O(1) length lookup via arena-allocated headers.

Resources

Stars

Watchers

Forks

Contributors

Languages