pub trait RefBitXor<Rhs>: BitXor<Rhs> {
fn ref_bitxor(&self, other: Rhs) -> Self::Output;
}Expand description
An escape hatch for implimenting
BitXor
for references to newtypes.
As of Rust 1.52.1, the following code does not compile:
ⓘ
use core::ops::BitXor;
#[derive(PartialEq)]
struct A<T>(T);
impl<'a, 'b, T, U> BitXor<&'b A<U>> for &'a A<T>
where
T: BitXor<&'b U>,
&'a T: BitXor<&'b U, Output = T::Output>,
{
type Output = A<T::Output>;
fn bitxor(self, other: &'b A<U>) -> Self::Output {
A(self.0.bitxor(&other.0))
}
}
pub fn f<T, U>(a: T, b: U)
where
for<'a, 'b> &'a T: BitXor<&'b U>,
{
let a_b = (&a).bitxor(&b);
// to do something with `a`, `b`, and `a_b`
todo!();
}
pub fn g<T, U>(a: T, b: U)
where
for<'a, 'b> &'a T: BitXor<&'b U>,
{
f(a, b);
}
assert!(&A(3) ^ &A(5) == A(6));but the following code does:
use core::ops::BitXor;
use ref_ops::RefBitXor;
#[derive(PartialEq)]
struct A<T>(T);
impl<'a, T, U> BitXor<&'a A<U>> for &A<T>
where
T: RefBitXor<&'a U>,
{
type Output = A<T::Output>;
fn bitxor(self, other: &'a A<U>) -> Self::Output {
A(self.0.ref_bitxor(&other.0))
}
}
pub fn f<T, U>(a: T, b: U)
where
for<'a, 'b> &'a T: BitXor<&'b U>,
{
let a_b = (&a).bitxor(&b);
// to do something with `a`, `b`, and `a_b`
todo!();
}
pub fn g<T, U>(a: T, b: U)
where
for<'a, 'b> &'a T: BitXor<&'b U>,
{
f(a, b);
}
assert!(&A(3) ^ &A(5) == A(6));