Parsing frames.
parent
6dc4c28bb5
commit
7ee1a91549
@ -1,4 +1,5 @@
|
||||
mod command;
|
||||
mod mpv_framed;
|
||||
mod mpvctl;
|
||||
|
||||
pub use mpvctl::MpvCtl;
|
||||
|
@ -0,0 +1,58 @@
|
||||
use bytes::{Buf, BytesMut};
|
||||
use std::io::{self, Cursor};
|
||||
use tokio::{io::AsyncReadExt, net::unix::OwnedReadHalf};
|
||||
|
||||
pub struct MpvFramed {
|
||||
buffer: BytesMut,
|
||||
socket_read: OwnedReadHalf,
|
||||
}
|
||||
|
||||
impl MpvFramed {
|
||||
pub fn new(socket_read: OwnedReadHalf) -> Self {
|
||||
MpvFramed {
|
||||
socket_read,
|
||||
buffer: BytesMut::with_capacity(4 * 1024),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn read_frame(
|
||||
&mut self,
|
||||
) -> Result<Option<serde_json::Value>, Box<dyn std::error::Error>> {
|
||||
//
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn parse_frame(&mut self) -> Result<Option<serde_json::Value>, Box<dyn std::error::Error>> {
|
||||
let mut cursor = Cursor::new(&self.buffer[..]);
|
||||
if Self::has_frame(&mut cursor) {
|
||||
let len = cursor.position() as usize;
|
||||
cursor.set_position(0);
|
||||
let frame: serde_json::Value = serde_json::from_slice(&cursor.get_ref()[0..len])?;
|
||||
self.buffer.advance(len);
|
||||
return Ok(Some(frame));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn has_frame(cursor: &mut Cursor<&[u8]>) -> bool {
|
||||
loop {
|
||||
match Self::next_byte(cursor) {
|
||||
Some(nb) if nb == b'\n' => {
|
||||
return true;
|
||||
}
|
||||
Some(_) => (),
|
||||
None => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn next_byte(cursor: &mut Cursor<&[u8]>) -> Option<u8> {
|
||||
if !cursor.has_remaining() {
|
||||
None
|
||||
} else {
|
||||
Some(cursor.get_u8())
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue