@@ -217,11 +217,21 @@ impl<T: ProtocolHandler> ProtocolHandler for Box<T> {
217217 }
218218}
219219
220+ impl < T : ProtocolHandler > From < T > for Box < dyn DynProtocolHandler > {
221+ fn from ( value : T ) -> Self {
222+ Box :: new ( value)
223+ }
224+ }
225+
220226/// A dyn-compatible version of [`ProtocolHandler`] that returns boxed futures.
221227///
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 {
225235 /// See [`ProtocolHandler::on_connecting`].
226236 fn on_connecting (
227237 & self ,
@@ -276,8 +286,7 @@ impl ProtocolMap {
276286 }
277287
278288 /// 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 > ) {
281290 self . 0 . insert ( alpn, handler) ;
282291 }
283292
@@ -348,8 +357,18 @@ impl RouterBuilder {
348357
349358 /// Configures the router to accept the [`ProtocolHandler`] when receiving a connection
350359 /// 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 ( ) ) ;
353372 self
354373 }
355374
0 commit comments