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

Class Method Summary collapse

Class Method Details

.adler32(*args) ⇒ Object



2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
# File 'ext/multi_compress/multi_compress.c', line 2000

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



135
136
137
# File 'lib/multi_compress.rb', line 135

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

.algorithmsObject



2049
2050
2051
2052
2053
2054
2055
# File 'ext/multi_compress/multi_compress.c', line 2049

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)


2057
2058
2059
2060
# File 'ext/multi_compress/multi_compress.c', line 2057

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

.brotli(data, level: nil) ⇒ Object



111
112
113
# File 'lib/multi_compress.rb', line 111

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

.brotli_decompress(data) ⇒ Object



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

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

.compress(*args) ⇒ Object



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
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
# File 'ext/multi_compress/multi_compress.c', line 1250

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);
            int ctx_error = 0;
            size_t csize =
                zstd_compress_cached(RSTRING_PTR(dst), bound, src, slen, level, cdict, &ctx_error);
            if (ctx_error)
                rb_raise(eMemError, "zstd: failed to create context");
            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)) {
                BrotliEncoderDestroyPreparedDictionary(pd);
                BrotliEncoderDestroyInstance(enc);
                rb_raise(eError, "brotli: failed to set quality parameter");
            }
            if (!BrotliEncoderSetParameter(enc, BROTLI_PARAM_SIZE_HINT,
                                           slen > UINT32_MAX ? UINT32_MAX : (uint32_t)slen)) {
                BrotliEncoderDestroyPreparedDictionary(pd);
                BrotliEncoderDestroyInstance(enc);
                rb_raise(eError, "brotli: failed to set size hint parameter");
            }
            if (!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



1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
# File 'ext/multi_compress/multi_compress.c', line 1988

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



1554
1555
1556
# File 'ext/multi_compress/multi_compress.c', line 1554

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
108
109
# File 'lib/multi_compress.rb', line 103

def self.lz4(data, level: nil, format: nil)
  if format
    compress(data, algo: :lz4, level: level, format: format)
  else
    compress(data, algo: :lz4, level: level)
  end
end

.lz4_decompress(data, format: nil) ⇒ Object



123
124
125
126
127
128
129
# File 'lib/multi_compress.rb', line 123

def self.lz4_decompress(data, format: nil)
  if format
    decompress(data, algo: :lz4, format: format)
  else
    decompress(data, algo: :lz4)
  end
end

.version(algo_sym) ⇒ Object



2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
# File 'ext/multi_compress/multi_compress.c', line 2062

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: level)
end

.zstd_decompress(data) ⇒ Object



119
120
121
# File 'lib/multi_compress.rb', line 119

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