remove mention of Sendable and the ipc.rs module

This commit is contained in:
bunnie 2021-02-18 02:01:11 +08:00
parent 0af72ffb6d
commit c5e6391e22
18 changed files with 125 additions and 359 deletions

3
Cargo.lock generated
View file

@ -70,6 +70,7 @@ dependencies = [
"graphics-server", "graphics-server",
"log", "log",
"log-server", "log-server",
"rkyv",
"ticktimer-server", "ticktimer-server",
"utralib", "utralib",
"xous", "xous",
@ -82,6 +83,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"log", "log",
"log-server", "log-server",
"rkyv",
"utralib", "utralib",
"xous", "xous",
"xous-names", "xous-names",
@ -390,6 +392,7 @@ dependencies = [
"keyboard", "keyboard",
"log", "log",
"log-server", "log-server",
"rkyv",
"ticktimer-server", "ticktimer-server",
"trng", "trng",
"utralib", "utralib",

View file

@ -7,6 +7,7 @@ description = "Benchmark target for Xous"
[dependencies] [dependencies]
xous = { path = "../../xous-rs" } xous = { path = "../../xous-rs" }
rkyv = { version = "0.3.1", default_features = false }
xous-names = { path = "../xous-names" } xous-names = { path = "../xous-names" }
log-server = { path = "../log-server" } log-server = { path = "../log-server" }
log = "0.4" log = "0.4"

View file

@ -1,7 +1,6 @@
use xous::{Message, ScalarMessage}; use xous::{Message, ScalarMessage};
#[repr(C)] #[derive(Debug, rkyv::Archive, rkyv::Unarchive)]
#[derive(Debug)]
pub struct TestStruct { pub struct TestStruct {
pub challenge: [u32; 8], pub challenge: [u32; 8],
} }
@ -14,7 +13,7 @@ impl TestStruct {
} }
#[allow(dead_code)] #[allow(dead_code)]
#[derive(Debug)] #[derive(Debug, rkyv::Archive, rkyv::Unarchive)]
pub enum Opcode { pub enum Opcode {
TestScalar(u32), TestScalar(u32),
TestMemory(TestStruct), TestMemory(TestStruct),

View file

@ -4,7 +4,6 @@ pub mod api;
use api::*; use api::*;
use xous::{CID, send_message}; use xous::{CID, send_message};
use xous::ipc::Sendable;
pub fn test_scalar(cid: CID, testvar: u32) -> Result<u32, xous::Error> { pub fn test_scalar(cid: CID, testvar: u32) -> Result<u32, xous::Error> {
let response = send_message(cid, api::Opcode::TestScalar(testvar).into())?; let response = send_message(cid, api::Opcode::TestScalar(testvar).into())?;
@ -16,9 +15,22 @@ pub fn test_scalar(cid: CID, testvar: u32) -> Result<u32, xous::Error> {
} }
pub fn test_memory(cid: CID, testvar: u32) -> Result<u32, xous::Error> { pub fn test_memory(cid: CID, testvar: u32) -> Result<u32, xous::Error> {
let reg = TestStruct::new(); use rkyv::Write;
let mut sendable_reg = Sendable::new(reg).expect("can't create test structure"); let mut reg = TestStruct::new();
sendable_reg.challenge[0] = testvar; reg.challenge[0] = testvar;
sendable_reg.lend_mut(cid, 0).expect("test failure");
Ok(sendable_reg.challenge[0]) let reg_opcode = api::Opcode::TestMemory(reg);
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&reg_opcode).expect("couldn't archive test structure");
let mut xous_buffer = writer.into_inner();
xous_buffer.lend_mut(cid, pos as u32).expect("test failure");
let archived = unsafe {rkyv::archived_value::<api::Opcode>(xous_buffer.as_ref(), pos) };
match archived {
rkyv::Archived::<api::Opcode>::TestMemory(result) => {
Ok(result.challenge[0])
},
_ => panic!("mutable lend did not return a recognizable value")
}
} }

View file

@ -8,6 +8,11 @@ use core::convert::TryFrom;
use log::{error, info}; use log::{error, info};
use rkyv::archived_value_mut;
use core::pin::Pin;
use core::convert::TryInto;
use rkyv::Unarchive;
#[xous::xous_main] #[xous::xous_main]
fn xmain() -> ! { fn xmain() -> ! {
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
@ -27,9 +32,24 @@ fn xmain() -> ! {
_ => error!("BENCHTARGET: opcode not yet implemented"), _ => error!("BENCHTARGET: opcode not yet implemented"),
} }
} else if let xous::Message::MutableBorrow(m) = &envelope.body { } else if let xous::Message::MutableBorrow(m) = &envelope.body {
//let lookup: &mut Lookup = unsafe { &mut *(m.buf.as_mut_ptr() as *mut Lookup) }; let mut buf = unsafe { xous::XousBuffer::from_memory_message(m) };
let lookup: &mut TestStruct = unsafe { &mut *(m.buf.as_mut_ptr() as *mut TestStruct) }; let value = unsafe {
lookup.challenge[0] = lookup.challenge[0] + 1; archived_value_mut::<api::Opcode>(Pin::new(buf.as_mut()), m.id.try_into().unwrap())
};
match &*value {
rkyv::Archived::<api::Opcode>::TestMemory(reg) => {
use rkyv::Write;
let mut ret = TestStruct::new();
ret.challenge[0] = reg.challenge[0] + 1;
let retop = Opcode::TestMemory(ret);
let mut writer = rkyv::ArchiveBuffer::new(buf);
let pos = writer.archive(&retop).expect("couldn't archive return value");
unsafe{ rkyv::archived_value::<api::Opcode>(writer.into_inner().as_ref(), pos) };
}
_ => panic!("Invalid response from server -- corruption occurred"),
};
} else { } else {
error!("BENCHTARGET: couldn't convert opcode"); error!("BENCHTARGET: couldn't convert opcode");
} }

View file

@ -7,6 +7,7 @@ description = "Benchmarks for Xous"
[dependencies] [dependencies]
xous = { path = "../../xous-rs" } xous = { path = "../../xous-rs" }
rkyv = { version = "0.3.1", default_features = false }
graphics-server = { path = "../graphics-server" } graphics-server = { path = "../graphics-server" }
ticktimer-server = { path = "../ticktimer-server" } ticktimer-server = { path = "../ticktimer-server" }
xous-names = { path = "../xous-names" } xous-names = { path = "../xous-names" }

View file

@ -106,7 +106,7 @@ fn shell_main() -> ! {
let screensize = graphics_server::screen_size(graphics_conn).expect("Couldn't get screen size"); let screensize = graphics_server::screen_size(graphics_conn).expect("Couldn't get screen size");
let mut string_buffer = String::new(4096); let mut string_buffer = String::<4096>::new();
graphics_server::set_glyph_style(graphics_conn, GlyphStyle::Small) graphics_server::set_glyph_style(graphics_conn, GlyphStyle::Small)
.expect("unable to set glyph"); .expect("unable to set glyph");
@ -154,12 +154,12 @@ fn shell_main() -> ! {
// actual benchmark // actual benchmark
// get a scalar message // get a scalar message
if false { if false {
// measured at 1349 iterations per second in this loop (hardware); 55/s (hosted) // measured at 1479.2 iterations per second in this loop (hardware); 55/s (hosted)
count = benchmark_target::test_scalar(target_conn, count).expect("BENCHMARK: couldn't send test message"); count = benchmark_target::test_scalar(target_conn, count).expect("BENCHMARK: couldn't send test message");
check_count = check_count + 1; check_count = check_count + 1;
} else { } else {
// works on hosted mode, 35/s (hosted) // works on hosted mode, 35/s (hosted)
// does *not* work on hardware // measured at 762.6 iterations per second (hardware)
count = benchmark_target::test_memory(target_conn, count).expect("BENCHMARK: couldn't send test message"); count = benchmark_target::test_memory(target_conn, count).expect("BENCHMARK: couldn't send test message");
check_count = check_count + 1; check_count = check_count + 1;
} }

View file

@ -8,6 +8,7 @@ description = "Graphical Abstraction Manager for Xous"
[dependencies] [dependencies]
bitflags = "1.2.1" bitflags = "1.2.1"
xous = { path = "../../xous-rs" } xous = { path = "../../xous-rs" }
rkyv = { version = "0.3.1", default_features = false }
graphics-server = { path = "../graphics-server" } graphics-server = { path = "../graphics-server" }
ticktimer-server = { path = "../ticktimer-server" } ticktimer-server = { path = "../ticktimer-server" }
xous-names = { path = "../xous-names" } xous-names = { path = "../xous-names" }

View file

@ -80,7 +80,7 @@ be able to have exquisite control over the "look and feel" of their applications
calls can "simulate" certain properties (such as figuring out the dynamic calls can "simulate" certain properties (such as figuring out the dynamic
width or height of a text box based on the size of the string within) to assist width or height of a text box based on the size of the string within) to assist
with laying out `TextViews`. Once the layout is finalized, the `TextView` objects with laying out `TextViews`. Once the layout is finalized, the `TextView` objects
are then immutably lent to the GAM using a `xous::ipc::Sendable.lend()` wrapper; are then immutably lent to the GAM using an `rkyv` lend wrapper;
the calling thread then blocks until the GAM completes the rendering operation. the calling thread then blocks until the GAM completes the rendering operation.
One can think of a `TextView` as a text bubble, that can have rounded or square One can think of a `TextView` as a text bubble, that can have rounded or square

View file

@ -3,7 +3,7 @@ use graphics_server::{Point, Rectangle, TextView, Gid};
use blitstr_ref as blitstr; use blitstr_ref as blitstr;
use blitstr::{GlyphStyle, Cursor}; use blitstr::{GlyphStyle, Cursor};
#[derive(Debug)] #[derive(Debug, rkyv::Archive)]
pub enum Opcode { pub enum Opcode {
// clears a canvas with a given GID // clears a canvas with a given GID
ClearCanvas(Gid), ClearCanvas(Gid),
@ -11,6 +11,9 @@ pub enum Opcode {
// renders a TextView // renders a TextView
RenderTextView(TextView), RenderTextView(TextView),
// result codes from operations on TextViews
TextViewResult(TextViewResult),
// returns a GID to the "content" Canvas; requires an authentication token // returns a GID to the "content" Canvas; requires an authentication token
RequestContentCanvas(Gid), RequestContentCanvas(Gid),

View file

@ -10,27 +10,34 @@ use graphics_server::api::{TextOp, TextView};
use graphics_server::api::{Rectangle, Point, Gid, TextBounds}; use graphics_server::api::{Rectangle, Point, Gid, TextBounds};
use log::{error, info}; use log::{error, info};
use rkyv::Write;
/// this "posts" a textview -- it's not a "draw" as the update is neither guaranteed nor instantaneous /// this "posts" a textview -- it's not a "draw" as the update is neither guaranteed nor instantaneous
/// the GAM first has to check that the textview is allowed to be updated, and then it will decide when /// the GAM first has to check that the textview is allowed to be updated, and then it will decide when
/// the actual screen update is allowed /// the actual screen update is allowed
pub fn post_textview(gam_cid: xous::CID, tv: &mut TextView) -> Result<(), xous::Error> { pub fn post_textview(gam_cid: xous::CID, tv: &mut TextView) -> Result<(), xous::Error> {
let mut tv_backup = TextView::new(Gid::new([0,0,0,0]), 0, // for testing only
TextBounds::BoundingBox(Rectangle::new(Point::new(0, 0), Point::new(0, 0)))); tv.set_op(TextOp::Render);
tv_backup.populate_from(&tv); tv.cursor.pt.x = 37;
info!("tv_backup: {:?}", tv_backup); tv.cursor.pt.y = 5;
let mut sendable_tv = Sendable::new(tv).expect("can't create sendable textview"); info!("tv before lend: {:?}", tv);
sendable_tv.populate_from(&tv_backup); let mut rkyv_tv = api::Opcode::RenderTextView(tv);
info!("sendable_tv: {:?}", sendable_tv); let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rkyv_tv).expect("couldn't archive textview");
let mut xous_buffer = writer.into_inner();
sendable_tv.set_op(TextOp::Render); xous_buffer.lend_mut(gam_cid, pos as u32).expect("RenderTextView operation failure");
sendable_tv.cursor.pt.x = 37;
sendable_tv.cursor.pt.y = 5;
info!("sendable_tv before lend: {:?}", sendable_tv); let returned = unsafe { rkyv::archived_value::<api::Opcode>(xous_buffer.as_ref(), pos)};
sendable_tv.lend_mut(gam_cid, sendable_tv.get_op().into()).expect("draw_textview operation failure"); match returned {
rkyv::Archived::<api::Opcode>::TextViewResult(result) => {
tv.set_bounds_computed(result.bounds_computed);
tv.cursor = result.cursor;
},
_ => panic!("post_textview got a return value from the server that isn't expected or handled")
}
sendable_tv.set_op(TextOp::Nop); tv.set_op(TextOp::Nop);
Ok(()) Ok(())
} }

View file

@ -189,19 +189,31 @@ fn xmain() -> ! {
_ => todo!("GAM: opcode not yet implemented"), _ => todo!("GAM: opcode not yet implemented"),
} }
} else if let xous::Message::MutableBorrow(m) = &envelope.body { } else if let xous::Message::MutableBorrow(m) = &envelope.body {
match TextOp::from(m.id) { let mut buf = unsafe { buffer::XousBuffer::from_memory_message(m) };
TextOp::Nop => (), let value = unsafe {
TextOp::Render => { archived_value_mut::<api::Request>(Pin::new(buf.as_mut()), m.id.try_into().unwrap())
let mut tv: &mut TextView = unsafe { };
&mut *(m.buf.as_mut_ptr() as *mut TextView) let new_value = match &*value {
}; rkyv::Archived::<api::Opcode>::RenderTextView(tv) => {
info!("GAM: render request for {:?}", tv); match tv.operation {
tv_draw(gfx_conn, trng_conn, &mut canvases, &mut tv).expect("GAM: can't render TextView"); TextOp::Nop => (),
}, TextOp::Render => {
TextOp::ComputeBounds => { info!("GAM: render request for {:?}", tv);
tv_draw(gfx_conn, trng_conn, &mut canvases, &mut tv).expect("GAM: can't render TextView");
},
TextOp::ComputeBounds => {
}, },
} };
let tv_ret = TextViewResult {
bounds_computed: tv.get_boundscomputed(),
cursor: tv.cursor,
};
rkyv::Archived::<api::Opcode>::TextViewResult(tv_ret)
}
_ => panic!("GAM: invalid mutable borrow message"),
};
unsafe { *value.get_unchecked_mut() = new_value };
} }
} }
_ => xous::yield_slice(), _ => xous::yield_slice(),

View file

@ -31,7 +31,7 @@ use hash32::{Hash, Hasher};
//////////////// OS APIs //////////////// OS APIs
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[derive(Debug, Copy, Clone, PartialEq, Eq, rkyv::Archive)]
pub struct Gid { pub struct Gid {
/// a 128-bit random identifier for graphical objects /// a 128-bit random identifier for graphical objects
gid: [u32; 4], gid: [u32; 4],

View file

@ -4,14 +4,14 @@ use blitstr::{GlyphStyle, Cursor};
use log::info; use log::info;
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone, rkyv::Archive)]
pub enum TextAlignment { pub enum TextAlignment {
Left, Left,
Center, Center,
Right, Right,
} }
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone, rkyv::Archive)]
pub enum TextBounds { pub enum TextBounds {
// fixed width and height in a rectangle // fixed width and height in a rectangle
BoundingBox(Rectangle), BoundingBox(Rectangle),
@ -23,7 +23,7 @@ pub enum TextBounds {
GrowableFromBl(Point, u16), GrowableFromBl(Point, u16),
} }
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone, rkyv::Archive)]
// operations that may be requested of a TextView when sent to GAM // operations that may be requested of a TextView when sent to GAM
pub enum TextOp { pub enum TextOp {
Nop, Nop,
@ -52,8 +52,13 @@ impl From<usize> for TextOp {
// roughly 168 bytes to represent the rest of the struct, and we want to fill out the 4096 byte page with text // roughly 168 bytes to represent the rest of the struct, and we want to fill out the 4096 byte page with text
const TEXTVIEW_LEN: usize = 3072; const TEXTVIEW_LEN: usize = 3072;
#[repr(C)] #[derive(Copy, Clone, rkyv::Archive)]
#[derive(Copy, Clone)] pub struct TextViewResult {
pub bounds_computed: Option<Rectangle>,
pub cursor: Cursor,
}
#[derive(Copy, Clone, rkyv::Archive)]
pub struct TextView { pub struct TextView {
// this is the operation as specified for the GAM. Note this is different from the "op" when sent to graphics-server // this is the operation as specified for the GAM. Note this is different from the "op" when sent to graphics-server
// only the GAM should be sending TextViews to the graphics-server, and a different coding scheme is used for that link. // only the GAM should be sending TextViews to the graphics-server, and a different coding scheme is used for that link.
@ -71,7 +76,7 @@ pub struct TextView {
bounds_computed: Option<Rectangle>, // is Some(Rectangle) if bounds have been computed and text has not been modified bounds_computed: Option<Rectangle>, // is Some(Rectangle) if bounds have been computed and text has not been modified
pub style: GlyphStyle, pub style: GlyphStyle,
text: [u8; TEXTVIEW_LEN], text: xous::String::<3072>,
length: u32, length: u32,
pub alignment: TextAlignment, pub alignment: TextAlignment,
pub cursor: Cursor, pub cursor: Cursor,
@ -99,7 +104,7 @@ impl TextView {
bounds_hint, bounds_hint,
bounds_computed: None, bounds_computed: None,
style: GlyphStyle::Regular, style: GlyphStyle::Regular,
text: [0; TEXTVIEW_LEN], text: xous::String::<3072>::new(),
length: 0, length: 0,
alignment: TextAlignment::Left, alignment: TextAlignment::Left,
cursor: Cursor::new(0,0,0), cursor: Cursor::new(0,0,0),
@ -128,15 +133,15 @@ impl TextView {
} }
Ok(()) Ok(())
} }
pub(crate) fn set_computed_bounds(&mut self, r: Option<Rectangle>) {
pub fn to_str(&self) -> &str { self.bounds_computed = r;
core::str::from_utf8(unsafe {
core::slice::from_raw_parts(self.text.as_ptr(), self.length as usize)
})
.unwrap()
} }
pub fn clear_str(&mut self) { self.text = [0; TEXTVIEW_LEN] } pub fn to_str(&self) -> &str {
self.text.as_str().unwrap()
}
pub fn clear_str(&mut self) { self.text.clear() }
pub fn populate_from(&mut self, t: &TextView) { pub fn populate_from(&mut self, t: &TextView) {
self.operation = t.operation; self.operation = t.operation;
@ -187,26 +192,6 @@ impl core::fmt::Display for TextView {
// allow `write!()` macro on a` &TextView` // allow `write!()` macro on a` &TextView`
impl core::fmt::Write for TextView { impl core::fmt::Write for TextView {
fn write_str(&mut self, s: &str) -> core::result::Result<(), core::fmt::Error> { fn write_str(&mut self, s: &str) -> core::result::Result<(), core::fmt::Error> {
self.bounds_computed = None; write!(self.text, "{}", s)
let b = s.bytes();
// Ensure the length is acceptable
if b.len() + self.length as usize > self.text.len() as usize {
Err(core::fmt::Error)?;
}
// append the write to the array
for c in s.bytes() {
if self.length < self.text.len() as u32 {
self.text[self.length as usize] = c;
self.length += 1;
}
}
// Attempt to convert the string to UTF-8 to validate it's correct UTF-8.
core::str::from_utf8(unsafe {
core::slice::from_raw_parts(self.text.as_ptr(), self.length as usize)
})
.map_err(|_| core::fmt::Error)?;
Ok(())
} }
} }

View file

@ -21,8 +21,8 @@ pub struct ScanCode {
#[derive(Debug, Default, Copy, Clone)] #[derive(Debug, Default, Copy, Clone)]
pub struct RowCol { pub struct RowCol {
pub r: u8, pub r: u32,
pub c: u8, pub c: u32,
} }
#[repr(packed)] #[repr(packed)]
pub struct KeyRawStates { pub struct KeyRawStates {

View file

@ -1,268 +0,0 @@
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::marker::{PhantomData, Unpin};
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;
#[derive(PartialEq, Debug)]
enum MemoryState {
/// This struct is available for lending and sending
Available,
/// This memory has been mutably lent out and will be returned
MutablyLent,
/// This memory was moved, and should be forgotten
Moved,
}
// #[repr(C)]
pub struct UninitializedSendable<T> {
contents: NonNull<T>,
}
pub struct Sendable<T> {
contents: *mut T,
total_size: usize,
memory_state: MemoryState,
// NOTE: this marker has no consequences for variance, but is necessary
// for dropck to understand that we logically own a `T`.
//
// For details, see:
// https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
_marker: PhantomData<T>,
}
impl<T> UninitializedSendable<T> {
fn type_size() -> usize {
let type_size = core::mem::size_of::<T>();
let remainder = type_size & 4095;
type_size + (4096 - remainder)
}
pub fn new(val: T) -> Result<UninitializedSendable<T>, crate::Error>
where
T: Unpin,
{
let uninitialized = Self::uninit()?;
let type_size = core::mem::size_of::<T>();
unsafe {
let src_slice = core::slice::from_raw_parts(&val as *const _ as *const u8, type_size);
let dest_slice = core::slice::from_raw_parts_mut(
uninitialized.contents.as_ptr() as *mut u8,
type_size,
);
for (src, dest) in src_slice.iter().zip(dest_slice) {
*dest = *src;
}
}
Ok(uninitialized)
}
pub fn uninit() -> Result<UninitializedSendable<T>, crate::Error> {
let padded_size = Self::type_size();
// Ensure this object takes up exactly a multiple of a page. This
// ensures it can be sent to another process.
let new_mem = crate::map_memory(
None,
None,
padded_size,
crate::MemoryFlags::R | crate::MemoryFlags::W,
)?;
let contents = unsafe { NonNull::new_unchecked(new_mem.as_mut_ptr() as *mut T) };
Ok(UninitializedSendable { contents })
}
pub unsafe fn assume_init(self) -> Sendable<T> {
Sendable {
contents: self.contents.as_ptr(),
total_size: Self::type_size(),
memory_state: MemoryState::Available,
_marker: PhantomData,
}
}
}
impl<T: Default + Unpin + Send> Default for Sendable<T> {
/// Creates a `Box<T>`, with the `Default` value for T.
fn default() -> Sendable<T> {
Sendable::new(Default::default()).unwrap()
}
}
// impl<T> Default for Sendable<[T]> {
// fn default() -> Sendable<[T]> {
// Sendable::<[T; 0]>::new([])
// }
// }
/// `Unique` pointers are `Send` if `T` is `Send` because the data they
/// reference is unaliased. Note that this aliasing invariant is
/// unenforced by the type system; the abstraction using the
/// `Unique` must enforce it.
unsafe impl<T: Send> Send for Sendable<T> {}
/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
/// reference is unaliased. Note that this aliasing invariant is
/// unenforced by the type system; the abstraction using the
/// `Unique` must enforce it.
unsafe impl<T: Sync> Sync for Sendable<T> {}
impl<T: Send> Sendable<T> {
pub fn new(val: T) -> Result<Sendable<T>, crate::Error>
where
T: Unpin,
{
Ok(unsafe { UninitializedSendable::new(val)?.assume_init() })
}
/// Perform an immutable lend of this Carton to the specified server.
/// This function will block until the server returns.
pub fn lend(&self, connection: crate::CID, id: u32) -> Result<crate::Result, crate::Error> {
let buf = crate::MemoryRange::new(self.contents as usize, self.total_size)?;
let msg = crate::MemoryMessage {
id: id as usize,
buf,
offset: None,
valid: crate::MemorySize::new(core::mem::size_of::<T>()),
};
crate::send_message(connection, crate::Message::Borrow(msg))
}
/// Perform a mutable lend of this Carton to the server.
pub fn lend_mut(
&mut self,
connection: crate::CID,
id: u32,
) -> Result<crate::Result, crate::Error> {
let buf = crate::MemoryRange::new(self.contents as usize, self.total_size)?;
let msg = crate::MemoryMessage {
id: id as usize,
buf,
offset: None,
valid: crate::MemorySize::new(core::mem::size_of::<T>()),
};
self.memory_state = MemoryState::MutablyLent;
let result = crate::send_message(connection, crate::Message::MutableBorrow(msg));
self.memory_state = MemoryState::Available;
result
}
/// Perform a move of this Carton to the server.
pub fn send(
mut self,
connection: crate::CID,
id: u32,
) -> Result<crate::Result, crate::Error> {
let buf = crate::MemoryRange::new(self.contents as usize, self.total_size)?;
let msg = crate::MemoryMessage {
id: id as usize,
buf,
offset: None,
valid: crate::MemorySize::new(core::mem::size_of::<T>()),
};
let result = crate::send_message(connection, crate::Message::Move(msg))?;
// Mark this state as Moved, which prevents it from being Dropped.
self.memory_state = MemoryState::Moved;
Ok(result)
}
}
impl<T> Deref for Sendable<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.contents }
}
}
impl<T> DerefMut for Sendable<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.contents }
}
}
// Display formatting
impl<T: fmt::Display> fmt::Display for Sendable<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<T: fmt::Debug> fmt::Debug for Sendable<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<T> fmt::Pointer for Sendable<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// It's not possible to extract the inner Uniq directly from the Box,
// instead we cast it to a *const which aliases the Unique
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
impl<T: PartialEq> PartialEq for Sendable<T> {
#[inline]
fn eq(&self, other: &Sendable<T>) -> bool {
PartialEq::eq(&**self, &**other)
}
#[inline]
fn ne(&self, other: &Sendable<T>) -> bool {
PartialEq::ne(&**self, &**other)
}
}
impl<T: PartialOrd> PartialOrd for Sendable<T> {
#[inline]
fn partial_cmp(&self, other: &Sendable<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Sendable<T>) -> bool {
PartialOrd::lt(&**self, &**other)
}
#[inline]
fn le(&self, other: &Sendable<T>) -> bool {
PartialOrd::le(&**self, &**other)
}
#[inline]
fn ge(&self, other: &Sendable<T>) -> bool {
PartialOrd::ge(&**self, &**other)
}
#[inline]
fn gt(&self, other: &Sendable<T>) -> bool {
PartialOrd::gt(&**self, &**other)
}
}
impl<T: Ord> Ord for Sendable<T> {
#[inline]
fn cmp(&self, other: &Sendable<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
impl<T: Eq> Eq for Sendable<T> {}
impl<T: Hash> Hash for Sendable<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl<T> Drop for Sendable<T> {
fn drop(&mut self) {
if self.memory_state != MemoryState::Available {
panic!("invalid memory state: {:?}", self.memory_state);
}
let range = crate::MemoryRange::new(self.contents as usize, self.total_size).unwrap();
crate::unmap_memory(range).unwrap();
}
}

View file

@ -11,7 +11,6 @@ pub mod arch;
pub mod carton; pub mod carton;
pub mod definitions; pub mod definitions;
pub mod ipc;
mod messages; mod messages;
pub mod string; pub mod string;
pub mod buffer; pub mod buffer;

View file

@ -5,7 +5,7 @@ use rkyv::Unarchive;
use rkyv::archived_value; use rkyv::archived_value;
use core::pin::Pin; use core::pin::Pin;
//#[derive(rkyv::Archive)] #[derive(Copy, Clone)]
pub struct String<const N: usize> { pub struct String<const N: usize> {
bytes: [u8; N], bytes: [u8; N],
len: u32, len: u32,
@ -121,15 +121,6 @@ pub struct ArchivedString {
ptr: rkyv::RelPtr, ptr: rkyv::RelPtr,
len: u32, len: u32,
} }
/*
impl ArchivedString {
pub fn as_str(&self) -> &str {
unsafe {
let bytes = core::slice::from_raw_parts(self.ptr.as_ptr(), self.len as usize);
core::str::from_utf8_unchecked(&bytes)
}
}
}*/
pub struct StringResolver { pub struct StringResolver {
bytes_pos: usize, bytes_pos: usize,
} }