@@ -217,11 +217,21 @@ impl<T: ProtocolHandler> ProtocolHandler for Box<T> {
217
217
}
218
218
}
219
219
220
+ impl < T : ProtocolHandler > From < T > for Box < dyn DynProtocolHandler > {
221
+ fn from ( value : T ) -> Self {
222
+ Box :: new ( value)
223
+ }
224
+ }
225
+
220
226
/// A dyn-compatible version of [`ProtocolHandler`] that returns boxed futures.
221
227
///
222
- /// We are not using [`n0_future::boxed::BoxFuture] because we don't need a `'static` bound
223
- /// on these futures.
224
- pub ( crate ) trait DynProtocolHandler : Send + Sync + std:: fmt:: Debug + ' static {
228
+ /// Any type that implements [`ProtocolHandler`] automatically also implements [`DynProtocolHandler`].
229
+ /// There is a also [`From`] impl to turn any type that implements [`ProtocolHandler`] into a
230
+ /// `Box<dyn DynProtocolHandler>`.
231
+ //
232
+ // We are not using [`n0_future::boxed::BoxFuture] because we don't need a `'static` bound
233
+ // on these futures.
234
+ pub trait DynProtocolHandler : Send + Sync + std:: fmt:: Debug + ' static {
225
235
/// See [`ProtocolHandler::on_connecting`].
226
236
fn on_connecting (
227
237
& self ,
@@ -276,8 +286,7 @@ impl ProtocolMap {
276
286
}
277
287
278
288
/// Inserts a protocol handler.
279
- pub ( crate ) fn insert ( & mut self , alpn : Vec < u8 > , handler : impl ProtocolHandler ) {
280
- let handler = Box :: new ( handler) ;
289
+ pub ( crate ) fn insert ( & mut self , alpn : Vec < u8 > , handler : Box < dyn DynProtocolHandler > ) {
281
290
self . 0 . insert ( alpn, handler) ;
282
291
}
283
292
@@ -348,8 +357,18 @@ impl RouterBuilder {
348
357
349
358
/// Configures the router to accept the [`ProtocolHandler`] when receiving a connection
350
359
/// with this `alpn`.
351
- pub fn accept ( mut self , alpn : impl AsRef < [ u8 ] > , handler : impl ProtocolHandler ) -> Self {
352
- self . protocols . insert ( alpn. as_ref ( ) . to_vec ( ) , handler) ;
360
+ ///
361
+ /// `handler` can either be a type that implements [`ProtocolHandler`] or a
362
+ /// [`Box<dyn DynProtocolHandler>`].
363
+ ///
364
+ /// [`Box<dyn DynProtocolHandler>`]: DynProtocolHandler
365
+ pub fn accept (
366
+ mut self ,
367
+ alpn : impl AsRef < [ u8 ] > ,
368
+ handler : impl Into < Box < dyn DynProtocolHandler > > ,
369
+ ) -> Self {
370
+ self . protocols
371
+ . insert ( alpn. as_ref ( ) . to_vec ( ) , handler. into ( ) ) ;
353
372
self
354
373
}
355
374
0 commit comments