aboutsummaryrefslogtreecommitdiff
path: root/src/bitboard.rs
diff options
context:
space:
mode:
authoreug-vs <eugene@eug-vs.xyz>2023-08-24 02:36:14 +0300
committereug-vs <eugene@eug-vs.xyz>2023-08-24 02:36:14 +0300
commit791ba3906d0ec41f328c20a9a1be8eabb12a84c6 (patch)
tree84c7281df28c92dacbdae7f4aee26f38397d43ab /src/bitboard.rs
parent85fbcdadec3853a92da6d434dbc94bb85bdfdcfe (diff)
downloadchessnost-791ba3906d0ec41f328c20a9a1be8eabb12a84c6.tar.gz
perf: use iterator in bitboard serialization
Diffstat (limited to 'src/bitboard.rs')
-rw-r--r--src/bitboard.rs24
1 files changed, 16 insertions, 8 deletions
diff --git a/src/bitboard.rs b/src/bitboard.rs
index 056822b..48a60d8 100644
--- a/src/bitboard.rs
+++ b/src/bitboard.rs
@@ -28,7 +28,7 @@ pub trait BitboardFns {
fn bitscan_and_reset(&mut self) -> Square;
/// Convert bitboard into the list of squares
- fn serialize(self) -> Vec<Square>;
+ fn serialize(self) -> SquareIterator;
/// Return bitboard shifted nort, no wrap occurs
fn nort_one(self) -> Self;
@@ -109,12 +109,8 @@ impl BitboardFns for Bitboard {
square
}
- fn serialize(mut self) -> Vec<Square> {
- let mut serialized = Vec::with_capacity(64);
- while self > 0 {
- serialized.push(self.bitscan_and_reset());
- }
- serialized
+ fn serialize(self) -> SquareIterator {
+ SquareIterator(self)
}
fn nort_one(self) -> Self {
@@ -150,6 +146,18 @@ impl BitboardFns for Bitboard {
}
}
+pub struct SquareIterator (Bitboard);
+impl Iterator for SquareIterator {
+ type Item = Square;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.0 > 0 {
+ return Some(self.0.bitscan_and_reset());
+ }
+ None
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -184,7 +192,7 @@ mod tests {
#[test]
fn test_serialize_bitboard() {
let bb = 1 << 4 | 1 << 15 | 1 << 60;
- let serialized = bb.serialize();
+ let serialized = bb.serialize().collect::<Vec<_>>();
assert_eq!(serialized[0], Square::from(4));
assert_eq!(serialized[1], Square::from(15));
assert_eq!(serialized[2], Square::from(60));