Module: MultiCompress

Defined in:
lib/multi_compress.rb,
lib/multi_compress/version.rb,
ext/multi_compress/multi_compress.c

Defined Under Namespace

Modules: Brotli, InflaterDefaults, LZ4, Zstd Classes: Config, DataError, Deflater, Dictionary, Error, Inflater, LevelError, MemError, Reader, StreamError, UnsupportedError, Writer

Constant Summary collapse

FASTEST =
:fastest
DEFAULT =
:default
BEST =
:best
DEFAULT_MAX_OUTPUT_SIZE =
512 * 1024 * 1024
DEFAULT_STREAMING_MAX_OUTPUT_SIZE =
2 * 1024 * 1024 * 1024
VERSION =
"0.3.1"

Class Method Summary collapse

Class Method Details

.adler32(*args) ⇒ Object



1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
# File 'ext/multi_compress/multi_compress.c', line 1853

static VALUE compress_adler32(int argc, VALUE *argv, VALUE self) {
    (void)self;
    VALUE data, prev;
    rb_scan_args(argc, argv, "11", &data, &prev);
    StringValue(data);

    const uint8_t *restrict src = (const uint8_t *)RSTRING_PTR(data);
    size_t len = (size_t)RSTRING_LEN(data);
    const uint32_t adler = NIL_P(prev) ? 1u : NUM2UINT(prev);

    uint32_t s1 = adler & 0xFFFFu;
    uint32_t s2 = (adler >> 16) & 0xFFFFu;
    enum { ADLER_BASE = 65521, ADLER_NMAX = 5552 };

    while (len > 0) {
        size_t chunk = len > ADLER_NMAX ? (size_t)ADLER_NMAX : len;
        len -= chunk;

        while (chunk >= 8) {
            s1 += src[0];
            s2 += s1;
            s1 += src[1];
            s2 += s1;
            s1 += src[2];
            s2 += s1;
            s1 += src[3];
            s2 += s1;
            s1 += src[4];
            s2 += s1;
            s1 += src[5];
            s2 += s1;
            s1 += src[6];
            s2 += s1;
            s1 += src[7];
            s2 += s1;
            src += 8;
            chunk -= 8;
        }
        while (chunk--) {
            s1 += *src++;
            s2 += s1;
        }
        s1 %= ADLER_BASE;
        s2 %= ADLER_BASE;
    }

    return UINT2NUM((s2 << 16) | s1);
}

.algo_from_ext(path) ⇒ Object



131
132
133
# File 'lib/multi_compress.rb', line 131

def self.algo_from_ext(path)
  EXTENSION_MAP[File.extname(path).downcase]
end

.algorithmsObject



1902
1903
1904
1905
1906
1907
1908
# File 'ext/multi_compress/multi_compress.c', line 1902

static VALUE compress_algorithms(VALUE self) {
    VALUE ary = rb_ary_new_capa(3);
    rb_ary_push(ary, sym_cache.zstd);
    rb_ary_push(ary, sym_cache.lz4);
    rb_ary_push(ary, sym_cache.brotli);
    return ary;
}

.available?(algo_sym) ⇒ Boolean

Returns:

  • (Boolean)


1910
1911
1912
1913
# File 'ext/multi_compress/multi_compress.c', line 1910

static VALUE compress_available_p(VALUE self, VALUE algo_sym) {
    sym_to_algo(algo_sym);
    return Qtrue;
}

.brotli(data, level: nil) ⇒ Object



109
110
111
# File 'lib/multi_compress.rb', line 109

def self.brotli(data, level: nil)
  compress(data, algo: :brotli, **level_opts(level))
end

.brotli_decompress(data) ⇒ Object



127
128
129
# File 'lib/multi_compress.rb', line 127

def self.brotli_decompress(data)
  decompress(data, algo: :brotli)
end

.compress(*args) ⇒ Object



1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
# File 'ext/multi_compress/multi_compress.c', line 1108

static VALUE compress_compress(int argc, VALUE *argv, VALUE self) {
    VALUE data, opts;
    rb_scan_args(argc, argv, "1:", &data, &opts);
    StringValue(data);
    reject_algorithm_keyword(opts);

    VALUE algo_sym = Qnil, level_val = Qnil, dict_val = Qnil;
    if (!NIL_P(opts)) {
        algo_sym = opt_get(opts, sym_cache.algo);
        level_val = opt_get(opts, sym_cache.level);
        dict_val = opt_get(opts, sym_cache.dictionary);
    }

    int explicit_algo = !NIL_P(algo_sym);
    compress_algo_t algo = explicit_algo ? sym_to_algo(algo_sym) : ALGO_ZSTD;
    lz4_format_t lz4_format = parse_lz4_format(opts, algo, explicit_algo);
    int level = resolve_level(algo, level_val);

    dictionary_t *dict = NULL;
    if (!NIL_P(dict_val)) {
        if (algo == ALGO_LZ4) {
            rb_raise(eUnsupportedError, "LZ4 does not support dictionaries");
        }
        dict = opt_dictionary(dict_val);
    }

    const char *src = RSTRING_PTR(data);
    size_t slen = RSTRING_LEN(data);
    const algo_policy_t *policy = algo_policy(algo);

    switch (algo) {
    case ALGO_ZSTD: {
        size_t bound = ZSTD_compressBound(slen);

        ZSTD_CDict *cdict = NULL;
        if (dict) {
            cdict = dict_get_cdict(dict, level);
            if (!cdict)
                rb_raise(eMemError, "zstd: failed to create/get cdict");
        }

        if (slen < policy->gvl_unlock_threshold) {
            VALUE dst = rb_binary_str_buf_reserve(bound);
            size_t csize;
            if (cdict) {
                ZSTD_CCtx *cctx = ZSTD_createCCtx();
                if (!cctx)
                    rb_raise(eMemError, "zstd: failed to create context");
                csize = ZSTD_compress_usingCDict(cctx, RSTRING_PTR(dst), bound, src, slen, cdict);
                ZSTD_freeCCtx(cctx);
            } else {
                csize = ZSTD_compress(RSTRING_PTR(dst), bound, src, slen, level);
            }
            if (ZSTD_isError(csize))
                rb_raise(eError, "zstd compress: %s", ZSTD_getErrorName(csize));
            rb_str_set_len(dst, (long)csize);
            RB_GC_GUARD(data);
            RB_GC_GUARD(dict_val);
            return dst;
        }

        {
            VALUE scheduler = current_fiber_scheduler();
            work_exec_mode_t mode = select_fiber_nogvl_or_direct_mode(
                scheduler, slen, policy->gvl_unlock_threshold, policy->gvl_unlock_threshold);

            if (mode == WORK_EXEC_FIBER) {
                char *out_buf = (char *)malloc(bound);
                if (!out_buf)
                    rb_raise(eMemError, "zstd: malloc failed");
                zstd_fiber_compress_t fargs = {
                    .src = src,
                    .src_len = slen,
                    .level = level,
                    .cdict = cdict,
                    .dst = out_buf,
                    .dst_cap = bound,
                    .result = 0,
                    .error = 0,
                };

                RUN_WITH_EXEC_MODE(mode, zstd_fiber_compress_nogvl, fargs);

                if (fargs.error) {
                    free(out_buf);
                    rb_raise(eMemError, "zstd: failed to create context");
                }
                if (ZSTD_isError(fargs.result)) {
                    free(out_buf);
                    rb_raise(eError, "zstd compress: %s", ZSTD_getErrorName(fargs.result));
                }

                VALUE result = rb_binary_str_new(out_buf, (long)fargs.result);
                free(out_buf);
                RB_GC_GUARD(data);
                RB_GC_GUARD(dict_val);
                return result;
            }
        }

        {
            VALUE dst = rb_binary_str_buf_reserve(bound);
            zstd_compress_args_t args = {
                .src = src,
                .src_len = slen,
                .dst = RSTRING_PTR(dst),
                .dst_cap = bound,
                .level = level,
                .cdict = cdict,
                .result = 0,
                .error = 0,
            };
            RUN_WITH_EXEC_MODE(WORK_EXEC_NOGVL, zstd_compress_nogvl, args);

            if (args.error)
                rb_raise(eMemError, "zstd: failed to create context");
            if (ZSTD_isError(args.result))
                rb_raise(eError, "zstd compress: %s", ZSTD_getErrorName(args.result));

            rb_str_set_len(dst, (long)args.result);
            RB_GC_GUARD(data);
            RB_GC_GUARD(dict_val);
            return dst;
        }
    }
    case ALGO_LZ4: {
        if (lz4_format == LZ4_FORMAT_FRAME) {
            LZ4F_preferences_t prefs;
            memset(&prefs, 0, sizeof(prefs));
            prefs.frameInfo.blockChecksumFlag = LZ4F_blockChecksumEnabled;
            prefs.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled;
            size_t bound = LZ4F_compressFrameBound(slen, &prefs);
            VALUE dst = rb_binary_str_buf_reserve((long)bound);
            lz4frame_compress_args_t args = {
                .src = src,
                .src_len = slen,
                .dst = RSTRING_PTR(dst),
                .dst_cap = bound,
                .result = 0,
                .error_code = 0,
            };
            {
                VALUE scheduler = current_fiber_scheduler();
                work_exec_mode_t mode = select_fiber_nogvl_or_direct_mode(
                    scheduler, slen, policy->gvl_unlock_threshold, policy->gvl_unlock_threshold);
                RUN_WITH_EXEC_MODE(mode, lz4frame_compress_nogvl, args);
            }
            if (args.error_code)
                rb_raise(eError, "lz4 frame compress failed: %s",
                         LZ4F_getErrorName(args.error_code));
            rb_str_set_len(dst, (long)args.result);
            RB_GC_GUARD(data);
            return dst;
        }
        if (slen > (size_t)INT_MAX)
            rb_raise(eError, "lz4: input too large (max 2GB)");
        int bound = LZ4_compressBound((int)slen);

        int csize;
        if (slen >= policy->gvl_unlock_threshold) {
            VALUE dst = rb_binary_str_buf_reserve(8 + (size_t)bound + 4);
            char *out = RSTRING_PTR(dst);

            write_le_u32((uint8_t *)out, (uint32_t)slen);

            lz4_compress_args_t args = {
                .src = src,
                .src_len = (int)slen,
                .dst = out + 8,
                .dst_cap = bound,
                .level = level,
            };

            VALUE scheduler = current_fiber_scheduler();
            work_exec_mode_t mode = select_fiber_nogvl_or_direct_mode(
                scheduler, slen, policy->gvl_unlock_threshold, policy->gvl_unlock_threshold);
            RUN_WITH_EXEC_MODE(mode, lz4_compress_nogvl, args);
            csize = args.result;

            if (csize <= 0)
                rb_raise(eError, "lz4 compress failed");

            write_le_u32((uint8_t *)out + 4, (uint32_t)csize);

            size_t total = 8 + (size_t)csize;
            write_le_u32((uint8_t *)out + total, 0);

            rb_str_set_len(dst, (long)(total + 4));
            RB_GC_GUARD(data);
            return dst;
        } else {
            VALUE dst = rb_binary_str_buf_reserve(8 + bound + 4);
            char *out = RSTRING_PTR(dst);

            write_le_u32((uint8_t *)out, (uint32_t)slen);

            if (level > 1) {
                csize = LZ4_compress_HC(src, out + 8, (int)slen, bound, level);
            } else {
                csize = LZ4_compress_default(src, out + 8, (int)slen, bound);
            }
            if (csize <= 0)
                rb_raise(eError, "lz4 compress failed");

            write_le_u32((uint8_t *)out + 4, (uint32_t)csize);

            size_t total = 8 + csize;
            write_le_u32((uint8_t *)out + total, 0);

            rb_str_set_len(dst, total + 4);
            RB_GC_GUARD(data);
            return dst;
        }
    }
    case ALGO_BROTLI: {
        size_t out_len = BrotliEncoderMaxCompressedSize(slen);
        if (out_len == 0)
            out_len = slen + (slen >> 2) + 1024;

        if (dict) {
            VALUE dst = rb_binary_str_buf_reserve(out_len);
            BrotliEncoderState *enc = BrotliEncoderCreateInstance(NULL, NULL, NULL);
            if (!enc)
                rb_raise(eMemError, "brotli: failed to create encoder");

            BrotliEncoderPreparedDictionary *pd =
                BrotliEncoderPrepareDictionary(BROTLI_SHARED_DICTIONARY_RAW, dict->size, dict->data,
                                               BROTLI_MAX_QUALITY, NULL, NULL, NULL);
            if (!pd) {
                BrotliEncoderDestroyInstance(enc);
                rb_raise(eMemError, "brotli: failed to prepare dictionary");
            }

            if (!BrotliEncoderSetParameter(enc, BROTLI_PARAM_QUALITY, level) ||
                !BrotliEncoderAttachPreparedDictionary(enc, pd)) {
                BrotliEncoderDestroyPreparedDictionary(pd);
                BrotliEncoderDestroyInstance(enc);
                rb_raise(eError, "brotli: failed to attach dictionary");
            }

            size_t available_in = slen;
            const uint8_t *next_in = (const uint8_t *)src;
            size_t available_out = out_len;
            uint8_t *next_out = (uint8_t *)RSTRING_PTR(dst);
            size_t initial_out = available_out;

            BROTLI_BOOL ok =
                BrotliEncoderCompressStream(enc, BROTLI_OPERATION_FINISH, &available_in, &next_in,
                                            &available_out, &next_out, NULL);

            BrotliEncoderDestroyPreparedDictionary(pd);
            BrotliEncoderDestroyInstance(enc);
            if (!ok)
                rb_raise(eError, "brotli compress with dict failed");

            rb_str_set_len(dst, initial_out - available_out);
            RB_GC_GUARD(data);
            RB_GC_GUARD(dict_val);
            return dst;
        } else if (slen >= policy->gvl_unlock_threshold) {
            VALUE dst = rb_binary_str_buf_reserve(out_len);
            size_t actual_out_len = out_len;

            brotli_compress_args_t args = {
                .level = level,
                .src_len = slen,
                .src = (const uint8_t *)src,
                .out_len = &actual_out_len,
                .dst = (uint8_t *)RSTRING_PTR(dst),
            };

            VALUE scheduler = current_fiber_scheduler();
            work_exec_mode_t mode = select_fiber_nogvl_or_direct_mode(
                scheduler, slen, policy->gvl_unlock_threshold, policy->gvl_unlock_threshold);
            RUN_WITH_EXEC_MODE(mode, brotli_compress_nogvl, args);

            if (!args.result)
                rb_raise(eError, "brotli compress failed");

            rb_str_set_len(dst, (long)actual_out_len);
            RB_GC_GUARD(data);
            return dst;
        } else {
            VALUE dst = rb_binary_str_buf_reserve(out_len);
            BROTLI_BOOL ok =
                BrotliEncoderCompress(level, BROTLI_DEFAULT_WINDOW, BROTLI_DEFAULT_MODE, slen,
                                      (const uint8_t *)src, &out_len, (uint8_t *)RSTRING_PTR(dst));
            if (!ok)
                rb_raise(eError, "brotli compress failed");
            rb_str_set_len(dst, out_len);
            RB_GC_GUARD(data);
            return dst;
        }
    }
    }

    return Qnil;
}

.configObject



82
83
84
# File 'lib/multi_compress.rb', line 82

def config
  @config ||= Config.new
end

.configure {|config| ... } ⇒ Object

Yields:



86
87
88
89
90
91
# File 'lib/multi_compress.rb', line 86

def configure
  return config unless block_given?

  yield(config)
  config
end

.crc32(*args) ⇒ Object



1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
# File 'ext/multi_compress/multi_compress.c', line 1841

static VALUE compress_crc32(int argc, VALUE *argv, VALUE self) {
    VALUE data, prev;
    rb_scan_args(argc, argv, "11", &data, &prev);
    StringValue(data);

    const uint8_t *src = (const uint8_t *)RSTRING_PTR(data);
    size_t len = RSTRING_LEN(data);
    uint32_t crc = NIL_P(prev) ? 0 : NUM2UINT(prev);

    return UINT2NUM(crc32_compute(src, len, crc));
}

.decompress(*args) ⇒ Object



1407
1408
1409
# File 'ext/multi_compress/multi_compress.c', line 1407

def self.decompress(data, **opts)
  _c_decompress(data, **resolved_one_shot_options(opts))
end

.lz4(data, level: nil, format: nil) ⇒ Object



103
104
105
106
107
# File 'lib/multi_compress.rb', line 103

def self.lz4(data, level: nil, format: nil)
  opts = level_opts(level)
  opts[:format] = format if format
  compress(data, algo: :lz4, **opts)
end

.lz4_decompress(data, format: nil) ⇒ Object



121
122
123
124
125
# File 'lib/multi_compress.rb', line 121

def self.lz4_decompress(data, format: nil)
  opts = { algo: :lz4 }
  opts[:format] = format if format
  decompress(data, **opts)
end

.version(algo_sym) ⇒ Object



1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
# File 'ext/multi_compress/multi_compress.c', line 1915

static VALUE compress_version(VALUE self, VALUE algo_sym) {
    compress_algo_t algo = sym_to_algo(algo_sym);
    switch (algo) {
    case ALGO_ZSTD:
        return rb_str_new_cstr(ZSTD_versionString());
    case ALGO_LZ4:
        return rb_sprintf("%d.%d.%d", LZ4_VERSION_MAJOR, LZ4_VERSION_MINOR, LZ4_VERSION_RELEASE);
    case ALGO_BROTLI:
        return rb_sprintf("%d.%d.%d", BrotliEncoderVersion() >> 24,
                          (BrotliEncoderVersion() >> 12) & 0xFFF, BrotliEncoderVersion() & 0xFFF);
    }
    return Qnil;
}

.zstd(data, level: nil) ⇒ Object



99
100
101
# File 'lib/multi_compress.rb', line 99

def self.zstd(data, level: nil)
  compress(data, algo: :zstd, **level_opts(level))
end

.zstd_decompress(data) ⇒ Object



117
118
119
# File 'lib/multi_compress.rb', line 117

def self.zstd_decompress(data)
  decompress(data, algo: :zstd)
end