libzarr
Header-only C++17 Zarr v2/v3, WASM-compatible
Loading...
Searching...
No Matches
codecs_blosc.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2
3#ifndef LIBZARR_CODECS_BLOSC_HPP
4#define LIBZARR_CODECS_BLOSC_HPP
5
6#ifndef LIBZARR_HAS_BLOSC
7#error "libzarr/codecs_blosc.hpp requires c-blosc: define LIBZARR_HAS_BLOSC and link blosc"
8#endif
9
10#include <cstddef>
11#include <cstdint>
12#include <optional>
13#include <string>
14
15#include <blosc.h>
16
17#include "libzarr/detail/common.hpp"
18#include "libzarr/types.hpp"
19
23
24namespace zarr::detail {
25
26struct BloscParams {
27 std::string cname = "lz4";
28 int clevel = 5;
29 int shuffle = BLOSC_SHUFFLE;
30 std::size_t typesize = 1;
31 std::size_t blocksize = 0; // 0 = automatic
32};
33
34inline Bytes blosc_decompress_bytes(const Bytes& src, std::optional<std::uint64_t> expected,
35 const char* what) {
36 std::size_t nbytes = 0;
37 if (blosc_cbuffer_validate(src.data(), src.size(), &nbytes) < 0) {
38 throw error(std::string(what) + ": corrupt blosc frame");
39 }
40 if (expected && nbytes != *expected) {
41 throw error(std::string(what) + ": blosc frame decodes to " + std::to_string(nbytes) +
42 " bytes, expected " + std::to_string(*expected));
43 }
44 Bytes out(nbytes);
45 const int n = blosc_decompress_ctx(src.data(), out.data(), out.size(), /*numinternalthreads=*/1);
46 if (n < 0 || static_cast<std::size_t>(n) != nbytes) {
47 throw error(std::string(what) + ": blosc decompression failed (" + std::to_string(n) + ")");
48 }
49 return out;
50}
51
52inline Bytes blosc_compress_bytes(const Bytes& src, const BloscParams& params, const char* what) {
53 Bytes out(src.size() + BLOSC_MAX_OVERHEAD);
54 const int n = blosc_compress_ctx(params.clevel, params.shuffle, params.typesize, src.size(),
55 src.data(), out.data(), out.size(), params.cname.c_str(),
56 params.blocksize, /*numinternalthreads=*/1);
57 if (n <= 0) {
58 throw error(std::string(what) + ": blosc compression failed (" + std::to_string(n) + ")");
59 }
60 out.resize(static_cast<std::size_t>(n));
61 return out;
62}
63
64} // namespace zarr::detail
65
66#endif // LIBZARR_CODECS_BLOSC_HPP
CodecSpec shuffle(int elementsize=0)
shuffle: byte-transposition filter. elementsize 0 means the dtype size.
Definition metadata.hpp:69
std::vector< std::uint8_t > Bytes
Owned byte buffer used throughout the value-based public API.
Definition types.hpp:42