TARFS 0.1.5
Read-only TAR filesystem for ESP32
Loading...
Searching...
No Matches
refc.c
Go to the documentation of this file.
1/*
2 * TARFS - Immutable (read-only) filesystem for embedded systems.
3 *
4 * Copyright (c) 2026 Viacheslav Logunov
5 * SPDX-License-Identifier: MMIT
6 *
7 * Author:
8 * Viacheslav Logunov <vvb333007@gmail.com>
9 *
10 * Project:
11 * https://github.com/vvb333007/tarfs
12 *
13 * @file refc.c
14 * @brief Public Atomic Reference Counter API implementation
15 */
16
17
18// if (addref(&str->ref)) {
19// use(str);
20// unref(&str->ref);
21// }
22//
23//
24
25
26#include <stdint.h>
27#include <stdatomic.h>
28#include <stdlib.h>
29#include <stdbool.h>
30
31#include "refc.h"
32
40
42 refc_type_t lim;
43
44 if ( ref == NULL )
45 return 0;
46
47 r = atomic_load_explicit(ref, memory_order_relaxed);
48 lim = ((refc_type_t )(-1)) - n;
49
50 do {
51
52 /* refcounter is dead or will be overflow by the addition of `n`? return `false` */
53 if (r < 1 || r > lim)
54 return 0;
55
56 /* CAS, acquire */
57 } while (!atomic_compare_exchange_weak_explicit(
58 ref,
59 &r,
60 r + n,
61 memory_order_acquire,
62 memory_order_relaxed));
63
64 return r + n;
65}
66
67
75refc_type_t unrefxn(refc_t *r, void *object, refc_type_t n, void (* dtor)(void *)) {
76
77 if (r != NULL && n > 0) {
78
79 int prev;
80
81 do {
82
83 if ((prev = atomic_fetch_sub_explicit(r, 1, memory_order_release)) == 1) {
84 atomic_thread_fence(memory_order_acquire);
85 /* call dtor() with either /object/ or /r/ as its argument */
86 if (dtor != NULL)
87 dtor(object ? object : r);
88 break;
89 }
90 } while(--n);
91 /* Successfully decremented, return old value to the user */
92 return prev;
93 }
94 return 0;
95}
refc_type_t unrefxn(refc_t *r, void *object, refc_type_t n, void(*dtor)(void *))
Release references and optionally destroy object.
Definition refc.c:75
refc_type_t addrefn(refc_t *ref, refc_type_t n)
Increase reference counter by specified value.
Definition refc.c:39
unsigned int refc_type_t
Use case:
Definition refc.h:47