Merge pull request #51 from betrusted-io/hardware

Merge xobs changes to make typing much easier
This commit is contained in:
bunnie 2021-03-13 18:20:39 +08:00 committed by GitHub
commit 6d2697667b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 264 additions and 200 deletions

41
Cargo.lock generated
View file

@ -704,8 +704,8 @@ dependencies = [
[[package]] [[package]]
name = "minifb" name = "minifb"
version = "0.19.2" version = "0.19.3"
source = "git+https://github.com/xobs/rust_minifb.git?rev=bbbfc07c059919fae700fabe771346a001226dbc#bbbfc07c059919fae700fabe771346a001226dbc" source = "git+https://github.com/xobs/rust_minifb.git?rev=ea25c2e4843abd130d6794b2045812907a24eab2#ea25c2e4843abd130d6794b2045812907a24eab2"
dependencies = [ dependencies = [
"cc", "cc",
"orbclient", "orbclient",
@ -732,15 +732,14 @@ dependencies = [
[[package]] [[package]]
name = "nix" name = "nix"
version = "0.17.0" version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50e4785f2c3b7589a0d0c1dd60285e1188adac4006e8abd6dd578e1567027363" checksum = "fa9b4819da1bc61c0ea48b63b7bc8604064dd43013e7cc325df098d49cd7c18a"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"cc", "cc",
"cfg-if 0.1.10", "cfg-if 1.0.0",
"libc", "libc",
"void",
] ]
[[package]] [[package]]
@ -1360,12 +1359,6 @@ version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed" checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
[[package]]
name = "void"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
[[package]] [[package]]
name = "wasi" name = "wasi"
version = "0.10.2+wasi-snapshot-preview1" version = "0.10.2+wasi-snapshot-preview1"
@ -1374,9 +1367,9 @@ checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
[[package]] [[package]]
name = "wayland-client" name = "wayland-client"
version = "0.27.0" version = "0.28.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab702fefbcd6d6f67fb5816e3a89a3b5a42a94290abbc015311c9a30d1068ae4" checksum = "06ca44d86554b85cf449f1557edc6cc7da935cc748c8e4bf1c507cbd43bae02c"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"downcast-rs", "downcast-rs",
@ -1389,9 +1382,9 @@ dependencies = [
[[package]] [[package]]
name = "wayland-commons" name = "wayland-commons"
version = "0.27.0" version = "0.28.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e972e9336ad5a9dd861b4e21ff35ad71d3e5c6b4803d65c39913612f851b95f1" checksum = "8bd75ae380325dbcff2707f0cd9869827ea1d2d6d534cff076858d3f0460fd5a"
dependencies = [ dependencies = [
"nix", "nix",
"once_cell", "once_cell",
@ -1401,9 +1394,9 @@ dependencies = [
[[package]] [[package]]
name = "wayland-cursor" name = "wayland-cursor"
version = "0.27.0" version = "0.28.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "539f346e1a3f706f38c8ccbe1196001e2fb1c9b3e6b605c27d665db2f5b60d41" checksum = "b37e5455ec72f5de555ec39b5c3704036ac07c2ecd50d0bffe02d5fe2d4e65ab"
dependencies = [ dependencies = [
"nix", "nix",
"wayland-client", "wayland-client",
@ -1412,9 +1405,9 @@ dependencies = [
[[package]] [[package]]
name = "wayland-protocols" name = "wayland-protocols"
version = "0.27.0" version = "0.28.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3d6fc54b17b98b5083bc21ae3a30e6d75cb4b01647360e4c3a04648bcf8781d" checksum = "95df3317872bcf9eec096c864b69aa4769a1d5d6291a5b513f8ba0af0efbd52c"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"wayland-client", "wayland-client",
@ -1424,9 +1417,9 @@ dependencies = [
[[package]] [[package]]
name = "wayland-scanner" name = "wayland-scanner"
version = "0.27.0" version = "0.28.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "030f56009d932bd9400bb472764fea8109be1b0fc482d9cd75496c943ac30328" checksum = "389d680d7bd67512dc9c37f39560224327038deb0f0e8d33f870900441b68720"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
@ -1435,9 +1428,9 @@ dependencies = [
[[package]] [[package]]
name = "wayland-sys" name = "wayland-sys"
version = "0.27.0" version = "0.28.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bdeffbbb474477dfa2acb45ac7479e5fe8f741c64ab032c5d11b94d07edc269" checksum = "2907bd297eef464a95ba9349ea771611771aa285b932526c633dc94d5400a8e2"
dependencies = [ dependencies = [
"pkg-config", "pkg-config",
] ]

View file

@ -69,4 +69,3 @@ exclude = [
codegen-units = 1 # 1 better optimizations codegen-units = 1 # 1 better optimizations
debug = true # symbols are nice and they don't increase the size on Flash debug = true # symbols are nice and they don't increase the size on Flash
lto = "fat" lto = "fat"

View file

@ -312,6 +312,7 @@ fn listen_thread(
// Read the challenge access key from the client // Read the challenge access key from the client
let mut access_key = [0u8; 16]; let mut access_key = [0u8; 16];
conn.read_exact(&mut access_key).unwrap(); conn.read_exact(&mut access_key).unwrap();
conn.set_nodelay(true).unwrap();
// Spawn a new process. This process will start out in the "Allocated" state. // Spawn a new process. This process will start out in the "Allocated" state.
chn.send(ThreadMessage::NewConnection( chn.send(ThreadMessage::NewConnection(

View file

@ -30,9 +30,10 @@ pub struct ContentCanvasRequest {
pub servername: xous::String<256>, pub servername: xous::String<256>,
} }
#[repr(C)]
#[derive(Debug, rkyv::Archive, rkyv::Unarchive, Copy, Clone)] #[derive(Debug, rkyv::Archive, rkyv::Unarchive, Copy, Clone)]
// #[archive(derive(Copy, Clone))] // #[archive(derive(Copy, Clone))]
pub enum Opcode { pub(crate) enum Opcode {
// clears a canvas with a given GID // clears a canvas with a given GID
ClearCanvas(Gid), ClearCanvas(Gid),

View file

@ -13,14 +13,14 @@ keyboard = {path = "../keyboard"}
log = "0.4" log = "0.4"
log-server = {path = "../log-server"} log-server = {path = "../log-server"}
xous = {path = "../../xous-rs"} xous = {path = "../../xous-rs"}
rkyv = { version = "0.3.1", default_features = false } rkyv = { version = "0.3.1", default_features = false, features = ["strict"] }
xous-names = {path = "../xous-names"} xous-names = {path = "../xous-names"}
[target.'cfg(not(any(windows,unix)))'.dependencies] [target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = {path = "../../utralib"} utralib = {path = "../../utralib"}
[target.'cfg(any(windows,unix))'.dependencies] [target.'cfg(any(windows,unix))'.dependencies]
minifb = {version = "0.19.2", git = "https://github.com/xobs/rust_minifb.git", rev = "bbbfc07c059919fae700fabe771346a001226dbc"} minifb = {version = "0.19.2", git = "https://github.com/xobs/rust_minifb.git", rev = "ea25c2e4843abd130d6794b2045812907a24eab2"}
[features] [features]
debugprint = [] debugprint = []

View file

@ -1,5 +1,5 @@
use minifb::{Key, Window, WindowOptions, KeyRepeat};
use crate::api::Point; use crate::api::Point;
use minifb::{Key, Window, WindowOptions};
const WIDTH: usize = 336; const WIDTH: usize = 336;
const HEIGHT: usize = 536; const HEIGHT: usize = 536;
@ -16,13 +16,18 @@ pub struct XousDisplay {
native_buffer: Vec<u32>, //[u32; WIDTH * HEIGHT], native_buffer: Vec<u32>, //[u32; WIDTH * HEIGHT],
emulated_buffer: [u32; FB_SIZE], emulated_buffer: [u32; FB_SIZE],
window: Window, window: Window,
}
struct XousKeyboardHandler {
kbd_conn: xous::CID, kbd_conn: xous::CID,
left_shift: bool,
right_shift: bool,
} }
impl XousDisplay { impl XousDisplay {
pub fn new() -> XousDisplay { pub fn new() -> XousDisplay {
let mut window = Window::new( let mut window = Window::new(
"Betrusted", "Precursor",
WIDTH, WIDTH,
HEIGHT, HEIGHT,
WindowOptions { WindowOptions {
@ -45,17 +50,25 @@ impl XousDisplay {
.update_with_buffer(&native_buffer, WIDTH, HEIGHT) .update_with_buffer(&native_buffer, WIDTH, HEIGHT)
.unwrap(); .unwrap();
let kbd_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_KBD).expect("GFX|hosted: can't connect to KBD for emulation"); let kbd_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_KBD)
.expect("GFX|hosted: can't connect to KBD for emulation");
let keyboard_handler = Box::new(XousKeyboardHandler {
kbd_conn: kbd_conn,
left_shift: false,
right_shift: false,
});
window.set_input_callback(keyboard_handler);
XousDisplay { XousDisplay {
native_buffer, native_buffer,
window, window,
emulated_buffer: [0u32; FB_SIZE], emulated_buffer: [0u32; FB_SIZE],
kbd_conn,
} }
} }
pub fn screen_size(&self) -> Point { Point::new(WIDTH as i16, HEIGHT as i16) } pub fn screen_size(&self) -> Point {
Point::new(WIDTH as i16, HEIGHT as i16)
}
pub fn blit_screen(&mut self, bmp: [u32; FB_SIZE]) { pub fn blit_screen(&mut self, bmp: [u32; FB_SIZE]) {
for (dest, src) in self.emulated_buffer.iter_mut().zip(bmp.iter()) { for (dest, src) in self.emulated_buffer.iter_mut().zip(bmp.iter()) {
@ -80,17 +93,16 @@ impl XousDisplay {
if !self.window.is_open() || self.window.is_key_down(Key::Escape) { if !self.window.is_open() || self.window.is_key_down(Key::Escape) {
std::process::exit(0); std::process::exit(0);
} }
// let pressed = self.window.get_keys_pressed(KeyRepeat::No);
let pressed = self.window.get_keys_pressed(KeyRepeat::No); // if let Some(keys) = pressed {
if let Some(keys) = pressed { // for k in keys {
for k in keys { // log::info!("GFX|hosted: sending key {:?}", k);
log::info!("GFX|hosted: sending key {:?}", k); // let c = self.decode_key(k);
let c = self.decode_key(k); // if c != '\u{0000}' {
if c != '\u{0000}' { // xous::send_message(self.kbd_conn, keyboard::api::Opcode::HostModeInjectKey(c).into()).map(|_| ()).unwrap();
xous::send_message(self.kbd_conn, keyboard::api::Opcode::HostModeInjectKey(c).into()).map(|_| ()).unwrap(); // }
} // }
} // }
}
} }
fn emulated_to_native(&mut self) { fn emulated_to_native(&mut self) {
@ -110,15 +122,12 @@ impl XousDisplay {
} }
} }
} }
}
impl XousKeyboardHandler {
fn decode_key(&mut self, k: Key) -> char { fn decode_key(&mut self, k: Key) -> char {
let mut shift = false; let shift = self.left_shift || self.right_shift;
if self.window.is_key_pressed(Key::LeftShift, KeyRepeat::Yes) || let base: char = if shift == false {
self.window.is_key_pressed(Key::RightShift, KeyRepeat::Yes) {
shift = true;
}
let base: char =
if shift == false {
match k { match k {
Key::A => 'a', Key::A => 'a',
Key::B => 'b', Key::B => 'b',
@ -229,3 +238,32 @@ impl XousDisplay {
base base
} }
} }
impl minifb::InputCallback for XousKeyboardHandler {
fn add_char(&mut self, _uni_char: u32) {}
fn set_key_state(&mut self, key: minifb::Key, state: bool) {
if key == Key::LeftShift {
self.left_shift = state;
return;
}
if key == Key::RightShift {
self.right_shift = state;
return;
}
if !state {
return;
}
log::info!("GFX|hosted: sending key {:?}", key);
let c = self.decode_key(key);
if c != '\u{0000}' {
xous::send_message(
self.kbd_conn,
keyboard::api::Opcode::HostModeInjectKey(c).into(),
)
.map(|_| ())
.unwrap();
}
}
}

View file

@ -8,7 +8,7 @@ description = "System call interface for Xous"
[dependencies] [dependencies]
bitflags = {version = "1", optional = true } bitflags = {version = "1", optional = true }
xous-macros = { path = "../macros", version = "0.1.0" } xous-macros = { path = "../macros", version = "0.1.0", optional = true }
log = { version = "0.4", optional = true } log = { version = "0.4", optional = true }
rkyv = { version = "0.3.1", default_features = false, optional = true } rkyv = { version = "0.3.1", default_features = false, optional = true }
core = { version = '1.0.0', optional = true, package = 'rustc-std-workspace-core' } core = { version = '1.0.0', optional = true, package = 'rustc-std-workspace-core' }
@ -33,7 +33,7 @@ logging = ["log"]
# This is being built as part of libstd # This is being built as part of libstd
rustc-dep-of-std = ['core', 'compiler_builtins/rustc-dep-of-std'] rustc-dep-of-std = ['core', 'compiler_builtins/rustc-dep-of-std']
default = ["bit-flags", "archive"] default = ["bit-flags", "archive", "xous-macros"]
[target.'cfg(any(windows,unix))'.dependencies] [target.'cfg(any(windows,unix))'.dependencies]
lazy_static = "1.4" lazy_static = "1.4"

View file

@ -397,6 +397,7 @@ fn xous_connect_impl(
Ok(mut conn) => { Ok(mut conn) => {
conn.write_all(&key.0).unwrap(); // Send key to authenticate us as PID 1 conn.write_all(&key.0).unwrap(); // Send key to authenticate us as PID 1
conn.flush().unwrap(); conn.flush().unwrap();
conn.set_nodelay(true).unwrap();
let mut pid = [0u8]; let mut pid = [0u8];
conn.read_exact(&mut pid).unwrap(); conn.read_exact(&mut pid).unwrap();
PROCESS_ID.with(|process_id| *process_id.borrow_mut() = PID::new(pid[0]).unwrap()); PROCESS_ID.with(|process_id| *process_id.borrow_mut() = PID::new(pid[0]).unwrap());
@ -456,7 +457,7 @@ pub fn _xous_syscall(
a6, a6,
a7, a7,
&call, &call,
&mut xsc_asmut.send.lock().unwrap(), xsc_asmut
); );
_xous_syscall_result(ret, *tid.borrow(), xsc_asmut); _xous_syscall_result(ret, *tid.borrow(), xsc_asmut);
if *ret != Result::WouldBlock { if *ret != Result::WouldBlock {
@ -656,7 +657,7 @@ fn _xous_syscall_to(
a6: usize, a6: usize,
a7: usize, a7: usize,
call: &crate::SysCall, call: &crate::SysCall,
xsc: &mut TcpStream, xsc: &mut ServerConnection,
) { ) {
// println!( // println!(
// "Making Syscall: {:?}", // "Making Syscall: {:?}",
@ -677,9 +678,10 @@ fn _xous_syscall_to(
pkt.extend_from_slice(data); pkt.extend_from_slice(data);
} }
if let Err(e) = xsc.write_all(&pkt) { let mut stream = xsc.send.lock().unwrap();
if let Err(e) = stream.write_all(&pkt) {
eprintln!("Server shut down: {}", e); eprintln!("Server shut down: {}", e);
std::process::exit(0); std::process::exit(0);
} }
xsc.flush().unwrap(); // stream.flush().unwrap();
} }

View file

@ -4,8 +4,9 @@
#[macro_use] #[macro_use]
extern crate bitflags; extern crate bitflags;
#[cfg(not(feature = "rustc-dep-of-std"))]
extern crate xous_macros as macros; extern crate xous_macros as macros;
#[cfg(not(feature = "rustc-dep-of-std"))]
pub use macros::xous_main; pub use macros::xous_main;
pub mod arch; pub mod arch;

View file

@ -1,9 +1,9 @@
use crate::{CID, Error, MemoryMessage, Result}; use crate::{Error, MemoryMessage, Result, CID};
use rkyv::Write;
use rkyv::Unarchive;
use rkyv::archived_value;
use core::pin::Pin; use core::pin::Pin;
use rkyv::archived_value;
use rkyv::Unarchive;
use rkyv::Write;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct String<const N: usize> { pub struct String<const N: usize> {
@ -19,6 +19,24 @@ impl<const N: usize> String<N> {
} }
} }
pub fn from_str(src: &str) -> String<N> {
let mut s = Self::new();
// Copy the string into our backing store.
for (&src_byte, dest_byte) in src.as_bytes().iter().zip(&mut s.bytes) {
*dest_byte = src_byte;
}
// Set the string length to the length of the passed-in String,
// or the maximum possible length. Which ever is smaller.
s.len = s.bytes.len().min(src.as_bytes().len()) as u32;
// If the string is not valid, set its length to 0.
if s.as_str().is_err() {
s.len = 0;
}
s
}
pub fn as_bytes(&self) -> [u8; N] { pub fn as_bytes(&self) -> [u8; N] {
self.bytes self.bytes
} }
@ -37,13 +55,11 @@ impl<const N: usize> String<N> {
/// Convert a `MemoryMessage` into a `String` /// Convert a `MemoryMessage` into a `String`
pub fn from_message( pub fn from_message(
message: & mut MemoryMessage, message: &mut MemoryMessage,
) -> core::result::Result<String<N>, core::str::Utf8Error> { ) -> core::result::Result<String<N>, core::str::Utf8Error> {
let buf = unsafe{ crate::XousBuffer::from_memory_message(message) }; let buf = unsafe { crate::XousBuffer::from_memory_message(message) };
let bytes = Pin::new(buf.as_ref()); let bytes = Pin::new(buf.as_ref());
let value = unsafe { let value = unsafe { archived_value::<String<N>>(&bytes, message.id as usize) };
archived_value::<String<N>>(&bytes, message.id as usize)
};
let s = value.unarchive(); let s = value.unarchive();
Ok(s) Ok(s)
} }
@ -60,9 +76,10 @@ impl<const N: usize> String<N> {
connection: CID, connection: CID,
// id: crate::MessageId, // id: crate::MessageId,
) -> core::result::Result<Result, Error> { ) -> core::result::Result<Result, Error> {
let mut writer = rkyv::ArchiveBuffer::new(crate::XousBuffer::new(N));
let mut writer = rkyv::ArchiveBuffer::new(crate::XousBuffer::new( N )); let pos = writer
let pos = writer.archive(self).expect("xous::String -- couldn't archive self"); .archive(self)
.expect("xous::String -- couldn't archive self");
let xous_buffer = writer.into_inner(); let xous_buffer = writer.into_inner();
// note that "id" is actually used as the position into the rkyv buffer // note that "id" is actually used as the position into the rkyv buffer
@ -75,8 +92,11 @@ impl<const N: usize> String<N> {
connection: CID, connection: CID,
// id: crate::MessageId, // id: crate::MessageId,
) -> core::result::Result<Result, Error> { ) -> core::result::Result<Result, Error> {
let mut writer = rkyv::ArchiveBuffer::new(crate::XousBuffer::new(/*self.bytes.len()*/ 4096)); let mut writer =
let pos = writer.archive(&self).expect("xous::String -- couldn't archive self"); rkyv::ArchiveBuffer::new(crate::XousBuffer::new(/*self.bytes.len()*/ 4096));
let pos = writer
.archive(&self)
.expect("xous::String -- couldn't archive self");
let xous_buffer = writer.into_inner(); let xous_buffer = writer.into_inner();
xous_buffer.send(connection, pos as u32) xous_buffer.send(connection, pos as u32)
@ -116,14 +136,12 @@ impl<const N: usize> String<N> {
Some(_thing) => { Some(_thing) => {
self.push(c).unwrap(); // always succeeds because we're re-encoding our string self.push(c).unwrap(); // always succeeds because we're re-encoding our string
maybe_c = next_c; maybe_c = next_c;
}, }
None => { None => return next_c,
return next_c
} }
} }
},
None => { None => {
return None // we should actually never get here because len() == 0 case already covered return None; // we should actually never get here because len() == 0 case already covered
} }
} }
} }
@ -139,7 +157,7 @@ impl<const N: usize> String<N> {
} else { } else {
Err(Error::OutOfMemory) Err(Error::OutOfMemory)
} }
}, }
_ => { _ => {
let mut bytes: usize = 0; let mut bytes: usize = 0;
let mut data: [u8; 4] = [0; 4]; let mut data: [u8; 4] = [0; 4];
@ -154,7 +172,7 @@ impl<const N: usize> String<N> {
} else { } else {
Err(Error::OutOfMemory) Err(Error::OutOfMemory)
} }
}, }
} }
} }
@ -164,7 +182,7 @@ impl<const N: usize> String<N> {
if let Ok(bytes) = self.push(ch) { if let Ok(bytes) = self.push(ch) {
bytes_added += bytes; bytes_added += bytes;
} else { } else {
return Err(Error::OutOfMemory) return Err(Error::OutOfMemory);
} }
} }
Ok(bytes_added) Ok(bytes_added)
@ -205,48 +223,59 @@ impl<const N: usize> core::fmt::Debug for String<N> {
} }
} }
#[repr(C)]
pub struct ArchivedString { pub struct ArchivedString {
ptr: rkyv::RelPtr, ptr: rkyv::RelPtr,
len: u32, len: u32,
} }
impl ArchivedString {
// Provide a `str` view of an `ArchivedString`.
fn as_str(&self) -> &str {
unsafe {
// The as_ptr() function of RelPtr will get a pointer
// to its memory.
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,
} }
// Turn a stream of bytes into an `ArchivedString`.
impl<const N: usize> rkyv::Resolve<String<N>> for StringResolver { impl<const N: usize> rkyv::Resolve<String<N>> for StringResolver {
type Archived = ArchivedString; type Archived = ArchivedString;
fn resolve(self, pos: usize, value: &String<N>) -> Self::Archived { fn resolve(self, pos: usize, value: &String<N>) -> Self::Archived {
Self::Archived { Self::Archived {
ptr: unsafe { ptr: unsafe {
rkyv::RelPtr::new( rkyv::RelPtr::new(pos + rkyv::offset_of!(ArchivedString, ptr), self.bytes_pos)
pos + rkyv::offset_of!(ArchivedString, ptr),
self.bytes_pos)
}, },
len: value.len() as u32, len: value.len() as u32,
} }
} }
} }
/// Turn a `String` into an archived object
impl<const N: usize> rkyv::Archive for String<N> { impl<const N: usize> rkyv::Archive for String<N> {
type Archived = ArchivedString; type Archived = ArchivedString;
type Resolver = StringResolver; type Resolver = StringResolver;
fn archive<W: rkyv::Write + ?Sized>(&self, writer: &mut W) -> core::result::Result<Self::Resolver, W::Error> { fn archive<W: rkyv::Write + ?Sized>(
&self,
writer: &mut W,
) -> core::result::Result<Self::Resolver, W::Error> {
let bytes_pos = writer.pos(); let bytes_pos = writer.pos();
writer.write(&self.bytes[0..self.len()])?; writer.write(&self.bytes[0..self.len()])?;
Ok(Self::Resolver { bytes_pos }) Ok(Self::Resolver { bytes_pos })
} }
} }
impl<const N: usize> rkyv::Unarchive<String<N>> for ArchivedString { impl<const N: usize> rkyv::Unarchive<String<N>> for ArchivedString {
fn unarchive(&self) -> String<N> { fn unarchive(&self) -> String<N> {
let mut s: String<N> = String::<N>::new(); String::from_str(self.as_str())
unsafe {
let p = self.ptr.as_ptr() as *const u8;
for(i, val) in s.bytes.iter_mut().enumerate() {
*val = p.add(i).read();
}
};
s.len = self.len;
s
} }
} }