summaryrefslogtreecommitdiff
path: root/byte_encode_derive/src/lib.rs
blob: 5970c6677d2850126197c2ea0f920479d376749f (plain) (blame)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Code mostly made by gemini somehow

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Fields};

#[proc_macro_derive(ByteEncode)]
pub fn derive_byte_encode(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;

    // We only support structs with named fields for this example
    let fields = match input.data {
        Data::Struct(data) => match data.fields {
            Fields::Named(fields) => fields.named,
            _ => panic!("Only named fields are supported"),
        },
        _ => panic!("Only structs are supported"),
    };

    // --- 1. Generate from_le_bytes parsing logic ---
    let mut current_offset = quote! { 0 };
    let from_le_bytes_initializers = fields.iter().map(|f| {
        let field_name = &f.ident;
        let field_type = &f.ty;

        // Calculate start and end bounds for the current field slice
        let start = quote! { #current_offset };
        let end = quote! { #start + <#field_type>::SIZE };
        
        // Update the offset tracking for the next iteration loop
        current_offset = quote! { #end };

        quote! {
            #field_name: <#field_type as ByteEncode<{<#field_type>::SIZE}>>::from_le_bytes(
                buffer[#start..#end].try_into().unwrap()
            )
        }
    });
	let mut current_offset = quote! { 0 };
    let from_be_bytes_initializers = fields.iter().map(|f| {
        let field_name = &f.ident;
        let field_type = &f.ty;

        // Calculate start and end bounds for the current field slice
        let start = quote! { #current_offset };
        let end = quote! { #start + <#field_type>::SIZE };
        
        // Update the offset tracking for the next iteration loop
        current_offset = quote! { #end };

        quote! {
            #field_name: <#field_type as ByteEncode<{<#field_type>::SIZE}>>::from_be_bytes(
                &mut buffer[#start..#end].try_into().unwrap()
            )
        }
    });

	
    // --- 2. Generate to_le_bytes serialization logic ---
    let mut current_offset = quote! { 0 };
    let to_le_bytes_writers = fields.iter().map(|f| {
        let field_name = &f.ident;
        let field_type = &f.ty;

        let start = quote! { #current_offset };
        let end = quote! { #start + <#field_type>::SIZE };
        
        current_offset = quote! { #end };

        quote! {
            res[#start..#end].copy_from_slice(&self.#field_name.to_le_bytes());
        }
    });
	let mut current_offset = quote! { 0 };
    let to_be_bytes_writers = fields.iter().map(|f| {
        let field_name = &f.ident;
        let field_type = &f.ty;

        let start = quote! { #current_offset };
        let end = quote! { #start + <#field_type>::SIZE };
        
        current_offset = quote! { #end };

        quote! {
            res[#start..#end].copy_from_slice(&self.#field_name.to_be_bytes());
        }
    });
	

    // --- 3. Construct final token stream ---
    // This dynamically sums up sizes like: 0 + Field1::SIZE + Field2::SIZE ...
    let total_size_expr = fields.iter().fold(quote! { 0 }, |acc, f| {
        let field_type = &f.ty;
        quote! { #acc + <#field_type>::SIZE }
    });

    let expanded = quote! {
        impl ByteEncode<{ #total_size_expr }> for #name {
            fn from_le_bytes(buffer: &[u8; { #total_size_expr }]) -> Self {
                Self {
                    #( #from_le_bytes_initializers, )*
                }
            }

            fn to_le_bytes(&self) -> [u8; { #total_size_expr }] {
                let mut res = [0u8; { #total_size_expr }];
                #( #to_le_bytes_writers )*
                res
            }

			
            fn from_be_bytes(buffer: &mut [u8; { #total_size_expr }]) -> Self {
                Self {
                    #( #from_be_bytes_initializers, )*
                }
            }

            fn to_be_bytes(&self) -> [u8; { #total_size_expr }] {
                let mut res = [0u8; { #total_size_expr }];
                #( #to_be_bytes_writers )*
                res
            }
        }
    };

    TokenStream::from(expanded)
}