cortex_m_semihosting/
hio.rsuse crate::nr;
use core::{fmt, slice};
#[derive(Clone, Copy)]
pub struct HostStream {
fd: usize,
}
impl HostStream {
pub fn write_all(&mut self, buffer: &[u8]) -> Result<(), ()> {
write_all(self.fd, buffer)
}
}
impl fmt::Write for HostStream {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write_all(s.as_bytes()).map_err(|_| fmt::Error)
}
}
pub fn hstderr() -> Result<HostStream, ()> {
open(":tt\0", nr::open::W_APPEND)
}
pub fn hstdout() -> Result<HostStream, ()> {
open(":tt\0", nr::open::W_TRUNC)
}
fn open(name: &str, mode: usize) -> Result<HostStream, ()> {
let name = name.as_bytes();
match unsafe { syscall!(OPEN, name.as_ptr(), mode, name.len() - 1) } as isize {
-1 => Err(()),
fd => Ok(HostStream { fd: fd as usize }),
}
}
fn write_all(fd: usize, mut buffer: &[u8]) -> Result<(), ()> {
while !buffer.is_empty() {
match unsafe { syscall!(WRITE, fd, buffer.as_ptr(), buffer.len()) } {
0 => return Ok(()),
n if n <= buffer.len() => {
let offset = (buffer.len() - n) as isize;
buffer = unsafe { slice::from_raw_parts(buffer.as_ptr().offset(offset), n) }
}
#[cfg(feature = "jlink-quirks")]
n if n > 0xfffffff0 => return Ok(()),
_ => return Err(()),
}
}
Ok(())
}