@@ -124,12 +124,42 @@ static bool file_exists (char *filename) {
124
124
return (stat (filename , & buffer ) == 0 );
125
125
}
126
126
127
+ void schunk_base_incref (blosc2_schunk * schunk )
128
+ {
129
+ blosc2_schunk * base ;
130
+ if (schunk -> base != NULL ) {
131
+ base = schunk -> base ;
132
+ }
133
+ else {
134
+ base = schunk ;
135
+ }
136
+ base -> refcount += 1 ;
137
+ }
138
+
139
+ /* Decrement owner refcount and free owner when reaches zero.
140
+ * Note: this frees the owner struct itself; callers must ensure they don't access owner afterwards.
141
+ */
142
+ void schunk_base_decref (blosc2_schunk * schunk )
143
+ {
144
+ blosc2_schunk * base ;
145
+ if (schunk -> base != NULL ) {
146
+ base = schunk -> base ;
147
+ }
148
+ else {
149
+ base = schunk ;
150
+ }
151
+ base -> refcount -= 1 ;
152
+ if (base -> refcount <= 0 ) {
153
+ blosc2_schunk_free (base ); // this frees schunk and will free data if necessary
154
+ }
155
+ }
127
156
128
157
/* Create a new super-chunk */
129
158
blosc2_schunk * blosc2_schunk_new (blosc2_storage * storage ) {
130
159
blosc2_schunk * schunk = calloc (1 , sizeof (blosc2_schunk ));
131
160
schunk -> version = 0 ; /* pre-first version */
132
161
schunk -> base = (blosc2_schunk * ) NULL ; /* not a view by default, is its own base */
162
+ schunk -> refcount = 1 ; /* one reference by default */
133
163
134
164
// Get the storage with proper defaults
135
165
schunk -> storage = get_new_storage (storage , & BLOSC2_CPARAMS_DEFAULTS , & BLOSC2_DPARAMS_DEFAULTS , & BLOSC2_IO_DEFAULTS );
@@ -494,7 +524,7 @@ int64_t blosc2_schunk_append_file(blosc2_schunk* schunk, const char* urlpath) {
494
524
int blosc2_schunk_free (blosc2_schunk * schunk ) {
495
525
int err = 0 ;
496
526
497
- if (schunk -> data != NULL && schunk -> base ! = NULL ) {
527
+ if (schunk -> data != NULL && schunk -> base = = NULL ) {
498
528
// If not a view (and so base points to true array), free all chunks
499
529
for (int i = 0 ; i < schunk -> nchunks ; i ++ ) {
500
530
free (schunk -> data [i ]);
@@ -540,7 +570,7 @@ int blosc2_schunk_free(blosc2_schunk *schunk) {
540
570
free (schunk -> storage );
541
571
}
542
572
543
- if (schunk -> frame != NULL && schunk -> base ! = NULL ) {
573
+ if (schunk -> frame != NULL && schunk -> base = = NULL ) {
544
574
// If not a view (and so base points to true array), free all chunks
545
575
frame_free ((blosc2_frame_s * ) schunk -> frame );
546
576
}
0 commit comments