summaryrefslogtreecommitdiff
path: root/ext/Hash-Util-FieldHash/FieldHash.xs
blob: e726041f605b0d373ade5072141a58542ea55b09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#define PERL_NO_GET_CONTEXT

#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

/* support for Hash::Util::FieldHash, prefix HUF_ */

/* A Perl sub that returns a hashref to the object registry */
#define HUF_OB_REG "Hash::Util::FieldHash::_ob_reg"
/* Identifier for PERL_MAGIC_ext magic */
#define HUF_IDCACHE 0x4944

/* For global cache of object registry */
#define MY_CXT_KEY "Hash::Util::FieldHash::_guts" XS_VERSION
typedef struct {
    HV* ob_reg; /* Cache object registry */
} my_cxt_t;
START_MY_CXT

/* Inquire the object registry (a lexical hash) from perl */
HV *
HUF_get_ob_reg(pTHX) {
    dSP;
    HV* ob_reg = NULL;
    I32 items;
    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    items = call_pv(HUF_OB_REG, G_SCALAR|G_NOARGS);
    SPAGAIN;

    if (items == 1 && TOPs && SvROK(TOPs) && SvTYPE(SvRV(TOPs)) == SVt_PVHV)
        ob_reg = (HV*)SvRV(POPs);
    PUTBACK;
    FREETMPS;
    LEAVE;

    if (!ob_reg)
        Perl_die(aTHX_ "Can't get object registry hash");
    return ob_reg;
}

/* Deal with global context */
#define HUF_INIT 1
#define HUF_CLONE 0
#define HUF_RESET -1

void
HUF_global(pTHX_ I32 how) {
    if (how == HUF_INIT) {
        MY_CXT_INIT;
        MY_CXT.ob_reg = HUF_get_ob_reg(aTHX);
    } else if (how == HUF_CLONE) {
        MY_CXT_CLONE;
        MY_CXT.ob_reg = HUF_get_ob_reg(aTHX);
    } else if (how == HUF_RESET) {
        dMY_CXT;
        MY_CXT.ob_reg = HUF_get_ob_reg(aTHX);
    }
}

/* Object id */

/* definition of id transformation */
#define HUF_OBJ_ID(x) newSVuv(PTR2UV(x))

SV *
HUF_obj_id(pTHX_ SV *obj) {
    SV *item = SvRV(obj);
    MAGIC *mg;
    SV *id;

    /* Get cached object ID, if it exists */
    if (SvTYPE(item) >= SVt_PVMG) {
        for ( mg = SvMAGIC(item); mg; mg = mg->mg_moremagic ) {
            if ((mg->mg_type == PERL_MAGIC_ext) &&
                (mg->mg_private == HUF_IDCACHE)
            ) {
                return mg->mg_obj;
            }
        }
    }

    /* Create an object ID, cache it */
    id = HUF_OBJ_ID(item);
    mg = sv_magicext(item, id, PERL_MAGIC_ext, NULL, NULL, 0);
    mg->mg_private = HUF_IDCACHE;
    SvREFCNT_dec(id); /* refcnt++ in sv_magicext() */

    /* Return the object ID */
    return id;
}

/* set up uvar magic for any sv */
void
HUF_add_uvar_magic(
    pTHX_
    SV* sv,                    /* the sv to enchant, visible to get/set */
    I32(* val)(pTHX_ IV, SV*), /* "get" function */
    I32(* set)(pTHX_ IV, SV*), /* "set" function */
    I32 index,                 /* get/set will see this */
    SV* thing                  /* any associated info */
) {
    struct ufuncs uf;
        uf.uf_val = val;
        uf.uf_set = set;
        uf.uf_index = index;
    sv_magic(sv, thing, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));
}

/* Fetch the data container of a trigger */
AV *
HUF_get_trigger_content(pTHX_ SV *trigger) {
    MAGIC* mg;
    if (trigger && (mg = mg_find(trigger, PERL_MAGIC_uvar)))
        return (AV*)mg->mg_obj;
    return NULL;
}

/* Delete an object from all field hashes it may occur in.  Also delete
 * the object's entry from the object registry.  This function goes in
 * the uf_set field of the uvar magic of a trigger.
 */
I32 HUF_destroy_obj(pTHX_ IV index, SV *trigger) {
    PERL_UNUSED_ARG(index);
    /* Do nothing if the weakref wasn't undef'd.  Also don't bother
     * during global destruction.  (MY_CXT.ob_reg is sometimes funny there) */
    if (!SvROK(trigger) && (!PL_in_clean_all)) {
        dMY_CXT;
        AV* cont = HUF_get_trigger_content(aTHX_ trigger);
        SV* ob_id = *av_fetch(cont, 0, 0);
        HV* field_tab = (HV*) *av_fetch(cont, 1, 0);
        HE* ent;
        hv_iterinit(field_tab);
        while ((ent = hv_iternext(field_tab))) {
            SV* field_ref = HeVAL(ent);
            SV* field = SvRV(field_ref);
            (void) hv_delete_ent((HV*)field, ob_id, 0, 0);
        }
        /* make it safe in case we must run in global clenaup, after all */
        if (PL_in_clean_all)
            HUF_global(aTHX_ HUF_RESET); /* shoudn't be needed */
        (void) hv_delete_ent(MY_CXT.ob_reg, ob_id, 0, 0);
    }
    return 0;
}

/* Create a trigger for an object.  The trigger is a magical SV
 * that holds a weak ref to the object.  The magic fires when the object
 * expires and takes care of garbage collection in registred hashes.
 * For that purpose, the magic structure holds the original id of
 * the object, and a list (a hash, really) of hashes from which the
 * object may * have to be deleted.  The trigger is stored in the
 * object registry and is also deleted when the object expires.
 */
SV *
HUF_new_trigger(pTHX_ SV *obj, SV *ob_id) {
    dMY_CXT;
    SV* trigger = sv_rvweaken(newRV_inc(SvRV(obj)));
    AV* cont = newAV();
    sv_2mortal((SV*)cont);
    av_store(cont, 0, SvREFCNT_inc(ob_id));
    av_store(cont, 1, (SV*)newHV());
    HUF_add_uvar_magic(aTHX_ trigger, NULL, &HUF_destroy_obj, 0, (SV*)cont);
    (void) hv_store_ent(MY_CXT.ob_reg, ob_id, trigger, 0);
    return trigger;
}

/* retrieve a trigger for obj if one exists, return NULL otherwise */
SV *
HUF_ask_trigger(pTHX_ SV *ob_id) {
    dMY_CXT;
    HE* ent;
    if ((ent = hv_fetch_ent(MY_CXT.ob_reg, ob_id, 0, 0)))
        return HeVAL(ent);
    return NULL;
}

/* get the trigger for an object, creating it if necessary */
SV *
HUF_get_trigger0(pTHX_ SV *obj, SV *ob_id) {
    SV* trigger;
    if (!(trigger = HUF_ask_trigger(aTHX_ ob_id)))
        trigger = HUF_new_trigger(aTHX_ obj, ob_id);
    return trigger;
}

SV *
HUF_get_trigger(pTHX_ SV *obj, SV *ob_id) {
    SV* trigger = HUF_ask_trigger(aTHX_ ob_id);
    if (!trigger)
        trigger = HUF_new_trigger(aTHX_ obj, ob_id);
    return( trigger);
}

/* mark an object (trigger) as having been used with a field
   (a clenup-liability)
*/
void
HUF_mark_field(pTHX_ SV *trigger, SV *field) {
    AV* cont = HUF_get_trigger_content(aTHX_ trigger);
    HV* field_tab = (HV*) *av_fetch(cont, 1, 0);
    SV* field_ref = newRV_inc(field);
    UV field_addr = PTR2UV(field);
    (void) hv_store(field_tab, (char *)&field_addr, sizeof(field_addr), field_ref, 0);
}

/* Determine, from the value of action, whether this call may create a new
 * hash key */
#define HUF_WOULD_CREATE_KEY(x) ((x) != HV_DELETE && ((x) & (HV_FETCH_ISSTORE | HV_FETCH_LVALUE)))

/* The key exchange functions.  They communicate with S_hv_magic_uvar_xkey
 * in hv.c */
I32 HUF_watch_key_safe(pTHX_ IV action, SV* field) {
    MAGIC* mg = mg_find(field, PERL_MAGIC_uvar);
    SV* keysv;
    if (mg && (keysv = mg->mg_obj)) {
        if (SvROK(keysv)) { /* ref key */
            SV* ob_id = HUF_obj_id(aTHX_ keysv);
            mg->mg_obj = ob_id; /* key replacement */
            if (HUF_WOULD_CREATE_KEY(action)) {
                SV* trigger = HUF_get_trigger(aTHX_ keysv, ob_id);
                HUF_mark_field(aTHX_ trigger, field);
            }
        } else if (HUF_WOULD_CREATE_KEY(action)) { /* string key */
            /* registered as object id? */
            SV* trigger;
            if (( trigger = HUF_ask_trigger(aTHX_ keysv)))
                HUF_mark_field(aTHX_ trigger, field);
        }
    } else {
        Perl_die(aTHX_ "Rogue call of 'HUF_watch_key_safe'");
    }
    return 0;
}

I32 HUF_watch_key_id(pTHX_ IV action, SV* field) {
    MAGIC* mg = mg_find(field, PERL_MAGIC_uvar);
    SV* keysv;
    PERL_UNUSED_ARG(action);
    if (mg && (keysv = mg->mg_obj)) {
        if (SvROK(keysv)) /* ref key */
            mg->mg_obj = HUF_obj_id(aTHX_ keysv); /* key replacement */
    } else {
        Perl_die(aTHX_ "Rogue call of 'HUF_watch_key_id'");
    }
    return 0;
}

int HUF_func_2mode( I32(* val)(pTHX_ IV, SV*)) {
    int ans = 0;
    if (val == &HUF_watch_key_id)
        ans = 1;
    if (val == &HUF_watch_key_safe)
        ans = 2;
    return(ans);
}

I32(* HUF_mode_2func( int mode))(pTHX_ IV, SV*) {
    I32(* ans)(pTHX_ IV, SV*) = NULL;
    switch (mode) {
        case 1:
            ans = &HUF_watch_key_id;
            break;
        case 2:
            ans = &HUF_watch_key_safe;
            break;
    }
    return(ans);
}

/* see if something is a field hash */
int
HUF_get_status(pTHX_ HV *hash) {
    int ans = 0;
    if (hash && (SvTYPE(hash) == SVt_PVHV)) {
        MAGIC* mg;
        struct ufuncs* uf;
        if ((mg = mg_find((SV*)hash, PERL_MAGIC_uvar)) &&
            (uf = (struct ufuncs *)mg->mg_ptr) &&
            (uf->uf_set == NULL)
        ) {
            ans = HUF_func_2mode(uf->uf_val);
        }
    }
    return ans;
}

/* Thread support.  These routines are called by CLONE (and nothing else) */

/* Fix entries for one object in all field hashes */
void
HUF_fix_trigger(pTHX_ SV *trigger, SV *new_id) {
    AV* cont = HUF_get_trigger_content(aTHX_ trigger);
    HV* field_tab = (HV*) *av_fetch(cont, 1, 0);
    HV* new_tab = newHV();
    HE* ent;
    SV* old_id = *av_fetch(cont, 0, 0);
    hv_iterinit(field_tab);
    while ((ent = hv_iternext(field_tab))) {
        SV* field_ref = HeVAL(ent);
        HV* field = (HV*)SvRV(field_ref);
        UV field_addr = PTR2UV(field);
        SV* val;
        /* recreate field tab entry */
        (void) hv_store(new_tab, (char *)&field_addr, sizeof(field_addr), SvREFCNT_inc(field_ref), 0);
        /* recreate field entry, if any */
        if ((val = hv_delete_ent(field, old_id, 0, 0)))
            (void) hv_store_ent(field, new_id, SvREFCNT_inc(val), 0);
    }
    /* update the trigger */
    av_store(cont, 0, SvREFCNT_inc(new_id));
    av_store(cont, 1, (SV*)new_tab);
}

/* Go over object registry and fix all objects.  Also fix the object
 * registry.
 */
void
HUF_fix_objects(pTHX) {
    dMY_CXT;
    I32 i, len;
    HE* ent;
    AV* oblist = (AV*)sv_2mortal((SV*)newAV());
    hv_iterinit(MY_CXT.ob_reg);
    while((ent = hv_iternext(MY_CXT.ob_reg)))
        av_push(oblist, SvREFCNT_inc(hv_iterkeysv(ent)));
    len = av_len(oblist);
    for (i = 0; i <= len; ++i) {
        SV* old_id = *av_fetch(oblist, i, 0);
        SV* trigger = hv_delete_ent(MY_CXT.ob_reg, old_id, 0, 0);
        SV* obj = SvRV(trigger);
        MAGIC *mg;

        SV* new_id = HUF_OBJ_ID(obj);

        /* Replace cached object ID with this new one */
        for (mg = SvMAGIC(obj); mg; mg = mg->mg_moremagic) {
            if ((mg->mg_type == PERL_MAGIC_ext) &&
                    (mg->mg_private == HUF_IDCACHE)
                ) {
                mg->mg_obj = new_id;
            }
        }

        HUF_fix_trigger(aTHX_ trigger, new_id);
        (void) hv_store_ent(MY_CXT.ob_reg, new_id, SvREFCNT_inc(trigger), 0);
    }
}

/* test support (not needed for functionality) */

static SV* counter;
I32 HUF_inc_var(pTHX_ IV index, SV* which) {
    PERL_UNUSED_ARG(index);
    PERL_UNUSED_ARG(which);
    sv_setiv(counter, 1 + SvIV(counter));
    return 0;
}

MODULE = Hash::Util::FieldHash          PACKAGE = Hash::Util::FieldHash

BOOT:
{
    HUF_global(aTHX_ HUF_INIT); /* create variables */
}

int
_fieldhash(SV* href, int mode)
PROTOTYPE: $$
CODE:
    HV* field;
    RETVAL = 0;
    if (mode &&
        href && SvROK(href) &&
        (field = (HV*)SvRV(href)) &&
        SvTYPE(field) == SVt_PVHV
    ) {
        
        HUF_add_uvar_magic(
            aTHX_
            SvRV(href),
            HUF_mode_2func(mode),
            NULL,
            0,
            NULL
        );
        RETVAL = HUF_get_status(aTHX_ field);
    }
OUTPUT:
    RETVAL

void
id(SV* ref)
PROTOTYPE: $
PPCODE:
    if (SvROK(ref)) {
        XPUSHs(HUF_obj_id(aTHX_ ref));
    } else {
        XPUSHs(ref);
    }

SV*
id_2obj(SV* id)
PROTOTYPE: $
CODE:
    SV* obj = HUF_ask_trigger(aTHX_ id);
    if (obj) {
        RETVAL = newRV_inc(SvRV(obj));
    } else {
        RETVAL = &PL_sv_undef;
    }
OUTPUT:
    RETVAL

SV*
register(SV* obj, ...)
PROTOTYPE: $@
CODE:
    SV* trigger;
    int i;
    RETVAL = NULL;
    if (!SvROK(obj)) {
        Perl_die(aTHX_ "Attempt to register a non-ref");
    } else {
        RETVAL = newRV_inc(SvRV(obj));
    }
    trigger = HUF_get_trigger(aTHX_ obj, HUF_obj_id(aTHX_ obj));
    for (i = 1; i < items; ++ i) {
        SV* field_ref = POPs;
        if (SvROK(field_ref) && (SvTYPE(SvRV(field_ref)) == SVt_PVHV)) {
            HUF_mark_field(aTHX_ trigger, SvRV(field_ref));
        }
    }
OUTPUT:
    RETVAL

void
CLONE(char* classname)
CODE:
    if (0 == strcmp(classname, "Hash::Util::FieldHash")) {
        HUF_global(aTHX_ HUF_CLONE);
        HUF_fix_objects(aTHX);
    }

void
_active_fields(SV* obj)
PPCODE:
    if (SvROK(obj)) {
        SV* ob_id = HUF_obj_id(aTHX_ obj);
        SV* trigger = HUF_ask_trigger(aTHX_ ob_id);
        if (trigger) {
            AV* cont = HUF_get_trigger_content(aTHX_ trigger);
            HV* field_tab = (HV*) *av_fetch(cont, 1, 0);
            HE* ent;
            hv_iterinit(field_tab);
            while ((ent = hv_iternext(field_tab))) {
                HV* field = (HV*)SvRV(HeVAL(ent));
                if (hv_exists_ent(field, ob_id, 0))
                    XPUSHs(sv_2mortal(newRV_inc((SV*)field)));
            }
        }
    }

void
_test_uvar_get(SV* svref, SV* countref)
ALIAS:
_test_uvar_get = 1
_test_uvar_set = 2
_test_uvar_same = 3
CODE:
    if (SvROK(svref) && SvROK(countref)) {
        counter = SvRV(countref);
        sv_setiv(counter, 0);
        HUF_add_uvar_magic(
            aTHX_
            SvRV(svref),
            ix & 1 ? &HUF_inc_var : 0,
            ix & 2 ? &HUF_inc_var : 0,
	    0,
            SvRV(countref)
        );
    }