Coverage Report

Created: 2026-12-01 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/c-blosc2/blosc/schunk.c
Line
Count
Source
1
/*********************************************************************
2
  Blosc - Blocked Shuffling and Compression Library
3
4
  Copyright (c) 2021  Blosc Development Team <blosc@blosc.org>
5
  https://blosc.org
6
  License: BSD 3-Clause (see LICENSE.txt)
7
8
  See LICENSE.txt for details about copyright and rights to use.
9
**********************************************************************/
10
11
#include "frame.h"
12
#include "prefetch.h"
13
#include "schunk-private.h"
14
#include "stune.h"
15
#include "blosc-private.h"
16
#include "blosc-checked.h"
17
#include "context.h"
18
#include "blosc2/tuners-registry.h"
19
#include "blosc2.h"
20
21
#if defined(_WIN32)
22
#include <windows.h>
23
#include <direct.h>
24
#include <malloc.h>
25
#define mkdir(D, M) _mkdir(D)
26
#else
27
#include <unistd.h>
28
#endif  /* _WIN32 */
29
30
#include <sys/stat.h>
31
32
#include <inttypes.h>
33
#include <limits.h>
34
#include <stdio.h>
35
#include <stdint.h>
36
#include <stdlib.h>
37
#include <string.h>
38
39
/* If C11 is supported, use it's built-in aligned allocation. */
40
#if __STDC_VERSION__ >= 201112L
41
  #include <stdalign.h>
42
#endif
43
44
static int schunk_get_chunk_flags2(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk_flags2);
45
46
47
2.03M
static int validate_nchunk(blosc2_schunk *schunk, int64_t nchunk, bool allow_end, const char *func_name) {
48
2.03M
  if (nchunk < 0) {
49
0
    BLOSC_TRACE_ERROR("nchunk ('%" PRId64 "') is negative in %s.", nchunk, func_name);
50
0
    return BLOSC2_ERROR_INVALID_PARAM;
51
0
  }
52
53
2.03M
  if (allow_end) {
54
537k
    if (nchunk > schunk->nchunks) {
55
0
      BLOSC_TRACE_ERROR("nchunk ('%" PRId64 "') is out of range [0, %" PRId64 "] in %s.",
56
0
                        nchunk, schunk->nchunks, func_name);
57
0
      return BLOSC2_ERROR_INVALID_PARAM;
58
0
    }
59
537k
  }
60
1.50M
  else {
61
1.50M
    if (nchunk >= schunk->nchunks) {
62
41.0k
      BLOSC_TRACE_ERROR("nchunk ('%" PRId64 "') exceeds the number of chunks "
63
41.0k
                        "('%" PRId64 "') in %s.", nchunk, schunk->nchunks, func_name);
64
41.0k
      return BLOSC2_ERROR_INVALID_PARAM;
65
41.0k
    }
66
1.50M
  }
67
68
1.99M
  return BLOSC2_ERROR_SUCCESS;
69
2.03M
}
70
71
72
/* Get the cparams associated with a super-chunk */
73
21.1k
int blosc2_schunk_get_cparams(blosc2_schunk *schunk, blosc2_cparams **cparams) {
74
21.1k
  *cparams = calloc(1, sizeof(blosc2_cparams));
75
21.1k
  (*cparams)->schunk = schunk;
76
148k
  for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) {
77
126k
    (*cparams)->filters[i] = schunk->filters[i];
78
126k
    (*cparams)->filters_meta[i] = schunk->filters_meta[i];
79
126k
  }
80
21.1k
  (*cparams)->compcode = schunk->compcode;
81
21.1k
  (*cparams)->compcode_meta = schunk->compcode_meta;
82
21.1k
  (*cparams)->clevel = schunk->clevel;
83
21.1k
  (*cparams)->typesize = schunk->typesize;
84
21.1k
  (*cparams)->blocksize = schunk->blocksize;
85
21.1k
  (*cparams)->splitmode = schunk->splitmode;
86
21.1k
  (*cparams)->use_dict = schunk->use_dict;
87
21.1k
  if (schunk->cctx == NULL) {
88
11.8k
    (*cparams)->nthreads = blosc2_get_nthreads();
89
11.8k
  }
90
9.33k
  else {
91
9.33k
    (*cparams)->nthreads = (int16_t)schunk->cctx->nthreads;
92
9.33k
  }
93
21.1k
  return 0;
94
21.1k
}
95
96
97
/* Get the dparams associated with a super-chunk */
98
11.8k
int blosc2_schunk_get_dparams(blosc2_schunk *schunk, blosc2_dparams **dparams) {
99
11.8k
  *dparams = calloc(1, sizeof(blosc2_dparams));
100
11.8k
  (*dparams)->schunk = schunk;
101
11.8k
  if (schunk->dctx == NULL) {
102
11.8k
    (*dparams)->nthreads = blosc2_get_nthreads();
103
11.8k
  }
104
0
  else {
105
0
    (*dparams)->nthreads = schunk->dctx->nthreads;
106
0
  }
107
11.8k
  return 0;
108
11.8k
}
109
110
111
57.1k
int update_schunk_properties(struct blosc2_schunk* schunk) {
112
57.1k
  blosc2_cparams* cparams = schunk->storage->cparams;
113
57.1k
  blosc2_dparams* dparams = schunk->storage->dparams;
114
115
399k
  for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) {
116
342k
    schunk->filters[i] = cparams->filters[i];
117
342k
    schunk->filters_meta[i] = cparams->filters_meta[i];
118
342k
  }
119
57.1k
  schunk->compcode = cparams->compcode;
120
57.1k
  schunk->compcode_meta = cparams->compcode_meta;
121
57.1k
  schunk->clevel = cparams->clevel;
122
57.1k
  schunk->splitmode = cparams->splitmode;
123
57.1k
  schunk->use_dict = (uint8_t)cparams->use_dict;
124
57.1k
  schunk->typesize = cparams->typesize;
125
57.1k
  schunk->blocksize = cparams->blocksize;
126
57.1k
  schunk->chunksize = -1;
127
57.1k
  schunk->flags2 = 0;
128
57.1k
  schunk->tuner_params = cparams->tuner_params;
129
57.1k
  schunk->tuner_id = cparams->tuner_id;
130
57.1k
  if (cparams->tuner_id == BLOSC_BTUNE) {
131
0
    cparams->use_dict = 0;
132
0
  }
133
  /* The compression context */
134
57.1k
  if (schunk->cctx != NULL) {
135
0
    blosc2_free_ctx(schunk->cctx);
136
0
  }
137
57.1k
  cparams->schunk = schunk;
138
57.1k
  schunk->cctx = blosc2_create_cctx(*cparams);
139
57.1k
  if (schunk->cctx == NULL) {
140
0
    BLOSC_TRACE_ERROR("Could not create compression ctx");
141
0
    return BLOSC2_ERROR_NULL_POINTER;
142
0
  }
143
144
  /* The decompression context */
145
57.1k
  if (schunk->dctx != NULL) {
146
0
    blosc2_free_ctx(schunk->dctx);
147
0
  }
148
57.1k
  dparams->schunk = schunk;
149
57.1k
  schunk->dctx = blosc2_create_dctx(*dparams);
150
57.1k
  if (schunk->dctx == NULL) {
151
0
    BLOSC_TRACE_ERROR("Could not create decompression ctx");
152
0
    return BLOSC2_ERROR_NULL_POINTER;
153
0
  }
154
155
57.1k
  return BLOSC2_ERROR_SUCCESS;
156
57.1k
}
157
158
159
0
static bool file_exists (char *filename) {
160
0
  struct stat   buffer;
161
0
  return (stat (filename, &buffer) == 0);
162
0
}
163
164
165
/* Create a new super-chunk */
166
57.1k
blosc2_schunk* blosc2_schunk_new(blosc2_storage *storage) {
167
57.1k
  blosc2_schunk* schunk = calloc(1, sizeof(blosc2_schunk));
168
57.1k
  schunk->version = 0;     /* pre-first version */
169
57.1k
  schunk->view = false;  /* not a view by default */
170
171
  // Get the storage with proper defaults
172
57.1k
  schunk->storage = get_new_storage(storage, &BLOSC2_CPARAMS_DEFAULTS, &BLOSC2_DPARAMS_DEFAULTS, &BLOSC2_IO_DEFAULTS);
173
  // Update the (local variable) storage
174
57.1k
  storage = schunk->storage;
175
176
57.1k
  char* tradeoff = getenv("BTUNE_TRADEOFF");
177
57.1k
  if (tradeoff != NULL) {
178
    // If BTUNE_TRADEOFF passed, automatically use btune
179
0
    storage->cparams->tuner_id = BLOSC_BTUNE;
180
0
  }
181
182
  // ...and update internal properties
183
57.1k
  if (update_schunk_properties(schunk) < 0) {
184
0
    BLOSC_TRACE_ERROR("Error when updating schunk properties");
185
0
    blosc2_schunk_free(schunk);
186
0
    return NULL;
187
0
  }
188
189
57.1k
  if (!storage->contiguous && storage->urlpath != NULL){
190
0
    char* urlpath;
191
0
    char last_char = storage->urlpath[strlen(storage->urlpath) - 1];
192
0
    urlpath = malloc(strlen(storage->urlpath) + 1);
193
0
    strcpy(urlpath, storage->urlpath);
194
0
    if (last_char == '\\' || last_char == '/') {
195
0
      urlpath[strlen(storage->urlpath) - 1] = '\0';
196
0
    }
197
    // Create directory
198
0
    if (mkdir(urlpath, 0777) == -1) {
199
0
      BLOSC_TRACE_ERROR("Error during the creation of the directory, maybe it already exists.");
200
0
      free(urlpath);
201
0
      blosc2_schunk_free(schunk);
202
0
      return NULL;
203
0
    }
204
    // We want a sparse (directory) frame as storage
205
0
    blosc2_frame_s* frame = frame_new(urlpath);
206
0
    free(urlpath);
207
0
    if (frame == NULL) {
208
0
      BLOSC_TRACE_ERROR("Error creating sparse frame.");
209
0
      blosc2_schunk_free(schunk);
210
0
      return NULL;
211
0
    }
212
0
    frame->sframe = true;
213
0
    frame_set_locking(frame, schunk->storage->io);
214
    // Initialize frame (basically, encode the header)
215
0
    frame->schunk = schunk;
216
0
    int64_t frame_len = frame_from_schunk(schunk, frame);
217
0
    if (frame_len < 0) {
218
0
      BLOSC_TRACE_ERROR("Error during the conversion of schunk to frame.");
219
0
      frame_free(frame);
220
0
      blosc2_schunk_free(schunk);
221
0
      return NULL;
222
0
    }
223
0
    schunk->frame = (blosc2_frame*)frame;
224
0
  }
225
57.1k
  if (storage->contiguous){
226
    // We want a contiguous frame as storage
227
27.6k
    if (storage->urlpath != NULL) {
228
0
      if (file_exists(storage->urlpath)) {
229
0
        BLOSC_TRACE_ERROR("You are trying to overwrite an existing frame.  Remove it first!");
230
0
        blosc2_schunk_free(schunk);
231
0
        return NULL;
232
0
      }
233
0
    }
234
27.6k
    blosc2_frame_s* frame = frame_new(storage->urlpath);
235
27.6k
    if (frame == NULL) {
236
0
      BLOSC_TRACE_ERROR("Error creating contiguous frame.");
237
0
      blosc2_schunk_free(schunk);
238
0
      return NULL;
239
0
    }
240
27.6k
    frame->sframe = false;
241
27.6k
    frame_set_locking(frame, schunk->storage->io);
242
    // Initialize frame (basically, encode the header)
243
27.6k
    frame->schunk = schunk;
244
27.6k
    int64_t frame_len = frame_from_schunk(schunk, frame);
245
27.6k
    if (frame_len < 0) {
246
0
      BLOSC_TRACE_ERROR("Error during the conversion of schunk to frame.");
247
0
      frame_free(frame);
248
0
      blosc2_schunk_free(schunk);
249
0
      return NULL;
250
0
    }
251
27.6k
    schunk->frame = (blosc2_frame*)frame;
252
27.6k
  }
253
254
57.1k
  return schunk;
255
57.1k
}
256
257
258
/* A new, empty super-chunk with `storage` and the metalayers of `schunk`: the
259
   first part of schunk_copy_impl().  Sets *chunks_as_is to whether the chunks of
260
   `schunk` can go into it as they are (else they have to be recompressed).
261
   `filters_force_recompression` as in schunk_copy_impl(). */
262
static blosc2_schunk* schunk_copy_skeleton(blosc2_schunk *schunk, const blosc2_storage *dest_storage,
263
9.52k
                                           bool filters_force_recompression, bool *chunks_as_is) {
264
  // A copy, so that the defaults below do not end up in the caller's storage: a
265
  // pointer to the local cparams left there would dangle after the return
266
9.52k
  blosc2_storage storage_ = *dest_storage;
267
9.52k
  blosc2_storage *storage = &storage_;
268
  // Check if cparams are equals
269
9.52k
  bool cparams_equal = true;
270
9.52k
  blosc2_cparams cparams = {0};
271
9.52k
  if (storage->cparams == NULL) {
272
    // When cparams are not specified, just use the same of schunk
273
9.52k
    cparams.typesize = schunk->typesize;
274
9.52k
    cparams.clevel = schunk->cctx->clevel;
275
9.52k
    cparams.compcode = schunk->cctx->compcode;
276
9.52k
    cparams.compcode_meta = schunk->cctx->compcode_meta;
277
9.52k
    cparams.splitmode = schunk->cctx->splitmode;
278
9.52k
    cparams.use_dict = schunk->cctx->use_dict;
279
9.52k
    cparams.blocksize = schunk->cctx->blocksize;
280
9.52k
    memcpy(cparams.filters, schunk->cctx->filters, BLOSC2_MAX_FILTERS);
281
9.52k
    memcpy(cparams.filters_meta, schunk->cctx->filters_meta, BLOSC2_MAX_FILTERS);
282
9.52k
    storage->cparams = &cparams;
283
9.52k
  }
284
0
  else {
285
0
    cparams = *storage->cparams;
286
0
  }
287
9.52k
  if (cparams.blocksize == 0) {
288
    // TODO: blocksize should be read from schunk->blocksize
289
    // For this, it should be updated during the first append
290
    // (or change API to make this a property during schunk creation).
291
4.33k
    cparams.blocksize = schunk->cctx->blocksize;
292
4.33k
  }
293
294
9.52k
  if (cparams.typesize != schunk->typesize ||
295
9.52k
      cparams.clevel != schunk->cctx->clevel ||
296
9.52k
      cparams.compcode != schunk->cctx->compcode ||
297
9.52k
      cparams.use_dict != schunk->cctx->use_dict ||
298
9.52k
      cparams.blocksize != schunk->cctx->blocksize ||
299
      // In case of prefilters or postfilters, force their execution.
300
9.52k
      (filters_force_recompression &&
301
0
       (schunk->cctx->prefilter != NULL || schunk->dctx->postfilter != NULL))) {
302
0
    cparams_equal = false;
303
0
  }
304
66.6k
  for (int i = 0; i < BLOSC2_MAX_FILTERS; ++i) {
305
57.1k
    if (cparams.filters[i] != schunk->cctx->filters[i] ||
306
57.1k
        cparams.filters_meta[i] != schunk->cctx->filters_meta[i]) {
307
0
      cparams_equal = false;
308
0
    }
309
57.1k
  }
310
311
  // Create new schunk
312
9.52k
  blosc2_schunk *new_schunk = blosc2_schunk_new(storage);
313
9.52k
  if (new_schunk == NULL) {
314
0
    BLOSC_TRACE_ERROR("Can not create a new schunk");
315
0
    return NULL;
316
0
  }
317
  // Set the chunksize for the schunk, as it cannot be derived from storage
318
9.52k
  new_schunk->chunksize = schunk->chunksize;
319
9.52k
  new_schunk->flags2 = schunk->flags2;
320
321
  // Copy metalayers
322
10.5k
  for (int nmeta = 0; nmeta < schunk->nmetalayers; ++nmeta) {
323
1.07k
    blosc2_metalayer *meta = schunk->metalayers[nmeta];
324
1.07k
    if (blosc2_meta_add(new_schunk, meta->name, meta->content, meta->content_len) < 0) {
325
0
      BLOSC_TRACE_ERROR("Can not add %s `metalayer`.", meta->name);
326
0
      blosc2_schunk_free(new_schunk);
327
0
      return NULL;
328
0
    }
329
1.07k
  }
330
331
9.52k
  *chunks_as_is = cparams_equal || (schunk->flags2 & BLOSC2_VL_BLOCKS) != 0;
332
9.52k
  return new_schunk;
333
9.52k
}
334
335
336
/* See blosc-private.h */
337
9.41k
int schunk_copy_vlmetalayers(blosc2_schunk *schunk, blosc2_schunk *new_schunk, blosc2_cparams *cparams) {
338
9.41k
  for (int nmeta = 0; nmeta < schunk->nvlmetalayers; ++nmeta) {
339
0
    uint8_t *content = NULL;
340
0
    int32_t content_len;
341
0
    char* name = schunk->vlmetalayers[nmeta]->name;
342
0
    if (blosc2_vlmeta_get(schunk, name, &content, &content_len) < 0) {
343
      // Passing the (previously uninitialized) content pointer forward ended
344
      // in a bogus free that aborted the process; bail out instead.
345
0
      BLOSC_TRACE_ERROR("Can not get %s `vlmetalayer`.", name);
346
0
      return BLOSC2_ERROR_FAILURE;
347
0
    }
348
0
    if (blosc2_vlmeta_add(new_schunk, name, content, content_len, cparams) < 0) {
349
0
      BLOSC_TRACE_ERROR("Can not add %s `vlmetalayer`.", name);
350
0
      free(content);
351
0
      return BLOSC2_ERROR_FAILURE;
352
0
    }
353
0
    free(content);
354
0
  }
355
9.41k
  return BLOSC2_ERROR_SUCCESS;
356
9.41k
}
357
358
359
/* A copy of a super-chunk.  With `filters_force_recompression`, a prefilter or
360
   postfilter of `schunk` forces decompressing and recompressing the chunks, so that
361
   the copy holds the data as read.  Without it, the filters force nothing, but chunks
362
   that are recompressed for other reasons (the cparams of `storage` differ from those
363
   of `schunk`) still go through the postfilter; see schunk_copy_as_stored(). */
364
static blosc2_schunk* schunk_copy_impl(blosc2_schunk *schunk, blosc2_storage *storage,
365
9.52k
                                       bool filters_force_recompression) {
366
9.52k
  if (schunk == NULL) {
367
0
    BLOSC_TRACE_ERROR("Can not copy a NULL `schunk`.");
368
0
    return NULL;
369
0
  }
370
9.52k
  bool chunks_as_is;
371
9.52k
  blosc2_schunk *new_schunk = schunk_copy_skeleton(schunk, storage, filters_force_recompression,
372
9.52k
                                                   &chunks_as_is);
373
9.52k
  if (new_schunk == NULL) {
374
0
    return NULL;
375
0
  }
376
377
  // Copy chunks
378
9.52k
  blosc2_frame_s* new_frame = (blosc2_frame_s*)new_schunk->frame;
379
9.52k
  if (chunks_as_is && new_frame != NULL && !new_frame->sframe) {
380
    // A contiguous frame takes all the chunks in one go
381
9.52k
    if (frame_fill_from_schunk(new_frame, new_schunk, schunk) < 0) {
382
110
      BLOSC_TRACE_ERROR("Can not copy the chunks into the new frame.");
383
110
      goto error;
384
110
    }
385
9.52k
  }
386
0
  else if (chunks_as_is) {
387
0
    for (int nchunk = 0; nchunk < schunk->nchunks; ++nchunk) {
388
0
      uint8_t *chunk;
389
0
      bool needs_free;
390
0
      int rc = blosc2_schunk_get_chunk(schunk, nchunk, &chunk, &needs_free);
391
0
      if (rc < 0) {
392
0
        BLOSC_TRACE_ERROR("Can not get the `chunk` %d.", nchunk);
393
0
        goto error;
394
0
      }
395
0
      rc = blosc2_schunk_append_chunk(new_schunk, chunk, !needs_free);
396
0
      if (rc < 0) {
397
0
        BLOSC_TRACE_ERROR("Can not append the `chunk` into super-chunk.");
398
        // A failed append leaves a chunk passed without a copy to us
399
0
        if (needs_free) {
400
0
          free(chunk);
401
0
        }
402
0
        goto error;
403
0
      }
404
0
    }
405
0
  } else {
406
0
    int32_t chunksize = schunk->chunksize == -1 ? 0 : schunk->chunksize;
407
0
    uint8_t *buffer = malloc(chunksize > 0 ? chunksize : 1);
408
0
    if (buffer == NULL) {
409
0
      BLOSC_TRACE_ERROR("Can not allocate memory for decompressing the chunks.");
410
0
      goto error;
411
0
    }
412
0
    for (int nchunk = 0; nchunk < schunk->nchunks; ++nchunk) {
413
      // The last chunk can be shorter
414
0
      int nbytes = blosc2_schunk_decompress_chunk(schunk, nchunk, buffer, chunksize);
415
0
      if (nbytes < 0) {
416
0
        BLOSC_TRACE_ERROR("Can not decompress the `chunk` %d.", nchunk);
417
0
        free(buffer);
418
0
        goto error;
419
0
      }
420
0
      if (blosc2_schunk_append_buffer(new_schunk, buffer, nbytes) < 0) {
421
0
        BLOSC_TRACE_ERROR("Can not append the `buffer` into super-chunk.");
422
0
        free(buffer);
423
0
        goto error;
424
0
      }
425
0
    }
426
0
    free(buffer);
427
0
  }
428
429
9.41k
  if (schunk_copy_vlmetalayers(schunk, new_schunk, NULL) < 0) {
430
0
    goto error;
431
0
  }
432
9.41k
  return new_schunk;
433
434
110
error:
435
110
  blosc2_schunk_free(new_schunk);
436
110
  return NULL;
437
9.41k
}
438
439
440
/* Create a copy of a super-chunk */
441
0
blosc2_schunk* blosc2_schunk_copy(blosc2_schunk *schunk, blosc2_storage *storage) {
442
0
  return schunk_copy_impl(schunk, storage, true);
443
0
}
444
445
446
/* See blosc-private.h */
447
9.52k
blosc2_schunk* schunk_copy_as_stored(blosc2_schunk *schunk, blosc2_storage *storage) {
448
9.52k
  if (storage->cparams != NULL) {
449
0
    BLOSC_TRACE_ERROR("Copying the chunks as stored takes no cparams.");
450
0
    return NULL;
451
0
  }
452
9.52k
  return schunk_copy_impl(schunk, storage, false);
453
9.52k
}
454
455
456
/* Open an existing super-chunk that is on-disk (no copy is made). */
457
0
blosc2_schunk* blosc2_schunk_open_udio(const char* urlpath, const blosc2_io *udio) {
458
0
  return blosc2_schunk_open_offset_udio(urlpath, 0, udio);
459
0
}
460
461
// frame_from_file_offset()'s bootstrap read (path stat + header + trailer)
462
// happens before any lock is taken, so it can race a concurrent writer
463
// growing or rewriting the frame (e.g. a stat() size snapshot made stale by
464
// a header already advertising the writer's new, larger frame length) and
465
// fail outright instead of returning a frame to refresh under lock.  Under
466
// the locking contract such a failure is expected to be transient, so
467
// retry a bounded number of times with a short backoff before giving up;
468
// without locking requested this is the pre-existing single-attempt
469
// behavior (a concurrent writer without locking is already out of the SWMR
470
// contract).  Used for every bootstrap/re-read of the frame header in
471
// blosc2_schunk_open_offset_udio() below -- a compressed-size change on an
472
// in-place update can rewrite the frame layout just like growth does, so
473
// this race is not limited to append/resize.
474
static blosc2_frame_s* frame_from_file_offset_retrying(
475
0
    const char* urlpath, const blosc2_io *udio, int64_t offset, int max_attempts) {
476
0
  blosc2_frame_s* frame = NULL;
477
0
  for (int attempt = 0; attempt < max_attempts; attempt++) {
478
0
    frame = frame_from_file_offset(urlpath, udio, offset);
479
0
    if (frame != NULL || attempt + 1 == max_attempts) {
480
0
      break;
481
0
    }
482
#if defined(_WIN32)
483
    Sleep(1);
484
#else
485
0
    usleep(1000);
486
0
#endif
487
0
  }
488
0
  return frame;
489
0
}
490
491
0
blosc2_schunk* blosc2_schunk_open_offset_udio(const char* urlpath, int64_t offset, const blosc2_io *udio) {
492
0
  if (urlpath == NULL) {
493
0
    BLOSC_TRACE_ERROR("You need to supply a urlpath.");
494
0
    return NULL;
495
0
  }
496
497
0
  bool retry_on_race = frame_locking_requested(udio);
498
0
  const int max_attempts = retry_on_race ? 50 : 1;
499
0
  blosc2_frame_s* frame = frame_from_file_offset_retrying(urlpath, udio, offset, max_attempts);
500
0
  if (frame == NULL) {
501
0
    blosc2_io_cb *io_cb = blosc2_get_io_cb(udio->id);
502
0
    if (io_cb == NULL) {
503
0
        BLOSC_TRACE_ERROR("Error getting the input/output API");
504
0
        return NULL;
505
0
    }
506
0
    int rc = io_cb->destroy(udio->params);
507
0
    if (rc < 0) {
508
0
      BLOSC_TRACE_ERROR("Cannot destroy the input/output object.");
509
0
    }
510
0
    return NULL;
511
0
  }
512
  // Guard the initial read of the frame against concurrent writers
513
0
  if (frame_lock(frame, false) < 0) {
514
0
    frame_free(frame);
515
0
    return NULL;
516
0
  }
517
0
  if (frame->force_refresh) {
518
    // The bootstrap read in frame_from_file_offset() happened before the lock
519
    // acquisition above, so a writer may have mutated the frame in between
520
    // (the generation counter cannot tell a first acquisition from a raced
521
    // one, so this also triggers on every open of a previously-mutated frame;
522
    // one extra header read at open time is a fair price).  Re-read the frame
523
    // now, taking the fresh handle's own shared lock *before* releasing the
524
    // current one so that no writer can interleave.  Same transient race as
525
    // the bootstrap read above, so the same bounded retry applies.
526
0
    blosc2_frame_s* fresh = frame_from_file_offset_retrying(urlpath, udio, offset, max_attempts);
527
0
    int lock_rc = (fresh == NULL) ? BLOSC2_ERROR_FILE_READ : frame_lock(fresh, false);
528
0
    frame_free(frame);  // closing its lock fd releases the old shared lock
529
0
    if (fresh == NULL) {
530
0
      return NULL;
531
0
    }
532
0
    if (lock_rc < 0) {
533
0
      frame_free(fresh);
534
0
      return NULL;
535
0
    }
536
    // The re-read ran under a continuously-held shared lock, so it is
537
    // current: the seq mismatch of a first acquisition is not a mutation
538
0
    fresh->force_refresh = false;
539
0
    frame = fresh;
540
0
  }
541
0
  blosc2_schunk* schunk = frame_to_schunk(frame, false, udio);
542
0
  if (schunk == NULL) {
543
0
    BLOSC_TRACE_ERROR("Error converting frame to super-chunk");
544
    // frame_to_schunk() has already freed the frame on failure; closing its
545
    // lock fd released the OS lock, so no frame_unlock() here
546
0
    return NULL;
547
0
  }
548
0
  frame_unlock(frame);
549
550
  // Set the storage with proper defaults
551
0
  size_t pathlen = strlen(urlpath);
552
0
  schunk->storage->urlpath = malloc(pathlen + 1);
553
0
  strcpy(schunk->storage->urlpath, urlpath);
554
0
  schunk->storage->contiguous = !frame->sframe;
555
556
0
  return schunk;
557
0
}
558
559
0
blosc2_schunk* blosc2_schunk_open(const char* urlpath) {
560
0
  return blosc2_schunk_open_udio(urlpath, &BLOSC2_IO_DEFAULTS);
561
0
}
562
563
0
blosc2_schunk* blosc2_schunk_open_offset(const char* urlpath, int64_t offset) {
564
0
  return blosc2_schunk_open_offset_udio(urlpath, offset, &BLOSC2_IO_DEFAULTS);
565
0
}
566
567
18.3k
int64_t blosc2_schunk_to_buffer(blosc2_schunk* schunk, uint8_t** dest, bool* needs_free) {
568
18.3k
  blosc2_frame_s* frame;
569
18.3k
  int64_t cframe_len;
570
571
  // Initialize defaults in case of errors
572
18.3k
  *dest = NULL;
573
18.3k
  *needs_free = false;
574
575
18.3k
  if ((schunk->storage->contiguous == true) && (schunk->storage->urlpath == NULL)) {
576
8.84k
    frame =  (blosc2_frame_s*)(schunk->frame);
577
8.84k
    *dest = frame->cframe;
578
8.84k
    cframe_len = frame->len;
579
8.84k
    *needs_free = false;
580
8.84k
  }
581
9.52k
  else {
582
    // Copy to a contiguous storage
583
9.52k
    blosc2_storage frame_storage = {.contiguous=true};
584
9.52k
    blosc2_schunk* schunk_copy = schunk_copy_as_stored(schunk, &frame_storage);
585
9.52k
    if (schunk_copy == NULL) {
586
110
      BLOSC_TRACE_ERROR("Error during the conversion of schunk to buffer.");
587
110
      return BLOSC2_ERROR_SCHUNK_COPY;
588
110
    }
589
9.41k
    frame = (blosc2_frame_s*)(schunk_copy->frame);
590
9.41k
    *dest = frame->cframe;
591
9.41k
    cframe_len = frame->len;
592
9.41k
    *needs_free = true;
593
9.41k
    frame->avoid_cframe_free = true;
594
9.41k
    blosc2_schunk_free(schunk_copy);
595
9.41k
  }
596
597
18.2k
  return cframe_len;
598
599
18.3k
}
600
601
602
/* Convert a super-chunk into a contiguous frame in a buffer from the caller. */
603
int64_t blosc2_schunk_to_buffer_alloc(blosc2_schunk* schunk,
604
0
                                      uint8_t* (*alloc)(int64_t len, void* user_data), void* user_data) {
605
0
  if (schunk == NULL || alloc == NULL) {
606
0
    BLOSC_TRACE_ERROR("schunk and alloc cannot be NULL.");
607
0
    return BLOSC2_ERROR_NULL_POINTER;
608
0
  }
609
0
  if (schunk->frame == NULL || schunk->storage->urlpath != NULL) {
610
    // Anything but an in-memory frame: write the frame that blosc2_schunk_to_buffer()
611
    // would build straight into the destination
612
0
    blosc2_storage frame_storage = BLOSC2_STORAGE_DEFAULTS;
613
0
    frame_storage.contiguous = true;
614
0
    bool chunks_as_is;
615
0
    blosc2_schunk* skeleton = schunk_copy_skeleton(schunk, &frame_storage, false, &chunks_as_is);
616
0
    if (skeleton == NULL) {
617
0
      BLOSC_TRACE_ERROR("Error during the conversion of schunk to buffer.");
618
0
      return BLOSC2_ERROR_SCHUNK_COPY;
619
0
    }
620
0
    if (chunks_as_is) {
621
      // With no chunks yet, adding the vlmetalayers first gives the same frame
622
0
      int64_t len = schunk_copy_vlmetalayers(schunk, skeleton, NULL);
623
0
      if (len >= 0) {
624
0
        len = frame_fill_alloc((blosc2_frame_s*)skeleton->frame, skeleton, schunk, alloc, user_data);
625
0
      }
626
0
      blosc2_schunk_free(skeleton);
627
0
      return len;
628
0
    }
629
0
    blosc2_schunk_free(skeleton);
630
0
  }
631
632
0
  uint8_t* cframe;
633
0
  bool needs_free;
634
0
  int64_t len = blosc2_schunk_to_buffer(schunk, &cframe, &needs_free);
635
0
  if (len < 0) {
636
0
    return len;
637
0
  }
638
0
  uint8_t* dest = alloc(len, user_data);
639
0
  if (dest == NULL) {
640
0
    BLOSC_TRACE_ERROR("Cannot get a buffer for the frame.");
641
0
    len = BLOSC2_ERROR_MEMORY_ALLOC;
642
0
  }
643
0
  else {
644
0
    memcpy(dest, cframe, (size_t)len);
645
0
  }
646
0
  if (needs_free) {
647
0
    free(cframe);
648
0
  }
649
0
  return len;
650
0
}
651
652
653
/* Write an in-memory frame out to a file. */
654
0
int64_t frame_to_file(blosc2_frame_s* frame, const char* urlpath) {
655
0
  blosc2_io_cb *io_cb = blosc2_get_io_cb(frame->schunk->storage->io->id);
656
0
  if (io_cb == NULL) {
657
0
    BLOSC_TRACE_ERROR("Error getting the input/output API");
658
0
    return BLOSC2_ERROR_PLUGIN_IO;
659
0
  }
660
0
  void* fp = io_cb->open(urlpath, "wb", frame->schunk->storage->io->params);
661
0
  if (fp == NULL) {
662
0
    BLOSC_TRACE_ERROR("Cannot open %s for writing.", urlpath);
663
0
    return BLOSC2_ERROR_FILE_OPEN;
664
0
  }
665
0
  int64_t io_pos = 0;
666
0
  int64_t nitems = io_cb->write(frame->cframe, frame->len, 1, io_pos, fp);
667
0
  int close_rc = io_cb->close(fp);
668
0
  if (nitems != 1 || close_rc != 0) {
669
0
    BLOSC_TRACE_ERROR("Cannot write the frame to %s.", urlpath);
670
0
    return BLOSC2_ERROR_FILE_WRITE;
671
0
  }
672
0
  return nitems * frame->len;
673
0
}
674
675
676
/* Append an in-memory frame to a file. */
677
0
int64_t append_frame_to_file(blosc2_frame_s* frame, const char* urlpath) {
678
0
    blosc2_io_cb *io_cb = blosc2_get_io_cb(frame->schunk->storage->io->id);
679
0
    if (io_cb == NULL) {
680
0
        BLOSC_TRACE_ERROR("Error getting the input/output API");
681
0
        return BLOSC2_ERROR_PLUGIN_IO;
682
0
    }
683
    /* "rb+" rather than "ab": the write below passes an explicit position, and
684
       POSIX ignores it on an O_APPEND descriptor (every write lands at EOF)
685
       while Windows honours it.  Without O_APPEND the position means the same
686
       thing on both.  "rb+" will not create, so create the file first when it
687
       is not there yet -- which is what "ab" used to cover.  Creating with "ab"
688
       rather than "wb+": should the "rb+" below have failed for some reason
689
       other than a missing file, "ab" leaves its contents alone where "wb+"
690
       would truncate them away.
691
692
       Note this gives up O_APPEND's atomic land-at-EOF: two processes appending
693
       to the same file concurrently can now write at the same offset.  They
694
       could not use the result before either -- the offset returned here comes
695
       from a size() that the other process invalidates just the same -- and
696
       Windows never had the atomicity to begin with, since it honours the
697
       explicit position even on an append handle. */
698
0
    void* fp = io_cb->open(urlpath, "rb+", frame->schunk->storage->io->params);
699
0
    if (fp == NULL) {
700
0
        fp = io_cb->open(urlpath, "ab", frame->schunk->storage->io->params);
701
0
        if (fp != NULL) {
702
0
            io_cb->close(fp);
703
0
            fp = io_cb->open(urlpath, "rb+", frame->schunk->storage->io->params);
704
0
        }
705
0
    }
706
0
    if (fp == NULL) {
707
0
        BLOSC_TRACE_ERROR("Cannot open %s for appending.", urlpath);
708
0
        return BLOSC2_ERROR_FILE_OPEN;
709
0
    }
710
711
0
    int64_t io_pos = io_cb->size(fp);
712
0
    if (io_pos < 0) {
713
0
        io_cb->close(fp);
714
0
        BLOSC_TRACE_ERROR("Cannot determine the size of %s.", urlpath);
715
0
        return BLOSC2_ERROR_FILE_READ;
716
0
    }
717
0
    int64_t nitems = io_cb->write(frame->cframe, frame->len, 1, io_pos, fp);
718
0
    int close_rc = io_cb->close(fp);
719
0
    if (nitems != 1 || close_rc != 0) {
720
0
        BLOSC_TRACE_ERROR("Cannot append the frame to %s.", urlpath);
721
0
        return BLOSC2_ERROR_FILE_WRITE;
722
0
    }
723
0
    return io_pos;
724
0
}
725
726
727
/* Write super-chunk out to a file. */
728
0
int64_t blosc2_schunk_to_file(blosc2_schunk* schunk, const char* urlpath) {
729
0
  if (urlpath == NULL) {
730
0
    BLOSC_TRACE_ERROR("urlpath cannot be NULL");
731
0
    return BLOSC2_ERROR_INVALID_PARAM;
732
0
  }
733
734
  // Accelerated path for in-memory frames
735
0
  if (schunk->storage->contiguous && schunk->storage->urlpath == NULL) {
736
0
    int64_t len = frame_to_file((blosc2_frame_s*)(schunk->frame), urlpath);
737
0
    if (len <= 0) {
738
0
      BLOSC_TRACE_ERROR("Error writing to file");
739
0
      return len;
740
0
    }
741
0
    return len;
742
0
  }
743
744
  // Copy to a contiguous file
745
0
  blosc2_storage frame_storage = {.contiguous=true, .urlpath=(char*)urlpath};
746
0
  blosc2_schunk* schunk_copy = schunk_copy_as_stored(schunk, &frame_storage);
747
0
  if (schunk_copy == NULL) {
748
0
    BLOSC_TRACE_ERROR("Error during the conversion of schunk to buffer.");
749
0
    return BLOSC2_ERROR_SCHUNK_COPY;
750
0
  }
751
0
  blosc2_frame_s* frame = (blosc2_frame_s*)(schunk_copy->frame);
752
0
  int64_t frame_len = frame->len;
753
0
  blosc2_schunk_free(schunk_copy);
754
0
  return frame_len;
755
0
}
756
757
758
/* Append a super-chunk to a file. */
759
0
int64_t blosc2_schunk_append_file(blosc2_schunk* schunk, const char* urlpath) {
760
0
    if (urlpath == NULL) {
761
0
        BLOSC_TRACE_ERROR("urlpath cannot be NULL");
762
0
        return BLOSC2_ERROR_INVALID_PARAM;
763
0
    }
764
765
    // Accelerated path for in-memory frames
766
0
    if (schunk->storage->contiguous && schunk->storage->urlpath == NULL) {
767
0
        int64_t offset = append_frame_to_file((blosc2_frame_s*)(schunk->frame), urlpath);
768
0
        if (offset <= 0) {
769
0
            BLOSC_TRACE_ERROR("Error writing to file");
770
0
            return offset;
771
0
        }
772
0
        return offset;
773
0
    }
774
775
    // Copy to a contiguous file
776
0
    blosc2_storage frame_storage = {.contiguous=true, .urlpath=NULL};
777
0
    blosc2_schunk* schunk_copy = schunk_copy_as_stored(schunk, &frame_storage);
778
0
    if (schunk_copy == NULL) {
779
0
        BLOSC_TRACE_ERROR("Error during the conversion of schunk to buffer.");
780
0
        return BLOSC2_ERROR_SCHUNK_COPY;
781
0
    }
782
0
    blosc2_frame_s* frame = (blosc2_frame_s*)(schunk_copy->frame);
783
0
    int64_t offset = append_frame_to_file(frame, urlpath);
784
0
    blosc2_schunk_free(schunk_copy);
785
0
    return offset;
786
0
}
787
788
789
/* Free all memory from a super-chunk. */
790
69.4k
void schunk_free_metalayers(blosc2_schunk *schunk) {
791
86.6k
  for (int i = 0; i < schunk->nmetalayers; i++) {
792
17.1k
    if (schunk->metalayers[i] != NULL) {
793
16.7k
      free(schunk->metalayers[i]->name);
794
16.7k
      free(schunk->metalayers[i]->content);
795
16.7k
      free(schunk->metalayers[i]);
796
16.7k
      schunk->metalayers[i] = NULL;
797
16.7k
    }
798
17.1k
  }
799
69.4k
  schunk->nmetalayers = 0;
800
69.4k
}
801
802
803
69.4k
void schunk_free_vlmetalayers(blosc2_schunk *schunk) {
804
116k
  for (int i = 0; i < schunk->nvlmetalayers; i++) {
805
47.2k
    if (schunk->vlmetalayers[i] != NULL) {
806
669
      free(schunk->vlmetalayers[i]->name);
807
669
      free(schunk->vlmetalayers[i]->content);
808
669
      free(schunk->vlmetalayers[i]);
809
669
      schunk->vlmetalayers[i] = NULL;
810
669
    }
811
47.2k
  }
812
69.4k
  schunk->nvlmetalayers = 0;
813
69.4k
}
814
815
816
69.4k
int blosc2_schunk_free(blosc2_schunk *schunk) {
817
69.4k
  int err = 0;
818
819
  // If it is a view, the data belongs to original array and should not be freed
820
69.4k
  if (schunk->data != NULL && !schunk->view) {
821
252k
    for (int i = 0; i < schunk->nchunks; i++) {
822
226k
      free(schunk->data[i]);
823
226k
    }
824
25.1k
    free(schunk->data);
825
25.1k
  }
826
69.4k
  if (schunk->cctx != NULL)
827
68.9k
    blosc2_free_ctx(schunk->cctx);
828
69.4k
  if (schunk->dctx != NULL)
829
68.9k
    blosc2_free_ctx(schunk->dctx);
830
69.4k
  if (schunk->blockshape != NULL)
831
353
    free(schunk->blockshape);
832
833
69.4k
  schunk_free_metalayers(schunk);
834
835
69.4k
  if (schunk->storage != NULL) {
836
68.9k
    blosc2_io_cb *io_cb = blosc2_get_io_cb(schunk->storage->io->id);
837
68.9k
    if (io_cb != NULL) {
838
68.9k
      int rc = io_cb->destroy(schunk->storage->io->params);
839
68.9k
      if (rc < 0) {
840
0
        BLOSC_TRACE_ERROR("Could not free the I/O resources.");
841
0
        err = 1;
842
0
      }
843
68.9k
    }
844
845
68.9k
    if (schunk->storage->urlpath != NULL) {
846
0
      free(schunk->storage->urlpath);
847
0
    }
848
68.9k
    free(schunk->storage->cparams);
849
68.9k
    free(schunk->storage->dparams);
850
68.9k
    free(schunk->storage->io);
851
68.9k
    free(schunk->storage);
852
68.9k
  }
853
854
  // If it is a view, the frame belongs to original array and should not be freed
855
69.4k
  if (schunk->frame != NULL && !schunk->view) {
856
39.9k
    int rc = frame_free((blosc2_frame_s *) schunk->frame);
857
39.9k
    if (rc < 0 && err == 0) {
858
0
      err = rc;
859
0
    }
860
39.9k
  }
861
862
69.4k
  schunk_free_vlmetalayers(schunk);
863
864
69.4k
  free(schunk);
865
866
69.4k
  return err;
867
69.4k
}
868
869
870
0
int blosc2_schunk_flush(blosc2_schunk *schunk) {
871
0
  BLOSC_ERROR_NULL(schunk, BLOSC2_ERROR_NULL_POINTER);
872
0
  if (schunk->view || schunk->frame == NULL) {
873
0
    return BLOSC2_ERROR_SUCCESS;
874
0
  }
875
0
  return frame_flush((blosc2_frame_s *) schunk->frame);
876
0
}
877
878
879
/* Create a super-chunk out of a contiguous frame buffer */
880
12.4k
blosc2_schunk* blosc2_schunk_from_buffer(uint8_t *cframe, int64_t len, bool copy) {
881
  // Check that the buffer actually comes from a cframe
882
12.4k
  if (cframe == NULL || len < FRAME_HEADER_MINLEN) {
883
3
    return NULL;
884
3
  }
885
12.4k
  char *magic_number = (char *)cframe + FRAME_HEADER_MAGIC;
886
12.4k
  if (memcmp(magic_number, "b2frame", sizeof("b2frame")) != 0) {
887
73
    return NULL;
888
73
  }
889
12.3k
  blosc2_frame_s* frame = frame_from_cframe(cframe, len, false);
890
12.3k
  if (frame == NULL) {
891
41
    return NULL;
892
41
  }
893
12.3k
  blosc2_schunk* schunk = frame_to_schunk(frame, copy, &BLOSC2_IO_DEFAULTS);
894
12.3k
  if (schunk && copy) {
895
    // Super-chunk has its own copy of frame
896
0
    frame_free(frame);
897
0
  }
898
12.3k
  return schunk;
899
12.3k
}
900
901
902
/* Set whether freeing this super-chunk should avoid freeing its contiguous frame buffer */
903
0
void blosc2_schunk_avoid_cframe_free(blosc2_schunk *schunk, bool avoid_cframe_free) {
904
0
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
905
0
  if (frame) {
906
0
    frame_avoid_cframe_free(frame, avoid_cframe_free);
907
0
  }
908
0
}
909
910
911
/* Hold the exclusive frame lock across several operations: the operations
912
   between blosc2_schunk_lock() and blosc2_schunk_unlock() nest on the
913
   already-held lock (via the frame's lock depth counter) instead of
914
   re-acquiring it, so the whole bracket is atomic against other handles.
915
   No-ops (success) when locking is not enabled on the handle. */
916
0
int blosc2_schunk_lock(blosc2_schunk *schunk) {
917
0
  return frame_lock((blosc2_frame_s*)schunk->frame, true);
918
0
}
919
920
921
0
int blosc2_schunk_unlock(blosc2_schunk *schunk) {
922
0
  return frame_unlock((blosc2_frame_s*)schunk->frame);
923
0
}
924
925
926
0
int blosc2_schunk_begin_updates(blosc2_schunk *schunk) {
927
0
  BLOSC_ERROR_NULL(schunk, BLOSC2_ERROR_NULL_POINTER);
928
0
  return frame_begin_updates((blosc2_frame_s*)schunk->frame);
929
0
}
930
931
932
0
int blosc2_schunk_end_updates(blosc2_schunk *schunk) {
933
0
  BLOSC_ERROR_NULL(schunk, BLOSC2_ERROR_NULL_POINTER);
934
0
  return frame_end_updates((blosc2_frame_s*)schunk->frame, schunk);
935
0
}
936
937
938
/* Re-sync the cached counters (nchunks, nbytes, cbytes) and metalayers of a
939
   disk-based super-chunk when another handle changed it behind our back.
940
   A no-op for in-memory super-chunks. */
941
0
int blosc2_schunk_refresh(blosc2_schunk *schunk) {
942
0
  if (schunk == NULL) {
943
0
    return BLOSC2_ERROR_NULL_POINTER;
944
0
  }
945
0
  if (schunk->frame == NULL) {
946
0
    return 0;
947
0
  }
948
0
  return frame_check_stale((blosc2_frame_s *) schunk->frame);
949
0
}
950
951
952
/* Fill an empty frame with special values (fast path). */
953
int64_t blosc2_schunk_fill_special(blosc2_schunk* schunk, int64_t nitems, int special_value,
954
6.15k
                               int32_t chunksize) {
955
6.15k
  if (nitems == 0) {
956
0
    return 0;
957
0
  }
958
959
6.15k
  int32_t typesize = schunk->typesize;
960
6.15k
  if (nitems < 0 || chunksize <= 0 || typesize <= 0) {
961
0
    BLOSC_TRACE_ERROR("Invalid special fill parameters.");
962
0
    return BLOSC2_ERROR_INVALID_PARAM;
963
0
  }
964
965
6.15k
  if ((schunk->nbytes > 0) || (schunk->cbytes > 0)) {
966
0
    BLOSC_TRACE_ERROR("Filling with special values only works on empty super-chunks");
967
0
    return BLOSC2_ERROR_FRAME_SPECIAL;
968
0
  }
969
970
  // Compute the number of chunks and the length of the offsets chunk
971
6.15k
  int32_t chunkitems = chunksize / typesize;
972
6.15k
  if (chunkitems <= 0) {
973
0
    BLOSC_TRACE_ERROR("chunksize must be >= typesize for special fill.");
974
0
    return BLOSC2_ERROR_INVALID_PARAM;
975
0
  }
976
6.15k
  int64_t nchunks = nitems / chunkitems;
977
6.15k
  if (nchunks > INT_MAX) {
978
0
    BLOSC_TRACE_ERROR("nitems is too large.  Try increasing the chunksize.");
979
0
    return BLOSC2_ERROR_SCHUNK_SPECIAL;
980
0
  }
981
6.15k
  if (!blosc2_checked_mul_i64_nonneg(nitems, typesize, NULL)) {
982
0
    BLOSC_TRACE_ERROR("nitems is too large for nbytes accounting.");
983
0
    return BLOSC2_ERROR_SCHUNK_SPECIAL;
984
0
  }
985
6.15k
  int32_t leftover_items = (int32_t)(nitems % chunkitems);
986
987
6.15k
  if (schunk->frame == NULL) {
988
    // Build the special chunks
989
4.23k
    int32_t leftover_size = leftover_items * typesize;
990
4.23k
    void* chunk = malloc(BLOSC_EXTENDED_HEADER_LENGTH);
991
4.23k
    void* chunk2 = malloc(BLOSC_EXTENDED_HEADER_LENGTH);
992
4.23k
    blosc2_cparams* cparams;
993
4.23k
    blosc2_schunk_get_cparams(schunk, &cparams);
994
4.23k
    int csize, csize2;
995
4.23k
    switch (special_value) {
996
4.23k
      case BLOSC2_SPECIAL_ZERO:
997
4.23k
        csize = blosc2_chunk_zeros(*cparams, chunksize, chunk, BLOSC_EXTENDED_HEADER_LENGTH);
998
4.23k
        csize2 = blosc2_chunk_zeros(*cparams, leftover_size, chunk2, BLOSC_EXTENDED_HEADER_LENGTH);
999
4.23k
        break;
1000
0
      case BLOSC2_SPECIAL_UNINIT:
1001
0
        csize = blosc2_chunk_uninit(*cparams, chunksize, chunk, BLOSC_EXTENDED_HEADER_LENGTH);
1002
0
        csize2 = blosc2_chunk_uninit(*cparams, leftover_size, chunk2, BLOSC_EXTENDED_HEADER_LENGTH);
1003
0
        break;
1004
0
      case BLOSC2_SPECIAL_NAN:
1005
0
        csize = blosc2_chunk_nans(*cparams, chunksize, chunk, BLOSC_EXTENDED_HEADER_LENGTH);
1006
0
        csize2 = blosc2_chunk_nans(*cparams, leftover_size, chunk2, BLOSC_EXTENDED_HEADER_LENGTH);
1007
0
        break;
1008
0
      default:
1009
0
        BLOSC_TRACE_ERROR("Only zeros, NaNs or non-initialized values are supported.");
1010
0
        return BLOSC2_ERROR_SCHUNK_SPECIAL;
1011
4.23k
    }
1012
4.23k
    free(cparams);
1013
4.23k
    if (csize < 0 || csize2 < 0) {
1014
0
      BLOSC_TRACE_ERROR("Error creating special chunks.");
1015
0
      return BLOSC2_ERROR_SCHUNK_SPECIAL;
1016
0
    }
1017
1018
1.55M
    for (int nchunk = 0; nchunk < nchunks; nchunk++) {
1019
1.55M
      int64_t nchunk_ = blosc2_schunk_append_chunk(schunk, chunk, true);
1020
1.55M
      if (nchunk_ != nchunk + 1) {
1021
0
        BLOSC_TRACE_ERROR("Error appending special chunks.");
1022
0
        return BLOSC2_ERROR_SCHUNK_SPECIAL;
1023
0
      }
1024
1.55M
    }
1025
1026
4.23k
    if (leftover_items) {
1027
0
      int64_t nchunk_ = blosc2_schunk_append_chunk(schunk, chunk2, true);
1028
0
      if (nchunk_ != nchunks + 1) {
1029
0
        BLOSC_TRACE_ERROR("Error appending last special chunk.");
1030
0
        return BLOSC2_ERROR_SCHUNK_SPECIAL;
1031
0
      }
1032
0
    }
1033
4.23k
    free(chunk);
1034
4.23k
    free(chunk2);
1035
4.23k
  }
1036
1.91k
  else {
1037
    /* Fill an empty frame with special values (fast path). */
1038
1.91k
    blosc2_frame_s *frame = (blosc2_frame_s *) schunk->frame;
1039
1.91k
    int64_t total_chunks = nchunks + (leftover_items ? 1 : 0);
1040
1.91k
    if (!blosc2_nchunks_to_offsets_nbytes(total_chunks, NULL)) {
1041
0
      BLOSC_TRACE_ERROR("Too many chunks for frame offsets representation.");
1042
0
      return BLOSC2_ERROR_FRAME_SPECIAL;
1043
0
    }
1044
1045
1.91k
    int64_t old_nchunks = schunk->nchunks;
1046
1.91k
    int64_t old_nbytes = schunk->nbytes;
1047
1.91k
    int32_t old_chunksize = schunk->chunksize;
1048
1049
    /* Update counters (necessary for the frame_fill_special() logic) */
1050
1.91k
    if (leftover_items) {
1051
0
      nchunks += 1;
1052
0
    }
1053
1.91k
    schunk->chunksize = chunksize;
1054
1.91k
    schunk->nchunks = nchunks;
1055
1.91k
    schunk->nbytes = nitems * typesize;
1056
1.91k
    int rc = frame_lock(frame, true);
1057
1.91k
    if (rc < 0) {
1058
0
      schunk->chunksize = old_chunksize;
1059
0
      schunk->nchunks = old_nchunks;
1060
0
      schunk->nbytes = old_nbytes;
1061
0
      return rc;
1062
0
    }
1063
1.91k
    int64_t frame_len = frame_fill_special(frame, nitems, special_value, chunksize, schunk);
1064
1.91k
    frame_unlock(frame);
1065
1.91k
    if (frame_len < 0) {
1066
0
      schunk->chunksize = old_chunksize;
1067
0
      schunk->nchunks = old_nchunks;
1068
0
      schunk->nbytes = old_nbytes;
1069
0
      BLOSC_TRACE_ERROR("Error creating special frame.");
1070
0
      return frame_len;
1071
0
    }
1072
1.91k
  }
1073
1074
6.15k
  return schunk->nchunks;
1075
6.15k
}
1076
1077
/* The header of chunk `nchunk` of `schunk` in *chunk: the chunk itself, NULL for a
1078
   missing one, or for a frame a copy in `header` (BLOSC_EXTENDED_HEADER_LENGTH
1079
   bytes), so an on-disk frame does not read the whole chunk.  Returns the cbytes
1080
   of the chunk (0 for a missing one), or a negative value on error. */
1081
static int schunk_get_chunk_header(blosc2_schunk *schunk, int64_t nchunk, uint8_t *header,
1082
5.85M
                                   const uint8_t **chunk) {
1083
5.85M
  if (schunk->frame != NULL) {
1084
2.34M
    *chunk = header;
1085
2.34M
    return frame_get_chunk_header((blosc2_frame_s *)schunk->frame, nchunk, header);
1086
2.34M
  }
1087
3.50M
  *chunk = schunk->data[nchunk];
1088
3.50M
  if (*chunk == NULL) {
1089
0
    return 0;
1090
0
  }
1091
3.50M
  int32_t chunk_cbytes;
1092
3.50M
  int rc = blosc2_cbuffer_sizes(*chunk, NULL, &chunk_cbytes, NULL);
1093
3.50M
  return rc < 0 ? rc : chunk_cbytes;
1094
3.50M
}
1095
1096
2.29M
static int schunk_get_chunk_nbytes(blosc2_schunk *schunk, int64_t nchunk, int32_t *chunk_nbytes) {
1097
2.29M
  uint8_t header[BLOSC_EXTENDED_HEADER_LENGTH];
1098
2.29M
  const uint8_t *chunk;
1099
2.29M
  int rc = schunk_get_chunk_header(schunk, nchunk, header, &chunk);
1100
2.29M
  if (rc < 0) {
1101
434
    return rc;
1102
434
  }
1103
2.29M
  if (chunk == NULL) {
1104
0
    return BLOSC2_ERROR_DATA;
1105
0
  }
1106
2.29M
  return blosc2_cbuffer_sizes(chunk, chunk_nbytes, NULL, NULL);
1107
2.29M
}
1108
1109
2.93M
static int schunk_get_chunk_flags2(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk_flags2) {
1110
2.93M
  uint8_t header[BLOSC_EXTENDED_HEADER_LENGTH];
1111
2.93M
  const uint8_t *chunk;
1112
2.93M
  int rc = schunk_get_chunk_header(schunk, nchunk, header, &chunk);
1113
2.93M
  if (rc < 0) {
1114
2.53k
    return rc;
1115
2.53k
  }
1116
2.93M
  if (chunk == NULL) {
1117
0
    return BLOSC2_ERROR_DATA;
1118
0
  }
1119
2.93M
  *chunk_flags2 = get_chunk_flags2(chunk, rc);
1120
2.93M
  return 0;
1121
2.93M
}
1122
1123
/* The nbytes and cbytes of chunk `nchunk` that the counters of `schunk` hold:
1124
   none for a missing chunk, no cbytes for a chunk made of its header only. */
1125
static int schunk_get_counted_sizes(blosc2_schunk *schunk, int64_t nchunk, int32_t *chunk_nbytes,
1126
628k
                                    int32_t *chunk_cbytes) {
1127
628k
  *chunk_nbytes = 0;
1128
628k
  *chunk_cbytes = 0;
1129
628k
  uint8_t header[BLOSC_EXTENDED_HEADER_LENGTH];
1130
628k
  const uint8_t *chunk;
1131
628k
  int rc = schunk_get_chunk_header(schunk, nchunk, header, &chunk);
1132
628k
  if (rc < 0 || chunk == NULL) {
1133
817
    return rc;
1134
817
  }
1135
627k
  rc = blosc2_cbuffer_sizes(chunk, chunk_nbytes, chunk_cbytes, NULL);
1136
627k
  if (rc < 0) {
1137
0
    return rc;
1138
0
  }
1139
627k
  if (*chunk_cbytes == BLOSC2_MAX_OVERHEAD) {
1140
599k
    *chunk_cbytes = 0;
1141
599k
  }
1142
627k
  return BLOSC2_ERROR_SUCCESS;
1143
627k
}
1144
1145
1146
/* How a chunk write hands over its chunk */
1147
typedef enum {
1148
  CHUNK_GIVEN,   // copy=false: the super-chunk owns the chunk after a successful write
1149
  CHUNK_COPIED,  // copy=true: the caller keeps the chunk
1150
  CHUNK_LENT,    // the caller keeps the chunk, which is private memory (see schunk_update_chunk_lent())
1151
} chunk_handover;
1152
1153
1154
/* Whether a write of a chunk handed over as `how` into `frame` (NULL for a plain super-chunk)
1155
   needs a private copy of it.  A plain super-chunk keeps the chunk itself.  A frame stores its
1156
   own copy, but a chunk that the caller keeps may point into storage that the write moves
1157
   (realloc, mremap) or overwrites (the tail that an update shifts): of this frame, or of
1158
   another handle (or process) that maps the same file.  Only a lent chunk is known not to. */
1159
2.97M
static bool chunk_needs_private_copy(const blosc2_frame_s *frame, chunk_handover how) {
1160
2.97M
  return how == CHUNK_COPIED || (how == CHUNK_LENT && frame == NULL);
1161
2.97M
}
1162
1163
1164
/* Free what a write of `chunk` (handed over as `how`, maybe a private copy) into a frame leaves
1165
   to the schunk layer: the frame stores its own copy of the chunk, so a private copy goes in any
1166
   case, and a given chunk once `written`; a failed write leaves any other chunk to the caller. */
1167
1.19M
static void frame_write_done(uint8_t *chunk, chunk_handover how, bool private_copy, bool written) {
1168
1.19M
  if (private_copy || (written && how == CHUNK_GIVEN)) {
1169
545k
    free(chunk);
1170
545k
  }
1171
1.19M
}
1172
1173
1174
/* Append an existing chunk into a super-chunk. */
1175
1.82M
static int64_t schunk_append_chunk_unlocked(blosc2_schunk *schunk, uint8_t *chunk, chunk_handover how) {
1176
1.82M
  int32_t chunk_nbytes;
1177
1.82M
  int32_t chunk_cbytes;
1178
1.82M
  int64_t nchunks = schunk->nchunks;
1179
1180
1.82M
  int rc = blosc2_cbuffer_sizes(chunk, &chunk_nbytes, &chunk_cbytes, NULL);
1181
1.82M
  if (rc < 0) {
1182
0
    return rc;
1183
0
  }
1184
  // Saved, so that the super-chunk is left unchanged if appending to the frame fails
1185
1.82M
  uint8_t old_flags2 = schunk->flags2;
1186
1.82M
  int32_t old_chunksize = schunk->chunksize;
1187
1.82M
  int64_t old_current_nchunk = schunk->current_nchunk;
1188
1.82M
  int64_t old_nbytes = schunk->nbytes;
1189
1.82M
  int64_t old_cbytes = schunk->cbytes;
1190
1191
1.82M
  uint8_t flags2 = get_chunk_flags2(chunk, chunk_cbytes);
1192
1.82M
  bool chunk_vlblocks = (flags2 & BLOSC2_VL_BLOCKS) != 0;
1193
1.82M
  if (nchunks > 0) {
1194
1.78M
    uint8_t first_flags2;
1195
1.78M
    rc = schunk_get_chunk_flags2(schunk, 0, &first_flags2);
1196
1.78M
    if (rc < 0) {
1197
2.48k
      return rc;
1198
2.48k
    }
1199
1.78M
    if (((first_flags2 & BLOSC2_VL_BLOCKS) != 0) != chunk_vlblocks) {
1200
517
      BLOSC_TRACE_ERROR("schunks cannot mix regular chunks and VL-block chunks.");
1201
517
      return BLOSC2_ERROR_CHUNK_APPEND;
1202
517
    }
1203
1.78M
  }
1204
44.1k
  else {
1205
44.1k
    schunk->flags2 = flags2;
1206
44.1k
  }
1207
1208
1.82M
  int32_t last_nbytes = 0;
1209
1.82M
  if (schunk->chunksize != 0 && nchunks > 0) {
1210
1.76M
    rc = schunk_get_chunk_nbytes(schunk, nchunks - 1, &last_nbytes);
1211
1.76M
    if (rc < 0) {
1212
427
      return rc;
1213
427
    }
1214
1.76M
  }
1215
1.82M
  int32_t chunksize = schunk->chunksize;
1216
1.82M
  if (!chunksize_after_adding(&schunk->chunksize, nchunks, last_nbytes, chunk_nbytes, true)) {
1217
905
    BLOSC_TRACE_ERROR("Appending chunks that have different lengths in the same schunk "
1218
905
                      "is not supported yet: %d > %d.", chunk_nbytes, chunksize);
1219
905
    return BLOSC2_ERROR_CHUNK_APPEND;
1220
905
  }
1221
1222
  /* Update counters */
1223
1.82M
  schunk->current_nchunk = nchunks;
1224
1.82M
  schunk->nchunks = nchunks + 1;
1225
1.82M
  schunk->nbytes += chunk_nbytes;
1226
  // A frame codes special chunks in their offsets
1227
1.82M
  if (schunk->frame == NULL || !chunk_special_in_offset(chunk, chunk_cbytes)) {
1228
1.82M
    schunk->cbytes += chunk_cbytes;
1229
1.82M
  }
1230
1231
1.82M
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1232
1.82M
  bool private_copy = chunk_needs_private_copy(frame, how);
1233
1.82M
  if (private_copy) {
1234
    // Make a copy of the chunk
1235
1.64M
    uint8_t *chunk_copy = malloc(chunk_cbytes);
1236
1.64M
    memcpy(chunk_copy, chunk, chunk_cbytes);
1237
1.64M
    chunk = chunk_copy;
1238
1.64M
  }
1239
1240
  // Update super-chunk or frame
1241
1.82M
  if (frame == NULL) {
1242
1.78M
    if (how == CHUNK_GIVEN && (chunk_cbytes < chunk_nbytes)) {
1243
      // We still want to do a shrink of the chunk
1244
44.2k
      chunk = realloc(chunk, chunk_cbytes);
1245
44.2k
    }
1246
1247
    /* Make space for appending the copy of the chunk and do it */
1248
1.78M
    if ((nchunks + 1) * sizeof(void *) > schunk->data_len) {
1249
      // Extend the data pointer by one memory page (4k)
1250
30.0k
      schunk->data_len += 4096;  // must be a multiple of sizeof(void*)
1251
30.0k
      schunk->data = realloc(schunk->data, schunk->data_len);
1252
30.0k
    }
1253
1.78M
    schunk->data[nchunks] = chunk;
1254
1.78M
  }
1255
39.8k
  else {
1256
39.8k
    bool written = frame_append_chunk(frame, chunk, schunk) != NULL;
1257
39.8k
    frame_write_done(chunk, how, private_copy, written);
1258
39.8k
    if (!written) {
1259
3.98k
      BLOSC_TRACE_ERROR("Problems appending a chunk.");
1260
3.98k
      schunk->flags2 = old_flags2;
1261
3.98k
      schunk->chunksize = old_chunksize;
1262
3.98k
      schunk->current_nchunk = old_current_nchunk;
1263
3.98k
      schunk->nchunks = nchunks;
1264
3.98k
      schunk->nbytes = old_nbytes;
1265
3.98k
      schunk->cbytes = old_cbytes;
1266
3.98k
      return BLOSC2_ERROR_CHUNK_APPEND;
1267
3.98k
    }
1268
39.8k
  }
1269
1.82M
  return schunk->nchunks;
1270
1.82M
}
1271
1272
1273
1.82M
static int64_t schunk_append_chunk_locked(blosc2_schunk *schunk, uint8_t *chunk, chunk_handover how) {
1274
1.82M
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1275
1.82M
  int rc = frame_lock(frame, true);
1276
1.82M
  if (rc < 0) {
1277
0
    return rc;
1278
0
  }
1279
  // Sync the cached counters before the delta below is applied to them, so a
1280
  // handle whose lock acquisition just flagged staleness does not persist
1281
  // wrong nbytes/cbytes/nchunks (see plans/todo-locking-swmr.md item 1).
1282
1.82M
  rc = frame_check_stale(frame);
1283
1.82M
  if (rc < 0) {
1284
0
    frame_unlock(frame);
1285
0
    return rc;
1286
0
  }
1287
1.82M
  int64_t nchunks = schunk_append_chunk_unlocked(schunk, chunk, how);
1288
1.82M
  frame_unlock(frame);
1289
1.82M
  return nchunks;
1290
1.82M
}
1291
1292
1293
/* Append an existing @p chunk to a super-chunk. */
1294
1.56M
int64_t blosc2_schunk_append_chunk(blosc2_schunk *schunk, uint8_t *chunk, bool copy) {
1295
1.56M
  return schunk_append_chunk_locked(schunk, chunk, copy ? CHUNK_COPIED : CHUNK_GIVEN);
1296
1.56M
}
1297
1298
1299
/* Insert an existing @p chunk in a specified position on a super-chunk */
1300
static int64_t schunk_insert_chunk_unlocked(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk,
1301
537k
                                            chunk_handover how) {
1302
537k
  int rc = validate_nchunk(schunk, nchunk, true, "blosc2_schunk_insert_chunk");
1303
537k
  if (rc < 0) {
1304
0
    return rc;
1305
0
  }
1306
1307
537k
  int32_t chunk_nbytes;
1308
537k
  int32_t chunk_cbytes;
1309
537k
  int64_t nchunks = schunk->nchunks;
1310
1311
537k
  rc = blosc2_cbuffer_sizes(chunk, &chunk_nbytes, &chunk_cbytes, NULL);
1312
537k
  if (rc < 0) {
1313
0
    return rc;
1314
0
  }
1315
  // Saved, so that the super-chunk is left unchanged if inserting into the frame fails
1316
537k
  uint8_t old_flags2 = schunk->flags2;
1317
537k
  int32_t old_chunksize = schunk->chunksize;
1318
537k
  int64_t old_current_nchunk = schunk->current_nchunk;
1319
537k
  int64_t old_nbytes = schunk->nbytes;
1320
537k
  int64_t old_cbytes = schunk->cbytes;
1321
537k
  uint8_t flags2 = get_chunk_flags2(chunk, chunk_cbytes);
1322
537k
  bool chunk_vlblocks = (flags2 & BLOSC2_VL_BLOCKS) != 0;
1323
537k
  if (nchunks > 0) {
1324
532k
    uint8_t first_flags2;
1325
532k
    rc = schunk_get_chunk_flags2(schunk, 0, &first_flags2);
1326
532k
    if (rc < 0) {
1327
29
      return rc;
1328
29
    }
1329
532k
    if (((first_flags2 & BLOSC2_VL_BLOCKS) != 0) != chunk_vlblocks) {
1330
21
      BLOSC_TRACE_ERROR("schunks cannot mix regular chunks and VL-block chunks.");
1331
21
      return BLOSC2_ERROR_CHUNK_INSERT;
1332
21
    }
1333
532k
  }
1334
4.78k
  else {
1335
4.78k
    schunk->flags2 = flags2;
1336
4.78k
  }
1337
1338
537k
  int32_t last_nbytes = 0;
1339
537k
  if (schunk->chunksize != 0 && nchunks > 0) {
1340
532k
    rc = schunk_get_chunk_nbytes(schunk, nchunks - 1, &last_nbytes);
1341
532k
    if (rc < 0) {
1342
7
      return rc;
1343
7
    }
1344
532k
  }
1345
537k
  int32_t chunksize = schunk->chunksize;
1346
537k
  if (!chunksize_after_adding(&schunk->chunksize, nchunks, last_nbytes, chunk_nbytes,
1347
537k
                              nchunk == nchunks)) {
1348
58
    BLOSC_TRACE_ERROR("Inserting chunks that have different lengths in the same schunk "
1349
58
                      "is not supported yet: %d > %d.", chunk_nbytes, chunksize);
1350
58
    return BLOSC2_ERROR_CHUNK_INSERT;
1351
58
  }
1352
1353
  /* Update counters */
1354
537k
  schunk->current_nchunk = nchunk;
1355
537k
  schunk->nchunks = nchunks + 1;
1356
537k
  schunk->nbytes += chunk_nbytes;
1357
  // A frame codes special chunks in their offsets
1358
537k
  if (schunk->frame == NULL || !chunk_special_in_offset(chunk, chunk_cbytes)) {
1359
5.13k
    schunk->cbytes += chunk_cbytes;
1360
5.13k
  }
1361
1362
537k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1363
537k
  bool private_copy = chunk_needs_private_copy(frame, how);
1364
537k
  if (private_copy) {
1365
    // Make a copy of the chunk
1366
5.28k
    uint8_t *chunk_copy = malloc(chunk_cbytes);
1367
5.28k
    memcpy(chunk_copy, chunk, chunk_cbytes);
1368
5.28k
    chunk = chunk_copy;
1369
5.28k
  }
1370
1371
  // Update super-chunk or frame
1372
537k
  if (frame == NULL) {
1373
2.45k
    if (how == CHUNK_GIVEN && (chunk_cbytes < chunk_nbytes)) {
1374
      // We still want to do a shrink of the chunk
1375
0
      chunk = realloc(chunk, chunk_cbytes);
1376
0
    }
1377
1378
    // Make space for appending the copy of the chunk and do it
1379
2.45k
    if ((nchunks + 1) * sizeof(void *) > schunk->data_len) {
1380
      // Extend the data pointer by one memory page (4k)
1381
2.06k
      schunk->data_len += 4096;  // must be a multiple of sizeof(void*)
1382
2.06k
      schunk->data = realloc(schunk->data, schunk->data_len);
1383
2.06k
    }
1384
1385
    // Reorder the offsets and insert the new chunk
1386
3.11k
    for (int64_t i = nchunks; i > nchunk; --i) {
1387
658
      schunk->data[i] = schunk->data[i-1];
1388
658
    }
1389
2.45k
    schunk->data[nchunk] = chunk;
1390
2.45k
  }
1391
1392
534k
  else {
1393
534k
    bool written = frame_insert_chunk(frame, nchunk, chunk, schunk) != NULL;
1394
534k
    frame_write_done(chunk, how, private_copy, written);
1395
534k
    if (!written) {
1396
463
      BLOSC_TRACE_ERROR("Problems inserting a chunk in a frame.");
1397
463
      schunk->flags2 = old_flags2;
1398
463
      schunk->chunksize = old_chunksize;
1399
463
      schunk->current_nchunk = old_current_nchunk;
1400
463
      schunk->nchunks = nchunks;
1401
463
      schunk->nbytes = old_nbytes;
1402
463
      schunk->cbytes = old_cbytes;
1403
463
      return BLOSC2_ERROR_CHUNK_INSERT;
1404
463
    }
1405
534k
  }
1406
536k
  return schunk->nchunks;
1407
537k
}
1408
1409
1410
static int64_t schunk_insert_chunk_locked(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk,
1411
537k
                                          chunk_handover how) {
1412
537k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1413
537k
  int rc = frame_lock(frame, true);
1414
537k
  if (rc < 0) {
1415
0
    return rc;
1416
0
  }
1417
  // See schunk_append_chunk_locked() for why this must happen before the
1418
  // counter deltas below are applied.
1419
537k
  rc = frame_check_stale(frame);
1420
537k
  if (rc < 0) {
1421
0
    frame_unlock(frame);
1422
0
    return rc;
1423
0
  }
1424
537k
  int64_t nchunks = schunk_insert_chunk_unlocked(schunk, nchunk, chunk, how);
1425
537k
  frame_unlock(frame);
1426
537k
  return nchunks;
1427
537k
}
1428
1429
1430
/* Insert an existing @p chunk in a specified position on a super-chunk. */
1431
537k
int64_t blosc2_schunk_insert_chunk(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk, bool copy) {
1432
537k
  return schunk_insert_chunk_locked(schunk, nchunk, chunk, copy ? CHUNK_COPIED : CHUNK_GIVEN);
1433
537k
}
1434
1435
1436
static int64_t schunk_update_chunk_unlocked(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk,
1437
617k
                                            chunk_handover how) {
1438
617k
  int rc = validate_nchunk(schunk, nchunk, false, "blosc2_schunk_update_chunk");
1439
617k
  if (rc < 0) {
1440
52
    return rc;
1441
52
  }
1442
1443
617k
  uint8_t old_flags2 = schunk->flags2;
1444
617k
  int32_t old_chunksize = schunk->chunksize;
1445
617k
  int64_t old_current_nchunk = schunk->current_nchunk;
1446
617k
  int64_t old_nbytes = schunk->nbytes;
1447
617k
  int64_t old_cbytes = schunk->cbytes;
1448
1449
617k
  int32_t chunk_nbytes;
1450
617k
  int32_t chunk_cbytes;
1451
1452
617k
  rc = blosc2_cbuffer_sizes(chunk, &chunk_nbytes, &chunk_cbytes, NULL);
1453
617k
  if (rc < 0) {
1454
0
    return rc;
1455
0
  }
1456
617k
  uint8_t flags2 = get_chunk_flags2(chunk, chunk_cbytes);
1457
617k
  bool chunk_vlblocks = (flags2 & BLOSC2_VL_BLOCKS) != 0;
1458
617k
  if (schunk->nchunks > 1 || (schunk->nchunks == 1 && nchunk != 0)) {
1459
616k
    int64_t ref_nchunk = (nchunk == 0) ? 1 : 0;
1460
616k
    uint8_t ref_flags2;
1461
616k
    rc = schunk_get_chunk_flags2(schunk, ref_nchunk, &ref_flags2);
1462
616k
    if (rc < 0) {
1463
19
      return rc;
1464
19
    }
1465
616k
    if (((ref_flags2 & BLOSC2_VL_BLOCKS) != 0) != chunk_vlblocks) {
1466
14
      BLOSC_TRACE_ERROR("schunks cannot mix regular chunks and VL-block chunks.");
1467
14
      return BLOSC2_ERROR_CHUNK_UPDATE;
1468
14
    }
1469
616k
  }
1470
1.49k
  else {
1471
1.49k
    schunk->flags2 = flags2;
1472
1.49k
  }
1473
1474
617k
  int32_t chunksize = schunk->chunksize;
1475
617k
  bool variable_chunksize = (chunksize == 0);
1476
617k
  if (chunksize == -1) {
1477
24
    schunk->chunksize = chunk_nbytes;  // The super-chunk is initialized now
1478
24
    chunksize = schunk->chunksize;
1479
24
  }
1480
1481
617k
  if (!variable_chunksize && (chunk_nbytes > chunksize ||
1482
616k
      (nchunk != schunk->nchunks - 1 && chunk_nbytes != chunksize))) {
1483
471
    variable_chunksize = true;
1484
471
    schunk->chunksize = 0;
1485
471
  }
1486
617k
  if (!variable_chunksize && chunksize > 0 && chunk_nbytes > chunksize) {
1487
0
    BLOSC_TRACE_ERROR("Updating chunks having different lengths in the same schunk "
1488
0
                      "is not supported yet: %d > %d.", chunk_nbytes, chunksize);
1489
0
    return BLOSC2_ERROR_CHUNK_UPDATE;
1490
0
  }
1491
1492
  // Only the sizes of the old chunk are needed, so do not read all of it from disk
1493
617k
  int32_t chunk_nbytes_old;
1494
617k
  int32_t chunk_cbytes_old;
1495
617k
  rc = schunk_get_counted_sizes(schunk, nchunk, &chunk_nbytes_old, &chunk_cbytes_old);
1496
617k
  if (rc < 0) {
1497
64
    BLOSC_TRACE_ERROR("%" PRId64 " chunk can not be obtained from schunk.", nchunk);
1498
64
    return rc;
1499
64
  }
1500
617k
  schunk->current_nchunk = nchunk;
1501
1502
617k
  blosc2_frame_s* frame = (blosc2_frame_s*)(schunk->frame);
1503
617k
  bool private_copy = chunk_needs_private_copy(frame, how);
1504
617k
  if (private_copy) {
1505
    // Make a copy of the chunk
1506
8.99k
    uint8_t *chunk_copy = malloc(chunk_cbytes);
1507
8.99k
    memcpy(chunk_copy, chunk, chunk_cbytes);
1508
8.99k
    chunk = chunk_copy;
1509
8.99k
  }
1510
1511
617k
  if (schunk->frame == NULL) {
1512
    /* Update counters */
1513
324
    schunk->nbytes += chunk_nbytes;
1514
324
    schunk->nbytes -= chunk_nbytes_old;
1515
324
    schunk->cbytes += chunk_cbytes;
1516
324
    schunk->cbytes -= chunk_cbytes_old;
1517
617k
  } else {
1518
    // A frame codes special chunks in their offsets
1519
617k
    schunk->nbytes += chunk_nbytes;
1520
617k
    schunk->nbytes -= chunk_nbytes_old;
1521
617k
    if (!chunk_special_in_offset(chunk, chunk_cbytes)) {
1522
510k
      schunk->cbytes += chunk_cbytes;
1523
510k
    }
1524
617k
    schunk->cbytes -= chunk_cbytes_old;
1525
617k
  }
1526
1527
  // Update super-chunk or frame
1528
617k
  if (schunk->frame == NULL) {
1529
324
    if (how == CHUNK_GIVEN && (chunk_cbytes < chunk_nbytes)) {
1530
      // We still want to do a shrink of the chunk
1531
0
      chunk = realloc(chunk, chunk_cbytes);
1532
0
    }
1533
1534
    // Free old chunk and add reference to new chunk
1535
324
    if (schunk->data[nchunk] != 0) {
1536
324
      free(schunk->data[nchunk]);
1537
324
    }
1538
324
    schunk->data[nchunk] = chunk;
1539
324
  }
1540
617k
  else {
1541
617k
    bool written = frame_update_chunk(frame, nchunk, chunk, schunk, chunk_cbytes_old) != NULL;
1542
617k
    frame_write_done(chunk, how, private_copy, written);
1543
617k
    if (!written) {
1544
314
      BLOSC_TRACE_ERROR("Problems updating a chunk in a frame.");
1545
314
      schunk->flags2 = old_flags2;
1546
314
      schunk->chunksize = old_chunksize;
1547
314
      schunk->current_nchunk = old_current_nchunk;
1548
314
      schunk->nbytes = old_nbytes;
1549
314
      schunk->cbytes = old_cbytes;
1550
314
      return BLOSC2_ERROR_CHUNK_UPDATE;
1551
314
    }
1552
617k
  }
1553
1554
617k
  return schunk->nchunks;
1555
617k
}
1556
1557
static int64_t schunk_update_chunk_locked(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk,
1558
617k
                                          chunk_handover how) {
1559
617k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1560
617k
  int rc = frame_lock(frame, true);
1561
617k
  if (rc < 0) {
1562
0
    return rc;
1563
0
  }
1564
617k
  int64_t nchunks = schunk_update_chunk_unlocked(schunk, nchunk, chunk, how);
1565
617k
  frame_unlock(frame);
1566
617k
  return nchunks;
1567
617k
}
1568
1569
/* Update the chunk at a specified position of a super-chunk. */
1570
9.12k
int64_t blosc2_schunk_update_chunk(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk, bool copy) {
1571
9.12k
  return schunk_update_chunk_locked(schunk, nchunk, chunk, copy ? CHUNK_COPIED : CHUNK_GIVEN);
1572
9.12k
}
1573
1574
/* See blosc-private.h */
1575
608k
int64_t schunk_update_chunk_lent(blosc2_schunk *schunk, int64_t nchunk, uint8_t *chunk) {
1576
608k
  return schunk_update_chunk_locked(schunk, nchunk, chunk, CHUNK_LENT);
1577
608k
}
1578
1579
1580
24.0k
static int64_t schunk_delete_chunk_unlocked(blosc2_schunk *schunk, int64_t nchunk) {
1581
24.0k
  int rc = validate_nchunk(schunk, nchunk, false, "blosc2_schunk_delete_chunk");
1582
24.0k
  if (rc < 0) {
1583
12.9k
    return rc;
1584
12.9k
  }
1585
1586
  // Only the sizes of the old chunk are needed (see schunk_update_chunk_unlocked)
1587
11.0k
  int32_t chunk_nbytes_old;
1588
11.0k
  int32_t chunk_cbytes_old;
1589
11.0k
  rc = schunk_get_counted_sizes(schunk, nchunk, &chunk_nbytes_old, &chunk_cbytes_old);
1590
11.0k
  if (rc < 0) {
1591
753
    BLOSC_TRACE_ERROR("%" PRId64 "chunk can not be obtained from schunk.", nchunk);
1592
753
    return rc;
1593
753
  }
1594
10.2k
  schunk->current_nchunk = nchunk;
1595
1596
10.2k
  blosc2_frame_s* frame = (blosc2_frame_s*)(schunk->frame);
1597
10.2k
  schunk->nchunks -= 1;
1598
10.2k
  if (schunk->nchunks == 0) {
1599
5.52k
    schunk->flags2 = 0;
1600
5.52k
  }
1601
10.2k
  if (schunk->frame == NULL) {
1602
    /* Update counters */
1603
5.23k
    schunk->nbytes -= chunk_nbytes_old;
1604
5.23k
    schunk->cbytes -= chunk_cbytes_old;
1605
5.23k
  } else {
1606
    // A frame
1607
5.03k
    schunk->nbytes -= chunk_nbytes_old;
1608
5.03k
    if (frame->sframe) {
1609
0
      schunk->cbytes -= chunk_cbytes_old;
1610
0
    }
1611
5.03k
  }
1612
1613
  // Update super-chunk or frame
1614
10.2k
  if (schunk->frame == NULL) {
1615
    // Free old chunk
1616
5.23k
    if (schunk->data[nchunk] != 0) {
1617
5.23k
      free(schunk->data[nchunk]);
1618
5.23k
    }
1619
    // Reorder the offsets and insert the new chunk
1620
8.42k
    for (int64_t i = nchunk; i < schunk->nchunks; i++) {
1621
3.18k
      schunk->data[i] = schunk->data[i + 1];
1622
3.18k
    }
1623
5.23k
    schunk->data[schunk->nchunks] = NULL;
1624
1625
5.23k
  }
1626
5.03k
  else {
1627
5.03k
    if (frame_delete_chunk(frame, nchunk, schunk) == NULL) {
1628
1.14k
      BLOSC_TRACE_ERROR("Problems deleting a chunk in a frame.");
1629
1.14k
      return BLOSC2_ERROR_CHUNK_UPDATE;
1630
1.14k
    }
1631
5.03k
  }
1632
9.12k
  return schunk->nchunks;
1633
10.2k
}
1634
1635
1636
/* Delete the chunk at a specified position of a super-chunk. */
1637
24.0k
int64_t blosc2_schunk_delete_chunk(blosc2_schunk *schunk, int64_t nchunk) {
1638
24.0k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1639
24.0k
  int rc = frame_lock(frame, true);
1640
24.0k
  if (rc < 0) {
1641
0
    return rc;
1642
0
  }
1643
24.0k
  int64_t nchunks = schunk_delete_chunk_unlocked(schunk, nchunk);
1644
24.0k
  frame_unlock(frame);
1645
24.0k
  return nchunks;
1646
24.0k
}
1647
1648
1649
/* See blosc-private.h */
1650
635k
uint8_t *schunk_scratch_malloc(const blosc2_schunk *schunk, int32_t nbytes, size_t *capacity) {
1651
635k
  if (schunk->frame != NULL) {
1652
635k
    return blosc2_tmp_malloc((size_t) nbytes, capacity);
1653
635k
  }
1654
0
  *capacity = 0;
1655
0
  return malloc((size_t) nbytes);
1656
635k
}
1657
1658
1659
typedef enum {
1660
  WRITE_APPEND,
1661
  WRITE_INSERT,
1662
  WRITE_UPDATE,
1663
} chunk_write_op;
1664
1665
1666
/* Compress @p src (@p nbytes) with the super-chunk's context and append, insert or update the
1667
   chunk at @p nchunk (ignored for appends).  Always compresses into a reusable thread-local
1668
   scratch buffer (see blosc2_tmp_malloc()) so repeated chunks avoid allocating and faulting
1669
   fresh multi-megabyte VM pages.  A frame stores its own copy; compressible plain chunks
1670
   (cbytes < nbytes / 2) are lent so the schunk allocates an exact cbytes buffer directly instead
1671
   of shrinking a multi-megabyte buffer via realloc(). */
1672
static int64_t schunk_compress_store(blosc2_schunk *schunk, int64_t nchunk, const void *src,
1673
268k
                                     int32_t nbytes, chunk_write_op op, const char *func_name) {
1674
268k
  if (nbytes < 0 || nbytes > BLOSC2_MAX_BUFFERSIZE) {
1675
0
    BLOSC_TRACE_ERROR("nbytes ('%d') is out of range [0, %d] in %s.", nbytes,
1676
0
                      BLOSC2_MAX_BUFFERSIZE, func_name);
1677
0
    return BLOSC2_ERROR_INVALID_PARAM;
1678
0
  }
1679
  // `nchunk` is left to the store below, which checks it under the frame lock (inserts and
1680
  // appends after refreshing a handle that another one made stale).
1681
268k
  bool in_frame = schunk->frame != NULL;
1682
268k
  int32_t dest_nbytes = nbytes + BLOSC2_MAX_OVERHEAD;
1683
268k
  size_t capacity;
1684
268k
  uint8_t *chunk = blosc2_tmp_malloc((size_t)dest_nbytes, &capacity);
1685
268k
  BLOSC_ERROR_NULL(chunk, BLOSC2_ERROR_MEMORY_ALLOC);
1686
  // Prefilters read the number of the chunk being compressed
1687
268k
  int64_t old_current_nchunk = schunk->current_nchunk;
1688
268k
  schunk->current_nchunk = nchunk;
1689
268k
  int cbytes = blosc2_compress_ctx(schunk->cctx, src, nbytes, chunk, dest_nbytes);
1690
268k
  if (cbytes <= 0) {
1691
167
    blosc2_tmp_free(chunk, capacity);
1692
167
    schunk->current_nchunk = old_current_nchunk;
1693
167
    BLOSC_TRACE_ERROR("Cannot compress the buffer in %s.", func_name);
1694
167
    return cbytes < 0 ? cbytes : BLOSC2_ERROR_WRITE_BUFFER;
1695
167
  }
1696
268k
  bool lend = in_frame || (cbytes < nbytes / 2);
1697
267k
  chunk_handover how = lend ? CHUNK_LENT : CHUNK_GIVEN;
1698
267k
  int64_t nchunks;
1699
267k
  switch (op) {
1700
267k
    case WRITE_APPEND:
1701
267k
      nchunks = schunk_append_chunk_locked(schunk, chunk, how);
1702
267k
      break;
1703
0
    case WRITE_INSERT:
1704
0
      nchunks = schunk_insert_chunk_locked(schunk, nchunk, chunk, how);
1705
0
      break;
1706
0
    default:
1707
0
      nchunks = schunk_update_chunk_locked(schunk, nchunk, chunk, how);
1708
0
      break;
1709
267k
  }
1710
  // A lent buffer stays in the thread-local cache; a failed store leaves it to us
1711
267k
  if (lend || nchunks < 0) {
1712
131k
    blosc2_tmp_free(chunk, capacity);
1713
131k
  }
1714
267k
  if (nchunks < 0) {
1715
7.83k
    schunk->current_nchunk = old_current_nchunk;
1716
7.83k
    BLOSC_TRACE_ERROR("Cannot store the compressed buffer in %s.", func_name);
1717
7.83k
  }
1718
267k
  return nchunks;
1719
267k
}
1720
1721
1722
/* Append a data buffer to a super-chunk. */
1723
268k
int64_t blosc2_schunk_append_buffer(blosc2_schunk *schunk, const void *src, int32_t nbytes) {
1724
268k
  return schunk_compress_store(schunk, schunk->nchunks, src, nbytes, WRITE_APPEND,
1725
268k
                               "blosc2_schunk_append_buffer");
1726
268k
}
1727
1728
1729
/* Insert a data buffer as a new chunk in a specified position of a super-chunk. */
1730
int64_t blosc2_schunk_insert_buffer(blosc2_schunk *schunk, int64_t nchunk, const void *src,
1731
0
                                    int32_t nbytes) {
1732
0
  return schunk_compress_store(schunk, nchunk, src, nbytes, WRITE_INSERT,
1733
0
                               "blosc2_schunk_insert_buffer");
1734
0
}
1735
1736
1737
/* Replace the chunk at a specified position of a super-chunk with a data buffer. */
1738
int64_t blosc2_schunk_update_buffer(blosc2_schunk *schunk, int64_t nchunk, const void *src,
1739
0
                                    int32_t nbytes) {
1740
0
  return schunk_compress_store(schunk, nchunk, src, nbytes, WRITE_UPDATE,
1741
0
                               "blosc2_schunk_update_buffer");
1742
0
}
1743
1744
1745
/* Decompress and return a chunk that is part of a super-chunk. */
1746
int blosc2_schunk_decompress_chunk(blosc2_schunk *schunk, int64_t nchunk,
1747
755k
                                   void *dest, int32_t nbytes) {
1748
755k
  int rc = validate_nchunk(schunk, nchunk, false, "blosc2_schunk_decompress_chunk");
1749
755k
  if (rc < 0) {
1750
24.1k
    return rc;
1751
24.1k
  }
1752
1753
731k
  int32_t chunk_nbytes;
1754
731k
  int32_t chunk_cbytes;
1755
731k
  int chunksize;
1756
731k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1757
1758
731k
  schunk->current_nchunk = nchunk;
1759
731k
  if (frame == NULL) {
1760
105k
    uint8_t* src = schunk->data[nchunk];
1761
105k
    if (src == 0) {
1762
0
      return 0;
1763
0
    }
1764
1765
105k
    rc = blosc2_cbuffer_sizes(src, &chunk_nbytes, &chunk_cbytes, NULL);
1766
105k
    if (rc < 0) {
1767
0
      return rc;
1768
0
    }
1769
1770
105k
    if (nbytes < chunk_nbytes) {
1771
6.84k
      BLOSC_TRACE_ERROR("Buffer size is too small for the decompressed buffer "
1772
6.84k
                        "('%d' bytes, but '%d' are needed).", nbytes, chunk_nbytes);
1773
6.84k
      return BLOSC2_ERROR_INVALID_PARAM;
1774
6.84k
    }
1775
1776
98.5k
    chunksize = blosc2_decompress_ctx(schunk->dctx, src, chunk_cbytes, dest, nbytes);
1777
98.5k
    if (chunksize < 0 || chunksize != chunk_nbytes) {
1778
22.6k
      BLOSC_TRACE_ERROR("Error in decompressing chunk.");
1779
22.6k
      if (chunksize < 0)
1780
22.1k
        return chunksize;
1781
509
      return BLOSC2_ERROR_FAILURE;
1782
22.6k
    }
1783
626k
  } else {
1784
626k
    rc = frame_lock(frame, false);
1785
626k
    if (rc < 0) {
1786
0
      return rc;
1787
0
    }
1788
626k
    chunksize = frame_decompress_chunk(schunk->dctx, frame, nchunk, dest, nbytes);
1789
626k
    frame_unlock(frame);
1790
626k
    if (chunksize < 0) {
1791
13.9k
      return chunksize;
1792
13.9k
    }
1793
626k
  }
1794
688k
  return chunksize;
1795
731k
}
1796
1797
1798
/* Return a compressed chunk that is part of a super-chunk in the `chunk` parameter.
1799
 * If the super-chunk is backed by a frame that is disk-based, a buffer is allocated for the
1800
 * (compressed) chunk, and hence a free is needed.  You can check if the chunk requires a free
1801
 * with the `needs_free` parameter.
1802
 * If the chunk does not need a free, it means that a pointer to the location in the super-chunk
1803
 * (or the backing in-memory frame) is returned in the `chunk` parameter.
1804
 *
1805
 * The size of the (compressed) chunk is returned.  If some problem is detected, a negative code
1806
 * is returned instead.
1807
*/
1808
14.4k
int blosc2_schunk_get_chunk(blosc2_schunk *schunk, int64_t nchunk, uint8_t **chunk, bool *needs_free) {
1809
14.4k
  int rc = validate_nchunk(schunk, nchunk, false, "blosc2_schunk_get_chunk");
1810
14.4k
  if (rc < 0) {
1811
3.50k
    return rc;
1812
3.50k
  }
1813
1814
10.9k
  if (ctx_uses_parallel_backend(schunk->dctx)) {
1815
0
    blosc2_pthread_mutex_lock(&schunk->dctx->nchunk_mutex);
1816
0
    schunk->current_nchunk = nchunk;
1817
0
    blosc2_pthread_mutex_unlock(&schunk->dctx->nchunk_mutex);
1818
0
  }
1819
10.9k
  else {
1820
10.9k
    schunk->current_nchunk = nchunk;
1821
10.9k
  }
1822
10.9k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1823
10.9k
  if (frame != NULL) {
1824
5.19k
    rc = frame_lock(frame, false);
1825
5.19k
    if (rc < 0) {
1826
0
      return rc;
1827
0
    }
1828
5.19k
    rc = frame_get_chunk(frame, nchunk, chunk, needs_free);
1829
5.19k
    frame_unlock(frame);
1830
5.19k
    return rc;
1831
5.19k
  }
1832
1833
5.74k
  *chunk = schunk->data[nchunk];
1834
5.74k
  if (*chunk == 0) {
1835
0
    *needs_free = 0;
1836
0
    return 0;
1837
0
  }
1838
1839
5.74k
  *needs_free = false;
1840
5.74k
  int32_t chunk_cbytes;
1841
5.74k
  rc = blosc2_cbuffer_sizes(*chunk, NULL, &chunk_cbytes, NULL);
1842
5.74k
  if (rc < 0) {
1843
0
    return rc;
1844
0
  }
1845
5.74k
  return (int)chunk_cbytes;
1846
5.74k
}
1847
1848
1849
/* See blosc2.h */
1850
0
int blosc2_schunk_get_chunk_range(blosc2_schunk *schunk, int64_t nchunk, int64_t *offset, int64_t *nbytes) {
1851
0
  BLOSC_ERROR_NULL(schunk, BLOSC2_ERROR_NULL_POINTER);
1852
0
  BLOSC_ERROR_NULL(offset, BLOSC2_ERROR_NULL_POINTER);
1853
0
  BLOSC_ERROR_NULL(nbytes, BLOSC2_ERROR_NULL_POINTER);
1854
0
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1855
0
  if (frame == NULL) {
1856
0
    BLOSC_TRACE_ERROR("The super-chunk is not stored in a frame.");
1857
0
    return BLOSC2_ERROR_INVALID_PARAM;
1858
0
  }
1859
0
  int rc = frame_lock(frame, false);
1860
0
  if (rc < 0) {
1861
0
    return rc;
1862
0
  }
1863
0
  int64_t range[2];
1864
0
  rc = frame_get_chunk_ranges(frame, &nchunk, 1, range);
1865
0
  frame_unlock(frame);
1866
0
  if (rc >= 0) {
1867
0
    *offset = range[0];
1868
0
    *nbytes = range[1];
1869
0
  }
1870
0
  return rc;
1871
0
}
1872
1873
1874
/* Return a compressed chunk that is part of a super-chunk in the `chunk` parameter.
1875
 * If the super-chunk is backed by a frame that is disk-based, a buffer is allocated for the
1876
 * (compressed) chunk, and hence a free is needed.  You can check if the chunk requires a free
1877
 * with the `needs_free` parameter.
1878
 * If the chunk does not need a free, it means that a pointer to the location in the super-chunk
1879
 * (or the backing in-memory frame) is returned in the `chunk` parameter.
1880
 *
1881
 * The size of the (compressed) chunk is returned.  If some problem is detected, a negative code
1882
 * is returned instead.
1883
*/
1884
89.7k
int blosc2_schunk_get_lazychunk(blosc2_schunk *schunk, int64_t nchunk, uint8_t **chunk, bool *needs_free) {
1885
89.7k
  int rc = validate_nchunk(schunk, nchunk, false, "blosc2_schunk_get_lazychunk");
1886
89.7k
  if (rc < 0) {
1887
354
    return rc;
1888
354
  }
1889
1890
89.3k
  if (ctx_uses_parallel_backend(schunk->dctx)) {
1891
0
    blosc2_pthread_mutex_lock(&schunk->dctx->nchunk_mutex);
1892
0
    schunk->current_nchunk = nchunk;
1893
0
    blosc2_pthread_mutex_unlock(&schunk->dctx->nchunk_mutex);
1894
0
  }
1895
89.3k
  else {
1896
89.3k
    schunk->current_nchunk = nchunk;
1897
89.3k
  }
1898
89.3k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
1899
89.3k
  if (schunk->frame != NULL) {
1900
73.7k
    rc = frame_lock(frame, false);
1901
73.7k
    if (rc < 0) {
1902
0
      return rc;
1903
0
    }
1904
73.7k
    rc = frame_get_lazychunk(frame, nchunk, chunk, needs_free);
1905
73.7k
    frame_unlock(frame);
1906
73.7k
    return rc;
1907
73.7k
  }
1908
1909
15.6k
  *chunk = schunk->data[nchunk];
1910
15.6k
  if (*chunk == 0) {
1911
0
    *needs_free = 0;
1912
0
    return 0;
1913
0
  }
1914
1915
15.6k
  *needs_free = false;
1916
15.6k
  int32_t chunk_cbytes;
1917
15.6k
  rc = blosc2_cbuffer_sizes(*chunk, NULL, &chunk_cbytes, NULL);
1918
15.6k
  if (rc < 0) {
1919
0
    return rc;
1920
0
  }
1921
15.6k
  return (int)chunk_cbytes;
1922
15.6k
}
1923
1924
1925
int blosc2_schunk_get_vlblock(blosc2_schunk *schunk, int64_t nchunk, int32_t nblock,
1926
0
                              uint8_t **dest, int32_t *destsize) {
1927
0
  if (schunk == NULL || dest == NULL || destsize == NULL) {
1928
0
    BLOSC_TRACE_ERROR("schunk, dest, and destsize must not be NULL.");
1929
0
    return BLOSC2_ERROR_INVALID_PARAM;
1930
0
  }
1931
1932
0
  uint8_t *chunk = NULL;
1933
0
  bool needs_free = false;
1934
0
  int cbytes = blosc2_schunk_get_chunk(schunk, nchunk, &chunk, &needs_free);
1935
0
  if (cbytes < 0) {
1936
0
    return cbytes;
1937
0
  }
1938
0
  if (chunk == NULL || cbytes == 0) {
1939
0
    BLOSC_TRACE_ERROR("Chunk %" PRId64 " is not initialized.", nchunk);
1940
0
    return BLOSC2_ERROR_INVALID_PARAM;
1941
0
  }
1942
1943
0
  int result = blosc2_vldecompress_block_ctx(schunk->dctx, chunk, cbytes,
1944
0
                                             nblock, dest, destsize);
1945
0
  if (needs_free) {
1946
0
    free(chunk);
1947
0
  }
1948
0
  return result;
1949
0
}
1950
1951
/* Whether a read of `nbytes` bytes at `chunk_start` that is not the whole chunk should decompress
1952
   the blocks it needs in parallel (see masked_slice_read()) instead of one after the other with
1953
   getitem. */
1954
static bool use_masked_slice_read(blosc2_schunk *schunk, const uint8_t *chunk, int32_t cbytes,
1955
26.0k
                                  int32_t blocksize, int32_t chunk_start, int32_t nbytes) {
1956
26.0k
  blosc2_context *dctx = schunk->dctx;
1957
26.0k
  if (dctx->new_nthreads <= 1 || dctx->postfilter != NULL || blocksize <= 0 ||
1958
26.0k
      cbytes < BLOSC_EXTENDED_HEADER_LENGTH) {
1959
26.0k
    return false;
1960
26.0k
  }
1961
0
  uint8_t flags = chunk[BLOSC2_CHUNK_FLAGS];
1962
0
  uint8_t blosc2_flags = chunk[BLOSC2_CHUNK_BLOSC2_FLAGS];
1963
0
  bool extended_header = (flags & BLOSC_DOSHUFFLE) && (flags & BLOSC_DOBITSHUFFLE);
1964
  // Memcpyed and special-value chunks cost getitem nothing to decode, VL-block ones do not support
1965
  // it, and the postfilter that does the copy is bypassed by instrumented codecs
1966
0
  if (!extended_header || (flags & BLOSC_MEMCPYED) || ((blosc2_flags >> 4) & BLOSC2_SPECIAL_MASK) != 0 ||
1967
0
      (blosc2_flags & BLOSC2_INSTR_CODEC) || (get_chunk_flags2(chunk, cbytes) & BLOSC2_VL_BLOCKS)) {
1968
0
    return false;
1969
0
  }
1970
  // DELTA decodes against the first block of the destination, which the postfilter never writes
1971
0
  if (filters_contain(chunk + BLOSC2_CHUNK_FILTER_CODES, BLOSC_DELTA)) {
1972
0
    return false;
1973
0
  }
1974
  // Let getitem report a range that the chunk does not hold
1975
0
  if ((int64_t) chunk_start + nbytes > sw32_(chunk + BLOSC2_CHUNK_NBYTES)) {
1976
0
    return false;
1977
0
  }
1978
0
  int32_t nblocks_needed = (chunk_start + nbytes - 1) / blocksize - chunk_start / blocksize + 1;
1979
  // Below this, waking the threads costs more than decoding serially (LZ4, 256 KB blocks: 2 blocks
1980
  // took 1.5x longer in parallel, 8 blocks 2.4x shorter)
1981
0
  return nblocks_needed >= 4 && nbytes >= 1024 * 1024;
1982
0
}
1983
1984
1985
typedef struct {
1986
  uint8_t *dest;
1987
  int32_t start;
1988
  int32_t stop;
1989
} range_scatter;
1990
1991
1992
// Copy the part of a decompressed block that falls into the slice, in the thread that decoded it
1993
0
static int range_scatter_postfilter(blosc2_postfilter_params *params) {
1994
0
  const range_scatter *scatter = params->user_data;
1995
0
  int32_t lo = params->offset > scatter->start ? params->offset : scatter->start;
1996
0
  int32_t hi = params->offset + params->size < scatter->stop ? params->offset + params->size : scatter->stop;
1997
0
  if (lo < hi) {
1998
0
    memcpy(scatter->dest + (lo - scatter->start), params->input + (lo - params->offset), hi - lo);
1999
0
  }
2000
0
  return 0;
2001
0
}
2002
2003
2004
/* See blosc-private.h */
2005
int schunk_decompress_masked(blosc2_schunk *schunk, int64_t nchunk, const uint8_t *chunk, int32_t cbytes,
2006
                             const bool *maskout, int32_t nblocks, blosc2_postfilter_fn postfilter,
2007
447k
                             void *user_data, void *dest, int32_t destsize) {
2008
447k
  blosc2_context *dctx = schunk->dctx;
2009
447k
  int rc = blosc2_set_maskout(dctx, (bool *) maskout, nblocks);
2010
447k
  if (rc < 0) {
2011
0
    return rc;
2012
0
  }
2013
447k
  blosc2_postfilter_fn saved_postfilter = dctx->postfilter;
2014
447k
  blosc2_postfilter_params *saved_postparams = dctx->postparams;
2015
447k
  blosc2_postfilter_params params;
2016
447k
  if (postfilter != NULL) {
2017
446k
    memset(&params, 0, sizeof(params));
2018
446k
    params.user_data = user_data;
2019
446k
    dctx->postfilter = postfilter;
2020
446k
    dctx->postparams = &params;
2021
446k
  }
2022
447k
  if (chunk != NULL) {
2023
0
    rc = blosc2_decompress_ctx(dctx, chunk, cbytes, dest, destsize);
2024
0
  }
2025
447k
  else {
2026
447k
    rc = blosc2_schunk_decompress_chunk(schunk, nchunk, dest, destsize);
2027
447k
  }
2028
447k
  dctx->postfilter = saved_postfilter;
2029
447k
  dctx->postparams = saved_postparams;
2030
  // A decompression that failed early, or a missing chunk, leaves the mask set
2031
447k
  ctx_clear_maskout(dctx);
2032
447k
  return rc;
2033
447k
}
2034
2035
2036
/* Read `nbytes` bytes at `chunk_start` of `chunk` into `dest`: the threads of the decompression
2037
   context decode only the blocks that hold them, and copy each one straight to `dest`. */
2038
static int masked_slice_read(blosc2_schunk *schunk, uint8_t *chunk, int32_t cbytes, int32_t blocksize,
2039
0
                             int32_t chunk_start, int32_t nbytes, uint8_t *dest) {
2040
0
  int32_t chunk_nbytes = sw32_(chunk + BLOSC2_CHUNK_NBYTES);
2041
0
  int32_t nblocks = chunk_nbytes / blocksize + (chunk_nbytes % blocksize != 0);
2042
0
  int32_t nblock_start = chunk_start / blocksize;
2043
0
  int32_t nblock_stop = (chunk_start + nbytes - 1) / blocksize;
2044
  // The decompressor wants a chunk-sized destination, but with a postfilter it never writes to it
2045
0
  uint8_t *unused_dest = malloc(chunk_nbytes);
2046
0
  bool *maskout = malloc(nblocks);
2047
0
  if (unused_dest == NULL || maskout == NULL) {
2048
0
    free(unused_dest);
2049
0
    free(maskout);
2050
0
    return BLOSC2_ERROR_MEMORY_ALLOC;
2051
0
  }
2052
0
  for (int32_t nblock = 0; nblock < nblocks; nblock++) {
2053
0
    maskout[nblock] = (nblock < nblock_start) || (nblock > nblock_stop);
2054
0
  }
2055
0
  range_scatter scatter;
2056
0
  scatter.dest = dest;
2057
0
  scatter.start = chunk_start;
2058
0
  scatter.stop = chunk_start + nbytes;
2059
0
  int rc = schunk_decompress_masked(schunk, -1, chunk, cbytes, maskout, nblocks, range_scatter_postfilter,
2060
0
                                    &scatter, unused_dest, chunk_nbytes);
2061
0
  free(maskout);
2062
0
  free(unused_dest);
2063
0
  return rc < 0 ? rc : nbytes;
2064
0
}
2065
2066
2067
static int schunk_get_slice_buffer_unlocked(blosc2_schunk *schunk, int64_t start, int64_t stop, void *buffer,
2068
27.2k
                                            prefetch_batch *prefetch) {
2069
27.2k
  if (schunk->chunksize <= 0 || schunk->typesize <= 0) {
2070
0
    BLOSC_TRACE_ERROR("schunk must have a positive chunksize and typesize.");
2071
0
    return BLOSC2_ERROR_INVALID_PARAM;
2072
0
  }
2073
27.2k
  int64_t byte_start = start * schunk->typesize;
2074
27.2k
  int64_t byte_stop = stop * schunk->typesize;
2075
27.2k
  int64_t nchunk_start = byte_start / schunk->chunksize;
2076
27.2k
  int32_t chunk_start = (int32_t) (byte_start % schunk->chunksize); // 0 indexed
2077
27.2k
  int32_t chunk_stop; // 0 indexed
2078
27.2k
  if (byte_stop >= (nchunk_start + 1) * schunk->chunksize) {
2079
3.39k
    chunk_stop = schunk->chunksize;
2080
3.39k
  }
2081
23.8k
  else {
2082
23.8k
    chunk_stop = (int32_t) (byte_stop % schunk->chunksize);
2083
23.8k
  }
2084
2085
27.2k
  uint8_t *dst_ptr = (uint8_t *) buffer;
2086
27.2k
  bool needs_free;
2087
27.2k
  uint8_t *chunk;
2088
27.2k
  int32_t cbytes;
2089
27.2k
  int64_t nchunk = nchunk_start;
2090
27.2k
  int64_t nbytes_read = 0;
2091
27.2k
  int32_t nbytes;
2092
27.2k
  int32_t chunksize = schunk->chunksize;
2093
2094
43.0k
  while (nbytes_read < ((stop - start) * schunk->typesize)) {
2095
29.3k
    prefetch_batch_wait(prefetch, nchunk);
2096
29.3k
    cbytes = blosc2_schunk_get_lazychunk(schunk, nchunk, &chunk, &needs_free);
2097
29.3k
    if (cbytes < 0) {
2098
607
      BLOSC_TRACE_ERROR("Cannot get lazychunk ('%" PRId64 "').", nchunk);
2099
607
      return BLOSC2_ERROR_FAILURE;
2100
607
    }
2101
28.7k
    int32_t blocksize = sw32_(chunk + BLOSC2_CHUNK_BLOCKSIZE);
2102
28.7k
    if (blocksize <= 0) {
2103
0
      BLOSC_TRACE_ERROR("Corrupted chunk blocksize %d.", blocksize);
2104
0
      if (needs_free) {
2105
0
        free(chunk);
2106
0
      }
2107
0
      return BLOSC2_ERROR_DATA;
2108
0
    }
2109
2110
28.7k
    if (nchunk == (schunk->nchunks - 1) && schunk->nbytes % schunk->chunksize != 0) {
2111
1.26k
      chunksize = (int32_t) (schunk->nbytes % schunk->chunksize);
2112
1.26k
    }
2113
28.7k
    if (chunksize <= 0) {
2114
0
      BLOSC_TRACE_ERROR("Corrupted chunksize %d.", chunksize);
2115
0
      if (needs_free) {
2116
0
        free(chunk);
2117
0
      }
2118
0
      return BLOSC2_ERROR_DATA;
2119
0
    }
2120
2121
28.7k
    if (chunk_start == 0 && chunk_stop == chunksize) {
2122
      // Avoid memcpy
2123
2.65k
      nbytes = blosc2_decompress_ctx(schunk->dctx, chunk, cbytes, dst_ptr, chunksize);
2124
2.65k
      if (nbytes < 0) {
2125
336
        BLOSC_TRACE_ERROR("Cannot decompress chunk ('%" PRId64 "').", nchunk);
2126
336
        if (needs_free) {
2127
55
          free(chunk);
2128
55
        }
2129
336
        return BLOSC2_ERROR_FAILURE;
2130
336
      }
2131
2.65k
    }
2132
26.0k
    else {
2133
26.0k
      int32_t nbytes_wanted = chunk_stop - chunk_start;
2134
26.0k
      if (use_masked_slice_read(schunk, chunk, cbytes, blocksize, chunk_start, nbytes_wanted)) {
2135
0
        nbytes = masked_slice_read(schunk, chunk, cbytes, blocksize, chunk_start, nbytes_wanted, dst_ptr);
2136
0
        if (nbytes < 0) {
2137
0
          BLOSC_TRACE_ERROR("Cannot decompress chunk ('%" PRId64 "').", nchunk);
2138
0
          if (needs_free) {
2139
0
            free(chunk);
2140
0
          }
2141
0
          return BLOSC2_ERROR_FAILURE;
2142
0
        }
2143
0
      }
2144
26.0k
      else {
2145
        /* Few blocks to read; use a getitem call.  Counting in bytes
2146
           keeps this right for typesizes above BLOSC_MAX_TYPESIZE, which chunks
2147
           record as 1. */
2148
26.0k
        nbytes = blosc2_getitem_bytes_ctx(schunk->dctx, chunk, cbytes, chunk_start,
2149
26.0k
                                          nbytes_wanted, dst_ptr, nbytes_wanted);
2150
26.0k
        if (nbytes < 0) {
2151
12.5k
          BLOSC_TRACE_ERROR("Cannot get item from ('%" PRId64 "') chunk.", nchunk);
2152
12.5k
          if (needs_free) {
2153
54
            free(chunk);
2154
54
          }
2155
12.5k
          return BLOSC2_ERROR_FAILURE;
2156
12.5k
        }
2157
13.4k
        if (nbytes != nbytes_wanted) {
2158
0
          BLOSC_TRACE_ERROR("Short read (%d out of %d bytes) in ('%" PRId64 "') chunk.",
2159
0
                            nbytes, nbytes_wanted, nchunk);
2160
0
          if (needs_free) {
2161
0
            free(chunk);
2162
0
          }
2163
0
          return BLOSC2_ERROR_FAILURE;
2164
0
        }
2165
13.4k
      }
2166
26.0k
    }
2167
2168
15.8k
    dst_ptr += nbytes;
2169
15.8k
    nbytes_read += nbytes;
2170
15.8k
    nchunk++;
2171
2172
15.8k
    if (needs_free) {
2173
740
      free(chunk);
2174
740
    }
2175
15.8k
    chunk_start = 0;
2176
15.8k
    if (byte_stop >= (nchunk + 1) * chunksize) {
2177
1.70k
      chunk_stop = chunksize;
2178
1.70k
    }
2179
14.1k
    else {
2180
14.1k
      chunk_stop = (int32_t)(byte_stop % chunksize);
2181
14.1k
    }
2182
15.8k
  }
2183
2184
13.7k
  return BLOSC2_ERROR_SUCCESS;
2185
27.2k
}
2186
2187
2188
/* Start reading the chunks of items [start, stop) of a super-chunk in a frame on disk ahead (see
2189
   blosc2_set_prefetch()); NULL if read-ahead is off or does not apply */
2190
27.2k
static prefetch_batch* prefetch_items(blosc2_schunk *schunk, int64_t start, int64_t stop) {
2191
27.2k
  if (!prefetch_applies((blosc2_frame_s *) schunk->frame) || schunk->chunksize <= 0 || stop <= start) {
2192
27.2k
    return NULL;
2193
27.2k
  }
2194
0
  int64_t *nchunks = NULL;
2195
0
  int64_t n = schunk_get_slice_nchunks(schunk, start, stop, &nchunks);
2196
0
  prefetch_batch *batch = prefetch_batch_new((blosc2_frame_s *) schunk->frame, nchunks, n, NULL, 0);
2197
0
  free(nchunks);
2198
0
  return batch;
2199
27.2k
}
2200
2201
2202
27.2k
int blosc2_schunk_get_slice_buffer(blosc2_schunk *schunk, int64_t start, int64_t stop, void *buffer) {
2203
27.2k
  BLOSC_ERROR_NULL(schunk, BLOSC2_ERROR_NULL_POINTER);
2204
27.2k
  BLOSC_ERROR_NULL(buffer, BLOSC2_ERROR_NULL_POINTER);
2205
27.2k
  if (start < 0 || stop < start) {
2206
0
    BLOSC_TRACE_ERROR("Invalid slice bounds (start=%" PRId64 ", stop=%" PRId64 ").", start, stop);
2207
0
    return BLOSC2_ERROR_INVALID_PARAM;
2208
0
  }
2209
27.2k
  if (stop == start) {
2210
0
    return BLOSC2_ERROR_SUCCESS;
2211
0
  }
2212
27.2k
  if (schunk->typesize <= 0) {
2213
0
    BLOSC_TRACE_ERROR("schunk must have a positive typesize.");
2214
0
    return BLOSC2_ERROR_INVALID_PARAM;
2215
0
  }
2216
27.2k
  if (schunk->chunksize <= 0) {
2217
0
    BLOSC_TRACE_ERROR("blosc2_schunk_get_slice_buffer does not support variable-length chunks yet.");
2218
0
    return BLOSC2_ERROR_INVALID_PARAM;
2219
0
  }
2220
2221
  // With locking on, hold the shared frame lock from the refresh to the last chunk read, as
2222
  // b2nd_get_slice_cbuffer() does: with a lock per chunk access, a writer could change the
2223
  // frame between two chunks of the slice, or between reading a lazy chunk and its blocks.
2224
  // Unlocked handles keep SWMR's transient errors, and skip the refresh.
2225
27.2k
  blosc2_frame_s *frame = (blosc2_frame_s *) schunk->frame;
2226
27.2k
  int rc = frame_lock(frame, false);
2227
27.2k
  if (rc < 0) {
2228
0
    return rc;
2229
0
  }
2230
27.2k
  if (frame != NULL && frame->locking) {
2231
0
    rc = frame_check_stale(frame);
2232
0
  }
2233
27.2k
  if (rc >= 0) {
2234
27.2k
    prefetch_batch *prefetch = prefetch_items(schunk, start, stop);
2235
27.2k
    rc = schunk_get_slice_buffer_unlocked(schunk, start, stop, buffer, prefetch);
2236
27.2k
    prefetch_batch_free(prefetch);
2237
27.2k
  }
2238
27.2k
  frame_unlock(frame);
2239
27.2k
  return rc;
2240
27.2k
}
2241
2242
2243
typedef struct {
2244
  int64_t coord;
2245
  int64_t out_index;
2246
} sparse_coord_entry;
2247
2248
typedef struct {
2249
  int64_t nchunk;
2250
  uint8_t *chunk;
2251
  int cbytes;
2252
  bool needs_free;
2253
} sparse_chunk_entry;
2254
2255
typedef struct {
2256
  int64_t first;
2257
  int64_t count;
2258
  int64_t chunk_index;
2259
  int32_t nblock;
2260
} sparse_block_task;
2261
2262
typedef struct {
2263
  const sparse_coord_entry *entries;
2264
  const sparse_block_task *tasks;
2265
  const sparse_chunk_entry *chunks;
2266
  int64_t ntasks;
2267
  uint8_t *buffer;
2268
  int32_t typesize;
2269
  int32_t blocksize;
2270
  int64_t chunk_nitems;
2271
  int64_t next_task;
2272
  int error;
2273
  blosc2_pthread_mutex_t mutex;
2274
} sparse_work;
2275
2276
typedef struct {
2277
  sparse_work *work;
2278
  blosc2_context *dctx;
2279
  uint8_t *block;
2280
} sparse_worker;
2281
2282
0
static int sparse_coord_entry_cmp(const void *a, const void *b) {
2283
0
  const sparse_coord_entry *ea = (const sparse_coord_entry *)a;
2284
0
  const sparse_coord_entry *eb = (const sparse_coord_entry *)b;
2285
0
  if (ea->coord < eb->coord) return -1;
2286
0
  if (ea->coord > eb->coord) return 1;
2287
0
  if (ea->out_index < eb->out_index) return -1;
2288
0
  if (ea->out_index > eb->out_index) return 1;
2289
0
  return 0;
2290
0
}
2291
2292
0
static void sparse_work_set_error(sparse_work *work, int error) {
2293
0
  blosc2_pthread_mutex_lock(&work->mutex);
2294
0
  if (work->error == 0) {
2295
0
    work->error = error;
2296
0
  }
2297
0
  blosc2_pthread_mutex_unlock(&work->mutex);
2298
0
}
2299
2300
0
static void sparse_worker_func(void *arg) {
2301
0
  sparse_worker *worker = (sparse_worker *)arg;
2302
0
  sparse_work *work = worker->work;
2303
2304
0
  while (true) {
2305
0
    blosc2_pthread_mutex_lock(&work->mutex);
2306
0
    if (work->error < 0 || work->next_task >= work->ntasks) {
2307
0
      blosc2_pthread_mutex_unlock(&work->mutex);
2308
0
      break;
2309
0
    }
2310
0
    int64_t task_index = work->next_task++;
2311
0
    blosc2_pthread_mutex_unlock(&work->mutex);
2312
2313
0
    const sparse_block_task *task = &work->tasks[task_index];
2314
0
    const sparse_chunk_entry *chunk_entry = &work->chunks[task->chunk_index];
2315
0
    int nbytes = blosc2_decompress_block_ctx(worker->dctx, chunk_entry->chunk, chunk_entry->cbytes,
2316
0
                                             task->nblock, worker->block, work->blocksize);
2317
0
    if (nbytes < 0) {
2318
0
      sparse_work_set_error(work, nbytes);
2319
0
      break;
2320
0
    }
2321
2322
0
    for (int64_t i = task->first; i < task->first + task->count; ++i) {
2323
0
      const sparse_coord_entry *entry = &work->entries[i];
2324
0
      int64_t item_in_chunk = entry->coord % work->chunk_nitems;
2325
0
      int64_t byte_in_chunk = item_in_chunk * work->typesize;
2326
0
      int32_t block_offset = (int32_t)(byte_in_chunk % work->blocksize);
2327
0
      if (block_offset < 0 || block_offset > nbytes - work->typesize) {
2328
0
        sparse_work_set_error(work, BLOSC2_ERROR_DATA);
2329
0
        return;
2330
0
      }
2331
0
      memcpy(work->buffer + entry->out_index * work->typesize,
2332
0
             worker->block + block_offset,
2333
0
             (size_t)work->typesize);
2334
0
    }
2335
0
  }
2336
2337
0
  return;
2338
0
}
2339
2340
0
static int schunk_get_sparse_getitem(blosc2_schunk *schunk, int64_t ncoords, const int64_t* coords, void *buffer) {
2341
0
  int64_t nitems = schunk->nbytes / schunk->typesize;
2342
0
  int64_t chunk_nitems = schunk->chunksize / schunk->typesize;
2343
0
  uint8_t *dst_ptr = (uint8_t *)buffer;
2344
2345
0
  for (int64_t i = 0; i < ncoords; ++i) {
2346
0
    int64_t coord = coords[i];
2347
0
    if (coord < 0 || coord >= nitems) {
2348
0
      BLOSC_TRACE_ERROR("Coordinate out of bounds.");
2349
0
      return BLOSC2_ERROR_INVALID_PARAM;
2350
0
    }
2351
2352
0
    int64_t nchunk = coord / chunk_nitems;
2353
    // count in bytes, so that a typesize above BLOSC_MAX_TYPESIZE (which chunks
2354
    // record as 1) needs no special casing here
2355
0
    int32_t start = (int32_t)((coord % chunk_nitems) * schunk->typesize);
2356
0
    uint8_t *chunk = NULL;
2357
0
    bool needs_free = false;
2358
0
    int cbytes = blosc2_schunk_get_lazychunk(schunk, nchunk, &chunk, &needs_free);
2359
0
    if (cbytes <= 0) {
2360
0
      BLOSC_TRACE_ERROR("Cannot get lazychunk ('%" PRId64 "').", nchunk);
2361
0
      return BLOSC2_ERROR_FAILURE;
2362
0
    }
2363
2364
0
    int nbytes = blosc2_getitem_bytes_ctx(schunk->dctx, chunk, cbytes, start,
2365
0
                                          schunk->typesize, dst_ptr, schunk->typesize);
2366
0
    if (needs_free) {
2367
0
      free(chunk);
2368
0
    }
2369
0
    if (nbytes != schunk->typesize) {
2370
0
      BLOSC_TRACE_ERROR("Cannot get item from ('%" PRId64 "') chunk.", nchunk);
2371
0
      return BLOSC2_ERROR_FAILURE;
2372
0
    }
2373
0
    dst_ptr += schunk->typesize;
2374
0
  }
2375
2376
0
  return BLOSC2_ERROR_SUCCESS;
2377
0
}
2378
2379
0
int blosc2_schunk_get_sparse_buffer(blosc2_schunk *schunk, int64_t ncoords, const int64_t* coords, void *buffer) {
2380
0
  if (schunk == NULL) {
2381
0
    BLOSC_TRACE_ERROR("schunk must not be NULL.");
2382
0
    return BLOSC2_ERROR_INVALID_PARAM;
2383
0
  }
2384
0
  if (ncoords < 0) {
2385
0
    BLOSC_TRACE_ERROR("ncoords must be non-negative.");
2386
0
    return BLOSC2_ERROR_INVALID_PARAM;
2387
0
  }
2388
0
  if (ncoords == 0) {
2389
0
    return BLOSC2_ERROR_SUCCESS;
2390
0
  }
2391
0
  if (coords == NULL || buffer == NULL) {
2392
0
    BLOSC_TRACE_ERROR("coords and buffer must not be NULL when ncoords > 0.");
2393
0
    return BLOSC2_ERROR_INVALID_PARAM;
2394
0
  }
2395
0
  if (schunk->typesize <= 0) {
2396
0
    BLOSC_TRACE_ERROR("schunk must have a positive typesize.");
2397
0
    return BLOSC2_ERROR_INVALID_PARAM;
2398
0
  }
2399
0
  if (schunk->chunksize <= 0) {
2400
0
    BLOSC_TRACE_ERROR("blosc2_schunk_get_sparse_buffer does not support variable-length chunks yet.");
2401
0
    return BLOSC2_ERROR_INVALID_PARAM;
2402
0
  }
2403
0
  if (schunk->blocksize <= 0 || (schunk->flags2 & BLOSC2_VL_BLOCKS)) {
2404
0
    BLOSC_TRACE_ERROR("blosc2_schunk_get_sparse_buffer does not support variable-length blocks yet.");
2405
0
    return BLOSC2_ERROR_INVALID_PARAM;
2406
0
  }
2407
0
  if ((schunk->chunksize % schunk->typesize) != 0 || (schunk->blocksize % schunk->typesize) != 0) {
2408
0
    BLOSC_TRACE_ERROR("chunksize and blocksize must be multiples of typesize.");
2409
0
    return BLOSC2_ERROR_INVALID_PARAM;
2410
0
  }
2411
2412
0
  if (filters_contain(schunk->filters, BLOSC_DELTA) ||
2413
0
      (schunk->dctx != NULL && schunk->dctx->postfilter != NULL)) {
2414
0
    return schunk_get_sparse_getitem(schunk, ncoords, coords, buffer);
2415
0
  }
2416
0
  if (ncoords <= 1) {
2417
0
    return schunk_get_sparse_getitem(schunk, ncoords, coords, buffer);
2418
0
  }
2419
2420
0
  int rc = BLOSC2_ERROR_SUCCESS;
2421
0
  int64_t nitems = schunk->nbytes / schunk->typesize;
2422
0
  int64_t chunk_nitems = schunk->chunksize / schunk->typesize;
2423
0
  sparse_coord_entry *entries = NULL;
2424
0
  sparse_block_task *tasks = NULL;
2425
0
  sparse_chunk_entry *chunks = NULL;
2426
0
  sparse_worker *workers = NULL;
2427
0
  int16_t nthreads = 1;
2428
0
  int64_t ntasks = 0;
2429
0
  int64_t nchunks = 0;
2430
0
  sparse_work work;
2431
0
  memset(&work, 0, sizeof(work));
2432
2433
0
  if (chunk_nitems <= 0 || chunk_nitems > INT32_MAX) {
2434
0
    BLOSC_TRACE_ERROR("Invalid chunk item count.");
2435
0
    return BLOSC2_ERROR_INVALID_PARAM;
2436
0
  }
2437
2438
0
  entries = calloc((size_t)ncoords, sizeof(sparse_coord_entry));
2439
0
  if (entries == NULL) {
2440
0
    rc = BLOSC2_ERROR_MEMORY_ALLOC;
2441
0
    goto cleanup;
2442
0
  }
2443
2444
0
  for (int64_t i = 0; i < ncoords; ++i) {
2445
0
    int64_t coord = coords[i];
2446
0
    if (coord < 0 || coord >= nitems) {
2447
0
      BLOSC_TRACE_ERROR("Coordinate out of bounds.");
2448
0
      rc = BLOSC2_ERROR_INVALID_PARAM;
2449
0
      goto cleanup;
2450
0
    }
2451
0
    entries[i].coord = coord;
2452
0
    entries[i].out_index = i;
2453
0
  }
2454
2455
0
  qsort(entries, (size_t)ncoords, sizeof(sparse_coord_entry), sparse_coord_entry_cmp);
2456
2457
  /* First pass over sorted entries: count touched chunks and selected block tasks. */
2458
0
  for (int64_t i = 0; i < ncoords;) {
2459
0
    int64_t nchunk = entries[i].coord / chunk_nitems;
2460
0
    ++nchunks;
2461
0
    while (i < ncoords && entries[i].coord / chunk_nitems == nchunk) {
2462
0
      int64_t item_in_chunk = entries[i].coord % chunk_nitems;
2463
0
      int64_t byte_in_chunk = item_in_chunk * schunk->typesize;
2464
0
      int32_t nblock = (int32_t)(byte_in_chunk / schunk->blocksize);
2465
0
      while (i < ncoords &&
2466
0
             entries[i].coord / chunk_nitems == nchunk &&
2467
0
             (int32_t)(((entries[i].coord % chunk_nitems) * schunk->typesize) / schunk->blocksize) == nblock) {
2468
0
        ++i;
2469
0
      }
2470
0
      ++ntasks;
2471
0
    }
2472
0
  }
2473
2474
0
  tasks = calloc((size_t)ntasks, sizeof(sparse_block_task));
2475
0
  chunks = calloc((size_t)nchunks, sizeof(sparse_chunk_entry));
2476
0
  if (tasks == NULL || chunks == NULL) {
2477
0
    rc = BLOSC2_ERROR_MEMORY_ALLOC;
2478
0
    goto cleanup;
2479
0
  }
2480
2481
  /* Second pass: fetch touched chunks and build one task per selected block. */
2482
0
  int64_t chunk_index = 0;
2483
0
  int64_t task_index = 0;
2484
0
  for (int64_t i = 0; i < ncoords;) {
2485
0
    int64_t nchunk = entries[i].coord / chunk_nitems;
2486
0
    uint8_t *chunk = NULL;
2487
0
    bool needs_free = false;
2488
0
    int cbytes = blosc2_schunk_get_lazychunk(schunk, nchunk, &chunk, &needs_free);
2489
0
    if (cbytes <= 0) {
2490
0
      BLOSC_TRACE_ERROR("Cannot get lazychunk ('%" PRId64 "').", nchunk);
2491
0
      rc = BLOSC2_ERROR_FAILURE;
2492
0
      goto cleanup;
2493
0
    }
2494
0
    chunks[chunk_index].nchunk = nchunk;
2495
0
    chunks[chunk_index].chunk = chunk;
2496
0
    chunks[chunk_index].cbytes = cbytes;
2497
0
    chunks[chunk_index].needs_free = needs_free;
2498
2499
0
    while (i < ncoords && entries[i].coord / chunk_nitems == nchunk) {
2500
0
      int64_t item_in_chunk = entries[i].coord % chunk_nitems;
2501
0
      int64_t byte_in_chunk = item_in_chunk * schunk->typesize;
2502
0
      int32_t nblock = (int32_t)(byte_in_chunk / schunk->blocksize);
2503
0
      int64_t first = i;
2504
0
      while (i < ncoords &&
2505
0
             entries[i].coord / chunk_nitems == nchunk &&
2506
0
             (int32_t)(((entries[i].coord % chunk_nitems) * schunk->typesize) / schunk->blocksize) == nblock) {
2507
0
        ++i;
2508
0
      }
2509
0
      tasks[task_index].first = first;
2510
0
      tasks[task_index].count = i - first;
2511
0
      tasks[task_index].chunk_index = chunk_index;
2512
0
      tasks[task_index].nblock = nblock;
2513
0
      ++task_index;
2514
0
    }
2515
0
    ++chunk_index;
2516
0
  }
2517
2518
0
  nthreads = schunk->dctx != NULL ? schunk->dctx->nthreads : blosc2_get_nthreads();
2519
0
  if (nthreads < 1) {
2520
0
    nthreads = 1;
2521
0
  }
2522
0
  if ((int64_t)nthreads > ntasks) {
2523
0
    nthreads = (int16_t)ntasks;
2524
0
  }
2525
2526
0
  workers = calloc((size_t)nthreads, sizeof(sparse_worker));
2527
0
  if (workers == NULL) {
2528
0
    rc = BLOSC2_ERROR_MEMORY_ALLOC;
2529
0
    goto cleanup;
2530
0
  }
2531
2532
0
  work.entries = entries;
2533
0
  work.tasks = tasks;
2534
0
  work.chunks = chunks;
2535
0
  work.ntasks = ntasks;
2536
0
  work.buffer = (uint8_t *)buffer;
2537
0
  work.typesize = schunk->typesize;
2538
0
  work.blocksize = schunk->blocksize;
2539
0
  work.chunk_nitems = chunk_nitems;
2540
0
  work.next_task = 0;
2541
0
  work.error = 0;
2542
0
  blosc2_pthread_mutex_init(&work.mutex, NULL);
2543
2544
0
  for (int16_t i = 0; i < nthreads; ++i) {
2545
0
    blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS;
2546
0
    dparams.nthreads = 1;
2547
0
    dparams.schunk = schunk;
2548
0
    workers[i].work = &work;
2549
0
    workers[i].dctx = blosc2_create_dctx(dparams);
2550
0
    workers[i].block = malloc((size_t)schunk->blocksize);
2551
0
    if (workers[i].dctx == NULL || workers[i].block == NULL) {
2552
0
      rc = BLOSC2_ERROR_MEMORY_ALLOC;
2553
0
      goto cleanup_work_mutex;
2554
0
    }
2555
0
  }
2556
2557
0
  if (nthreads == 1) {
2558
0
    sparse_worker_func(&workers[0]);
2559
0
  }
2560
0
  else {
2561
0
    int err = blosc2_run_parallel(nthreads, sparse_worker_func, sizeof(sparse_worker), workers);
2562
0
    if (err < 0) {
2563
0
      sparse_work_set_error(&work, err);
2564
0
    }
2565
0
  }
2566
2567
0
  if (work.error < 0) {
2568
0
    rc = work.error;
2569
0
  }
2570
2571
0
cleanup_work_mutex:
2572
0
  blosc2_pthread_mutex_destroy(&work.mutex);
2573
0
cleanup:
2574
0
  if (workers != NULL) {
2575
0
    int16_t nworkers = nthreads > 0 ? nthreads : 1;
2576
0
    for (int16_t i = 0; i < nworkers; ++i) {
2577
0
      if (workers[i].dctx != NULL) {
2578
0
        blosc2_free_ctx(workers[i].dctx);
2579
0
      }
2580
0
      free(workers[i].block);
2581
0
    }
2582
0
  }
2583
0
  if (chunks != NULL) {
2584
0
    for (int64_t i = 0; i < nchunks; ++i) {
2585
0
      if (chunks[i].needs_free) {
2586
0
        free(chunks[i].chunk);
2587
0
      }
2588
0
    }
2589
0
  }
2590
0
  free(workers);
2591
0
  free(chunks);
2592
0
  free(tasks);
2593
0
  free(entries);
2594
2595
0
  return rc;
2596
0
}
2597
2598
2599
0
static int schunk_set_slice_buffer(blosc2_schunk *schunk, int64_t start, int64_t stop, void *buffer) {
2600
0
  BLOSC_ERROR_NULL(schunk, BLOSC2_ERROR_NULL_POINTER);
2601
0
  BLOSC_ERROR_NULL(buffer, BLOSC2_ERROR_NULL_POINTER);
2602
0
  if (start < 0 || stop < start) {
2603
0
    BLOSC_TRACE_ERROR("Invalid slice bounds (start=%" PRId64 ", stop=%" PRId64 ").", start, stop);
2604
0
    return BLOSC2_ERROR_INVALID_PARAM;
2605
0
  }
2606
0
  if (stop == start) {
2607
0
    return BLOSC2_ERROR_SUCCESS;
2608
0
  }
2609
0
  if (schunk->typesize <= 0) {
2610
0
    BLOSC_TRACE_ERROR("schunk must have a positive typesize.");
2611
0
    return BLOSC2_ERROR_INVALID_PARAM;
2612
0
  }
2613
0
  if (schunk->chunksize <= 0) {
2614
0
    BLOSC_TRACE_ERROR("blosc2_schunk_set_slice_buffer does not support variable-length chunks yet.");
2615
0
    return BLOSC2_ERROR_INVALID_PARAM;
2616
0
  }
2617
2618
0
  int64_t byte_start = start * schunk->typesize;
2619
0
  int64_t byte_stop = stop * schunk->typesize;
2620
0
  int64_t nchunk_start = byte_start / schunk->chunksize;
2621
0
  int32_t chunk_start = (int32_t) (byte_start % schunk->chunksize);
2622
0
  int32_t chunk_stop;
2623
0
  if (byte_stop >= (nchunk_start + 1) * schunk->chunksize) {
2624
0
    chunk_stop = schunk->chunksize;
2625
0
  }
2626
0
  else {
2627
0
    chunk_stop = (int32_t) (byte_stop % schunk->chunksize);
2628
0
  }
2629
2630
0
  uint8_t *src_ptr = (uint8_t *) buffer;
2631
0
  int64_t nchunk = nchunk_start;
2632
0
  int64_t nbytes_written = 0;
2633
0
  int32_t nbytes;
2634
0
  uint8_t *data = malloc(schunk->chunksize);
2635
0
  if (data == NULL) {
2636
0
    BLOSC_TRACE_ERROR("Cannot allocate temporary buffer.");
2637
0
    return BLOSC2_ERROR_MEMORY_ALLOC;
2638
0
  }
2639
0
  int64_t nchunks;
2640
0
  int32_t chunksize = schunk->chunksize;
2641
2642
0
  while (nbytes_written < ((stop - start) * schunk->typesize)) {
2643
0
    if (chunksize <= 0) {
2644
0
      BLOSC_TRACE_ERROR("Corrupted chunksize %d.", chunksize);
2645
0
      free(data);
2646
0
      return BLOSC2_ERROR_DATA;
2647
0
    }
2648
0
    if (chunk_start == 0 &&
2649
0
        (chunk_stop == schunk->chunksize || chunk_stop == schunk->nbytes % schunk->chunksize)) {
2650
0
      if (chunk_stop == schunk->nbytes % schunk->chunksize) {
2651
0
        chunksize = chunk_stop;
2652
0
      }
2653
0
      nchunks = schunk_compress_store(schunk, nchunk, src_ptr, chunksize, WRITE_UPDATE,
2654
0
                                      "blosc2_schunk_set_slice_buffer");
2655
0
      if (nchunks != schunk->nchunks) {
2656
0
        BLOSC_TRACE_ERROR("Cannot update chunk ('%" PRId64 "').", nchunk);
2657
0
        free(data);
2658
0
        return nchunks < 0 ? (int) nchunks : BLOSC2_ERROR_CHUNK_UPDATE;
2659
0
      }
2660
0
    }
2661
0
    else {
2662
0
      nbytes = blosc2_schunk_decompress_chunk(schunk, nchunk, data, schunk->chunksize);
2663
0
      if (nbytes < 0) {
2664
0
        BLOSC_TRACE_ERROR("Cannot decompress chunk ('%" PRId64 "').", nchunk);
2665
0
        free(data);
2666
0
        return BLOSC2_ERROR_FAILURE;
2667
0
      }
2668
0
      memcpy(&data[chunk_start], src_ptr, chunk_stop - chunk_start);
2669
0
      nchunks = schunk_compress_store(schunk, nchunk, data, nbytes, WRITE_UPDATE,
2670
0
                                      "blosc2_schunk_set_slice_buffer");
2671
0
      if (nchunks != schunk->nchunks) {
2672
0
        BLOSC_TRACE_ERROR("Cannot update chunk ('%" PRId64 "').", nchunk);
2673
0
        free(data);
2674
0
        return nchunks < 0 ? (int) nchunks : BLOSC2_ERROR_CHUNK_UPDATE;
2675
0
      }
2676
0
    }
2677
0
    nchunk++;
2678
0
    nbytes_written += chunk_stop - chunk_start;
2679
0
    src_ptr += chunk_stop - chunk_start;
2680
0
    chunk_start = 0;
2681
0
    if (byte_stop >= (nchunk + 1) * schunk->chunksize) {
2682
0
      chunk_stop = schunk->chunksize;
2683
0
    }
2684
0
    else {
2685
0
      chunk_stop = (int32_t) (byte_stop % schunk->chunksize);
2686
0
    }
2687
0
  }
2688
0
  free(data);
2689
2690
0
  return BLOSC2_ERROR_SUCCESS;
2691
0
}
2692
2693
2694
0
int blosc2_schunk_set_slice_buffer(blosc2_schunk *schunk, int64_t start, int64_t stop, void *buffer) {
2695
0
  BLOSC_ERROR_NULL(schunk, BLOSC2_ERROR_NULL_POINTER);
2696
  // One exclusive lock and one compaction for all the chunks written (see blosc2_schunk_begin_updates())
2697
0
  BLOSC_ERROR(blosc2_schunk_begin_updates(schunk));
2698
0
  int rc = schunk_set_slice_buffer(schunk, start, stop, buffer);
2699
0
  int end_rc = blosc2_schunk_end_updates(schunk);
2700
0
  return rc < 0 ? rc : end_rc;
2701
0
}
2702
2703
2704
0
int64_t schunk_get_slice_nchunks(blosc2_schunk *schunk, int64_t start, int64_t stop, int64_t **chunks_idx) {
2705
0
  BLOSC_ERROR_NULL(schunk, BLOSC2_ERROR_NULL_POINTER);
2706
0
  BLOSC_ERROR_NULL(chunks_idx, BLOSC2_ERROR_NULL_POINTER);
2707
0
  if (start < 0 || stop < start) {
2708
0
    BLOSC_TRACE_ERROR("Invalid slice bounds (start=%" PRId64 ", stop=%" PRId64 ").", start, stop);
2709
0
    return BLOSC2_ERROR_INVALID_PARAM;
2710
0
  }
2711
0
  if (schunk->nchunks == 0 || stop == start) {
2712
0
    *chunks_idx = NULL;
2713
0
    return 0;
2714
0
  }
2715
0
  if (schunk->typesize <= 0) {
2716
0
    BLOSC_TRACE_ERROR("schunk must have a positive typesize.");
2717
0
    return BLOSC2_ERROR_INVALID_PARAM;
2718
0
  }
2719
0
  if (schunk->chunksize <= 0) {
2720
0
    BLOSC_TRACE_ERROR("schunk_get_slice_nchunks does not support variable-length chunks yet.");
2721
0
    return BLOSC2_ERROR_INVALID_PARAM;
2722
0
  }
2723
0
  int64_t byte_start = start * schunk->typesize;
2724
0
  int64_t byte_stop = stop * schunk->typesize;
2725
0
  int64_t nchunk_start = byte_start / schunk->chunksize;
2726
0
  int64_t nchunk_stop = byte_stop / schunk->chunksize;
2727
0
  if (byte_stop % schunk->chunksize != 0) {
2728
0
    nchunk_stop++;
2729
0
  }
2730
0
  int64_t nchunk = nchunk_start;
2731
0
  int64_t nchunks = nchunk_stop - nchunk_start;
2732
0
  *chunks_idx = malloc(nchunks * sizeof(int64_t));
2733
0
  int64_t *ptr = *chunks_idx;
2734
0
  for (int64_t i = 0; i < nchunks; ++i) {
2735
0
    ptr[i] = nchunk;
2736
0
    nchunk++;
2737
0
  }
2738
0
  return nchunks;
2739
0
}
2740
2741
/* Reorder the chunk offsets of an existing super-chunk. */
2742
0
int blosc2_schunk_reorder_offsets(blosc2_schunk *schunk, int64_t *offsets_order) {
2743
  // Check that the offsets order are correct
2744
0
  bool *index_check = (bool *) calloc(schunk->nchunks, sizeof(bool));
2745
0
  for (int i = 0; i < schunk->nchunks; ++i) {
2746
0
    int64_t index = offsets_order[i];
2747
0
    if (index < 0 || index >= schunk->nchunks) {
2748
0
      BLOSC_TRACE_ERROR("Index is out of range (negative or >= number of chunks).");
2749
0
      free(index_check);
2750
0
      return BLOSC2_ERROR_DATA;
2751
0
    }
2752
0
    if (index_check[index] == false) {
2753
0
      index_check[index] = true;
2754
0
    } else {
2755
0
      BLOSC_TRACE_ERROR("Index is yet used.");
2756
0
      free(index_check);
2757
0
      return BLOSC2_ERROR_DATA;
2758
0
    }
2759
0
  }
2760
0
  free(index_check);
2761
2762
0
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
2763
0
  if (frame != NULL) {
2764
0
    int rc = frame_lock(frame, true);
2765
0
    if (rc < 0) {
2766
0
      return rc;
2767
0
    }
2768
0
    rc = frame_reorder_offsets(frame, offsets_order, schunk);
2769
0
    frame_unlock(frame);
2770
0
    return rc;
2771
0
  }
2772
0
  uint8_t **offsets = schunk->data;
2773
2774
  // Make a copy of the chunk offsets and reorder it
2775
0
  uint8_t **offsets_copy = malloc(schunk->data_len);
2776
0
  memcpy(offsets_copy, offsets, schunk->data_len);
2777
2778
0
  for (int i = 0; i < schunk->nchunks; ++i) {
2779
0
    offsets[i] = offsets_copy[offsets_order[i]];
2780
0
  }
2781
0
  free(offsets_copy);
2782
2783
0
  return 0;
2784
0
}
2785
2786
2787
// Get the length (in bytes) of the internal frame of the super-chunk
2788
0
int64_t blosc2_schunk_frame_len(blosc2_schunk* schunk) {
2789
0
  int64_t len;
2790
0
  blosc2_frame_s* frame_s = (blosc2_frame_s*)(schunk->frame);
2791
0
  if (frame_s != NULL) {
2792
0
    len = frame_s->len;
2793
0
  }
2794
0
  else {
2795
    // No attached frame, but we can still come with an estimate
2796
0
    len = (int64_t) (schunk->cbytes + schunk->nchunks * sizeof(int64_t));
2797
0
  }
2798
2799
0
  return len;
2800
0
}
2801
2802
2803
/**
2804
 * @brief Flush metalayers content into a possible attached frame.
2805
 *
2806
 * @param schunk The super-chunk to which the flush should be applied.
2807
 *
2808
 * @return If successful, a 0 is returned. Else, return a negative value.
2809
 */
2810
// Initially, this was a public function, but as it is really meant to be used only
2811
// in the schunk_add_metalayer(), I decided to convert it into private and call it
2812
// implicitly instead of requiring the user to do so.  The only drawback is that
2813
// each add operation requires a complete frame re-build, but as users should need
2814
// very few metalayers, this overhead should be negligible in practice.
2815
15.0k
int metalayer_flush(blosc2_schunk* schunk) {
2816
15.0k
  int rc = BLOSC2_ERROR_SUCCESS;
2817
15.0k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
2818
15.0k
  if (frame == NULL) {
2819
6.22k
    return rc;
2820
6.22k
  }
2821
8.86k
  rc = frame_lock(frame, true);
2822
8.86k
  if (rc < 0) {
2823
0
    return rc;
2824
0
  }
2825
8.86k
  rc = frame_update_header(frame, schunk, true);
2826
8.86k
  if (rc < 0) {
2827
4.33k
    BLOSC_TRACE_ERROR("Unable to update metalayers into frame.");
2828
4.33k
    frame_unlock(frame);
2829
4.33k
    return rc;
2830
4.33k
  }
2831
4.52k
  rc = frame_update_trailer(frame, schunk);
2832
4.52k
  if (rc < 0) {
2833
13
    BLOSC_TRACE_ERROR("Unable to update trailer into frame.");
2834
13
    frame_unlock(frame);
2835
13
    return rc;
2836
13
  }
2837
4.51k
  frame_unlock(frame);
2838
4.51k
  return rc;
2839
4.52k
}
2840
2841
2842
/* Add content into a new metalayer.
2843
 *
2844
 * If successful, return the index of the new metalayer.  Else, return a negative value.
2845
 */
2846
15.0k
int blosc2_meta_add(blosc2_schunk *schunk, const char *name, uint8_t *content, int32_t content_len) {
2847
15.0k
  if (schunk == NULL || name == NULL) {
2848
0
    BLOSC_TRACE_ERROR("Invalid parameters.");
2849
0
    return BLOSC2_ERROR_INVALID_PARAM;
2850
0
  }
2851
15.0k
  int nmetalayer = blosc2_meta_exists(schunk, name);
2852
15.0k
  if (nmetalayer >= 0) {
2853
0
    BLOSC_TRACE_ERROR("Metalayer \"%s\" already exists.", name);
2854
0
    return BLOSC2_ERROR_INVALID_PARAM;
2855
0
  }
2856
15.0k
  if (content_len < 0) {
2857
0
    BLOSC_TRACE_ERROR("Metalayer content length must not be negative.");
2858
0
    return BLOSC2_ERROR_INVALID_PARAM;
2859
0
  }
2860
15.0k
  if (content_len > 0 && content == NULL) {
2861
0
    BLOSC_TRACE_ERROR("Metalayer content pointer must not be NULL when content length is positive.");
2862
0
    return BLOSC2_ERROR_INVALID_PARAM;
2863
0
  }
2864
2865
  // Add the metalayer
2866
15.0k
  blosc2_metalayer *metalayer = malloc(sizeof(blosc2_metalayer));
2867
15.0k
  BLOSC_ERROR_NULL(metalayer, BLOSC2_ERROR_MEMORY_ALLOC);
2868
2869
15.0k
  char* name_ = malloc(strlen(name) + 1);
2870
15.0k
  if (name_ == NULL) {
2871
0
    free(metalayer);
2872
0
    BLOSC_TRACE_ERROR("Unable to allocate metalayer name buffer.");
2873
0
    return BLOSC2_ERROR_MEMORY_ALLOC;
2874
0
  }
2875
15.0k
  strcpy(name_, name);
2876
15.0k
  metalayer->name = name_;
2877
2878
15.0k
  uint8_t* content_buf = malloc((size_t)content_len);
2879
15.0k
  if (content_buf == NULL && content_len > 0) {
2880
0
    free(name_);
2881
0
    free(metalayer);
2882
0
    BLOSC_TRACE_ERROR("Unable to allocate metalayer content buffer.");
2883
0
    return BLOSC2_ERROR_MEMORY_ALLOC;
2884
0
  }
2885
15.0k
  if (content_len > 0) {
2886
15.0k
    memcpy(content_buf, content, content_len);
2887
15.0k
  }
2888
15.0k
  metalayer->content = content_buf;
2889
15.0k
  metalayer->content_len = content_len;
2890
15.0k
  schunk->metalayers[schunk->nmetalayers] = metalayer;
2891
15.0k
  schunk->nmetalayers += 1;
2892
2893
15.0k
  int rc = metalayer_flush(schunk);
2894
15.0k
  if (rc < 0) {
2895
4.35k
    return rc;
2896
4.35k
  }
2897
10.7k
  schunk->change_tick++;
2898
2899
10.7k
  return schunk->nmetalayers - 1;
2900
15.0k
}
2901
2902
2903
/* Update the content of an existing metalayer.
2904
 *
2905
 * If successful, return the index of the new metalayer.  Else, return a negative value.
2906
 */
2907
2.40k
int blosc2_meta_update(blosc2_schunk *schunk, const char *name, uint8_t *content, int32_t content_len) {
2908
2.40k
  if (schunk == NULL || name == NULL) {
2909
0
    BLOSC_TRACE_ERROR("Invalid parameters.");
2910
0
    return BLOSC2_ERROR_INVALID_PARAM;
2911
0
  }
2912
2.40k
  int nmetalayer = blosc2_meta_exists(schunk, name);
2913
2.40k
  if (nmetalayer < 0) {
2914
0
    BLOSC_TRACE_ERROR("Metalayer \"%s\" not found.", name);
2915
0
    return nmetalayer;
2916
0
  }
2917
2.40k
  if (content_len < 0) {
2918
0
    BLOSC_TRACE_ERROR("Metalayer content length must not be negative.");
2919
0
    return BLOSC2_ERROR_INVALID_PARAM;
2920
0
  }
2921
2.40k
  if (content_len > 0 && content == NULL) {
2922
0
    BLOSC_TRACE_ERROR("Metalayer content pointer must not be NULL when content length is positive.");
2923
0
    return BLOSC2_ERROR_INVALID_PARAM;
2924
0
  }
2925
2926
2.40k
  blosc2_metalayer *metalayer = schunk->metalayers[nmetalayer];
2927
2.40k
  if (content_len > metalayer->content_len) {
2928
208
    BLOSC_TRACE_ERROR("`content_len` cannot exceed the existing size of %d bytes.", metalayer->content_len);
2929
208
    return nmetalayer;
2930
208
  }
2931
2932
  // Update the contents of the metalayer
2933
2.19k
  if (content_len > 0) {
2934
2.19k
    memmove(metalayer->content, content, content_len);
2935
2.19k
  }
2936
2937
  // Update the metalayers in frame (as size has not changed, we don't need to update the trailer)
2938
2.19k
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
2939
2.19k
  if (frame != NULL) {
2940
1.96k
    int rc = frame_lock(frame, true);
2941
1.96k
    if (rc < 0) {
2942
0
      return rc;
2943
0
    }
2944
1.96k
    rc = frame_update_header(frame, schunk, false);
2945
1.96k
    frame_unlock(frame);
2946
1.96k
    if (rc < 0) {
2947
552
      BLOSC_TRACE_ERROR("Unable to update meta info from frame.");
2948
552
      return rc;
2949
552
    }
2950
1.96k
  }
2951
1.64k
  schunk->change_tick++;
2952
2953
1.64k
  return nmetalayer;
2954
2.19k
}
2955
2956
2957
/* Find whether the schunk has a variable-length metalayer or not.
2958
 *
2959
 * If successful, return the index of the variable-length metalayer.  Else, return a negative value.
2960
 */
2961
0
int blosc2_vlmeta_exists(blosc2_schunk *schunk, const char *name) {
2962
0
  if (strlen(name) > BLOSC2_METALAYER_NAME_MAXLEN) {
2963
0
    BLOSC_TRACE_ERROR("Variable-length metalayer names cannot be larger than %d chars.", BLOSC2_METALAYER_NAME_MAXLEN);
2964
0
    return BLOSC2_ERROR_INVALID_PARAM;
2965
0
  }
2966
  // Re-sync the cached vlmetalayers if another handle rewrote the frame, so
2967
  // that a vlmetalayer added or deleted elsewhere is (not) found.  The other
2968
  // vlmeta entry points (add/get/update/delete) all pass through here, so
2969
  // this is the single sync point for the vlmetalayers.
2970
0
  if (schunk->frame != NULL) {
2971
0
    int rc = frame_check_stale((blosc2_frame_s*)schunk->frame);
2972
0
    if (rc < 0) {
2973
0
      return rc;
2974
0
    }
2975
0
  }
2976
2977
0
  for (int nvlmetalayer = 0; nvlmetalayer < schunk->nvlmetalayers; nvlmetalayer++) {
2978
0
    if (strcmp(name, schunk->vlmetalayers[nvlmetalayer]->name) == 0) {
2979
0
      return nvlmetalayer;
2980
0
    }
2981
0
  }
2982
0
  return BLOSC2_ERROR_NOT_FOUND;
2983
0
}
2984
2985
0
int vlmetalayer_flush(blosc2_schunk* schunk) {
2986
0
  int rc = BLOSC2_ERROR_SUCCESS;
2987
0
  blosc2_frame_s* frame = (blosc2_frame_s*)schunk->frame;
2988
0
  if (frame == NULL) {
2989
0
    return rc;
2990
0
  }
2991
0
  rc = frame_lock(frame, true);
2992
0
  if (rc < 0) {
2993
0
    return rc;
2994
0
  }
2995
0
  rc = frame_update_header(frame, schunk, false);
2996
0
  if (rc < 0) {
2997
0
    BLOSC_TRACE_ERROR("Unable to update metalayers into frame.");
2998
0
    frame_unlock(frame);
2999
0
    return rc;
3000
0
  }
3001
0
  rc = frame_update_trailer(frame, schunk);
3002
0
  if (rc < 0) {
3003
0
    BLOSC_TRACE_ERROR("Unable to update trailer into frame.");
3004
0
    frame_unlock(frame);
3005
0
    return rc;
3006
0
  }
3007
0
  frame_unlock(frame);
3008
0
  return rc;
3009
0
}
3010
3011
/* The content of a variable-length metalayer is not chunk data, so it is
3012
   compressed without the prefilter that `cparams` (often the super-chunk's own)
3013
   may carry, and decompressed without the super-chunk's postfilter. */
3014
0
static blosc2_context* vlmeta_create_cctx(const blosc2_cparams *cparams) {
3015
0
  blosc2_cparams vlmeta_cparams = (cparams != NULL) ? *cparams : BLOSC2_CPARAMS_DEFAULTS;
3016
0
  vlmeta_cparams.prefilter = NULL;
3017
0
  vlmeta_cparams.preparams = NULL;
3018
0
  return blosc2_create_cctx(vlmeta_cparams);
3019
0
}
3020
3021
0
static blosc2_context* vlmeta_create_dctx(const blosc2_dparams *dparams) {
3022
0
  blosc2_dparams vlmeta_dparams = *dparams;
3023
0
  vlmeta_dparams.postfilter = NULL;
3024
0
  vlmeta_dparams.postparams = NULL;
3025
0
  return blosc2_create_dctx(vlmeta_dparams);
3026
0
}
3027
3028
/* Add content into a new variable-length metalayer.
3029
 *
3030
 * If successful, return the index of the new variable-length metalayer.  Else, return a negative value.
3031
 */
3032
int blosc2_vlmeta_add(blosc2_schunk *schunk, const char *name, uint8_t *content, int32_t content_len,
3033
0
                      blosc2_cparams *cparams) {
3034
0
  if (schunk == NULL || name == NULL) {
3035
0
    BLOSC_TRACE_ERROR("Invalid parameters.");
3036
0
    return BLOSC2_ERROR_INVALID_PARAM;
3037
0
  }
3038
0
  int nvlmetalayer = blosc2_vlmeta_exists(schunk, name);
3039
0
  if (nvlmetalayer >= 0) {
3040
0
    BLOSC_TRACE_ERROR("Variable-length metalayer \"%s\" already exists.", name);
3041
0
    return BLOSC2_ERROR_INVALID_PARAM;
3042
0
  }
3043
0
  if (content_len < 0) {
3044
0
    BLOSC_TRACE_ERROR("Variable-length metalayer content length must not be negative.");
3045
0
    return BLOSC2_ERROR_INVALID_PARAM;
3046
0
  }
3047
0
  if (content_len > 0 && content == NULL) {
3048
0
    BLOSC_TRACE_ERROR("Variable-length metalayer content pointer must not be NULL when content length is positive.");
3049
0
    return BLOSC2_ERROR_INVALID_PARAM;
3050
0
  }
3051
3052
  // Add the vlmetalayer
3053
0
  blosc2_metalayer *vlmetalayer = malloc(sizeof(blosc2_metalayer));
3054
0
  BLOSC_ERROR_NULL(vlmetalayer, BLOSC2_ERROR_MEMORY_ALLOC);
3055
0
  vlmetalayer->name = strdup(name);
3056
0
  if (vlmetalayer->name == NULL) {
3057
0
    free(vlmetalayer);
3058
0
    BLOSC_TRACE_ERROR("Unable to allocate variable-length metalayer name buffer.");
3059
0
    return BLOSC2_ERROR_MEMORY_ALLOC;
3060
0
  }
3061
3062
0
  int64_t destsize = (int64_t)content_len + BLOSC2_MAX_OVERHEAD;
3063
0
  if (destsize > INT32_MAX) {
3064
0
    free(vlmetalayer->name);
3065
0
    free(vlmetalayer);
3066
0
    BLOSC_TRACE_ERROR("Variable-length metalayer size is too large.");
3067
0
    return BLOSC2_ERROR_INVALID_PARAM;
3068
0
  }
3069
0
  size_t destsize_sz = (size_t)destsize;
3070
0
  uint8_t* content_buf = malloc(destsize_sz);
3071
0
  if (content_buf == NULL) {
3072
0
    free(vlmetalayer->name);
3073
0
    free(vlmetalayer);
3074
0
    BLOSC_TRACE_ERROR("Unable to allocate variable-length metalayer buffer.");
3075
0
    return BLOSC2_ERROR_MEMORY_ALLOC;
3076
0
  }
3077
3078
0
  blosc2_context *cctx = vlmeta_create_cctx(cparams);
3079
0
  if (cctx == NULL) {
3080
0
    free(content_buf);
3081
0
    free(vlmetalayer->name);
3082
0
    free(vlmetalayer);
3083
0
    BLOSC_TRACE_ERROR("Error while creating the compression context");
3084
0
    return BLOSC2_ERROR_NULL_POINTER;
3085
0
  }
3086
3087
0
  int csize = blosc2_compress_ctx(cctx, content, content_len, content_buf, (int32_t)destsize);
3088
0
  if (csize < 0) {
3089
0
    blosc2_free_ctx(cctx);
3090
0
    free(content_buf);
3091
0
    free(vlmetalayer->name);
3092
0
    free(vlmetalayer);
3093
0
    BLOSC_TRACE_ERROR("Can not compress the `%s` variable-length metalayer.", name);
3094
0
    return csize;
3095
0
  }
3096
0
  blosc2_free_ctx(cctx);
3097
3098
0
  uint8_t *compressed_buf = realloc(content_buf, csize);
3099
0
  if (compressed_buf == NULL && csize > 0) {
3100
0
    compressed_buf = content_buf;
3101
0
  }
3102
0
  vlmetalayer->content = compressed_buf;
3103
0
  vlmetalayer->content_len = csize;
3104
0
  schunk->vlmetalayers[schunk->nvlmetalayers] = vlmetalayer;
3105
0
  schunk->nvlmetalayers += 1;
3106
3107
  // Propagate to frames
3108
0
  int rc = vlmetalayer_flush(schunk);
3109
0
  if (rc < 0) {
3110
0
    schunk->nvlmetalayers -= 1;
3111
0
    schunk->vlmetalayers[schunk->nvlmetalayers] = NULL;
3112
0
    free(vlmetalayer->content);
3113
0
    free(vlmetalayer->name);
3114
0
    free(vlmetalayer);
3115
0
    BLOSC_TRACE_ERROR("Can not propagate de `%s` variable-length metalayer to a frame.", name);
3116
0
    return rc;
3117
0
  }
3118
0
  schunk->change_tick++;
3119
3120
0
  return schunk->nvlmetalayers - 1;
3121
0
}
3122
3123
3124
int blosc2_vlmeta_get(blosc2_schunk *schunk, const char *name, uint8_t **content,
3125
0
                      int32_t *content_len) {
3126
0
  if (schunk == NULL || name == NULL || content == NULL || content_len == NULL) {
3127
0
    BLOSC_TRACE_ERROR("Invalid parameters.");
3128
0
    return BLOSC2_ERROR_INVALID_PARAM;
3129
0
  }
3130
  // blosc2_vlmeta_exists() re-syncs the cached vlmetalayers if another handle
3131
  // rewrote the frame
3132
0
  int nvlmetalayer = blosc2_vlmeta_exists(schunk, name);
3133
0
  if (nvlmetalayer < 0) {
3134
0
    BLOSC_TRACE_ERROR("User metalayer \"%s\" not found.", name);
3135
0
    return nvlmetalayer;
3136
0
  }
3137
0
  blosc2_metalayer *meta = schunk->vlmetalayers[nvlmetalayer];
3138
0
  int32_t nbytes, cbytes;
3139
0
  blosc2_cbuffer_sizes(meta->content, &nbytes, &cbytes, NULL);
3140
0
  if (cbytes != meta->content_len) {
3141
0
    BLOSC_TRACE_ERROR("User metalayer \"%s\" is corrupted.", meta->name);
3142
0
    return BLOSC2_ERROR_DATA;
3143
0
  }
3144
0
  if (nbytes < 0) {
3145
0
    BLOSC_TRACE_ERROR("User metalayer \"%s\" has corrupted decompressed size %d.", meta->name, nbytes);
3146
0
    return BLOSC2_ERROR_DATA;
3147
0
  }
3148
0
  *content_len = nbytes;
3149
0
  if (nbytes == 0) {
3150
0
    *content = NULL;
3151
0
  } else {
3152
0
    *content = malloc((size_t) nbytes);
3153
0
    if (*content == NULL) {
3154
0
      BLOSC_TRACE_ERROR("Unable to allocate variable-length metalayer content buffer.");
3155
0
      *content_len = 0;
3156
0
      return BLOSC2_ERROR_MEMORY_ALLOC;
3157
0
    }
3158
0
  }
3159
0
  blosc2_context *dctx = vlmeta_create_dctx(schunk->storage->dparams);
3160
0
  if (dctx == NULL) {
3161
0
    if (*content != NULL) {
3162
0
      free(*content);
3163
0
      *content = NULL;
3164
0
    }
3165
0
    *content_len = 0;
3166
0
    BLOSC_TRACE_ERROR("Error while creating the decompression context");
3167
0
    return BLOSC2_ERROR_NULL_POINTER;
3168
0
  }
3169
0
  int nbytes_ = blosc2_decompress_ctx(dctx, meta->content, meta->content_len, *content, nbytes);
3170
0
  blosc2_free_ctx(dctx);
3171
0
  if (nbytes_ != nbytes) {
3172
0
    if (*content != NULL) {
3173
0
      free(*content);
3174
0
      *content = NULL;
3175
0
    }
3176
0
    *content_len = 0;
3177
0
    BLOSC_TRACE_ERROR("User metalayer \"%s\" is corrupted.", meta->name);
3178
0
    return BLOSC2_ERROR_READ_BUFFER;
3179
0
  }
3180
0
  return nvlmetalayer;
3181
0
}
3182
3183
int blosc2_vlmeta_update(blosc2_schunk *schunk, const char *name, uint8_t *content, int32_t content_len,
3184
0
                         blosc2_cparams *cparams) {
3185
0
  if (schunk == NULL || name == NULL) {
3186
0
    BLOSC_TRACE_ERROR("Invalid parameters.");
3187
0
    return BLOSC2_ERROR_INVALID_PARAM;
3188
0
  }
3189
0
  int nvlmetalayer = blosc2_vlmeta_exists(schunk, name);
3190
0
  if (nvlmetalayer < 0) {
3191
0
    BLOSC_TRACE_ERROR("User vlmetalayer \"%s\" not found.", name);
3192
0
    return nvlmetalayer;
3193
0
  }
3194
0
  if (content_len < 0) {
3195
0
    BLOSC_TRACE_ERROR("Variable-length metalayer content length must not be negative.");
3196
0
    return BLOSC2_ERROR_INVALID_PARAM;
3197
0
  }
3198
0
  if (content_len > 0 && content == NULL) {
3199
0
    BLOSC_TRACE_ERROR("Variable-length metalayer content pointer must not be NULL when content length is positive.");
3200
0
    return BLOSC2_ERROR_INVALID_PARAM;
3201
0
  }
3202
3203
0
  blosc2_metalayer *vlmetalayer = schunk->vlmetalayers[nvlmetalayer];
3204
0
  int64_t destsize = (int64_t)content_len + BLOSC2_MAX_OVERHEAD;
3205
0
  if (destsize > INT32_MAX) {
3206
0
    BLOSC_TRACE_ERROR("Variable-length metalayer size is too large.");
3207
0
    return BLOSC2_ERROR_INVALID_PARAM;
3208
0
  }
3209
0
  size_t destsize_sz = (size_t)destsize;
3210
0
  uint8_t* content_buf = malloc(destsize_sz);
3211
0
  if (content_buf == NULL && content_len > 0) {
3212
0
    BLOSC_TRACE_ERROR("Unable to allocate variable-length metalayer buffer.");
3213
0
    return BLOSC2_ERROR_MEMORY_ALLOC;
3214
0
  }
3215
3216
0
  blosc2_context *cctx = vlmeta_create_cctx(cparams);
3217
0
  if (cctx == NULL) {
3218
0
    free(content_buf);
3219
0
    BLOSC_TRACE_ERROR("Error while creating the compression context");
3220
0
    return BLOSC2_ERROR_NULL_POINTER;
3221
0
  }
3222
3223
0
  int csize = blosc2_compress_ctx(cctx, content, content_len, content_buf, (int32_t)destsize);
3224
0
  if (csize < 0) {
3225
0
    blosc2_free_ctx(cctx);
3226
0
    free(content_buf);
3227
0
    BLOSC_TRACE_ERROR("Can not compress the `%s` variable-length metalayer.", name);
3228
0
    return csize;
3229
0
  }
3230
0
  blosc2_free_ctx(cctx);
3231
3232
0
  uint8_t* compressed_buf = realloc(content_buf, csize);
3233
0
  if (compressed_buf == NULL && csize > 0) {
3234
0
    compressed_buf = content_buf;
3235
0
  }
3236
0
  uint8_t* old_content = vlmetalayer->content;
3237
0
  vlmetalayer->content = compressed_buf;
3238
0
  vlmetalayer->content_len = csize;
3239
0
  free(old_content);
3240
3241
  // Propagate to frames
3242
0
  int rc = vlmetalayer_flush(schunk);
3243
0
  if (rc < 0) {
3244
0
    BLOSC_TRACE_ERROR("Can not propagate de `%s` variable-length metalayer to a frame.", name);
3245
0
    return rc;
3246
0
  }
3247
0
  schunk->change_tick++;
3248
3249
0
  return nvlmetalayer;
3250
0
}
3251
3252
0
int blosc2_vlmeta_delete(blosc2_schunk *schunk, const char *name) {
3253
0
  int nvlmetalayer = blosc2_vlmeta_exists(schunk, name);
3254
0
  if (nvlmetalayer < 0) {
3255
0
    BLOSC_TRACE_ERROR("User vlmetalayer \"%s\" not found.", name);
3256
0
    return nvlmetalayer;
3257
0
  }
3258
3259
0
  blosc2_metalayer *vlmetalayer = schunk->vlmetalayers[nvlmetalayer];
3260
0
  for (int i = nvlmetalayer; i < (schunk->nvlmetalayers - 1); i++) {
3261
0
    schunk->vlmetalayers[i] = schunk->vlmetalayers[i + 1];
3262
0
  }
3263
0
  schunk->vlmetalayers[schunk->nvlmetalayers - 1] = NULL;
3264
0
  free(vlmetalayer->name);
3265
0
  free(vlmetalayer->content);
3266
0
  free(vlmetalayer);
3267
0
  schunk->nvlmetalayers--;
3268
3269
  // Propagate to frames
3270
0
  int rc = vlmetalayer_flush(schunk);
3271
0
  if (rc < 0) {
3272
0
    BLOSC_TRACE_ERROR("Can not propagate de `%s` variable-length metalayer to a frame.", name);
3273
0
    return rc;
3274
0
  }
3275
0
  schunk->change_tick++;
3276
3277
0
  return schunk->nvlmetalayers;
3278
0
}
3279
3280
3281
0
int blosc2_vlmeta_get_names(blosc2_schunk *schunk, char **names) {
3282
0
  int16_t nvlmetalayers = schunk->nvlmetalayers;
3283
3284
0
  for (int i = 0; i < nvlmetalayers; ++i) {
3285
0
    names[i] = schunk->vlmetalayers[i]->name;
3286
0
  }
3287
3288
0
  return nvlmetalayers;
3289
0
}