Closed
Description
This is a documentation issue.
In the documentation for BitOps -> BitOr
, BitAnd
and BitXor
, Following documentation should be changed to use Bitwise operators for Boolean operations and not the logical operations.
// For BitOr
use std::ops::BitOr;
#[derive(Debug, PartialEq)]
struct BooleanVector(Vec<bool>);
impl BitOr for BooleanVector {
type Output = Self;
fn bitor(self, Self(rhs): Self) -> Self::Output {
let Self(lhs) = self;
assert_eq!(lhs.len(), rhs.len());
Self(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x || *y).collect()) // <- Here we should use bit-wise or and not logical or
}
}
let bv1 = BooleanVector(vec![true, true, false, false]);
let bv2 = BooleanVector(vec![true, false, true, false]);
let expected = BooleanVector(vec![true, true, true, false]);
assert_eq!(bv1 | bv2, expected);
Also, similar changes are required for Bitwise And and Bitwise Xor. Note: While the output is not wrong per se, it's actually a bit confusing since, those operators already exist for scalar versions of bool
.
The changes for BitXor
are more confusing
// <snip>
impl BitXor for BooleanVector {
type Output = Self;
fn bitxor(self, Self(rhs): Self) -> Self::Output {
let Self(lhs) = self;
assert_eq!(lhs.len(), rhs.len());
Self(lhs.iter()
.zip(rhs.iter())
.map(|(x, y)| (*x || *y) && !(*x && *y))
.collect())
}
}
let bv1 = BooleanVector(vec![true, true, false, false]);
let bv2 = BooleanVector(vec![true, false, true, false]);
let expected = BooleanVector(vec![false, true, true, false]);
assert_eq!(bv1 ^ bv2, expected);
Where a simple bitwise xor above like .map(|(x, y)| (*x ^ *y))
should suffice.
I have quickly verified these changes indeed work on playground using nightly
and stable
.
Meta
Since this is really a documentation issue, added for completeness.
rustc --version --verbose
:
$ rustc --version --verbose
rustc 1.47.0 (18bf6b4f0 2020-10-07)
binary: rustc
commit-hash: 18bf6b4f01a6feaf7259ba7cdae58031af1b7b39
commit-date: 2020-10-07
host: x86_64-unknown-linux-gnu
release: 1.47.0
LLVM version: 11.0