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_100 | rust_dataset.txt | 100 | 512 | {
if self.is_empty() {
Poll::Ready(None)
} else {
let bytes = match mem::take(self.get_mut()) {
Cow::Borrowed(b) => Bytes::from_static(b),
Cow::Owned(b) => Bytes::from(b),
};
Poll::Ready(Some... |
rust_dataset_chunk_101 | rust_dataset.txt | 101 | 512 | #[inline]
fn poll_next(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Self::Error>>> {
if self.is_empty() {
Poll::Ready(None)
} else {
let bytes = match mem::take(self.get_mut()) {
... |
rust_dataset_chunk_102 | rust_dataset.txt | 102 | 512 | ) -> BodySize {
self.body.size()
}
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Self::Error>>> {
let this = self.as_mut().project();
match ready!(this.body.poll_next(cx)) {
Some(Err(err)) => {
... |
rust_dataset_chunk_103 | rust_dataset.txt | 103 | 512 | assert_eq!(().size(), (&(&mut ())).size());
let pl = &mut ();
let mut pl = pin!(pl);
assert_poll_next_none!(pl);
let pl = &mut Box::new(());
let mut pl = pin!(pl);
assert_poll_next_none!(pl);
let mut body = body::SizedStream::new(
8,
... |
rust_dataset_chunk_104 | rust_dataset.txt | 104 | 512 | pin!(pl);
assert_poll_next!(pl, Bytes::from("test"));
}
#[tokio::test(flavor = "local")]
async fn test_bytes() {
assert_eq!(Bytes::new().size(), BodySize::Sized(0));
assert_eq!(Bytes::from_static(b"test").size(), BodySize::Sized(4));
let pl = Bytes::from_static(b"test");
... |
rust_dataset_chunk_105 | rust_dataset.txt | 105 | 512 | (flavor = "local")]
async fn complete_body_combinators_poll() {
let body = Bytes::from_static(b"test");
let body = BoxBody::new(body);
let body = EitherBody::<_, ()>::left(body);
let body = EitherBody::<(), _>::right(body);
let mut body = body;
assert_eq!(body.size()... |
rust_dataset_chunk_106 | rust_dataset.txt | 106 | 512 | (stream::iter([
Ok::<_, std::io::Error>(Bytes::from("1234")),
Ok(Bytes::from("5678")),
]));
let bytes = body::to_bytes(&mut body).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"12345678"));
}
}
--- FILE: actix-web/actix-http/src/body/mod.rs ---
//! Traits an... |
rust_dataset_chunk_107 | rust_dataset.txt | 107 | 512 | ::None
}
#[inline]
fn poll_next(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Self::Error>>> {
Poll::Ready(Option::None)
}
#[inline]
fn try_into_bytes(self) -> Result<Bytes, Self> {
Ok(Bytes::new())
}
}
--- FILE: actix-we... |
rust_dataset_chunk_108 | rust_dataset.txt | 108 | 512 | <S>
where
S: Stream<Item = Result<Bytes, E>>,
E: Into<Box<dyn StdError>> + 'static,
{
type Error = E;
#[inline]
fn size(&self) -> BodySize {
BodySize::Sized(self.size)
}
/// Attempts to pull out the next value of the underlying [`Stream`].
///
/// Empty values are skipped t... |
rust_dataset_chunk_109 | rust_dataset.txt | 109 | 512 | yield Bytes::new();
yield Bytes::from_static(b"1");
tokio::task::yield_now().await;
yield Bytes::new();
yield Bytes::from_static(b"2");
yield Bytes::new();
};
let body = SizedStream::from_infallible(2, stream);
assert_eq!(body.size(),... |
rust_dataset_chunk_110 | rust_dataset.txt | 110 | 512 | await, Ok(Bytes::new()));
let body = SizedStream::new(1, stream::once(async { Err("stringy error") }));
assert!(matches!(to_bytes(body).await, Err("stringy error")));
}
#[tokio::test(flavor = "local")]
async fn stream_boxed_error() {
// `Box<dyn Error>` does not impl `Error`
... |
rust_dataset_chunk_111 | rust_dataset.txt | 111 | 512 | _eof());
/// ```
pub fn is_eof(&self) -> bool {
matches!(self, BodySize::None | BodySize::Sized(0))
}
}
--- FILE: actix-web/actix-http/src/body/utils.rs ---
use std::{pin::pin, task::Poll};
use actix_utils::future::poll_fn;
use bytes::{Bytes, BytesMut};
use derive_more::{Display, Error};
use futu... |
rust_dataset_chunk_112 | rust_dataset.txt | 112 | 512 | /// let body = Bytes::from_static(b"123");
/// let bytes = to_bytes_limited(body, 10).await.unwrap().unwrap();
/// assert_eq!(bytes, "123");
///
/// let body = Bytes::from_static(b"123");
/// assert!(to_bytes_limited(body, 2).await.is_err());
/// # });
/// ```
pub async fn to_bytes_limited<B: MessageBody>(
body: B,... |
rust_dataset_chunk_113 | rust_dataset.txt | 113 | 512 | (flavor = "local")]
async fn to_bytes_complete() {
let bytes = to_bytes(()).await.unwrap();
assert!(bytes.is_empty());
let body = Bytes::from_static(b"123");
let bytes = to_bytes(body).await.unwrap();
assert_eq!(bytes, b"123"[..]);
}
#[tokio::test(flavor = "local")]... |
rust_dataset_chunk_114 | rust_dataset.txt | 114 | 512 | _bytes_limited(body, 3).await.is_err());
let stream = stream::iter(vec![Bytes::from_static(b"123"), Bytes::from_static(b"abc")])
.map(Ok::<_, Error>);
let body = BodyStream::new(stream);
assert!(to_bytes_limited(body, 3).await.is_err());
}
#[tokio::test(flavor = "local")]
... |
rust_dataset_chunk_115 | rust_dataset.txt | 115 | 512 | : ServiceFactory<Request, Config = ()>,
S::Error: Into<Response<BoxBody>> + 'static,
S::InitError: fmt::Debug,
<S::Service as Service<Request>>::Future: 'static,
{
fn default() -> Self {
HttpServiceBuilder {
// ServiceConfig parts (make sure defaults match)
keep_alive: Ke... |
rust_dataset_chunk_116 | rust_dataset.txt | 116 | 512 | .local_addr = Some(addr);
self
}
/// Set the timeout for reading a client request head.
///
/// Defines a timeout for reading client request header. If the client does not transmit the
/// request head within this duration, the connection is terminated with a `408 Request Timeout`
/// r... |
rust_dataset_chunk_117 | rust_dataset.txt | 117 | 512 | /// Sets the maximum response write buffer size for HTTP/1 connections.
///
/// Once the response buffer reaches this size, the dispatcher flushes it to the I/O stream.
///
/// The default value is 32 KiB.
///
/// # Panics
///
/// Panics if `size` is 0.
pub fn h1_write_buffer_size(m... |
rust_dataset_chunk_118 | rust_dataset.txt | 118 | 512 | .keep_alive,
client_request_timeout: self.client_request_timeout,
client_disconnect_timeout: self.client_disconnect_timeout,
tcp_nodelay: self.tcp_nodelay,
secure: self.secure,
local_addr: self.local_addr,
h1_allow_half_closed: self.h1_allow_half_c... |
rust_dataset_chunk_119 | rust_dataset.txt | 119 | 512 | in middleware
/// and handlers.
pub fn on_connect_ext<F>(mut self, f: F) -> Self
where
F: Fn(&T, &mut Extensions) + 'static,
{
self.on_connect_ext = Some(Rc::new(f));
self
}
/// Finish service configuration and create a service for the HTTP/1 protocol.
pub fn h1<F, ... |
rust_dataset_chunk_120 | rust_dataset.txt | 120 | 512 | local_addr(self.local_addr)
.h1_allow_half_closed(self.h1_allow_half_closed)
.h1_write_buffer_size(self.h1_write_buffer_size)
.h2_initial_window_size(self.h2_stream_window_size)
.h2_initial_connection_window_size(self.h2_conn_window_size)
.graceful_shutdown_si... |
rust_dataset_chunk_121 | rust_dataset.txt | 121 | 512 | Signal {
pub(crate) fn new<F, Fut>(signal: F) -> Self
where
F: Fn() -> Fut + 'static,
Fut: Future<Output = ()> + 'static,
{
Self(Rc::new(move || Box::pin(signal())))
}
fn notified(&self) -> GracefulShutdownFuture {
(self.0)()
}
}
impl fmt::Debug for GracefulShut... |
rust_dataset_chunk_122 | rust_dataset.txt | 122 | 512 | self
}
/// Sets connection keep-alive setting
pub fn keep_alive(mut self, keep_alive: KeepAlive) -> Self {
self.inner.keep_alive = keep_alive;
self
}
/// Sets the timeout for the client to finish sending a request head.
pub fn client_request_timeout(mut self, timeout: Duration... |
rust_dataset_chunk_123 | rust_dataset.txt | 123 | 512 | ///
/// Higher values can improve upload performance on high-latency links at the cost of higher
/// worst-case memory usage per connection.
///
/// The default value is 1MiB.
pub fn h2_initial_window_size(mut self, size: u32) -> Self {
self.inner.h2_stream_window_size = size;
se... |
rust_dataset_chunk_124 | rust_dataset.txt | 124 | 512 | Duration,
client_disconnect_timeout: Duration,
secure: bool,
local_addr: Option<SocketAddr>,
) -> ServiceConfig {
ServiceConfig(Rc::new(Inner {
keep_alive: keep_alive.normalize(),
client_request_timeout,
client_disconnect_timeout,
secu... |
rust_dataset_chunk_125 | rust_dataset.txt | 125 | 512 | let timeout = self.0.client_disconnect_timeout;
(timeout != Duration::ZERO).then(|| self.now() + timeout)
}
/// Whether HTTP/1 connections should support half-closures.
///
/// Clients can choose to shutdown their writer-side of the connection after completing their
/// request and while w... |
rust_dataset_chunk_126 | rust_dataset.txt | 126 | 512 | ].copy_from_slice(if camel_case { b"Date: " } else { b"date: " });
self.0.date_service.with_date(|date| {
buf[PREFIX_LEN..PREFIX_LEN + DATE_VALUE_LENGTH].copy_from_slice(&date.bytes)
});
buf[PREFIX_LEN + DATE_VALUE_LENGTH..].copy_from_slice(b"\r\n");
dst.extend_from_slice(&... |
rust_dataset_chunk_127 | rust_dataset.txt | 127 | 512 | service.clone();
let clone2 = service.clone();
let clone3 = service.clone();
drop(clone1);
assert!(!notify_on_drop::is_dropped());
drop(clone2);
assert!(!notify_on_drop::is_dropped());
drop(clone3);
assert!(!notify_on_drop::is_dropped());
drop(s... |
rust_dataset_chunk_128 | rust_dataset.txt | 128 | 512 | Copy)]
pub(crate) struct Date {
pub(crate) bytes: [u8; DATE_VALUE_LENGTH],
pos: usize,
}
impl Date {
fn new() -> Date {
let mut date = Date {
bytes: [0; DATE_VALUE_LENGTH],
pos: 0,
};
date.update();
date
}
fn update(&mut self) {
self... |
rust_dataset_chunk_129 | rust_dataset.txt | 129 | 512 | {
// stop the timer update async task on drop.
self.handle.abort();
}
}
--- FILE: actix-web/actix-http/src/encoding/decoder.rs ---
//! Stream decoders.
use std::{
future::Future,
io::{self, Write as _},
pin::Pin,
task::{Context, Poll},
};
use bytes::Bytes;
#[cfg(feature = "compr... |
rust_dataset_chunk_130 | rust_dataset.txt | 130 | 512 | Writer::new(), DEFAULT_DECODER_CAPACITY);
br.set_parameter(
brotli_decompressor::BrotliDecoderParameter::BROTLI_DECODER_PARAM_LARGE_WINDOW,
0,
);
Some(ContentDecoder::Brotli(Box::new(br)))
}
#[cfg(feature =... |
rust_dataset_chunk_131 | rust_dataset.txt | 131 | 512 | Identity);
Self::new(stream, encoding)
}
}
impl<S> Stream for Decoder<S>
where
S: Stream<Item = Result<Bytes, PayloadError>>,
{
type Item = Result<Bytes, PayloadError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project()... |
rust_dataset_chunk_132 | rust_dataset.txt | 132 | 512 | decoder.feed_eof() {
Ok(Some(res)) => Poll::Ready(Some(Ok(res))),
Ok(None) => Poll::Ready(None),
Err(err) => Poll::Ready(Some(Err(from_decoder_error(err)))),
}
} else {
... |
rust_dataset_chunk_133 | rust_dataset.txt | 133 | 512 | compress-gzip")]
ContentDecoder::Gzip(ref mut decoder) => match decoder.try_finish() {
Ok(_) => {
let b = decoder.get_mut().take();
if !b.is_empty() {
Ok(Some(b))
} else {
Ok(None)
... |
rust_dataset_chunk_134 | rust_dataset.txt | 134 | 512 | -zstd")]
ContentDecoder::Zstd(ref mut decoder) => match decoder.write_all(&data) {
Ok(_) => {
decoder.flush()?;
let b = decoder.get_mut().take();
if !b.is_empty() {
Ok(Some(b))
} else {
... |
rust_dataset_chunk_135 | rust_dataset.txt | 135 | 512 | encoder.write_all(data).unwrap();
encoder.into_inner().into()
}
#[cfg(feature = "compress-gzip")]
ContentEncoding::Gzip => {
let mut encoder =
flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
... |
rust_dataset_chunk_136 | rust_dataset.txt | 136 | 512 | :?} should report overflow"
);
assert!(
decoder.next().await.is_none(),
"{encoding:?} should end after overflow"
);
}
}
#[tokio::test(flavor = "local")]
async fn decoded_output_at_limit_is_complete() {
let data = vec![b'a';... |
rust_dataset_chunk_137 | rust_dataset.txt | 137 | 512 | (0);
assert!(
matches!(decoder.next().await, Some(Err(PayloadError::Overflow))),
"{encoding:?} should report overflow"
);
}
}
#[test]
fn io_errors_are_not_classified_as_overflow() {
assert!(matches!(
from_decoder_error(io::... |
rust_dataset_chunk_138 | rust_dataset.txt | 138 | 512 | }
}
fn empty() -> Self {
Encoder {
body: EncoderBody::Full { body: Bytes::new() },
encoder: None,
fut: None,
needs_flush: false,
eof: true,
}
}
/// Constructs a response body encoder and updates the response head if co... |
rust_dataset_chunk_139 | rust_dataset.txt | 139 | 512 | #[project = EncoderBodyProj]
enum EncoderBody<B> {
None { body: body::None },
Full { body: Bytes },
Stream { #[pin] body: B },
}
}
impl<B> MessageBody for EncoderBody<B>
where
B: MessageBody,
{
type Error = EncoderError;
#[inline]
fn size(&self) -> BodySize {
m... |
rust_dataset_chunk_140 | rust_dataset.txt | 140 | 512 | Io(io::Error::other(
"Blocking task was cancelled unexpectedly",
))
})?
.map_err(EncoderError::Io)?;
let chunk = encoder.take();
*this.encoder = Some(encoder);
this.fut.take();
... |
rust_dataset_chunk_141 | rust_dataset.txt | 141 | 512 | Err(body) => {
self.body = body;
Err(self)
}
}
}
}
}
fn update_head(encoding: ContentEncoding, head: &mut ResponseHead) {
head.headers_mut()
.insert(header::CONTENT_ENCODING, encoding.to_header_value());
hea... |
rust_dataset_chunk_142 | rust_dataset.txt | 142 | 512 | ().take(),
#[cfg(feature = "compress-gzip")]
ContentEncoder::Gzip(ref mut encoder) => encoder.get_mut().take(),
#[cfg(feature = "compress-zstd")]
ContentEncoder::Zstd(ref mut encoder) => encoder.get_mut().take(),
}
}
fn flush(&mut self) -> Result<(), io... |
rust_dataset_chunk_143 | rust_dataset.txt | 143 | 512 | encoding gzip data: {}", err);
Err(err)
}
},
#[cfg(feature = "compress-gzip")]
ContentEncoder::Deflate(ref mut encoder) => match encoder.write_all(data) {
Ok(_) => Ok(()),
Err(err) => {
trace!("... |
rust_dataset_chunk_144 | rust_dataset.txt | 144 | 512 |
//! controlled by crate features:
//!
//! - `compress-brotli`: Brotli (`br`).
//! - `compress-gzip`: Gzip (`gzip`) and zlib-wrapped DEFLATE (`deflate`).
//! - `compress-zstd`: Zstandard (`zstd`).
//!
//! This module is available when at least one of these features is enabled. Identity encoding and
//! encodings whose ... |
rust_dataset_chunk_145 | rust_dataset.txt | 145 | 512 | _all(b"ab").unwrap();
assert!(writer.write_all(b"cdef").is_err());
assert_eq!(writer.take().as_ref(), b"ab");
assert!(writer.write_all(b"more output").is_err());
assert!(writer.take().is_empty());
}
#[test]
fn writer_zero_limit_rejects_output() {
let mut writer = W... |
rust_dataset_chunk_146 | rust_dataset.txt | 146 | 512 | -> Self {
self.inner.cause = Some(cause.into());
self
}
pub(crate) fn new_http() -> Self {
Self::new(Kind::Http)
}
pub(crate) fn new_parse() -> Self {
Self::new(Kind::Parse)
}
pub(crate) fn new_payload() -> Self {
Self::new(Kind::Payload)
}
pu... |
rust_dataset_chunk_147 | rust_dataset.txt | 147 | 512 | fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.inner.cause.as_ref() {
Some(err) => write!(f, "{}: {err}", self.inner.kind),
None => write!(f, "{}", self.inner.kind),
}
}
}
impl StdError for Error {
fn source(&self) -> ... |
rust_dataset_chunk_148 | rust_dataset.txt | 148 | 512 | #[display("Timeout")]
Timeout,
/// An I/O error that occurred while trying to read or write to a network stream.
#[display("I/O error: {}", _0)]
Io(io::Error),
/// Parsing a field as string failed.
#[display("UTF-8 error: {}", _0)]
Utf8(Utf8Error),
}
impl From<io::Error> for ParseErro... |
rust_dataset_chunk_149 | rust_dataset.txt | 149 | 512 | ,
/// Payload length is unknown.
#[display("Payload length is unknown")]
UnknownLength,
/// HTTP/2 payload error.
#[cfg(feature = "http2")]
#[display("{}", _0)]
Http2Payload(::h2::Error),
/// Generic I/O error.
#[display("{}", _0)]
Io(io::Error),
}
impl std::error::Error for ... |
rust_dataset_chunk_150 | rust_dataset.txt | 150 | 512 | #[display("{}", _0)]
#[cfg(feature = "http2")]
H2(h2::Error),
/// The first request did not complete within the specified timeout.
#[display("Request did not complete within the specified timeout")]
SlowRequestTimeout,
/// Disconnect timeout. Makes sense for TLS streams.
#[display("Con... |
rust_dataset_chunk_151 | rust_dataset.txt | 151 | 512 | ("other");
let err = Error::new_io().with_cause(orig);
assert_eq!("Connection error: other", err.to_string());
}
#[test]
fn test_error_http_response() {
let orig = io::Error::other("other");
let err = Error::new_io().with_cause(orig);
let resp: Response<BoxBody> = er... |
rust_dataset_chunk_152 | rust_dataset.txt | 152 | 512 | BuildHasherDefault, Hasher},
};
/// A hasher for `TypeId`s that takes advantage of its known characteristics.
///
/// Author of `anymap` crate has done research on the topic:
/// https://github.com/chris-morgan/anymap/blob/2e9a5704/src/lib.rs#L599
#[derive(Debug, Default)]
struct NoOpHasher(u64);
impl Hasher for NoOp... |
rust_dataset_chunk_153 | rust_dataset.txt | 153 | 512 | None);
/// assert!(map.contains::<u32>());
/// ```
pub fn contains<T: 'static>(&self) -> bool {
self.map.contains_key(&TypeId::of::<T>())
}
/// Get a reference to an item of a given type.
///
/// ```
/// # use actix_http::Extensions;
/// let mut map = Extensions::new();
... |
rust_dataset_chunk_154 | rust_dataset.txt | 154 | 512 | /// let mut map = Extensions::new();
/// assert_eq!(map.get::<Vec<u32>>(), None);
///
/// map.get_or_insert_with(Vec::<u32>::new).push(1);
/// assert_eq!(map.get::<Vec<u32>>(), Some(&vec![1]));
///
/// map.get_or_insert_with(Vec::<u32>::new).push(2);
/// assert_eq!(map.get::<Vec<u32>>(),... |
rust_dataset_chunk_155 | rust_dataset.txt | 155 | 512 | ()
}
}
fn downcast_owned<T: 'static>(boxed: Box<dyn Any>) -> Option<T> {
boxed.downcast().ok().map(|boxed| *boxed)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_remove() {
let mut map = Extensions::new();
map.insert::<i8>(123);
assert!(map.get::<i8>().is_some()... |
rust_dataset_chunk_156 | rust_dataset.txt | 156 | 512 | }
#[test]
fn test_composition() {
struct Magi<T>(pub T);
struct Madoka {
pub god: bool,
}
struct Homura {
pub attempts: usize,
}
struct Mami {
pub guns: usize,
}
let mut map = Extensions::new();
... |
rust_dataset_chunk_157 | rust_dataset.txt | 157 | 512 | /h1/chunked.rs ---
use std::{io, task::Poll};
use bytes::{Buf as _, Bytes, BytesMut};
use tracing::{debug, trace};
macro_rules! byte (
($rdr:ident) => ({
match &$rdr[..] {
&[b, ..] => {
$rdr.advance(1);
b
}
[] => return Poll::Pending,
... |
rust_dataset_chunk_158 | rust_dataset.txt | 158 | 512 | '..=b'9' => b - b'0',
b @ b'a'..=b'f' => b + 10 - b'a',
b @ b'A'..=b'F' => b + 10 - b'A',
_ => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk size line: Invalid size first-byte",
... |
rust_dataset_chunk_159 | rust_dataset.txt | 159 | 512 | | b' ' => Poll::Ready(Ok(ChunkedState::SizeLws)),
b';' => Poll::Ready(Ok(ChunkedState::Extension)),
b'\r' => Poll::Ready(Ok(ChunkedState::SizeLf)),
_ => Poll::Ready(Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk size linear white spac... |
rust_dataset_chunk_160 | rust_dataset.txt | 160 | 512 | (io::Error::new(
io::ErrorKind::InvalidData,
"Invalid character in chunk extension quoted string",
))),
}
}
fn read_extension_quoted_pair(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> {
// RFC 9110 §5.6.4 relevant BNFs:
// quote... |
rust_dataset_chunk_161 | rust_dataset.txt | 161 | 512 | buf = Some(slice);
if *rem > 0 {
Poll::Ready(Ok(ChunkedState::Body))
} else {
Poll::Ready(Ok(ChunkedState::BodyCr))
}
}
}
fn read_body_cr(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> {
match byte!(rdr) {
... |
rust_dataset_chunk_162 | rust_dataset.txt | 162 | 512 | Poll::Ready(Ok(ChunkedState::EndCr)),
_ => Poll::Ready(Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid chunk trailer LF",
))),
}
}
fn read_end_cr(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> {
match byte!(rdr) {
... |
rust_dataset_chunk_163 | rust_dataset.txt | 163 | 512 | ) => {
assert_eq!(
$pl.decode(&mut $buf).unwrap().unwrap().chunk().as_ref(),
$expected,
);
};
}
macro_rules! assert_decode_chunked_eof {
($pl:expr, $buf:expr) => {
assert!($pl.decode(&mut $buf).unwrap().unwrap().eof());
... |
rust_dataset_chunk_164 | rust_dataset.txt | 164 | 512 | (val) = req.chunked() {
assert!(val);
} else {
unreachable!("Error");
}
// intentional typo in "chunked"
let mut buf = BytesMut::from(
"GET /test HTTP/1.1\r\n\
Host: localhost\r\n\
transfer-encoding: chnked\r\n\r\n",
... |
rust_dataset_chunk_165 | rust_dataset.txt | 165 | 512 | ");
let msg = pl.decode(&mut buf).unwrap().unwrap();
assert!(msg.eof());
let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
assert!(req.chunked().unwrap());
assert_eq!(*req.method(), Method::POST);
assert!(req.chunked().unwrap());
}
#[test]
fn test_ht... |
rust_dataset_chunk_166 | rust_dataset.txt | 166 | 512 | Transfer-Encoding: chunked\r\n\
\r\n\
2;hello=b;one=\"1 2 3\"\r\n\
xx",
);
let mut reader = MessageDecoder::<Request>::default();
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
let mut pl = pl.unwrap();
let chunk = pl... |
rust_dataset_chunk_167 | rust_dataset.txt | 167 | 512 | .decode(&mut buf)
.expect("Valid quoted-pair bytes should decode")
{
match item {
PayloadItem::Chunk(chunk) => body.extend_from_slice(&chunk),
PayloadItem::Eof => {
... |
rust_dataset_chunk_168 | rust_dataset.txt | 168 | 512 | escaped quote cannot close the string, and a backslash cannot escape CR.
for prefix in [b"1;ext=\"\\\"".as_slice(), b"1;ext=\"\\"] {
// Test every split point so quote and escape state must survive partial reads.
for split in 0..=prefix.len() {
let mut pl = PayloadDecode... |
rust_dataset_chunk_169 | rust_dataset.txt | 169 | 512 | \r\n\
0\r\n",
);
let mut reader = MessageDecoder::<Request>::default();
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
let mut pl = pl.unwrap();
let err = pl.decode(&mut buf).unwrap_err();
assert!(err
.to_string()
.contai... |
rust_dataset_chunk_170 | rust_dataset.txt | 170 | 512 | later CR or connection EOF.
let err = pl.decode(&mut buf).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(buf.is_empty());
}
}
#[test]
fn test_chunked_trailer_rejects_control_bytes() {
for byte in (0x00..=0x1f).chain([0x7f]) {
... |
rust_dataset_chunk_171 | rust_dataset.txt | 171 | 512 | 2\r\n\r\nab";
// End the trailer with bare LF, then append a complete request in the same buffer.
buf.extend_from_slice(b"5\r\nhello\r\n0\r\nX\n");
buf.extend_from_slice(next_request);
assert_decode_chunk_eq!(pl, buf, b"hello");
// Stop at the invalid LF and leave the entire ... |
rust_dataset_chunk_172 | rust_dataset.txt | 172 | 512 | self, PayloadDecoder, PayloadItem, PayloadType},
encoder, reserve_readbuf, Message, MessageType,
};
use crate::{
body::BodySize,
error::{ParseError, PayloadError},
ConnectionType, RequestHeadType, ResponseHead, ServiceConfig,
};
bitflags! {
#[derive(Debug, Clone, Copy)]
struct Flags: u8 {
... |
rust_dataset_chunk_173 | rust_dataset.txt | 173 | 512 | == ConnectionType::KeepAlive
}
/// Check last request's message type
pub fn message_type(&self) -> MessageType {
if self.inner.flags.contains(Flags::STREAM) {
MessageType::Stream
} else if self.inner.payload.is_none() {
MessageType::None
} else {
... |
rust_dataset_chunk_174 | rust_dataset.txt | 174 | 512 | (match self.inner.payload.as_mut().unwrap().decode(src)? {
Some(PayloadItem::Chunk(chunk)) => {
reserve_readbuf(src);
Some(Some(chunk))
}
Some(PayloadItem::Eof) => {
self.inner.payload.take();
Some(None)
}
... |
rust_dataset_chunk_175 | rust_dataset.txt | 175 | 512 | = 0b0000_0010;
const STREAM = 0b0000_0100;
}
}
/// HTTP/1 Codec
pub struct Codec {
config: ServiceConfig,
decoder: decoder::MessageDecoder<Request>,
payload: Option<PayloadDecoder>,
version: Version,
conn_type: ConnectionType,
// encoder part
flags: Flags,
pub(... |
rust_dataset_chunk_176 | rust_dataset.txt | 176 | 512 | &self.config
}
}
impl Decoder for Codec {
type Item = Message<Request>;
type Error = ParseError;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if let Some(ref mut payload) = self.payload {
Ok(match payload.decode(src)? {
... |
rust_dataset_chunk_177 | rust_dataset.txt | 177 | 512 | Chunk(Some(bytes)) => {
self.encoder.encode_chunk(bytes.as_ref(), dst)?;
}
Message::Chunk(None) => {
self.encoder.encode_eof(dst)?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
header::{Heade... |
rust_dataset_chunk_178 | rust_dataset.txt | 178 | 512 | buf.extend(
b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n\
POST /test2 HTTP/1.1\r\n\
Host: localhost\r\n\
transfer-encoding: chunked\r\n\r\n"
.iter(),
);
let msg = codec.decode(&mut buf).unwrap().unwrap();
assert_eq!(msg.c... |
rust_dataset_chunk_179 | rust_dataset.txt | 179 | 512 | (PayloadDecoder),
}
impl<T: MessageType> Default for MessageDecoder<T> {
fn default() -> Self {
MessageDecoder(PhantomData)
}
}
impl<T: MessageType> Decoder for MessageDecoder<T> {
type Item = (T, PayloadType);
type Error = ParseError;
fn decode(&mut self, src: &mut BytesMut) -> Result<Op... |
rust_dataset_chunk_180 | rust_dataset.txt | 180 | 512 | Content-Length");
return Err(ParseError::Header);
}
header::CONTENT_LENGTH => match value.to_str().map(str::trim) {
Ok(val) if val.starts_with('+') => {
debug!("illegal Content-Length: {:?}", val);
... |
rust_dataset_chunk_181 | rust_dataset.txt | 181 | 512 | ::UPGRADE => {
if let Ok(val) = value.to_str().map(str::trim) {
if val.eq_ignore_ascii_case("websocket") {
has_upgrade_websocket = true;
}
}
}
... |
rust_dataset_chunk_182 | rust_dataset.txt | 182 | 512 | // Create an uninitialized array of `MaybeUninit`. The `assume_init` is safe because the
// type we are claiming to have initialized here is a bunch of `MaybeUninit`s, which
// do not require initialization.
let mut parsed = unsafe {
MaybeUninit::<[MaybeUn... |
rust_dataset_chunk_183 | rust_dataset.txt | 183 | 512 | }
if msg.head().headers.contains_key(header::CONTENT_LENGTH) {
debug!("both Content-Length and Transfer-Encoding are set");
return Err(ParseError::Header);
}
}
// disallow HTTP/1.0 POST requests that do not contain a Content-Length headers
... |
rust_dataset_chunk_184 | rust_dataset.txt | 184 | 512 | which
// do not require initialization.
let mut parsed = unsafe {
MaybeUninit::<[MaybeUninit<httparse::Header<'_>>; MAX_HEADERS]>::uninit()
.assume_init()
};
let mut res = httparse::Response::new(&mut []);
let mut config ... |
rust_dataset_chunk_185 | rust_dataset.txt | 185 | 512 | else {
// for HTTP/1.0 read to eof and close connection
if msg.version == Version::HTTP_10 {
msg.set_connection_type(ConnectionType::Close);
PayloadType::Payload(PayloadDecoder::eof())
} else {
PayloadType::None
}
}... |
rust_dataset_chunk_186 | rust_dataset.txt | 186 | 512 | -> PayloadDecoder {
PayloadDecoder { kind: Kind::Eof }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
/// A reader used when a `Content-Length` header is passed with a positive integer.
Length(u64),
/// A reader used when `Transfer-Encoding` is `chunked`.
Chunked(ChunkedState, u64... |
rust_dataset_chunk_187 | rust_dataset.txt | 187 | 512 | (ref mut state, ref mut size) => {
loop {
let mut buf = None;
// advances the chunked state
*state = match state.step(src, size, &mut buf) {
Poll::Pending => return Ok(None),
Poll::Ready(Ok(state... |
rust_dataset_chunk_188 | rust_dataset.txt | 188 | 512 | () {
let mut buf = BytesMut::from("GET /test HTTP/1.1\r\nHost: localhost\r\n\r\n");
let mut reader = MessageDecoder::<Request>::default();
match reader.decode(&mut buf) {
Ok(Some((req, _))) => {
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(... |
rust_dataset_chunk_189 | rust_dataset.txt | 189 | 512 | \r\n\
\r\n",
);
let mut reader = MessageDecoder::<Request>::default();
let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
assert_eq!(req.version(), Version::HTTP_10);
assert_eq!(*req.method(), Method::GET);
assert_eq!(req.path(), "/test2");
le... |
rust_dataset_chunk_190 | rust_dataset.txt | 190 | 512 | Host: localhost\r\nContent-Length: 4\r\n\r\nbody",
);
let mut reader = MessageDecoder::<Request>::default();
let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
let mut pl = pl.unwrap();
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(*req.method(), Method... |
rust_dataset_chunk_191 | rust_dataset.txt | 191 | 512 | is_none() }
buf.extend(b"t: value\r\n\r\n");
let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
assert_eq!(req.version(), Version::HTTP_11);
assert_eq!(*req.method(), Method::GET);
assert_eq!(req.path(), "/test");
assert_eq!(
req.headers()
... |
rust_dataset_chunk_192 | rust_dataset.txt | 192 | 512 | continue\r\n\r\n",
));
assert!(!req.head().expect());
}
#[test]
fn test_conn_default_1_0() {
let req = parse_ready!(&mut BytesMut::from("GET /test HTTP/1.0\r\n\r\n"));
assert_eq!(req.head().connection_type(), ConnectionType::Close);
}
#[test]
fn test_conn_defaul... |
rust_dataset_chunk_193 | rust_dataset.txt | 193 | 512 | GET /test HTTP/1.1\r\n\
Host: localhost\r\n\
connection: keep-alive\r\n\r\n",
));
assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
}
#[test]
fn test_conn_other_1_0() {
let req = parse_ready!(&mut BytesMut::from(
"GET /test HT... |
rust_dataset_chunk_194 | rust_dataset.txt | 194 | 512 | req = parse_ready!(&mut BytesMut::from(raw.as_str()));
assert_eq!(req.head().connection_type(), expected, "{connection:?}");
assert_eq!(
req.upgrade(),
expected == ConnectionType::Upgrade,
"{connection:?}"
);
assert_eq!(req... |
rust_dataset_chunk_195 | rust_dataset.txt | 195 | 512 | ::from("getpath \r\n\r\n"));
}
#[test]
fn test_http_request_upgrade_websocket() {
let mut buf = BytesMut::from(
"GET /test HTTP/1.1\r\n\
Host: localhost\r\n\
connection: upgrade\r\n\
upgrade: websocket\r\n\r\n\
some raw data",
... |
rust_dataset_chunk_196 | rust_dataset.txt | 196 | 512 | HT/11\r\n\r\n"));
}
#[test]
fn test_response_http10_read_until_eof() {
let mut buf = BytesMut::from("HTTP/1.0 200 Ok\r\n\r\ntest data");
let mut reader = MessageDecoder::<ResponseHead>::default();
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
let mut pl = pl.... |
rust_dataset_chunk_197 | rust_dataset.txt | 197 | 512 | : example.com\r\n\
Content-Length: 0\r\n\
Content-Length: 2\r\n\
\r\n\
ab",
));
}
#[test]
fn hrs_content_length_plus() {
expect_parse_err!(&mut BytesMut::from(
"GET / HTTP/1.1\r\n\
Host: example.com\r\n\
Con... |
rust_dataset_chunk_198 | rust_dataset.txt | 198 | 512 | "POST / HTTP/1.1\r\n\
Host: example.com\r\n\
Content-Length: 3\r\n\
Transfer-Encoding: identity\r\n\
\r\n\
0\r\n",
));
}
#[test]
fn hrs_unknown_transfer_encoding() {
let mut buf = BytesMut::from(
"GET / HTTP... |
rust_dataset_chunk_199 | rust_dataset.txt | 199 | 512 | fn http11_reject_duplicate_host_header() {
let mut buf = BytesMut::from(
"GET /test HTTP/1.1\r\n\
Host: example.com\r\n\
Host: duplicate.com\r\n\r\n",
);
let mut reader = MessageDecoder::<Request>::default();
let err = reader.decode(&mut buf).unwr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.