blitz_handle.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "blitz.h"
  2. #define HASH_SIZE 1024
  3. #define HASH_SLOT(X) (((X)/8)&(HASH_SIZE-1)) // divide-by-8 for better void* mapping.
  4. static int _handle_id;
  5. typedef struct Hash Hash;
  6. struct Hash{
  7. Hash *succ;
  8. int key,value;
  9. };
  10. static Hash *object_hash[HASH_SIZE];
  11. static Hash *handle_hash[HASH_SIZE];
  12. static int hashFind( Hash **table,int key ){
  13. Hash *t,**p;
  14. int t_key=HASH_SLOT(key);
  15. for( p=&table[t_key];(t=*p) && t->key!=key;p=&t->succ ){}
  16. return t ? t->value : 0;
  17. }
  18. static int hashRemove( Hash **table,int key ){
  19. Hash *t,**p;
  20. int t_key=HASH_SLOT(key),n;
  21. for( p=&table[t_key];(t=*p) && key!=t->key;p=&t->succ ){}
  22. if( !t ) return 0;
  23. n=t->value;
  24. *p=t->succ;
  25. bbMemFree( t );
  26. return n;
  27. }
  28. static void hashInsert( Hash **table,int key,int value ){
  29. int t_key=HASH_SLOT(key);
  30. Hash *t=(Hash*)bbMemAlloc( sizeof(Hash) );
  31. t->key=key;
  32. t->value=value;
  33. t->succ=table[t_key];
  34. table[t_key]=t;
  35. }
  36. int bbHandleFromObject( BBObject *o ){
  37. int n;
  38. if( o==&bbNullObject ) return 0;
  39. n=hashFind( object_hash,(int)o );
  40. if( n ) return n/8;
  41. BBRETAIN( o );
  42. _handle_id+=8;
  43. if( !(_handle_id/8) ) _handle_id+=8; //just-in-case!
  44. hashInsert( object_hash,(int)o,_handle_id );
  45. hashInsert( handle_hash,_handle_id,(int)o );
  46. return _handle_id/8;
  47. }
  48. BBObject *bbHandleToObject( int handle ){
  49. BBObject *o=(BBObject*)hashFind( handle_hash,handle*8 );
  50. return o ? o : &bbNullObject;
  51. }
  52. void bbHandleRelease( int handle ){
  53. BBObject *o=(BBObject*)hashRemove( handle_hash,handle*8 );
  54. if( !o ) return;
  55. hashRemove( object_hash,(int)o );
  56. BBRELEASE( o );
  57. }