rust-analyzer/crates/stdx/src/macros.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

68 lines
2 KiB
Rust
Raw Normal View History

2020-07-13 13:54:12 +00:00
//! Convenience macros.
2020-07-13 13:54:12 +00:00
/// Appends formatted string to a `String`.
#[macro_export]
macro_rules! format_to {
($buf:expr) => ();
($buf:expr, $lit:literal $($arg:tt)*) => {
2023-09-22 06:08:00 +00:00
{
use ::std::fmt::Write as _;
// We can't do ::std::fmt::Write::write_fmt($buf, format_args!($lit $($arg)*))
// unfortunately, as that loses out on autoref behavior.
_ = $buf.write_fmt(format_args!($lit $($arg)*))
}
2020-07-13 13:54:12 +00:00
};
2024-01-30 13:12:42 +00:00
}
/// Appends formatted string to a `String` and returns the `String`.
///
/// Useful for folding iterators into a `String`.
#[macro_export]
macro_rules! format_to_acc {
($buf:expr, $lit:literal $($arg:tt)*) => {
{
use ::std::fmt::Write as _;
// We can't do ::std::fmt::Write::write_fmt($buf, format_args!($lit $($arg)*))
// unfortunately, as that loses out on autoref behavior.
_ = $buf.write_fmt(format_args!($lit $($arg)*));
$buf
}
};
2020-07-13 13:54:12 +00:00
}
2020-09-01 08:26:10 +00:00
/// Generates `From` impls for `Enum E { Foo(Foo), Bar(Bar) }` enums
///
/// # Example
///
/// ```rust
/// impl_from!(Struct, Union, Enum for Adt);
/// ```
#[macro_export]
macro_rules! impl_from {
($($variant:ident $(($($sub_variant:ident),*))?),* for $enum:ident) => {
$(
impl From<$variant> for $enum {
fn from(it: $variant) -> $enum {
$enum::$variant(it)
}
}
$($(
impl From<$sub_variant> for $enum {
fn from(it: $sub_variant) -> $enum {
$enum::$variant($variant::$sub_variant(it))
}
}
)*)?
)*
2023-01-31 10:49:49 +00:00
};
($($variant:ident$(<$V:ident>)?),* for $enum:ident) => {
$(
impl$(<$V>)? From<$variant$(<$V>)?> for $enum$(<$V>)? {
fn from(it: $variant$(<$V>)?) -> $enum$(<$V>)? {
$enum::$variant(it)
}
}
)*
}
}