livekit_protocol/
enum_dispatch.rs

1// Copyright 2023 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// TODO(theomonnom): Async methods
16#[macro_export]
17macro_rules! enum_dispatch {
18    // This arm is used to avoid nested loops with the arguments
19    // The arguments are transformed to $combined_args tt
20    (@match [$($variant:ident),+]: $fnc:ident, $self:ident, $combined_args:tt) => {
21        match $self {
22            $(
23                Self::$variant(inner) => inner.$fnc$combined_args,
24            )+
25        }
26    };
27
28    // Create the function and extract self fron the $args tt (little hack)
29    (@fnc [$($variant:ident),+]: $vis:vis fn $fnc:ident($self:ident: $sty:ty $(, $arg:ident: $t:ty)*) -> $ret:ty) => {
30        #[inline]
31        $vis fn $fnc($self: $sty, $($arg: $t),*) -> $ret {
32            enum_dispatch!(@match [$($variant),+]: $fnc, $self, ($($arg,)*))
33        }
34    };
35
36    ($variants:tt; $($vis:vis fn $fnc:ident$args:tt -> $ret:ty;)+) => {
37        $(
38            enum_dispatch!(@fnc $variants: $vis fn $fnc$args -> $ret);
39        )+
40    };
41}