use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use bytes::{Bytes, BytesMut};
use encoding_rs::{Encoding, UTF_8};
use futures_util::stream::{Stream, TryStreamExt};
use http::header::HeaderMap;
#[cfg(feature = "json")]
use serde::de::DeserializeOwned;
use crate::content_disposition::ContentDisposition;
use crate::multipart::{MultipartState, StreamingStage};
use crate::{Error, helpers};
#[derive(Debug)]
pub struct Field<'r> {
state: Arc<Mutex<MultipartState<'r>>>,
done: bool,
headers: HeaderMap,
content_disposition: ContentDisposition,
content_type: Option<mime::Mime>,
content_type_charset: Option<String>,
idx: usize,
}
impl<'r> Field<'r> {
pub(crate) fn new(
state: Arc<Mutex<MultipartState<'r>>>,
headers: HeaderMap,
idx: usize,
content_disposition: ContentDisposition,
) -> Self {
let (content_type, content_type_charset) =
helpers::parse_content_type(&headers).map_or((None, None), |parsed| {
(
parsed.to_mime(),
parsed.get_param("charset").map(str::to_owned),
)
});
Field {
state,
headers,
content_disposition,
content_type,
content_type_charset,
idx,
done: false,
}
}
#[must_use]
pub fn name(&self) -> Option<&str> {
self.content_disposition.field_name.as_deref()
}
#[must_use]
pub fn file_name(&self) -> Option<&str> {
self.content_disposition.file_name.as_deref()
}
#[must_use]
pub const fn content_type(&self) -> Option<&mime::Mime> {
self.content_type.as_ref()
}
#[must_use]
pub const fn headers(&self) -> &HeaderMap {
&self.headers
}
pub async fn bytes(self) -> crate::Result<Bytes> {
let mut first_chunk: Option<Bytes> = None;
let mut buf = BytesMut::new();
let mut chunks_since_yield = 0;
let mut this = self;
while let Some(bytes) = this.chunk().await? {
chunks_since_yield += 1;
if chunks_since_yield == 32 {
let mut yielded = false;
std::future::poll_fn(|cx| {
if yielded {
Poll::Ready(())
} else {
yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
})
.await;
chunks_since_yield = 0;
}
if bytes.is_empty() {
continue;
}
if let Some(first) = first_chunk.take() {
buf.reserve(first.len().saturating_add(bytes.len()));
buf.extend_from_slice(&first);
} else if buf.is_empty() {
first_chunk = Some(bytes);
continue;
}
buf.extend_from_slice(&bytes);
}
Ok(first_chunk.unwrap_or_else(|| buf.freeze()))
}
pub async fn chunk(&mut self) -> crate::Result<Option<Bytes>> {
self.try_next().await
}
#[cfg(feature = "json")]
pub async fn json<T: DeserializeOwned>(self) -> crate::Result<T> {
serde_json::from_slice(&self.bytes().await?).map_err(Error::DecodeJson)
}
pub async fn text(self) -> crate::Result<String> {
self.text_with_charset("utf-8").await
}
pub async fn text_with_charset(self, default_encoding: &str) -> crate::Result<String> {
let encoding_name = self
.content_type_charset
.as_deref()
.unwrap_or(default_encoding);
let encoding = Encoding::for_label(encoding_name.as_bytes()).unwrap_or(UTF_8);
let bytes = self.bytes().await?;
Ok(encoding.decode(&bytes).0.into_owned())
}
#[must_use]
pub const fn index(&self) -> usize {
self.idx
}
}
impl Stream for Field<'_> {
type Item = Result<Bytes, Error>;
#[allow(clippy::significant_drop_tightening)] fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.done {
return Poll::Ready(None);
}
let state = self.state.clone();
let Ok(mut lock) = state.try_lock() else {
return Poll::Ready(Some(Err(Error::LockFailure)));
};
let state = &mut *lock;
let mut read_stream = false;
let mut needs_wake = false;
loop {
match state.buffer.read_field_data(
&state.field_boundary_bytes,
state.curr_field_name.as_deref(),
) {
Ok(Some((done, bytes))) => {
state.curr_field_size_counter = state
.curr_field_size_counter
.saturating_add(bytes.len() as u64);
if state.curr_field_size_counter > state.curr_field_size_limit {
return Poll::Ready(Some(Err(Error::FieldSizeExceeded {
limit: state.curr_field_size_limit,
field_name: state.curr_field_name.clone(),
})));
}
if done {
state.stage = StreamingStage::ReadingBoundary;
self.done = true;
}
return Poll::Ready(Some(Ok(bytes)));
}
Ok(None) if !read_stream => {
read_stream = true;
match state.buffer.poll_stream(cx) {
Ok(wake) => needs_wake = wake,
Err(err) => return Poll::Ready(Some(Err(err))),
}
}
Ok(None) => {
if needs_wake {
cx.waker().wake_by_ref();
}
return Poll::Pending;
}
Err(err) => return Poll::Ready(Some(Err(err))),
}
}
}
}