Class: Containers::Bitset

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/containers/bitset.rb,
ext/containers/bitset/bitset.c

Overview

Copyright © 2011 Tyler McMullen

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ary) ⇒ Object


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'ext/containers/bitset/bitset.c', line 59

static VALUE rb_bitset_initialize(VALUE self, VALUE ary) {
    Bitset * bs = get_bitset(self);
    if (RB_TYPE_P(ary, T_ARRAY)) {
        int i;
        int len = (int) RARRAY_LEN(ary);
        bitset_setup(bs, len);
        for (i = 0; i < len; ++i) {
            // This could be more efficient, but if you're converting
            // from a Ruby array of bits, you're not looking
            // at blazing speed anyhow.
            if (RTEST(rb_ary_entry(ary, i))) {
                _set_bit(bs, i);
            }
        }
    } else {
        bitset_setup(bs, NUM2INT(ary));
    }
    return self;
}

Class Method Details

.from_s(s) ⇒ Object


347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'ext/containers/bitset/bitset.c', line 347

static VALUE rb_bitset_from_s(VALUE self, VALUE s) {
    int length = RSTRING_LEN(s);
    char* data = StringValuePtr(s);
    Bitset * new_bs = bitset_new();
    int i;

    bitset_setup(new_bs, length);

    for (i = 0; i < length; i++) {
        if (data[i] == '1') {
            _set_bit(new_bs, i);
        }
    }

    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

.unpack(str) ⇒ Object

Convert a string created using the pack method back into a bitset.


42
43
44
45
46
# File 'lib/containers/bitset.rb', line 42

def self.unpack str
  bits = str.unpack("b*")[0]
  padding_bits = bits[0...3].to_i(2)
  from_s(bits[3 .. -1 - padding_bits])
end

Instance Method Details

#==(other) ⇒ Object


569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'ext/containers/bitset/bitset.c', line 569

static VALUE rb_bitset_equal(VALUE self, VALUE other) {
    int i;
    Bitset * bs = get_bitset(self);
    Bitset * other_bs = get_bitset(other);
    int max = INTS(bs);

    if (bs->len != other_bs->len)
       return Qfalse;
    for(i = 0; i < max; i++) {
       if (bs->data[i] != other_bs->data[i]) {
          return Qfalse;
       }
    }
    return Qtrue;
}

#[](index) ⇒ Object


107
108
109
110
111
112
# File 'ext/containers/bitset/bitset.c', line 107

static VALUE rb_bitset_aref(VALUE self, VALUE index) {
    Bitset * bs = get_bitset(self);
    int idx = NUM2INT(index);
    validate_index(bs, idx);
    return _get_bit(bs, idx) > 0 ? Qtrue : Qfalse;
}

#[]=(index, value) ⇒ Object


114
115
116
117
118
119
120
# File 'ext/containers/bitset/bitset.c', line 114

static VALUE rb_bitset_aset(VALUE self, VALUE index, VALUE value) {
    Bitset * bs = get_bitset(self);
    int idx = NUM2INT(index);
    validate_index(bs, idx);
    assign_bit(bs, idx, value);
    return Qtrue;
}

#cardinalityObject


232
233
234
235
# File 'ext/containers/bitset/bitset.c', line 232

static VALUE rb_bitset_cardinality(VALUE self) {
    Bitset * bs = get_bitset(self);
    return INT2NUM(cardinality(bs));
}

#clear(*args) ⇒ Object


174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'ext/containers/bitset/bitset.c', line 174

static VALUE rb_bitset_clear(int argc, VALUE * argv, VALUE self) {
    int i;
    Bitset * bs = get_bitset(self);

    if (argc == 1 && rb_obj_is_kind_of(argv[0], rb_const_get(rb_cObject, rb_intern("Array")))) {
        for(i = 0; i < RARRAY_LEN(argv[0]); i++) {
            VALUE index = RARRAY_PTR(argv[0])[i];
            int idx = NUM2INT(index);
            validate_index(bs, idx);
            _clear_bit(bs, idx);
        }
    } else {
        for(i = 0; i < argc; i++) {
            VALUE index = argv[i];
            int idx = NUM2INT(index);
            validate_index(bs, idx);
            _clear_bit(bs, idx);
        }
    }
    return Qtrue;
}

#clear?(*args) ⇒ Boolean

Returns:

  • (Boolean)

196
197
198
199
200
201
202
203
204
205
206
207
# File 'ext/containers/bitset/bitset.c', line 196

static VALUE rb_bitset_clear_p(int argc, VALUE * argv, VALUE self) {
    int i;
    Bitset * bs = get_bitset(self);
    for(i = 0; i < argc; i++) {
        VALUE index = argv[i];
        int idx = NUM2INT(index);
        validate_index(bs, idx);
        if(_get_bit(bs, idx) > 0)
            return Qfalse;
    }
    return Qtrue;
}

#difference(other) ⇒ Object Also known as: -


277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'ext/containers/bitset/bitset.c', line 277

static VALUE rb_bitset_difference(VALUE self, VALUE other) {
    Bitset * bs = get_bitset(self);
    Bitset * other_bs = get_bitset(other);
    Bitset * new_bs;
    int max = INTS(bs);
    int i;

    verify_equal_size(bs, other_bs);
    new_bs = bitset_new();
    bitset_setup(new_bs, bs->len);

    for(i = 0; i < max; i++) {
        uint64_t segment = bs->data[i];
        uint64_t other_segment = other_bs->data[i];
        new_bs->data[i] = segment & ~other_segment;
    }

    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

#difference!(other) ⇒ Object


619
620
621
# File 'ext/containers/bitset/bitset.c', line 619

static VALUE rb_bitset_difference_mutable(VALUE self, VALUE other) {
    return mutable(self, other, &difference);
}

#dupObject Also known as: clone


428
429
430
431
432
433
434
435
436
437
# File 'ext/containers/bitset/bitset.c', line 428

static VALUE rb_bitset_dup(VALUE self) {
    Bitset * bs = get_bitset(self);
    int max = INTS(bs);

    Bitset * new_bs = bitset_new();
    bitset_setup(new_bs, bs->len);

    memcpy(new_bs->data, bs->data, max * sizeof(bs->data[0]));
    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

#eachObject


380
381
382
383
384
385
386
387
388
389
# File 'ext/containers/bitset/bitset.c', line 380

static VALUE rb_bitset_each(VALUE self) {
    Bitset * bs = get_bitset(self);
    int i;

    for(i = 0; i < bs->len; i++) {
        rb_yield(_get_bit(bs, i) ? Qtrue : Qfalse);
    }

    return self;
}

#each_set(*args) ⇒ Object Also known as: to_a

Yield the bit numbers of each set bit in sequence to a block. If

there is no block, return an array of those numbers.

441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
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
# File 'ext/containers/bitset/bitset.c', line 441

static VALUE rb_bitset_each_set(int argc, VALUE * argv,  VALUE self) {
    Bitset * bs = get_bitset(self);
    int seg_no;
    int max = INTS(bs);
    uint64_t* seg_ptr = bs->data;
    int block_p = rb_block_given_p();
    VALUE ary = Qnil;
    int set_bit_no = -1;

    /* If there is one argument, it is an index into the notional
       output array, and return an int. If there are two arguments,
       return up to <n> arguments where is the second argument. */
    int min_set_bit_no = (argc > 0) ? NUM2INT(argv[0]) : 0;
    int max_set_bit_no;

    if (argc > 2) {
       VALUE error = rb_const_get(rb_cObject, rb_intern("ArgumentError"));
       rb_raise(error, "wrong number of arguments (given %d, expected 0..2)",
                argc);
    }

    if (min_set_bit_no < 0) {
        /* Convert negative numbers into offsets from the end of the array. */
        min_set_bit_no = cardinality(bs) + min_set_bit_no;
    }

    max_set_bit_no = (argc == 0)
        ? INT_MAX
        : (argc == 1)
        ? (min_set_bit_no + 1)
        : (min_set_bit_no + NUM2INT(argv[1]));

    if (min_set_bit_no < 0 || max_set_bit_no < min_set_bit_no)
        return Qnil;

    if (argc != 1 && !block_p) {
       ary = rb_ary_new();
    }
    if (min_set_bit_no < 0 || max_set_bit_no < min_set_bit_no)
        return Qnil;

    for (seg_no = 0; seg_no < max; ++seg_no, ++seg_ptr) {
       uint64_t segment = *seg_ptr;
       int bit_position = 0;
       bool finished = false;
       while (segment) {
          VALUE v;

          if (!(segment & 1)) {
             int shift = psnip_builtin_ctz64(segment);
             bit_position += shift;
             segment >>= shift;
          }
          v = INT2NUM(_seg_no_to_bit_no(seg_no) + bit_position);
          ++bit_position;
          segment >>= 1;
          ++set_bit_no;
          if (set_bit_no < min_set_bit_no) {
             continue;
          }
          if (set_bit_no >= max_set_bit_no) {
              finished = true;
             break;
          }
          if (block_p) {
             rb_yield(v);
          } else if (argc == 1) {
              return v;
          } else {
             rb_ary_push(ary, v);
          }
       }
       if (finished) {
           break;
       }
    }

    return block_p ? self : ary;
}

#empty?Boolean

#each_set allows an optional block, and #to_a normally doesn’t.

But an alias is simpler than having two different functions.

Returns:

  • (Boolean)

521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'ext/containers/bitset/bitset.c', line 521

static VALUE rb_bitset_empty_p(VALUE self) {
    Bitset * bs = get_bitset(self);
    int seg_no;
    int max = INTS(bs);
    uint64_t* seg_ptr = bs->data;

    for (seg_no = 0; seg_no < max; ++seg_no, ++seg_ptr) {
       if (*seg_ptr) {
          return Qfalse;
       }
    }
    return Qtrue;
}

#flip(*args) ⇒ Object


144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'ext/containers/bitset/bitset.c', line 144

static VALUE rb_bitset_flip(int argc, VALUE * argv, VALUE self) {
    int i;
    Bitset * bs = get_bitset(self);

    if (argc == 1 && rb_obj_is_kind_of(argv[0], rb_const_get(rb_cObject, rb_intern("Array")))) {
        for(i = 0; i < RARRAY_LEN(argv[0]); i++) {
            VALUE index = RARRAY_PTR(argv[0])[i];
            int idx = NUM2INT(index);
            validate_index(bs, idx);
            if (_get_bit(bs, idx) == 0) {
                _set_bit(bs, idx);
            } else {
                _clear_bit(bs, idx);
            }
        }
    } else {
        for(i = 0; i < argc; i++) {
            VALUE index = argv[i];
            int idx = NUM2INT(index);
            validate_index(bs, idx);
            if (_get_bit(bs, idx) == 0) {
                _set_bit(bs, idx);
            } else {
                _clear_bit(bs, idx);
            }
        }
    }
    return Qtrue;
}

#hamming(other) ⇒ Object


364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'ext/containers/bitset/bitset.c', line 364

static VALUE rb_bitset_hamming(VALUE self, VALUE other) {
    Bitset * bs = get_bitset(self);
    Bitset * other_bs = get_bitset(other);

    int max = INTS(bs);
    int count = 0;
    int i;
    for(i = 0; i < max; i++) {
        uint64_t segment = bs->data[i];
        uint64_t other_segment = other_bs->data[i];
        count += psnip_builtin_popcount64(segment ^ other_segment);
    }

    return INT2NUM(count);
}

#intersect(other) ⇒ Object Also known as: &, and


237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'ext/containers/bitset/bitset.c', line 237

static VALUE rb_bitset_intersect(VALUE self, VALUE other) {
    Bitset * bs = get_bitset(self);
    Bitset * other_bs = get_bitset(other);
    Bitset * new_bs;
    int max = INTS(bs);
    int i;

    verify_equal_size(bs, other_bs);
    new_bs = bitset_new();
    bitset_setup(new_bs, bs->len);

    for(i = 0; i < max; i++) {
        uint64_t segment = bs->data[i];
        uint64_t other_segment = other_bs->data[i];
        new_bs->data[i] = segment & other_segment;
    }

    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

#intersect!(other) ⇒ Object Also known as: and!


611
612
613
# File 'ext/containers/bitset/bitset.c', line 611

static VALUE rb_bitset_intersect_mutable(VALUE self, VALUE other) {
    return mutable(self, other, &and);
}

#marshal_dumpObject


391
392
393
394
395
396
397
398
399
400
# File 'ext/containers/bitset/bitset.c', line 391

static VALUE rb_bitset_marshall_dump(VALUE self) {
    Bitset * bs = get_bitset(self);
    VALUE hash = rb_hash_new();
    VALUE data = rb_str_new((const char *) bs->data, BYTES(bs));

    rb_hash_aset(hash, ID2SYM(rb_intern("len")), UINT2NUM(bs->len));
    rb_hash_aset(hash, ID2SYM(rb_intern("data")), data);

    return hash;
}

#marshal_load(hash) ⇒ Object


402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'ext/containers/bitset/bitset.c', line 402

static VALUE rb_bitset_marshall_load(VALUE self, VALUE hash) {
    Bitset * bs = get_bitset(self);
    int len = NUM2INT(rb_hash_aref(hash, ID2SYM(rb_intern("len"))));

    VALUE data = rb_hash_aref(hash, ID2SYM(rb_intern("data")));

    bitset_setup(bs, len);

    bs->data = (uint64_t *) calloc(INTS(bs), sizeof(uint64_t));
    memcpy(bs->data, RSTRING_PTR(data), BYTES(bs));

    return Qnil;
}

#notObject Also known as: ~


317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'ext/containers/bitset/bitset.c', line 317

static VALUE rb_bitset_not(VALUE self) {
    Bitset * bs = get_bitset(self);
    Bitset * new_bs = bitset_new();
    int max = INTS(bs);
    int i;

    bitset_setup(new_bs, bs->len);
    for(i = 0; i < max; i++) {
        uint64_t segment = bs->data[i];
        new_bs->data[i] = ~segment;
    }
    if(_bit_no(bs->len) != 0)
        new_bs->data[max-1] &= _bit_mask(bs->len) - 1;

    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

#packObject

You could make a good case that this is redundant with Marshal.dump and Marshal.load, but it does save a few bytes.


34
35
36
37
38
39
# File 'lib/containers/bitset.rb', line 34

def pack
  # Number of bits of zero padding in this representation.
  padding_bits = (size+3) & 7
  padding_bits = (padding_bits == 0) ? 0 : (8 - padding_bits)
  [("%03b" % padding_bits) + self.to_s].pack("b*")
end

#reset!Object


623
624
625
626
627
# File 'ext/containers/bitset/bitset.c', line 623

static VALUE rb_bitset_reset(VALUE self) {
    Bitset * bs = get_bitset(self);
    memset(bs->data, 0, (INTS(bs) * sizeof(uint64_t)) );
    return self;
}

#reverse(index_array) ⇒ Object

This could run a bit faster if you worked at it.


554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'ext/containers/bitset/bitset.c', line 554

static VALUE rb_bitset_reverse(VALUE self, VALUE index_array) {
    int i;
    Bitset * bs = get_bitset(self);
    int len = bs->len;
    Bitset * new_bs = bitset_new();
    bitset_setup(new_bs, len);
    for (i = 0; i < len; ++i) {
       if (_get_bit(bs, i)) {
          _set_bit(new_bs, len - i - 1);
       }
    }

    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

#set(*args) ⇒ Object


122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'ext/containers/bitset/bitset.c', line 122

static VALUE rb_bitset_set(int argc, VALUE * argv, VALUE self) {
    int i;
    Bitset * bs = get_bitset(self);

    if (argc == 1 && rb_obj_is_kind_of(argv[0], rb_const_get(rb_cObject, rb_intern("Array")))) {
        for(i = 0; i < RARRAY_LEN(argv[0]); i++) {
            VALUE index = RARRAY_PTR(argv[0])[i];
            int idx = NUM2INT(index);
            validate_index(bs, idx);
            _set_bit(bs, idx);
        }
    } else {
        for(i = 0; i < argc; i++) {
            VALUE index = argv[i];
            int idx = NUM2INT(index);
            validate_index(bs, idx);
            _set_bit(bs, idx);
        }
    }
    return Qtrue;
}

#set?(*args) ⇒ Boolean

Returns:

  • (Boolean)

209
210
211
212
213
214
215
216
217
218
219
220
# File 'ext/containers/bitset/bitset.c', line 209

static VALUE rb_bitset_set_p(int argc, VALUE * argv, VALUE self) {
    int i;
    Bitset * bs = get_bitset(self);
    for(i = 0; i < argc; i++) {
        VALUE index = argv[i];
        int idx = NUM2INT(index);
        validate_index(bs, idx);
        if(_get_bit(bs, idx) == 0)
            return Qfalse;
    }
    return Qtrue;
}

#sizeObject Also known as: length


79
80
81
82
# File 'ext/containers/bitset/bitset.c', line 79

static VALUE rb_bitset_size(VALUE self) {
    Bitset * bs = get_bitset(self);
    return INT2NUM(bs->len);
}

#to_binary_arrayObject


416
417
418
419
420
421
422
423
424
425
426
# File 'ext/containers/bitset/bitset.c', line 416

static VALUE rb_bitset_to_binary_array(VALUE self) {
    Bitset * bs = get_bitset(self);
    int i;

    VALUE array = rb_ary_new2(bs->len / 2);
    for(i = 0; i < bs->len; i++) {
        rb_ary_push(array, INT2NUM(_get_bit(bs, i) > 0 ? 1 : 0));
    }

    return array;
}

#to_sObject Also known as: inspect


334
335
336
337
338
339
340
341
342
343
344
345
# File 'ext/containers/bitset/bitset.c', line 334

static VALUE rb_bitset_to_s(VALUE self) {
    Bitset * bs = get_bitset(self);

    int i;
    char * data = malloc(bs->len + 1);
    for(i = 0; i < bs->len; i++) {
        data[i] = _get_bit(bs, i)  ? '1' : '0';
    }
    data[bs->len] = 0;

    return rb_str_new2(data);
}

#union(other) ⇒ Object Also known as: |, or


257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'ext/containers/bitset/bitset.c', line 257

static VALUE rb_bitset_union(VALUE self, VALUE other) {
    Bitset * bs = get_bitset(self);
    Bitset * other_bs = get_bitset(other);
    Bitset * new_bs;
    int max = INTS(bs);
    int i;

    verify_equal_size(bs, other_bs);
    new_bs = bitset_new();
    bitset_setup(new_bs, bs->len);

    for(i = 0; i < max; i++) {
        uint64_t segment = bs->data[i];
        uint64_t other_segment = other_bs->data[i];
        new_bs->data[i] = segment | other_segment;
    }

    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

#union!(other) ⇒ Object Also known as: or!


607
608
609
# File 'ext/containers/bitset/bitset.c', line 607

static VALUE rb_bitset_union_mutable(VALUE self, VALUE other) {
    return mutable(self, other, &or);
}

#values_at(index_array) ⇒ Object Also known as: select_bits


535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'ext/containers/bitset/bitset.c', line 535

static VALUE rb_bitset_values_at(VALUE self, VALUE index_array) {
    int i;
    Bitset * bs = get_bitset(self);
    int blen = bs->len;
    int alen = RARRAY_LEN(index_array);
    VALUE *ptr = RARRAY_PTR(index_array);
    Bitset * new_bs = bitset_new();
    bitset_setup(new_bs, alen);
    for (i = 0; i < alen; ++i) {
       int idx = NUM2INT(ptr[i]);
       if (idx >= 0 && idx < blen && _get_bit(bs, idx)) {
          _set_bit(new_bs, i);
       }
    }

    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

#xor(other) ⇒ Object Also known as: ^, symmetric_difference


297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'ext/containers/bitset/bitset.c', line 297

static VALUE rb_bitset_xor(VALUE self, VALUE other) {
    Bitset * bs = get_bitset(self);
    Bitset * other_bs = get_bitset(other);
    Bitset * new_bs;
    int max = INTS(bs);
    int i;

    verify_equal_size(bs, other_bs);
    new_bs = bitset_new();
    bitset_setup(new_bs, bs->len);

    for(i = 0; i < max; i++) {
        uint64_t segment = bs->data[i];
        uint64_t other_segment = other_bs->data[i];
        new_bs->data[i] = segment ^ other_segment;
    }

    return Data_Wrap_Struct(cBitset, 0, bitset_free, new_bs);
}

#xor!(other) ⇒ Object Also known as: symmetric_difference!


615
616
617
# File 'ext/containers/bitset/bitset.c', line 615

static VALUE rb_bitset_xor_mutable(VALUE self, VALUE other) {
    return mutable(self, other, &xor);
}