1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
//! # Calling Convention Polymorphism in Rust //! //! To parameterize a function by calling convention, we can specify that it takes some `T: //! By<'a, Convention>`, and say that its input is of type `<T as By<'a, //! Convention>>::Type`. This is essentially a defunctionalization of Rust's reference operators. //! This trick can be used to permit the *implementor* of a trait to pick the calling convention for //! a value passed into (or out of) a function defined in that trait, rather than this being //! hardcoded in the trait definition. //! ## Examples //! For instance, say we wanted to define an abstraction for channels that can send values. Imagine, //! however, that some channels might need to take ownership of the values they send, while others //! might serialize values given only a reference to that value. In order to unify these two notions //! into one trait, we can parameterize over the calling convention for the input value: //! ```rust //! use call_by::{By, Convention}; //! trait Sender<'a, T> //! where //! T: By<'a, Self::Convention>, //! { //! type Convention: Convention; //! fn send(&self, value: <T as By<'a, Self::Convention>>::Type); //! } //! ``` //! Implementers of the `Sender` trait can choose whether the associated type `Convention` should be //! `Val`, `Ref`, or `Mut`, which toggles the result of `<T as By<'a, Self::Convention>>::Type` //! between `T`, `&'a T`, and `&'a mut T`, respectively. Meanwhile, callers of the `send` method on //! concretely known types don't need to specify the calling convention; the type-level function //! determines what type they need to pass as the argument to `send`, and type errors are reported //! in reference to that concrete type if it is known at the call site. //! <!-- snip --> use std::{mem, ptr}; /// There are three fundamental ways to pass a `T` as input or return a `T` as output: by [`Val`]ue, /// by shared immutable [`Ref`]erence, and by unique [`Mut`]able reference. /// /// This is a sealed trait, implemented for all three of these conventions. pub trait Convention: sealed::Convention + Sized { const TOKEN: Self; } impl Convention for Val { const TOKEN: Self = Val; } impl Convention for Ref { const TOKEN: Self = Ref; } impl Convention for Mut { const TOKEN: Self = Mut; } /// To get the type of `T` via calling convention `Convention`, write `<T as By<'a, /// Convention>>::Type`. pub trait By<'a, C: Convention> { /// The type of `Self` when called by `Convention`. type Type; /// Copy a thing of unknown calling convention, returning an owned value. fn copy(this: Self::Type) -> Self where Self: Copy; /// Clone a thing of unknown calling convention, returning an owned value. fn clone(this: Self::Type) -> Self where Self: Clone; } /// Taking a `T` by [`Val`]ue means taking a `T` as input to or output from a function. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct Val; impl<'a, T> By<'a, Val> for T { type Type = T; fn copy(this: Self::Type) -> Self where Self: Copy, { this } fn clone(this: Self::Type) -> Self where Self: Clone, { this } } /// Taking a `T` by [`Ref`]erence means taking `&'a T` as input to or output from a function. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct Ref; impl<'a, T: 'a + ?Sized> By<'a, Ref> for T { type Type = &'a T; fn copy(this: Self::Type) -> Self where Self: Copy, { *this } fn clone(this: Self::Type) -> Self where Self: Clone, { this.clone() } } /// Taking a `T` by [`Mut`]able reference means taking `&'a mut T` as input to or output from a /// function. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct Mut; impl<'a, T: 'a + ?Sized> By<'a, Mut> for T { type Type = &'a mut T; fn copy(this: Self::Type) -> Self where Self: Copy, { *this } fn clone(this: Self::Type) -> Self where Self: Clone, { this.clone() } } /// Convert between different calling conventions. /// /// Only some conversions are sensible in Rust, due to the ownership system. These are the valid /// conversions, with the constraints on the underlying type `T` noted: /// /// | Can I convert... | ... to [`Val`] (`T`) | ... to [`Ref`] (`&'a T`) | ... to [`Mut`] (`&'a mut T`) | /// | :--------------------------------- | :------------------ | :------ | :------ | /// | **from [`Val`] (`T`) ...** | (valid for all `T`) | ❌* | ❌* | /// | **from [`Ref`] (`&'a T`) ...** | `T: 'a +` [`Clone`] | `T: 'a` | ❌** | /// | **from [`Mut`] (`&'a mut T`) ...** | `T: 'a +` [`Clone`] | `T: 'a` | `T: 'a` | /// /// > \* Impossible because references can't outlive the data they borrow. /// > /// > \** Impossible because potentially-aliased data can't be mutably referenced. pub trait Convert<'a, From: Convention, To: Convention> where Self: By<'a, To> + By<'a, From>, { /// Convert from one calling convention to another. /// /// Because of the generic parameters on the trait, this often requires rather explicit type /// annotations. /// /// # Examples /// /// ``` /// use call_by::*; /// /// let a: u8 = <u8 as Convert<Val, Val>>::convert(1); /// let b: u8 = <u8 as Convert<Ref, Val>>::convert(&2); // implicit clone /// let c: u8 = <u8 as Convert<Mut, Val>>::convert(&mut 3); // implicit clone /// /// let d: &u8 = <u8 as Convert<Ref, Ref>>::convert(&4); /// let e: &u8 = <u8 as Convert<Mut, Ref>>::convert(&mut 5); /// /// let b: &mut u8 = <u8 as Convert<Mut, Mut>>::convert(&mut 6); /// ``` #[allow(clippy::wrong_self_convention)] fn convert(from: <Self as By<'a, From>>::Type) -> <Self as By<'a, To>>::Type; } impl<'a, T> Convert<'a, Val, Val> for T { fn convert(from: T) -> T { from } } impl<'a, T: 'a + Clone> Convert<'a, Ref, Val> for T { fn convert(from: &T) -> T { from.clone() } } impl<'a, T: 'a + Clone> Convert<'a, Mut, Val> for T { fn convert(from: &mut T) -> T { Clone::clone(from) } } impl<'a, T: 'a> Convert<'a, Ref, Ref> for T { fn convert(from: &T) -> &T { from } } impl<'a, T: 'a> Convert<'a, Mut, Ref> for T { fn convert(from: &mut T) -> &T { &*from } } impl<'a, T: 'a> Convert<'a, Mut, Mut> for T { fn convert(from: &mut T) -> &mut T { from } } /// The generalization of [`Into`], [`AsRef`], and [`AsMut`]: in a calling-convention polymorphic /// context, this trait allows you to invoke the appropriate conversion method depending on the /// applicable calling convention. /// /// # Examples /// /// ``` /// use call_by::*; /// /// fn do_something<'a, T, S, C>(input: <S as By<'a, C>>::Type) /// where /// T: By<'a, C>, /// S: By<'a, C> + As<'a, C, T>, /// C: Convention, /// { /// let t: <T as By<'a, C>>::Type = S::as_convention(input); /// // ... do something with `t` ... /// } /// ``` pub trait As<'a, C: Convention, T: By<'a, C>>: By<'a, C> { #[allow(clippy::wrong_self_convention)] fn as_convention(this: <Self as By<'a, C>>::Type) -> <T as By<'a, C>>::Type; } impl<'a, T, S> As<'a, Val, T> for S where S: Into<T>, { fn as_convention(this: S) -> T { this.into() } } impl<'a, T: 'a, S: 'a> As<'a, Ref, T> for S where S: AsRef<T>, { fn as_convention(this: &S) -> &T { this.as_ref() } } impl<'a, T: 'a, S: 'a> As<'a, Mut, T> for S where S: AsMut<T>, { fn as_convention(this: &mut S) -> &mut T { this.as_mut() } } /// Safe, zero-cost cast from `<T as By<'a, Val>>::Type` to `T`. /// /// Rust's type system does not always know that `<T as By<'a, Val>>::Type` is `T` for all `'a`. /// This function safely converts from the former to the latter. pub fn to_val<'a, T: By<'a, Val>>(by_val: T::Type) -> T { let ptr = &by_val as *const <T as By<'a, Val>>::Type as *const T; let val = unsafe { ptr::read(ptr) }; mem::forget(by_val); // prevent double-free val } /// Safe, zero-cost cast from `T` to `<T as By<'a, Val>>::Type`. /// /// Rust's type system does not always know that `T` is `<T as By<'a, Val>>::Type` for all `'a`. /// This function safely converts from the former to the latter. pub fn from_val<'a, T: By<'a, Val>>(by_val: T) -> T::Type { let ptr = &by_val as *const T as *const <T as By<'a, Val>>::Type; let val = unsafe { ptr::read(ptr) }; mem::forget(by_val); // prevent double-free val } /// Safe, zero-cost cast from `<T as By<'a, Ref>>::Type` to `&'a T`. /// /// Rust's type system does not always know that `<T as By<'a, Ref>>::Type` is `&'a T` for all `'a`. /// This function safely converts from the former to the latter. pub fn to_ref<'a, T: By<'a, Ref>>(by_ref: T::Type) -> &'a T { let ptr = &by_ref as *const <T as By<'a, Ref>>::Type as *const &'a T; unsafe { ptr::read(ptr) } } /// Safe, zero-cost cast from `&'a T` to `<T as By<'a, Ref>>::Type`. /// /// Rust's type system does not always know that `&'a T` is `<T as By<'a, Ref>>::Type` for all `'a`. /// This function safely converts from the former to the latter. pub fn from_ref<'a, T: By<'a, Ref>>(by_ref: &'a T) -> T::Type { let ptr = &by_ref as *const &'a T as *const <T as By<'a, Ref>>::Type; unsafe { ptr::read(ptr) } } /// Safe, zero-cost cast from `<T as By<'a, Mut>>::Type` to `&'a mut T`. /// /// Rust's type system does not always know that `<T as By<'a, Mut>>::Type` is `&'a mut T` for all /// `'a`. This function safely converts from the former to the latter. pub fn to_mut<'a, T: By<'a, Mut>>(by_mut: T::Type) -> &'a mut T { let ptr = &by_mut as *const <T as By<'a, Mut>>::Type as *const &'a mut T; unsafe { ptr::read(ptr) } } /// Safe, zero-cost cast from `&'a mut T` to `<T as By<'a, Mut>>::Type`. /// /// Rust's type system does not always know that `&'a mut T` is `<T as By<'a, Mut>>::Type` for all /// `'a`. This function safely converts from the former to the latter. pub fn from_mut<'a, T: By<'a, Mut>>(by_mut: &'a mut T) -> T::Type { let ptr = &by_mut as *const &'a mut T as *const <T as By<'a, Mut>>::Type; unsafe { ptr::read(ptr) } } mod sealed { use super::*; pub trait Convention {} impl Convention for Val {} impl Convention for Ref {} impl Convention for Mut {} }