hidra 0.0.4

Pure Rust HID library.
Documentation
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! # hidra
//!
//! A pure-Rust HID library.
//!
//! hidra talks to HID devices through native OS interfaces:
//!
#![cfg_attr(
    not(target_arch = "wasm32"),
    doc = "| Target | [`Native`] | [`Nusb`] (feature `nusb`) |
|--------|---------------------|------------------------------------|
| Linux   | `hidraw` device nodes + sysfs enumeration | USB interrupt/control transfers via [nusb] |
| Windows | `hid.dll` / `SetupAPI` via `windows-sys` declarations | as above |
| macOS   | `IOHIDManager` via direct framework FFI | as above |
"
)]
#![cfg_attr(
    target_arch = "wasm32",
    doc = "| Target | Native | `nusb` (feature `nusb`) |
|--------|--------|-------------------------|
| Linux   | `hidraw` device nodes + sysfs enumeration | USB interrupt/control transfers via [nusb] |
| Windows | `hid.dll` / `SetupAPI` via `windows-sys` declarations | as above |
| macOS   | `IOHIDManager` via direct framework FFI | as above |
"
)]
//!
//! On WebAssembly the backend is always
//! [`WebHID`](https://wicg.github.io/webhid/) via `web-sys`.
//!
#![cfg_attr(
    not(target_arch = "wasm32"),
    doc = "The backend is a type parameter: [`Hidra<Native>`](Hidra) for the OS HID
stack, [`Hidra<Nusb>`](Hidra) for raw USB. Both coexist in one build, so a
program can drive two devices through different backends at once. A backend
this build does not have cannot be named, so the wrong choice is a compile
error rather than a run-time one.
"
)]
//!
//! ```no_run
//! # #[cfg(all(not(target_arch = "wasm32"), feature = "nusb"))] fn demo() -> hidra::HidResult<()> {
//! use hidra::{Hidra, Nusb};
//! let native = Hidra::new()?;                    // the OS HID stack
//! let usb = Hidra::<Nusb>::builder().build()?;  // raw USB transfers
//! # let _ = (native, usb);
//! # Ok(()) }
//! ```
//!
//! They are different types, so a handle that holds either is the caller's to
//! declare; `examples/backends.rs` shows the whole of it.
//!
//! Following nusb's model, every [`Hidra`] / [`HidDevice`] I/O method returns
//! an `impl Future`. On native targets bring `MaybeFuture` into scope to drive
//! it blocking with `.wait()`, or `.await` it under any async runtime (no
//! executor dependency, wake-ups are plain `Waker`s like nusb).
//!
//! On `wasm32` the same [`Hidra`] / [`HidDevice`] types are backed by `WebHID`;
//! there is no blocking mode, so always `.await` their futures (no `.wait()`).
//! Discovery is WebHID-shaped: `Hidra::request_device` shows the browser's
//! device chooser (filtered with `DeviceFilter`) and `Hidra::get_devices`
//! lists previously granted devices. [`descriptor`] offers report-descriptor
//! primitives that work everywhere.
//!
//! ```no_run
//! # #[cfg(not(target_arch = "wasm32"))] fn demo() -> hidra::HidResult<()> {
//! use hidra::MaybeFuture;
//! let api = hidra::Hidra::new()?;
//! for dev in api.device_list() {
//!     println!("{:04x}:{:04x} {}", dev.vendor_id(), dev.product_id(),
//!              dev.product_string().unwrap_or("<unnamed>"));
//! }
//! let device = api.open(0x046d, 0xc216).wait()?;
//! device.write(&[0x00, 0x01, 0x02]).wait()?; // report ID 0 + payload
//! let mut buf = [0u8; 64];
//! let len = device.read(&mut buf).wait()?;
//! # let _ = len; Ok(()) }
//! ```
//!
//! [nusb]: https://docs.rs/nusb

pub mod descriptor;
mod device_info;
mod error;
pub mod report_info;

pub use device_info::{BusType, DeviceInfo};
pub use error::{HidError, HidResult};

// Houses every backend: the per-OS native ones and nusb (non-wasm), and the
// WebHID backend (wasm). Its internals are individually cfg-gated.
mod backend;

#[cfg(not(target_arch = "wasm32"))]
mod maybe_future;
#[cfg(not(target_arch = "wasm32"))]
pub use maybe_future::MaybeFuture;

/// WebHID-only public surface: the device filter for `Hidra::request_device`,
/// the listener handle returned by the event hooks, and the buffered input
/// report stream from `HidDevice::start_reading`.
#[cfg(target_arch = "wasm32")]
pub use backend::webhid::{DeviceFilter, EventListenerHandle, InputReportStream};

/// hidra's version, mirroring `hid_version()`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ApiVersion {
    /// Major version component.
    pub major: u16,
    /// Minor version component.
    pub minor: u16,
    /// Patch version component.
    pub patch: u16,
}

/// Library version (`hid_version` equivalent).
pub const fn version() -> ApiVersion {
    const fn parse(s: &str) -> u16 {
        let bytes = s.as_bytes();
        let mut v = 0u16;
        let mut i = 0;
        while i < bytes.len() {
            v = v * 10 + (bytes[i] - b'0') as u16;
            i += 1;
        }
        v
    }
    ApiVersion {
        major: parse(env!("CARGO_PKG_VERSION_MAJOR")),
        minor: parse(env!("CARGO_PKG_VERSION_MINOR")),
        patch: parse(env!("CARGO_PKG_VERSION_PATCH")),
    }
}

/// Library version string (`hid_version_str` equivalent).
pub const fn version_str() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// The backend traits, and the backend types implementing them.
#[cfg(not(target_arch = "wasm32"))]
pub use backend::{HidBackend, HidDeviceBackend};
#[cfg(not(target_arch = "wasm32"))]
pub use backend::{Native, NativeDevice};
#[cfg(all(
    feature = "nusb",
    any(target_os = "linux", target_os = "macos", target_os = "windows")
))]
pub use backend::{Nusb, NusbDevice};
#[cfg(not(target_arch = "wasm32"))]
pub use native::{HidDevice, Hidra, HidraBuilder};

#[cfg(target_arch = "wasm32")]
pub use web::{HidDevice, Hidra};

#[cfg(not(target_arch = "wasm32"))]
mod native {
    use core::future::Future;

    use crate::backend::{HidBackend, HidDeviceBackend, Native, NativeDevice};
    use crate::{DeviceInfo, HidResult};

    /// Entry point to the library; owns backend state and the cached device
    /// list.
    ///
    /// `B` is the backend: [`Native`] (the default) for the OS HID stack, or
    /// [`Nusb`](crate::Nusb) for raw USB transfers. A backend this build does
    /// not have is simply not nameable, so the wrong choice is a compile
    /// error.
    ///
    /// There is no global state: create as many instances as you like, from
    /// any thread, on either backend.
    pub struct Hidra<B: HidBackend = Native> {
        backend: B,
        device_list: Vec<DeviceInfo>,
    }

    // The platform backends hold raw OS handles that have no useful `Debug`;
    // report the selected backend and the cached device count instead, which
    // is what a caller inspecting a `Hidra` actually wants to see.
    impl<B: HidBackend> core::fmt::Debug for Hidra<B> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("Hidra")
                .field("devices", &self.device_list.len())
                .finish_non_exhaustive()
        }
    }

    /// Configures a [`Hidra`]: whether to enumerate up front, and on which
    /// backend.
    ///
    /// ```no_run
    /// # fn demo() -> hidra::HidResult<()> {
    /// use hidra::{Hidra, Nusb};
    /// let api = Hidra::<Nusb>::builder().build()?;
    /// # let _ = api; Ok(()) }
    /// ```
    #[derive(Debug, Clone)]
    pub struct HidraBuilder<B: HidBackend = Native> {
        enumerate_on_build: bool,
        backend: core::marker::PhantomData<B>,
    }

    impl<B: HidBackend> Default for HidraBuilder<B> {
        fn default() -> Self {
            HidraBuilder {
                enumerate_on_build: true,
                backend: core::marker::PhantomData,
            }
        }
    }

    impl<B: HidBackend> HidraBuilder<B> {
        /// Whether [`build`](Self::build) enumerates connected devices.
        /// Defaults to `true`; pass `false` when you only need
        /// [`Hidra::open_path`].
        #[must_use]
        pub fn enumerate_on_build(mut self, enumerate: bool) -> Self {
            self.enumerate_on_build = enumerate;
            self
        }

        /// Initialize the backend.
        pub fn build(self) -> HidResult<Hidra<B>> {
            let mut api = Hidra {
                backend: B::new()?,
                device_list: Vec::new(),
            };
            if self.enumerate_on_build {
                api.refresh_devices()?;
            }
            Ok(api)
        }
    }

    /// Constructors for the default backend.
    ///
    /// These are on `Hidra<Native>` rather than the generic impl for the same
    /// reason `HashMap::new` is: a default type parameter does not drive
    /// inference, so `Hidra::new()` would otherwise need a turbofish. Other
    /// backends go through [`builder`](Hidra::builder).
    impl Hidra<Native> {
        /// Initialize the default backend and enumerate all connected HID
        /// devices.
        pub fn new() -> HidResult<Self> {
            Self::builder().build()
        }

        /// Initialize the default backend without enumerating (cheaper when
        /// you only need [`open_path`](Self::open_path)).
        #[deprecated(
            since = "0.0.4",
            note = "use Hidra::builder().enumerate_on_build(false).build()"
        )]
        pub fn new_without_enumerate() -> HidResult<Self> {
            Self::builder().enumerate_on_build(false).build()
        }
    }

    impl<B: HidBackend> Hidra<B> {
        /// Start configuring a `Hidra`.
        #[must_use]
        pub fn builder() -> HidraBuilder<B> {
            HidraBuilder::default()
        }

        /// Re-enumerate connected devices, refreshing
        /// [`device_list`](Self::device_list).
        pub fn refresh_devices(&mut self) -> HidResult<()> {
            self.device_list = self.backend.enumerate(0, 0)?;
            Ok(())
        }

        /// The cached device list from the last enumeration.
        pub fn device_list(&self) -> impl Iterator<Item = &DeviceInfo> {
            self.device_list.iter()
        }

        /// Enumerate devices matching `vendor_id`/`product_id` directly from
        /// the OS (`hid_enumerate(vid, pid)` equivalent; `0` is a wildcard).
        /// Does not touch the cached list.
        pub fn enumerate(&self, vendor_id: u16, product_id: u16) -> HidResult<Vec<DeviceInfo>> {
            self.backend.enumerate(vendor_id, product_id)
        }

        /// Open the first device matching `vendor_id`/`product_id`
        /// (`hid_open` with a null serial).
        pub fn open(
            &self,
            vendor_id: u16,
            product_id: u16,
        ) -> impl Future<Output = HidResult<HidDevice<B::Device>>> + '_ {
            crate::maybe_future::Blocking::new(move || {
                Ok(HidDevice {
                    backend: self.backend.open(vendor_id, product_id, None)?,
                })
            })
        }

        /// Open the device matching `vendor_id`/`product_id` and serial
        /// number (`hid_open` equivalent).
        pub fn open_serial<'a>(
            &'a self,
            vendor_id: u16,
            product_id: u16,
            serial_number: &'a str,
        ) -> impl Future<Output = HidResult<HidDevice<B::Device>>> + 'a {
            crate::maybe_future::Blocking::new(move || {
                Ok(HidDevice {
                    backend: self
                        .backend
                        .open(vendor_id, product_id, Some(serial_number))?,
                })
            })
        }

        /// Open a device by platform path (`hid_open_path` equivalent). Use
        /// the paths reported by [`DeviceInfo::path`].
        pub fn open_path<'a>(
            &'a self,
            path: &'a str,
        ) -> impl Future<Output = HidResult<HidDevice<B::Device>>> + 'a {
            crate::maybe_future::Blocking::new(move || {
                Ok(HidDevice {
                    backend: self.backend.open_path(path)?,
                })
            })
        }
    }

    /// macOS-specific options, on [`Native`] only.
    ///
    /// `Nusb` claims the USB interface outright and has no shared mode to
    /// configure, so it does not carry these at all.
    #[cfg(target_os = "macos")]
    impl Hidra<Native> {
        /// Whether subsequently opened devices are seized exclusively
        /// (`hid_darwin_set_open_exclusive`). Defaults to shared
        /// (non-exclusive) access.
        pub fn set_open_exclusive(&self, exclusive: bool) {
            self.backend.set_open_exclusive(exclusive);
        }

        /// Current exclusivity setting.
        pub fn open_exclusive(&self) -> bool {
            self.backend.open_exclusive()
        }
    }

    /// An open HID device. Closed on drop.
    ///
    /// `D` follows from the [`Hidra`] that opened it. All methods take
    /// `&self`; the handle is `Send + Sync` and may be shared across threads.
    pub struct HidDevice<D: HidDeviceBackend = NativeDevice> {
        backend: D,
    }

    impl<D: HidDeviceBackend> core::fmt::Debug for HidDevice<D> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("HidDevice").finish_non_exhaustive()
        }
    }

    impl<D: HidDeviceBackend> HidDevice<D> {
        /// Send an output report (`hid_write`).
        ///
        /// `data[0]` must be the report ID (0 when the device has no
        /// numbered reports); the first byte is consumed accordingly and
        /// counts toward the returned length.
        ///
        /// Writes are synchronous kernel calls on every platform (there is no
        /// async OS primitive for them), so the returned future completes on
        /// first poll; it is exposed as a future only so blocking and async
        /// callers share one API.
        pub fn write<'a>(&'a self, data: &'a [u8]) -> impl Future<Output = HidResult<usize>> + 'a {
            crate::maybe_future::Blocking::new(move || self.backend.write(data))
        }

        /// Read one input report asynchronously (hidra's async `hid_read`).
        ///
        /// Resolves once a report has been copied into `buf`, returning its
        /// length, never `Ok(0)`; use your runtime's timeout combinator
        /// (e.g. `tokio::time::timeout`) to bound the wait. Reports are
        /// prefixed with their report ID only when the device uses numbered
        /// reports. Fails with
        /// [`HidError::Disconnected`](crate::HidError::Disconnected) when the
        /// device is removed.
        ///
        /// The future is runtime-agnostic (plain `Waker` wake-ups, like nusb,
        /// works under tokio, async-std, smol or a hand-rolled executor) and
        /// cancel-safe: dropping it never loses a report; pending input stays
        /// queued for the next read. Drive it blocking with
        /// [`MaybeFuture::wait`](crate::MaybeFuture::wait).
        ///
        /// Only input reads are asynchronous: writes and feature reports are
        /// synchronous kernel calls on every platform, so those futures
        /// complete on first poll.
        pub fn read<'a>(
            &'a self,
            buf: &'a mut [u8],
        ) -> impl Future<Output = HidResult<usize>> + 'a {
            self.backend.read_async(buf)
        }

        /// Send a feature report (`hid_send_feature_report`). `data[0]` is
        /// the report ID, 0 if unnumbered.
        pub fn send_feature_report<'a>(
            &'a self,
            data: &'a [u8],
        ) -> impl Future<Output = HidResult<()>> + 'a {
            crate::maybe_future::Blocking::new(move || self.backend.send_feature_report(data))
        }

        /// Get a feature report (`hid_get_feature_report`). Set `buf[0]` to
        /// the report ID before calling; returns the report (ID included)
        /// and its length.
        pub fn get_feature_report<'a>(
            &'a self,
            buf: &'a mut [u8],
        ) -> impl Future<Output = HidResult<usize>> + 'a {
            crate::maybe_future::Blocking::new(move || self.backend.get_feature_report(buf))
        }

        /// Get an input report synchronously (`hid_get_input_report`). Same
        /// buffer convention as [`get_feature_report`](Self::get_feature_report).
        pub fn get_input_report<'a>(
            &'a self,
            buf: &'a mut [u8],
        ) -> impl Future<Output = HidResult<usize>> + 'a {
            crate::maybe_future::Blocking::new(move || self.backend.get_input_report(buf))
        }

        /// Manufacturer string (`hid_get_manufacturer_string`).
        pub fn get_manufacturer_string(
            &self,
        ) -> impl Future<Output = HidResult<Option<String>>> + '_ {
            crate::maybe_future::Blocking::new(move || self.backend.get_manufacturer_string())
        }

        /// Product string (`hid_get_product_string`).
        pub fn get_product_string(&self) -> impl Future<Output = HidResult<Option<String>>> + '_ {
            crate::maybe_future::Blocking::new(move || self.backend.get_product_string())
        }

        /// Serial number string (`hid_get_serial_number_string`).
        pub fn get_serial_number_string(
            &self,
        ) -> impl Future<Output = HidResult<Option<String>>> + '_ {
            crate::maybe_future::Blocking::new(move || self.backend.get_serial_number_string())
        }

        /// A string from the device's string descriptor table
        /// (`hid_get_indexed_string`). Only meaningful for USB devices.
        pub fn get_indexed_string(
            &self,
            index: u32,
        ) -> impl Future<Output = HidResult<Option<String>>> + '_ {
            crate::maybe_future::Blocking::new(move || self.backend.get_indexed_string(index))
        }

        /// Raw report descriptor (`hid_get_report_descriptor`). Returns the
        /// number of bytes written into `buf`; 4096 bytes is always enough.
        pub fn get_report_descriptor<'a>(
            &'a self,
            buf: &'a mut [u8],
        ) -> impl Future<Output = HidResult<usize>> + 'a {
            crate::maybe_future::Blocking::new(move || self.backend.get_report_descriptor(buf))
        }

        /// Raw report descriptor as a vector (convenience over
        /// [`get_report_descriptor`](Self::get_report_descriptor)).
        pub fn report_descriptor(&self) -> impl Future<Output = HidResult<Vec<u8>>> + '_ {
            crate::maybe_future::Blocking::new(move || {
                let mut buf = vec![0u8; crate::MAX_REPORT_DESCRIPTOR_SIZE];
                let len = self.backend.get_report_descriptor(&mut buf)?;
                buf.truncate(len);
                Ok(buf)
            })
        }

        /// Parsed report descriptor (hidra extension built on
        /// [`crate::descriptor`]).
        pub async fn parsed_report_descriptor(
            &self,
        ) -> HidResult<crate::descriptor::ReportDescriptor> {
            let bytes = self.report_descriptor().await?;
            crate::descriptor::ReportDescriptor::parse(&bytes)
        }

        /// Metadata for this open device (`hid_get_device_info`).
        pub fn get_device_info(&self) -> impl Future<Output = HidResult<DeviceInfo>> + '_ {
            crate::maybe_future::Blocking::new(move || self.backend.get_device_info())
        }
    }

    /// Windows-specific extensions (`hid_winapi_*` equivalents), on
    /// [`NativeDevice`] only.
    ///
    /// `Nusb` goes nowhere near the Windows HID stack these come from, so it
    /// does not carry them at all.
    #[cfg(target_os = "windows")]
    impl HidDevice<NativeDevice> {
        /// The container ID GUID grouping this interface with its siblings
        /// (`hid_winapi_get_container_id`), as 16 little-endian GUID bytes.
        pub fn container_id(&self) -> impl Future<Output = HidResult<[u8; 16]>> + '_ {
            crate::maybe_future::Blocking::new(move || self.backend.container_id())
        }

        /// Set the timeout for `write` in milliseconds
        /// (`hid_winapi_set_write_timeout`). Defaults to 1000 ms.
        pub fn set_write_timeout(&self, timeout_ms: u32) {
            self.backend.set_write_timeout(timeout_ms);
        }
    }
}

/// Largest report descriptor a HID device can have
/// (`HID_API_MAX_REPORT_DESCRIPTOR_SIZE`).
pub const MAX_REPORT_DESCRIPTOR_SIZE: usize = 4096;

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    /// `Hidra` and `HidDevice` are documented as shareable across threads.
    /// The `HidBackend`/`HidDeviceBackend` bounds make that hold for whichever
    /// backend is selected; this pins it for the public wrappers too.
    #[test]
    fn public_handles_are_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<super::Hidra>();
        assert_send_sync::<super::HidDevice>();
        assert_send_sync::<super::HidError>();
        assert_send_sync::<super::DeviceInfo>();
    }

    /// Both backends satisfy the same bounds, so a caller can be generic over
    /// them without the wrapper types diverging.
    #[cfg(feature = "nusb")]
    #[test]
    fn both_backends_are_usable_generically() {
        fn assert_backend<B: super::HidBackend>() {}
        assert_backend::<super::Native>();
        assert_backend::<super::Nusb>();
        fn assert_handles<B: super::HidBackend>() {
            fn send_sync<T: Send + Sync>() {}
            send_sync::<super::Hidra<B>>();
        }
        assert_handles::<super::Native>();
        assert_handles::<super::Nusb>();
    }
}

#[cfg(target_arch = "wasm32")]
mod web {
    use core::cell::RefCell;
    use core::future::Future;

    use crate::backend::webhid::{
        DeviceFilter, EventListenerHandle, InputReportStream, WebHidApi, WebHidDevice,
    };
    use crate::report_info::CollectionInfo;
    use crate::{DeviceInfo, HidResult};

    /// Entry point to the library, backed by `WebHID` (`navigator.hid`).
    ///
    /// Discovery is WebHID-shaped rather than native-HID-shaped: the browser only
    /// ever exposes devices the user has granted access to, so there is no
    /// enumerate / open-by-vid-pid. Use [`request_device`](Self::request_device)
    /// to show the permission chooser and [`get_devices`](Self::get_devices) to
    /// list previously granted devices.
    pub struct Hidra {
        backend: WebHidApi,
    }

    impl core::fmt::Debug for Hidra {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("Hidra").finish_non_exhaustive()
        }
    }

    // These I/O methods return `impl Future` to mirror the native `Hidra` /
    // `HidDevice` signatures exactly (native backs them with `Blocking`, not an
    // async block), so the `manual_async_fn` suggestion does not apply.
    #[allow(clippy::manual_async_fn)]
    impl Hidra {
        /// Bind to `window.navigator.hid`.
        ///
        /// Fails with [`HidError::Initialization`](crate::HidError::Initialization)
        /// when `WebHID` is unavailable (no window, a non-secure context, or a
        /// browser without `WebHID` support).
        pub fn new() -> HidResult<Self> {
            Ok(Hidra {
                backend: WebHidApi::new()?,
            })
        }

        /// Ask the user to grant access to devices matching `filters`
        /// (`navigator.hid.requestDevice`). An empty filter list matches every
        /// device.
        ///
        /// Shows the browser's device chooser and resolves with every device
        /// the user granted (an empty `Vec` when the chooser was dismissed).
        /// **Must be called from within a user gesture** (e.g. a click event
        /// handler), otherwise the browser rejects the request.
        pub fn request_device<'a>(
            &'a self,
            filters: &'a [DeviceFilter],
        ) -> impl Future<Output = HidResult<Vec<HidDevice>>> + 'a {
            async move {
                let devices = self.backend.request_device(filters).await?;
                Ok(devices.into_iter().map(HidDevice::new).collect())
            }
        }

        /// Devices the user has already granted this origin access to
        /// (`navigator.hid.getDevices`). Needs no user gesture.
        pub fn get_devices(&self) -> impl Future<Output = HidResult<Vec<HidDevice>>> + '_ {
            async move {
                let devices = self.backend.get_devices().await?;
                Ok(devices.into_iter().map(HidDevice::new).collect())
            }
        }

        /// Invoke `f` whenever a granted device is plugged in (the `connect`
        /// event). Drop the returned handle to unregister.
        pub fn on_connect(&self, mut f: impl FnMut(HidDevice) + 'static) -> EventListenerHandle {
            self.backend.on_connect(move |dev| f(HidDevice::new(dev)))
        }

        /// Invoke `f` whenever a granted device is unplugged (the `disconnect`
        /// event). Drop the returned handle to unregister.
        pub fn on_disconnect(&self, mut f: impl FnMut(HidDevice) + 'static) -> EventListenerHandle {
            self.backend
                .on_disconnect(move |dev| f(HidDevice::new(dev)))
        }

        /// The underlying `navigator.hid` object (`WebHID` escape hatch).
        pub fn raw(&self) -> &web_sys::Hid {
            self.backend.raw()
        }
    }

    /// An HID device exposed by the browser, backed by `WebHID`.
    ///
    /// Unlike a native HID library the handle exists before the device is opened, so
    /// call [`open`](Self::open) before transferring reports.
    pub struct HidDevice {
        backend: WebHidDevice,
        /// Lazily started on the first [`read`](Self::read); reused thereafter.
        stream: RefCell<Option<InputReportStream>>,
    }

    impl core::fmt::Debug for HidDevice {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("HidDevice")
                .field("opened", &self.backend.opened())
                .finish_non_exhaustive()
        }
    }

    #[allow(clippy::manual_async_fn)]
    impl HidDevice {
        fn new(backend: WebHidDevice) -> Self {
            HidDevice {
                backend,
                stream: RefCell::new(None),
            }
        }

        // --- shared methods (signatures match native) ----------------------

        /// Send an output report (`hid_write`).
        ///
        /// `data[0]` must be the report ID (0 when the device has no numbered
        /// reports); the first byte is consumed accordingly and counts toward
        /// the returned length.
        pub fn write<'a>(&'a self, data: &'a [u8]) -> impl Future<Output = HidResult<usize>> + 'a {
            self.backend.write(data)
        }

        /// Read one input report asynchronously (hidra's async `hid_read`).
        ///
        /// Resolves once a report has been copied into `buf`, returning its
        /// length. Reports are prefixed with their report ID only when the
        /// device uses numbered reports, matching native.
        ///
        /// Backed by a single [`InputReportStream`] lazily started on the first
        /// call (so reports are queued from that point on); subsequent reads
        /// reuse it and drain the queue in order.
        pub fn read<'a>(
            &'a self,
            buf: &'a mut [u8],
        ) -> impl Future<Output = HidResult<usize>> + 'a {
            async move {
                if self.stream.borrow().is_none() {
                    *self.stream.borrow_mut() = Some(self.backend.start_reading());
                }
                // `next_report` clones the stream's shared queue handle, so the
                // RefCell borrow is released before awaiting.
                let read = {
                    let guard = self.stream.borrow();
                    let stream = guard.as_ref().expect("stream started above");
                    stream.next_report()
                };
                let report = read.await?;
                let len = report.len().min(buf.len());
                buf[..len].copy_from_slice(&report[..len]);
                Ok(len)
            }
        }

        /// Send a feature report (`hid_send_feature_report`). `data[0]` is the
        /// report ID, 0 if unnumbered.
        pub fn send_feature_report<'a>(
            &'a self,
            data: &'a [u8],
        ) -> impl Future<Output = HidResult<()>> + 'a {
            self.backend.send_feature_report(data)
        }

        /// Get a feature report (`hid_get_feature_report`). Set `buf[0]` to the
        /// report ID before calling; returns the report (ID included) and its
        /// length.
        pub fn get_feature_report<'a>(
            &'a self,
            buf: &'a mut [u8],
        ) -> impl Future<Output = HidResult<usize>> + 'a {
            async move {
                let report_id =
                    buf.first()
                        .copied()
                        .ok_or_else(|| crate::HidError::InvalidData {
                            message: "get_feature_report requires at least the report ID byte"
                                .into(),
                        })?;
                let report = self.backend.get_feature_report(report_id).await?;
                let len = report.len().min(buf.len());
                buf[..len].copy_from_slice(&report[..len]);
                Ok(len)
            }
        }

        /// Raw report descriptor (`hid_get_report_descriptor`). Returns the
        /// number of bytes written into `buf`; 4096 bytes is always enough.
        pub fn get_report_descriptor<'a>(
            &'a self,
            buf: &'a mut [u8],
        ) -> impl Future<Output = HidResult<usize>> + 'a {
            async move {
                let descriptor = self.backend.report_descriptor()?;
                let len = descriptor.len().min(buf.len());
                buf[..len].copy_from_slice(&descriptor[..len]);
                Ok(len)
            }
        }

        /// Raw report descriptor as a vector (convenience over
        /// [`get_report_descriptor`](Self::get_report_descriptor)).
        pub fn report_descriptor(&self) -> impl Future<Output = HidResult<Vec<u8>>> + '_ {
            async move { self.backend.report_descriptor() }
        }

        /// Parsed report descriptor (hidra extension built on
        /// [`crate::descriptor`]).
        pub async fn parsed_report_descriptor(
            &self,
        ) -> HidResult<crate::descriptor::ReportDescriptor> {
            self.backend.parsed_report_descriptor()
        }

        /// Product string (`hid_get_product_string`).
        pub fn get_product_string(&self) -> impl Future<Output = HidResult<Option<String>>> + '_ {
            async move { Ok(self.backend.product_name()) }
        }

        /// Metadata for this open device (`hid_get_device_info`).
        pub fn get_device_info(&self) -> impl Future<Output = HidResult<DeviceInfo>> + '_ {
            async move { Ok(self.backend.device_info()) }
        }

        // --- WebHID-specific extras ----------------------------------------

        /// Open the device for I/O (`HIDDevice.open`). Required before any
        /// report transfer.
        pub async fn open(&self) -> HidResult<()> {
            self.backend.open().await
        }

        /// Close the device (`HIDDevice.close`). The permission grant is kept,
        /// reopen with [`open`](Self::open).
        pub async fn close(&self) -> HidResult<()> {
            // Drop any input stream so a reopen starts a fresh listener.
            *self.stream.borrow_mut() = None;
            self.backend.close().await
        }

        /// Whether the device is currently open (`HIDDevice.opened`).
        pub fn opened(&self) -> bool {
            self.backend.opened()
        }

        /// Revoke the user's permission grant for this device
        /// (`HIDDevice.forget`).
        pub async fn forget(&self) -> HidResult<()> {
            self.backend.forget().await
        }

        /// Invoke `f` with `(report_id, payload)` for every incoming input
        /// report (the `inputreport` event). Drop the returned handle to
        /// unregister.
        pub fn on_input_report(&self, f: impl FnMut(u8, Vec<u8>) + 'static) -> EventListenerHandle {
            self.backend.on_input_report(f)
        }

        /// Start an independent buffered input-report stream. Most callers
        /// should use [`read`](Self::read) instead; this is exposed for the
        /// `WebHID` streaming idiom.
        pub fn start_reading(&self) -> InputReportStream {
            self.backend.start_reading()
        }

        /// The collection tree the browser parsed from the device's report
        /// descriptor (`HIDDevice.collections`).
        pub fn collections(&self) -> Vec<CollectionInfo> {
            self.backend.collections()
        }

        /// The underlying `HIDDevice` object (`WebHID` escape hatch).
        pub fn raw(&self) -> &web_sys::HidDevice {
            self.backend.raw()
        }
    }
}