jhorstmann commented on code in PR #12024:
URL: https://github.com/apache/arrow-rs/pull/12024#discussion_r4437607586


##########
arrow-buffer/src/builder/boolean.rs:
##########
@@ -276,9 +276,31 @@ impl BooleanBufferBuilder {
         self.advance(additional);
 
         let offset = self.len() - additional;
-        for (i, v) in slice.iter().enumerate() {
+        let buffer = self.buffer.as_slice_mut();
+
+        // Set bits individually until the write position is byte aligned
+        let head = ((8 - offset % 8) % 8).min(additional);
+        let (head_slice, rest) = slice.split_at(head);
+        for (i, v) in head_slice.iter().enumerate() {
             if *v {
-                unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), 
offset + i) }
+                bit_util::set_bit(buffer, offset + i)
+            }
+        }
+
+        // Pack 8 bools into each byte without branching: a `bool` is a byte
+        // holding 0 or 1, and the multiply moves byte `i` to bit `56 + i`
+        let byte_offset = (offset + head) / 8;
+        let (chunks, remainder) = rest.as_chunks::<8>();
+        for (dst, chunk) in buffer[byte_offset..].iter_mut().zip(chunks) {
+            let bytes: [u8; 8] = std::array::from_fn(|i| chunk[i] as u8);
+            let packed = 
u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56;

Review Comment:
   Very nice trick. On x86_64 with bmi2 feature this could also be written as
   
   ```
   std::arch::x86_64::_pext_u64(u64::from_le_bytes(bytes), 0x01010101_01010101)
   ```
   
   But I think that only saves a single cycle for the shift. Very cool that 
there is a portable alternative.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to