medfall

A super great game engine
Log | Files | Refs

stringhash.h (1091B)


      1 #pragma once
      2 
      3 #include "intrinsics.h"
      4 
      5 constexpr u32 fnv1a_ct( const char * str, size_t n, u32 basis = U32( 2166136261 ) ) {
      6 	return n == 0 ? basis : fnv1a_ct( str + 1, n - 1, ( basis ^ str[ 0 ] ) * U32( 16777619 ) );
      7 }
      8 
      9 struct StringHash {
     10 	const char * str;
     11 	u32 hash;
     12 
     13 	StringHash() { }
     14 
     15 	template< size_t N >
     16 	StringHash( const char ( & s )[ N ] ) {
     17 		str = s;
     18 		hash = fnv1a_ct( s, N - 1 );
     19 	}
     20 };
     21 
     22 template< typename T, size_t N >
     23 class StaticMap {
     24 	struct Node {
     25 		StringHash key;
     26 		T value;
     27 	};
     28 
     29 	Node nodes[ N ];
     30 	size_t nodes_in_use = 0;
     31 
     32 	bool get( StringHash key, T * x ) {
     33 		for( size_t i = 0; i < nodes_in_use; i++ ) {
     34 			if( nodes[ i ].key.hash == key.hash ) {
     35 				if( x != NULL ) *x = nodes[ i ].value;
     36 				return true;
     37 			}
     38 		}
     39 		return false;
     40 	}
     41 
     42 public:
     43 	void add( StringHash key, const T & value ) {
     44 		ASSERT( nodes_in_use < N );
     45 		ASSERT( !get( key, NULL ) );
     46 
     47 		Node node;
     48 		node.key = key;
     49 		node.value = value;
     50 		nodes[ nodes_in_use ] = node;
     51 
     52 		nodes_in_use++;
     53 	}
     54 
     55 	T get( StringHash key ) {
     56 		T res;
     57 		bool ok = get( key, &res );
     58 		ASSERT( ok );
     59 		return res;
     60 	}
     61 };