diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index f024e26..b0a9092 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -1,16 +1,56 @@
-name: Test
+name: CI
on:
- push:
- branches: [master, develop]
pull_request:
- branches: [master, develop]
+ push:
+ branches:
+ - master
+ - develop
+
+env:
+ RUSTFLAGS: -Dwarnings
jobs:
- build:
- runs-on: ubuntu-latest
+ build_and_test:
+ name: Build and test
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [ubuntu-latest]
+ rust: [stable, nightly]
steps:
- - uses: actions/checkout@v2
- - name: Run tests
- run: cargo test --verbose --features="all"
+ - uses: actions/checkout@master
+
+ - name: Install ${{ matrix.rust }}
+ uses: actions-rs/toolchain@v1
+ with:
+ toolchain: ${{ matrix.rust }}
+ override: true
+
+ - name: check
+ uses: actions-rs/cargo@v1
+ with:
+ command: check
+ args: --all --bins --examples --features=all
+
+ - name: tests
+ uses: actions-rs/cargo@v1
+ with:
+ command: test
+ args: --all --features=all
+
+ check_fmt_and_docs:
+ name: Checking fmt, clippy, and docs
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@master
+
+ - name: clippy
+ run: cargo clippy --tests --examples --bins -- -D warnings
+
+ - name: fmt
+ run: cargo fmt --all -- --check
+
+ - name: Docs
+ run: cargo doc --no-deps
diff --git a/Cargo.toml b/Cargo.toml
index 15a4b21..9e551fc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -47,12 +47,7 @@ tokio = { version = "0.2", features = ["full"] }
hyper = "0.13"
routerify = "1.1"
-[[example]]
-name = "test"
-path = "examples/test.rs"
-required-features = ["json", "reader"]
-
[[example]]
name = "parse_async_read"
path = "examples/parse_async_read.rs"
-required-features = ["reader"]
\ No newline at end of file
+required-features = ["reader"]
diff --git a/examples/test.rs b/examples/test.rs
deleted file mode 100644
index 8b1893d..0000000
--- a/examples/test.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-use bytes::Bytes;
-use futures::stream::{Stream, StreamExt};
-use futures::TryStreamExt;
-use hyper::service::{make_service_fn, service_fn};
-use hyper::{Body, Request, Response, Server};
-use multer::{Constraints, Error, Field, Multipart, SizeLimit};
-use std::{convert::Infallible, net::SocketAddr};
-use tokio::fs::{File, OpenOptions};
-use tokio::io::{AsyncWrite, AsyncWriteExt};
-
-async fn handle(req: Request
) -> Result, Infallible> {
- let stream = req.into_body();
-
- // let multipart_constraints = Constraints::new()
- // .allowed_fields(vec!["a", "b"])
- // .size_limit(SizeLimit::new().per_field(30).for_field("a", 10));
-
- let mut multipart = Multipart::new(stream, "X-INSOMNIA-BOUNDARY");
-
- while let Some(field) = multipart.next_field().await.unwrap() {
- println!("name: {:?}", field.name());
- println!("filename: {:?}", field.file_name());
- let text = field.text().await.unwrap();
- println!("content: {}", text);
- }
-
- Ok(Response::new("Hello, World!".into()))
-}
-
-#[tokio::main]
-async fn main() {
- let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
-
- let make_svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handle)) });
-
- let server = Server::bind(&addr).serve(make_svc);
-
- println!("Server is running at: {}", addr);
- if let Err(e) = server.await {
- eprintln!("server error: {}", e);
- }
-}
diff --git a/src/buffer.rs b/src/buffer.rs
index cfa41b4..b83b1dd 100644
--- a/src/buffer.rs
+++ b/src/buffer.rs
@@ -1,6 +1,7 @@
use crate::constants;
use bytes::{Bytes, BytesMut};
use futures::stream::Stream;
+use std::fmt;
use std::pin::Pin;
use std::task::{Context, Poll};
@@ -26,7 +27,7 @@ impl StreamBuffer {
}
}
- pub fn poll_stream(&mut self, cx: &mut Context) -> Result<(), crate::Error> {
+ pub fn poll_stream(&mut self, cx: &mut Context<'_>) -> Result<(), crate::Error> {
if self.eof {
return Ok(());
}
@@ -116,12 +117,10 @@ impl StreamBuffer {
Err(crate::Error::IncompleteFieldData {
field_name: field_name.map(|s| s.to_owned()),
})
+ } else if bytes.is_empty() {
+ Ok(None)
} else {
- if bytes.is_empty() {
- Ok(None)
- } else {
- Ok(Some((false, bytes)))
- }
+ Ok(Some((false, bytes)))
}
}
None => {
@@ -153,3 +152,9 @@ impl StreamBuffer {
self.buf.split_to(self.buf.len()).freeze()
}
}
+
+impl fmt::Debug for StreamBuffer {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("StreamBuffer").finish()
+ }
+}
diff --git a/src/constants.rs b/src/constants.rs
index 34d278e..f09aa14 100644
--- a/src/constants.rs
+++ b/src/constants.rs
@@ -5,12 +5,12 @@ pub(crate) const DEFAULT_WHOLE_STREAM_SIZE_LIMIT: u64 = std::u64::MAX;
pub(crate) const DEFAULT_PER_FIELD_SIZE_LIMIT: u64 = std::u64::MAX;
pub(crate) const MAX_HEADERS: usize = 32;
-pub(crate) const BOUNDARY_EXT: &'static str = "--";
-pub(crate) const CR: &'static str = "\r";
+pub(crate) const BOUNDARY_EXT: &str = "--";
+pub(crate) const CR: &str = "\r";
#[allow(dead_code)]
-pub(crate) const LF: &'static str = "\n";
-pub(crate) const CRLF: &'static str = "\r\n";
-pub(crate) const CRLF_CRLF: &'static str = "\r\n\r\n";
+pub(crate) const LF: &str = "\n";
+pub(crate) const CRLF: &str = "\r\n";
+pub(crate) const CRLF_CRLF: &str = "\r\n\r\n";
lazy_static! {
pub(crate) static ref CONTENT_DISPOSITION_FIELD_NAME_RE: Regex = Regex::new(r#"(?-u)name="([^"]+)""#).unwrap();
diff --git a/src/constraints.rs b/src/constraints.rs
index 29e5c09..fde59a1 100644
--- a/src/constraints.rs
+++ b/src/constraints.rs
@@ -42,6 +42,7 @@ use crate::size_limit::SizeLimit;
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
+#[derive(Debug)]
pub struct Constraints {
pub(crate) size_limit: SizeLimit,
pub(crate) allowed_fields: Option>,
diff --git a/src/content_disposition.rs b/src/content_disposition.rs
index a185358..7d2fe04 100644
--- a/src/content_disposition.rs
+++ b/src/content_disposition.rs
@@ -1,6 +1,7 @@
use crate::constants;
use http::header::{self, HeaderMap};
+#[derive(Debug)]
pub(crate) struct ContentDisposition {
pub(crate) field_name: Option,
pub(crate) file_name: Option,
diff --git a/src/error.rs b/src/error.rs
index 22a85d5..8058836 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -6,6 +6,7 @@ type BoxError = Box;
/// A set of errors that can occur during parsing multipart stream and in other operations.
#[derive(Display)]
#[display(fmt = "multer: {}")]
+#[non_exhaustive]
pub enum Error {
/// An unknown field is detected when multipart [`constraints`](./struct.Constraints.html#method.allowed_fields) are added.
#[display(
@@ -77,9 +78,6 @@ pub enum Error {
#[cfg(feature = "json")]
#[display(fmt = "Failed to decode the field data as JSON: {}", _0)]
DecodeJson(BoxError),
-
- #[doc(hidden)]
- __Nonexhaustive,
}
impl Debug for Error {
diff --git a/src/field.rs b/src/field.rs
index 5cc6723..fbe4fca 100644
--- a/src/field.rs
+++ b/src/field.rs
@@ -7,8 +7,6 @@ use futures::stream::{Stream, TryStreamExt};
use http::header::HeaderMap;
#[cfg(feature = "json")]
use serde::de::DeserializeOwned;
-#[cfg(feature = "json")]
-use serde_json;
use std::borrow::Cow;
use std::ops::DerefMut;
use std::pin::Pin;
@@ -50,6 +48,7 @@ use std::task::{Context, Poll};
/// then the parent [`Multipart`](./struct.Multipart.html) will never be able to yield the next field in the stream.
/// The task waiting on the [`Multipart`](./struct.Multipart.html) will also never be notified, which, depending on the executor implementation,
/// may cause a deadlock.
+#[derive(Debug)]
pub struct Field {
state: Arc>,
headers: HeaderMap,
@@ -57,6 +56,7 @@ pub struct Field {
meta: FieldMeta,
}
+#[derive(Debug)]
struct FieldMeta {
content_disposition: ContentDisposition,
content_type: Option,
@@ -86,20 +86,12 @@ impl Field {
/// The field name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.
pub fn name(&self) -> Option<&str> {
- self.meta
- .content_disposition
- .field_name
- .as_ref()
- .map(|name| name.as_str())
+ self.meta.content_disposition.field_name.as_deref()
}
/// The file name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.
pub fn file_name(&self) -> Option<&str> {
- self.meta
- .content_disposition
- .file_name
- .as_ref()
- .map(|file_name| file_name.as_str())
+ self.meta.content_disposition.file_name.as_deref()
}
/// Get the content type of the field.
@@ -238,7 +230,7 @@ impl Field {
/// let stream = once(async move { Result::::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
- /// while let Some(mut field) = multipart.next_field().await.unwrap() {
+ /// while let Some(field) = multipart.next_field().await.unwrap() {
/// let content = field.text().await.unwrap();
/// assert_eq!(content, "abcd");
/// }
@@ -268,7 +260,7 @@ impl Field {
/// let stream = once(async move { Result::::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
- /// while let Some(mut field) = multipart.next_field().await.unwrap() {
+ /// while let Some(field) = multipart.next_field().await.unwrap() {
/// let content = field.text_with_charset("utf-8").await.unwrap();
/// assert_eq!(content, "abcd");
/// }
@@ -324,7 +316,7 @@ impl Field {
impl Stream for Field {
type Item = Result;
- fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll