X-Git-Url: https://git.ozlabs.org/?a=blobdiff_plain;f=ccan%2Ftal%2Fautoptr%2Fautoptr.c;fp=ccan%2Ftal%2Fautoptr%2Fautoptr.c;h=5f22ef2c08c3272840017f53645a4e2bba6b0b33;hb=97ac5832db26f5f836fff979b08f01e17d7216bd;hp=0000000000000000000000000000000000000000;hpb=58277ab6c8b4dd6bb66638b88bd8505f46fdcb07;p=ccan diff --git a/ccan/tal/autoptr/autoptr.c b/ccan/tal/autoptr/autoptr.c new file mode 100644 index 00000000..5f22ef2c --- /dev/null +++ b/ccan/tal/autoptr/autoptr.c @@ -0,0 +1,35 @@ +/* MIT (BSD) license - see LICENSE file for details */ +#include + +struct autonull { + void **pp; +}; + +static void autonull_remove(struct autonull *a); +static void autonull_null_out(tal_t *p UNNEEDED, struct autonull *a) +{ + void **pp = a->pp; + tal_del_destructor(a, autonull_remove); + tal_free(a); + *pp = NULL; +} + +static void autonull_remove(struct autonull *a) +{ + /* Don't NULL us out now. */ + tal_del_destructor2(*a->pp, autonull_null_out, a); +} + +struct autonull *autonull_set_ptr_(const tal_t *ctx, void *pp, const tal_t *p) +{ + struct autonull *a = tal(ctx, struct autonull); + a->pp = (void **)pp; + *a->pp = (void *)p; + + /* If p is freed, NULL out a->pp */ + tal_add_destructor2(*a->pp, autonull_null_out, a); + + /* If they free autonull, it removes other destructor. */ + tal_add_destructor(a, autonull_remove); + return a; +}