Skip to content

Commit c8c20a6

Browse files
DrChatemilio
authored andcommitted
Deduplicate dyngen code
1 parent 75eaaa6 commit c8c20a6

File tree

1 file changed

+27
-25
lines changed

1 file changed

+27
-25
lines changed

src/codegen/dyngen.rs

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -131,39 +131,41 @@ impl DynamicItems {
131131
assert_eq!(args.len(), args_identifiers.len());
132132
}
133133

134-
self.struct_members.push(
135-
if is_required {
136-
quote! {
137-
pub #ident: unsafe extern #abi fn ( #( #args),* ) #ret,
138-
}
139-
} else {
140-
quote! {
141-
pub #ident: Result<unsafe extern #abi fn ( #( #args ),* ) #ret, ::libloading::Error>,
142-
}
134+
let signature = quote! { unsafe extern #abi fn ( #( #args),* ) #ret };
135+
let member = if is_required {
136+
signature
137+
} else {
138+
quote! { Result<#signature, ::libloading::Error> }
139+
};
140+
141+
self.struct_members.push(quote! {
142+
pub #ident: #member,
143+
});
144+
145+
// N.B: If the signature was required, it won't be wrapped in a Result<...>
146+
// and we can simply call it directly.
147+
let call_body = if is_required {
148+
quote! {
149+
self.#ident(#( #args_identifiers ),*)
150+
}
151+
} else {
152+
quote! {
153+
let sym = self.#ident.as_ref().expect("Expected function, got error.");
154+
(sym)(#( #args_identifiers ),*)
143155
}
144-
);
156+
};
145157

146158
// We can't implement variadic functions from C easily, so we allow to
147159
// access the function pointer so that the user can call it just fine.
148160
if !is_variadic {
149-
self.struct_implementation.push(
150-
if is_required {
151-
quote! {
152-
pub unsafe fn #ident ( &self, #( #args ),* ) -> #ret_ty {
153-
self.#ident(#( #args_identifiers ),*)
154-
}
155-
}
156-
} else {
157-
quote! {
158-
pub unsafe fn #ident ( &self, #( #args ),* ) -> #ret_ty {
159-
let sym = self.#ident.as_ref().expect("Expected function, got error.");
160-
(sym)(#( #args_identifiers ),*)
161-
}
162-
}
161+
self.struct_implementation.push(quote! {
162+
pub unsafe fn #ident ( &self, #( #args ),* ) -> #ret_ty {
163+
#call_body
163164
}
164-
);
165+
});
165166
}
166167

168+
// N.B: Unwrap the signature upon construction if it is required to be resolved.
167169
let ident_str = codegen::helpers::ast_ty::cstr_expr(ident.to_string());
168170
self.constructor_inits.push(if is_required {
169171
quote! {

0 commit comments

Comments
 (0)