util-macros (0.1.0)
Published 2026-02-03 17:45:37 +00:00 by irith
Installation
[registries.forgejo]
index = "sparse+ " # Sparse index
# index = " " # Git
[net]
git-fetch-with-cli = truecargo add util-macros@0.1.0 --registry forgejoAbout this package
Some helper Rust macros.
util-macros
Some helper Rust macros.
AutoNew derive macro
Adding on #[derive(AutoNew)]:
/// On structs only.
#[derive(AutoNew)]
pub struct Alpha {
foo: usize,
bar: String,
}
produces:
impl Alpha {
pub fn new(foo: usize, bar: String) -> Self {
Self {foo, bar}
}
}
AutoIntoResponse derive macro + auto_into_response attribute
Adding on #[derive(AutoIntoResponse)] and #[auto_into_response(status_code, is_transparent)]:
/// On structs...
#[derive(AutoIntoResponse)]
#[auto_into_response(StatusCode::UNPROCESSABLE_ENTITY, true)]
pub struct Alpha(String);
/// ...and enums.
#[derive(AutoIntoResponse)]
pub enum Bravo {
#[auto_into_response(StatusCode::INTERNAL_SERVER_ERROR, false)]
Foo(String),
#[auto_into_response(StatusCode::CONFLICT, true)]
Bar(String),
}
adds:
impl IntoResponse for Alpha {
fn into_response(self) -> Response {
let mut error = self.to_string();
error!("{}", error);
let status_code = {
let status_code = StatusCode::UNPROCESSABLE_ENTITY;
error = status_code.canonical_reason()
.expect("StatusCode had no canonical reason?")
.to_string();
status_code
};
let response = HTTPErrorResponse::new(error);
(status_code, Json(response)).into_response()
}
}
impl IntoResponse for Bravo {
fn into_response(self) -> Response {
let mut error = self.to_string();
error!("{}", error);
let status_code = match self {
Self::Foo(_) => StatusCode::INTERNAL_SERVER_ERROR,
Self::Bar(_, _) => {
let status_code = StatusCode::CONFLICT;
error = status_code.canonical_reason()
.expect("StatusCode had no canonical reason?")
.to_string();
status_code
},
};
let response = HTTPErrorResponse::new(error);
(status_code, Json(response)).into_response()
}
}
...where the following is relied on in the client code:
http::StatusCodetracing::erroraxum::response::IntoResponseaxum::response::Responseaxum::extract::JsonHTTPErrorResponse(this is a custom struct that implementsIntoResponse^)
AutoDeserialize derive macro + auto_deserialize attribute
Adding on #[derive(AutoDeserialize)] and #[auto_deserialize(type)]:
/// On structs only.
#[derive(AutoDeserialize)]
pub struct Alpha {
#[auto_deserialize(String)]
foo: Foo,
#[auto_deserialize(String)]
bar: Bar,
}
gives you:
#[derive(Debug, Deserialize)]
pub struct RawAlpha {
foo: String,
bar: String,
}
impl TryFrom<RawAlpha> for Alpha {
type Error = ErrorResponse;
fn try_from(raw: RawAlpha) -> Result<Self, Self::Error> {
let foo = Foo::new(&raw.foo)?;
let bar = Bar::new(&raw.bar)?;
Ok(Self::new(foo, bar))
}
}
...making use of the following:
serde::Deserializeaxum::response::ErrorResponse
Dependencies
| ID | Version |
|---|---|
| proc-macro-error | ^1.0 |
| proc-macro2 | ^1.0 |
| quote | ^1.0 |
| syn | ^2.0 |
Details
Assets (1)
Versions (4)
View all
util-macros-0.1.0.crate
17 KiB