Merge pull request #573 from betrusted-io/rkyv-0.8

Rkyv 0.8 - planning
This commit is contained in:
bunnie 2024-09-18 01:00:55 +08:00 committed by GitHub
commit fd0eaaade6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 1341 additions and 30 deletions

60
Cargo.lock generated
View file

@ -44,7 +44,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae0784134ba9375416d469ec31e7c5f9fa94405049cf08c5ce5b4698be673e0d"
dependencies = [
"aead",
"aes 0.8.3",
"aes 0.8.4",
"cipher",
"ctr",
"polyval",
@ -58,7 +58,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69fa2b352dcefb5f7f3a5fb840e02665d311d878955380515e4fd50095dd3d8c"
dependencies = [
"aes 0.8.3",
"aes 0.8.4",
]
[[package]]
@ -160,7 +160,7 @@ dependencies = [
"argh_shared",
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1199,7 +1199,7 @@ source = "git+https://github.com/betrusted-io/curve25519-dalek.git?branch=main#7
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1269,7 +1269,7 @@ dependencies = [
"ident_case",
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1291,7 +1291,7 @@ checksum = "1d1545d67a2149e1d93b7e5c7752dce5a7426eb5d1357ddcfd89336b94444f77"
dependencies = [
"darling_core 0.20.5",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1326,7 +1326,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1391,7 +1391,7 @@ checksum = "5fe87ce4529967e0ba1dcf8450bab64d97dfd5010a6256187ffe2e43e6f0e049"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1411,7 +1411,7 @@ checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1469,7 +1469,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1723,7 +1723,7 @@ dependencies = [
"once_cell",
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1744,7 +1744,7 @@ dependencies = [
"darling 0.20.5",
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1936,7 +1936,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e"
dependencies = [
"frunk_proc_macro_helpers",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -1948,7 +1948,7 @@ dependencies = [
"frunk_core",
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -2022,7 +2022,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -3225,7 +3225,7 @@ checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -3315,7 +3315,7 @@ checksum = "96667db765a921f7b295ffee8b60472b686a51d4f21c2ee4ffdb94c7013b65a6"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -3831,9 +3831,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"
[[package]]
name = "proc-macro2"
version = "1.0.78"
version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
dependencies = [
"unicode-ident",
]
@ -4053,7 +4053,7 @@ checksum = "8b86292cf41ccfc96c5de7165c1c53d5b4ac540c5bab9d1857acbe9eba5f1a0b"
dependencies = [
"proc-macro-hack",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -4505,7 +4505,7 @@ checksum = "33c85360c95e7d137454dc81d9a4ed2b8efd8fbe19cee57357b32b9771fccb67"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -4527,7 +4527,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -4934,9 +4934,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.48"
version = "2.0.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f"
checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed"
dependencies = [
"proc-macro2",
"quote",
@ -5048,7 +5048,7 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -5230,7 +5230,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -5823,7 +5823,7 @@ dependencies = [
"once_cell",
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
"wasm-bindgen-shared",
]
@ -5857,7 +5857,7 @@ checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
@ -5890,7 +5890,7 @@ checksum = "a5211b7550606857312bba1d978a8ec75692eae187becc5e680444fffc5e6f89"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]
@ -6583,7 +6583,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
"syn 2.0.77",
]
[[package]]

View file

@ -125,6 +125,8 @@ exclude = [
"api/xous-api-ticktimer",
# The "packing" crate is forked and is a separate workspace
"libs/mass-storage/packing",
# This directory is dedicated to out-of-tree tests and examples
"planning/",
]
[profile.release]

194
planning/rkyv-migration1/Cargo.lock generated Normal file
View file

@ -0,0 +1,194 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "bytes"
version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50"
[[package]]
name = "equivalent"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "indexmap"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "munge"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64142d38c84badf60abf06ff9bd80ad2174306a5b11bd4706535090a30a419df"
dependencies = [
"munge_macro",
]
[[package]]
name = "munge_macro"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bb5c1d8184f13f7d0ccbeeca0def2f9a181bce2624302793005f5ca8aa62e5e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
dependencies = [
"unicode-ident",
]
[[package]]
name = "ptr_meta"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe9e76f66d3f9606f44e45598d155cb13ecf09f4a28199e48daf8c8fc937ea90"
dependencies = [
"ptr_meta_derive",
]
[[package]]
name = "ptr_meta_derive"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca414edb151b4c8d125c12566ab0d74dc9cdba36fb80eb7b848c15f495fd32d1"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "quote"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rancor"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf5f7161924b9d1cea0e4cabc97c372cea92b5f927fc13c6bca67157a0ad947"
dependencies = [
"ptr_meta",
]
[[package]]
name = "rend"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31c1f1959e4db12c985c0283656be0925f1539549db1e47c4bd0b8b599e1ef7"
[[package]]
name = "rkyv"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c923eb995dc793cd26858a18f4bcce2df4b4a14a1ec767ea21a83b17b65f9aa"
dependencies = [
"bytes",
"hashbrown",
"indexmap",
"munge",
"ptr_meta",
"rancor",
"rend",
"rkyv_derive",
"tinyvec",
"uuid",
]
[[package]]
name = "rkyv-test1"
version = "0.1.0"
dependencies = [
"rkyv",
"xous",
]
[[package]]
name = "rkyv_derive"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67fe1bd2d15adf4f037438696f8efe7ad1eae0b10d53bb0946d6a93faaf96051"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
version = "2.0.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tinyvec"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "unicode-ident"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe"
[[package]]
name = "uuid"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314"
[[package]]
name = "xous"
version = "0.9.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ca3a121c4c2f9751469bbf19e777a9aaf15ad46a35d153a5e26d4b382e5171"
dependencies = [
"lazy_static",
]

View file

@ -0,0 +1,8 @@
[package]
name = "rkyv-test1"
version = "0.1.0"
edition = "2021"
[dependencies]
rkyv = { version = "0.8.5", default-features = false, features = ["std", "alloc"] } # , "bytecheck"
xous = "0.9.63"

View file

@ -0,0 +1,197 @@
use core::mem::MaybeUninit;
use rkyv::{
api::low::LowSerializer, deserialize, rancor::{Error, Panic, Strategy}, ser::{allocator::SubAllocator,
writer::Buffer as RkyvBuffer,
Positional,
}, with::{ArchiveWith, Identity, SerializeWith}, Archive, Deserialize, Place, Portable, Serialize
};
use std::marker::PhantomData;
use xous::{MemoryMessage, MemoryRange};
const PAGE_SIZE: usize = 4096;
const PAGE_POOL_SIZE: usize = 8;
// Create a "fake" memory pool of pages, just for testing
#[repr(C, align(4096))]
pub struct Pool {
pub bytes: [u8; PAGE_SIZE * PAGE_POOL_SIZE]
}
// A test structure with rkyv derives
#[derive(Archive, Deserialize, Serialize, Debug, PartialEq)]
#[rkyv(
// This will generate a PartialEq impl between our unarchived
// and archived types
compare(PartialEq),
// Derives can be passed through to the generated type:
derive(Debug),
)]
struct Test {
int: u8,
string: String,
option: Option<Vec<i32>>,
string2: String,
}
// The new Xous-IPC Buffer format
#[derive(Debug)]
pub struct Buffer<'buf> {
pages: MemoryRange,
alloc_at: usize,
pos: usize,
slice: &'buf mut [u8],
should_drop: bool,
memory_message: Option<&'buf mut MemoryMessage>,
}
// what is a safe number for this? empirically, 20 bytes seems to be the overhead we've measured
const RKYV_OVERHEAD: usize = 32;
// fake some allocateable memory, simply bump-allocated
static mut PAGE_POOL: Pool = Pool {bytes: [0u8; PAGE_SIZE * PAGE_POOL_SIZE]};
static mut PAGE_PTR: usize = 0;
pub fn map_memory(len: usize) -> MemoryRange {
assert!(len % 4096 == 0);
let address = unsafe{& PAGE_POOL.bytes[PAGE_PTR..PAGE_PTR + len]};
let mr = unsafe{MemoryRange::new(address.as_ptr() as usize, len).unwrap()};
unsafe{ PAGE_PTR += len };
mr
}
type Serializer<'a, 'b> =
LowSerializer<'a, RkyvBuffer<'b>, SubAllocator<'a>, Panic>;
impl<'buf> Buffer<'buf> {
pub fn new(len: usize) -> Self {
let len_to_page = (len + (PAGE_SIZE -1)) & !(PAGE_SIZE - 1);
// let alloc_start = len + RKYV_OVERHEAD;
let alloc_start = len_to_page - RKYV_OVERHEAD;
// Allocate enough memory to hold the requested data
let new_mem = map_memory(len_to_page);
Buffer {
pages: new_mem,
slice: unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), len_to_page) },
pos: 0,
alloc_at: alloc_start,
should_drop: true,
memory_message: None,
}
}
pub fn into_buf<F, T>(src: &T) -> Self
where
F: for<'a, 'b> SerializeWith<T, Serializer<'a, 'b>>,
{
struct Wrap<'a, F, T>(&'a T, PhantomData<F>);
impl<F, T> Archive for Wrap<'_, F, T>
where
F: ArchiveWith<T>,
{
type Archived = <F as ArchiveWith<T>>::Archived;
type Resolver = <F as ArchiveWith<T>>::Resolver;
fn resolve(
&self,
resolver: Self::Resolver,
out: Place<Self::Archived>,
) {
F::resolve_with(self.0, resolver, out)
}
}
impl<'a, 'b, F, T> Serialize<Serializer<'a, 'b>> for Wrap<'_, F, T>
where
F: SerializeWith<T, Serializer<'a, 'b>>,
{
fn serialize(
&self,
serializer: &mut Serializer<'a, 'b>,
) -> Result<Self::Resolver, Panic> {
F::serialize_with(self.0, serializer)
}
}
let mut xous_buf = Self::new(core::mem::size_of::<T>());
println!("alloc at: {}", xous_buf.alloc_at);
let (buf, scratch) = xous_buf.slice.split_at_mut(xous_buf.alloc_at);
let wrap = Wrap(src, PhantomData::<F>);
let writer = RkyvBuffer::from(buf);
let maybe_uninit_slice: &mut [MaybeUninit<u8>] = unsafe {
std::slice::from_raw_parts_mut(scratch.as_ptr() as *mut MaybeUninit<u8>, scratch.len())
};
let alloc = SubAllocator::new(maybe_uninit_slice);
let serbuf = rkyv::api::low::to_bytes_in_with_alloc::<_, _, Panic>(&wrap, writer, alloc).unwrap();
xous_buf.pos = serbuf.pos();
println!("pos: {}", xous_buf.pos);
println!("scratch: {:x?}", &scratch[..32]);
xous_buf
}
pub fn to_original<T, U, E>(&self) -> core::result::Result<T, E>
where
T: rkyv::Archive<Archived = U>,
U: Portable,
E: std::fmt::Debug, <T as Archive>::Archived: Deserialize<T, Strategy<rkyv::de::Pool, E>>
{
let r = unsafe{rkyv::access_unchecked::<U>(&self.slice[..self.pos])};
Ok(rkyv::deserialize::<T, E>(r).unwrap())
}
pub fn as_flat<T, U>(&self) -> core::result::Result<&U, ()>
where
T: rkyv::Archive<Archived = U>,
U: Portable
{
let r = unsafe{rkyv::access_unchecked::<U>(&self.slice[..self.pos])};
Ok(r)
}
}
fn main() {
println!("Size of Test: {}", core::mem::size_of::<Test>());
// with an alloc
let value = Test {
int: 42,
string: "The quick brown fox jumps over the lazy dogs".to_string(),
option: Some(vec![1, 2, 3, 4]),
string2: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.".to_string(),
};
let buf = Buffer::into_buf::<Identity, Test>(&value); // AsBox
let f = buf.as_flat::<Test, _>().unwrap();
println!("f: {:?}", f);
let t1 = buf.to_original::<Test, _, Error>().unwrap();
println!("t copy 1: {:?}", t1);
println!("buf.slice: {:x?}", &buf.slice[..buf.pos+1]);
let archived = unsafe{rkyv::access_unchecked::<ArchivedTest>(&buf.slice[..buf.pos])};
println!("archived: {:?}", archived);
let t = rkyv::deserialize::<Test, Error>(archived).unwrap();
println!("t: {:?}", t);
assert_eq!(t.string, value.string);
use rkyv::ser::allocator::Arena;
use rkyv::api::high::to_bytes_with_alloc;
let mut arena = Arena::new();
// let de = buf.to_original::<Test, rkyv::rancor::Error>().unwrap();
let bytes =
to_bytes_with_alloc::<_, Error>(&value, arena.acquire()).unwrap();
let archived =
unsafe { rkyv::access_unchecked::<ArchivedTest>(&bytes[..]) };
assert_eq!(archived, &value);
let deserialized = deserialize::<Test, Error>(archived).unwrap();
assert_eq!(deserialized.string2, value.string2);
}

266
planning/rkyv-migration2/Cargo.lock generated Normal file
View file

@ -0,0 +1,266 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "autocfg"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
[[package]]
name = "bytecheck"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50c8f430744b23b54ad15161fcbc22d82a29b73eacbe425fea23ec822600bc6f"
dependencies = [
"bytecheck_derive",
"ptr_meta",
"rancor",
"simdutf8",
]
[[package]]
name = "bytecheck_derive"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "523363cbe1df49b68215efdf500b103ac3b0fb4836aed6d15689a076eadb8fff"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.77",
]
[[package]]
name = "bytes"
version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50"
[[package]]
name = "equivalent"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "indexmap"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "munge"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64142d38c84badf60abf06ff9bd80ad2174306a5b11bd4706535090a30a419df"
dependencies = [
"munge_macro",
]
[[package]]
name = "munge_macro"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bb5c1d8184f13f7d0ccbeeca0def2f9a181bce2624302793005f5ca8aa62e5e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.77",
]
[[package]]
name = "num-derive"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "proc-macro2"
version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
dependencies = [
"unicode-ident",
]
[[package]]
name = "ptr_meta"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe9e76f66d3f9606f44e45598d155cb13ecf09f4a28199e48daf8c8fc937ea90"
dependencies = [
"ptr_meta_derive",
]
[[package]]
name = "ptr_meta_derive"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca414edb151b4c8d125c12566ab0d74dc9cdba36fb80eb7b848c15f495fd32d1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.77",
]
[[package]]
name = "quote"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rancor"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf5f7161924b9d1cea0e4cabc97c372cea92b5f927fc13c6bca67157a0ad947"
dependencies = [
"ptr_meta",
]
[[package]]
name = "rend"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31c1f1959e4db12c985c0283656be0925f1539549db1e47c4bd0b8b599e1ef7"
dependencies = [
"bytecheck",
]
[[package]]
name = "rkyv"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c923eb995dc793cd26858a18f4bcce2df4b4a14a1ec767ea21a83b17b65f9aa"
dependencies = [
"bytecheck",
"bytes",
"hashbrown",
"indexmap",
"munge",
"ptr_meta",
"rancor",
"rend",
"rkyv_derive",
"tinyvec",
"uuid",
]
[[package]]
name = "rkyv-test2"
version = "0.1.0"
dependencies = [
"num-derive",
"num-traits",
"rkyv",
"xous",
]
[[package]]
name = "rkyv_derive"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67fe1bd2d15adf4f037438696f8efe7ad1eae0b10d53bb0946d6a93faaf96051"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.77",
]
[[package]]
name = "simdutf8"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tinyvec"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "unicode-ident"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe"
[[package]]
name = "uuid"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314"
[[package]]
name = "xous"
version = "0.9.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ca3a121c4c2f9751469bbf19e777a9aaf15ad46a35d153a5e26d4b382e5171"
dependencies = [
"lazy_static",
]

View file

@ -0,0 +1,10 @@
[package]
name = "rkyv-test2"
version = "0.1.0"
edition = "2021"
[dependencies]
rkyv = { version = "0.8.5", default-features = false, features = ["std", "alloc", "bytecheck"] }
xous = { version = "0.9.63", features = ["forget-memory-messages"]}
num-derive = { version = "0.3.3", default-features = false }
num-traits = { version = "0.2.14", default-features = false }

View file

@ -0,0 +1,330 @@
use core::mem::MaybeUninit;
use std::marker::PhantomData;
use rkyv::{
api::low::LowSerializer,
rancor::{Panic, Strategy},
ser::{allocator::SubAllocator, writer::Buffer as RkyvBuffer, Positional},
with::{ArchiveWith, Identity, SerializeWith},
Archive, Deserialize, Place, Portable, Serialize,
};
use xous::{Error, MemoryAddress, MemoryMessage, MemoryRange, MemorySize, Message, Result, CID};
use crate::testcases::{DrawStyle, PixelColor, Point, Rectangle};
const PAGE_SIZE: usize = 4096;
const PAGE_POOL_SIZE: usize = 8;
// Create a "fake" memory pool of pages, just for testing
#[repr(C, align(4096))]
pub struct Pool {
pub bytes: [u8; PAGE_SIZE * PAGE_POOL_SIZE],
}
// The new Xous-IPC Buffer format
#[derive(Debug)]
pub struct Buffer<'buf> {
pages: MemoryRange,
used: usize,
slice: &'buf mut [u8],
should_drop: bool,
memory_message: Option<&'buf mut MemoryMessage>,
}
// fake some allocateable memory, simply bump-allocated
static mut PAGE_POOL: Pool = Pool { bytes: [0u8; PAGE_SIZE * PAGE_POOL_SIZE] };
static mut PAGE_PTR: usize = 0;
pub fn map_memory(len: usize) -> MemoryRange {
assert!(len % 4096 == 0);
let address = unsafe { &PAGE_POOL.bytes[PAGE_PTR..PAGE_PTR + len] };
let mr = unsafe { MemoryRange::new(address.as_ptr() as usize, len).unwrap() };
unsafe { PAGE_PTR += len };
mr
}
pub fn unmap_memory(_pages: MemoryRange) -> core::result::Result<(), xous::Error> {
// dummy function for testing
Ok(())
}
pub fn send_message(connection: CID, mut message: Message) -> core::result::Result<Result, Error> {
let body = message.memory_message_mut().expect("test routine only handles mutable memory message types");
let mut msg = xous::MessageEnvelope {
sender: xous::sender::Sender::from_usize(1), // fake
body: xous::Message::MutableBorrow(xous::MemoryMessage {
id: body.id,
buf: body.buf,
offset: body.offset,
valid: body.valid,
}),
};
// don't actually send anything, just do the unwrap to receive in here and print the values
match connection {
1 => {
// emulated TextView
let mut buffer =
unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut tv = buffer.to_original::<crate::testcases::TextView, _>().unwrap();
println!("MSG: TextView");
println!("Contents: {:?}", tv);
tv.bounds_computed = Some(Rectangle {
tl: Point { x: 42, y: 42 },
br: Point { x: 420, y: 69 },
style: DrawStyle { fill_color: None, stroke_color: Some(PixelColor::Dark), stroke_width: 3 },
});
buffer.replace(tv).unwrap();
let ret = Result::MemoryReturned(body.offset, body.valid);
println!("returning with {:?}", ret);
Ok(ret)
}
_ => Err(Error::InternalError),
}
}
type Serializer<'a, 'b> = LowSerializer<'a, RkyvBuffer<'b>, SubAllocator<'a>, Panic>;
impl<'buf> Buffer<'buf> {
pub fn new(len: usize) -> Self {
let len_to_page = (len + (PAGE_SIZE - 1)) & !(PAGE_SIZE - 1);
// Allocate enough memory to hold the requested data
let new_mem = map_memory(len_to_page);
Buffer {
pages: new_mem,
slice: unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), len_to_page) },
used: 0,
should_drop: true,
memory_message: None,
}
}
fn into_buf_inner<F, T>(src: &T) -> Self
where
F: for<'a, 'b> SerializeWith<T, Serializer<'a, 'b>>,
{
struct Wrap<'a, F, T>(&'a T, PhantomData<F>);
impl<F, T> Archive for Wrap<'_, F, T>
where
F: ArchiveWith<T>,
{
type Archived = <F as ArchiveWith<T>>::Archived;
type Resolver = <F as ArchiveWith<T>>::Resolver;
fn resolve(&self, resolver: Self::Resolver, out: Place<Self::Archived>) {
F::resolve_with(self.0, resolver, out)
}
}
impl<'a, 'b, F, T> Serialize<Serializer<'a, 'b>> for Wrap<'_, F, T>
where
F: SerializeWith<T, Serializer<'a, 'b>>,
{
fn serialize(
&self,
serializer: &mut Serializer<'a, 'b>,
) -> core::result::Result<Self::Resolver, Panic> {
F::serialize_with(self.0, serializer)
}
}
let mut xous_buf = Self::new(core::mem::size_of::<T>());
let mut scratch = [MaybeUninit::<u8>::uninit(); 256];
let wrap = Wrap(src, PhantomData::<F>);
let writer = RkyvBuffer::from(&mut xous_buf.slice[..]);
let alloc = SubAllocator::new(&mut scratch);
let serbuf = rkyv::api::low::to_bytes_in_with_alloc::<_, _, Panic>(&wrap, writer, alloc).unwrap();
xous_buf.used = serbuf.pos();
println!("pos: {}", xous_buf.used);
println!("scratch: {:x?}", &scratch[..16]);
xous_buf
}
pub fn into_buf<T>(src: &T) -> Self
where
T: for<'b, 'a> rkyv::Serialize<rkyv::rancor::Strategy<rkyv::ser::Serializer<rkyv::ser::writer::Buffer<'b>, rkyv::ser::allocator::SubAllocator<'a>, ()>, rkyv::rancor::Panic>> {
Buffer::into_buf_inner::<Identity, T>(src)
}
fn replace_inner<F, T>(&mut self, src: T) -> core::result::Result<(), &'static str>
where
F: for<'a, 'b> SerializeWith<T, Serializer<'a, 'b>>,
{
struct Wrap<'a, F, T>(&'a T, PhantomData<F>);
impl<F, T> Archive for Wrap<'_, F, T>
where
F: ArchiveWith<T>,
{
type Archived = <F as ArchiveWith<T>>::Archived;
type Resolver = <F as ArchiveWith<T>>::Resolver;
fn resolve(&self, resolver: Self::Resolver, out: Place<Self::Archived>) {
F::resolve_with(self.0, resolver, out)
}
}
impl<'a, 'b, F, T> Serialize<Serializer<'a, 'b>> for Wrap<'_, F, T>
where
F: SerializeWith<T, Serializer<'a, 'b>>,
{
fn serialize(
&self,
serializer: &mut Serializer<'a, 'b>,
) -> core::result::Result<Self::Resolver, Panic> {
F::serialize_with(self.0, serializer)
}
}
// 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 scratch = [MaybeUninit::<u8>::uninit(); 256];
let wrap = Wrap(&src, PhantomData::<F>);
let writer = RkyvBuffer::from(&mut copied_slice[..]);
let alloc = SubAllocator::new(&mut scratch);
let serbuf = rkyv::api::low::to_bytes_in_with_alloc::<_, _, Panic>(&wrap, writer, alloc).unwrap();
self.used = serbuf.pos();
if let Some(ref mut msg) = self.memory_message.as_mut() {
msg.offset = MemoryAddress::new(self.used);
}
Ok(())
}
#[allow(dead_code)]
pub fn replace<T>(&mut self, src: T) -> core::result::Result<(), &'static str>
where
T: for<'b, 'a> rkyv::Serialize<rkyv::rancor::Strategy<rkyv::ser::Serializer<rkyv::ser::writer::Buffer<'b>, rkyv::ser::allocator::SubAllocator<'a>, ()>, rkyv::rancor::Panic>>
{
self.replace_inner::<Identity, T>(src)
}
pub fn to_original<T, U>(&self) -> core::result::Result<T, ()>
where
T: rkyv::Archive<Archived = U>,
U: Portable,
<T as Archive>::Archived: Deserialize<T, Strategy<rkyv::de::Pool, rkyv::rancor::Error>>,
{
let r = unsafe { rkyv::access_unchecked::<U>(&self.slice[..self.used]) };
Ok(rkyv::deserialize::<T, rkyv::rancor::Error>(r).unwrap())
}
pub fn as_flat<T, U>(&self) -> core::result::Result<&U, ()>
where
T: rkyv::Archive<Archived = U>,
U: Portable,
{
let r = unsafe { rkyv::access_unchecked::<U>(&self.slice[..self.used]) };
Ok(r)
}
pub fn used(&self) -> usize { self.used }
/// Perform a mutable lend of this Buffer to the server.
pub fn lend_mut(&mut self, connection: CID, id: u32) -> core::result::Result<Result, Error> {
let msg = MemoryMessage {
id: id as usize,
buf: self.pages,
offset: MemoryAddress::new(self.used),
valid: MemorySize::new(self.pages.len()),
};
// Update the offset pointer if the server modified it.
println!("Just before send_message");
let result = send_message(connection, Message::MutableBorrow(msg));
println!("result: {:?}", result);
if let Ok(Result::MemoryReturned(offset, _valid)) = result {
self.used = offset.map_or(0, |v| v.get());
}
result
}
// 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) {
(self.pages.as_ptr() as usize, self.pages.len(), self.used)
}
// 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");
Buffer {
pages: mem,
slice: core::slice::from_raw_parts_mut(mem.as_mut_ptr(), mem.len()),
used: offset,
should_drop: false,
memory_message: None,
}
}
#[allow(dead_code)]
pub unsafe fn from_memory_message(mem: &'buf MemoryMessage) -> Self {
Buffer {
pages: mem.buf,
slice: core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len()),
used: mem.offset.map_or(0, |v| v.get()),
should_drop: false,
memory_message: None,
}
}
#[allow(dead_code)]
pub unsafe fn from_memory_message_mut(mem: &'buf mut MemoryMessage) -> Self {
Buffer {
pages: mem.buf,
slice: core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len()),
used: mem.offset.map_or(0, |v| v.get()),
should_drop: false,
memory_message: Some(mem),
}
}
}
impl<'a> core::convert::AsRef<[u8]> for Buffer<'a> {
fn as_ref(&self) -> &[u8] { &self.slice[..self.used] }
}
impl<'a> core::convert::AsMut<[u8]> for Buffer<'a> {
fn as_mut(&mut self) -> &mut [u8] { &mut self.slice[..self.used] }
}
impl<'a> core::ops::Deref for Buffer<'a> {
type Target = [u8];
fn deref(&self) -> &Self::Target { &*(&self.slice[..self.used]) }
}
impl<'a> core::ops::DerefMut for Buffer<'a> {
fn deref_mut(&mut self) -> &mut Self::Target { &mut *(&mut self.slice[..self.used]) }
}
impl<'a> Drop for Buffer<'a> {
fn drop(&mut self) {
if self.should_drop {
unmap_memory(self.pages).expect("Buffer: failed to drop memory");
}
}
}

View file

@ -0,0 +1,90 @@
mod buffer;
use buffer::*;
mod testcases;
use rkyv::{deserialize, rancor::Error, Archive, Deserialize, Serialize};
use testcases::*;
// A test structure with rkyv derives
#[derive(Archive, Deserialize, Serialize, Debug, PartialEq)]
#[rkyv(
// This will generate a PartialEq impl between our unarchived
// and archived types
compare(PartialEq),
// Derives can be passed through to the generated type:
derive(Debug),
)]
struct Test {
int: u8,
string: String,
option: Option<Vec<i32>>,
string2: String,
}
fn main() {
println!("Size of Test: {}", core::mem::size_of::<Test>());
// with an alloc
let value = Test {
int: 42,
string: "The quick brown fox jumps over the lazy dogs".to_string(),
option: Some(vec![1, 2, 3, 4]),
string2: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.".to_string(),
};
let buf = Buffer::into_buf(&value); // AsBox
let f = buf.as_flat::<Test, _>().unwrap();
println!("f: {:?}", f);
let t1 = buf.to_original::<Test, _>().unwrap();
println!("t copy 1: {:?}", t1);
println!("buf.slice: {:x?}", &buf[..buf.used()]);
let archived = unsafe { rkyv::access_unchecked::<ArchivedTest>(&buf) };
println!("archived: {:?}", archived);
let t = rkyv::deserialize::<Test, Error>(archived).unwrap();
println!("t: {:?}", t);
assert_eq!(t.string, value.string);
use rkyv::api::high::to_bytes_with_alloc;
use rkyv::ser::allocator::Arena;
let mut arena = Arena::new();
// let de = buf.to_original::<Test, rkyv::rancor::Error>().unwrap();
let bytes = to_bytes_with_alloc::<_, Error>(&value, arena.acquire()).unwrap();
let archived = unsafe { rkyv::access_unchecked::<ArchivedTest>(&bytes[..]) };
assert_eq!(archived, &value);
let deserialized = deserialize::<Test, Error>(archived).unwrap();
assert_eq!(deserialized.string2, value.string2);
let mut tv = testcases::TextView::new(
Gid { gid: [6, 7, 8, 9] },
TextBounds::BoundingBox(Rectangle {
tl: Point { x: 0, y: 0 },
br: Point { x: 100, y: 100 },
style: DrawStyle { fill_color: None, stroke_color: None, stroke_width: 1 },
}),
);
// make a lorem ipsum text
tv.text.push_str(&value.string2);
println!("Tv bounds computed before: {:?}", tv.bounds_computed);
let mut tv_buf = Buffer::into_buf(&tv);
match tv_buf.lend_mut(1, 1) {
Ok(r) => {
println!("Returned {:?}", r);
let mut tv_orig = tv_buf.to_original::<TextView, _>().unwrap();
println!("bounds_computed: {:?}", tv_orig.bounds_computed);
assert_eq!(tv_orig.bounds_computed.unwrap().tl.x, 42);
assert_eq!(tv_orig.bounds_computed.unwrap().tl.y, 42);
println!("now embedded in routine");
draw_textview(1, &mut tv_orig).ok();
}
Err(e) => {
println!("Test failed with error {:?}", e);
panic!("test failed");
}
}
}

View file

@ -0,0 +1,214 @@
use num_traits::*;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Point {
pub x: i16,
pub y: i16,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum PixelColor {
Dark,
Light,
}
impl From<bool> for PixelColor {
fn from(pc: bool) -> Self { if pc { PixelColor::Dark } else { PixelColor::Light } }
}
impl From<PixelColor> for bool {
fn from(pc: PixelColor) -> bool { if pc == PixelColor::Dark { true } else { false } }
}
impl From<usize> for PixelColor {
fn from(pc: usize) -> Self { if pc == 0 { PixelColor::Light } else { PixelColor::Dark } }
}
impl From<PixelColor> for usize {
fn from(pc: PixelColor) -> usize { if pc == PixelColor::Light { 0 } else { 1 } }
}
/// Style properties for an object
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct DrawStyle {
/// Fill colour of the object
pub fill_color: Option<PixelColor>,
/// Stroke (border/line) color of the object
pub stroke_color: Option<PixelColor>,
/// Stroke width
pub stroke_width: i16,
}
#[derive(Debug, Clone, Copy, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Rectangle {
/// Top left point of the rect
pub tl: Point,
/// Bottom right point of the rect
pub br: Point,
/// Drawing style
pub style: DrawStyle,
}
/// coordinates are local to the canvas, not absolute to the screen
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum TextBounds {
// fixed width and height in a rectangle
BoundingBox(Rectangle),
// fixed width, grows up from bottom right
GrowableFromBr(Point, u16),
// fixed width, grows down from top left
GrowableFromTl(Point, u16),
// fixed width, grows up from bottom left
GrowableFromBl(Point, u16),
// fixed width, grows down from top right
GrowableFromTr(Point, u16),
// fixed width, centered aligned top
CenteredTop(Rectangle),
// fixed width, centered aligned bottom
CenteredBot(Rectangle),
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Gid {
/// a 128-bit random identifier for graphical objects
pub gid: [u32; 4],
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, PartialEq)]
// operations that may be requested of a TextView when sent to GAM
pub enum TextOp {
Nop,
Render,
ComputeBounds, // maybe we don't need this
}
/// Style options for Latin script fonts
#[derive(Copy, Clone, Debug, PartialEq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum GlyphStyle {
Small = 0,
Regular = 1,
Bold = 2,
Monospace = 3,
Cjk = 4,
Large = 5,
ExtraLarge = 6,
Tall = 7,
}
/// Point specifies a pixel coordinate
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Pt {
pub x: i16,
pub y: i16,
}
#[derive(Copy, Clone, Debug, PartialEq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Cursor {
pub pt: Pt,
pub line_height: usize,
}
#[derive(Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Debug)]
pub struct TextView {
// 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.
operation: TextOp,
canvas: Gid, // GID of the canvas to draw on
pub clip_rect: Option<Rectangle>, /* this is set by the GAM to the canvas' clip_rect; needed by gfx
* for drawing. Note this is in screen coordinates. */
pub untrusted: bool, // render content with random stipples to indicate the strings within are untrusted
pub token: Option<[u32; 4]>, // optional 128-bit token which is presented to prove a field's trustability
pub invert: bool, // only trusted, token-validated TextViews will have the invert bit respected
// offsets for text drawing -- exactly one of the following options should be specified
// note that the TextBounds coordinate system is local to the canvas, not the screen
pub bounds_hint: TextBounds,
pub bounds_computed: Option<Rectangle>, /* is Some(Rectangle) if bounds have been computed and text
* has not been modified. This is local to the canvas. */
pub overflow: Option<bool>, /* indicates if the text has overflowed the canvas, set by the drawing
* routine */
dry_run: bool, /* callers should not set; use TexOp to select. gam-side bookkeepping, set to true if
* no drawing is desired and we just want to compute the bounds */
pub style: GlyphStyle,
pub cursor: Cursor,
pub insertion: Option<i32>, // this is the insertion point offset, if it's to be drawn, on the string
pub ellipsis: bool,
pub draw_border: bool,
pub clear_area: bool, // you almost always want this to be true
pub border_width: u16,
pub rounded_border: Option<u16>, // radius of the rounded border, if applicable
pub margin: Point,
// this field specifies the beginning and end of a "selected" region of text
pub selected: Option<[u32; 2]>,
// this field tracks the state of a busy animation, if `Some`
pub busy_animation_state: Option<u32>,
pub text: String,
}
pub const TEXTVIEW_DEFAULT_STYLE: GlyphStyle = GlyphStyle::Regular;
#[allow(dead_code)]
impl Cursor {
// Make a new Cursor. When in doubt, set line_height = 0.
pub fn new(x: i16, y: i16, line_height: usize) -> Cursor { Cursor { pt: Pt { x, y }, line_height } }
}
impl TextView {
pub fn new(canvas: Gid, bounds_hint: TextBounds) -> Self {
TextView {
canvas,
operation: TextOp::Nop,
untrusted: true,
token: None,
invert: false,
clip_rect: None,
bounds_hint,
bounds_computed: None,
style: TEXTVIEW_DEFAULT_STYLE,
text: String::new(),
cursor: Cursor::new(0, 0, 0),
insertion: None,
ellipsis: false,
draw_border: true,
border_width: 1,
rounded_border: None,
margin: Point { x: 4, y: 4 },
selected: None,
clear_area: true,
overflow: None,
dry_run: false,
busy_animation_state: None,
}
}
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum Opcode {
/// draws a textview
DrawTextView, //(TextView),
Quit,
}
pub fn draw_textview(conn: xous::CID, tv: &mut TextView) -> Result<(), xous::Error> {
let mut buf = crate::Buffer::into_buf(tv);
buf.lend_mut(conn, Opcode::DrawTextView.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let tvr = buf.to_original::<TextView, _>().unwrap();
tv.bounds_computed = tvr.bounds_computed;
tv.cursor = tvr.cursor;
tv.overflow = tvr.overflow;
tv.busy_animation_state = tvr.busy_animation_state;
Ok(())
}