Class: FastBloomFilter::Filter

Inherits:
Object
  • Object
show all
Defined in:
lib/fast_bloom_filter.rb,
ext/fast_bloom_filter/fast_bloom_filter.c

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Object



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 360

static VALUE bloom_initialize(int argc, VALUE *argv, VALUE self) {
    VALUE opts = Qnil;

    if (argc == 0) {
    } else if (argc == 1 && RB_TYPE_P(argv[0], T_HASH)) {
        opts = argv[0];
    } else {
        rb_raise(rb_eArgError,
                 "wrong number of arguments (given %d, expected 0 or keyword arguments)", argc);
    }

    double error_rate = DEFAULT_ERROR_RATE;
    size_t initial_capacity = DEFAULT_INITIAL_CAP;
    double tightening = DEFAULT_TIGHTENING;

    if (!NIL_P(opts)) {
        VALUE v;
        v = rb_hash_aref(opts, ID2SYM(rb_intern("error_rate")));
        if (!NIL_P(v))
            error_rate = NUM2DBL(v);
        v = rb_hash_aref(opts, ID2SYM(rb_intern("initial_capacity")));
        if (!NIL_P(v))
            initial_capacity = (size_t)NUM2LONG(v);
        v = rb_hash_aref(opts, ID2SYM(rb_intern("tightening")));
        if (!NIL_P(v))
            tightening = NUM2DBL(v);
    }

    if (error_rate <= 0 || error_rate >= 1)
        rb_raise(rb_eArgError, "error_rate must be between 0 and 1 (exclusive)");
    if (initial_capacity == 0)
        rb_raise(rb_eArgError, "initial_capacity must be positive");
    if (tightening <= 0 || tightening >= 1)
        rb_raise(rb_eArgError, "tightening must be between 0 and 1 (exclusive)");

    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    sb->error_rate = error_rate;
    sb->initial_capacity = initial_capacity;
    sb->tightening = tightening;
    sb->total_count = 0;

    if (!scalable_add_layer(sb))
        rb_raise(rb_eNoMemError, "failed to allocate initial layer");

    return self;
}

Class Method Details

.load(data) ⇒ Object



673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 673

static VALUE bloom_load(VALUE klass, VALUE data) {
    Check_Type(data, T_STRING);

    const uint8_t *buf = (const uint8_t *)RSTRING_PTR(data);
    size_t data_len = (size_t)RSTRING_LEN(data);

    if (data_len < HEADER_SIZE)
        rb_raise(rb_eArgError, "data too short for bloom filter header");

    size_t off = 0;
    uint32_t version = read_le32(buf + off);
    off += 4;
    if (version != SERIAL_VERSION)
        rb_raise(rb_eArgError, "unsupported serialization version: %u", version);
    off += 4;

    VALUE obj = bloom_alloc(klass);
    ScalableBloom *sb;
    TypedData_Get_Struct(obj, ScalableBloom, &scalable_bloom_type, sb);

    sb->error_rate = read_le_double(buf + off);
    off += 8;
    sb->tightening = read_le_double(buf + off);
    off += 8;
    sb->initial_capacity = (size_t)read_le64(buf + off);
    off += 8;
    sb->total_count = (size_t)read_le64(buf + off);
    off += 8;

    size_t num_layers = (size_t)read_le64(buf + off);
    off += 8;

    if (sb->error_rate <= 0 || sb->error_rate >= 1)
        rb_raise(rb_eArgError, "invalid error_rate in serialized data");
    if (sb->tightening <= 0 || sb->tightening >= 1)
        rb_raise(rb_eArgError, "invalid tightening in serialized data");
    if (num_layers > 1000)
        rb_raise(rb_eArgError, "unreasonable number of layers: %zu", num_layers);

    sb->layers_cap = num_layers < 4 ? 4 : num_layers;
    sb->layers = (BloomLayer **)calloc(sb->layers_cap, sizeof(BloomLayer *));
    if (!sb->layers)
        rb_raise(rb_eNoMemError, "failed to allocate layers array");

    for (size_t i = 0; i < num_layers; i++) {
        if (off + LAYER_META > data_len) {
            for (size_t j = 0; j < sb->num_layers; j++)
                layer_free(sb->layers[j]);
            sb->num_layers = 0;
            rb_raise(rb_eArgError, "data truncated at layer %zu metadata", i);
        }

        BloomLayer *l = (BloomLayer *)calloc(1, sizeof(BloomLayer));
        if (!l) {
            for (size_t j = 0; j < sb->num_layers; j++)
                layer_free(sb->layers[j]);
            sb->num_layers = 0;
            rb_raise(rb_eNoMemError, "failed to allocate layer");
        }

        l->capacity = (size_t)read_le64(buf + off);
        off += 8;
        l->count = (size_t)read_le64(buf + off);
        off += 8;
        l->size = (size_t)read_le64(buf + off);
        off += 8;
        l->num_hashes = (int)read_le32(buf + off);
        off += 4;
        off += 4;

        if (l->size > (1ULL << 30) || off + l->size > data_len) {
            free(l);
            for (size_t j = 0; j < sb->num_layers; j++)
                layer_free(sb->layers[j]);
            sb->num_layers = 0;
            rb_raise(rb_eArgError, "invalid or truncated layer %zu", i);
        }

        l->bits = (uint8_t *)malloc(l->size);
        if (!l->bits) {
            free(l);
            for (size_t j = 0; j < sb->num_layers; j++)
                layer_free(sb->layers[j]);
            sb->num_layers = 0;
            rb_raise(rb_eNoMemError, "failed to allocate bits");
        }
        memcpy(l->bits, buf + off, l->size);
        off += l->size;

        sb->layers[sb->num_layers++] = l;
    }

    return obj;
}

Instance Method Details

#<<(str) ⇒ Object



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 409

static VALUE bloom_add(VALUE self, VALUE str) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    str = StringValue(str);

    BloomLayer *active = sb->layers[sb->num_layers - 1];
    if (layer_is_full(active)) {
        active = scalable_add_layer(sb);
        if (!active)
            rb_raise(rb_eNoMemError, "failed to allocate new layer");
    }

    layer_add(active, RSTRING_PTR(str), RSTRING_LEN(str));
    sb->total_count++;

    return Qtrue;
}

#add(str) ⇒ Object



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 409

static VALUE bloom_add(VALUE self, VALUE str) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    str = StringValue(str);

    BloomLayer *active = sb->layers[sb->num_layers - 1];
    if (layer_is_full(active)) {
        active = scalable_add_layer(sb);
        if (!active)
            rb_raise(rb_eNoMemError, "failed to allocate new layer");
    }

    layer_add(active, RSTRING_PTR(str), RSTRING_LEN(str));
    sb->total_count++;

    return Qtrue;
}

#add_all(items) ⇒ Object



20
21
22
23
# File 'lib/fast_bloom_filter.rb', line 20

def add_all(items)
  items.each { |item| add(item.to_s) }
  self
end

#add_if_absent(str) ⇒ Object



428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 428

static VALUE bloom_add_if_absent(VALUE self, VALUE str) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    str = StringValue(str);
    const char *data = RSTRING_PTR(str);
    size_t len = RSTRING_LEN(str);

    for (size_t i = sb->num_layers; i > 0; i--) {
        if (sb->layers[i - 1]->count == 0)
            continue;
        if (layer_include(sb->layers[i - 1], data, len))
            return Qfalse;
    }

    BloomLayer *active = sb->layers[sb->num_layers - 1];
    if (layer_is_full(active)) {
        active = scalable_add_layer(sb);
        if (!active)
            rb_raise(rb_eNoMemError, "failed to allocate new layer");
    }

    layer_add(active, data, len);
    sb->total_count++;

    return Qtrue;
}

#clearObject



473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 473

static VALUE bloom_clear(VALUE self) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    for (size_t i = 0; i < sb->num_layers; i++)
        layer_free(sb->layers[i]);
    sb->num_layers = 0;
    sb->total_count = 0;

    if (!scalable_add_layer(sb))
        rb_raise(rb_eNoMemError, "failed to allocate layer after clear");

    return Qnil;
}

#countObject



541
542
543
544
545
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 541

static VALUE bloom_count(VALUE self) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);
    return LONG2NUM(sb->total_count);
}

#count_possible_matches(items) ⇒ Object



25
26
27
# File 'lib/fast_bloom_filter.rb', line 25

def count_possible_matches(items)
  items.count { |item| include?(item.to_s) }
end

#dumpObject



626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 626

static VALUE bloom_dump(VALUE self) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    size_t total_size = HEADER_SIZE;
    for (size_t i = 0; i < sb->num_layers; i++)
        total_size += LAYER_META + sb->layers[i]->size;

    VALUE str = rb_str_buf_new((long)total_size);
    rb_str_set_len(str, (long)total_size);
    uint8_t *buf = (uint8_t *)RSTRING_PTR(str);
    size_t off = 0;

    write_le32(buf + off, SERIAL_VERSION);
    off += 4;
    write_le32(buf + off, 0);
    off += 4;
    write_le_double(buf + off, sb->error_rate);
    off += 8;
    write_le_double(buf + off, sb->tightening);
    off += 8;
    write_le64(buf + off, (uint64_t)sb->initial_capacity);
    off += 8;
    write_le64(buf + off, (uint64_t)sb->total_count);
    off += 8;
    write_le64(buf + off, (uint64_t)sb->num_layers);
    off += 8;

    for (size_t i = 0; i < sb->num_layers; i++) {
        BloomLayer *l = sb->layers[i];
        write_le64(buf + off, (uint64_t)l->capacity);
        off += 8;
        write_le64(buf + off, (uint64_t)l->count);
        off += 8;
        write_le64(buf + off, (uint64_t)l->size);
        off += 8;
        write_le32(buf + off, (uint32_t)l->num_hashes);
        off += 4;
        write_le32(buf + off, 0);
        off += 4;
        memcpy(buf + off, l->bits, l->size);
        off += l->size;
    }

    return str;
}

#include?(str) ⇒ Boolean

Returns:

  • (Boolean)


456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 456

static VALUE bloom_include(VALUE self, VALUE str) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    str = StringValue(str);
    const char *data = RSTRING_PTR(str);
    size_t len = RSTRING_LEN(str);

    for (size_t i = sb->num_layers; i > 0; i--) {
        if (sb->layers[i - 1]->count == 0)
            continue;
        if (layer_include(sb->layers[i - 1], data, len))
            return Qtrue;
    }
    return Qfalse;
}

#inspectObject



29
30
31
32
33
34
35
36
# File 'lib/fast_bloom_filter.rb', line 29

def inspect
  s = stats
  total_kb = (s[:total_bytes] / 1024.0).round(2)
  fill_pct = (s[:fill_ratio] * 100).round(2)

  "#<FastBloomFilter::Filter v2 layers=#{s[:num_layers]} " \
  "count=#{s[:total_count]} size=#{total_kb}KB fill=#{fill_pct}%>"
end

#member?(str) ⇒ Boolean

Returns:

  • (Boolean)


456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 456

static VALUE bloom_include(VALUE self, VALUE str) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    str = StringValue(str);
    const char *data = RSTRING_PTR(str);
    size_t len = RSTRING_LEN(str);

    for (size_t i = sb->num_layers; i > 0; i--) {
        if (sb->layers[i - 1]->count == 0)
            continue;
        if (layer_include(sb->layers[i - 1], data, len))
            return Qtrue;
    }
    return Qfalse;
}

#merge!(other) ⇒ Object



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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 553

static VALUE bloom_merge(VALUE self, VALUE other) {
    ScalableBloom *sb1, *sb2;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb1);
    TypedData_Get_Struct(other, ScalableBloom, &scalable_bloom_type, sb2);

    if (fabs(sb1->error_rate - sb2->error_rate) > 1e-10)
        rb_raise(rb_eArgError, "cannot merge filters with different error rates (%.6f vs %.6f)",
                 sb1->error_rate, sb2->error_rate);
    if (fabs(sb1->tightening - sb2->tightening) > 1e-10)
        rb_raise(rb_eArgError,
                 "cannot merge filters with different tightening ratios (%.6f vs %.6f)",
                 sb1->tightening, sb2->tightening);

    for (size_t i = 0; i < sb2->num_layers; i++) {
        BloomLayer *src = sb2->layers[i];
        int merged = 0;

        if (i < sb1->num_layers) {
            BloomLayer *dst = sb1->layers[i];
            if (dst->size == src->size && dst->num_hashes == src->num_hashes) {
                size_t j = 0;
                for (; j + 8 <= dst->size; j += 8) {
                    uint64_t a, b;
                    memcpy(&a, dst->bits + j, 8);
                    memcpy(&b, src->bits + j, 8);
                    a |= b;
                    memcpy(dst->bits + j, &a, 8);
                }
                for (; j < dst->size; j++)
                    dst->bits[j] |= src->bits[j];

                size_t new_count = dst->count + src->count;
                dst->count = new_count < dst->capacity ? new_count : dst->capacity;
                merged = 1;
            }
        }

        if (!merged) {
            BloomLayer *copy = (BloomLayer *)calloc(1, sizeof(BloomLayer));
            if (!copy)
                rb_raise(rb_eNoMemError, "failed to allocate layer copy");

            copy->size = src->size;
            copy->capacity = src->capacity;
            copy->count = src->count;
            copy->num_hashes = src->num_hashes;
            copy->bits = (uint8_t *)malloc(src->size);
            if (!copy->bits) {
                free(copy);
                rb_raise(rb_eNoMemError, "failed to allocate bits");
            }
            memcpy(copy->bits, src->bits, src->size);

            if (sb1->num_layers >= sb1->layers_cap) {
                size_t new_slots = sb1->layers_cap == 0 ? 4 : sb1->layers_cap * 2;
                BloomLayer **tmp =
                    (BloomLayer **)realloc(sb1->layers, new_slots * sizeof(BloomLayer *));
                if (!tmp) {
                    layer_free(copy);
                    rb_raise(rb_eNoMemError, "realloc failed");
                }
                sb1->layers = tmp;
                sb1->layers_cap = new_slots;
            }
            sb1->layers[sb1->num_layers++] = copy;
        }
    }

    size_t new_total = sb1->total_count + sb2->total_count;
    sb1->total_count = new_total >= sb1->total_count ? new_total : SIZE_MAX;
    return self;
}

#num_layersObject



547
548
549
550
551
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 547

static VALUE bloom_num_layers(VALUE self) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);
    return LONG2NUM(sb->num_layers);
}

#sizeObject



541
542
543
544
545
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 541

static VALUE bloom_count(VALUE self) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);
    return LONG2NUM(sb->total_count);
}

#statsObject



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
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
# File 'ext/fast_bloom_filter/fast_bloom_filter.c', line 488

static VALUE bloom_stats(VALUE self) {
    ScalableBloom *sb;
    TypedData_Get_Struct(self, ScalableBloom, &scalable_bloom_type, sb);

    size_t total_bytes = 0;
    size_t total_bits = 0;
    size_t total_bits_set = 0;
    double combined_fpr = 1.0;

    VALUE layers_ary = rb_ary_new_capa((long)sb->num_layers);

    for (size_t i = 0; i < sb->num_layers; i++) {
        BloomLayer *l = sb->layers[i];
        size_t bs = layer_bits_set(l);
        size_t tb = l->size * 8;
        double est_fpr = layer_estimated_fpr(l);

        total_bytes += l->size;
        total_bits += tb;
        total_bits_set += bs;
        combined_fpr *= (1.0 - est_fpr);

        VALUE lh = rb_hash_new();
        rb_hash_aset(lh, ID2SYM(rb_intern("layer")), LONG2NUM(i));
        rb_hash_aset(lh, ID2SYM(rb_intern("capacity")), LONG2NUM(l->capacity));
        rb_hash_aset(lh, ID2SYM(rb_intern("count")), LONG2NUM(l->count));
        rb_hash_aset(lh, ID2SYM(rb_intern("size_bytes")), LONG2NUM(l->size));
        rb_hash_aset(lh, ID2SYM(rb_intern("num_hashes")), INT2NUM(l->num_hashes));
        rb_hash_aset(lh, ID2SYM(rb_intern("bits_set")), LONG2NUM(bs));
        rb_hash_aset(lh, ID2SYM(rb_intern("total_bits")), LONG2NUM(tb));
        rb_hash_aset(lh, ID2SYM(rb_intern("fill_ratio")), DBL2NUM((double)bs / tb));
        rb_hash_aset(lh, ID2SYM(rb_intern("target_error_rate")),
                     DBL2NUM(layer_error_rate(sb->error_rate, sb->tightening, i)));
        rb_hash_aset(lh, ID2SYM(rb_intern("estimated_error_rate")), DBL2NUM(est_fpr));
        rb_ary_push(layers_ary, lh);
    }

    double total_est_fpr = 1.0 - combined_fpr;

    VALUE hash = rb_hash_new();
    rb_hash_aset(hash, ID2SYM(rb_intern("total_count")), LONG2NUM(sb->total_count));
    rb_hash_aset(hash, ID2SYM(rb_intern("num_layers")), LONG2NUM(sb->num_layers));
    rb_hash_aset(hash, ID2SYM(rb_intern("total_bytes")), LONG2NUM(total_bytes));
    rb_hash_aset(hash, ID2SYM(rb_intern("total_bits")), LONG2NUM(total_bits));
    rb_hash_aset(hash, ID2SYM(rb_intern("total_bits_set")), LONG2NUM(total_bits_set));
    rb_hash_aset(hash, ID2SYM(rb_intern("fill_ratio")),
                 DBL2NUM((double)total_bits_set / total_bits));
    rb_hash_aset(hash, ID2SYM(rb_intern("target_error_rate")), DBL2NUM(sb->error_rate));
    rb_hash_aset(hash, ID2SYM(rb_intern("estimated_error_rate")), DBL2NUM(total_est_fpr));
    rb_hash_aset(hash, ID2SYM(rb_intern("layers")), layers_ary);
    return hash;
}

#to_sObject



38
39
40
# File 'lib/fast_bloom_filter.rb', line 38

def to_s
  inspect
end