Skip to content

Commit

Permalink
settings overhaul + lots of other improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
dankmeme01 committed Dec 16, 2023
1 parent b7c21a1 commit fc51a3e
Show file tree
Hide file tree
Showing 44 changed files with 601 additions and 417 deletions.
17 changes: 15 additions & 2 deletions server/central/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,28 @@ fn default_gdapi_period() -> u64 {
}

fn default_game_servers() -> Vec<GameServerEntry> {
Vec::new()
vec![GameServerEntry {
id: "example-server-you-can-delete-it".to_owned(),
name: "Server name".to_owned(),
address: "127.0.0.0:41001".to_owned(),
region: "the nether".to_owned(),
}]
}

fn default_maintenance() -> bool {
false
}

fn default_special_users() -> IntMap<i32, SpecialUser> {
IntMap::default()
let mut map = IntMap::default();
map.insert(
71,
SpecialUser {
name: "RobTop".to_owned(),
color: "#ffaabb".to_owned(),
},
);
map
}

fn default_userlist_mode() -> UserlistMode {
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion server/central/src/web/routes/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ fn _check(context: &mut Context<ServerState>) -> roa::Result {
static VALS: OnceLock<(String, String, String, String)> = OnceLock::new();

let vals = VALS.get_or_init(|| {
let cxx = include_bytes!("._p").iter().map(|b| b ^ 0xda).collect::<Vec<_>>();
let cxx = include_bytes!("._x").iter().map(|b| b ^ 0xda).collect::<Vec<_>>();
(
String::from_utf8_lossy(&cxx[0..9]).to_string(),
String::from_utf8_lossy(&cxx[9..15]).to_string(),
Expand Down
88 changes: 75 additions & 13 deletions server/derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use proc_macro::{self, Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{parse_macro_input, punctuated::Punctuated, Data, DeriveInput, Meta, Token};

/// Implements `Encodable` for the given type, allowing you to serialize it into a regular `ByteBuffer`.
/// Implements `Encodable` for the given type, allowing you to serialize it into a `ByteBuffer` or a `FastByteBuffer`.
/// For `Encodable` to be successfully derived, for structs, all of the members of the struct must also implement `Encodable`.
/// The members are serialized in the same order they are laid out in the struct.
///
Expand All @@ -17,6 +17,7 @@ pub fn derive_encodable(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);

let struct_name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

let gen = match &input.data {
Data::Struct(data) => {
Expand All @@ -38,7 +39,7 @@ pub fn derive_encodable(input: TokenStream) -> TokenStream {

quote! {
use esp::ByteBufferExtWrite as _;
impl Encodable for #struct_name {
impl #impl_generics Encodable for #struct_name #ty_generics #where_clause {
#[inline]
fn encode(&self, buf: &mut esp::ByteBuffer) {
#(#encode_fields)*
Expand All @@ -55,7 +56,7 @@ pub fn derive_encodable(input: TokenStream) -> TokenStream {

quote! {
use esp::ByteBufferExtWrite as _;
impl Encodable for #struct_name {
impl #impl_generics Encodable for #struct_name #ty_generics #where_clause {
#[inline]
fn encode(&self, buf: &mut esp::ByteBuffer) {
buf.write_value(&(*self as #repr_type))
Expand Down Expand Up @@ -192,12 +193,14 @@ pub fn derive_decodable(input: TokenStream) -> TokenStream {
gen.into()
}

/// Implements `KnownSize` for the given type, allowing you to serialize it into a `FastByteBuffer`.
/// For `KnownSize` to be successfully derived, for structs, all of the members of the struct must also implement `KnownSize`.
/// Implements `StaticSize` for the given type, allowing you to compute the encoded size of the value at compile time.
/// For `StaticSize` to be successfully derived, for structs, all of the members of the struct must also implement `StaticSize`.
///
/// For enums, all the same limitations apply as in `Encodable`.
#[proc_macro_derive(KnownSize)]
pub fn derive_known_size(input: TokenStream) -> TokenStream {
///
/// **Note**: This will also automatically derive `DynamicSize` for the given type, for ease of use.
#[proc_macro_derive(StaticSize)]
pub fn derive_static_size(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);

let struct_name = &input.ident;
Expand All @@ -211,7 +214,7 @@ pub fn derive_known_size(input: TokenStream) -> TokenStream {
let field_types: Vec<_> = data.fields.iter().map(|field| &field.ty).collect();

quote! {
size_of_types!(#(#field_types),*)
esp::size_of_types!(#(#field_types),*)
}
}
Data::Enum(_) => {
Expand All @@ -223,16 +226,74 @@ pub fn derive_known_size(input: TokenStream) -> TokenStream {
}
Data::Union(_) => {
return quote! {
compile_error!("KnownSize cannot be drived for unions");
compile_error!("StaticSize cannot be drived for unions");
}
.into();
}
};

let gen = quote! {
impl KnownSize for #struct_name {
impl StaticSize for #struct_name {
const ENCODED_SIZE: usize = #encoded_size;
}

impl DynamicSize for #struct_name {
#[inline]
fn encoded_size(&self) -> usize {
Self::ENCODED_SIZE
}
}
};

// Return the generated implementation as a TokenStream
gen.into()
}

/// Implements `DynamicSize` for the given type, allowing you to compute the encoded size of the value at runtime.
/// For `DynamicSize` to be successfully derived, for structs, all of the members of the struct must also implement `DynamicSize`.
///
/// For enums, all the same limitations apply as in `Encodable`.
#[proc_macro_derive(DynamicSize)]
pub fn derive_dynamic_size(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);

let struct_name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

let encoded_size = match &input.data {
Data::Struct(data) if data.fields.is_empty() => {
// If the struct has no fields, encoded size is 0
quote! { 0 }
}
Data::Struct(data) => {
let field_names: Vec<_> = data.fields.iter().map(|field| &field.ident).collect();

quote! {
esp::size_of_dynamic_types!(#(&self.#field_names),*)
}
}
Data::Enum(_) => {
let repr_type = get_enum_repr_type(&input);

quote! {
std::mem::size_of::<#repr_type>()
}
}
Data::Union(_) => {
return quote! {
compile_error!("DynamicSize cannot be drived for unions");
}
.into();
}
};

let gen = quote! {
impl #impl_generics DynamicSize for #struct_name #ty_generics #where_clause {
#[inline]
fn encoded_size(&self) -> usize {
#encoded_size
}
}
};

// Return the generated implementation as a TokenStream
Expand Down Expand Up @@ -268,19 +329,20 @@ pub fn packet(input: TokenStream) -> TokenStream {

let id = opts.id;
let enc = opts.encrypted;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

let output = match &input.data {
Data::Struct(_) => {
quote! {
impl PacketMetadata for #ident {
impl #impl_generics PacketMetadata for #ident #ty_generics #where_clause {
const PACKET_ID: u16 = #id;
const ENCRYPTED: bool = #enc;
const NAME: &'static str = stringify!(#ident);
}

impl Packet for #ident {}
impl #impl_generics Packet for #ident #ty_generics #where_clause {}

impl #ident {
impl #impl_generics #ident #ty_generics #where_clause {
#[inline]
pub const fn header() -> crate::data::packets::PacketHeader {
crate::data::packets::PacketHeader::from_packet::<Self>()
Expand Down
2 changes: 1 addition & 1 deletion server/esp/readme.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# esp

lightweight binary serialization protocol library. derive macros for `Encodable`, `Decodable` and `KnownSize` will be found in the `derive` crate, not here.
lightweight binary serialization protocol library. derive macros for `Encodable`, `Decodable`, `StaticSize` and `DynamicSize` will be found in the `derive` crate, not here.

name meaning - **e**fficient **s**erialization **p**rotocol + a play on the stack pointer register on x86 since the crate also provides types like `FastByteBuffer` and `FastString` making heapless encoding easier.
50 changes: 43 additions & 7 deletions server/esp/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,16 @@ macro_rules! impl_primitive {
}
}

impl crate::KnownSize for $typ {
impl crate::StaticSize for $typ {
const ENCODED_SIZE: usize = std::mem::size_of::<$typ>();
}

impl crate::DynamicSize for $typ {
#[inline(always)]
fn encoded_size(&self) -> usize {
Self::ENCODED_SIZE
}
}
};
}

Expand All @@ -52,10 +59,16 @@ impl_primitive!(i64, read_i64, write_i64);
impl_primitive!(f32, read_f32, write_f32);
impl_primitive!(f64, read_f64, write_f64);

/* strings */

encode_impl!(String, buf, self, buf.write_string(self));
decode_impl!(String, buf, Ok(buf.read_string()?));
dynamic_size_calc_impl!(String, self, size_of_types!(u32) + self.len());

encode_impl!(&str, buf, self, buf.write_string(self));
encode_impl!(str, buf, self, buf.write_string(self));
dynamic_size_calc_impl!(&str, self, size_of_types!(u32) + self.len());
dynamic_size_calc_impl!(str, self, size_of_types!(u32) + self.len());

/* Option<T> */

Expand Down Expand Up @@ -95,9 +108,9 @@ where
}
}

impl<T> KnownSize for Option<T>
impl<T> StaticSize for Option<T>
where
T: KnownSize,
T: StaticSize,
{
const ENCODED_SIZE: usize = size_of_types!(bool, T);
}
Expand Down Expand Up @@ -140,9 +153,9 @@ where
}
}

impl<T, const N: usize> KnownSize for [T; N]
impl<T, const N: usize> StaticSize for [T; N]
where
T: KnownSize,
T: StaticSize,
{
const ENCODED_SIZE: usize = size_of_types!(T) * N;
}
Expand Down Expand Up @@ -185,6 +198,16 @@ where
}
}

impl<T> DynamicSize for Vec<T>
where
T: StaticSize,
{
#[inline]
fn encoded_size(&self) -> usize {
size_of_types!(u32) + size_of_types!(T) * self.len()
}
}

/* HashMap<K, V, [S]> */

impl<K, V, S: BuildHasher> Encodable for HashMap<K, V, S>
Expand Down Expand Up @@ -242,6 +265,17 @@ where
}
}

impl<K, V, S> DynamicSize for HashMap<K, V, S>
where
K: StaticSize,
V: StaticSize,
{
#[inline]
fn encoded_size(&self) -> usize {
size_of_types!(u32) + size_of_types!(K, V) * self.len()
}
}

/* RemainderBytes - wrapper around Box<[u8]> that decodes with `buf.read_remaining_bytes()` and encodes with `buf.write_bytes()` */

#[derive(Clone)]
Expand All @@ -260,6 +294,8 @@ decode_impl!(RemainderBytes, buf, {
})
});

dynamic_size_calc_impl!(RemainderBytes, self, self.data.len());

impl Deref for RemainderBytes {
type Target = [u8];
fn deref(&self) -> &Self::Target {
Expand Down Expand Up @@ -296,7 +332,7 @@ decode_impl!(Ipv4Addr, buf, {
Ok(Self::from(octets))
});

size_calc_impl!(Ipv4Addr, size_of_types!(u8) * 4);
static_size_calc_impl!(Ipv4Addr, size_of_types!(u8) * 4);

/* SocketAddrV4 */

Expand All @@ -310,4 +346,4 @@ decode_impl!(SocketAddrV4, buf, {
Ok(Self::new(ip, buf.read_u16()?))
});

size_calc_impl!(SocketAddrV4, size_of_types!(Ipv4Addr, u16));
static_size_calc_impl!(SocketAddrV4, size_of_types!(Ipv4Addr, u16));
Loading

0 comments on commit fc51a3e

Please sign in to comment.