From c1210a947d5474d138f5eff89210cedef1bc870e Mon Sep 17 00:00:00 2001 From: mutantbob Date: Mon, 25 Mar 2024 17:55:56 -0400 Subject: [PATCH] new maybe_push_input() method to HIDClass using lazy closure to produce data only if the underlying device will not block (#34) Co-authored-by: Robert Forsman --- src/hid_class.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/hid_class.rs b/src/hid_class.rs index 5c3e9d9..5f57ad0 100644 --- a/src/hid_class.rs +++ b/src/hid_class.rs @@ -408,6 +408,24 @@ impl HIDClass<'_, B> { } } + pub fn maybe_push_input<'a, IR: AsInputReport>( + &self, + mut producer: impl FnMut() -> IR, + ) -> Option> { + if let Some(ep) = &self.in_ep { + let mut buff: [u8; 64] = [0; 64]; + ep.maybe_write(|| { + let size = match serialize(&mut buff, &producer()) { + Ok(l) => l, + Err(_) => return Err(UsbError::BufferOverflow), + }; + Ok(&buff[0..size]) + }) + } else { + Some(Err(UsbError::InvalidEndpoint)) + } + } + /// Tries to write an input (device-to-host) report from the given raw bytes. /// Data is expected to be a valid HID report for INPUT items. If report ID's /// were used in the descriptor, the report ID corresponding to this report