Skip to content

Instantly share code, notes, and snippets.

@Restioson Restioson/hackish_solution_trimmed.rs Secret
Last active Dec 31, 2017

Embed
What would you like to do?
/// A PS2 device
pub trait Device: DeviceHelper {
fn port(&self) -> DevicePort;
// Example of a method using the helper method
fn enable_scanning(&self) -> Result<(), Ps2Error> {
self.command(DeviceCommand::EnableScanning as u8)
}
// Example of method needing to be called by helper trait
fn state(&self) -> Result<DeviceState, Ps2Error> {
// *Snip*
}
}
/// Helper trait for devices which allows sending commands to be private
trait DeviceHelper {
fn state_helper(&self) -> Result<DeviceState, Ps2Error>;
// Example of helper method needing to be called by actual trait, and also needing
// to call actual trait's method
fn command(&self, cmd: u8) -> Result<(), Ps2Error> {
if self.state_helper()? != DeviceState::Enabled {
return Err(Ps2Error::DeviceDisabled)
}
// If second PS2 port, send context switch command
if self.port_helper() == DevicePort::Two {
io::write(&STATUS_COMMAND_PORT, ControllerCommand::WriteInputPort2 as u8)?;
}
for _ in 0..4 {
io::write(&io::DEVICE_DATA_PORT, cmd)?;
match io::read(&DEVICE_DATA_PORT) {
Ok(RESEND) => continue,
Ok(ACK) => return Ok(()), // TODO check dis
Ok(unknown) => return Err(Ps2Error::UnexpectedResponse(unknown)),
Err(err) => return Err(err),
}
}
Err(Ps2Error::NoData)
}
}
impl<T: Device> DeviceHelper for T {
fn state_helper(&self) -> Result<DeviceState, Ps2Error> {
self.state()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.