Skip to content

Commit

Permalink
rust: Add method to make a pair of unix channels
Browse files Browse the repository at this point in the history
Signed-off-by: Siddharth Chandrasekaran <[email protected]>
  • Loading branch information
sidcha committed Jan 6, 2024
1 parent 62d557a commit f50ea0b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
3 changes: 3 additions & 0 deletions rust/src/channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ pub trait Read {
/// Wrapper around either [`std::io::Read::read`] or [`embedded_io::Read::read`] depending on the availability of `std`.
fn read(&mut self, buf: &mut [u8]) -> Result<usize, RWError>;
}

/// A trait for objects which are byte-oriented sinks.
///
/// Wrapper around either [`std::io::Write`] or [`embedded_io::Write`] depending on the availability of `std`.
Expand All @@ -116,6 +117,7 @@ impl<T: std::io::Read> Read for T {
self.read(buf)
}
}

#[cfg(feature = "std")]
impl<T: std::io::Write> Write for T {
#[inline(always)]
Expand All @@ -139,6 +141,7 @@ where
.map_err(|e| Box::new(e) as Box<dyn embedded_io::Error>)
}
}

#[cfg(not(feature = "std"))]
impl<T: embedded_io::Write> Write for T
where
Expand Down
15 changes: 15 additions & 0 deletions rust/src/channel/unix_channel.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
//! OSDP unix channel

use super::Channel;
use core::time::Duration;
use std::{
io::{Read, Write},
os::unix::net::{UnixListener, UnixStream},
path::PathBuf,
str::FromStr,
thread,
};

type Result<T> = std::result::Result<T, crate::OsdpError>;
Expand Down Expand Up @@ -39,6 +41,19 @@ impl UnixChannel {
let (stream, _) = listener.accept()?;
Ok(Self { id, stream })
}

/// Create a bi-directional channel pair. Returns Result<(server, client)>
pub fn pair(name: &str) -> Result<(Self, Self)> {
let name_clone = String::from_str(name)?;
let h = thread::spawn(|| {
let name = name_clone;
UnixChannel::new(&name)
});
thread::sleep(Duration::from_secs(1));
let client = UnixChannel::connect(name)?;
let server = h.join().unwrap()?;
Ok((server, client))
}
}

impl Read for UnixChannel {
Expand Down

0 comments on commit f50ea0b

Please sign in to comment.