#conventions #calling #traits #polymorphism #call #reference #input

call-by

A trick to parameterize functions and traits by the calling convention of their arguments and results

5 releases

0.2.3 Apr 13, 2021
0.2.2 Apr 5, 2021
0.2.1 Apr 1, 2021
0.2.0 Mar 24, 2021
0.1.0 Dec 16, 2020

#1164 in Encoding

Download history 8/week @ 2024-05-26 13/week @ 2024-06-02 7/week @ 2024-06-09 11/week @ 2024-06-16 10/week @ 2024-06-23 2/week @ 2024-06-30 5/week @ 2024-07-07 15/week @ 2024-07-14 11/week @ 2024-07-21 12/week @ 2024-07-28 7/week @ 2024-08-04 6/week @ 2024-08-11 6/week @ 2024-08-18 34/week @ 2024-08-25 19/week @ 2024-09-01 5/week @ 2024-09-08

65 downloads per month
Used in 7 crates (via dialectic)

MIT license

14KB
183 lines

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:

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.

No runtime deps