AppFlowy/rust-lib/flowy-ws/src/msg.rs

57 lines
1.5 KiB
Rust
Raw Normal View History

2021-09-18 14:32:00 +00:00
use bytes::Bytes;
2021-09-23 09:50:28 +00:00
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
2021-09-18 14:32:00 +00:00
use std::convert::{TryFrom, TryInto};
2021-09-23 09:50:28 +00:00
use tokio_tungstenite::tungstenite::Message as TokioMessage;
2021-09-18 14:32:00 +00:00
// Opti: using four bytes of the data to represent the source
2021-09-18 14:32:00 +00:00
#[derive(ProtoBuf, Debug, Clone, Default)]
pub struct WsMessage {
#[pb(index = 1)]
pub module: WsModule,
2021-09-18 14:32:00 +00:00
#[pb(index = 2)]
pub data: Vec<u8>,
}
2021-09-23 09:50:28 +00:00
#[derive(ProtoBuf_Enum, Debug, Clone, Eq, PartialEq, Hash)]
pub enum WsModule {
2021-09-23 09:50:28 +00:00
Doc = 0,
}
impl std::default::Default for WsModule {
fn default() -> Self { WsModule::Doc }
2021-09-23 09:50:28 +00:00
}
impl ToString for WsModule {
2021-09-23 09:50:28 +00:00
fn to_string(&self) -> String {
match self {
WsModule::Doc => "0".to_string(),
2021-09-23 09:50:28 +00:00
}
}
}
impl std::convert::Into<TokioMessage> for WsMessage {
fn into(self) -> TokioMessage {
2021-09-18 14:32:00 +00:00
let result: Result<Bytes, ::protobuf::ProtobufError> = self.try_into();
match result {
2021-09-23 09:50:28 +00:00
Ok(bytes) => TokioMessage::Binary(bytes.to_vec()),
2021-09-18 14:32:00 +00:00
Err(e) => {
log::error!("WsMessage serialize error: {:?}", e);
2021-09-23 09:50:28 +00:00
TokioMessage::Binary(vec![])
2021-09-18 14:32:00 +00:00
},
}
}
}
2021-09-23 09:50:28 +00:00
impl std::convert::From<TokioMessage> for WsMessage {
fn from(value: TokioMessage) -> Self {
2021-09-18 14:32:00 +00:00
match value {
2021-09-23 09:50:28 +00:00
TokioMessage::Binary(bytes) => WsMessage::try_from(Bytes::from(bytes)).unwrap(),
2021-09-18 14:32:00 +00:00
_ => {
log::error!("WsMessage deserialize failed. Unsupported message");
WsMessage::default()
},
}
}
}