Skip to content

Commit b3dae36

Browse files
committed
gcoap: Open server registration for different listeners
1 parent 3933e83 commit b3dae36

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

src/gcoap.rs

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,28 @@ pub struct RegistrationScope {
2929

3030
impl RegistrationScope {
3131
// FIXME: Generalize SingleHandlerListener::get_listener into a trait
32-
pub fn register<'scope, 'handler: 'scope, H: Handler>(&'scope mut self, handler: &'handler mut SingleHandlerListener<'handler, H>) {
32+
pub fn register<'scope, 'handler, P>(&'scope mut self, handler: &'handler mut P) where
33+
'handler: 'scope,
34+
P: 'handler + ListenerProvider
35+
{
3336
// Unsafe: Moving in a pointer to an internal structure to which we were given an exclusive
3437
// reference that outlives self -- and whoever can create a Self guarantees that
3538
// deregister_all() will be called before the end of this self's lifetime.
36-
unsafe { gcoap_register_listener(handler.get_listener()) };
39+
unsafe { gcoap_register_listener(handler.get_listener() as *mut _) };
3740
}
3841

3942
fn deregister_all(&mut self) {
4043
panic!("Registration callback returned, but Gcoap does not allow deregistration.");
4144
}
4245
}
4346

47+
pub trait ListenerProvider {
48+
/// Provide an exclusive reference to the underlying gcoap listener. The function is marked
49+
/// unsafe as the returned value contains raw pointers that will later be dereferenced, and
50+
/// returning arbitrary pointers would make RegistratinScope::register() pass bad data on to C.
51+
unsafe fn get_listener<'a>(&'a mut self) -> &'a mut gcoap_listener_t;
52+
}
53+
4454
pub struct SingleHandlerListener<'a, H> {
4555
_phantom: PhantomData<&'a H>,
4656
resource: coap_resource_t,
@@ -75,15 +85,6 @@ where
7585
}
7686
}
7787

78-
pub fn get_listener(&mut self) -> *mut gcoap_listener_t {
79-
self.listener.resources = &self.resource;
80-
self.listener.resources_len = 1;
81-
self.listener.next = 0 as *mut _;
82-
83-
&mut self.listener as *mut _
84-
}
85-
86-
8788
unsafe extern "C" fn call_handler(
8889
pkt: *mut coap_pkt_t,
8990
buf: *mut u8,
@@ -97,6 +98,20 @@ where
9798
}
9899
}
99100

101+
impl<'a, H> ListenerProvider for SingleHandlerListener<'a, H>
102+
where
103+
H: 'a + Handler
104+
{
105+
unsafe fn get_listener(&mut self) -> &mut gcoap_listener_t {
106+
self.listener.resources = &self.resource;
107+
self.listener.resources_len = 1;
108+
self.listener.next = 0 as *mut _;
109+
110+
&mut self.listener
111+
}
112+
113+
}
114+
100115
pub trait Handler {
101116
fn handle(&mut self, pkt: &mut PacketBuffer) -> isize;
102117
}

0 commit comments

Comments
 (0)