Skip to content

Instantly share code, notes, and snippets.

@graysonarts
Last active November 21, 2023 18:21
Show Gist options
  • Save graysonarts/98e7a5f12c7344ec1a15ea99b3e0a683 to your computer and use it in GitHub Desktop.
Save graysonarts/98e7a5f12c7344ec1a15ea99b3e0a683 to your computer and use it in GitHub Desktop.
Helpful Macros for common rust things I run into
macro_rules! string_value_type {
($TypeName:ident $(~$derive_name:ident)*) => {
#[derive($($derive_name),*)]
pub struct $TypeName(String);
impl From<&str> for $TypeName {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<String> for $TypeName {
fn from(value: String) -> Self {
Self(value)
}
}
impl std::ops::Deref for $TypeName {
type Target = str;
fn deref(&self) -> &Self::Target {
return &self.0;
}
}
};
}
/// calls an async block from a sync context.
///
/// Usage:
///
/// ```
/// let result = block_on!({query_file_as!(PgUser, "queries/users/list.sql")
/// .fetch_all(&self.pool)
/// .await})?;
/// ```
macro_rules! block_on {
($b:block) => {{
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(async $b)
}};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment