medfall

A super great game engine
Log | Files | Refs

commit fe92c9f6e9b0b3aa94a11e53547f96a54f3b6cf9
parent 1fd5e48ec77dab6949e13c32dfcc860852224b60
Author: Michael Savage <mikejsavage@gmail.com>
Date:   Mon May 15 03:31:42 +0300

Add stringhash.h

Diffstat:
stringhash.h | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 66 insertions(+), 0 deletions(-)
diff --git a/stringhash.h b/stringhash.h @@ -0,0 +1,66 @@ +#pragma once + +#include "intrinsics.h" + +constexpr static inline u32 fnv1a( const char * str, size_t n ) { + return n == 0 ? 0x811C9DC5 : ( fnv1a( str + 1, n - 1 ) ^ u32( str[ 0 ] ) ) * 0x01000193; +} + +template< size_t N > +constexpr static inline u32 fnv1a( const char ( & str )[ N ] ) { + return fnv1a( str, N ); +} + +struct StringHash { + const char * str; + u32 hash; + + StringHash() { } + + template< size_t N > + StringHash( const char ( & s )[ N ] ) { + str = s; + hash = fnv1a( s ); + } +}; + +template< typename T, size_t N > +class StaticMap { + struct Node { + StringHash key; + T value; + }; + + Node nodes[ N ]; + size_t nodes_in_use = 0; + + bool get( StringHash key, T * x ) { + for( size_t i = 0; i < nodes_in_use; i++ ) { + if( nodes[ i ].key.hash == key.hash ) { + if( x != NULL ) *x = nodes[ i ].value; + return true; + } + } + return false; + } + +public: + void add( StringHash key, const T & value ) { + ASSERT( nodes_in_use < N ); + ASSERT( !get( key, NULL ) ); + + Node node; + node.key = key; + node.value = value; + nodes[ nodes_in_use ] = node; + + nodes_in_use++; + } + + T get( StringHash key ) { + T res; + bool ok = get( key, &res ); + ASSERT( ok ); + return res; + } +};