Add #[must_use] to types and methods (#3395)

Co-authored-by: Theodore Bjernhed <fosseder@danwin1210.de>
This commit is contained in:
Theodore Bjernhed 2025-07-05 19:07:24 +02:00 committed by GitHub
parent d7104313cb
commit fb64e72de9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
22 changed files with 59 additions and 6 deletions

View File

@ -35,10 +35,12 @@ lossy_float_literal = "warn"
macro_use_imports = "warn"
match_wildcard_for_single_variants = "warn"
mem_forget = "warn"
must_use_candidate = "warn"
needless_borrow = "warn"
needless_continue = "warn"
option_option = "warn"
rest_pat_in_fully_bound_structs = "warn"
return_self_not_must_use = "warn"
str_to_string = "warn"
suboptimal_flops = "warn"
todo = "warn"

View File

@ -34,6 +34,7 @@ where
}
/// The body type used in axum requests and responses.
#[must_use]
#[derive(Debug)]
pub struct Body(BoxBody);
@ -135,6 +136,7 @@ impl http_body::Body for Body {
/// A stream of data frames.
///
/// Created with [`Body::into_data_stream`].
#[must_use]
#[derive(Debug)]
pub struct BodyDataStream {
inner: Body,

View File

@ -16,6 +16,7 @@ impl Error {
}
/// Convert an `Error` back into the underlying boxed trait object.
#[must_use]
pub fn into_inner(self) -> BoxError {
self.inner
}

View File

@ -106,11 +106,13 @@ macro_rules! __define_rejection {
}
/// Get the response body text used for this rejection.
#[must_use]
pub fn body_text(&self) -> String {
self.to_string()
}
/// Get the status code used for this rejection.
#[must_use]
pub fn status(&self) -> http::StatusCode {
http::StatusCode::$status
}
@ -179,6 +181,7 @@ macro_rules! __composite_rejection {
impl $name {
/// Get the response body text used for this rejection.
#[must_use]
pub fn body_text(&self) -> String {
match self {
$(
@ -188,6 +191,7 @@ macro_rules! __composite_rejection {
}
/// Get the status code used for this rejection.
#[must_use]
pub fn status(&self) -> http::StatusCode {
match self {
$(

View File

@ -84,6 +84,7 @@ pub use cookie::Key;
/// .route("/me", get(me));
/// # let app: Router = app;
/// ```
#[must_use = "`CookieJar` should be returned as part of a `Response`, otherwise it does nothing."]
#[derive(Debug, Default, Clone)]
pub struct CookieJar {
jar: cookie::CookieJar,
@ -153,6 +154,7 @@ impl CookieJar {
/// .map(|cookie| cookie.value().to_owned());
/// }
/// ```
#[must_use]
pub fn get(&self, name: &str) -> Option<&Cookie<'static>> {
self.jar.get(name)
}
@ -169,7 +171,6 @@ impl CookieJar {
/// jar.remove(Cookie::from("foo"))
/// }
/// ```
#[must_use]
pub fn remove<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self {
self.jar.remove(cookie);
self
@ -189,7 +190,6 @@ impl CookieJar {
/// jar.add(Cookie::new("foo", "bar"))
/// }
/// ```
#[must_use]
#[allow(clippy::should_implement_trait)]
pub fn add<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self {
self.jar.add(cookie);

View File

@ -104,6 +104,7 @@ use std::{convert::Infallible, fmt, marker::PhantomData};
/// }
/// }
/// ```
#[must_use = "`PrivateCookieJar` should be returned as part of a `Response`, otherwise it does nothing."]
pub struct PrivateCookieJar<K = Key> {
jar: cookie::CookieJar,
key: Key,
@ -201,6 +202,7 @@ impl<K> PrivateCookieJar<K> {
/// .map(|cookie| cookie.value().to_owned());
/// }
/// ```
#[must_use]
pub fn get(&self, name: &str) -> Option<Cookie<'static>> {
self.private_jar().get(name)
}
@ -217,7 +219,6 @@ impl<K> PrivateCookieJar<K> {
/// jar.remove(Cookie::from("foo"))
/// }
/// ```
#[must_use]
pub fn remove<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self {
self.private_jar_mut().remove(cookie);
self
@ -237,7 +238,6 @@ impl<K> PrivateCookieJar<K> {
/// jar.add(Cookie::new("foo", "bar"))
/// }
/// ```
#[must_use]
#[allow(clippy::should_implement_trait)]
pub fn add<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self {
self.private_jar_mut().add(cookie);
@ -246,6 +246,7 @@ impl<K> PrivateCookieJar<K> {
/// Authenticates and decrypts `cookie`, returning the plaintext version if decryption succeeds
/// or `None` otherwise.
#[must_use]
pub fn decrypt(&self, cookie: Cookie<'static>) -> Option<Cookie<'static>> {
self.private_jar().decrypt(cookie)
}
@ -284,6 +285,7 @@ impl<K> IntoResponse for PrivateCookieJar<K> {
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
struct PrivateCookieJarIter<'a, K> {
jar: &'a PrivateCookieJar<K>,
iter: cookie::Iter<'a>,

View File

@ -121,6 +121,7 @@ use std::{convert::Infallible, fmt, marker::PhantomData};
/// }
/// }
/// ```
#[must_use = "`SignedCookieJar` should be returned as part of a `Response`, otherwise it does nothing."]
pub struct SignedCookieJar<K = Key> {
jar: cookie::CookieJar,
key: Key,
@ -219,6 +220,7 @@ impl<K> SignedCookieJar<K> {
/// .map(|cookie| cookie.value().to_owned());
/// }
/// ```
#[must_use]
pub fn get(&self, name: &str) -> Option<Cookie<'static>> {
self.signed_jar().get(name)
}
@ -235,7 +237,6 @@ impl<K> SignedCookieJar<K> {
/// jar.remove(Cookie::from("foo"))
/// }
/// ```
#[must_use]
pub fn remove<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self {
self.signed_jar_mut().remove(cookie);
self
@ -255,7 +256,6 @@ impl<K> SignedCookieJar<K> {
/// jar.add(Cookie::new("foo", "bar"))
/// }
/// ```
#[must_use]
#[allow(clippy::should_implement_trait)]
pub fn add<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self {
self.signed_jar_mut().add(cookie);
@ -264,6 +264,7 @@ impl<K> SignedCookieJar<K> {
/// Verifies the authenticity and integrity of `cookie`, returning the plaintext version if
/// verification succeeds or `None` otherwise.
#[must_use]
pub fn verify(&self, cookie: Cookie<'static>) -> Option<Cookie<'static>> {
self.signed_jar().verify(cookie)
}
@ -302,6 +303,7 @@ impl<K> IntoResponse for SignedCookieJar<K> {
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
struct SignedCookieJarIter<'a, K> {
jar: &'a SignedCookieJar<K>,
iter: cookie::Iter<'a>,

View File

@ -150,6 +150,7 @@ impl Field {
/// The field name found in the
/// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
/// header.
#[must_use]
pub fn name(&self) -> Option<&str> {
self.inner.name()
}
@ -157,16 +158,19 @@ impl Field {
/// The file name found in the
/// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
/// header.
#[must_use]
pub fn file_name(&self) -> Option<&str> {
self.inner.file_name()
}
/// Get the [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) of the field.
#[must_use]
pub fn content_type(&self) -> Option<&str> {
self.inner.content_type().map(|m| m.as_ref())
}
/// Get a map of headers as [`HeaderMap`].
#[must_use]
pub fn headers(&self) -> &HeaderMap {
self.inner.headers()
}
@ -253,6 +257,7 @@ impl MultipartError {
}
/// Get the status code used for this rejection.
#[must_use]
pub fn status(&self) -> http::StatusCode {
status_code_from_multer_error(&self.source)
}

View File

@ -44,6 +44,7 @@ use tokio_util::io::ReaderStream;
/// let app = Router::new().route("/file-stream", get(file_stream));
/// # let _: Router = app;
/// ```
#[must_use]
#[derive(Debug)]
pub struct FileStream<S> {
/// stream.

View File

@ -8,6 +8,7 @@ use mime::Mime;
/// Create multipart forms to be used in API responses.
///
/// This struct implements [`IntoResponse`], and so it can be returned from a handler.
#[must_use]
#[derive(Debug)]
pub struct MultipartForm {
parts: Vec<Part>,
@ -103,6 +104,7 @@ impl Part {
/// let parts: Vec<Part> = vec![Part::text("foo".to_string(), "abc")];
/// let form = MultipartForm::from_iter(parts);
/// ```
#[must_use]
pub fn text(name: String, contents: &str) -> Self {
Self {
name,
@ -127,6 +129,7 @@ impl Part {
/// let parts: Vec<Part> = vec![Part::file("foo", "foo.txt", vec![0x68, 0x68, 0x20, 0x6d, 0x6f, 0x6d])];
/// let form = MultipartForm::from_iter(parts);
/// ```
#[must_use]
pub fn file(field_name: &str, file_name: &str, contents: Vec<u8>) -> Self {
Self {
name: field_name.to_owned(),

View File

@ -28,6 +28,7 @@ pub use self::typed::{SecondElementIs, TypedPath};
// Validates a path at compile time, used with the vpath macro.
#[rustversion::since(1.80)]
#[doc(hidden)]
#[must_use]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
if path.is_empty() {
panic!("Paths must start with a `/`. Use \"/\" for root routes")
@ -76,6 +77,7 @@ macro_rules! vpath {
}
/// Extension trait that adds additional methods to [`Router`].
#[allow(clippy::return_self_not_must_use)]
pub trait RouterExt<S>: sealed::Sealed {
/// Add a typed `GET` route to the router.
///

View File

@ -137,11 +137,13 @@ pub struct TypedHeaderRejection {
impl TypedHeaderRejection {
/// Name of the header that caused the rejection
#[must_use]
pub fn name(&self) -> &http::header::HeaderName {
self.name
}
/// Reason why the header extraction has failed
#[must_use]
pub fn reason(&self) -> &TypedHeaderRejectionReason {
&self.reason
}

View File

@ -58,6 +58,7 @@ pub struct MatchedPath(pub(crate) Arc<str>);
impl MatchedPath {
/// Returns a `str` representation of the path.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}

View File

@ -146,6 +146,7 @@ impl Field<'_> {
/// The field name found in the
/// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
/// header.
#[must_use]
pub fn name(&self) -> Option<&str> {
self.inner.name()
}
@ -153,16 +154,19 @@ impl Field<'_> {
/// The file name found in the
/// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
/// header.
#[must_use]
pub fn file_name(&self) -> Option<&str> {
self.inner.file_name()
}
/// Get the [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) of the field.
#[must_use]
pub fn content_type(&self) -> Option<&str> {
self.inner.content_type().map(|m| m.as_ref())
}
/// Get a map of headers as [`HeaderMap`].
#[must_use]
pub fn headers(&self) -> &HeaderMap {
self.inner.headers()
}
@ -238,11 +242,13 @@ impl MultipartError {
}
/// Get the response body text used for this rejection.
#[must_use]
pub fn body_text(&self) -> String {
self.source.to_string()
}
/// Get the status code used for this rejection.
#[must_use]
pub fn status(&self) -> http::StatusCode {
status_code_from_multer_error(&self.source)
}

View File

@ -41,6 +41,7 @@ pub struct NestedPath(Arc<str>);
impl NestedPath {
/// Returns a `str` representation of the path.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}

View File

@ -279,6 +279,7 @@ impl std::error::Error for PathDeserializationError {}
/// This type is obtained through [`FailedToDeserializePathParams::kind`] or
/// [`FailedToDeserializePathParams::into_kind`] and is useful for building
/// more precise error messages.
#[must_use]
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
@ -417,6 +418,7 @@ impl FailedToDeserializePathParams {
}
/// Get the response body text used for this rejection.
#[must_use]
pub fn body_text(&self) -> String {
match self.0.kind {
ErrorKind::Message(_)
@ -432,6 +434,7 @@ impl FailedToDeserializePathParams {
}
/// Get the status code used for this rejection.
#[must_use]
pub fn status(&self) -> StatusCode {
match self.0.kind {
ErrorKind::Message(_)
@ -523,6 +526,7 @@ where
impl RawPathParams {
/// Get an iterator over the path parameters.
#[must_use]
pub fn iter(&self) -> RawPathParamsIter<'_> {
self.into_iter()
}
@ -561,11 +565,13 @@ pub struct InvalidUtf8InPathParam {
impl InvalidUtf8InPathParam {
/// Get the response body text used for this rejection.
#[must_use]
pub fn body_text(&self) -> String {
self.to_string()
}
/// Get the status code used for this rejection.
#[must_use]
pub fn status(&self) -> StatusCode {
StatusCode::BAD_REQUEST
}

View File

@ -128,6 +128,7 @@ use tokio_tungstenite::{
///
/// [`MethodFilter`]: crate::routing::MethodFilter
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
#[must_use]
pub struct WebSocketUpgrade<F = DefaultOnFailedUpgrade> {
config: WebSocketConfig,
/// The chosen protocol sent in the `Sec-WebSocket-Protocol` header of the response.
@ -580,6 +581,7 @@ pub struct Utf8Bytes(ts::Utf8Bytes);
impl Utf8Bytes {
/// Creates from a static str.
#[inline]
#[must_use]
pub const fn from_static(str: &'static str) -> Self {
Self(ts::Utf8Bytes::from_static(str))
}

View File

@ -56,11 +56,13 @@ impl Redirect {
}
/// Returns the HTTP status code of the `Redirect`.
#[must_use]
pub fn status_code(&self) -> StatusCode {
self.status_code
}
/// Returns the `Redirect`'s URI.
#[must_use]
pub fn location(&self) -> &str {
&self.location
}

View File

@ -58,6 +58,7 @@ impl MethodFilter {
}
/// Performs the OR operation between the [`MethodFilter`] in `self` with `other`.
#[must_use]
pub const fn or(self, other: Self) -> Self {
Self(self.0 | other.0)
}

View File

@ -703,6 +703,7 @@ impl MethodRouter<(), Infallible> {
/// ```
///
/// [`MakeService`]: tower::make::MakeService
#[must_use]
pub fn into_make_service(self) -> IntoMakeService<Self> {
IntoMakeService::new(self.with_state(()))
}
@ -736,6 +737,7 @@ impl MethodRouter<(), Infallible> {
/// [`MakeService`]: tower::make::MakeService
/// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
#[cfg(feature = "tokio")]
#[must_use]
pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
IntoMakeServiceWithConnectInfo::new(self.with_state(()))
}

View File

@ -317,6 +317,7 @@ where
}
/// True if the router currently has at least one route added.
#[must_use]
pub fn has_routes(&self) -> bool {
self.inner.path_router.has_routes()
}
@ -513,6 +514,7 @@ where
///
/// This is the same as [`Router::as_service`] instead it returns an owned [`Service`]. See
/// that method for more details.
#[must_use]
pub fn into_service<B>(self) -> RouterIntoService<B, S> {
RouterIntoService {
router: self,
@ -540,6 +542,7 @@ impl Router {
/// ```
///
/// [`MakeService`]: tower::make::MakeService
#[must_use]
pub fn into_make_service(self) -> IntoMakeService<Self> {
// call `Router::with_state` such that everything is turned into `Route` eagerly
// rather than doing that per request
@ -548,6 +551,7 @@ impl Router {
#[doc = include_str!("../docs/routing/into_make_service_with_connect_info.md")]
#[cfg(feature = "tokio")]
#[must_use]
pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
// call `Router::with_state` such that everything is turned into `Route` eagerly
// rather than doing that per request

View File

@ -83,11 +83,13 @@ impl TestClient {
}
#[allow(dead_code)]
#[must_use]
pub fn server_port(&self) -> u16 {
self.addr.port()
}
}
#[must_use]
pub struct RequestBuilder {
builder: reqwest::RequestBuilder,
}