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
//! Rust bindings for the BitMagic C++ Library
//! For more information please visit: http://bitmagic.io.

#![deny(missing_docs)]

use std::io::{Read, Write};
use std::os::raw::c_void;
use std::ptr;
use std::sync::Once;

mod fixedbitset_api;

/// Initialize libbm runtime before use
fn init_lib() {
    static START: Once = Once::new();

    START.call_once(|| {
        unsafe {
            let res = bitmagic_sys::BM_init(ptr::null_mut());
            _check_res(res);
        };
    });
}

/// A bitvector
pub struct BVector {
    handle: *mut c_void,
}

impl BVector {
    /// Serialize bit vector
    pub fn serialize<W>(&self, mut wtr: W) -> Result<(), Box<dyn std::error::Error>>
    where
        W: Write,
    {
        let mut bv_stat = bitmagic_sys::BM_bvector_statistics {
            bit_blocks: 0,
            gap_blocks: 0,
            max_serialize_mem: 0,
            memory_used: 0,
        };

        let mut res;
        unsafe {
            res = bitmagic_sys::BM_bvector_optimize(self.handle, 3, &mut bv_stat);
        }
        _check_res(res);

        let mut buf = vec![0u8; bv_stat.max_serialize_mem as usize];
        let mut blob_size = 0;
        unsafe {
            res = bitmagic_sys::BM_bvector_serialize(
                self.handle,
                buf.as_mut_ptr() as *mut i8,
                buf.len(),
                &mut blob_size,
            );
        }
        _check_res(res);

        if blob_size == 0 || blob_size > bv_stat.max_serialize_mem {
            unimplemented!("throw error")
        }

        wtr.write_all(buf.as_slice())?;

        Ok(())
    }

    /// Deserialize bit vector
    pub fn deserialize<R>(mut rdr: R) -> Result<Self, Box<dyn std::error::Error>>
    where
        R: Read,
    {
        let mut buf = vec![];
        rdr.read_to_end(&mut buf)?;

        let bnew = BVector::with_capacity(1);

        let res;
        unsafe {
            res = bitmagic_sys::BM_bvector_deserialize(
                bnew.handle,
                buf.as_mut_ptr() as *mut i8,
                buf.len(),
            );
        }
        _check_res(res);

        Ok(bnew)
    }

    /// Size of the intersection of two `BVector`s.
    ///
    /// Equivalent to the population count of AND of two bit vectors
    pub fn intersection_count(&self, other: &BVector) -> usize {
        let mut pcount = 0;

        let res;
        unsafe {
            res = bitmagic_sys::BM_bvector_count_AND(self.handle, other.handle, &mut pcount);
            // TODO: check res
        }
        _check_res(res);

        pcount as usize
    }

    /// Size of the union of two `BVector`s.
    ///
    /// Equivalent to the population count of OR of two bit vectors
    pub fn union_count(&self, other: &BVector) -> usize {
        let mut pcount = 0;

        let res;
        unsafe {
            res = bitmagic_sys::BM_bvector_count_OR(self.handle, other.handle, &mut pcount);
        }
        _check_res(res);

        pcount as usize
    }

    /// Size of the difference of two `BVector`s.
    ///
    /// Equivalent to the population count of SUB of two bit vectors
    pub fn difference_count(&self, other: &BVector) -> usize {
        let mut pcount = 0;

        let res;
        unsafe {
            res = bitmagic_sys::BM_bvector_count_SUB(self.handle, other.handle, &mut pcount);
        }
        _check_res(res);

        pcount as usize
    }

    /// Size of the symmetric difference of two `BVector`s.
    ///
    /// Equivalent to the population count of XOR of two bit vectors
    pub fn symmetric_difference_count(&self, other: &BVector) -> usize {
        let mut pcount = 0;

        let res;
        unsafe {
            res = bitmagic_sys::BM_bvector_count_XOR(self.handle, other.handle, &mut pcount);
            // TODO: check res
        }
        _check_res(res);

        pcount as usize
    }
}

pub(crate) fn _check_res(_res: i32) {
    // TODO: look into res values in the bitmagic API
    // TODO: check result, panic on error?
    // TODO: can be BM_OK or BM_ERR_CPU
}

#[cfg(test)]
mod tests {
    use crate::BVector;

    #[test]
    fn serde() {
        let mut bv = BVector::with_capacity(100);
        bv.set_range(10..20, true);
        bv.set_range(50..70, true);

        let mut wtr = vec![];
        bv.serialize(&mut wtr).unwrap();

        let new_bv = BVector::deserialize(wtr.as_slice()).unwrap();

        assert_eq!(new_bv, bv);

        for i in 10..20 {
            assert!(new_bv.contains(i));
        }

        for i in 50..70 {
            assert!(new_bv.contains(i));
        }
    }
}