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
#![forbid(future_incompatible)]
#![deny(bad_style, missing_docs)]
#![doc = include_str!("../README.md")]
use hidg_core::{check_read, check_write, open};
pub use hidg_core::{Class, Error, Result, StateChange, ValueChange};
#[cfg(feature = "keyboard")]
pub use hidg_core::{
Key, KeyStateChanges, Keyboard, KeyboardInput, KeyboardOutput, Led, LedStateChanges, Leds,
Modifiers,
};
#[cfg(feature = "mouse")]
pub use hidg_core::{
Button, Buttons, Mouse, MouseInput, MouseInputChange, MouseInputChanges, MouseOutput,
};
use core::marker::PhantomData;
use std::{
os::unix::io::{AsRawFd, RawFd},
pin::Pin,
task::{Context, Poll},
};
use async_io::Async;
use async_std::{
io::{Read, ReadExt, Write, WriteExt},
path::Path,
task::spawn_blocking as asyncify,
};
#[doc(hidden)]
pub struct File {
inner: Async<std::fs::File>,
}
impl File {
pub fn from_file(file: std::fs::File) -> Result<Self> {
Ok(Self {
inner: Async::new(file)?,
})
}
}
impl AsRawFd for File {
fn as_raw_fd(&self) -> RawFd {
self.inner.as_raw_fd()
}
}
impl Read for File {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
use std::io::Read;
match self.inner.poll_readable(cx) {
Poll::Ready(x) => x,
Poll::Pending => return Poll::Pending,
}?;
Poll::Ready(self.inner.get_ref().read(buf))
}
}
impl Write for File {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
use std::io::Write;
match self.inner.poll_writable(cx) {
Poll::Ready(x) => x,
Poll::Pending => return Poll::Pending,
}?;
Poll::Ready(self.inner.get_ref().write(buf))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
}
pub struct Device<C: Class> {
file: File,
_class: PhantomData<C>,
}
impl<C: Class> Device<C> {
pub async fn open(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref().to_owned();
let file = asyncify(move || open(path, false)).await?;
let file = File::from_file(file)?;
Ok(Self {
file,
_class: PhantomData,
})
}
pub async fn input(&mut self, input: &C::Input) -> Result<()>
where
C::Input: AsRef<[u8]>,
{
let raw = input.as_ref();
let len = self.file.write(raw).await?;
check_write(len, raw.len())
}
pub async fn output(&mut self, output: &mut C::Output) -> Result<()>
where
C::Output: AsMut<[u8]>,
{
let raw = output.as_mut();
let len = self.file.read(raw).await?;
check_read(len, raw.len())?;
Ok(())
}
}