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
use crate::behaviour::{
self, inject_from_swarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters,
};
use crate::handler::either::IntoEitherHandler;
use either::Either;
use libp2p_core::{Multiaddr, PeerId};
use std::{task::Context, task::Poll};
impl<L, R> NetworkBehaviour for Either<L, R>
where
L: NetworkBehaviour,
R: NetworkBehaviour,
{
type ConnectionHandler = IntoEitherHandler<L::ConnectionHandler, R::ConnectionHandler>;
type OutEvent = Either<L::OutEvent, R::OutEvent>;
fn new_handler(&mut self) -> Self::ConnectionHandler {
match self {
Either::Left(a) => IntoEitherHandler::Left(a.new_handler()),
Either::Right(b) => IntoEitherHandler::Right(b.new_handler()),
}
}
fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> {
match self {
Either::Left(a) => a.addresses_of_peer(peer_id),
Either::Right(b) => b.addresses_of_peer(peer_id),
}
}
fn on_swarm_event(&mut self, event: behaviour::FromSwarm<Self::ConnectionHandler>) {
match self {
Either::Left(b) => inject_from_swarm(
b,
event.map_handler(
|h| h.unwrap_left(),
|h| match h {
Either::Left(h) => h,
Either::Right(_) => unreachable!(),
},
),
),
Either::Right(b) => inject_from_swarm(
b,
event.map_handler(
|h| h.unwrap_right(),
|h| match h {
Either::Right(h) => h,
Either::Left(_) => unreachable!(),
},
),
),
}
}
fn on_connection_handler_event(
&mut self,
peer_id: PeerId,
connection_id: libp2p_core::connection::ConnectionId,
event: crate::THandlerOutEvent<Self>,
) {
match (self, event) {
(Either::Left(left), Either::Left(event)) => {
#[allow(deprecated)]
left.inject_event(peer_id, connection_id, event);
}
(Either::Right(right), Either::Right(event)) => {
#[allow(deprecated)]
right.inject_event(peer_id, connection_id, event);
}
_ => unreachable!(),
}
}
fn poll(
&mut self,
cx: &mut Context<'_>,
params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
let event = match self {
Either::Left(behaviour) => futures::ready!(behaviour.poll(cx, params))
.map_out(Either::Left)
.map_handler_and_in(IntoEitherHandler::Left, Either::Left),
Either::Right(behaviour) => futures::ready!(behaviour.poll(cx, params))
.map_out(Either::Right)
.map_handler_and_in(IntoEitherHandler::Right, Either::Right),
};
Poll::Ready(event)
}
}