From a6e23d731ef4feca3d2b24d784bff7c53f8adb64 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Thu, 29 Sep 2022 11:59:56 +0200 Subject: [PATCH] api: Slighty reduce the amount of macro-generated code By moving format(_args)! usage into a regular fn and calling that from the proc-macro-generated code. --- crates/ruma-common/src/api.rs | 16 +++++++++++- .../ruma-macros/src/api/request/outgoing.rs | 25 +++++++++++-------- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/crates/ruma-common/src/api.rs b/crates/ruma-common/src/api.rs index 97fc0c47..5b3cb229 100644 --- a/crates/ruma-common/src/api.rs +++ b/crates/ruma-common/src/api.rs @@ -399,9 +399,23 @@ pub enum AuthScheme { QueryOnlyAccessToken, } +// This function needs to be public, yet hidden, as it is used the code generated by `ruma_api!`. +#[doc(hidden)] +pub fn make_endpoint_url( + base_url: &str, + path: fmt::Arguments<'_>, + query_string: Option<&str>, +) -> String { + let base = base_url.strip_suffix('/').unwrap_or(base_url); + match query_string { + Some(query) => format!("{base}{path}?{query}"), + None => format!("{base}{path}"), + } +} + // This function helps picks the right path (or an error) from a set of matrix versions. // -// This function needs to be public, yet hidden, as all `try_into_http_request`s would be using it. +// This function needs to be public, yet hidden, as it is used the code generated by `ruma_api!`. #[doc(hidden)] pub fn select_path<'a>( versions: &'_ [MatrixVersion], diff --git a/crates/ruma-macros/src/api/request/outgoing.rs b/crates/ruma-macros/src/api/request/outgoing.rs index ace4aba8..47ecfc8f 100644 --- a/crates/ruma-macros/src/api/request/outgoing.rs +++ b/crates/ruma-macros/src/api/request/outgoing.rs @@ -60,9 +60,8 @@ impl Request { let request_query = RequestQuery(self.#field_name); assert_trait_impl(&request_query.0); - format_args!( - "?{}", - #ruma_common::serde::urlencoded::to_string(request_query)? + ::std::option::Option::Some( + &#ruma_common::serde::urlencoded::to_string(request_query)? ) }} } else if self.has_query_fields() { @@ -76,13 +75,12 @@ impl Request { #request_query_init_fields }; - format_args!( - "?{}", - #ruma_common::serde::urlencoded::to_string(request_query)? + ::std::option::Option::Some( + &#ruma_common::serde::urlencoded::to_string(request_query)? ) }} } else { - quote! { "" } + quote! { ::std::option::Option::None } }; // If there are no body fields, the request body will be empty (not `{}`), so the @@ -195,10 +193,15 @@ impl Request { let mut req_builder = #http::Request::builder() .method(#http::Method::#method) - .uri(::std::format!( - "{}{}{}", - base_url.strip_suffix('/').unwrap_or(base_url), - #ruma_common::api::select_path(considering_versions, &metadata, #unstable_path, #r0_path, #stable_path)?, + .uri(#ruma_common::api::make_endpoint_url( + base_url, + #ruma_common::api::select_path( + considering_versions, + &metadata, + #unstable_path, + #r0_path, + #stable_path, + )?, #request_query_string, ));