3 ms·
> If this produces simiarly nice code (I haven't checked yet) I'll be very happy You didn't specify what the type of `buffer` was, so I picked a `u8`. This cod
by shepmaster 9y ago
> If this produces simiarly nice code (I haven't checked yet) I'll be very happy
You didn't specify what the type of `buffer` was, so I picked a `u8`. This code[1]:
pub struct Thing {
buffer: Vec<u8>,
}
impl Thing {
pub fn copy(&mut self, data: &[u8]) {
for (dest, &source) in self.buffer.iter_mut().zip(data) {
*dest = source;
}
}
}
Produces this assembly:
_ZN10playground5Thing4copy17hf523bcb10e2298f3E:
.cfi_startproc
pushq %rax
.Ltmp0:
.cfi_def_cfa_offset 16
movq 16(%rdi), %rax
cmpq %rdx, %rax
cmovbeq %rax, %rdx
testq %rdx, %rdx
je .LBB0_2
movq (%rdi), %rdi
callq memcpy@PLT
.LBB0_2:
popq %rax
retq
The call to `memcpy` is what makes me happy.
----
Your `count_bits` already exists as a combination of iterator adapters (`filter`[2] and `count`[3]):
a_bit_iterator.filter(|bit| bit).count()
Although if you have a numeric value, I'd suggest using `count_ones`[4], which can use the `popcnt` intrinsic.
If you wanted to count all the bits in an array, I'd suggest `map`[5] and `sum`[6]
let p = [1u8, 2, 54, 2, 3, 6];
let result: u32 = p.iter().map(|b| b.count_ones()).sum();
If you wanted to keep the bit iterator, you could also use `flat_map`[7].
[1]: https://play.integer32.com/?gist=03f8ffbe3ade6ced4d315c8e02063f29&version=stable https://play.integer32.com/?gist=03f8ffbe3ade6ced4d315c8e020...
[2]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter https://doc.rust-lang.org/std/iter/trait.Iterator.html#metho...
[3]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.count https://doc.rust-lang.org/std/iter/trait.Iterator.html#metho...
[4]: https://doc.rust-lang.org/std/primitive.u8.html#method.count_ones https://doc.rust-lang.org/std/primitive.u8.html#method.count...
[5]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map https://doc.rust-lang.org/std/iter/trait.Iterator.html#metho...
[6]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.sum https://doc.rust-lang.org/std/iter/trait.Iterator.html#metho...
[7]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map https://doc.rust-lang.org/std/iter/trait.Iterator.html#metho...
- Lerc 9y ago>The call to `memcpy` is what makes me happy. That's the sort of thing I was hoping to see. >Your `count_bits` already exists as a combination of iterator adapters (`filter`[2] and `count`[3]): That's the problem with simple examples. I don't actually want to count bits. It was just the minimum workload I could think of to generate a result from the conversion. Seeing how the for (a,b) in ai.zip(bi) works well I'll probably be writing a bitmap glyph renderer that is basically if b {*a=color}