use crate::*;
impl Default for Context {
#[inline(always)]
fn default() -> Self {
Self {
aborted: false,
closed: false,
leaked: false,
stream: None,
request: Request::default(),
response: Response::default(),
route_params: RouteParams::default(),
attributes: ThreadSafeAttributeStore::default(),
server: default_server(),
}
}
}
impl PartialEq for Context {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.get_aborted() == other.get_aborted()
&& self.get_closed() == other.get_closed()
&& self.get_leaked() == other.get_leaked()
&& self.get_request() == other.get_request()
&& self.get_response() == other.get_response()
&& self.get_route_params() == other.get_route_params()
&& self.get_attributes().len() == other.get_attributes().len()
&& self.try_get_stream().is_some() == other.try_get_stream().is_some()
&& self.get_server() == other.get_server()
}
}
impl Eq for Context {}
impl From<&'static Server> for Context {
#[inline(always)]
fn from(server: &'static Server) -> Self {
let mut ctx: Context = Context::default();
ctx.set_server(server);
ctx
}
}
impl From<&ArcRwLockStream> for Context {
#[inline(always)]
fn from(stream: &ArcRwLockStream) -> Self {
let mut ctx: Context = Context::default();
ctx.set_stream(Some(stream.clone()));
ctx
}
}
impl From<ArcRwLockStream> for Context {
#[inline(always)]
fn from(stream: ArcRwLockStream) -> Self {
(&stream).into()
}
}
impl From<usize> for Context {
#[inline(always)]
fn from(address: usize) -> Self {
let ctx: &Context = address.into();
ctx.clone()
}
}
impl From<usize> for &'static Context {
#[inline(always)]
fn from(address: usize) -> &'static Context {
unsafe { &*(address as *const Context) }
}
}
impl<'a> From<usize> for &'a mut Context {
#[inline(always)]
fn from(address: usize) -> &'a mut Context {
unsafe { &mut *(address as *mut Context) }
}
}
impl From<&Context> for usize {
#[inline(always)]
fn from(ctx: &Context) -> Self {
ctx as *const Context as usize
}
}
impl From<&mut Context> for usize {
#[inline(always)]
fn from(ctx: &mut Context) -> Self {
ctx as *mut Context as usize
}
}
impl AsRef<Context> for Context {
#[inline(always)]
fn as_ref(&self) -> &Self {
let address: usize = self.into();
address.into()
}
}
impl AsMut<Context> for Context {
#[inline(always)]
fn as_mut(&mut self) -> &mut Self {
let address: usize = self.into();
address.into()
}
}
impl Lifetime for Context {
#[inline(always)]
fn leak(&self) -> &'static Self {
let address: usize = self.into();
address.into()
}
#[inline(always)]
fn leak_mut(&self) -> &'static mut Self {
let address: usize = self.into();
address.into()
}
}
impl Context {
#[inline(always)]
pub(crate) fn new(stream: &ArcRwLockStream, server: &'static Server) -> Self {
let mut ctx: Context = Context::default();
ctx.set_stream(Some(stream.clone())).set_server(server);
ctx
}
#[inline(always)]
pub fn free(&mut self) {
let _ = unsafe { Box::from_raw(self) };
}
pub fn try_spawn_local<F>(&self, hook: F) -> bool
where
F: Future<Output = ()> + Send + 'static,
{
self.get_server()
.get_task()
.try_spawn_local(Some(self.into()), hook)
}
pub async fn http_from_stream(&mut self) -> Result<Request, RequestError> {
if self.get_aborted() {
return Err(RequestError::RequestAborted(HttpStatus::BadRequest));
}
if let Some(stream) = self.try_get_stream() {
let request_res: Result<Request, RequestError> =
Request::http_from_stream(stream, self.get_server().get_request_config()).await;
if let Ok(request) = request_res.as_ref() {
self.set_request(request.clone());
}
return request_res;
};
Err(RequestError::GetTcpStream(HttpStatus::BadRequest))
}
pub async fn ws_from_stream(&mut self) -> Result<Request, RequestError> {
if self.get_aborted() {
return Err(RequestError::RequestAborted(HttpStatus::BadRequest));
}
if let Some(stream) = self.try_get_stream() {
let last_request: &Request = self.get_request();
let request_res: Result<Request, RequestError> = last_request
.ws_from_stream(stream, self.get_server().get_request_config())
.await;
match request_res.as_ref() {
Ok(request) => {
self.set_request(request.clone());
}
Err(_) => {
self.set_request(last_request.clone());
}
}
return request_res;
};
Err(RequestError::GetTcpStream(HttpStatus::BadRequest))
}
#[inline(always)]
pub fn is_terminated(&self) -> bool {
self.get_aborted() || self.get_closed()
}
#[inline(always)]
pub(crate) fn is_keep_alive(&self, keep_alive: bool) -> bool {
!self.get_closed() && keep_alive
}
#[inline(always)]
pub fn try_get_route_param<T>(&self, name: T) -> Option<String>
where
T: AsRef<str>,
{
self.get_route_params().get(name.as_ref()).cloned()
}
#[inline(always)]
pub fn get_route_param<T>(&self, name: T) -> String
where
T: AsRef<str>,
{
self.try_get_route_param(name).unwrap()
}
#[inline(always)]
pub fn try_get_attribute<V>(&self, key: impl AsRef<str>) -> Option<V>
where
V: AnySendSyncClone,
{
self.get_attributes()
.get(&Attribute::External(key.as_ref().to_owned()).to_string())
.and_then(|arc| arc.downcast_ref::<V>())
.cloned()
}
#[inline(always)]
pub fn get_attribute<V>(&self, key: impl AsRef<str>) -> V
where
V: AnySendSyncClone,
{
self.try_get_attribute(key).unwrap()
}
#[inline(always)]
pub fn set_attribute<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: AsRef<str>,
V: AnySendSyncClone,
{
self.get_mut_attributes().insert(
Attribute::External(key.as_ref().to_owned()).to_string(),
Arc::new(value),
);
self
}
#[inline(always)]
pub fn remove_attribute<K>(&mut self, key: K) -> &mut Self
where
K: AsRef<str>,
{
self.get_mut_attributes()
.remove(&Attribute::External(key.as_ref().to_owned()).to_string());
self
}
#[inline(always)]
pub fn clear_attribute(&mut self) -> &mut Self {
self.get_mut_attributes().clear();
self
}
#[inline(always)]
fn try_get_internal_attribute<V>(&self, key: InternalAttribute) -> Option<V>
where
V: AnySendSyncClone,
{
self.get_attributes()
.get(&Attribute::Internal(key).to_string())
.and_then(|arc| arc.downcast_ref::<V>())
.cloned()
}
#[inline(always)]
fn get_internal_attribute<V>(&self, key: InternalAttribute) -> V
where
V: AnySendSyncClone,
{
self.try_get_internal_attribute(key).unwrap()
}
#[inline(always)]
fn set_internal_attribute<V>(&mut self, key: InternalAttribute, value: V) -> &mut Self
where
V: AnySendSyncClone,
{
self.get_mut_attributes()
.insert(Attribute::Internal(key).to_string(), Arc::new(value));
self
}
#[inline(always)]
pub(crate) fn set_task_panic(&mut self, panic_data: PanicData) -> &mut Self {
self.set_internal_attribute(InternalAttribute::TaskPanicData, panic_data)
}
#[inline(always)]
pub fn try_get_task_panic_data(&self) -> Option<PanicData> {
self.try_get_internal_attribute(InternalAttribute::TaskPanicData)
}
#[inline(always)]
pub fn get_task_panic_data(&self) -> PanicData {
self.get_internal_attribute(InternalAttribute::TaskPanicData)
}
#[inline(always)]
pub(crate) fn set_request_error_data(&mut self, request_error: RequestError) -> &mut Self {
self.set_internal_attribute(InternalAttribute::RequestErrorData, request_error)
}
#[inline(always)]
pub fn try_get_request_error_data(&self) -> Option<RequestError> {
self.try_get_internal_attribute(InternalAttribute::RequestErrorData)
}
#[inline(always)]
pub fn get_request_error_data(&self) -> RequestError {
self.get_internal_attribute(InternalAttribute::RequestErrorData)
}
pub async fn try_send(&mut self) -> Result<(), ResponseError> {
if self.is_terminated() {
return Err(ResponseError::Terminated);
}
let response_data: ResponseData = self.get_mut_response().build();
if let Some(stream) = self.try_get_stream() {
return stream.try_send(response_data).await;
}
Err(ResponseError::NotFoundStream)
}
pub async fn send(&mut self) {
self.try_send().await.unwrap();
}
pub async fn try_send_body(&self) -> Result<(), ResponseError> {
if self.is_terminated() {
return Err(ResponseError::Terminated);
}
self.try_send_body_with_data(self.get_response().get_body())
.await
}
pub async fn send_body(&self) {
self.try_send_body().await.unwrap();
}
pub async fn try_send_body_with_data<D>(&self, data: D) -> Result<(), ResponseError>
where
D: AsRef<[u8]>,
{
if self.is_terminated() {
return Err(ResponseError::Terminated);
}
if let Some(stream) = self.try_get_stream() {
return stream.try_send_body(data).await;
}
Err(ResponseError::NotFoundStream)
}
pub async fn send_body_with_data<D>(&self, data: D)
where
D: AsRef<[u8]>,
{
self.try_send_body_with_data(data).await.unwrap();
}
pub async fn try_send_body_list<I, D>(&self, data_iter: I) -> Result<(), ResponseError>
where
I: IntoIterator<Item = D>,
D: AsRef<[u8]>,
{
if self.is_terminated() {
return Err(ResponseError::Terminated);
}
if let Some(stream) = self.try_get_stream() {
return stream.try_send_body_list(data_iter).await;
}
Err(ResponseError::NotFoundStream)
}
pub async fn send_body_list<I, D>(&self, data_iter: I)
where
I: IntoIterator<Item = D>,
D: AsRef<[u8]>,
{
self.try_send_body_list(data_iter).await.unwrap();
}
pub async fn try_send_body_list_with_data<I, D>(
&self,
data_iter: I,
) -> Result<(), ResponseError>
where
I: IntoIterator<Item = D>,
D: AsRef<[u8]>,
{
if self.is_terminated() {
return Err(ResponseError::Terminated);
}
if let Some(stream) = self.try_get_stream() {
return stream.try_send_body_list(data_iter).await;
}
Err(ResponseError::NotFoundStream)
}
pub async fn send_body_list_with_data<I, D>(&self, data_iter: I)
where
I: IntoIterator<Item = D>,
D: AsRef<[u8]>,
{
self.try_send_body_list_with_data(data_iter).await.unwrap()
}
pub async fn try_flush(&self) -> Result<(), ResponseError> {
if self.is_terminated() {
return Err(ResponseError::Terminated);
}
if let Some(stream) = self.try_get_stream() {
return stream.try_flush().await;
}
Err(ResponseError::NotFoundStream)
}
pub async fn flush(&self) {
self.try_flush().await.unwrap();
}
}