import std::io; # A struct has the bitwise operators and shifts by the methods that give them, # `bit_and`, `bit_or`, `bit_xor`, `bit_not`, `shift_left`, and `shift_right`, as it # has arithmetic, their compound assignments too, and a bound asking for them # gives a type parameter the operators. Integers give the methods as well. struct bits { var word: u64; } def bits::bit_and(&this, other: &bits): bits { return bits { word = this.word & other.word }; } def bits::bit_or(&this, other: &bits): bits { return bits { word = this.word | other.word }; } def bits::bit_xor(&this, other: &bits): bits { return bits { word = this.word ^ other.word }; } def bits::bit_not(&this): bits { return bits { word = ~this.word }; } def bits::shift_left(&this, by: &u32): bits { return bits { word = this.word << by }; } def bits::shift_right(&this, by: &u32): bits { return bits { word = this.word >> by }; } trait masks { def bit_and(&this, other: &self): self; def bit_not(&this): self; } def clear(a: T, b: T): T where T: masks { return a & ~b; } def main(): void { val a := bits { word = 0xF0F0 }; val b := bits { word = 0xFF00 }; io::println($"{(a & b).word} {(a | b).word} {(a ^ b).word} {(~a).word & 0xFFFF}"); io::println($"{(a << 4).word} {(a >> 4).word}"); var c := a; c &= b; c |= bits { word = 1 }; c <<= 1; c ^= bits { word = 3 }; c >>= 2; io::println($"{c.word}"); io::println($"{clear(a, b).word}"); val x: u32 = 12; io::println($"{x.bit_and(&10)} {x.bit_or(&3)} {x.bit_xor(&5)} {x.bit_not()} {x.shift_left(&2)} {x.shift_right(&2)}"); io::println($"{clear(x, 4 as u32)}"); }