pzzld_server/workers/serve/
context.rs

1/*
2    Appellation: context <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use crate::config::Scope;
6use core::net::SocketAddr;
7
8#[derive(Clone, Debug, Hash, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize)]
9pub struct ServerContext {
10    /// The address the server is bound to
11    pub(crate) addr: SocketAddr,
12    /// The scope of the server
13    pub(crate) scope: Scope,
14}
15
16impl ServerContext {
17    pub fn new(addr: SocketAddr, scope: Scope) -> Self {
18        Self { addr, scope }
19    }
20
21    pub fn localhost(port: u16, scope: Scope) -> Self {
22        Self {
23            addr: SocketAddr::from(([127, 0, 0, 1], port)),
24            scope,
25        }
26    }
27    /// Returns a copy of the address the server is bound to
28    pub fn addr(&self) -> SocketAddr {
29        self.addr
30    }
31    /// Returns a reference to the [Scope] of the server
32    pub const fn scope(&self) -> &Scope {
33        &self.scope
34    }
35    /// Returns a mutable reference to the [Scope] of the server
36    pub fn scope_mut(&mut self) -> &mut Scope {
37        &mut self.scope
38    }
39
40    setwith! {
41        addr: SocketAddr,
42        scope: Scope,
43    }
44    /// initialize a new listener, bound to the configured address
45    pub async fn listen(&self) -> tokio::net::TcpListener {
46        tokio::net::TcpListener::bind(&self.addr).await.unwrap()
47    }
48}