paper_utils/
stream.rs

1/*
2 * Copyright (c) Kia Shakiba
3 *
4 * This source code is licensed under the GNU AGPLv3 license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8pub mod error;
9pub mod reader;
10
11use std::{
12	io::{Read, Write},
13	net::TcpStream,
14};
15
16pub type Buffer = Box<[u8]>;
17pub type StackBuffer<const N: usize> = [u8; N];
18
19pub fn read_buf(stream: &mut TcpStream, buf_size: usize) -> Result<Buffer, StreamError> {
20	let mut buf = vec![0u8; buf_size].into_boxed_slice();
21
22	match stream.read_exact(&mut buf) {
23		Ok(_) => Ok(buf),
24		Err(_) => Err(StreamError::ClosedStream),
25	}
26}
27
28pub fn read_stack_buf<const N: usize>(stream: &mut TcpStream) -> Result<StackBuffer<N>, StreamError> {
29	let mut buf = [0u8; N];
30
31	match stream.read_exact(&mut buf) {
32		Ok(_) => Ok(buf),
33		Err(_) => Err(StreamError::ClosedStream),
34	}
35}
36
37pub fn write_buf(stream: &mut TcpStream, buf: &[u8]) -> Result<(), StreamError> {
38	match stream.write_all(buf) {
39		Ok(_) => Ok(()),
40		Err(_) => Err(StreamError::InvalidStream),
41	}
42}
43
44pub use crate::stream::error::*;
45pub use crate::stream::reader::*;