Sub topic 13
Bitwise and shift operator traits
This chapter covers the std::ops traits behind &, |, ^, !, << and >>. It assumes you can already implement Add for a struct, know what the Output associated type is, and are comfortable with Copy, generics and trait bounds. The bitwise traits work like Add and AddAssign. This chapter covers what is different: the traits are mostly used on flag-like types, shifts take an independent right-hand type, and several details differ from C-style expectations.
The trait family
Each bitwise or shift operator is a trait in std::ops with a single method. Each binary operator also has a compound assignment trait.
| Operator | Trait | Method | Assignment trait | Assignment method | Column |
|---|---|---|---|---|---|
| `a & b` | `BitAnd` | `bitand` | `BitAndAssign` | `bitand_assign` | |
| `a \ | b` | `BitOr` | `bitor` | `BitOrAssign` | `bitor_assign` |
| `a ^ b` | `BitXor` | `bitxor` | `BitXorAssign` | `bitxor_assign` | |
| `a << b` | `Shl` | `shl` | `ShlAssign` | `shl_assign` | |
| `a >> b` | `Shr` | `shr` | `ShrAssign` | `shr_assign` | |
| `!a` | `Not` | `not` | none | none |
The binary traits have the same shape as Add. Each takes a Rhs type parameter that defaults to Self, and each has an Output associated type. Not is unary, like Neg, so it has no Rhs and no assignment form.
Two operators are missing from the table. && and || cannot be overloaded, because they short-circuit. The right operand must not be evaluated when the left one decides the result, and a trait method call always evaluates its arguments first. These two operators only work on bool.
A flag type
Bitwise operators are most useful on small types that wrap an integer used as a set of flags. The next example defines a permission set with | to combine, & to intersect, and ! to complement.
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Perm(u8);
impl Perm {
const NONE: Perm = Perm(0);
const READ: Perm = Perm(0b001);
const WRITE: Perm = Perm(0b010);
const EXEC: Perm = Perm(0b100);
const ALL: Perm = Perm(0b111);
fn contains(self, other: Perm) -> bool {
self & other == other
}
}
impl BitOr for Perm {
type Output = Perm;
fn bitor(self, rhs: Perm) -> Perm {
Perm(self.0 | rhs.0)
}
}
impl BitAnd for Perm {
type Output = Perm;
fn bitand(self, rhs: Perm) -> Perm {
Perm(self.0 & rhs.0)
}
}
impl Not for Perm {
type Output = Perm;
fn not(self) -> Perm {
// Mask the result so that only defined flags can be set.
Perm(!self.0 & Perm::ALL.0)
}
}
impl BitOrAssign for Perm {
fn bitor_assign(&mut self, rhs: Perm) {
self.0 |= rhs.0;
}
}
impl BitAndAssign for Perm {
fn bitand_assign(&mut self, rhs: Perm) {
self.0 &= rhs.0;
}
}
fn main() {
let mut p = Perm::READ | Perm::WRITE;
assert!(p.contains(Perm::READ));
assert!(!p.contains(Perm::EXEC));
p |= Perm::EXEC;
assert_eq!(p, Perm::ALL);
p &= !Perm::WRITE;
assert_eq!(p, Perm(0b101));
assert_eq!(!Perm::NONE, Perm::ALL);
}Some details in this example are worth noting.
Notmasks its result withPerm::ALL. Without the mask,!Perm::NONEwould bePerm(0b1111_1111). That value has five bits that mean nothing, and it would not equalPerm::ALL. Complementing a flag type needs the mask, because the integer underneath has more bits than the type defines.containswritesself & other == otherwithout parentheses. In Rust,&,^and|bind tighter than==, which is the opposite of C. The expression parses as(self & other) == other.- Both
|and|=are implemented. ImplementingBitOrdoes not give you|=. ACopytype can still usep = p | q, butp |= qfails to compile untilBitOrAssignexists. Permhas noOutputother than itself. Set operations on a flag type close over the type, soOutput = Permis the natural choice for every one of these traits.
Shift operators
Shl and Shr differ from the other binary traits in one way. The right-hand operand is usually not Self. It is the shift amount. The Rhs parameter still defaults to Self, but for shifts you almost always set it explicitly, typically to u32. The standard library implements Shl and Shr for every integer type with every integer type as the right-hand side. For example, u8 << i64 and u64 << u8 both compile. The Output is the type of the left operand.
This has two practical effects.
- When a type has several
Shl<...>impls, an unsuffixed literal likex << 3has no single candidate impl to pick. Inference then falls back toi32for the literal. If you implement only one, such asShl<u32>, the literal is inferred asu32. - Shifting by an amount greater than or equal to the bit width of the type is an error for integers. It panics in a debug build. In a release build with overflow checks off, the amount is masked, so
1u8 << 9behaves like1u8 << 1. Integers also providechecked_shl,wrapping_shlandoverflowing_shlfor cases where you need to control this.
A custom type must choose its own behavior for large shift amounts. The next example defines a 32-bit set where shifting by 32 or more clears every bit, which is the usual meaning of "shift everything out".
use std::ops::{Shl, ShlAssign, Shr};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Bits(u32);
impl Shl<u32> for Bits {
type Output = Bits;
fn shl(self, n: u32) -> Bits {
// checked_shl returns None when n >= 32.
Bits(self.0.checked_shl(n).unwrap_or(0))
}
}
impl Shr<u32> for Bits {
type Output = Bits;
fn shr(self, n: u32) -> Bits {
Bits(self.0.checked_shr(n).unwrap_or(0))
}
}
impl ShlAssign<u32> for Bits {
fn shl_assign(&mut self, n: u32) {
*self = *self << n;
}
}
fn main() {
assert_eq!(Bits(1) << 4, Bits(16));
assert_eq!(Bits(0b1000) >> 3, Bits(1));
assert_eq!(Bits(1) << 32, Bits(0));
let mut b = Bits(3);
b <<= 2;
assert_eq!(b, Bits(12));
}shl_assign reuses shl through *self << n. This is the usual way to write an assignment trait for a Copy type, and it keeps the two behaviors from drifting apart.
Shift precedence is another place where C habits mislead. In Rust, << and >> bind looser than + and -, so 1 << 2 + 1 is 1 << 3, which is 8. Bitwise & binds looser than shifts, so x >> 4 & 0xF means (x >> 4) & 0xF. When a line mixes these operators, add parentheses even where they are not needed, so a reader does not have to recall the table.
Generic code over bitwise traits
Because the operators are traits, generic functions can require them as bounds. This works the same way as with Add and Mul. The bound names the operator and fixes Output to T so the result can be used as a T again.
use std::ops::{BitAnd, BitOr, Shl};
fn has_all<T>(value: T, mask: T) -> bool
where
T: Copy + PartialEq + BitAnd<Output = T>,
{
value & mask == mask
}
fn set_bit<T>(value: T, bit: u32) -> T
where
T: BitOr<Output = T> + Shl<u32, Output = T> + From<u8>,
{
value | (T::from(1u8) << bit)
}
fn main() {
assert!(has_all(0b0110u8, 0b0100));
assert!(!has_all(0b0110u8, 0b1000));
assert_eq!(set_bit(0u8, 3), 8);
assert_eq!(set_bit(1u64, 40), (1u64 << 40) | 1);
}set_bit shows the shift bound Shl<u32, Output = T>. It states both the right-hand type and the output type. A bound like T: Shl<Output = T> alone would mean Shl<T>, which asks for a shift amount of the same type as the value and is rarely what you want. From<u8> supplies the constant 1, since a generic function cannot write an integer literal of type T.
Gotchas and decisions
- No derive. Rust has no derive for these traits. Each impl is written by hand, or generated with a
macro_rules!macro, which a later chapter covers. - Overloading
!has no logical meaning. Onbool,!is logical negation. On integers it is bitwise complement. Your type decides which meaning applies, so document it. For flag types, define it as complement within the valid bits, as above. - References. The standard library implements these operators for references to integers, such as
&u8 & u8. For your own non-Copytypes, add reference impls the same way as forAddif callers should not have to clone. - Use the operators for set-like or bit-pattern semantics only.
|for "union of permissions" reads clearly.|for "chain two parsers" or<<for "append to a stream" is cleverness that readers have to learn. When the meaning is not a bit operation or a set operation, a named method is usually better. - Consider a crate for large flag sets. Hand-writing six traits for each flag type is repetitive. The
bitflagscrate generates them, along withDebugoutput that prints flag names.
Exercise
A colleague writes impl BitOr for Perm and then uses p |= Perm::EXEC on a Perm variable. The code does not compile. What is missing, and why does p = p | Perm::EXEC work anyway?
Show answer
The BitOrAssign trait is missing. |= calls BitOrAssign::bitor_assign(&mut p, rhs), which is a separate trait from BitOr. p = p | Perm::EXEC uses only BitOr and works because Perm is Copy, so p is still usable after being passed by value.
Exercise
Write a Shr<u32> impl for Bits(u32) that returns Bits(0) for shift amounts of 32 or more, then explain why Bits(1) >> 40 with this impl does not panic, while 1u32 >> 40u32 does in a debug build.
Show answer
The impl is impl Shr<u32> for Bits { type Output = Bits; fn shr(self, n: u32) -> Bits { Bits(self.0.checked_shr(n).unwrap_or(0)) } }. checked_shr returns None when n is at least 32, and unwrap_or(0) turns that into zero. The built-in u32 shift has no such handling. In debug builds it panics on overflow, and with overflow checks disabled the amount is masked instead.