Sub topic 13
Bitwise and shift operator traits
This chapter assumes you know how to implement Add for a struct, how Output works, and how Copy affects operands. The bitwise and shift operators follow the same pattern. Only the trait names change.
The trait table
Each bitwise or shift operator maps to a trait in std::ops, just like + maps to Add.
| Operator | Trait | Method | Compound form | Compound trait | Column | Column |
|---|---|---|---|---|---|---|
| `&` | `BitAnd` | `bitand` | `&=` | `BitAndAssign` | ||
| `\ | ` | `BitOr` | `bitor` | `\ | =` | `BitOrAssign` |
| `^` | `BitXor` | `bitxor` | `^=` | `BitXorAssign` | ||
| `<<` | `Shl` | `shl` | `<<=` | `ShlAssign` | ||
| `>>` | `Shr` | `shr` | `>>=` | `ShrAssign` | ||
| `!` | `Not` | `not` | none | none |
Not is unary, as covered in the chapter on Neg and Not. On integers it flips every bit. On bool it is logical negation. The other traits are binary and take an Rhs type parameter that defaults to Self, exactly like Add.
A flag set with BitOr and BitAnd
A common use is a set of flags stored in one integer. Here | combines flags, & finds the flags two sets share, and ! gives the complement.
use std::ops::{BitAnd, BitOr, BitOrAssign, Not};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Perms(u8);
impl Perms {
const READ: Perms = Perms(0b001);
const WRITE: Perms = Perms(0b010);
const EXEC: Perms = Perms(0b100);
const ALL: Perms = Perms(0b111);
fn contains(self, other: Perms) -> bool {
self & other == other
}
}
impl BitOr for Perms {
type Output = Perms;
fn bitor(self, rhs: Perms) -> Perms {
Perms(self.0 | rhs.0)
}
}
impl BitAnd for Perms {
type Output = Perms;
fn bitand(self, rhs: Perms) -> Perms {
Perms(self.0 & rhs.0)
}
}
impl BitOrAssign for Perms {
fn bitor_assign(&mut self, rhs: Perms) {
self.0 |= rhs.0;
}
}
impl Not for Perms {
type Output = Perms;
fn not(self) -> Perms {
Perms(!self.0 & Perms::ALL.0)
}
}
fn main() {
let mut p = Perms::READ | Perms::WRITE;
assert!(p.contains(Perms::READ));
assert!(!p.contains(Perms::EXEC));
p |= Perms::EXEC;
assert_eq!(p, Perms::ALL);
assert_eq!(!Perms::READ, Perms(0b110));
}Note the mask in not. Without & Perms::ALL.0, the complement of 0b001 would be 0b1111_1110, which sets bits that are not valid flags. When a type has fewer meaningful bits than its storage, Not must keep the value valid.
Shifts use a different Rhs
For shifts, the right operand is usually not the same type as the left. You shift a value by a count. So Shl and Shr are often implemented with Rhs set to an integer type.
use std::ops::{Shl, Shr};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Bits(u32);
impl Shl<u32> for Bits {
type Output = Bits;
fn shl(self, n: u32) -> Bits {
Bits(self.0 << n)
}
}
impl Shr<u32> for Bits {
type Output = Bits;
fn shr(self, n: u32) -> Bits {
Bits(self.0 >> n)
}
}
fn main() {
let b = Bits(0b0001);
assert_eq!(b << 3, Bits(0b1000));
assert_eq!(Bits(0b1000) >> 2, Bits(0b0010));
}The literal 3 is inferred as u32 because that is the only Shl impl for Bits. If you add several impls, such as Shl<u8> and Shl<u32>, a bare literal can become ambiguous and you may need a suffix like 3u32.
Gotchas
- Shifting by the bit width or more is an overflow. A debug build panics for
1u32 << 32. Release builds mask the count. Inside your ownshl, usechecked_shlorwrapping_shlif you want defined behavior. &and|here are not the short-circuiting&&and||. Those cannot be overloaded, and they only work onbool.- Operator precedence applies as usual.
a & b == cparses asa & (b == c), which is whycontainsabove writesself & other == otheronly because&binds tighter than==in Rust. Unlike C, Rust ranks bitwise operators above comparisons. Add parentheses anyway when it helps readers.
Exercise
Given struct Mask(u8) with BitXor implemented for it, which compound-assignment trait must you also implement to make m ^= other compile, and what is its method's signature?
Show answer
Implement BitXorAssign. Its method is fn bitxor_assign(&mut self, rhs: Mask). It mutates self in place and returns nothing. Implementing BitXor alone is not enough.