format xous-ipc

This commit is contained in:
bunnie 2024-01-14 23:09:37 +08:00
parent 8ca1ee9bc2
commit 34da894173
2 changed files with 37 additions and 84 deletions

View file

@ -2,8 +2,8 @@ use core::convert::TryInto;
use rkyv::{ser::Serializer, Fallible};
use xous::{
map_memory, send_message, unmap_memory, Error, MemoryAddress, MemoryFlags, MemoryMessage,
MemoryRange, MemorySize, Message, Result, CID,
map_memory, send_message, unmap_memory, Error, MemoryAddress, MemoryFlags, MemoryMessage, MemoryRange,
MemorySize, Message, Result, CID,
};
#[derive(Debug)]
@ -29,11 +29,7 @@ impl rkyv::Fallible for XousDeserializer {
impl<'a> Buffer<'a> {
#[allow(dead_code)]
pub fn new(len: usize) -> Self {
let remainder = if ((len & 0xFFF) == 0) && (len > 0) {
0
} else {
0x1000 - (len & 0xFFF)
};
let remainder = if ((len & 0xFFF) == 0) && (len > 0) { 0 } else { 0x1000 - (len & 0xFFF) };
let flags = MemoryFlags::R | MemoryFlags::W;
@ -47,13 +43,10 @@ impl<'a> Buffer<'a> {
)
.expect("Buffer: error in new()/map_memory");
let valid =
unsafe { MemoryRange::new(new_mem.as_mut_ptr() as usize, len + remainder).unwrap() };
let valid = unsafe { MemoryRange::new(new_mem.as_mut_ptr() as usize, len + remainder).unwrap() };
Buffer {
range: new_mem,
slice: unsafe {
core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), len + remainder)
},
slice: unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), len + remainder) },
valid,
offset: None,
should_drop: true,
@ -76,29 +69,23 @@ impl<'a> Buffer<'a> {
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
// use to serialize a buffer between process-local threads. mainly for spawning new threads with more complex argument structures.
// use to serialize a buffer between process-local threads. mainly for spawning new threads with more
// complex argument structures.
#[allow(dead_code)]
pub unsafe fn to_raw_parts(&self) -> (usize, usize, usize) {
if let Some(offset) = self.offset {
(
self.valid.as_ptr() as usize,
self.valid.len(),
usize::from(offset),
)
(self.valid.as_ptr() as usize, self.valid.len(), usize::from(offset))
} else {
(self.valid.as_ptr() as usize, self.valid.len(), 0)
}
}
// use to serialize a buffer between process-local threads. mainly for spawning new threads with more complex argument structures.
// use to serialize a buffer between process-local threads. mainly for spawning new threads with more
// complex argument structures.
#[allow(dead_code)]
pub unsafe fn from_raw_parts(address: usize, len: usize, offset: usize) -> Self {
let mem = MemoryRange::new(address, len).expect("invalid memory range args");
let off = if offset != 0 {
Some(offset.try_into().unwrap())
} else {
None
};
let off = if offset != 0 { Some(offset.try_into().unwrap()) } else { None };
Buffer {
range: mem,
slice: core::slice::from_raw_parts_mut(mem.as_mut_ptr(), mem.len()),
@ -238,7 +225,8 @@ impl<'a> Buffer<'a> {
Ok(())
}
/// Zero-copy representation of the data on the receiving side, wrapped in an "Archived" trait and left in the heap. Cheap so uses "as_" prefix.
/// Zero-copy representation of the data on the receiving side, wrapped in an "Archived" trait and left in
/// the heap. Cheap so uses "as_" prefix.
#[allow(dead_code)]
pub fn as_flat<T, U>(&self) -> core::result::Result<&U, ()>
where
@ -249,7 +237,8 @@ impl<'a> Buffer<'a> {
Ok(r)
}
/// A representation identical to the original, but reequires copying to the stack. More expensive so uses "to_" prefix.
/// A representation identical to the original, but reequires copying to the stack. More expensive so uses
/// "to_" prefix.
#[allow(dead_code)]
pub fn to_original<T, U>(&self) -> core::result::Result<T, ()>
where
@ -263,29 +252,21 @@ impl<'a> Buffer<'a> {
}
impl<'a> core::convert::AsRef<[u8]> for Buffer<'a> {
fn as_ref(&self) -> &[u8] {
self.slice
}
fn as_ref(&self) -> &[u8] { self.slice }
}
impl<'a> core::convert::AsMut<[u8]> for Buffer<'a> {
fn as_mut(&mut self) -> &mut [u8] {
self.slice
}
fn as_mut(&mut self) -> &mut [u8] { self.slice }
}
impl<'a> core::ops::Deref for Buffer<'a> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&*self.slice
}
fn deref(&self) -> &Self::Target { &*self.slice }
}
impl<'a> core::ops::DerefMut for Buffer<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *self.slice
}
fn deref_mut(&mut self) -> &mut Self::Target { &mut *self.slice }
}
impl<'a> Drop for Buffer<'a> {

View file

@ -1,10 +1,10 @@
use xous::{Error, MemoryMessage, Result, CID};
use core::pin::Pin;
use rkyv::archived_value;
use rkyv::ser::Serializer;
use rkyv::ArchiveUnsized;
use rkyv::SerializeUnsized;
use xous::{Error, MemoryMessage, Result, CID};
#[derive(Copy, Clone)]
pub struct String<const N: usize> {
@ -13,12 +13,7 @@ pub struct String<const N: usize> {
}
impl<const N: usize> String<N> {
pub fn new() -> String<N> {
String {
bytes: [0; N],
len: 0,
}
}
pub fn new() -> String<N> { String { bytes: [0; N], len: 0 } }
// use a volatile write to ensure a clear operation is not optimized out
// for ensuring that a string is cleared, e.g. at the exit of a function
@ -30,9 +25,9 @@ impl<const N: usize> String<N> {
}
}
self.len = 0; // also set my length to 0
// Ensure the compiler doesn't re-order the clear.
// We use `SeqCst`, because `Acquire` only prevents later accesses from being reordered before
// *reads*, but this method only *writes* to the locations.
// Ensure the compiler doesn't re-order the clear.
// We use `SeqCst`, because `Acquire` only prevents later accesses from being reordered before
// *reads*, but this method only *writes* to the locations.
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
@ -58,26 +53,18 @@ impl<const N: usize> String<N> {
s
}
pub fn as_bytes(&self) -> [u8; N] {
self.bytes
}
pub fn as_bytes(&self) -> [u8; N] { self.bytes }
pub fn as_str(&self) -> core::result::Result<&str, core::str::Utf8Error> {
core::str::from_utf8(&self.bytes[0..self.len as usize])
}
pub fn len(&self) -> usize {
self.len as usize
}
pub fn len(&self) -> usize { self.len as usize }
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn is_empty(&self) -> bool { self.len == 0 }
/// Convert a `MemoryMessage` into a `String`
pub fn from_message(
message: &MemoryMessage,
) -> core::result::Result<String<N>, core::str::Utf8Error> {
pub fn from_message(message: &MemoryMessage) -> core::result::Result<String<N>, core::str::Utf8Error> {
let buf = unsafe { crate::Buffer::from_memory_message(message) };
let bytes = Pin::new(buf.as_ref());
let value = unsafe { archived_value::<String<N>>(&bytes, message.id as usize) };
@ -98,9 +85,7 @@ impl<const N: usize> String<N> {
// id: crate::MessageId,
) -> core::result::Result<Result, Error> {
let mut writer = rkyv::ser::serializers::BufferSerializer::new(crate::Buffer::new(N));
let pos = writer
.serialize_value(self)
.expect("xous::String -- couldn't archive self");
let pos = writer.serialize_value(self).expect("xous::String -- couldn't archive self");
let xous_buffer = writer.into_inner();
// note that "id" is actually used as the position into the rkyv buffer
@ -114,9 +99,7 @@ impl<const N: usize> String<N> {
// id: crate::MessageId,
) -> core::result::Result<Result, Error> {
let mut writer = rkyv::ser::serializers::BufferSerializer::new(crate::Buffer::new(N));
let pos = writer
.serialize_value(&self)
.expect("xous::String -- couldn't archive self");
let pos = writer.serialize_value(&self).expect("xous::String -- couldn't archive self");
let xous_buffer = writer.into_inner();
xous_buffer.send(connection, pos as u32)
@ -128,9 +111,7 @@ impl<const N: usize> String<N> {
self.bytes = [0; N];
}
pub fn to_str(&self) -> &str {
unsafe { core::str::from_utf8_unchecked(&self.bytes[0..self.len()]) }
}
pub fn to_str(&self) -> &str { unsafe { core::str::from_utf8_unchecked(&self.bytes[0..self.len()]) } }
/// awful, O(N) implementation because we have to iterate through the entire string
/// and decode variable-length utf8 characters, until we can't.
@ -220,15 +201,11 @@ impl<const N: usize> String<N> {
}
impl<const N: usize> Default for String<N> {
fn default() -> Self {
Self::new()
}
fn default() -> Self { Self::new() }
}
impl<const N: usize> core::fmt::Display for String<N> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.to_str())
}
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.to_str()) }
}
impl<const N: usize> core::fmt::Write for String<N> {
@ -244,21 +221,16 @@ impl<const N: usize> core::fmt::Write for String<N> {
}
impl<const N: usize> core::fmt::Debug for String<N> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.to_str())
}
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.to_str()) }
}
impl<const N: usize> core::convert::AsRef<str> for String<N> {
fn as_ref(&self) -> &str {
self.to_str()
}
fn as_ref(&self) -> &str { self.to_str() }
}
impl<const N: usize> PartialEq for String<N> {
fn eq(&self, other: &Self) -> bool {
self.bytes[..self.len as usize] == other.bytes[..other.len as usize]
&& self.len == other.len
self.bytes[..self.len as usize] == other.bytes[..other.len as usize] && self.len == other.len
}
}