Refactor {send,read}_message() (#11)

* Refactor {send,read}_message()

* Use binding for Take

---------

Co-authored-by: Ryze <50497128+ryze312@users.noreply.github.com>
This commit is contained in:
eNV25 2024-02-16 08:53:21 +00:00 committed by GitHub
parent ce98b95008
commit dbc4e5c8f0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

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;
@ -23,23 +22,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(())