Skip to content
Closed
Show file tree
Hide file tree
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
88 changes: 88 additions & 0 deletions core/lib/src/data/bytes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use std::borrow::Cow;
use std::io;

use crate::data::{Capped, FromData, Limits, Outcome, N};
use crate::form::{DataField, Errors, FromFormField, ValueField};
use crate::http::{ContentType, Status};
use crate::{fs::FileName, outcome::IntoOutcome, Data, Request};

#[derive(Debug)]
pub struct Bytes<'v> {
pub file_name: Option<&'v FileName>,
pub content_type: Option<ContentType>,
pub content: Cow<'v, [u8]>,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just wondering, is there a reason for using Cow<[u8]> here instead of Vec<u8>? As far as I can tell converting a Cow<[T]> back into a Vec<T> would cause a reallocation of the entire file even if it's owned and I would rather have the Vec for my use-case.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm finally done with having to work so much, so hopefully I'll be more responsive now.
On line 52, I use it for the borrowed variant, so there is a purpose in using it and there should not be an unnecessary (re)allocation because:

Calling into_owned on a Cow::Owned returns the owned data. The data is moved out of the Cow without being cloned.

For extra clarification, the type of content doesn't mention Vec because it is inferred from the ToOwned implementation for slices that specifies its Owned variant is Vec.

}

impl<'v> Bytes<'v> {
async fn from<'a>(
req: &Request<'_>,
data: Data<'_>,
file_name: Option<&'a FileName>,
content_type: Option<ContentType>,
) -> io::Result<Capped<Bytes<'a>>> {
let limit = { content_type.as_ref() }
.and_then(|ct| ct.extension()?.limits().find(&["file", ext.as_str()]))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's a mistake here, shouldn't be

            .and_then(|ct| ct.extension())
            .and_then(|ext| req.limits().find(&["file", ext.as_str()]))

?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the delay, been busy working.
There is no need for a second .and_then(...) because the ? after .extension() extracts the value from Option::Some(T) or returns Option::None depending on which variant it happened to be, allowing for more concise code.
Apparently it was stabilized back in 2016, feels newer. There's a section in the book about it.

.or_else(|| req.limits().get("file"))
.unwrap_or(Limits::FILE);

let Capped { value, n } = data.open(limit).into_bytes().await?;

Ok(Capped::new(
Bytes {
content_type,
file_name,
content: value.into(),
},
n,
))
}
}

#[crate::async_trait]
impl<'v> FromFormField<'v> for Capped<Bytes<'v>> {
fn from_value(field: ValueField<'v>) -> Result<Self, Errors<'v>> {
let n = N {
written: field.value.len() as u64,
complete: true,
};
Ok(Capped::new(
Bytes {
file_name: None,
content_type: None,
content: field.value.as_bytes().into(),
},
n,
))
}

async fn from_data(f: DataField<'v, '_>) -> Result<Self, Errors<'v>> {
Ok(Bytes::from(f.request, f.data, f.file_name, Some(f.content_type)).await?)
}
}

#[crate::async_trait]
impl<'r> FromData<'r> for Capped<Bytes<'_>> {
type Error = io::Error;

async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r, Self> {
use yansi::Paint;

let has_form = |ty: &ContentType| ty.is_form_data() || ty.is_form();
if req.content_type().map_or(false, has_form) {
let (tf, form) = (Paint::white("Bytes<'_>"), Paint::white("Form<Bytes<'_>>"));
warn_!("Request contains a form that will not be processed.");
info_!(
"Bare `{}` data guard writes raw, unprocessed streams to disk.",
tf
);
info_!("Did you mean to use `{}` instead?", form);
}

Bytes::from(req, data, None, req.content_type().cloned())
.await
.into_outcome(Status::BadRequest)
}
}

impl_strict_from_form_field_from_capped!(Bytes<'v>);
impl_strict_from_data_from_capped!(Bytes<'_>);
4 changes: 3 additions & 1 deletion core/lib/src/data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@

#[macro_use]
mod capped;
mod bytes;
mod data;
mod data_stream;
mod from_data;
mod limits;

pub use self::bytes::Bytes;
pub use self::capped::{Capped, N};
pub use self::data::Data;
pub use self::data_stream::DataStream;
pub use self::from_data::{FromData, Outcome};
pub use self::limits::Limits;
pub use self::capped::{N, Capped};
pub use ubyte::{ByteUnit, ToByteUnit};

pub(crate) use self::data_stream::StreamReader;