bitmagic-sys 0.2.4+bitmagic.7.7.7

Low-level bindings for the bitmagic.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
63
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
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
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
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
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
625
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
672
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
#ifndef BMALGO__H__INCLUDED__
#define BMALGO__H__INCLUDED__
/*
Copyright(c) 2002-2017 Anatoliy Kuznetsov(anatoliy_kuznetsov at yahoo.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

For more information please visit:  http://bitmagic.io
*/

/*! \file bmalgo.h
    \brief Algorithms for bvector<> (main include)
*/

#ifndef BM__H__INCLUDED__
// BitMagic utility headers do not include main "bm.h" declaration 
// #include "bm.h" or "bm64.h" explicitly 
# error missing include (bm.h or bm64.h)
#endif

#include "bmfunc.h"
#include "bmdef.h"

#include "bmalgo_impl.h"



namespace bm
{

/*!
    \brief Computes bitcount of AND operation of two bitsets
    \param bv1 - Argument bit-vector.
    \param bv2 - Argument bit-vector.
    \return bitcount of the result
    \ingroup  setalgo
*/
template<class BV>
typename BV::size_type count_and(const BV& bv1, const BV& bv2) BMNOEXCEPT
{
    return bm::distance_and_operation(bv1, bv2);
}

/*!
   \brief Computes if there is any bit in AND operation of two bitsets
   \param bv1 - Argument bit-vector.
   \param bv2 - Argument bit-vector.
   \return non zero value if there is any bit
   \ingroup  setalgo
*/
template<class BV>
typename BV::size_type any_and(const BV& bv1, const BV& bv2) BMNOEXCEPT
{
    distance_metric_descriptor dmd(bm::COUNT_AND);

    distance_operation_any(bv1, bv2, &dmd, &dmd + 1);
    return dmd.result;
}



/*!
   \brief Computes bitcount of XOR operation of two bitsets
   \param bv1 - Argument bit-vector.
   \param bv2 - Argument bit-vector.
   \return bitcount of the result
   \ingroup  setalgo
*/
template<class BV>
bm::distance_metric_descriptor::size_type
count_xor(const BV& bv1, const BV& bv2) BMNOEXCEPT
{
    distance_metric_descriptor dmd(bm::COUNT_XOR);

    distance_operation(bv1, bv2, &dmd, &dmd + 1);
    return dmd.result;
}

/*!
   \brief Computes if there is any bit in XOR operation of two bitsets
   \param bv1 - Argument bit-vector.
   \param bv2 - Argument bit-vector.
   \return non zero value if there is any bit
   \ingroup  setalgo
*/
template<class BV>
typename BV::size_type any_xor(const BV& bv1, const BV& bv2) BMNOEXCEPT
{
    distance_metric_descriptor dmd(bm::COUNT_XOR);

    distance_operation_any(bv1, bv2, &dmd, &dmd + 1);
    return dmd.result;
}



/*!
   \brief Computes bitcount of SUB operation of two bitsets
   \param bv1 - Argument bit-vector.
   \param bv2 - Argument bit-vector.
   \return bitcount of the result
   \ingroup  setalgo
*/
template<class BV>
typename BV::size_type count_sub(const BV& bv1, const BV& bv2) BMNOEXCEPT
{
    distance_metric_descriptor dmd(bm::COUNT_SUB_AB);

    distance_operation(bv1, bv2, &dmd, &dmd + 1);
    return dmd.result;
}


/*!
   \brief Computes if there is any bit in SUB operation of two bitsets
   \param bv1 - Argument bit-vector.
   \param bv2 - Argument bit-vector.
   \return non zero value if there is any bit
   \ingroup  setalgo
*/
template<class BV>
typename BV::size_type any_sub(const BV& bv1, const BV& bv2) BMNOEXCEPT
{
    distance_metric_descriptor dmd(bm::COUNT_SUB_AB);

    distance_operation_any(bv1, bv2, &dmd, &dmd + 1);
    return dmd.result;
}


/*!
   \brief Computes bitcount of OR operation of two bitsets
   \param bv1 - Argument bit-vector.
   \param bv2 - Argument bit-vector.
   \return bitcount of the result
   \ingroup  setalgo
*/
template<class BV>
typename BV::size_type count_or(const BV& bv1, const BV& bv2) BMNOEXCEPT
{
    distance_metric_descriptor dmd(bm::COUNT_OR);

    distance_operation(bv1, bv2, &dmd, &dmd + 1);
    return dmd.result;
}

/*!
   \brief Computes if there is any bit in OR operation of two bitsets
   \param bv1 - Argument bit-vector.
   \param bv2 - Argument bit-vector.
   \return non zero value if there is any bit
   \ingroup  setalgo
*/
template<class BV>
typename BV::size_type any_or(const BV& bv1, const BV& bv2) BMNOEXCEPT
{
    distance_metric_descriptor dmd(bm::COUNT_OR);

    distance_operation_any(bv1, bv2, &dmd, &dmd + 1);
    return dmd.result;
}



#define BM_SCANNER_OP(x) \
if (0 != (block = blk_blk[j+x])) \
{ \
    if (BM_IS_GAP(block)) \
    { \
        bm::for_each_gap_blk(BMGAP_PTR(block), (r+j+x)*bm::bits_in_block,\
                             bit_functor); \
    } \
    else \
    { \
        bm::for_each_bit_blk(block, (r+j+x)*bm::bits_in_block,bit_functor); \
    } \
}
    

/**
    @brief bit-vector visitor scanner to traverse each 1 bit using C++ visitor
 
    @param bv - bit vector to scan
    @param bit_functor - visitor: should support add_bits(), add_range()
 
    \ingroup setalgo
    @sa for_each_bit_range visit_each_bit
*/
template<class BV, class Func>
void for_each_bit(const BV&    bv,
                  Func&        bit_functor)
{
    typedef typename BV::size_type size_type;

    const typename BV::blocks_manager_type& bman = bv.get_blocks_manager();
    bm::word_t*** blk_root = bman.top_blocks_root();
    
    if (!blk_root)
        return;
    
    unsigned tsize = bman.top_block_size();
    for (unsigned i = 0; i < tsize; ++i)
    {
        bm::word_t** blk_blk = blk_root[i];
        if (!blk_blk)
            continue;

        if ((bm::word_t*)blk_blk == FULL_BLOCK_FAKE_ADDR)
            blk_blk = FULL_SUB_BLOCK_REAL_ADDR;
        
        const bm::word_t* block;
        size_type r = size_type(i) * bm::set_sub_array_size;
        unsigned j = 0;
        do
        {
        #ifdef BM64_AVX2
            if (!avx2_test_all_zero_wave(blk_blk + j))
            {
                BM_SCANNER_OP(0)
                BM_SCANNER_OP(1)
                BM_SCANNER_OP(2)
                BM_SCANNER_OP(3)
            }
            j += 4;
        #elif defined(BM64_SSE4)
            if (!sse42_test_all_zero_wave(blk_blk + j))
            {
                BM_SCANNER_OP(0)
                BM_SCANNER_OP(1)
            }
            j += 2;
        #else
            BM_SCANNER_OP(0)
            ++j;
        #endif
        
        } while (j < bm::set_sub_array_size);
        
    }  // for i
}

/**
    @brief bit-vector range visitor to traverse each 1 bit

    @param bv - bit vector to scan
    @param right - start of closed interval [from..to]
    @param left   - end of close interval [from..to]
    @param bit_functor - visitor: should support add_bits(), add_range()

    \ingroup setalgo
    @sa for_each_bit
*/
template<class BV, class Func>
void for_each_bit_range(const BV&             bv,
                       typename BV::size_type left,
                       typename BV::size_type right,
                       Func&                  bit_functor)
{
    if (left > right)
        bm::xor_swap(left, right);
    if (right == bm::id_max)
        --right;
    BM_ASSERT(left < bm::id_max && right < bm::id_max);

    bm::for_each_bit_range_no_check(bv, left, right, bit_functor);
}


#undef BM_SCANNER_OP


/// private adaptor for C-style callbacks
///
/// @internal
///
template <class VCBT, class size_type>
struct bit_vitor_callback_adaptor
{
    typedef VCBT bit_visitor_callback_type;

    bit_vitor_callback_adaptor(void* h, bit_visitor_callback_type cb_func)
        : handle_(h), func_(cb_func)
    {}

    void add_bits(size_type offset, const unsigned char* bits, unsigned size)
    {
        for (unsigned i = 0; i < size; ++i)
            func_(handle_, offset + bits[i]);
    }
    void add_range(size_type offset, size_type size)
    {
        for (size_type i = 0; i < size; ++i)
            func_(handle_, offset + i);
    }

    void* handle_;
    bit_visitor_callback_type func_;
};


/// Functor for bit-copy (for testing)
///
/// @internal
///
template <class BV>
struct bit_vistor_copy_functor
{
    typedef typename BV::size_type size_type;

    bit_vistor_copy_functor(BV& bv)
        : bv_(bv)
    {
        bv_.init();
    }

    void add_bits(size_type offset, const unsigned char* bits, unsigned size)
    {
        BM_ASSERT(size);
        for (unsigned i = 0; i < size; ++i)
            bv_.set_bit_no_check(offset + bits[i]);
    }
    void add_range(size_type offset, size_type size)
    {
        BM_ASSERT(size);
        bv_.set_range(offset, offset + size - 1);
    }

    BV& bv_;
    bit_visitor_callback_type func_;
};



/**
    @brief bvector visitor scanner to traverse each 1 bit using C callback
 
    @param bv - bit vector to scan
    @param handle_ptr - handle to private memory used by callback
    @param callback_ptr - callback function
 
    \ingroup setalgo
 
    @sa bit_visitor_callback_type
*/
template<class BV>
void visit_each_bit(const BV&                 bv,
                    void*                     handle_ptr,
                    bit_visitor_callback_type callback_ptr)
{
    typedef typename BV::size_type size_type;
    bm::bit_vitor_callback_adaptor<bit_visitor_callback_type, size_type>
            func(handle_ptr, callback_ptr);
    bm::for_each_bit(bv, func);
}

/**
    @brief bvector visitor scanner to traverse each bits in range (C callback)

    @param bv - bit vector to scan
    @param left - from [left..right]
    @param right - to [left..right]
    @param handle_ptr - handle to private memory used by callback
    @param callback_ptr - callback function

    \ingroup setalgo

    @sa bit_visitor_callback_type for_each_bit
*/
template<class BV>
void visit_each_bit_range(const BV&                 bv,
                          typename BV::size_type    left,
                          typename BV::size_type    right,
                          void*                     handle_ptr,
                          bit_visitor_callback_type callback_ptr)
{
    typedef typename BV::size_type size_type;
    bm::bit_vitor_callback_adaptor<bit_visitor_callback_type, size_type>
            func(handle_ptr, callback_ptr);
    bm::for_each_bit_range(bv, left, right, func);
}

/**
    @brief Algorithm to identify bit-vector ranges (splits) for the rank

    Rank range split algorithm walks the bit-vector to create list of
    non-overlapping ranges [s1..e1],[s2..e2]...[sN...eN] with requested
    (rank) number of 1 bits. All ranges should be the same popcount weight,
    except the last one, which may have less.
    Scan is progressing from left to right so result ranges will be
    naturally sorted.

    @param bv       - bit vector to perform the range split scan
    @param rank     - requested number of bits in each range
                      if 0 it will create single range [first..last]
                      to cover the whole bv
    @param target_v - [out] STL(or STL-like) vector of pairs to keep pairs results

    \ingroup setalgo
 */
template<typename BV, typename PairVect>
void rank_range_split(const BV&              bv,
                      typename BV::size_type rank,
                      PairVect&              target_v)
{
    target_v.resize(0);
    typename BV::size_type first, last, pos;
    bool found = bv.find_range(first, last);
    if (!found) // empty bit-vector
        return;

    if (!rank) // if rank is not defined, include the whole vector [first..last]
    {
        typename PairVect::value_type pv;
        pv.first = first; pv.second = last;
        target_v.push_back(pv);
        return;
    }

    while (1)
    {
        typename PairVect::value_type pv;
        found = bv.find_rank(rank, first, pos);
        if (found)
        {
            pv.first = first; pv.second = pos;
            target_v.push_back(pv);
            if (pos >= last)
                break;
            first = pos + 1;
            continue;
        }
        // insufficient rank (last range)
        found = bv.any_range(first, last);
        if (found)
        {
            pv.first = first; pv.second = last;
            target_v.push_back(pv);
        }
        break;
    } // while

}



/**
    Algorithms for rank compression of bit-vector

    1. Source vector (bv_src) is a subset of index vector (bv_idx)
    2. As a subset it can be collapsed using bit-rank method, where each position
    in the source vector is defined by population count (range)
    [0..index_position] (count_range())
    As a result all integer set of source vector gets re-mapped in
    accord with the index vector.
 
    \ingroup setalgo
*/
template<typename BV>
class rank_compressor
{
public:
    typedef BV                         bvector_type;
    typedef typename BV::size_type     size_type;
    typedef typename BV::rs_index_type rs_index_type;
    enum buffer_cap
    {
        n_buffer_cap = 1024
    };
public:

    /**
    Rank decompression
    */
    void decompress(BV& bv_target, const BV& bv_idx, const BV& bv_src);

    /**
    Rank compression algorithm based on two palallel iterators/enumerators
    set of source vector gets re-mapped in accord with the index/rank vector.

    \param bv_target - target bit-vector
    \param bv_idx    - index (rank) vector used for address recalculation
    \param bv_src    - source vector for re-mapping
    */
    void compress(BV& bv_target, const BV& bv_idx, const BV& bv_src);
    
    /**
    \brief Source vector priority + index based rank
    
    @sa compress
    */
    void compress_by_source(BV& bv_target,
                                const BV& bv_idx,
                                const rs_index_type& bc_idx,
                                const BV& bv_src);
};


// ------------------------------------------------------------------------
//
// ------------------------------------------------------------------------


template<class BV>
void rank_compressor<BV>::compress(BV& bv_target,
                                   const BV& bv_idx,
                                   const BV& bv_src)
{
    bv_target.clear();
    bv_target.init();

    if (&bv_idx == &bv_src)
    {
        bv_target = bv_src;
        return;
    }
    size_type ibuffer[n_buffer_cap];
    size_type b_size;
    
    typedef typename BV::enumerator enumerator_t;
    enumerator_t en_s = bv_src.first();
    enumerator_t en_i = bv_idx.first();

    size_type r_idx = b_size = 0;
    size_type i, s;
    
    for (; en_i.valid(); )
    {
        if (!en_s.valid())
            break;
        i = *en_i; s = *en_s;

        BM_ASSERT(s >= i);
        BM_ASSERT(bv_idx.test(i));

        if (i == s)
        {
            ibuffer[b_size++] = r_idx++;
            if (b_size == n_buffer_cap)
            {
                bv_target.set(ibuffer, b_size, bm::BM_SORTED);
                b_size = 0;
            }
            ++en_i; ++en_s;
            continue;
        }
        BM_ASSERT(s > i);
        
        size_type dist = s - i;
        if (dist >= 64) // sufficiently far away, jump
        {
            size_type r_dist = bv_idx.count_range(i + 1, s);
            r_idx += r_dist;
            en_i.go_to(s);
            BM_ASSERT(en_i.valid());
        }
        else  // small distance, iterate to close the gap
        {
            for (; s > i; ++r_idx)
            {
                ++en_i;
                i = *en_i;
            } // for
            BM_ASSERT(en_i.valid());
        }
    } // for
    
    if (b_size)
    {
        bv_target.set(ibuffer, b_size, bm::BM_SORTED);
    }

}

// ------------------------------------------------------------------------

template<class BV>
void rank_compressor<BV>::decompress(BV& bv_target,
                                     const BV& bv_idx,
                                     const BV& bv_src)
{
    bv_target.clear();
    bv_target.init();

    if (&bv_idx == &bv_src)
    {
        bv_target = bv_src;
        return;
    }
    
    size_type r_idx, i, s, b_size;
    size_type ibuffer[n_buffer_cap];
    
    b_size = r_idx = 0;

    typedef typename BV::enumerator enumerator_t;
    enumerator_t en_s = bv_src.first();
    enumerator_t en_i = bv_idx.first();
    for (; en_i.valid(); )
    {
        if (!en_s.valid())
            break;
        s = *en_s;
        i = *en_i;
        if (s == r_idx)
        {
            ibuffer[b_size++] = i;
            if (b_size == n_buffer_cap)
            {
                bv_target.set(ibuffer, b_size, bm::BM_SORTED);
                b_size = 0;
            }
            ++en_i; ++en_s; ++r_idx;
            continue;
        }
        // source is "faster" than index, need to re-align
        BM_ASSERT(s > r_idx);
        size_type rank = s - r_idx + 1u;
        size_type new_pos = 0;
        
        if (rank < 256)
        {
            en_i.skip(s - r_idx);
            BM_ASSERT(en_i.valid());
            new_pos = *en_i;
        }
        else
        {
            bv_idx.find_rank(rank, i, new_pos);
            BM_ASSERT(new_pos);
            en_i.go_to(new_pos);
            BM_ASSERT(en_i.valid());
        }
        
        r_idx = s;
        ibuffer[b_size++] = new_pos;
        if (b_size == n_buffer_cap)
        {
            bv_target.set(ibuffer, b_size, bm::BM_SORTED);
            b_size = 0;
        }
        ++en_i; ++en_s; ++r_idx;
        
    } // for en
    
    if (b_size)
    {
        bv_target.set(ibuffer, b_size, bm::BM_SORTED);
    }
}

// ------------------------------------------------------------------------

template<class BV>
void rank_compressor<BV>::compress_by_source(BV& bv_target,
                                             const BV& bv_idx,
                                             const rs_index_type& bc_idx,
                                             const BV& bv_src)
{
    /// Rank compressor visitor (functor)
    /// @internal
    struct visitor_func
    {
        visitor_func(bvector_type&        bv_out,
                     const bvector_type&  bv_index,
                     const rs_index_type& bc_index)
        : bv_target_(bv_out),
          bv_index_(bv_index),
          bc_index_(bc_index)
        {}
        
        void add_bits(size_type arr_offset, const unsigned char* bits, unsigned bits_size)
        {
            for (unsigned i = 0; i < bits_size; ++i)
            {
                size_type idx = arr_offset + bits[i];
                BM_ASSERT(bv_index_.test(idx));

                size_type r_idx = bv_index_.count_to(idx, bc_index_) - 1;
                bv_target_.set_bit_no_check(r_idx);
            }
        }
        void add_range(size_type arr_offset, size_type sz)
        {
            for (size_type i = 0; i < sz; ++i)
            {
                size_type idx = i + arr_offset;
                BM_ASSERT(bv_index_.test(idx));

                size_type r_idx = bv_index_.count_to(idx, bc_index_) - 1;
                bv_target_.set_bit_no_check(r_idx);
            }
        }
        
        bvector_type&           bv_target_;
        const bvector_type&     bv_index_;
        const rs_index_type&    bc_index_;
    };
    // ------------------------------------

    bv_target.clear();
    bv_target.init();

    if (&bv_idx == &bv_src)
    {
        bv_target = bv_src;
        return;
    }
    visitor_func func(bv_target, bv_idx, bc_idx);
    bm::for_each_bit(bv_src, func);
}




} // bm


#endif