about summary refs log tree commit diff
path: root/gatherer-api/src/request.rs
blob: c74dfa5634ba6a82c6495dcbcb34926eb97a3a9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use std::io::Write;

use camino::Utf8PathBuf;
use gny::blobby::{
	BinRead, BinWrite, ByteCounter, Configuration, Decode, DecodeError, Encode, EncodeError,
	derive::{Decode, Encode},
};

#[derive(Clone, Debug, Encode, Decode)]
pub struct Request {
	msg: Message,
	body: Vec<u8>,
}

impl Request {
	pub fn new(msg: Message) -> Self {
		Self { msg, body: vec![] }
	}

	pub fn message(&self) -> &Message {
		&self.msg
	}

	pub fn with_body<T: Encode>(mut self, body: T) -> Result<Self, EncodeError> {
		let body_len = ByteCounter::new_counter(Configuration::default()).encodable_len(&body)?;
		self.body.resize(body_len, 0);

		let mut enc = BinWrite::from_buffer(&mut self.body, Configuration::default());
		enc.encode(&body)?;
		Ok(self)
	}

	pub fn get_body<T: Decode>(&self) -> Result<T, DecodeError> {
		let mut dec = BinRead::from_buffer(&self.body, Configuration::default());
		dec.decode()
	}

	pub fn send<W: Write>(self, w: W) -> Result<(), EncodeError> {
		let len = ByteCounter::new_counter(Configuration::default()).encodable_len(&self)?;
		let mut bw = BinWrite::new(w, Configuration::default());
		let count = bw.u16(len as u16)? + bw.encode(&self)?;
		tracing::trace!("sent {count} bytes");
		Ok(())
	}

	pub fn from_buffer(buf: &[u8]) -> Result<Self, DecodeError> {
		let mut br = BinRead::from_buffer(buf, Configuration::default());
		br.decode()
	}
}

#[derive(Copy, Clone, Debug, Encode, Decode, PartialEq)]
pub enum Message {
	GetGraphBounds,
	GenerateGraphs,
	GetRegularGraphs,
}

#[derive(Clone, Debug, Encode, Decode)]
pub struct GenerateGraphsBody {
	pub directory: Utf8PathBuf,
}