kernel/device/char/
mod.rs1use core::any::Any;
2
3use super::Device;
4
5extern crate alloc;
6
7pub trait CharDevice: Device {
13 fn read_byte(&self) -> Option<u8>;
22
23 fn write_byte(&self, byte: u8) -> Result<(), &'static str>;
33
34 fn read(&self, buffer: &mut [u8]) -> usize {
44 let mut bytes_read = 0;
45 for i in 0..buffer.len() {
46 if let Some(byte) = self.read_byte() {
47 buffer[i] = byte;
48 bytes_read += 1;
49 } else {
50 break;
51 }
52 }
53 bytes_read
54 }
55
56 fn write(&self, buffer: &[u8]) -> Result<usize, &'static str> {
66 let mut bytes_written = 0;
67 for &byte in buffer {
68 self.write_byte(byte)?;
69 bytes_written += 1;
70 }
71 Ok(bytes_written)
72 }
73
74 fn can_read(&self) -> bool;
76
77 fn can_write(&self) -> bool;
79}
80
81pub struct GenericCharDevice {
83 device_name: &'static str,
84 read_fn: fn() -> Option<u8>,
85 write_fn: fn(u8) -> Result<(), &'static str>,
86 can_read_fn: fn() -> bool,
87 can_write_fn: fn() -> bool,
88}
89
90impl GenericCharDevice {
91 pub fn new(
92 device_name: &'static str,
93 read_fn: fn() -> Option<u8>,
94 write_fn: fn(u8) -> Result<(), &'static str>,
95 can_read_fn: fn() -> bool,
96 can_write_fn: fn() -> bool,
97 ) -> Self {
98 Self {
99 device_name,
100 read_fn,
101 write_fn,
102 can_read_fn,
103 can_write_fn,
104 }
105 }
106}
107
108impl Device for GenericCharDevice {
109 fn device_type(&self) -> super::DeviceType {
110 super::DeviceType::Char
111 }
112
113 fn name(&self) -> &'static str {
114 self.device_name
115 }
116
117 fn as_any(&self) -> &dyn Any {
118 self
119 }
120
121 fn as_any_mut(&mut self) -> &mut dyn Any {
122 self
123 }
124
125 fn as_char_device(&self) -> Option<&dyn CharDevice> {
126 Some(self)
127 }
128}
129
130impl CharDevice for GenericCharDevice {
131 fn read_byte(&self) -> Option<u8> {
132 (self.read_fn)()
133 }
134
135 fn write_byte(&self, byte: u8) -> Result<(), &'static str> {
136 (self.write_fn)(byte)
137 }
138
139 fn can_read(&self) -> bool {
140 (self.can_read_fn)()
141 }
142
143 fn can_write(&self) -> bool {
144 (self.can_write_fn)()
145 }
146}
147
148#[cfg(test)]
149mod tests;
150
151#[cfg(test)]
152pub mod mockchar;
153
154pub mod tty;