Skip to content

Update deps + clippy + typos #517

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -28,10 +28,10 @@ serde = ["serde_qs", "serde_crate", "serde_json", "serde_urlencoded", "url/serde

[dependencies]
fastrand = "1.4.0"
base64 = "0.13.0"
base64 = "0.21.0"
futures-lite = "1.11.1"
async-channel = "1.5.1"
infer = "0.7.0"
infer = "0.13.0"
pin-project-lite = "0.2.0"
url = "2.1.1"
anyhow = "1.0.26"
@@ -43,14 +43,13 @@ async-std = { version = "1.6.0", optional = true }
http = { version = "0.2.0", optional = true }

# features: cookies
cookie = { version = "0.16.0", features = ["percent-encode"], optional = true }
cookie = { version = "0.17.0", features = ["percent-encode"], optional = true }

# features: serde
serde_json = { version = "1.0.51", optional = true }
serde_crate = { version = "1.0.106", features = ["derive"], optional = true, package = "serde" }
serde_urlencoded = { version = "0.7.0", optional = true}
serde_qs = { version = "0.9.1", optional = true }

serde_qs = { version = "0.12.0", optional = true }

[dev-dependencies]
http = "0.2.0"
8 changes: 4 additions & 4 deletions src/auth/authorization.rs
Original file line number Diff line number Diff line change
@@ -38,6 +38,7 @@ pub struct Authorization {

impl Authorization {
/// Create a new instance of `Authorization`.
#[must_use]
pub fn new(scheme: AuthenticationScheme, credentials: String) -> Self {
Self {
scheme,
@@ -47,10 +48,7 @@ impl Authorization {

/// Create a new instance from headers.
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
let headers = match headers.as_ref().get(AUTHORIZATION) {
Some(headers) => headers,
None => return Ok(None),
};
let Some(headers) = headers.as_ref().get(AUTHORIZATION) else { return Ok(None) };

// If we successfully parsed the header then there's always at least one
// entry. We want the last entry.
@@ -72,6 +70,7 @@ impl Authorization {
}

/// Get the authorization scheme.
#[must_use]
pub fn scheme(&self) -> AuthenticationScheme {
self.scheme
}
@@ -82,6 +81,7 @@ impl Authorization {
}

/// Get the authorization credentials.
#[must_use]
pub fn credentials(&self) -> &str {
self.credentials.as_str()
}
13 changes: 7 additions & 6 deletions src/auth/basic_auth.rs
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@ use crate::{
headers::Header,
};
use crate::{bail_status as bail, ensure_status as ensure};
use base64::{engine::general_purpose, Engine};

/// HTTP Basic authorization.
///
@@ -54,10 +55,7 @@ impl BasicAuth {

/// Create a new instance from headers.
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
let auth = match Authorization::from_headers(headers)? {
Some(auth) => auth,
None => return Ok(None),
};
let Some(auth) = Authorization::from_headers(headers)? else { return Ok(None) };

let scheme = auth.scheme();
ensure!(
@@ -71,7 +69,7 @@ impl BasicAuth {

/// Create a new instance from the base64 encoded credentials.
pub fn from_credentials(credentials: impl AsRef<[u8]>) -> crate::Result<Self> {
let bytes = base64::decode(credentials).status(400)?;
let bytes = general_purpose::STANDARD.decode(credentials).status(400)?;
let credentials = String::from_utf8(bytes).status(400)?;

let mut iter = credentials.splitn(2, ':');
@@ -88,11 +86,13 @@ impl BasicAuth {
}

/// Get the username.
#[must_use]
pub fn username(&self) -> &str {
self.username.as_str()
}

/// Get the password.
#[must_use]
pub fn password(&self) -> &str {
self.password.as_str()
}
@@ -105,7 +105,8 @@ impl Header for BasicAuth {

fn header_value(&self) -> HeaderValue {
let scheme = AuthenticationScheme::Basic;
let credentials = base64::encode(format!("{}:{}", self.username, self.password));
let credentials =
general_purpose::STANDARD.encode(format!("{}:{}", self.username, self.password));
let auth = Authorization::new(scheme, credentials);
auth.header_value()
}
13 changes: 5 additions & 8 deletions src/auth/www_authenticate.rs
Original file line number Diff line number Diff line change
@@ -44,16 +44,14 @@ pub struct WwwAuthenticate {

impl WwwAuthenticate {
/// Create a new instance of `WwwAuthenticate`.
#[must_use]
pub fn new(scheme: AuthenticationScheme, realm: String) -> Self {
Self { scheme, realm }
}

/// Create a new instance from headers.
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
let headers = match headers.as_ref().get(WWW_AUTHENTICATE) {
Some(headers) => headers,
None => return Ok(None),
};
let Some(headers) = headers.as_ref().get(WWW_AUTHENTICATE) else { return Ok(None) };

// If we successfully parsed the header then there's always at least one
// entry. We want the last entry.
@@ -69,10 +67,7 @@ impl WwwAuthenticate {
};

let realm = realm.trim_start();
let realm = match realm.strip_prefix(r#"realm=""#) {
Some(realm) => realm,
None => bail!(400, "realm not found"),
};
let Some(realm) = realm.strip_prefix(r#"realm=""#) else { bail!(400, "realm not found") };

let mut chars = realm.chars();
let mut closing_quote = false;
@@ -94,6 +89,7 @@ impl WwwAuthenticate {
}

/// Get the authorization scheme.
#[must_use]
pub fn scheme(&self) -> AuthenticationScheme {
self.scheme
}
@@ -104,6 +100,7 @@ impl WwwAuthenticate {
}

/// Get the authorization realm.
#[must_use]
pub fn realm(&self) -> &str {
self.realm.as_str()
}
14 changes: 11 additions & 3 deletions src/body.rs
Original file line number Diff line number Diff line change
@@ -76,6 +76,7 @@ impl Body {
/// let mut req = Response::new(StatusCode::Ok);
/// req.set_body(Body::empty());
/// ```
#[must_use]
pub fn empty() -> Self {
Self {
reader: Box::new(io::empty()),
@@ -129,6 +130,7 @@ impl Body {
/// let body = Body::from_reader(cursor, None);
/// let _ = body.into_reader();
/// ```
#[must_use]
pub fn into_reader(self) -> Box<dyn AsyncBufRead + Unpin + Send + Sync + 'static> {
self.reader
}
@@ -151,6 +153,7 @@ impl Body {
/// let input = vec![1, 2, 3];
/// req.set_body(Body::from_bytes(input));
/// ```
#[must_use]
pub fn from_bytes(bytes: Vec<u8>) -> Self {
Self {
mime: Some(mime::BYTE_STREAM),
@@ -201,6 +204,7 @@ impl Body {
/// let input = String::from("hello Nori!");
/// req.set_body(Body::from_string(input));
/// ```
#[must_use]
pub fn from_string(s: String) -> Self {
Self {
mime: Some(mime::PLAIN),
@@ -464,16 +468,19 @@ impl Body {
/// let body = Body::from_reader(cursor, Some(len));
/// assert_eq!(body.len(), Some(10));
/// ```
#[must_use]
pub fn len(&self) -> Option<u64> {
self.length
}

/// Returns `true` if the body has a length of zero, and `false` otherwise.
#[must_use]
pub fn is_empty(&self) -> Option<bool> {
self.length.map(|length| length == 0)
}

/// Returns the mime type of this Body.
#[must_use]
pub fn mime(&self) -> Option<&Mime> {
self.mime.as_ref()
}
@@ -517,6 +524,7 @@ impl Body {
/// assert_eq!(&body.into_string().await.unwrap(), "Hello Nori");
/// # Ok(()) }) }
/// ```
#[must_use]
pub fn chain(self, other: Body) -> Self {
let mime = if self.mime == other.mime {
self.mime.clone()
@@ -530,7 +538,7 @@ impl Body {
Self {
mime,
length,
reader: Box::new(futures_lite::io::AsyncReadExt::chain(self, other)),
reader: Box::new(io::AsyncReadExt::chain(self, other)),
bytes_read: 0,
}
}
@@ -608,7 +616,7 @@ impl AsyncBufRead for Body {
}

fn consume(mut self: Pin<&mut Self>, amt: usize) {
Pin::new(&mut self.reader).consume(amt)
Pin::new(&mut self.reader).consume(amt);
}
}

@@ -630,7 +638,7 @@ async fn peek_mime(file: &mut async_std::fs::File) -> io::Result<Option<Mime>> {
/// This is useful for plain-text formats such as HTML and CSS.
#[cfg(all(feature = "fs", not(target_os = "unknown")))]
fn guess_ext(path: &std::path::Path) -> Option<Mime> {
let ext = path.extension().and_then(|p| p.to_str());
let ext = path.extension().and_then(std::ffi::OsStr::to_str);
ext.and_then(Mime::from_extension)
}

8 changes: 4 additions & 4 deletions src/cache/age.rs
Original file line number Diff line number Diff line change
@@ -36,27 +36,27 @@ pub struct Age {

impl Age {
/// Create a new instance of `Age`.
#[must_use]
pub fn new(dur: Duration) -> Self {
Self { dur }
}

/// Create a new instance of `Age` from secs.
#[must_use]
pub fn from_secs(secs: u64) -> Self {
let dur = Duration::from_secs(secs);
Self { dur }
}

/// Get the duration from the header.
#[must_use]
pub fn duration(&self) -> Duration {
self.dur
}

/// Create an instance of `Age` from a `Headers` instance.
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
let headers = match headers.as_ref().get(AGE) {
Some(headers) => headers,
None => return Ok(None),
};
let Some(headers) = headers.as_ref().get(AGE) else { return Ok(None) };

// If we successfully parsed the header then there's always at least one
// entry. We want the last entry.
13 changes: 6 additions & 7 deletions src/cache/cache_control/cache_control.rs
Original file line number Diff line number Diff line change
@@ -37,22 +37,20 @@ pub struct CacheControl {

impl CacheControl {
/// Create a new instance of `CacheControl`.
#[must_use]
pub fn new() -> Self {
Self { entries: vec![] }
}

/// Create a new instance from headers.
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
let mut entries = vec![];
let headers = match headers.as_ref().get(CACHE_CONTROL) {
Some(headers) => headers,
None => return Ok(None),
};
let Some(headers) = headers.as_ref().get(CACHE_CONTROL) else { return Ok(None) };

for value in headers {
for part in value.as_str().trim().split(',') {
// Try and parse a directive from a str. If the directive is
// unkown we skip it.
// unknown we skip it.
if let Some(entry) = CacheDirective::from_str(part)? {
entries.push(entry);
}
@@ -67,6 +65,7 @@ impl CacheControl {
}

/// An iterator visiting all server entries.
#[must_use]
pub fn iter(&self) -> Iter<'_> {
Iter {
inner: self.entries.iter(),
@@ -90,8 +89,8 @@ impl Header for CacheControl {
for (n, directive) in self.entries.iter().enumerate() {
let directive: HeaderValue = directive.clone().into();
match n {
0 => write!(output, "{}", directive).unwrap(),
_ => write!(output, ", {}", directive).unwrap(),
0 => write!(output, "{directive}").unwrap(),
_ => write!(output, ", {directive}").unwrap(),
};
}

23 changes: 19 additions & 4 deletions src/cache/cache_control/cache_directive.rs
Original file line number Diff line number Diff line change
@@ -45,17 +45,24 @@ pub enum CacheDirective {

impl CacheDirective {
/// Check whether this directive is valid in an HTTP request.
#[must_use]
pub fn valid_in_req(&self) -> bool {
use CacheDirective::*;
use CacheDirective::{
MaxAge, MaxStale, MinFresh, NoCache, NoStore, NoTransform, OnlyIfCached,
};
matches!(
self,
MaxAge(_) | MaxStale(_) | MinFresh(_) | NoCache | NoStore | NoTransform | OnlyIfCached
)
}

/// Check whether this directive is valid in an HTTP response.
#[must_use]
pub fn valid_in_res(&self) -> bool {
use CacheDirective::*;
use CacheDirective::{
MaxAge, MustRevalidate, NoCache, NoStore, NoTransform, Private, ProxyRevalidate,
Public, SMaxAge, StaleIfError, StaleWhileRevalidate,
};
matches!(
self,
MustRevalidate
@@ -79,7 +86,11 @@ impl CacheDirective {
// function, but we cannot guarantee this to be true in the general
// sense.
pub(crate) fn from_str(s: &str) -> crate::Result<Option<Self>> {
use CacheDirective::*;
use CacheDirective::{
Immutable, MaxAge, MaxStale, MinFresh, MustRevalidate, NoCache, NoStore, NoTransform,
OnlyIfCached, Private, ProxyRevalidate, Public, SMaxAge, StaleIfError,
StaleWhileRevalidate,
};

let s = s.trim();

@@ -129,7 +140,11 @@ impl CacheDirective {

impl From<CacheDirective> for HeaderValue {
fn from(directive: CacheDirective) -> Self {
use CacheDirective::*;
use CacheDirective::{
Immutable, MaxAge, MaxStale, MinFresh, MustRevalidate, NoCache, NoStore, NoTransform,
OnlyIfCached, Private, ProxyRevalidate, Public, SMaxAge, StaleIfError,
StaleWhileRevalidate,
};
let h = |s: String| unsafe { HeaderValue::from_bytes_unchecked(s.into_bytes()) };

match directive {
2 changes: 1 addition & 1 deletion src/cache/cache_control/mod.rs
Original file line number Diff line number Diff line change
@@ -35,7 +35,7 @@ mod test {
}

#[test]
fn ignore_unkonwn_directives() -> crate::Result<()> {
fn ignore_unknown_directives() -> crate::Result<()> {
let mut headers = Headers::new();
headers.insert(CACHE_CONTROL, "barrel_roll").unwrap();
let entries = CacheControl::from_headers(headers)?.unwrap();
1 change: 1 addition & 0 deletions src/cache/clear_site_data/directive.rs
Original file line number Diff line number Diff line change
@@ -28,6 +28,7 @@ pub enum ClearDirective {

impl ClearDirective {
/// Get the formatted string.
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
ClearDirective::Cache => r#""cache""#,
Loading