wetstring/src/request_response.rs

46 lines
1.6 KiB
Rust

use std::net::SocketAddr;
/// A trait for an object that can store the state of a partially parsed request.
/// The incoming byte stream can be parsed incrementally, and the request can be converted
/// to an error response if the incoming bytes are invalid.
pub trait RequestParser<Req: Request> {
fn new(client_address: SocketAddr) -> Self;
fn push_bytes(&mut self, bytes: &[u8]);
fn try_parse(&mut self) -> RequestParseResult<Req>;
}
/// A trait for objects that represent a valid network request.
pub trait Request: Sized {
type Response: Response;
type Parser: RequestParser<Self>;
fn process(&self, request_processor: RequestProcessor<Self>) -> Self::Response {
request_processor(&self)
}
}
/// A trait for objects that represent the response to a network request.
pub trait Response {
fn to_bytes(self) -> Vec<u8>;
}
pub enum RequestParseResult<Req: Request> {
/// The request is waiting for the client to send more data before the
/// request can either be discarded as erroneous or parsed.
Incomplete,
/// Sufficient data has been received from the client, and the request
/// has been successfully parsed.
Complete(Req),
/// An error has been encountered in the received data, and a response
/// has been generated to be returned to the client.
Invalid(Req::Response),
}
/// A function that converts a Request into a Response. This one function will
/// contain all of the logic for a server.
pub type RequestProcessor<Req> = fn(request: &Req) -> <Req as Request>::Response;
// TODO: pub type InvalidRequestProcessor<Req, Res> = fn(invalid_request: &Req) -> Res;