mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-19 09:00:54 +00:00
rkyv-test-server: use xous-ipc buffer
Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
parent
fdce58d06e
commit
45239c61ef
3 changed files with 13 additions and 241 deletions
|
|
@ -1,226 +0,0 @@
|
||||||
use rkyv::{ser::Serializer, Fallible};
|
|
||||||
use xous::{
|
|
||||||
map_memory, send_message, unmap_memory, Error, MemoryAddress, MemoryFlags, MemoryMessage,
|
|
||||||
MemoryRange, MemorySize, Message, Result, CID,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Buffer<'a> {
|
|
||||||
range: MemoryRange,
|
|
||||||
valid: MemoryRange,
|
|
||||||
offset: Option<MemoryAddress>,
|
|
||||||
slice: &'a mut [u8],
|
|
||||||
should_drop: bool,
|
|
||||||
memory_message: Option<&'a mut MemoryMessage>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct XousDeserializer;
|
|
||||||
|
|
||||||
// Unreachable enum pattern, swap out for the never type (!) whenever that gets stabilized
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum XousUnreachable {}
|
|
||||||
|
|
||||||
impl rkyv::Fallible for XousDeserializer {
|
|
||||||
type Error = XousUnreachable;
|
|
||||||
}
|
|
||||||
|
|
||||||
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 flags = MemoryFlags::R | MemoryFlags::W;
|
|
||||||
|
|
||||||
// Allocate enough memory to hold the requested data
|
|
||||||
let new_mem = map_memory(
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
// Ensure our byte size is a multiple of 4096
|
|
||||||
len + remainder,
|
|
||||||
flags,
|
|
||||||
)
|
|
||||||
.expect("Buffer: error in new()/map_memory");
|
|
||||||
|
|
||||||
let mut valid = new_mem;
|
|
||||||
valid.size = MemorySize::new(len + remainder).unwrap();
|
|
||||||
Buffer {
|
|
||||||
range: new_mem,
|
|
||||||
slice: unsafe {
|
|
||||||
core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), len + remainder)
|
|
||||||
},
|
|
||||||
valid,
|
|
||||||
offset: None,
|
|
||||||
should_drop: true,
|
|
||||||
memory_message: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub unsafe fn from_memory_message(mem: &'a MemoryMessage) -> Self {
|
|
||||||
Buffer {
|
|
||||||
range: mem.buf,
|
|
||||||
slice: core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len()),
|
|
||||||
valid: mem.buf,
|
|
||||||
offset: mem.offset,
|
|
||||||
should_drop: false,
|
|
||||||
memory_message: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub unsafe fn from_memory_message_mut(mem: &'a mut MemoryMessage) -> Self {
|
|
||||||
Buffer {
|
|
||||||
range: mem.buf,
|
|
||||||
slice: core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len()),
|
|
||||||
valid: mem.buf,
|
|
||||||
offset: mem.offset,
|
|
||||||
should_drop: false,
|
|
||||||
memory_message: Some(mem),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Perform a mutable lend of this Buffer to the server.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn lend_mut(&mut self, connection: CID, id: u32) -> core::result::Result<Result, Error> {
|
|
||||||
let msg = MemoryMessage {
|
|
||||||
id: id as usize,
|
|
||||||
buf: self.valid,
|
|
||||||
offset: self.offset,
|
|
||||||
valid: MemorySize::new(self.slice.len()),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Update the offset pointer if the server modified it.
|
|
||||||
let result = send_message(connection, Message::MutableBorrow(msg));
|
|
||||||
if let Ok(Result::MemoryReturned(offset, _valid)) = result {
|
|
||||||
self.offset = offset;
|
|
||||||
}
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn lend(&self, connection: CID, id: u32) -> core::result::Result<Result, Error> {
|
|
||||||
let msg = MemoryMessage {
|
|
||||||
id: id as usize,
|
|
||||||
buf: self.valid,
|
|
||||||
offset: self.offset,
|
|
||||||
valid: MemorySize::new(self.slice.len()),
|
|
||||||
};
|
|
||||||
send_message(connection, Message::Borrow(msg))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn send(mut self, connection: CID, id: u32) -> core::result::Result<Result, Error> {
|
|
||||||
let msg = MemoryMessage {
|
|
||||||
id: id as usize,
|
|
||||||
buf: self.valid,
|
|
||||||
offset: self.offset,
|
|
||||||
valid: MemorySize::new(self.slice.len()),
|
|
||||||
};
|
|
||||||
let result = send_message(connection, Message::Move(msg))?;
|
|
||||||
|
|
||||||
// prevents it from being Dropped.
|
|
||||||
self.should_drop = false;
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn try_from<S>(src: S) -> core::result::Result<Self, ()>
|
|
||||||
where
|
|
||||||
S: rkyv::Serialize<rkyv::ser::serializers::BufferSerializer<Buffer<'a>>>,
|
|
||||||
{
|
|
||||||
let buf = Self::new(4096);
|
|
||||||
let mut ser = rkyv::ser::serializers::BufferSerializer::new(buf);
|
|
||||||
let pos = ser.serialize_value(&src).or(Err(()))?;
|
|
||||||
let mut buf = ser.into_inner();
|
|
||||||
buf.offset = MemoryAddress::new(pos);
|
|
||||||
Ok(buf)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn serialize_from<S>(&mut self, src: S) -> core::result::Result<(), &'static str>
|
|
||||||
where
|
|
||||||
S: rkyv::Serialize<rkyv::ser::serializers::BufferSerializer<&'a mut [u8]>>,
|
|
||||||
{
|
|
||||||
// We must have a `memory_message` to update in order for this to work.
|
|
||||||
// Otherwise, we risk having the pointer go to somewhere invalid.
|
|
||||||
if self.memory_message.is_none() {
|
|
||||||
// Create this message using `from_memory_message_mut()` instead of
|
|
||||||
// `from_memory_message()`.
|
|
||||||
Err("couldn't serialize because buffer wasn't mutable")?;
|
|
||||||
}
|
|
||||||
// Unsafe Warning: Create a copy of the backing slice to hand to the deserializer.
|
|
||||||
// This is required because the deserializer consumes the buffer and returns it
|
|
||||||
// later as part of `.into_inner()`.
|
|
||||||
// The "correct" way to do this would be to implement `rkyv::Serializer` an `rkyv::Fallible`
|
|
||||||
// for ourselves.
|
|
||||||
let copied_slice =
|
|
||||||
unsafe { core::slice::from_raw_parts_mut(self.slice.as_mut_ptr(), self.slice.len()) };
|
|
||||||
let mut ser = rkyv::ser::serializers::BufferSerializer::new(copied_slice);
|
|
||||||
let pos = ser.serialize_value(&src).or(Err("couldn't serialize"))?;
|
|
||||||
self.offset = MemoryAddress::new(pos);
|
|
||||||
if let Some(ref mut msg) = self.memory_message.as_mut() {
|
|
||||||
msg.offset = MemoryAddress::new(pos);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn try_into<T, U>(&self) -> core::result::Result<&U, ()>
|
|
||||||
where
|
|
||||||
T: rkyv::Archive<Archived = U>,
|
|
||||||
{
|
|
||||||
let pos = self.offset.map(|o| o.get()).unwrap_or_default();
|
|
||||||
let r = unsafe { rkyv::archived_value::<T>(self.slice, pos) };
|
|
||||||
Ok(r)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn deserialize<T, U>(&self) -> core::result::Result<T, ()>
|
|
||||||
where
|
|
||||||
T: rkyv::Archive<Archived = U>,
|
|
||||||
U: rkyv::Deserialize<T, dyn Fallible<Error = XousUnreachable>>,
|
|
||||||
{
|
|
||||||
let pos = self.offset.map(|o| o.get()).unwrap_or_default();
|
|
||||||
let r = unsafe { rkyv::archived_value::<T>(self.slice, pos) };
|
|
||||||
Ok(r.deserialize(&mut XousDeserializer {}).unwrap())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> core::convert::AsRef<[u8]> for Buffer<'a> {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> core::ops::Deref for Buffer<'a> {
|
|
||||||
type Target = [u8];
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Drop for Buffer<'a> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if self.should_drop {
|
|
||||||
unmap_memory(self.range).expect("Buffer: failed to drop memory");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,12 +1,11 @@
|
||||||
#![cfg_attr(target_os = "none", no_std)]
|
#![cfg_attr(target_os = "none", no_std)]
|
||||||
|
|
||||||
mod api;
|
mod api;
|
||||||
mod buffer;
|
|
||||||
|
|
||||||
use core::sync::atomic::{AtomicU32, Ordering};
|
use core::sync::atomic::{AtomicU32, Ordering};
|
||||||
use num_traits::{FromPrimitive, ToPrimitive};
|
use num_traits::{FromPrimitive, ToPrimitive};
|
||||||
|
|
||||||
use xous_ipc::String;
|
use xous_ipc::{String, Buffer};
|
||||||
|
|
||||||
// Note that connection IDs are never 0, so this is invalid, and could map to `None`.
|
// Note that connection IDs are never 0, so this is invalid, and could map to `None`.
|
||||||
static SERVER_CID: AtomicU32 = AtomicU32::new(0);
|
static SERVER_CID: AtomicU32 = AtomicU32::new(0);
|
||||||
|
|
@ -31,7 +30,7 @@ pub fn add(arg1: i32, arg2: i32) -> Result<i32, api::Error> {
|
||||||
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
||||||
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
||||||
// suitable for passing around as a message.
|
// suitable for passing around as a message.
|
||||||
let mut buf = buffer::Buffer::try_from(op).or(Err(api::Error::InternalError))?;
|
let mut buf = Buffer::try_from(op).or(Err(api::Error::InternalError))?;
|
||||||
|
|
||||||
// Mutably lend our op to the server, specifying the `api::Opcode::Mathematics` opcode.
|
// Mutably lend our op to the server, specifying the `api::Opcode::Mathematics` opcode.
|
||||||
// This will return a structure that we can deserialize back into something we
|
// This will return a structure that we can deserialize back into something we
|
||||||
|
|
@ -55,7 +54,7 @@ fn do_op(op: api::MathOperation) -> Result<i32, api::Error> {
|
||||||
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
||||||
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
||||||
// suitable for passing around as a message.
|
// suitable for passing around as a message.
|
||||||
let mut buf = buffer::Buffer::try_from(op).or(Err(api::Error::InternalError))?;
|
let mut buf = Buffer::try_from(op).or(Err(api::Error::InternalError))?;
|
||||||
|
|
||||||
// Lend our op to the server, specifying the `api::Opcode::Mathematics` opcode.
|
// Lend our op to the server, specifying the `api::Opcode::Mathematics` opcode.
|
||||||
// This will return a structure that we can deserialize back into something we
|
// This will return a structure that we can deserialize back into something we
|
||||||
|
|
@ -98,7 +97,7 @@ pub fn log_message<S: AsRef<str>, T: AsRef<str>>(prefix: S, message: T) {
|
||||||
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
||||||
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
||||||
// suitable for passing around as a message.
|
// suitable for passing around as a message.
|
||||||
let buf = buffer::Buffer::try_from(op).unwrap();
|
let buf = Buffer::try_from(op).unwrap();
|
||||||
|
|
||||||
// Send the message to the server.
|
// Send the message to the server.
|
||||||
buf.lend(
|
buf.lend(
|
||||||
|
|
@ -119,7 +118,7 @@ pub fn log_message_send<S: AsRef<str>, T: AsRef<str>>(prefix: S, message: T) {
|
||||||
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
||||||
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
||||||
// suitable for passing around as a message.
|
// suitable for passing around as a message.
|
||||||
let buf = buffer::Buffer::try_from(op).unwrap();
|
let buf = Buffer::try_from(op).unwrap();
|
||||||
|
|
||||||
// Send the message to the server.
|
// Send the message to the server.
|
||||||
buf.send(
|
buf.send(
|
||||||
|
|
@ -142,7 +141,7 @@ fn callback_server() {
|
||||||
match FromPrimitive::from_usize(msg.body.id()) {
|
match FromPrimitive::from_usize(msg.body.id()) {
|
||||||
Some(api::CallbackType::LogString) => {
|
Some(api::CallbackType::LogString) => {
|
||||||
let mem = msg.body.memory_message().unwrap();
|
let mem = msg.body.memory_message().unwrap();
|
||||||
let buffer = unsafe { buffer::Buffer::from_memory_message(mem) };
|
let buffer = unsafe { Buffer::from_memory_message(mem) };
|
||||||
let log_string = buffer.try_into::<api::LogString, _>().unwrap();
|
let log_string = buffer.try_into::<api::LogString, _>().unwrap();
|
||||||
unsafe {
|
unsafe {
|
||||||
for entry in CALLBACK_ARRAY.iter() {
|
for entry in CALLBACK_ARRAY.iter() {
|
||||||
|
|
@ -197,7 +196,7 @@ pub fn double_string<T>(value: &T) -> String<512> where T: AsRef<str> {
|
||||||
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
// Convert the opcode into a serialized buffer. This consumes the opcode, which will
|
||||||
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
// exist on the heap in its own page. Furthermore, this will be in a flattened format
|
||||||
// suitable for passing around as a message.
|
// suitable for passing around as a message.
|
||||||
let mut buf = buffer::Buffer::try_from(op).unwrap();
|
let mut buf = Buffer::try_from(op).unwrap();
|
||||||
|
|
||||||
// Send the message to the server.
|
// Send the message to the server.
|
||||||
buf.lend_mut(
|
buf.lend_mut(
|
||||||
|
|
|
||||||
|
|
@ -2,16 +2,15 @@
|
||||||
#![cfg_attr(target_os = "none", no_main)]
|
#![cfg_attr(target_os = "none", no_main)]
|
||||||
|
|
||||||
mod api;
|
mod api;
|
||||||
mod buffer;
|
|
||||||
use num_traits::{FromPrimitive, ToPrimitive};
|
use num_traits::{FromPrimitive, ToPrimitive};
|
||||||
use xous_ipc::String;
|
use xous_ipc::{String, Buffer};
|
||||||
|
|
||||||
fn value_or(val: Option<i32>, default: api::MathResult) -> api::MathResult {
|
fn value_or(val: Option<i32>, default: api::MathResult) -> api::MathResult {
|
||||||
val.map(|v| api::MathResult::Value(v)).unwrap_or(default)
|
val.map(|v| api::MathResult::Value(v)).unwrap_or(default)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_math_withcopy(mem: &mut xous::MemoryMessage) {
|
fn handle_math_withcopy(mem: &mut xous::MemoryMessage) {
|
||||||
let mut buffer = unsafe { buffer::Buffer::from_memory_message_mut(mem) };
|
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
|
||||||
let response = {
|
let response = {
|
||||||
use api::MathOperation::*;
|
use api::MathOperation::*;
|
||||||
match buffer.deserialize().unwrap() {
|
match buffer.deserialize().unwrap() {
|
||||||
|
|
@ -39,7 +38,7 @@ fn handle_math_withcopy(mem: &mut xous::MemoryMessage) {
|
||||||
// This doesn't deserialize the struct, and therefore operates entirely
|
// This doesn't deserialize the struct, and therefore operates entirely
|
||||||
// on the archived data. This saves a copy step.
|
// on the archived data. This saves a copy step.
|
||||||
fn handle_math_zerocopy(mem: &mut xous::MemoryMessage) {
|
fn handle_math_zerocopy(mem: &mut xous::MemoryMessage) {
|
||||||
let mut buffer = unsafe { buffer::Buffer::from_memory_message_mut(mem) };
|
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
|
||||||
let response = {
|
let response = {
|
||||||
use api::ArchivedMathOperation::*;
|
use api::ArchivedMathOperation::*;
|
||||||
match *buffer.try_into::<api::MathOperation, _>().unwrap() {
|
match *buffer.try_into::<api::MathOperation, _>().unwrap() {
|
||||||
|
|
@ -65,7 +64,7 @@ fn handle_math_zerocopy(mem: &mut xous::MemoryMessage) {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_log_string(mem: &xous::MemoryMessage) {
|
fn handle_log_string(mem: &xous::MemoryMessage) {
|
||||||
let buffer = unsafe { buffer::Buffer::from_memory_message(mem) };
|
let buffer = unsafe { Buffer::from_memory_message(mem) };
|
||||||
let log_string = buffer.try_into::<api::LogString, _>().unwrap();
|
let log_string = buffer.try_into::<api::LogString, _>().unwrap();
|
||||||
log::info!(
|
log::info!(
|
||||||
"Prefix: {} Message: {}",
|
"Prefix: {} Message: {}",
|
||||||
|
|
@ -77,7 +76,7 @@ fn handle_log_string(mem: &xous::MemoryMessage) {
|
||||||
/// Take the given string and double each character in an output string.
|
/// Take the given string and double each character in an output string.
|
||||||
fn double_string(mem: &mut xous::MemoryMessage) {
|
fn double_string(mem: &mut xous::MemoryMessage) {
|
||||||
use core::fmt::Write;
|
use core::fmt::Write;
|
||||||
let mut buffer = unsafe { buffer::Buffer::from_memory_message_mut(mem) };
|
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
|
||||||
let mut response = api::StringDoubler {
|
let mut response = api::StringDoubler {
|
||||||
value: String::new(),
|
value: String::new(),
|
||||||
};
|
};
|
||||||
|
|
@ -119,7 +118,7 @@ fn test_main() -> ! {
|
||||||
// If a callback exists, first pass this message to the callback server.
|
// If a callback exists, first pass this message to the callback server.
|
||||||
for callback_conn in logstring_callback_connections.iter() {
|
for callback_conn in logstring_callback_connections.iter() {
|
||||||
if let Some(callback_sid) = callback_conn {
|
if let Some(callback_sid) = callback_conn {
|
||||||
let buffer = unsafe { buffer::Buffer::from_memory_message(memory) };
|
let buffer = unsafe { Buffer::from_memory_message(memory) };
|
||||||
buffer
|
buffer
|
||||||
.lend(
|
.lend(
|
||||||
*callback_sid,
|
*callback_sid,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue