1use crate::error::Error;
2use crate::frame::{Frame, OpCode};
3
4#[derive(Debug, Clone, PartialEq)]
5pub enum Message {
6 Text(String),
7 Binary(Vec<u8>),
8}
9
10impl Message {
11 pub fn from_frame(frame: Frame) -> Result<Self, Error> {
13 match frame.opcode {
14 OpCode::Text => Ok(Message::Text(String::from_utf8(frame.payload)?)),
15 OpCode::Binary => Ok(Message::Binary(frame.payload)),
16 _ => Err(Error::InvalidOpcode),
17 }
18 }
19
20 pub fn as_binary(&self) -> Vec<u8> {
22 match self {
23 Message::Text(text) => text.as_bytes().to_vec(),
24 Message::Binary(data) => data.clone(),
25 }
26 }
27
28 pub fn as_text(&self) -> Result<String, Error> {
30 match self {
31 Message::Text(text) => Ok(text.clone()),
32 Message::Binary(data) => Ok(String::from_utf8(data.clone())?),
33 }
34 }
35}