use core::{fmt, ptr, slice};
use crate::peripheral::itm::Stim;
unsafe fn write_words(stim: &mut Stim, bytes: &[u32]) {
let mut p = bytes.as_ptr();
for _ in 0..bytes.len() {
while !stim.is_fifo_ready() {}
stim.write_u32(ptr::read(p));
p = p.offset(1);
}
}
unsafe fn write_aligned_impl(port: &mut Stim, buffer: &[u8]) {
let len = buffer.len();
if len == 0 {
return;
}
let split = len & !0b11;
#[allow(clippy::cast_ptr_alignment)]
write_words(
port,
slice::from_raw_parts(buffer.as_ptr() as *const u32, split >> 2),
);
let mut left = len & 0b11;
let mut ptr = buffer.as_ptr().add(split);
if left > 1 {
while !port.is_fifo_ready() {}
#[allow(clippy::cast_ptr_alignment)]
port.write_u16(ptr::read(ptr as *const u16));
ptr = ptr.offset(2);
left -= 2;
}
if left == 1 {
while !port.is_fifo_ready() {}
port.write_u8(*ptr);
}
}
struct Port<'p>(&'p mut Stim);
impl<'p> fmt::Write for Port<'p> {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
write_all(self.0, s.as_bytes());
Ok(())
}
}
#[repr(align(4))]
pub struct Aligned<T: ?Sized>(pub T);
#[allow(clippy::missing_inline_in_public_items)]
pub fn write_all(port: &mut Stim, buffer: &[u8]) {
unsafe {
let mut len = buffer.len();
let mut ptr = buffer.as_ptr();
if len == 0 {
return;
}
if ptr as usize % 2 == 1 {
while !port.is_fifo_ready() {}
port.write_u8(*ptr);
ptr = ptr.offset(1);
len -= 1;
}
if ptr as usize % 4 == 2 {
if len > 1 {
while !port.is_fifo_ready() {}
#[allow(clippy::cast_ptr_alignment)]
port.write_u16(ptr::read(ptr as *const u16));
ptr = ptr.offset(2);
len -= 2;
} else {
if len == 1 {
while !port.is_fifo_ready() {}
port.write_u8(*ptr);
}
return;
}
}
write_aligned_impl(port, slice::from_raw_parts(ptr, len));
}
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn write_aligned(port: &mut Stim, buffer: &Aligned<[u8]>) {
unsafe { write_aligned_impl(port, &buffer.0) }
}
#[inline]
pub fn write_fmt(port: &mut Stim, args: fmt::Arguments) {
use core::fmt::Write;
Port(port).write_fmt(args).ok();
}
#[inline]
pub fn write_str(port: &mut Stim, string: &str) {
write_all(port, string.as_bytes())
}