Skip to main content

Peer

Trait Peer 

Source
pub trait Peer: Send {
    // Required method
    fn receive(&mut self, bytes: &[u8]) -> Vec<u8> ⓘ;
}
Expand description

A device at the far end of a simulated serial line.

Every write to a SerialPort::simulated port reaches Peer::receive, and whatever it returns is what the device sends back, waiting for the next read. A program that wants to look at the device afterward shares it: Arc<Mutex<P>> is a peer whenever P is.

§Examples

use std::sync::{Arc, Mutex};
use std::time::Duration;

use pamoja_hal::port::{Peer, SerialPort, Settings};

/// A device that answers every write with the same bytes, upper-cased.
#[derive(Default)]
struct Shouter {
    heard: usize,
}

impl Peer for Shouter {
    fn receive(&mut self, bytes: &[u8]) -> Vec<u8> {
        self.heard += bytes.len();
        bytes.to_ascii_uppercase()
    }
}

let device = Arc::new(Mutex::new(Shouter::default()));
let port = SerialPort::simulated(Settings::new(9_600), Arc::clone(&device));
port.write(b"ping")?;

let mut reply = [0u8; 8];
let got = port.read(&mut reply, Duration::from_millis(50))?;
assert_eq!(&reply[..got], b"PING");
assert_eq!(device.lock().unwrap().heard, 4);

Required Methods§

Source

fn receive(&mut self, bytes: &[u8]) -> Vec<u8> ⓘ

Takes the bytes the port wrote and returns the bytes the device sends back.

§Arguments
  • bytes - one write’s bytes.
§Returns

The device’s answer, empty when it says nothing.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<P: Peer> Peer for Arc<Mutex<P>>

Source§

fn receive(&mut self, bytes: &[u8]) -> Vec<u8> ⓘ

Implementors§