e_macros/lib.rs
1#![allow(
2 clippy::cognitive_complexity,
3 clippy::large_enum_variant,
4 clippy::module_inception,
5 clippy::needless_doctest_main
6)]
7#![warn(
8 missing_debug_implementations,
9// missing_docs,
10 rust_2021_compatibility,
11 unreachable_pub
12)]
13#![deny(unused_must_use)]
14#![doc(test(
15 no_crate_inject,
16 attr(
17 deny(warnings, rust_2021_compatibility),
18 allow(dead_code, unused_variables)
19 )
20))]
21#![cfg_attr(docsrs, feature(doc_cfg))]
22#![cfg_attr(docsrs, allow(unused_attributes))]
23#![cfg_attr(loom, allow(dead_code, unreachable_pub))]
24
25extern crate proc_macro;
26
27use proc_macro::TokenStream;
28use quote::quote;
29use syn::{parse_macro_input, DeriveInput};
30
31/// # 对象克隆
32/// ```toml
33/// [dependencies]
34/// serde_json = "1.0"
35/// serde = { version = "1.0", features = ["derive"] }
36/// e-macros = { version = "0.1", git="https://gitee.com/eternalnight996/e-macros"}
37/// ```
38/// # Example
39///```rust
40/// #[derive(serde::Deserialize, Debug, serde::Serialize)]
41/// struct A {
42/// a: String,
43/// b: i32,
44/// d: i32,
45/// }
46/// #[derive(serde::Deserialize, Debug, serde::Serialize, Default, e_utils::Json)]
47/// struct B {
48/// d: i32,
49/// f: String,
50/// }
51/// fn test() {
52/// let mut a: A = A {
53/// a: "A".to_string(),
54/// b: 1,
55/// d: 2,
56/// };
57/// println!("A {:?}", a);
58/// let mut b: B = B::auto_json_cloned(&a);
59/// println!("B {:?}", b);
60/// a.d = 10;
61/// b.f = "test".to_string();
62/// b = b.self_json_cloned(&a);
63/// println!("B {:?}", b);
64/// }
65#[proc_macro_derive(Json)]
66pub fn json_derive(input: TokenStream) -> TokenStream {
67 // Parse the input tokens as a DeriveInput
68 let input = parse_macro_input!(input as DeriveInput);
69
70 // Get the name of the struct
71 let struct_name = &input.ident;
72
73 // Extract the fields of the struct
74 // let _fields = if let syn::Data::Struct(syn::DataStruct {
75 // fields: syn::Fields::Named(fields),
76 // ..
77 // }) = &input.data
78 // {
79 // fields.named.iter().map(|f| &f.ident).collect::<Vec<_>>()
80 // } else {
81 // panic!("This macro only supports structs with named fields");
82 // };
83
84 // Create the output tokens
85 let expanded = quote! {
86 // Implement the trait for the struct
87 impl #struct_name {
88 /// ```toml
89 /// [dependencies]
90 /// serde_json = "1.0"
91 /// serde = { version = "1.0", features = ["derive"] }
92 /// e-macros = { version = "0.1", git="https://gitee.com/eternalnight996/e-macros"}
93 /// ```
94 /// # Example
95 ///```rust
96 /// #[derive(serde::Deserialize, Debug, serde::Serialize)]
97 /// struct A {
98 /// a: String,
99 /// b: i32,
100 /// d: i32,
101 /// }
102 /// #[derive(serde::Deserialize, Debug, serde::Serialize, Default, e_utils::Json)]
103 /// struct B {
104 /// d: i32,
105 /// f: String,
106 /// }
107 /// fn test() {
108 /// let mut a: A = A {
109 /// a: "A".to_string(),
110 /// b: 1,
111 /// d: 2,
112 /// };
113 /// println!("A {:?}", a);
114 /// let mut b: B = B::auto_json_cloned(&a);
115 /// println!("B {:?}", b);
116 /// a.d = 10;
117 /// b.f = "test".to_string();
118 /// b = b.self_json_cloned(&a);
119 /// println!("B {:?}", b);
120 /// }
121 pub fn self_json_cloned<T:serde::ser::Serialize>(&self, target:&T) -> Self{
122 Self::own_json_cloned(self,target)
123 }
124 /// ```toml
125 /// [dependencies]
126 /// serde_json = "1.0"
127 /// serde = { version = "1.0", features = ["derive"] }
128 /// e-macros = { version = "0.1", git="https://gitee.com/eternalnight996/e-macros"}
129 /// ```
130 /// # Example
131 ///```rust
132 /// #[derive(serde::Deserialize, Debug, serde::Serialize)]
133 /// struct A {
134 /// a: String,
135 /// b: i32,
136 /// d: i32,
137 /// }
138 /// #[derive(serde::Deserialize, Debug, serde::Serialize, Default, e_utils::Json)]
139 /// struct B {
140 /// d: i32,
141 /// f: String,
142 /// }
143 /// fn test() {
144 /// let mut a: A = A {
145 /// a: "A".to_string(),
146 /// b: 1,
147 /// d: 2,
148 /// };
149 /// println!("A {:?}", a);
150 /// let mut b: B = B::auto_json_cloned(&a);
151 /// println!("B {:?}", b);
152 /// a.d = 10;
153 /// b.f = "test".to_string();
154 /// b = b.self_json_cloned(&a);
155 /// println!("B {:?}", b);
156 /// }
157 pub fn auto_json_cloned<R:serde::de::DeserializeOwned,T:serde::ser::Serialize>(target:&T) -> R {
158 Self::own_json_cloned(&Self::default(),target)
159 }
160 /// 内部
161 fn own_json_cloned<R:serde::de::DeserializeOwned,S:serde::ser::Serialize,T:serde::ser::Serialize>(source:&S,target:&T) -> R {
162 let mut e_self:serde_json::Map<String, serde_json::Value> =
163 serde_json::from_str::<serde_json::Value>(&serde_json::to_string(source).unwrap())
164 .unwrap().as_object()
165 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "Target is not an object"))
166 .unwrap()
167 .clone();
168 let e_target:serde_json::Map<String, serde_json::Value> =
169 serde_json::from_str::<serde_json::Value>(&serde_json::to_string(target).unwrap())
170 .unwrap().as_object()
171 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "Target is not an object"))
172 .unwrap()
173 .clone();
174 for (k, v) in e_target {
175 e_self.insert(k, v);
176 }
177 serde_json::from_value(serde_json::Value::Object(e_self)).unwrap()
178 }
179 /// #智能写入Json
180 /// # Example
181 /// ```rust
182 /// #[derive(serde::Deserialize, Debug, serde::Serialize, Default, e_utils::Json)]
183 /// struct B {
184 /// d: i32,
185 /// f: String,
186 /// }
187 /// fn test() {
188 /// let mut b: B = B::default();
189 /// b.f = "test".to_string();
190 /// b.auto_write_json(Path::new("."), "test.json").unwrap();
191 /// let b = B::auto_read_json(Path::new("test.json")).unwrap();
192 /// println!("B {:?}", b);
193 /// }
194 /// ```
195 /// B B { d: 0, f: "test" }
196 pub fn auto_write_json<P:AsRef<std::path::Path>,S:AsRef<str>>(&self, fpath: P, fname: S) -> std::io::Result<()> {
197 let fpath = fpath.as_ref();
198 let fname = fname.as_ref();
199 if !fpath.exists() {
200 std::fs::create_dir_all(fpath)?;
201 }
202 std::fs::write(fpath.join(fname), serde_json::to_string_pretty(self)?)?;
203 std::io::Result::Ok(())
204 }
205 /// #智能读取Json
206 /// # Example
207 /// ```rust
208 /// #[derive(serde::Deserialize, Debug, serde::Serialize, Default, e_utils::Json)]
209 /// struct B {
210 /// d: i32,
211 /// f: String,
212 /// }
213 /// fn test() {
214 /// let mut b: B = B::default();
215 /// b.f = "test".to_string();
216 /// b.auto_write_json(Path::new("."), "test.json").unwrap();
217 /// let b = B::auto_read_json(Path::new("test.json")).unwrap();
218 /// println!("B {:?}", b);
219 /// }
220 /// ```
221 /// B B { d: 0, f: "test" }
222 pub fn auto_read_json<P:AsRef<std::path::Path>>(path: P) -> std::io::Result<Self> {
223 let path = path.as_ref();
224 std::io::Result::Ok(serde_json::from_str::<Self>(&std::fs::read_to_string(
225 path
226 )?)?)
227 }
228 /// 序列化
229 pub fn to_s(&self) -> String{
230 serde_json::to_string_pretty(self).unwrap_or_default()
231 }
232 }
233
234 };
235
236 // Return the generated implementation
237 TokenStream::from(expanded)
238}
239
240/// 对C语言的增加处理方法
241/// ```toml
242/// [dependencies]
243/// serde_json = "1.0"
244/// serde = { version = "1.0", features = ["derive"] }
245/// e-macros = { version = "0.1", git="https://gitee.com/eternalnight996/e-macros"}
246/// ```
247/// # Example
248/// ```rust
249/// #[derive(e_utils::C)]
250/// struct B {
251/// d: i32,
252/// f: String,
253/// }
254/// fn test() -> Result<()> {
255/// // 假设我们有一个T类型的实例
256/// let value: B = B {
257/// d: 1,
258/// f: "test".to_string(),
259/// };
260/// let ptr = value.to_c_ptr();
261/// // 还原*c_void指针为<Box<T>>实例
262/// if let Some(restored_boxed_value) = unsafe { B::from_c_ptr(ptr) } {
263/// // 成功还原Box<T>实例
264/// println!("Restored value: {:?}", *restored_boxed_value);
265/// } else {
266/// // 还原过程中出现错误
267/// println!("Failed to restore value");
268/// }
269/// Ok(())
270/// }
271/// ```
272#[proc_macro_derive(C)]
273pub fn c_derive(input: TokenStream) -> TokenStream {
274 // Parse the input tokens as a DeriveInput
275 let input = parse_macro_input!(input as DeriveInput);
276
277 // Get the name of the struct
278 let struct_name = &input.ident;
279
280 // Extract the fields of the struct
281 // let _fields = if let syn::Data::Struct(syn::DataStruct {
282 // fields: syn::Fields::Named(fields),
283 // ..
284 // }) = &input.data
285 // {
286 // fields.named.iter().map(|f| &f.ident).collect::<Vec<_>>()
287 // } else {
288 // panic!("This macro only supports structs with named fields");
289 // };
290
291 // Create the output tokens
292 let expanded = quote! {
293 // Implement the trait for the struct
294 impl #struct_name {
295 /// # 获取*const c_void指针
296 /// ```rust
297 /// pub fn to_c_ptr2(self) -> *const std::ffi::c_void {
298 /// self as *const Self *const std::ffi::c_void
299 /// }
300 /// ```
301 /// 安全地获取*const c_void指针
302 pub fn to_c_ptr(self) -> *const std::ffi::c_void {
303 Box::into_raw(Box::new(self)) as *const std::ffi::c_void
304 }
305 /// 安全地还原*const c_void指针为Box<Self>
306 /// # Example
307 /// ```rust
308 /// #[derive(e_utils::C)]
309 /// struct B {
310 /// d: i32,
311 /// f: String,
312 /// }
313 /// fn test() -> Result<()> {
314 /// // 假设我们有一个T类型的实例
315 /// let value: B = B {
316 /// d: 1,
317 /// f: "test".to_string(),
318 /// };
319 /// let ptr = value.to_c_ptr();
320 /// // 还原*c_void指针为<Box<T>>实例
321 /// if let Some(restored_boxed_value) = unsafe { B::from_c_ptr(ptr) } {
322 /// // 成功还原Box<T>实例
323 /// println!("Restored value: {:?}", *restored_boxed_value);
324 /// } else {
325 /// // 还原过程中出现错误
326 /// println!("Failed to restore value");
327 /// }
328 /// Ok(())
329 /// }
330 /// ```
331 pub unsafe fn from_c_ptr(void_ptr: *const std::ffi::c_void) -> Option<Box<Self>> {
332 // 使用NonNull来避免空指针
333 let non_null_ptr = std::ptr::NonNull::new(void_ptr as *mut Self);
334 // 安全地解引用NonNull指针并创建一个新的Box
335 non_null_ptr.map(|ptr| Box::from_raw(ptr.as_ptr() as *mut Self))
336 }
337 /// 直接指针还原类型
338 pub unsafe fn from_c_ptr2(void_ptr: *const std::ffi::c_void) -> Self {
339 std::ptr::read(void_ptr as *const Self)
340 }
341 /// # 安全地获取*mut c_void指针
342 /// ```rust
343 /// pub fn to_c_mut_ptr(self) -> *mut std::ffi::c_void {
344 /// Box::into_raw(Box::new(self)) as *mut std::ffi::c_void
345 /// }
346 /// ```
347 /// 安全地还原*mut c_void指针为Box<Self>
348 pub unsafe fn from_c_mut_ptr(void_ptr: *mut c_void) -> Option<Box<Self>> {
349 // 使用NonNull来避免空指针
350 let non_null_ptr = std::ptr::NonNull::new(void_ptr as *mut Self);
351 // 安全地解引用NonNull指针并创建一个新的Box
352 non_null_ptr.map(|ptr| Box::from_raw(ptr.as_ptr() as *mut Self))
353 }
354 }
355 };
356
357 // Return the generated implementation
358 TokenStream::from(expanded)
359}