#proc-macro #enums #match #variant #arms #procedural #copy-pastes

all-the-same

一个用于为新类型变体枚举复制粘贴匹配分支的过程宏

2个稳定版本

1.1.0 2024年2月6日
1.0.0 2024年2月6日

#530过程宏

Download history 163/week @ 2024-07-28

每月下载量:163

BSD-3-Clause

11KB
85

完全一样!

如果你曾经有如下类似的代码

use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::AsyncWrite;
use tokio::net::{TcpStream, UnixStream};

enum Stream {
    Tcp(TcpStream),
    Unix(UnixStream),
    Custom(Box<dyn AsyncWrite + Unpin + 'static>),
}

impl AsyncWrite for Stream {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, io::Error>> {
        match self.get_mut() {
            Stream::Tcp(s) => Pin::new(s).poll_write(cx, buf),
            Stream::Unix(s) => Pin::new(s).poll_write(cx, buf),
            Stream::Custom(s) => Pin::new(s).poll_write(cx, buf),
        }
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
        match self.get_mut() {
            Stream::Tcp(s) => Pin::new(s).poll_shutdown(cx),
            Stream::Unix(s) => Pin::new(s).poll_shutdown(cx),
            Stream::Custom(s) => Pin::new(s).poll_shutdown(cx),
        }
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        match self.get_mut() {
            Stream::Tcp(s) => Pin::new(s).poll_flush(cx),
            Stream::Unix(s) => Pin::new(s).poll_flush(cx),
            Stream::Custom(s) => Pin::new(s).poll_flush(cx),
        }
    }
}

借助宏的帮助,你现在可以将其替换为

use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::AsyncWrite;
use tokio::net::{TcpStream, UnixStream};
use all_the_same::all_the_same;

enum Stream {
    Tcp(TcpStream),
    Unix(UnixStream),
    Custom(Box<dyn AsyncWrite + Unpin + 'static>),
}

impl AsyncWrite for Stream {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, io::Error>> {
        all_the_same!(match self.get_mut() {
            Stream::[Tcp, Unix, Custom](s) => Pin::new(s).poll_write(cx, buf)
        })
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
        all_the_same!(match self.get_mut() {
            Stream::[Tcp, Unix, Custom](s) => Pin::new(s).poll_shutdown(cx)
        })
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        all_the_same!(match self.get_mut() {
            Stream::[Tcp, Unix, Custom](s) => Pin::new(s).poll_flush(cx)
        })
    }
}

功能门控枚举变体等。

顺便说一句,你可以添加应用于匹配分支的属性,以处理功能门控枚举变体

use all_the_same::all_the_same;

enum Variants {
    Foo(String),

    #[cfg(test)]
    Bar(String)
}

impl Variants {
    pub fn value(&self) -> &str {
        all_the_same!(match self {
            Variants::[Foo, #[cfg(test)]Bar](v) => v
        })
    }
}

依赖关系

~1.5MB
~35K SLoC