Refactor {send,read}_message() #11

Merged
eNV25 merged 2 commits from main into main 2024-02-16 09:53:21 +01:00

View file

@ -1,7 +1,6 @@
use std::io::{self, Read, Write};
use serde::Deserialize; use serde::Deserialize;
use std::io;
use std::io::BufReader;
use std::io::{Read, Write};
use crate::error::FF2MpvError; use crate::error::FF2MpvError;
@ -22,23 +21,23 @@ pub fn get_mpv_message() -> Result<FF2MpvMessage, FF2MpvError> {
} }
fn read_message() -> Result<String, io::Error> { fn read_message() -> Result<String, io::Error> {
let mut stdin = io::stdin(); let mut stdin = io::stdin().lock();
let mut buf: [u8; 4] = [0; 4];
stdin.read_exact(&mut buf)?;
let length = u32::from_ne_bytes(buf); let mut len = 0_u32.to_ne_bytes();
let mut reader = BufReader::new(stdin.take(length as u64)); stdin.read_exact(&mut len)?;
let len = u32::from_ne_bytes(len);
let mut string = String::with_capacity(length as usize); let mut reader = stdin.take(len as u64);
reader.read_to_string(&mut string)?; let mut msg = String::with_capacity(len as usize);
Ok(string) reader.read_to_string(&mut msg)?;
Ok(msg)
} }
fn send_message(message: &str) -> Result<(), io::Error> { fn send_message(message: &str) -> Result<(), io::Error> {
let length = (message.len() as u32).to_ne_bytes(); let length = (message.len() as u32).to_ne_bytes();
let message = message.as_bytes(); let message = message.as_bytes();
let mut stdout = io::stdout(); let mut stdout = io::stdout().lock();
stdout.write_all(&length)?; stdout.write_all(&length)?;
stdout.write_all(message)?; stdout.write_all(message)?;
Ok(()) Ok(())