port rkyv ser/de usage in mtxchat

This commit is contained in:
bunnie 2024-09-23 17:00:16 +08:00
parent 3ce6baa202
commit c699e06c5a
4 changed files with 41 additions and 61 deletions

View file

@ -85,7 +85,7 @@ pub struct Post {
pub dialogue_id: String, pub dialogue_id: String,
pub author: String, pub author: String,
pub timestamp: u64, pub timestamp: u64,
pub text: String<POST_TEXT_MAX>, pub text: String,
pub attach_url: Option<String>, pub attach_url: Option<String>,
} }

View file

@ -2,7 +2,7 @@ use std::thread;
use ime_plugin_api::*; use ime_plugin_api::*;
use num_traits::*; use num_traits::*;
use xous::{msg_scalar_unpack, CID}; use xous::{CID, msg_scalar_unpack};
use xous_ipc::Buffer; use xous_ipc::Buffer;
pub(crate) const SERVER_NAME_ICONTRAY: &'static str = "_chat icon tray plugin_"; pub(crate) const SERVER_NAME_ICONTRAY: &'static str = "_chat icon tray plugin_";
@ -83,7 +83,7 @@ pub(crate) fn server(_cid: Option<CID>, icons: [&str; 4]) {
// every key press, the four slots get queried // every key press, the four slots get queried
prediction.string.clear(); prediction.string.clear();
if prediction.index < icons.len() as u32 { if prediction.index < icons.len() as u32 {
prediction.string.append(icons[prediction.index as usize]).ok(); prediction.string.push_str(icons[prediction.index as usize]);
prediction.valid = true; prediction.valid = true;
} else { } else {
prediction.valid = false; prediction.valid = false;

View file

@ -4,7 +4,7 @@ pub mod icontray;
pub mod ui; pub mod ui;
use std::convert::TryInto; use std::convert::TryInto;
use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc}; use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering};
use std::thread; use std::thread;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@ -13,9 +13,9 @@ use gam::MenuItem;
use graphics_server::api::GlyphStyle; use graphics_server::api::GlyphStyle;
use graphics_server::{Point, Rectangle, TextBounds, TextView}; use graphics_server::{Point, Rectangle, TextBounds, TextView};
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
use ui::VisualProperties;
pub use ui::BUSY_ANIMATION_RATE_MS; pub use ui::BUSY_ANIMATION_RATE_MS;
use xous::{msg_scalar_unpack, Error, CID, SID}; use ui::VisualProperties;
use xous::{CID, Error, SID, msg_scalar_unpack};
use xous_ipc::Buffer; use xous_ipc::Buffer;
/// Create a TextView with the default properties common to all text bubbles. /// Create a TextView with the default properties common to all text bubbles.
@ -231,8 +231,8 @@ impl Chat {
None => None, None => None,
}, },
}; };
post.author.append(author).unwrap(); post.author.push_str(author);
post.text.append(text).unwrap(); post.text.push_str(text);
match Buffer::into_buf(post) { match Buffer::into_buf(post) {
Ok(buf) => buf.send(self.cid, ChatOp::PostAdd as u32).map(|_| ()), Ok(buf) => buf.send(self.cid, ChatOp::PostAdd as u32).map(|_| ()),
Err(_) => Err(xous::Error::InternalError), Err(_) => Err(xous::Error::InternalError),
@ -261,7 +261,7 @@ impl Chat {
/// Error if unable to send the msg to the Chat UI server /// Error if unable to send the msg to the Chat UI server
pub fn post_find(&self, author: &str, timestamp: u64) -> Result<Option<usize>, Error> { pub fn post_find(&self, author: &str, timestamp: u64) -> Result<Option<usize>, Error> {
let mut find = Find { author: String::new(), timestamp, key: None }; let mut find = Find { author: String::new(), timestamp, key: None };
find.author.append(author).unwrap(); find.author.push_str(author);
match Buffer::into_buf(find) { match Buffer::into_buf(find) {
Ok(mut buf) => match buf.lend_mut(self.cid, ChatOp::PostFind as u32) { Ok(mut buf) => match buf.lend_mut(self.cid, ChatOp::PostFind as u32) {
Ok(..) => { Ok(..) => {

View file

@ -1,20 +1,15 @@
use std::cmp::min; use std::cmp::min;
use std::convert::TryFrom;
use std::fmt::Write as TextWrite; use std::fmt::Write as TextWrite;
use std::io::{Error, ErrorKind, Read, Write}; use std::io::{Error, ErrorKind, Read, Write};
use dialogue::{post::Post, Dialogue}; use dialogue::{Dialogue, post::Post};
use gam::{menu_matic, MenuMatic, UxRegistration}; use gam::{MenuMatic, UxRegistration, menu_matic};
use graphics_server::api::GlyphStyle; use graphics_server::api::GlyphStyle;
use graphics_server::{DrawStyle, Gid, Line, PixelColor, Point, Rectangle, TextBounds, TextView}; use graphics_server::{DrawStyle, Gid, Line, PixelColor, Point, Rectangle, TextBounds, TextView};
use locales::t; use locales::t;
use modals::Modals; use modals::Modals;
use rkyv::de::deserializers::AllocDeserializer;
use rkyv::ser::serializers::WriteSerializer;
use rkyv::ser::Serializer;
use rkyv::Deserialize;
use ticktimer_server::Ticktimer; use ticktimer_server::Ticktimer;
use xous::{MessageEnvelope, CID}; use xous::{CID, MessageEnvelope};
use xous_names::XousNames; use xous_names::XousNames;
use super::*; use super::*;
@ -40,7 +35,7 @@ pub struct VisualProperties {
pub(crate) struct Ui { pub(crate) struct Ui {
// optional structures that indicate new input to the Chat loop per iteration // optional structures that indicate new input to the Chat loop per iteration
// an input string // an input string
pub input: Option<String<{ POST_TEXT_MAX }>>, pub input: Option<String>,
// messages from other servers // messages from other servers
msg: Option<MessageEnvelope>, msg: Option<MessageEnvelope>,
@ -193,25 +188,29 @@ impl Ui {
Ok(mut pddb_key) => { Ok(mut pddb_key) => {
let mut bytes = [0u8; dialogue::MAX_BYTES + 2]; let mut bytes = [0u8; dialogue::MAX_BYTES + 2];
match pddb_key.read(&mut bytes) { match pddb_key.read(&mut bytes) {
Ok(_) => { Ok(pos) => {
// extract pos u16 from the first 2 bytes let archive = unsafe {
let pos: u16 = u16::from_be_bytes([bytes[0], bytes[1]]); rkyv::access_unchecked::<dialogue::ArchivedDialogue>(&bytes[..pos])
let pos: usize = pos.into();
// deserialize the Dialogue
let archive = unsafe { rkyv::archived_value::<Dialogue>(&bytes, pos) };
self.dialogue = match archive.deserialize(&mut AllocDeserializer {}) {
Ok(dialogue) => {
// show most recent posts onscreen
self.layout_selected = dialogue.post_last();
self.layout_range.clear();
self.layout_topdown = false;
Some(dialogue)
}
Err(e) => {
log::warn!("failed to deserialize Dialogue {}:{} {}", dict, key, e);
None
}
}; };
self.dialogue =
match rkyv::deserialize::<Dialogue, rkyv::rancor::Error>(archive) {
Ok(dialogue) => {
// show most recent posts onscreen
self.layout_selected = dialogue.post_last();
self.layout_range.clear();
self.layout_topdown = false;
Some(dialogue)
}
Err(e) => {
log::warn!(
"failed to deserialize Dialogue {}:{} {}",
dict,
key,
e
);
None
}
};
log::debug!("get '{}' = '{:?}'", key, self.dialogue); log::debug!("get '{}' = '{:?}'", key, self.dialogue);
} }
Err(e) => log::warn!("failed to read {}: {e}", key), Err(e) => log::warn!("failed to read {}: {e}", key),
@ -238,22 +237,7 @@ impl Ui {
let hint = Some(dialogue::MAX_BYTES + 2); let hint = Some(dialogue::MAX_BYTES + 2);
match self.pddb.get(&dict, &key, None, true, true, hint, None::<fn()>) { match self.pddb.get(&dict, &key, None, true, true, hint, None::<fn()>) {
Ok(mut pddb_key) => { Ok(mut pddb_key) => {
let mut buf = Vec::<u8>::new(); let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(dialogue).unwrap();
// reserve 2 bytes to hold a u16 (see below)
let reserved = 2;
buf.push(0u8);
buf.push(0u8);
// serialize the Dialogue
let mut serializer = WriteSerializer::with_pos(buf, reserved);
let pos = serializer.serialize_value(dialogue).unwrap();
let mut bytes = serializer.into_inner();
// copy pop u16 into the first 2 bytes to enable the rkyv archive to be deserialised
let pos: u16 = u16::try_from(pos).expect("data > u16");
let pos_bytes = pos.to_be_bytes();
bytes[0] = pos_bytes[0];
bytes[1] = pos_bytes[1];
match pddb_key.write(&bytes) { match pddb_key.write(&bytes) {
Ok(len) => { Ok(len) => {
self.pddb.sync().ok(); self.pddb.sync().ok();
@ -707,15 +691,11 @@ impl Ui {
self.gam self.gam
.draw_rectangle( .draw_rectangle(
self.vp.canvas, self.vp.canvas,
Rectangle::new_with_style( Rectangle::new_with_style(Point::new(0, 0), self.vp.total_screensize, DrawStyle {
Point::new(0, 0), fill_color: Some(PixelColor::Light),
self.vp.total_screensize, stroke_color: None,
DrawStyle { stroke_width: 0,
fill_color: Some(PixelColor::Light), }),
stroke_color: None,
stroke_width: 0,
},
),
) )
.expect("can't clear canvas area"); .expect("can't clear canvas area");