1 /* This file is part of the Lexical-Types Perl module.
2 * See http://search.cpan.org/dist/Lexical-Types/ */
4 /* This is a pointer table implementation essentially copied from the ptr_table
5 * implementation in perl's sv.c, except that it has been modified to use memory
6 * shared across threads.
7 * Copyright goes to the original authors, bug reports to me. */
9 typedef struct ptable_ent {
10 struct ptable_ent *next;
15 typedef struct ptable {
21 #ifndef PTABLE_VAL_FREE
22 # define PTABLE_VAL_FREE(V)
25 STATIC ptable *ptable_new(void) {
26 ptable *t = PerlMemShared_malloc(sizeof *t);
29 t->ary = PerlMemShared_calloc(t->max + 1, sizeof *t->ary);
33 #define PTABLE_HASH(ptr) \
34 ((PTR2UV(ptr) >> 3) ^ (PTR2UV(ptr) >> (3 + 7)) ^ (PTR2UV(ptr) >> (3 + 17)))
36 STATIC ptable_ent *ptable_find(const ptable * const t, const void * const key) {
38 const UV hash = PTABLE_HASH(key);
40 ent = t->ary[hash & t->max];
41 for (; ent; ent = ent->next) {
49 STATIC void *ptable_fetch(const ptable * const t, const void * const key) {
50 const ptable_ent *const ent = ptable_find(t, key);
52 return ent ? ent->val : NULL;
55 STATIC void ptable_split(ptable * const t) {
56 ptable_ent **ary = t->ary;
57 const UV oldsize = t->max + 1;
58 UV newsize = oldsize * 2;
61 ary = PerlMemShared_realloc(ary, newsize * sizeof(*ary));
62 Zero(&ary[oldsize], newsize - oldsize, sizeof(*ary));
66 for (i = 0; i < oldsize; i++, ary++) {
67 ptable_ent **curentp, **entp, *ent;
70 curentp = ary + oldsize;
71 for (entp = ary, ent = *ary; ent; ent = *entp) {
72 if ((newsize & PTABLE_HASH(ent->key)) != i) {
83 STATIC void ptable_store(ptable * const t, const void * const key, void * const val) {
84 ptable_ent *ent = ptable_find(t, key);
87 void *oldval = ent->val;
88 PTABLE_VAL_FREE(oldval);
91 const UV i = PTABLE_HASH(key) & t->max;
92 ent = PerlMemShared_malloc(sizeof *ent);
95 ent->next = t->ary[i];
98 if (ent->next && t->items > t->max)
105 STATIC void ptable_clear(ptable * const t) {
107 register ptable_ent ** const array = t->ary;
111 ptable_ent *entry = array[i];
113 ptable_ent * const oentry = entry;
114 void *val = oentry->val;
116 PTABLE_VAL_FREE(val);
117 PerlMemShared_free(entry);
126 STATIC void ptable_free(ptable * const t) {
130 PerlMemShared_free(t->ary);
131 PerlMemShared_free(t);