rustacean_db/
lib.rs

1use bincode::{Decode, Encode};
2
3#[derive(Decode, Encode, Debug)]
4enum Request {
5    Get(String),
6    Post(String, Vec<u8>)
7}
8
9pub mod blocking {
10    use std::{error::{self}, io::{Read}, net::TcpStream};
11    use bincode::{self, config::standard};
12    use packetio::{PacketReceiver, PacketSender};
13
14    use crate::Request;
15
16    pub fn get<T: bincode::Decode<()>>(ip: &str, req: &str) -> Result<T, Box<dyn error::Error>> {
17        let mut connection = TcpStream::connect(ip)?;
18
19        connection.send_packet(Request::Get(req.to_string()))?;
20        connection.recv_packet()
21    }
22
23    pub fn post<T: bincode::Decode<()> + bincode::Encode<>>(ip: &str, to: &str, what: T) -> Result<(), Box<dyn error::Error>> {
24        let mut connection = TcpStream::connect(ip)?;
25        
26        connection.send_packet(Request::Post(to.to_string(), bincode::encode_to_vec(what, standard())?))?;
27
28        let mut b: Vec<u8> = Vec::new();
29        connection.read_to_end(&mut b)?;
30
31        if b == vec![1] {
32            Ok(())
33        } else {
34            Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Server did not acknowledge").into())
35        }
36        
37    }
38}