| 1 | #![no_std] |
| 2 | #![cfg_attr( |
| 3 | feature = "unstable-512-bit-simd", |
| 4 | feature(link_llvm_intrinsics, repr_simd, simd_ffi, platform_intrinsics) |
| 5 | )] |
| 6 | |
| 7 | #[cfg(feature = "serde")] |
| 8 | mod serde_impl; |
| 9 | |
| 10 | use core::{ |
| 11 | fmt, |
| 12 | hash::{Hash, Hasher}, |
| 13 | ops::{BitAnd, BitOr, BitXor, Deref, DerefMut}, |
| 14 | slice, |
| 15 | }; |
| 16 | |
| 17 | #[cfg(feature = "space")] |
| 18 | use space::Metric; |
| 19 | |
| 20 | cfg_if::cfg_if! { |
| 21 | if #[cfg(feature = "unstable-512-bit-simd")] { |
| 22 | #[repr(simd)] |
| 23 | #[derive(Copy, Clone)] |
| 24 | struct Tup(u128, u128, u128, u128); |
| 25 | |
| 26 | #[allow(improper_ctypes, dead_code)] |
| 27 | extern "C" { |
| 28 | #[link_name = "llvm.ctpop.v4i128"] |
| 29 | fn ctpop_512(x: Tup) -> Tup; |
| 30 | #[link_name = "llvm.experimental.vector.reduce.add.v4i128"] |
| 31 | fn reduce_add_512(x: Tup) -> u128; |
| 32 | } |
| 33 | |
| 34 | extern "platform-intrinsic" { |
| 35 | fn simd_xor<T>(x: T, y: T) -> T; |
| 36 | } |
| 37 | |
| 38 | /// Split the bytes up into number of operations of size (512, 64, 8) |
| 39 | const fn split_up_simd(n: usize) -> (usize, usize, usize) { |
| 40 | let n_512 = n >> 6; |
| 41 | let bytes_512 = n_512 << 6; |
| 42 | let n_64 = (n - bytes_512) >> 3; |
| 43 | let bytes_64 = n_64 << 3; |
| 44 | let n_8 = n - bytes_512 - bytes_64; |
| 45 | (n_512, n_64, n_8) |
| 46 | } |
| 47 | } else { |
| 48 | /// Split the bytes up into number of operations of size (512, 64, 8) |
| 49 | const fn split_up_simd(n: usize) -> (usize, usize) { |
| 50 | let n_64 = n >> 3; |
| 51 | let bytes_64 = n_64 << 3; |
| 52 | let n_8 = n - bytes_64; |
| 53 | (n_64, n_8) |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// A constant sized array of bits. `B` defines the number of bytes. |
| 59 | /// This has an alignment of 64 to maximize the efficiency of SIMD operations. |
| 60 | /// It will automatically utilize SIMD at runtime where possible. |
| 61 | #[repr(align(64))] |
| 62 | #[derive(Copy, Clone)] |
| 63 | pub struct BitArray<const B: usize> { |
| 64 | pub bytes: [u8; B], |
| 65 | } |
| 66 | |
| 67 | impl<const B: usize> BitArray<B> { |
| 68 | /// Create a new `BitArray`. |
| 69 | /// |
| 70 | /// ``` |
| 71 | /// use bitarray::BitArray; |
| 72 | /// let array = BitArray::new([0]); |
| 73 | /// assert_eq!(*array.bytes(), [0]); |
| 74 | /// ``` |
| 75 | pub fn new(bytes: [u8; B]) -> Self { |
| 76 | Self { bytes } |
| 77 | } |
| 78 | |
| 79 | /// Create a new `BitArray` with all zeros. |
| 80 | /// |
| 81 | /// ``` |
| 82 | /// use bitarray::BitArray; |
| 83 | /// let array = BitArray::zeros(); |
| 84 | /// assert_eq!(array, BitArray::new([0])); |
| 85 | /// assert_eq!(*array, [0]); |
| 86 | /// ``` |
| 87 | pub fn zeros() -> Self { |
| 88 | Self { bytes: [0; B] } |
| 89 | } |
| 90 | |
| 91 | /// Retrieve the byte array of a `BitArray`. |
| 92 | /// |
| 93 | /// ``` |
| 94 | /// use bitarray::BitArray; |
| 95 | /// let array = BitArray::new([1, 2]); |
| 96 | /// assert_eq!(*array, [1, 2]); |
| 97 | /// ``` |
| 98 | pub fn bytes(&self) -> &[u8; B] { |
| 99 | &self.bytes |
| 100 | } |
| 101 | |
| 102 | /// Retrieve the mutable byte array of a `BitArray`. |
| 103 | /// |
| 104 | /// ``` |
| 105 | /// use bitarray::BitArray; |
| 106 | /// let mut array = BitArray::new([1, 2]); |
| 107 | /// array.bytes_mut()[0] = 3; |
| 108 | /// assert_eq!(*array, [3, 2]); |
| 109 | /// ``` |
| 110 | pub fn bytes_mut(&mut self) -> &mut [u8; B] { |
| 111 | &mut self.bytes |
| 112 | } |
| 113 | |
| 114 | /// Compute the hamming weight (number of ones) of the `BitArray`. |
| 115 | /// |
| 116 | /// This is also called `count_ones` in the standard library. |
| 117 | /// |
| 118 | /// ``` |
| 119 | /// use bitarray::BitArray; |
| 120 | /// let array = BitArray::new([0xAA; 83]); |
| 121 | /// assert_eq!(array.weight(), 4 * 83); |
| 122 | /// ``` |
| 123 | #[allow(clippy::cast_ptr_alignment)] |
| 124 | pub fn weight(&self) -> u32 { |
| 125 | cfg_if::cfg_if! { |
| 126 | if #[cfg(feature = "unstable-512-bit-simd")] { |
| 127 | let (n_512, n_64, n_8) = split_up_simd(self.bytes.len()); |
| 128 | let sum_512 = unsafe { |
| 129 | slice::from_raw_parts(self.bytes.as_ptr() as *const Tup, n_512) |
| 130 | .iter() |
| 131 | .copied() |
| 132 | .map(|chunk| reduce_add_512(ctpop_512(chunk)) as u32) |
| 133 | .sum::<u32>() |
| 134 | }; |
| 135 | let sum_64 = unsafe { |
| 136 | slice::from_raw_parts(self.bytes.as_ptr() as *const u64, n_64) |
| 137 | .iter() |
| 138 | .copied() |
| 139 | .map(|chunk| chunk.count_ones()) |
| 140 | .sum::<u32>() |
| 141 | }; |
| 142 | |
| 143 | let sum_8 = self.bytes[self.bytes.len() - n_8..] |
| 144 | .iter() |
| 145 | .copied() |
| 146 | .map(|b| b.count_ones()) |
| 147 | .sum::<u32>(); |
| 148 | |
| 149 | sum_512 + sum_64 + sum_8 |
| 150 | } else { |
| 151 | let (n_64, n_8) = split_up_simd(self.bytes.len()); |
| 152 | let sum_64 = unsafe { |
| 153 | slice::from_raw_parts(self.bytes.as_ptr() as *const u64, n_64) |
| 154 | .iter() |
| 155 | .copied() |
| 156 | .map(|chunk| chunk.count_ones()) |
| 157 | .sum::<u32>() |
| 158 | }; |
| 159 | |
| 160 | let sum_8 = self.bytes[self.bytes.len() - n_8..] |
| 161 | .iter() |
| 162 | .copied() |
| 163 | .map(|b| b.count_ones()) |
| 164 | .sum::<u32>(); |
| 165 | |
| 166 | sum_64 + sum_8 |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// Compute the hamming distance to another `BitArray`. |
| 172 | /// |
| 173 | /// ``` |
| 174 | /// use bitarray::BitArray; |
| 175 | /// |
| 176 | /// // All the bits are different. |
| 177 | /// let a = BitArray::new([0xAA; 65]); |
| 178 | /// let b = BitArray::new([0x55; 65]); |
| 179 | /// assert_eq!(a.distance(&b), 8 * 65); |
| 180 | /// |
| 181 | /// // None of the bits are different. |
| 182 | /// let a = BitArray::new([0xAA; 65]); |
| 183 | /// let b = BitArray::new([0xAA; 65]); |
| 184 | /// assert_eq!(a.distance(&b), 0); |
| 185 | /// ``` |
| 186 | #[allow(clippy::cast_ptr_alignment)] |
| 187 | pub fn distance(&self, other: &Self) -> u32 { |
| 188 | cfg_if::cfg_if! { |
| 189 | if #[cfg(feature = "unstable-512-bit-simd")] { |
| 190 | let simd_len = B >> 6; |
| 191 | let simd_bytes = simd_len << 6; |
| 192 | let simd_sum = unsafe { |
| 193 | slice::from_raw_parts(self.bytes.as_ptr() as *const Tup, simd_len) |
| 194 | .iter() |
| 195 | .copied() |
| 196 | .zip( |
| 197 | slice::from_raw_parts(other.bytes.as_ptr() as *const Tup, simd_len) |
| 198 | .iter() |
| 199 | .copied(), |
| 200 | ) |
| 201 | .map(|(a, b)| reduce_add_512(ctpop_512(simd_xor(a, b))) as u32) |
| 202 | .sum::<u32>() |
| 203 | }; |
| 204 | let remaining_sum = self.bytes[simd_bytes..] |
| 205 | .iter() |
| 206 | .copied() |
| 207 | .zip(other.bytes[simd_bytes..].iter().copied()) |
| 208 | .map(|(a, b)| (a ^ b).count_ones()) |
| 209 | .sum::<u32>(); |
| 210 | simd_sum + remaining_sum |
| 211 | } else { |
| 212 | self.bytes |
| 213 | .iter() |
| 214 | .copied() |
| 215 | .zip(other.bytes.iter().copied()) |
| 216 | .map(|(a, b)| (a ^ b).count_ones()) |
| 217 | .sum::<u32>() |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | impl<const B: usize> BitAnd for BitArray<B> { |
| 224 | type Output = Self; |
| 225 | |
| 226 | fn bitand(mut self, rhs: Self) -> Self::Output { |
| 227 | for (d, s) in self.iter_mut().zip(rhs.iter().copied()) { |
| 228 | *d &= s; |
| 229 | } |
| 230 | self |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | impl<const B: usize> BitOr for BitArray<B> { |
| 235 | type Output = Self; |
| 236 | |
| 237 | fn bitor(mut self, rhs: Self) -> Self::Output { |
| 238 | for (d, s) in self.iter_mut().zip(rhs.iter().copied()) { |
| 239 | *d |= s; |
| 240 | } |
| 241 | self |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | impl<const B: usize> BitXor for BitArray<B> { |
| 246 | type Output = Self; |
| 247 | |
| 248 | fn bitxor(mut self, rhs: Self) -> Self::Output { |
| 249 | for (d, s) in self.iter_mut().zip(rhs.iter().copied()) { |
| 250 | *d ^= s; |
| 251 | } |
| 252 | self |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | impl<const B: usize> PartialEq for BitArray<B> { |
| 257 | fn eq(&self, other: &Self) -> bool { |
| 258 | self.bytes |
| 259 | .iter() |
| 260 | .zip(other.bytes.iter()) |
| 261 | .all(|(&a, &b)| a == b) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | impl<const B: usize> Eq for BitArray<B> {} |
| 266 | |
| 267 | impl<const B: usize> fmt::Debug for BitArray<B> { |
| 268 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 269 | self.bytes[..].fmt(f) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | impl<const B: usize> Hash for BitArray<B> { |
| 274 | fn hash<H: Hasher>(&self, state: &mut H) { |
| 275 | self.bytes[..].hash(state) |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /// ``` |
| 280 | /// use bitarray::BitArray; |
| 281 | /// let mut array = BitArray::new([1, 2]); |
| 282 | /// assert_eq!(*array, [1, 2]); |
| 283 | /// ``` |
| 284 | impl<const B: usize> Deref for BitArray<B> { |
| 285 | type Target = [u8; B]; |
| 286 | |
| 287 | fn deref(&self) -> &Self::Target { |
| 288 | &self.bytes |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | /// ``` |
| 293 | /// use bitarray::BitArray; |
| 294 | /// let mut array = BitArray::zeros(); |
| 295 | /// array[0] = 1; |
| 296 | /// array[1] = 2; |
| 297 | /// assert_eq!(*array, [1, 2]); |
| 298 | /// ``` |
| 299 | impl<const B: usize> DerefMut for BitArray<B> { |
| 300 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 301 | &mut self.bytes |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /// Provides [hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) as a metric. |
| 306 | #[cfg(feature = "space")] |
| 307 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] |
| 308 | #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 309 | pub struct Hamming; |
| 310 | |
| 311 | #[cfg(feature = "space")] |
| 312 | impl<const B: usize> Metric<BitArray<B>> for Hamming { |
| 313 | type Unit = u32; |
| 314 | |
| 315 | fn distance(&self, a: &BitArray<B>, b: &BitArray<B>) -> u32 { |
| 316 | a.distance(b) as u32 |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | /// Provides [Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) as a metric. |
| 321 | /// |
| 322 | /// The Jaccard similarity is computed and then subtracted from `1.0` |
| 323 | /// so that items are ordered by Jaccard distance/dissimilarity. |
| 324 | #[cfg(feature = "space")] |
| 325 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] |
| 326 | #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 327 | pub struct Jaccard; |
| 328 | |
| 329 | #[cfg(feature = "space")] |
| 330 | impl<const B: usize> Metric<BitArray<B>> for Jaccard { |
| 331 | type Unit = u32; |
| 332 | |
| 333 | fn distance(&self, &a: &BitArray<B>, &b: &BitArray<B>) -> u32 { |
| 334 | let intersection = (a & b).weight(); |
| 335 | let union = (a | b).weight(); |
| 336 | if union == 0 { |
| 337 | 0 |
| 338 | } else { |
| 339 | (1.0 - intersection as f32 / union as f32).to_bits() |
| 340 | } |
| 341 | } |
| 342 | } |