id stringlengths 20 30 | source stringclasses 1
value | chunk_index int64 0 520k | token_count int32 154 512 | content stringlengths 185 57.5k |
|---|---|---|---|---|
rust_dataset_chunk_500 | rust_dataset.txt | 500 | 512 | {
assert!(self.was_polled());
Box::pin(async move {
let res = ws::handshake(req.head())?.message_body(())?;
framed.send((res, BodySize::None).into()).await?;
let framed = framed.replace_codec(ws::Codec::new());
ws::Dispatcher::with(framed, service)
... |
rust_dataset_chunk_501 | rust_dataset.txt | 501 | 512 | ]
fn accepts_valid_close_codes() {
for code in [
1000_u16, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 3000, 3999,
4999,
] {
let mut codec = ws::Codec::new();
let mut frame = masked_close(&code.to_be_bytes());
let Some(Frame::Close(Some(reason))) = ... |
rust_dataset_chunk_502 | rust_dataset.txt | 502 | 512 | ::build()
.upgrade(fn_factory(|| async {
Ok::<_, Infallible>(WsService::new())
}))
.finish(|_| async { Ok::<_, Infallible>(Response::not_found()) })
.tcp()
})
.await;
// client service
let mut framed = srv.ws().await.unwrap();
framed.s... |
rust_dataset_chunk_503 | rust_dataset.txt | 503 | 512 | _err());
framed
.send(Message::Close(Some(CloseCode::Normal.into())))
.await
.unwrap();
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, Frame::Close(Some(CloseCode::Normal.into())));
}
#[test]
fn rejects_new_data_frame_during_continuation() {
let mut codec =... |
rust_dataset_chunk_504 | rust_dataset.txt | 504 | 512 | _url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![allow(clippy::disallowed_names)] // false positives in some macro expansions
use std::collections::HashSet;
use bytesize::ByteSize;
use darling::{FromDeriveInput, FromField, Fr... |
rust_dataset_chunk_505 | rust_dataset.txt | 505 | 512 | (
input.ident.span(),
"`MultipartForm` can only be derived for a struct with named fields",
))
}
};
let attrs = match MultipartFormAttrs::from_derive_input(&input) {
Ok(attrs) => attrs,
Err(err) => return err.write_errors().into(),
};
... |
rust_dataset_chunk_506 | rust_dataset.txt | 506 | 512 | DuplicateField::Deny => quote!(::actix_multipart::form::DuplicateField::Deny),
DuplicateField::Replace => quote!(::actix_multipart::form::DuplicateField::Replace),
};
let max_parts_impl = attrs.max_parts.map(|limit| {
quote! {
fn max_parts() -> ::std::option::Option<usize> {... |
rust_dataset_chunk_507 | rust_dataset.txt | 507 | 512 | ::Future<Output = ::std::result::Result<(), ::actix_multipart::MultipartError>> + 't>> {
match field.name().unwrap() {
#handle_field_impl
_ => return ::std::boxed::Box::pin(async move { #unknown_field_result }),
}
}
fn from... |
rust_dataset_chunk_508 | rust_dataset.txt | 508 | 512 | --- FILE: actix-web/actix-multipart/src/error.rs ---
//! Error and Result module
use actix_web::{
error::{ParseError, PayloadError},
http::StatusCode,
ResponseError,
};
use derive_more::{Display, Error, From};
/// A set of errors that can occur during parsing multipart streams.
#[derive(Debug, Display, Fr... |
rust_dataset_chunk_509 | rust_dataset.txt | 509 | 512 | not supported.
#[display("Nested multipart is not supported")]
Nested,
/// The form contains more parts than the configured limit.
#[display("Multipart form has too many parts")]
TooManyParts,
/// Multipart stream is incomplete.
#[display("Multipart stream is incomplete")]
Incomplete,... |
rust_dataset_chunk_510 | rust_dataset.txt | 510 | 512 | err).to_string(),
"Error during field parsing: Message is incomplete"
);
let err = Error::ContentDispositionNameMissing;
assert_eq!(
Report::new(&err).to_string(),
"Content-Disposition 'name' parameter was not found when parsing a \"form-data\" field"
... |
rust_dataset_chunk_511 | rust_dataset.txt | 511 | 512 | ::default().to_http_request();
let _: actix_utils::future::Ready<Result<Multipart, Error>> =
Multipart::from_request(&req, &mut Payload::None);
}
}
--- FILE: actix-web/actix-multipart/src/field.rs ---
use std::{
cell::RefCell,
cmp, fmt,
future::poll_fn,
mem,
pin::Pin,
... |
rust_dataset_chunk_512 | rust_dataset.txt | 512 | 512 |
}
/// Returns a reference to the field's content (mime) type, if it is supplied by the client.
///
/// According to [RFC 7578](https://www.rfc-editor.org/rfc/rfc7578#section-4.4), if it is not
/// present, it should default to "text/plain". Note it is the responsibility of the client to
/// pr... |
rust_dataset_chunk_513 | rust_dataset.txt | 513 | 512 | is exhausted before returning the error so that
/// subsequent fields can still be read. To better defend against malicious/infinite requests,
/// it is advisable to also put a timeout on this call.
pub async fn bytes(&mut self, limit: usize) -> Result<Result<Bytes, Error>, LimitExceeded> {
/// Sen... |
rust_dataset_chunk_514 | rust_dataset.txt | 514 | 512 | {
return Poll::Pending;
}
inner.poll(&this.safety)
}
}
impl fmt::Debug for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(ct) = &self.content_type {
writeln!(f, "\nField: {}", ct)?;
} else {
writeln!(f, "\nFie... |
rust_dataset_chunk_515 | rust_dataset.txt | 515 | 512 | ")) =>
{
return Self::Cr;
}
// Binary data can contain frequent incidental CR bytes, so use the marker
// search. Also use marker search for unknown or missing types.
None | Some(_) => {}
}
// Include the first non-dash bounda... |
rust_dataset_chunk_516 | rust_dataset.txt | 516 | 512 | .
pub(crate) fn read_len(
payload: &mut PayloadBuffer,
size: &mut u64,
) -> Poll<Option<Result<Bytes, Error>>> {
if *size == 0 {
Poll::Ready(None)
} else {
match payload.read_max(*size)? {
Some(mut chunk) => {
let len = ... |
rust_dataset_chunk_517 | rust_dataset.txt | 517 | 512 | let available = len - b_len;
let check_len = cmp::min(available, boundary.len());
// A matching prefix must stay buffered; a mismatch is ordinary field data.
if payload.buf[b_len..b_len + check_len] == boundary.as_bytes()[..check_len] {
match (len >= b_si... |
rust_dataset_chunk_518 | rust_dataset.txt | 518 | 512 | stays buffered too.
if hyphen >= CRLF_LEN
&& &payload.buf[hyphen - CRLF_LEN..hyphen] == b"\r\n"
{
Some(hyphen - CRLF_LEN)
} else {
None
... |
rust_dataset_chunk_519 | rust_dataset.txt | 519 | 512 | 0 {
// Emit field data before the CR. On the next read, this
// candidate is at offset zero for the full boundary check.
Poll::Ready(Some(Ok(payload.buf.split_to(idx).freeze())))
} else {
... |
rust_dataset_chunk_520 | rust_dataset.txt | 520 | 512 | futures_util::{stream, FutureExt as _, StreamExt as _};
use super::*;
use crate::Multipart;
// TODO: use test utility when multi-file support is introduced
fn create_double_request_with_header() -> (Bytes, HeaderMap) {
let bytes = Bytes::from(
"testasdadsad\r\n\
--abb... |
rust_dataset_chunk_521 | rust_dataset.txt | 521 | 512 | be size limited")
.expect("Reading field data should not error");
assert_eq!(field, "two+two+two");
}
#[tokio::test(flavor = "local")]
async fn bytes_limited() {
let (body, headers) = create_double_request_with_header();
let mut multipart = Multipart::new(&headers, str... |
rust_dataset_chunk_522 | rust_dataset.txt | 522 | 512 |
.next()
.await
.expect("Multipart should have two fields")
.expect("Multipart body should be well formatted")
.bytes(usize::MAX)
.await
.expect("Field data should not be size limited")
.expect("Reading field data should not... |
rust_dataset_chunk_523 | rust_dataset.txt | 523 | 512 | header::CONTENT_TYPE,
header::HeaderValue::from_static("multipart/form-data; boundary=abc"),
);
let (mut tx, rx) = h1::Payload::create(false);
tx.feed_data(Bytes::from_static(
b"--abc\r\nContent-Disposition: form-data; name=\"field\"\r\n\r\n\r\n--ax",
));
... |
rust_dataset_chunk_524 | rust_dataset.txt | 524 | 512 | matches!(next, Some(Some(Err(crate::error::Error::Incomplete)))),
"EOF after yielding mismatch should report an incomplete message: {next:?}",
);
}
#[tokio::test(flavor = "local")]
async fn marker_candidates_and_all_chunk_splits_preserve_field_data() {
for content_type in [
... |
rust_dataset_chunk_525 | rust_dataset.txt | 525 | 512 | a field into memory.
use actix_web::{web::BytesMut, HttpRequest};
use futures_core::future::LocalBoxFuture;
use futures_util::TryStreamExt as _;
use mime::Mime;
use crate::{
form::{FieldReader, Limits},
Field, MultipartError,
};
/// Read the field into memory.
#[derive(Debug)]
pub struct Bytes {
/// The... |
rust_dataset_chunk_526 | rust_dataset.txt | 526 | 512 | : DeserializeOwned + 'static,
{
type Future = LocalBoxFuture<'t, Result<Self, MultipartError>>;
fn read_field(req: &'t HttpRequest, field: Field, limits: &'t mut Limits) -> Self::Future {
Box::pin(async move {
let config = JsonConfig::from_req(req);
if config.validate_content_t... |
rust_dataset_chunk_527 | rust_dataset.txt | 527 | 512 | _req(req: &HttpRequest) -> &Self {
req.app_data::<Self>()
.or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref()))
.unwrap_or(&DEFAULT_CONFIG)
}
fn map_error(&self, req: &HttpRequest, err: JsonFieldError) -> Error {
if let Some(err_handler) = self.err_handler.a... |
rust_dataset_chunk_528 | rust_dataset.txt | 528 | 512 | (body).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test(flavor = "local")]
async fn test_content_type_validation() {
let srv = actix_test::start(|| {
App::new()
.route("/", web::post().to(test_json_route))
.app_data(JsonCo... |
rust_dataset_chunk_529 | rust_dataset.txt | 529 | 512 | + Sync>>;
/// Trait that data types to be used in a multipart form struct should implement.
///
/// It represents an asynchronous handler that processes a multipart field to produce `Self`.
pub trait FieldReader<'t>: Sized + Any {
/// Future that resolves to a `Self`.
type Future: Future<Output = Result<Self,... |
rust_dataset_chunk_530 | rust_dataset.txt | 530 | 512 | _field {
DuplicateField::Ignore => {
return Box::pin(async move { discard_field(field, limits).await });
}
DuplicateField::Deny => {
return Box::pin(ready(Err(MultipartError::DuplicateField(
field.form_field... |
rust_dataset_chunk_531 | rust_dataset.txt | 531 | 512 | ) {
match duplicate_field {
DuplicateField::Ignore => {
return Box::pin(async move { discard_field(field, limits).await });
}
DuplicateField::Deny => {
return Box::pin(ready(Err(MultipartError::DuplicateField(
... |
rust_dataset_chunk_532 | rust_dataset.txt | 532 | 512 | ///
/// The extractor also applies the limit from [`MultipartFormConfig`]. The lower limit wins.
fn max_parts() -> Option<usize> {
None
}
/// An optional limit in bytes to be applied a given field name. Note this limit will be shared
/// across all fields sharing the same name.
fn limi... |
rust_dataset_chunk_533 | rust_dataset.txt | 533 | 512 | .memory_limit_remaining
.checked_sub(bytes)
.ok_or(MultipartError::Payload(PayloadError::Overflow))?;
}
if let Some(field_limit) = self.field_limit_remaining {
self.field_limit_remaining = Some(
field_limit
.checked_sub(by... |
rust_dataset_chunk_534 | rust_dataset.txt | 534 | 512 | multipart(rename = "foo")]` attribute to receive a field by a different name.
///
/// ```rust
/// use actix_multipart::form::{tempfile::TempFile, MultipartForm};
///
/// #[derive(MultipartForm)]
/// struct Form {
/// #[multipart(rename = "files[]")]
/// files: Vec<TempFile>,
/// }
/// ```
///
/// # Field Limits... |
rust_dataset_chunk_535 | rust_dataset.txt | 535 | 512 | ")]
/// struct Form {}
/// ```
///
/// [`bytesize`]: https://docs.rs/bytesize/2
/// [`MultipartError::DuplicateField`]: crate::MultipartError::DuplicateField
#[derive(Deref, DerefMut)]
pub struct MultipartForm<T: MultipartCollect>(pub T);
impl<T: MultipartCollect> MultipartForm<T> {
/// Unwrap into inner `T` value... |
rust_dataset_chunk_536 | rust_dataset.txt | 536 | 512 | limits.field_limit_remaining.clone_from(entry);
T::handle_field(&req, field, &mut limits, &mut state).await?;
// Update the stored limit
*entry = limits.field_limit_remaining;
}
let inner = T::from_state(s... |
rust_dataset_chunk_537 | rust_dataset.txt | 537 | 512 | }
/// Extracts payload config from app data. Check both `T` and `Data<T>`, in that order, and fall
/// back to the default payload config.
fn from_req(req: &HttpRequest) -> &Self {
req.app_data::<Self>()
.or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref()))
... |
rust_dataset_chunk_538 | rust_dataset.txt | 538 | 512 | _none());
HttpResponse::Ok().finish()
}
#[tokio::test(flavor = "local")]
async fn test_options() {
let srv = actix_test::start(|| App::new().route("/", web::post().to(test_options_route)));
let mut form = multipart::Form::default();
form.add_text("field1", "value");
... |
rust_dataset_chunk_539 | rust_dataset.txt | 539 | 512 | #[tokio::test(flavor = "local")]
async fn test_option_vec() {
let srv =
actix_test::start(|| App::new().route("/", web::post().to(test_option_vec_route)));
let mut form = multipart::Form::default();
form.add_text("list1", "value1");
form.add_text("list1", "value2");
... |
rust_dataset_chunk_540 | rust_dataset.txt | 540 | 512 | _unknown() {
let srv = actix_test::start(|| {
App::new()
.route("/deny", web::post().to(test_deny_unknown_route))
.route("/allow", web::post().to(test_allow_unknown_route))
});
let mut form = multipart::Form::default();
form.add_text("unknown"... |
rust_dataset_chunk_541 | rust_dataset.txt | 541 | 512 | , form, "/deny").await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let mut form = multipart::Form::default();
form.add_text("field", "first_value");
form.add_text("field", "second_value");
let response = send_form(&srv, form, "/replace").await;
assert_eq!(re... |
rust_dataset_chunk_542 | rust_dataset.txt | 542 | 512 | "{}--test-boundary--\r\n",
"--test-boundary\r\nContent-Disposition: form-data; name=\"files\"\r\n\r\n\r\n"
.repeat(count)
);
let req = TestRequest::post()
.uri("/")
.insert_header((
"content-t... |
rust_dataset_chunk_543 | rust_dataset.txt | 543 | 512 | !(matches!(err, MultipartError::TooManyParts));
actix_web::error::ErrorPayloadTooLarge(err)
}),
))
.route(
"/",
web::post().to(|form: MultipartForm<Upload>| async move {
... |
rust_dataset_chunk_544 | rust_dataset.txt | 544 | 512 | ) -> impl Responder {
assert!(!form.field.data.is_empty());
HttpResponse::Ok().finish()
}
async fn test_upload_limits_file(form: MultipartForm<TestFileUploadLimits>) -> impl Responder {
assert!(form.field.size > 0);
HttpResponse::Ok().finish()
}
#[tokio::test(flavor... |
rust_dataset_chunk_545 | rust_dataset.txt | 545 | 512 | _form(&srv, form, "/text").await;
assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
// Exceeds the 20 byte overall limit
let mut form = multipart::Form::default();
form.add_text("field", "this string is 28 bytes long");
let response = send_form(&srv, form, "/file").a... |
rust_dataset_chunk_546 | rust_dataset.txt | 546 | 512 | .add_text("field", "this string is 28 bytes long");
let response = send_form(&srv, form, "/").await;
assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
#[tokio::test(flavor = "local")]
async fn non_multipart_form_data() {
#[derive(MultipartForm)]
struct TestNonM... |
rust_dataset_chunk_547 | rust_dataset.txt | 547 | 512 | form should panic before reaching this point");
}
let app = init_service(App::new().service(null_sink)).await;
let (body, headers) = create_form_data_payload_and_headers(
"foo",
None,
None,
web::Bytes::from_static(b"test data"),
);
... |
rust_dataset_chunk_548 | rust_dataset.txt | 548 | 512 | ::File::from_std(file.reopen().map_err(|err| {
config.map_error(req, &field.form_field_name, TempFileError::FileIo(err))
})?);
while let Some(chunk) = field.try_next().await? {
limits.try_consume_limits(chunk.len(), false)?;
size += chunk.len();
... |
rust_dataset_chunk_549 | rust_dataset.txt | 549 | 512 | _req(req: &HttpRequest) -> &Self {
req.app_data::<Self>()
.or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref()))
.unwrap_or(&DEFAULT_CONFIG)
}
fn map_error(&self, req: &HttpRequest, field_name: &str, err: TempFileError) -> MultipartError {
let source = if let... |
rust_dataset_chunk_550 | rust_dataset.txt | 550 | 512 | ", bytes, "testfile.txt", mime::TEXT_PLAIN);
let response = send_form(&srv, form, "/").await;
assert_eq!(response.status(), StatusCode::OK);
}
}
--- FILE: actix-web/actix-multipart/src/form/text.rs ---
//! Deserializes a field from plain text.
use std::{str, sync::Arc};
use actix_web::{http::Sta... |
rust_dataset_chunk_551 | rust_dataset.txt | 551 | 512 | .data).map_err(|err| MultipartError::Field {
name: form_field_name.clone(),
source: config.map_error(req, TextError::Utf8Error(err)),
})?;
Ok(Text(serde_plain::from_str(text).map_err(|err| {
MultipartError::Field {
name: form_f... |
rust_dataset_chunk_552 | rust_dataset.txt | 552 | 512 | defines
/// `text/plain` as the default for text fields.
pub fn validate_content_type(mut self, validate_content_type: bool) -> Self {
self.validate_content_type = validate_content_type;
self
}
}
const DEFAULT_CONFIG: TextConfig = TextConfig {
err_handler: None,
validate_content_ty... |
rust_dataset_chunk_553 | rust_dataset.txt | 553 | 512 | request & form support for Actix Web.
//!
//! The [`Multipart`] extractor aims to support all kinds of `multipart/*` requests, including
//! `multipart/form-data`, `multipart/related` and `multipart/mixed`. This is a lower-level
//! extractor which supports reading [multipart fields](Field), in the order they are sent... |
rust_dataset_chunk_554 | rust_dataset.txt | 554 | 512 | form::MultipartForm
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_cfg))]
// This allows us to use the actix_multipart_derive within this crate's tests
#[cfg(test)]
extern crate self as actix_multipart;
mod error;
mo... |
rust_dataset_chunk_555 | rust_dataset.txt | 555 | 512 | . By default this limit is 64 KiB.
pub fn buffer_limit(mut self, buffer_limit: usize) -> Self {
self.buffer_limit = buffer_limit;
self
}
/// Extracts multipart config from app data. Check both `T` and `Data<T>`, in that order, and
/// fall back to the default multipart config.
fn fr... |
rust_dataset_chunk_556 | rust_dataset.txt | 556 | 512 | ime::BOUNDARY)
.ok_or(Error::BoundaryMissing)?
.as_str()
.to_owned();
if boundary.is_empty() {
return Err(Error::BoundaryMissing);
}
Ok((content_type, boundary))
}
/// Constructs a new multipart reader from given Content-Type, boundary, ... |
rust_dataset_chunk_557 | rust_dataset.txt | 557 | 512 | poll read payload to buffer.
buffer.poll_stream(cx)?;
} else if !this.safety.is_clean() {
// safety violation
return Poll::Ready(Some(Err(Error::NotConsumed)));
} else {
return Poll::Pending;
... |
rust_dataset_chunk_558 | rust_dataset.txt | 558 | 512 | .g. for boundary = "foo":
///
/// ```plain
/// --foo <-- in-between fields
/// --foo-- <-- final boundary; an epilogue may follow its CRLF
/// ```
///
/// Returns:
///
/// - `Ok(Some(true))` - final field boundary read
/// - `Ok(Some(false))` - field boundary read
/// - `... |
rust_dataset_chunk_559 | rust_dataset.txt | 559 | 512 | by the intermediate-delimiter check above.
// A closing delimiter may omit CRLF at EOF: b"-- \t\r\n" or b"-- \t".
let chunk = chunk.strip_suffix(LINE_BREAK).unwrap_or(chunk);
// After removing padding, only the closing "--" may remain.
if trim_transport_padding(chunk) == BOUNDARY_MARKE... |
rust_dataset_chunk_560 | rust_dataset.txt | 560 | 512 | }
let field_headers = if let Some(mut payload) = self.payload.get_mut(safety) {
match self.state {
// read until first boundary
State::FirstBoundary => {
match Inner::skip_until_boundary(&mut payload, &self.boundary... |
rust_dataset_chunk_561 | rust_dataset.txt | 561 | 512 | check out other multipart/* RFCs for specific requirements
let field_content_type: Option<Mime> = field_headers
.get(&header::CONTENT_TYPE)
.and_then(|ct| ct.to_str().ok())
.and_then(|ct| ct.parse().ok());
self.state = State::Boundary;
... |
rust_dataset_chunk_562 | rust_dataset.txt | 562 | 512 | abbc761f78ff4d7cb7573b5a23f96ef0";
#[tokio::test(flavor = "local")]
async fn test_boundary() {
let headers = HeaderMap::new();
match Multipart::find_ct_and_boundary(&headers) {
Err(Error::ContentTypeMissing) => {}
_ => unreachable!("should not happen"),
}
... |
rust_dataset_chunk_563 | rust_dataset.txt | 563 | 512 | adsad\r\n".as_bytes());
buf.put(body);
(buf.freeze(), headers)
}
// TODO: use test utility when multi-file support is introduced
fn create_double_request_with_header() -> (Bytes, HeaderMap) {
let bytes = Bytes::from(
"testasdadsad\r\n\
--abbc761f78ff4d7cb7... |
rust_dataset_chunk_564 | rust_dataset.txt | 564 | 512 | multipart = Multipart::from_ct_and_boundary(ct, String::new(), payload);
let res = multipart.next().await.unwrap();
assert_matches!(res, Err(Error::BoundaryMissing));
}
#[tokio::test(flavor = "local")]
async fn short_line_with_one_byte_boundary_does_not_panic() {
let bytes = Bytes:... |
rust_dataset_chunk_565 | rust_dataset.txt | 565 | 512 | _whole_field(&mut field).await, "two");
drop(field);
assert!(multipart.next().await.is_none());
}
#[tokio::test(flavor = "local")]
async fn one_byte_boundary_parses_when_split_across_chunks() {
let bytes = Bytes::from_static(
b"x\r\n\
--a\r\n\
Co... |
rust_dataset_chunk_566 | rust_dataset.txt | 566 | 512 | () {
let body = stream::iter(
[b"aaaaaaaa", b"bbbbbbbb", b"cccccccc"].map(|chunk| Ok(Bytes::from_static(chunk))),
);
let mut multipart = create_multipart_with_buffer_limit(body, 16);
let res = multipart.next().await.unwrap();
assert_matches!(res, Err(Error::Payload(... |
rust_dataset_chunk_567 | rust_dataset.txt | 567 | 512 | field).await,
Bytes::from(vec![b'x'; 100])
);
drop(field);
assert!(multipart.next().await.is_none());
}
#[tokio::test(flavor = "local")]
async fn test_multipart_no_end_crlf() {
let (sender, payload) = create_stream();
let (mut bytes, headers) = create_do... |
rust_dataset_chunk_568 | rust_dataset.txt | 568 | 512 | None => {}
_ => unreachable!(),
}
}
_ => unreachable!(),
}
match multipart.next().await {
None => {}
_ => unreachable!(),
}
}
#[tokio::test(flavor = "local")]
async fn test_multi... |
rust_dataset_chunk_569 | rust_dataset.txt | 569 | 512 | byte])))
.interleave_pending();
let mut multipart = Multipart::new(&headers, payload);
match multipart.next().await.unwrap() {
Ok(mut field) => {
let cd = field.content_disposition().unwrap();
assert_eq!(cd.disposition, DispositionType::FormData);... |
rust_dataset_chunk_570 | rust_dataset.txt | 570 | 512 | actix_web::dev::Payload::H1 { .. } => {} //expected
_ => unreachable!(),
}
}
#[tokio::test(flavor = "local")]
async fn no_content_disposition_form_data() {
let bytes = Bytes::from(
"testasdadsad\r\n\
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
... |
rust_dataset_chunk_571 | rust_dataset.txt | 571 | 512 | | Ok(Bytes::copy_from_slice(&[byte])))
.interleave_pending();
let mut multipart = Multipart::new(&headers, payload);
let res = multipart.next().await.unwrap();
res.unwrap();
}
#[tokio::test(flavor = "local")]
async fn no_name_in_form_data_content_disposition() {
... |
rust_dataset_chunk_572 | rust_dataset.txt | 572 | 512 | bytes, headers) = create_double_request_with_header();
sender.send(Ok(bytes)).unwrap();
drop(sender); // eof
let mut multipart = Multipart::new(&headers, payload);
let mut field = multipart.next().await.unwrap().unwrap();
let task = rt::spawn(async move {
rt::time::... |
rust_dataset_chunk_573 | rust_dataset.txt | 573 | 512 | Self
where
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
PayloadBuffer {
stream: Box::pin(stream),
pending: None,
buf: BytesMut::with_capacity(1_024), // pre-allocate 1KiB
buffer_limit,
eof: false,
}
}
///... |
rust_dataset_chunk_574 | rust_dataset.txt | 574 | 512 | .buf.extend_from_slice(&data);
} else {
let chunk = data.split_to(len);
self.buf.extend_from_slice(&chunk);
self.pending = Some(data);
}
Ok(len != 0)
}
/// Reads exact number of bytes.
#[cfg(test)]
pub(crate) fn read_exact(&mut self, size: us... |
rust_dataset_chunk_575 | rust_dataset.txt | 575 | 512 | until EOF.
#[inline]
pub(crate) fn readline_or_eof(&mut self) -> Result<Option<Bytes>, Error> {
match self.readline() {
Err(Error::Incomplete) if self.eof => Ok(Some(self.buf.split().freeze())),
line => line,
}
}
/// Puts unprocessed data back to the buffer.
... |
rust_dataset_chunk_576 | rust_dataset.txt | 576 | 512 | lazy(|cx| payload.poll_stream(cx)).await.err().unwrap();
}
#[tokio::test(flavor = "local")]
async fn read_max() {
let (mut sender, payload) = h1::Payload::create(false);
let mut payload = PayloadBuffer::new_with_limit(payload, DEFAULT_BUFFER_LIMIT);
sender.feed_data(Bytes::... |
rust_dataset_chunk_577 | rust_dataset.txt | 577 | 512 | assert_eq!(payload.buf.len(), 6);
assert_eq!(
Some(Bytes::from("1line2")),
payload.read_until(b"2").unwrap()
);
assert_eq!(payload.buf.len(), 0);
}
#[tokio::test(flavor = "local")]
async fn poll_stream_does_not_exceed_buffer_limit() {
let stream = f... |
rust_dataset_chunk_578 | rust_dataset.txt | 578 | 512 | most owner, is_clean flag is set to false.
#[derive(Debug)]
pub(crate) struct Safety {
task: LocalWaker,
level: usize,
payload: Rc<PhantomData<bool>>,
clean: Rc<Cell<bool>>,
}
impl Safety {
pub(crate) fn new() -> Safety {
let payload = Rc::new(PhantomData);
Safety {
tas... |
rust_dataset_chunk_579 | rust_dataset.txt | 579 | 512 | fn new(name: impl Into<Cow<'a, str>>, data: impl Into<Bytes>) -> Self {
Self {
name: name.into(),
filename: None,
content_type: None,
data: data.into(),
}
}
/// Sets the field's file name metadata.
pub fn filename(mut self, filename: impl Int... |
rust_dataset_chunk_580 | rust_dataset.txt | 580 | 512 | mut field = TestFormField::new(name, file);
if let Some(filename) = filename {
field = field.filename(filename);
}
if let Some(content_type) = content_type {
field = field.content_type(content_type);
}
create_form_data_payload_and_headers_from_fields([field])
}
/// Constructs a ... |
rust_dataset_chunk_581 | rust_dataset.txt | 581 | 512 | phanumeric.sample_string(&mut rand::rng(), 32);
create_form_data_payload_and_headers_from_fields_with_boundary(&boundary, fields)
}
/// Constructs a `multipart/form-data` payload from multiple fields with a fixed boundary.
// FIXME: terrible naming, but this is needed for compat with the current naming.
// Maybe ... |
rust_dataset_chunk_582 | rust_dataset.txt | 582 | 512 | find_boundary(headers: &HeaderMap) -> String {
headers
.get("content-type")
.unwrap()
.to_str()
.unwrap()
.parse::<mime::Mime>()
.unwrap()
.get_param(mime::BOUNDARY)
.unwrap()
.as_str()
.to_o... |
rust_dataset_chunk_583 | rust_dataset.txt | 583 | 512 | std::str::from_utf8(&pl).unwrap(),
"--------------------------qWeRtYuIoP\r\n\
Content-Disposition: form-data; name=\"foo\"\r\n\
Content-Length: 26\r\n\
\r\n\
Lorem ipsum dolor\n\
sit ame.\r\n\
--------------------------qWeRtYuIoP\r\n\
... |
rust_dataset_chunk_584 | rust_dataset.txt | 584 | 512 | ([
TestFormField::new("title", Bytes::from_static(b"Multipart support")),
TestFormField::new("tags", Bytes::from_static(b"tests")),
TestFormField::new("tags", Bytes::from_static(b"actix")),
]);
let req = headers
.into_iter()
.fold(TestRequest:... |
rust_dataset_chunk_585 | rust_dataset.txt | 585 | 512 | ::read_field did not finish within one second");
assert_eq!(
result.is_ok(),
valid,
"unexpected upload result: {result:?}"
);
}
#[tokio::test(flavor = "local")]
async fn missing_boundary_returns_error() {
check_local("Hello World\r\n", false).await;
}
#[tokio::test(flavor = "local"... |
rust_dataset_chunk_586 | rust_dataset.txt | 586 | 512 | "))
.to_http_parts();
let mut multipart = Multipart::from_request(&req, &mut payload).await.unwrap();
let mut field = multipart.next().await.unwrap().unwrap();
let result = timeout(Duration::from_secs(1), field.next())
.await
.expect("Raw Field stream did not finish at EOF");
a... |
rust_dataset_chunk_587 | rust_dataset.txt | 587 | 512 | actix-multipart/tests/trybuild/max-parts-parse-fail.rs ---
use actix_multipart::form::{bytes::Bytes, MultipartForm};
#[derive(MultipartForm)]
#[multipart(max_parts = -1)]
struct Negative {}
#[derive(MultipartForm)]
#[multipart(max_parts = "many")]
struct InvalidString {}
#[derive(MultipartForm)]
#[multipart(max_part... |
rust_dataset_chunk_588 | rust_dataset.txt | 588 | 512 | #[multipart(rename = "files[]")]
files: Vec<TempFile>,
}
async fn handler(_form: MultipartForm<Form>) -> impl Responder {
"Hello World!"
}
#[actix_web::main]
async fn main() {
App::new().default_service(web::to(handler));
}
--- FILE: actix-web/actix-multipart/tests/trybuild.rs ---
#[rustversion_msrv... |
rust_dataset_chunk_589 | rust_dataset.txt | 589 | 512 | ().default_service(web::to(handler));
}
--- FILE: actix-web/actix-router/benches/quoter.rs ---
use std::{borrow::Cow, fmt::Write as _, hint::black_box};
use criterion::{criterion_group, criterion_main, Criterion};
fn compare_quoters(c: &mut Criterion) {
let mut group = c.benchmark_group("Compare Quoters");
... |
rust_dataset_chunk_590 | rust_dataset.txt | 590 | 512 | ":p3", ":p4")
}};
(brackets) => {{
register!(finish => "{p1}", "{p2}", "{p3}", "{p4}")
}};
(regex) => {{
register!(finish => "(.*)", "(.*)", "(.*)", "(.*)")
}};
(finish => $p1:literal, $p2:literal, $p3:literal, $p4:literal) => {{
#[expect(clippy::useless_concat)]
... |
rust_dataset_chunk_591 | rust_dataset.txt | 591 | 512 | star"),
concat!("/repos/", $p1, "/", $p2, "/git/blobs/", $p3),
concat!("/repos/", $p1, "/", $p2, "/git/commits/", $p3),
concat!("/repos/", $p1, "/", $p2, "/git/refs"),
concat!("/repos/", $p1, "/", $p2, "/git/tags/", $p3),
concat!("/repos/", $p1, "/", $p2, "/gi... |
rust_dataset_chunk_592 | rust_dataset.txt | 592 | 512 | $p2),
concat!("/orgs/", $p1, "/public_members"),
concat!("/orgs/", $p1, "/public_members/", $p2),
concat!("/orgs/", $p1, "/teams"),
concat!("/teams/", $p1),
concat!("/teams/", $p1, "/members"),
concat!("/teams/", $p1, "/members", $p2),
... |
rust_dataset_chunk_593 | rust_dataset.txt | 593 | 512 | concat!("/repos/", $p1, "/", $p2, "/commits/", $p3, "/comments"),
concat!("/repos/", $p1, "/", $p2, "/commits"),
concat!("/repos/", $p1, "/", $p2, "/commits/", $p3),
concat!("/repos/", $p1, "/", $p2, "/readme"),
concat!("/repos/", $p1, "/", $p2, "/keys"),
con... |
rust_dataset_chunk_594 | rust_dataset.txt | 594 | 512 | !("/users/", $p1),
concat!("/user"),
concat!("/users"),
concat!("/user/emails"),
concat!("/users/", $p1, "/followers"),
concat!("/user/followers"),
concat!("/users/", $p1, "/following"),
concat!("/user/following"),
concat!("... |
rust_dataset_chunk_595 | rust_dataset.txt | 595 | 512 | ER: Quoter = Quoter::new(b"", b"");
}
macro_rules! unsupported_type {
($trait_fn:ident, $name:expr) => {
fn $trait_fn<V>(self, _: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(de::Error::custom(concat!("unsupported type: ", $name)))
}
}... |
rust_dataset_chunk_596 | rust_dataset.txt | 596 | 512 | fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_map(ParamsDeserializer {
params: self.path.iter(),
current: None,
})
}
fn deserialize_struct<V>(
self,
_: &'static str,
... |
rust_dataset_chunk_597 | rust_dataset.txt | 597 | 512 | deserialize_enum<V>(
self,
_: &'static str,
_: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.path.is_empty() {
Err(de::value::Error::custom("expected at least one parameters"))
} e... |
rust_dataset_chunk_598 | rust_dataset.txt | 598 | 512 | mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: de::DeserializeSeed<'de>,
{
if let Some((_, value)) = self.current.take() {
seed.deserialize(Value { value })
} else {
Err(de::value::Error::custom("unexpected item"))
}
}
}
struct Key<'de> ... |
rust_dataset_chunk_599 | rust_dataset.txt | 599 | 512 | ::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_unit_struct<V>(
self,
_: &'static str,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.