Module: VibeZstd

Defined in:
lib/vibe_zstd.rb,
lib/vibe_zstd/version.rb,
lib/vibe_zstd/constants.rb,
sig/vibe_zstd.rbs,
ext/vibe_zstd/vibe_zstd.c

Defined Under Namespace

Modules: Compress, Decompress, DictAttachPref, Format, LiteralCompressionMode, ResetDirective, Strategy, ThreadLocal Classes: CCtx, CDict, CompressWriter, DCtx, DDict, DecompressReader, DecompressedSizeExceeded, Error

Constant Summary collapse

VERSION =

Returns:

"1.3.0"

Class Method Summary collapse

Class Method Details

.compress(data, **options) ⇒ String

Module-level convenience methods

Parameters:

Returns:



23
24
25
26
27
# File 'lib/vibe_zstd.rb', line 23

def self.compress(data, **options)
  call_opts = options.slice(*COMPRESS_CALL_OPTIONS)
  ctx_opts = options.except(*COMPRESS_CALL_OPTIONS)
  CCtx.new(**ctx_opts).compress(data, **call_opts)
end

.compress_bound(size) ⇒ Object

VibeZstd.compress_bound(size)



75
# File 'sig/vibe_zstd.rbs', line 75

def self.compress_bound: (Integer size) -> Integer

.decompress(data, **options) ⇒ String

Convenience method for one-off decompression. Per-call options (dict, initial_capacity, max_decompressed_size/max_size) are passed to #decompress; any other keyword is a context parameter (e.g. format:, window_log_max:) applied to a fresh DCtx.

Parameters:

Returns:



33
34
35
36
37
# File 'lib/vibe_zstd.rb', line 33

def self.decompress(data, **options)
  call_opts = options.slice(*DECOMPRESS_CALL_OPTIONS)
  ctx_opts = options.except(*DECOMPRESS_CALL_OPTIONS)
  DCtx.new(**ctx_opts).decompress(data, **call_opts)
end

.default_compression_levelObject Also known as: default_level



277
278
279
280
281
# File 'ext/vibe_zstd/vibe_zstd.c', line 277

static VALUE
vibe_zstd_default_c_level(VALUE self) {
    (void)self;
    return INT2NUM(ZSTD_defaultCLevel());
}

.dict_header_size(dict_data) ⇒ Object

VibeZstd.dict_header_size(dict_data)



593
594
595
596
597
598
599
600
601
602
603
604
# File 'ext/vibe_zstd/dict.c', line 593

static VALUE
vibe_zstd_dict_header_size(VALUE self, VALUE dict_data) {
    StringValue(dict_data);
    size_t header_size = ZDICT_getDictHeaderSize(RSTRING_PTR(dict_data), RSTRING_LEN(dict_data));

    // Check for errors
    if (ZDICT_isError(header_size)) {
        rb_raise(rb_eRuntimeError, "Failed to get dictionary header size: %s", ZDICT_getErrorName(header_size));
    }

    return SIZET2NUM(header_size);
}

.each_skippable_frame(data) ⇒ Object

Iterate over all skippable frames in the data Yields [content, magic_variant, offset] for each skippable frame



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/vibe_zstd.rb', line 47

def self.each_skippable_frame(data)
  return enum_for(:each_skippable_frame, data) unless block_given?

  offset = 0
  while offset < data.bytesize
    frame_data = data.byteslice(offset..-1)
    frame_size = find_frame_compressed_size(frame_data)

    # Defense: Prevent infinite loop on malformed data
    # A valid frame must have non-zero size (at minimum: frame header)
    raise Error, "Invalid frame: zero or negative size at offset #{offset}" if frame_size <= 0

    if skippable_frame?(frame_data)
      content, magic_variant = read_skippable_frame(frame_data)
      yield content, magic_variant, offset
    end

    offset += frame_size
  end
end

.finalize_dictionary(*args) ⇒ Object

For large datasets, consider using a representative subset of samples.



510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'ext/vibe_zstd/dict.c', line 510

static VALUE
vibe_zstd_finalize_dictionary(int argc, VALUE* argv, VALUE self) {
    VALUE options;
    rb_scan_args(argc, argv, ":", &options);

    // Layer 1: Validate inputs BEFORE any allocation (fail-fast)
    if (NIL_P(options)) {
        rb_raise(rb_eArgError, "finalize_dictionary requires keyword arguments");
    }

    // Get required parameters
    VALUE content_val = rb_hash_aref(options, ID2SYM(rb_intern("content")));
    VALUE samples_val = rb_hash_aref(options, ID2SYM(rb_intern("samples")));
    VALUE max_size_val = rb_hash_aref(options, ID2SYM(rb_intern("max_size")));

    if (NIL_P(content_val)) {
        rb_raise(rb_eArgError, "content: parameter is required");
    }
    if (NIL_P(samples_val)) {
        rb_raise(rb_eArgError, "samples: parameter is required");
    }
    if (NIL_P(max_size_val)) {
        rb_raise(rb_eArgError, "max_size: parameter is required");
    }

    // Validate types early
    StringValue(content_val);
    Check_Type(samples_val, T_ARRAY);
    size_t max_size = NUM2SIZET(max_size_val);

    long num_samples = RARRAY_LEN(samples_val);
    if (num_samples == 0) {
        rb_raise(rb_eArgError, "samples array cannot be empty");
    }

    // Validate all samples are strings and calculate sizes BEFORE allocating.
    // Build a private converted-samples array (see vibe_zstd_train_dict for details).
    VALUE converted_samples = rb_ary_new_capa(num_samples);
    size_t total_samples_size = 0;
    for (long i = 0; i < num_samples; i++) {
        VALUE sample = rb_ary_entry(samples_val, i);
        StringValue(sample);  // Validate type early - may raise TypeError; updates local
        rb_ary_push(converted_samples, sample);
        total_samples_size += RSTRING_LEN(sample);
    }

    // Get optional parameters
    VALUE compression_level_val = rb_hash_aref(options, ID2SYM(rb_intern("compression_level")));
    VALUE dict_id_val = rb_hash_aref(options, ID2SYM(rb_intern("dict_id")));

    // Setup ZDICT_params_t
    ZDICT_params_t params;
    memset(&params, 0, sizeof(params));
    params.compressionLevel = NIL_P(compression_level_val) ? 0 : NUM2INT(compression_level_val);
    params.dictID = NIL_P(dict_id_val) ? 0 : NUM2UINT(dict_id_val);
    params.notificationLevel = 0;

    // Layer 2: Allocate late - only after validation passes
    dict_training_resources resources = {NULL, NULL, NULL};
    resources.sample_sizes = ALLOC_N(size_t, num_samples);
    resources.samples_buffer = ALLOC_N(char, total_samples_size);
    resources.dict_buffer = ALLOC_N(char, max_size);

    // Layer 3: Use rb_ensure for guaranteed cleanup
    finalize_dict_ctx ctx = {
        .base = {
            .resources = &resources,
            .result = Qnil,
            .max_dict_size = max_size,
            .num_samples = num_samples,
            .total_samples_size = total_samples_size,
            .samples = converted_samples  // use private array, not caller's array
        },
        .content_val = content_val,
        .params = params
    };

    rb_ensure(finalize_dict_body, (VALUE)&ctx, dict_training_cleanup, (VALUE)&resources);
    return ctx.base.result;
}

.find_frame_compressed_size(data) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'ext/vibe_zstd/frames.c', line 119

static VALUE
vibe_zstd_find_frame_compressed_size(VALUE self, VALUE data) {
    (void)self;
    StringValue(data);

    // Returns compressed size of first complete frame (including header/checksum)
    // Useful for splitting concatenated frames in multi-frame archives
    size_t frame_size = ZSTD_findFrameCompressedSize(RSTRING_PTR(data), RSTRING_LEN(data));

    if (ZSTD_isError(frame_size)) {
        rb_raise(rb_eRuntimeError, "Failed to find frame size: %s", ZSTD_getErrorName(frame_size));
    }

    return SIZET2NUM(frame_size);
}

.frame_content_size(data) ⇒ Integer?

Get the decompressed content size from a compressed frame Returns nil if size is unknown or data is invalid

Parameters:

Returns:



41
42
43
# File 'lib/vibe_zstd.rb', line 41

def self.frame_content_size(data)
  DCtx.frame_content_size(data)
end

.get_dict_id(dict_data) ⇒ Object

VibeZstd.get_dict_id(dict_data)



489
# File 'ext/vibe_zstd/dict.c', line 489

def self.get_dict_id: (String dict_data) -> Integer

.get_dict_id_from_frame(data) ⇒ Object

VibeZstd.get_dict_id_from_frame(data)



498
# File 'ext/vibe_zstd/dict.c', line 498

def self.get_dict_id_from_frame: (String data) -> Integer

.max_compression_levelObject Also known as: max_level



271
272
273
274
275
# File 'ext/vibe_zstd/vibe_zstd.c', line 271

static VALUE
vibe_zstd_max_c_level(VALUE self) {
    (void)self;
    return INT2NUM(ZSTD_maxCLevel());
}

.min_compression_levelObject Also known as: min_level



265
266
267
268
269
# File 'ext/vibe_zstd/vibe_zstd.c', line 265

static VALUE
vibe_zstd_min_c_level(VALUE self) {
    (void)self;
    return INT2NUM(ZSTD_minCLevel());
}

.read_skippable_frame(data) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'ext/vibe_zstd/frames.c', line 64

static VALUE
vibe_zstd_read_skippable_frame(VALUE self, VALUE data) {
    (void)self;
    StringValue(data);

    if (!ZSTD_isSkippableFrame(RSTRING_PTR(data), RSTRING_LEN(data))) {
        rb_raise(rb_eArgError, "data is not a skippable frame (%zu bytes provided)", RSTRING_LEN(data));
    }

    const char* src = RSTRING_PTR(data);
    size_t src_size = RSTRING_LEN(data);

    // Content size is in bytes 4-7 (little-endian uint32)
    if (src_size < 8) {
        rb_raise(rb_eArgError, "skippable frame too small (%zu bytes, minimum 8 bytes required)", src_size);
    }

    uint32_t content_size;
    memcpy(&content_size, src + 4, 4);

    // The content size field is attacker-controlled and may claim up to ~4 GiB.
    // A skippable frame's content cannot exceed the bytes actually provided
    // (src_size minus the 8-byte header), so cap the allocation accordingly to
    // prevent a tiny truncated input from forcing a huge allocation. A frame
    // whose declared size exceeds what is present is malformed and
    // ZSTD_readSkippableFrame reports the error below.
    size_t capacity = content_size;
    if (capacity > src_size - 8) {
        capacity = src_size - 8;
    }

    VALUE result = rb_str_buf_new(capacity);
    unsigned magic_variant;

    size_t bytes_read = ZSTD_readSkippableFrame(
        RSTRING_PTR(result),
        capacity,
        &magic_variant,
        src,
        src_size
    );

    if (ZSTD_isError(bytes_read)) {
        rb_raise(rb_eRuntimeError, "Failed to read skippable frame: %s", ZSTD_getErrorName(bytes_read));
    }

    rb_str_set_len(result, bytes_read);

    // Return [content, magic_variant]
    VALUE result_ary = rb_ary_new_capa(2);
    rb_ary_push(result_ary, result);
    rb_ary_push(result_ary, UINT2NUM(magic_variant));
    return result_ary;
}

.skippable_frame?(data) ⇒ Boolean

Returns:



12
13
14
15
16
17
18
# File 'ext/vibe_zstd/frames.c', line 12

static VALUE
vibe_zstd_skippable_frame_p(VALUE self, VALUE data) {
    (void)self;
    StringValue(data);
    unsigned result = ZSTD_isSkippableFrame(RSTRING_PTR(data), RSTRING_LEN(data));
    return result ? Qtrue : Qfalse;
}

.train_dict(*args) ⇒ Object

For large datasets, consider training on a representative subset to reduce memory footprint.



68
# File 'sig/vibe_zstd.rbs', line 68

def self.train_dict: (Array[String] samples, ?max_dict_size: Integer?) -> String

.train_dict_cover(*args) ⇒ Object

For large datasets, consider training on a representative subset to reduce memory footprint.



308
# File 'ext/vibe_zstd/dict.c', line 308

def self.train_dict_cover: (Array[String] samples, ?max_dict_size: Integer?, ?k: Integer?, ?d: Integer?, ?steps: Integer?, ?split_point: Float?, ?shrink_dict: bool?, ?shrink_dict_max_regression: Integer?, ?nb_threads: Integer?) -> String

.train_dict_fast_cover(*args) ⇒ Object

For large datasets, consider training on a representative subset to reduce memory footprint.



398
# File 'ext/vibe_zstd/dict.c', line 398

def self.train_dict_fast_cover: (Array[String] samples, ?max_dict_size: Integer?, ?k: Integer?, ?d: Integer?, ?f: Integer?, ?steps: Integer?, ?split_point: Float?, ?accel: Integer?, ?shrink_dict: bool?, ?shrink_dict_max_regression: Integer?, ?nb_threads: Integer?) -> String

.version_numberObject

Module-level version and compression level functions



253
254
255
256
257
# File 'ext/vibe_zstd/vibe_zstd.c', line 253

static VALUE
vibe_zstd_version_number(VALUE self) {
    (void)self;
    return UINT2NUM(ZSTD_versionNumber());
}

.version_stringObject



259
260
261
262
263
# File 'ext/vibe_zstd/vibe_zstd.c', line 259

static VALUE
vibe_zstd_version_string(VALUE self) {
    (void)self;
    return rb_str_new_cstr(ZSTD_versionString());
}

.write_skippable_frame(*args) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'ext/vibe_zstd/frames.c', line 20

static VALUE
vibe_zstd_write_skippable_frame(int argc, VALUE *argv, VALUE self) {
    (void)self;
    VALUE data, options;
    rb_scan_args(argc, argv, "11", &data, &options);

    StringValue(data);

    unsigned magic_variant = 0;  // Default to 0
    if (!NIL_P(options)) {
        Check_Type(options, T_HASH);
        VALUE magic_num = rb_hash_aref(options, ID2SYM(rb_intern("magic_number")));
        if (!NIL_P(magic_num)) {
            magic_variant = NUM2UINT(magic_num);
            if (magic_variant > 15) {
                rb_raise(rb_eArgError, "magic_number %u out of bounds (valid: 0-15)", magic_variant);
            }
        }
    }

    const char* src = RSTRING_PTR(data);
    size_t src_size = RSTRING_LEN(data);

    // Skippable frame structure: 4-byte magic (0x184D2A5X) + 4-byte size + content
    // Decoders skip these frames, allowing custom /padding
    size_t frame_size = 8 + src_size;
    VALUE result = rb_str_buf_new(frame_size);

    size_t written = ZSTD_writeSkippableFrame(
        RSTRING_PTR(result),
        frame_size,
        src,
        src_size,
        magic_variant
    );

    if (ZSTD_isError(written)) {
        rb_raise(rb_eRuntimeError, "Failed to write skippable frame: %s", ZSTD_getErrorName(written));
    }

    rb_str_set_len(result, written);
    return result;
}