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.2"

Class Method Summary collapse

Class Method Details

.adler32(*args) ⇒ Object



1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
# File 'ext/multi_compress/multi_compress.c', line 1931

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



1980
1981
1982
1983
1984
1985
1986
# File 'ext/multi_compress/multi_compress.c', line 1980

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)


1988
1989
1990
1991
# File 'ext/multi_compress/multi_compress.c', line 1988

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



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
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
# File 'ext/multi_compress/multi_compress.c', line 1186

static VALUE compress_compress(int argc, VALUE *argv, VALUE self) {
    VALUE data, opts;
    scan_one_required_keywords(argc, argv, &data, &opts);
    StringValue(data);

    mc_opts_t parsed_opts;
    mc_parse_opts(opts, &parsed_opts);
    reject_algorithm_keyword(&parsed_opts);

    VALUE algo_sym = parsed_opts.algo;
    VALUE level_val = parsed_opts.level;
    VALUE dict_val = parsed_opts.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(&parsed_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



1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
# File 'ext/multi_compress/multi_compress.c', line 1919

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



1485
1486
1487
# File 'ext/multi_compress/multi_compress.c', line 1485

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



1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
# File 'ext/multi_compress/multi_compress.c', line 1993

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