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_200 | rust_dataset.txt | 200 | 512 | Poll::Ready(Ok(written))
}
// as a TCP stream does, so large sized bodies are written without the copy; the default
// `poll_write_vectored` writes one buffer per call
fn is_write_vectored(&self) -> bool {
true
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> ... |
rust_dataset_chunk_201 | rust_dataset.txt | 201 | 512 | once(async move {
Ok::<_, Infallible>(chunk)
}));
Ok::<_, Error>(Response::ok().set_body(body))
}),
ExpectHandler,
None::<UpgradeHandler>,
);
let dispatcher = Dispatcher::new(
LimitedWriter {
io: io.clone(),
allowanc... |
rust_dataset_chunk_202 | rust_dataset.txt | 202 | 512 | HTTP headers.
// A smaller retained buffer must not come at the cost of missing response bytes.
let body_start = response
.windows(4)
.position(|window| window == b"\r\n\r\n")
.unwrap()
+ 4;
let mut body = format!("{body_len:X}\r\n").into_bytes();
body.extend(vec![b'x'; ... |
rust_dataset_chunk_203 | rust_dataset.txt | 203 | 512 | ).await;
}
#[tokio::test(flavor = "local")]
async fn small_write_watermark_preserves_normal_buffer() {
// A small watermark must not lower the 128 KiB retention limit.
check_buffer_retention(64 * 1024, 8 * 1024, false, false).await;
}
#[tokio::test(flavor = "local")]
async fn buffer_above_configured_write_wat... |
rust_dataset_chunk_204 | rust_dataset.txt | 204 | 512 | {
// The head is out, but the normal write buffer remains available for reuse.
assert!(inner.write_body.is_some());
assert!(
inner.write_buf.capacity() > LW_BUFFER_SIZE
&& inner.write_buf.capacity() <= HW_BUFFER_SIZE,
"write buffer... |
rust_dataset_chunk_205 | rust_dataset.txt | 205 | 512 | Request, Response, StatusCode,
};
const LW_BUFFER_SIZE: usize = 1024;
const HW_BUFFER_SIZE: usize = 1024 * 8;
const MAX_PIPELINED_MESSAGES: usize = 16;
/// Write buffer capacity at which we reallocate it after flushing.
const WRITE_BUFFER_RETENTION_LIMIT: usize = 1024 * 128;
bitflags! {
#[derive(Debug, Clone, C... |
rust_dataset_chunk_206 | rust_dataset.txt | 206 | 512 | <BoxBody>>,
U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{
#[pin]
inner: DispatcherState<T, S, B, X, U>,
}
}
#[cfg(test)]
pin_project! {
/// Dispatcher for HTTP/1.1 protocol
pub struct Dispatcher<T, S, B, X, U>
where
S: Ser... |
rust_dataset_chunk_207 | rust_dataset.txt | 207 | 512 | Error>,
#[pin]
pub(super) state: State<S, B, X>,
// when Some(_) dispatcher is in state of receiving request payload
payload: Option<PayloadSender>,
// true when current request uses chunked transfer encoding (drainable when payload is dropped)
payload_drainable: bool,
... |
rust_dataset_chunk_208 | rust_dataset.txt | 208 | 512 | U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{
/// Copies any pending body bytes into `write_buf` and clears `write_body`.
fn ensure_body_buffered(&mut self) {
if let Some(body) = self.write_body.take() {
self.write_buf.extend_from_slice(&body);
... |
rust_dataset_chunk_209 | rust_dataset.txt | 209 | 512 | , S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Response<BoxBody>>,
S::Response: Into<Response<B>>,
B: MessageBody,
X: Service<Request, Response = Request>,
X::Error: Into<Response<BoxBody>>,
U: Service<(Request, Framed<T, Codec>), Response ... |
rust_dataset_chunk_210 | rust_dataset.txt | 210 | 512 | >,
U::Error: fmt::Display,
{
fn can_read(&self, cx: &mut Context<'_>) -> bool {
if self.flags.contains(Flags::READ_DISCONNECT) {
false
} else if let Some(ref info) = self.payload {
matches!(
info.need_read(cx),
PayloadStatus::Read | Payload... |
rust_dataset_chunk_211 | rust_dataset.txt | 211 | 512 | new(body)])?,
// Keep buffered bytes ahead of the body when writing one slice at a time.
(head, _) => io.as_mut().poll_write(cx, head)?,
};
match polled {
Poll::Ready(0) => {
error!("write zero; closing");
... |
rust_dataset_chunk_212 | rust_dataset.txt | 212 | 512 | }
}
fn poll_linger(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Result<Poll<()>, DispatchError> {
if self.as_mut().poll_flush(cx)?.is_pending() {
return Ok(Poll::Pending);
}
if !self.as_mut().ensure_linger_timer(cx) {
let thi... |
rust_dataset_chunk_213 | rust_dataset.txt | 213 | 512 | ::Close);
}
let size = self.as_mut().send_response_inner(res, &body)?;
match size {
BodySize::None | BodySize::Sized(0) => {
let mut this = self.as_mut().project();
if close_for_unread_payload {
if this.config.client_disconnect_de... |
rust_dataset_chunk_214 | rust_dataset.txt | 214 | 512 | _buf
.extend_from_slice(b"HTTP/1.1 100 Continue\r\n\r\n");
}
fn poll_response(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Result<PollResponse, DispatchError> {
'res: loop {
let mut this = self.as_mut().project();
match this.state.as_mut(... |
rust_dataset_chunk_215 | rust_dataset.txt | 215 | 512 | ().replace_body(());
self.as_mut().send_response(res, body)?;
}
// send service call error as response
Poll::Ready(Err(err)) => {
let res: Response<BoxBody> = err.into();
... |
rust_dataset_chunk_216 | rust_dataset.txt | 216 | 512 | () {
Self::enter_linger(this.flags);
} else {
this.flags.insert(Flags::SHUTDOWN | Flags::FINISHED);
}
} else {
... |
rust_dataset_chunk_217 | rust_dataset.txt | 217 | 512 | _deadline().is_some() {
Self::enter_linger(this.flags);
} else {
this.flags.insert(Flags::SHUTDOWN | Flags::FINISHED);
}
} else {
... |
rust_dataset_chunk_218 | rust_dataset.txt | 218 | 512 | this.state.set(State::ServiceCall { fut });
};
};
// eagerly poll the future once (or twice if expect is resolved immediately).
loop {
match self.as_mut().project().state.project() {
StateProj::ExpectCall { fut } => {
match fut.poll(c... |
rust_dataset_chunk_219 | rust_dataset.txt | 219 | 512 | Pin<&mut Self>, cx: &mut Context<'_>) -> Result<bool, DispatchError> {
if self.flags.contains(Flags::DRAINING) && self.state.is_none() {
return Ok(false);
}
let pipeline_queue_full = self.messages.len() >= MAX_PIPELINED_MESSAGES;
let can_not_read = !self.can_read(cx);
... |
rust_dataset_chunk_220 | rust_dataset.txt | 220 | 512 | }
Message::Chunk(Some(chunk)) => {
if let Some(ref mut payload) = this.payload {
payload.feed_data(chunk);
} else {
error!("Internal server error: unex... |
rust_dataset_chunk_221 | rust_dataset.txt | 221 | 512 | trace!("parse error {}", &err);
if let Some(mut payload) = this.payload.take() {
payload.set_error(PayloadError::EncodingCorrupted);
}
// malformed requests should be responded with 400
this.mes... |
rust_dataset_chunk_222 | rust_dataset.txt | 222 | 512 | -alive timer has timed out
if timer.as_mut().poll(cx).is_ready() {
// no tasks at hand
trace!("timer timed out; closing connection");
this.flags.insert(Flags::SHUTDOWN);
if let Some(deadline) = this.config.client_disconnect_deadline() {
... |
rust_dataset_chunk_223 | rust_dataset.txt | 223 | 512 | )?;
self.as_mut().poll_shutdown_timer(cx)?;
Ok(())
}
/// Returns true when I/O stream can be disconnected after write to it.
///
/// It covers these conditions:
/// - `std::io::ErrorKind::ConnectionReset` after partial read;
/// - all data read done.
#[inline(always)] // TO... |
rust_dataset_chunk_224 | rust_dataset.txt | 224 | 512 | tokio_util::io::poll_read_buf(io.as_mut(), cx, this.read_buf) {
Poll::Ready(Ok(n)) => {
// When draining a dropped request payload, keep FINISHED set so the
// disconnect/keep-alive decision can be made once the payload is fully drained.
if !t... |
rust_dataset_chunk_225 | rust_dataset.txt | 225 | 512 | )]
{
*this.poll_count += 1;
}
match this.inner.project() {
DispatcherStateProj::Upgrade { fut: upgrade } => upgrade.poll(cx).map_err(|err| {
error!("Upgrade handler error: {}", err);
DispatchError::Upgrade
}),
Disp... |
rust_dataset_chunk_226 | rust_dataset.txt | 226 | 512 | (mut payload) = inner.payload.take() {
payload.set_error(PayloadError::Incomplete(None));
payload.feed_eof();
}
};
loop {
// poll response to populate write buffer
... |
rust_dataset_chunk_227 | rust_dataset.txt | 227 | 512 | true:
//
// - state is [`State::None`], which means that we're done with request
// processing, so if the client closed its writer-side it means that it won't
// send more requests.
// - The user requested to not al... |
rust_dataset_chunk_228 | rust_dataset.txt | 228 | 512 | body can be passed to the I/O in one write.
///
/// Uniquely owned chunks with spare capacity are also buffered. For example, the `String` produced
/// by JSON serialization can have more capacity than the body needs. Copying its contents into
/// `write_buf` lets the original allocation be freed instead of retaining ... |
rust_dataset_chunk_229 | rust_dataset.txt | 229 | 512 | ::{pin, Pin},
rc::Rc,
str,
task::{Context, Poll},
time::Duration,
};
use actix_codec::Framed;
use actix_service::{fn_service, Service};
use bytes::{Bytes, BytesMut};
use futures_util::{future::lazy, StreamExt as _};
use memchr::memmem;
use tokio::{
io::{AsyncRead, AsyncWrite, ReadBuf},
time::{s... |
rust_dataset_chunk_230 | rust_dataset.txt | 230 | 512 | buf = TestBuffer::empty();
let cfg = ServiceConfig::new(
KeepAlive::Disabled,
Duration::from_millis(100),
Duration::ZERO,
false,
None,
);
let services = HttpFlow::new(ok_service(), ExpectHandler, None);
let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new(
... |
rust_dataset_chunk_231 | rust_dataset.txt | 231 | 512 | );
let services = HttpFlow::new(echo_path_service(), ExpectHandler, None);
let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new(
buf.clone(),
services,
cfg,
None,
OnConnectData::default(),
);
let mut h1 = pin!(h1);
lazy(|cx| {
assert!(matches!(&h1... |
rust_dataset_chunk_232 | rust_dataset.txt | 232 | 512 | // polls: initial
assert_eq!(h1.poll_count, 1);
let mut res = buf.take_write_buf().to_vec();
stabilize_date_header(&mut res);
let res = &res[..];
let exp = b"\
HTTP/1.1 200 OK\r\n\
content-length: 5\r\n\
date: Thu, 01 Jan ... |
rust_dataset_chunk_233 | rust_dataset.txt | 233 | 512 | h1.as_mut().poll(cx).is_pending(),
"keep-alive should prevent poll from resolving"
);
// polls: initial
assert_eq!(h1.poll_count, 1);
let mut res = buf.take_write_buf().to_vec();
stabilize_date_header(&mut res);
let res = &res[..];
let exp = b"\
... |
rust_dataset_chunk_234 | rust_dataset.txt | 234 | 512 | mut res = buf.take_write_buf().to_vec();
stabilize_date_header(&mut res);
let res = &res[..];
let exp = b"\
HTTP/1.1 200 OK\r\n\
content-length: 4\r\n\
connection: close\r\n\
date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\r\n\
... |
rust_dataset_chunk_235 | rust_dataset.txt | 235 | 512 | \r\n");
let services = HttpFlow::new(ok_service(), ExpectHandler, None);
let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new(
buf.clone(),
services,
ServiceConfig::default(),
None,
OnConnectData::default(),
);
let mut h1 =... |
rust_dataset_chunk_236 | rust_dataset.txt | 236 | 512 | 01 Jan 1970 12:34:56 UTC\r\n\r\n\
/abcd\
HTTP/1.1 200 OK\r\n\
content-length: 4\r\n\
connection: close\r\n\
date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\r\n\
/def\
";
assert_eq!(
res,
... |
rust_dataset_chunk_237 | rust_dataset.txt | 237 | 512 | ?}\n\
expected: {:?}",
String::from_utf8_lossy(res),
String::from_utf8_lossy(exp)
);
buf.close_read();
assert!(h1.as_mut().poll(cx).is_pending());
assert!(h1.as_mut().poll(cx).is_ready());
})
.await;
}
#[tokio::test(flavor = "local")]
async f... |
rust_dataset_chunk_238 | rust_dataset.txt | 238 | 512 | uses_graceful_shutdown() {
let buf = TestSeqBuffer::new(
"\
POST / HTTP/1.1\r\n\
Host: localhost\r\n\
Content-Length: 8\r\n\
\r\n\
ab\
",
);
let cfg = ServiceConfig::new(
KeepAlive::Disabled,
Duration::ZERO,
... |
rust_dataset_chunk_239 | rust_dataset.txt | 239 | 512 | assert!(matches!(&h1.inner, DispatcherState::Normal { .. }));
match h1.as_mut().poll(cx) {
Poll::Pending => panic!("First poll should not be pending"),
Poll::Ready(res) => assert!(res.is_err()),
}
// polls: initial => shutdown
assert_eq!(h1.poll_count, 1);
... |
rust_dataset_chunk_240 | rust_dataset.txt | 240 | 512 | !(h1.poll_count, 1);
if let DispatcherState::Normal { ref inner } = h1.inner {
let io = inner.io.as_ref().unwrap();
let res = &io.write_buf()[..];
assert_eq!(
str::from_utf8(res).unwrap(),
"HTTP/1.1 100 Continue\r\n\r\n"
);
... |
rust_dataset_chunk_241 | rust_dataset.txt | 241 | 512 | .poll_count, 2);
if let DispatcherState::Normal { ref inner } = h1.inner {
let io = inner.io.as_ref().unwrap();
let mut res = io.write_buf()[..].to_owned();
stabilize_date_header(&mut res);
// Despite the content-length header and even though the request payload... |
rust_dataset_chunk_242 | rust_dataset.txt | 242 | 512 | \
\r\n\
",
);
let mut h1 = pin!(h1);
assert!(h1.as_mut().poll(cx).is_ready());
assert!(matches!(&h1.inner, DispatcherState::Upgrade { .. }));
// polls: manual shutdown
assert_eq!(h1.poll_count, 2);
})
.await;
}
#[tokio::test(fla... |
rust_dataset_chunk_243 | rust_dataset.txt | 243 | 512 | hbXBsZSBub25jZQ==
",
));
let services = HttpFlow::new(
fn_service(|req: Request| {
ready(crate::ws::handshake(req.head()).map(|mut res| res.finish()))
}),
ExpectHandler,
None::<UpgradeHandler>,
);
let h1 = Dispatcher::new(
buf.clone(),
... |
rust_dataset_chunk_244 | rust_dataset.txt | 244 | 512 | : 15
date: Thu, 01 Jan 1970 12:34:56 UTC
payload dropped
",
);
assert_eq!(
res,
exp,
"\nexpected response not in write buffer:\n\
response: {:?}\n\
expected: {:?}",
String::from_utf8_lossy... |
rust_dataset_chunk_245 | rust_dataset.txt | 245 | 512 |
connection: close
date: Thu, 01 Jan 1970 12:34:56 UTC
",
);
assert_eq!(
res,
exp,
"\nexpected response not in write buffer:\n\
response: {:?}\n\
expected: {:?}",
String::from_utf8_lossy(r... |
rust_dataset_chunk_246 | rust_dataset.txt | 246 | 512 | ) without stalling.
for _ in 0..32 {
let data = vec![b'a'; 8192];
let mut chunk = BytesMut::new();
chunk.extend_from_slice(format!("{:x}\r\n", data.len()).as_bytes());
chunk.extend_from_slice(&data);
chunk.extend_from_slice(b"\r\n");
buf.extend_read_buf(chunk);
... |
rust_dataset_chunk_247 | rust_dataset.txt | 247 | 512 | _ref());
let disptacher = Dispatcher::new(
buf.clone(),
services,
ServiceConfig::default(),
None,
OnConnectData::default(),
);
let mut disptacher = pin!(disptacher);
assert!(disptacher.as_mut().poll(&mut cx).is_pending());
assert_eq!(disptacher.poll_count, 1)... |
rust_dataset_chunk_248 | rust_dataset.txt | 248 | 512 | ().poll(&mut cx).is_ready());
assert_eq!(disptacher.poll_count, 2);
let res = BytesMut::from(buf.take_write_buf().as_ref());
assert!(res.is_empty());
let DispatcherStateProj::Normal { inner } = disptacher.as_mut().project().inner.project()
else {
panic!("End dispatcher state should be Norm... |
rust_dataset_chunk_249 | rust_dataset.txt | 249 | 512 | s_zero() {
let _ = crate::config::ServiceConfigBuilder::new().h1_write_buffer_size(0);
}
const SIZED_BODY_LEN: usize = 64 * 1024;
fn sized_body() -> Bytes {
(0..SIZED_BODY_LEN).map(|i| i as u8).collect()
}
fn sized_body_service() -> impl Service<Request, Response = Response<Bytes>, Error = Error> {
fn_se... |
rust_dataset_chunk_250 | rust_dataset.txt | 250 | 512 | self.vectored
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_shutdown(cx)
... |
rust_dataset_chunk_251 | rust_dataset.txt | 251 | 512 | pin!(h1);
lazy(|cx| {
assert!(h1.as_mut().poll(cx).is_pending());
// without vectored writes the chunk is copied into the write buffer, as before
let DispatcherStateProj::Normal { inner } = h1.as_mut().project().inner.project()
else {
panic!("di... |
rust_dataset_chunk_252 | rust_dataset.txt | 252 | 512 | let res = buf.take_write_buf();
let head_end = find_slice(&res, b"\r\n\r\n", 0).expect("response head") + 4;
assert_eq!(res[head_end..], sized_body()[..32 * 1024]);
assert_eq!(writes.get(), 1);
})
.await;
}
fn http_msg(msg: impl AsRef<str>) -> BytesMut {
let mut msg = msg
.... |
rust_dataset_chunk_253 | rust_dataset.txt | 253 | 512 | ().to_owned();
let mut payload = req.take_payload();
while let Some(item) = payload.next().await {
if item.is_err() {
return Ok::<_, Error>(Response::bad_request());
}
}
... |
rust_dataset_chunk_254 | rust_dataset.txt | 254 | 512 | = 2;
const CRLF_LEN: usize = 2;
const HEADER_DELIMITER_LEN: usize = COLON_SPACE_LEN + CRLF_LEN;
const ASCII_TO_UPPERCASE_MASK: u8 = 0b1101_1111;
#[derive(Debug)]
pub(crate) struct MessageEncoder<T: MessageType> {
#[allow(dead_code)]
pub length: BodySize,
pub te: TransferEncoding,
_phantom: PhantomData... |
rust_dataset_chunk_255 | rust_dataset.txt | 255 | 512 | ::None;
}
_ => {}
}
}
match length {
BodySize::Stream => {
if chunked {
skip_len = true;
if camel_case {
dst.put_slice(b"\r\nTransfer-Encoding: chunked\r\n")
... |
rust_dataset_chunk_256 | rust_dataset.txt | 256 | 512 | _slice(b"Connection: close\r\n")
} else {
dst.put_slice(b"connection: close\r\n")
}
}
_ => {}
}
// write headers
let mut has_date = false;
let mut buf = dst.chunk_mut().as_mut_ptr();
let mut remaining ... |
rust_dataset_chunk_257 | rust_dataset.txt | 257 | 512 | += len;
remaining -= len;
}
});
// final cursor synchronization with the bytes container
//
// SAFETY: all the bytes written up to position "pos" are initialized
// the written byte count and pointer advancement are kept in sync
unsafe {
... |
rust_dataset_chunk_258 | rust_dataset.txt | 258 | 512 | ed()
}
fn camel_case(&self) -> bool {
self.as_ref().camel_case_headers()
}
fn headers(&self) -> &HeaderMap {
self.as_ref().headers()
}
fn extra_headers(&self) -> Option<&HeaderMap> {
self.extra_headers()
}
fn encode_status(&mut self, dst: &mut BytesMut) -> io:... |
rust_dataset_chunk_259 | rust_dataset.txt | 259 | 512 | : &mut BytesMut) -> io::Result<()> {
self.te.encode_eof(buf)
}
/// Encode message.
pub fn encode(
&mut self,
dst: &mut BytesMut,
message: &mut T,
head: bool,
stream: bool,
version: Version,
length: BodySize,
conn_type: ConnectionType,
... |
rust_dataset_chunk_260 | rust_dataset.txt | 260 | 512 | ///
/// For fixed-length bodies, writes at most the remaining content length and returns `true`
/// when that length is exhausted. For chunked and EOF-delimited bodies, an empty `msg`
/// signals the end of the body. Chunked encoding also writes the final chunk once.
pub(crate) fn encode(&mut self, ... |
rust_dataset_chunk_261 | rust_dataset.txt | 261 | 512 | /// Callers must ensure that the given `len` matches the given `value` length and that `buf` is
/// valid for writes of at least `len` bytes.
unsafe fn write_data(value: &[u8], buf: *mut u8, len: usize) {
debug_assert_eq!(value.len(), len);
copy_nonoverlapping(value.as_ptr(), buf, len);
}
/// # Safety
/// Call... |
rust_dataset_chunk_262 | rust_dataset.txt | 262 | 512 | ().freeze(),
Bytes::from_static(b"4\r\ntest\r\n0\r\n\r\n")
);
}
#[tokio::test(flavor = "local")]
async fn test_camel_case() {
let mut bytes = BytesMut::with_capacity(2048);
let mut head = RequestHead::default();
head.set_camel_case_headers(true);
head.hea... |
rust_dataset_chunk_263 | rust_dataset.txt | 263 | 512 | Value::from_static("plain/text"));
head.headers
.append(CONTENT_TYPE, HeaderValue::from_static("xml"));
let mut head = RequestHeadType::Owned(head);
let _ = head.encode_headers(
&mut bytes,
Version::HTTP_11,
BodySize::Stream,
Connectio... |
rust_dataset_chunk_264 | rust_dataset.txt | 264 | 512 | ,
Version::HTTP_11,
BodySize::Stream,
ConnectionType::Upgrade,
&ServiceConfig::default(),
);
let data = String::from_utf8(Vec::from(bytes.split().freeze().as_ref())).unwrap();
assert!(!data.contains("content-length: 0\r\n"));
assert!(!data.... |
rust_dataset_chunk_265 | rust_dataset.txt | 265 | 512 | .
Chunk(Option<Bytes>),
}
impl<T> From<T> for Message<T> {
fn from(item: T) -> Self {
Message::Item(item)
}
}
/// Incoming request type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageType {
None,
Payload,
Stream,
}
const LW: usize = 2 * 1024;
const HW: usize = 32 * 1024;... |
rust_dataset_chunk_266 | rust_dataset.txt | 266 | 512 | - `Payload` - *Receiver* side of the stream
pub fn create(eof: bool) -> (PayloadSender, Payload) {
let shared = Rc::new(RefCell::new(Inner::new(eof)));
(
PayloadSender::new(Rc::downgrade(&shared)),
Payload { inner: shared },
)
}
/// Creates an empty payload... |
rust_dataset_chunk_267 | rust_dataset.txt | 267 | 512 | we check need_read only if Payload (other side) is alive,
// otherwise always return true (consume payload)
if let Some(shared) = self.inner.upgrade() {
if shared.borrow().need_read {
PayloadStatus::Read
} else {
shared.borrow_mut().register_io(cx... |
rust_dataset_chunk_268 | rust_dataset.txt | 268 | 512 | ().will_wake(w))
{
self.io_task = Some(cx.waker().clone());
}
}
#[inline]
fn set_error(&mut self, err: PayloadError) {
self.sender_closed = true;
self.err = Some(err);
self.wake();
}
fn close_sender(&mut self) {
if !self.sender_closed {
... |
rust_dataset_chunk_269 | rust_dataset.txt | 269 | 512 | );
assert_impl_all!(Inner: Unpin, Send, Sync);
const WAKE_TIMEOUT: Duration = Duration::from_secs(2);
fn prepare_waking_test(
mut payload: Payload,
expected: Option<Result<(), ()>>,
) -> (oneshot::Receiver<()>, JoinHandle<()>) {
let (tx, rx) = oneshot::channel();
let ... |
rust_dataset_chunk_270 | rust_dataset.txt | 270 | 512 | handle) = prepare_waking_test(payload, Some(Err(())));
rx.await.unwrap();
drop(sender);
timeout(WAKE_TIMEOUT, handle).await.unwrap().unwrap();
}
#[tokio::test(flavor = "local")]
async fn test_unread_data() {
let (_, mut payload) = Payload::create(false);
payload.u... |
rust_dataset_chunk_271 | rust_dataset.txt | 271 | 512 | cfg: ServiceConfig,
service: F,
) -> Self {
H1Service {
cfg,
srv: service.into_factory(),
expect: ExpectHandler,
upgrade: None,
on_connect_ext: None,
_phantom: PhantomData,
}
}
}
impl<S, B, X, U> H1Service<T... |
rust_dataset_chunk_272 | rust_dataset.txt | 272 | 512 | ,
X::Error: Into<Response<BoxBody>>,
X::InitError: fmt::Debug,
U: ServiceFactory<
(Request, Framed<TlsStream<TcpStream>, Codec>),
Config = (),
Response = (),
>,
U::Future: 'static,
U::Error: fmt::Display + Into<Response<BoxBody>>,
... |
rust_dataset_chunk_273 | rust_dataset.txt | 273 | 512 | ,
{
/// Create Rustls v0.20 based service.
pub fn rustls(
self,
config: ServerConfig,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<io::Error, DispatchError>,
InitError = (... |
rust_dataset_chunk_274 | rust_dataset.txt | 274 | 512 | map_init_err(|_| {
unreachable!("TLS acceptor service factory does not error on init")
})
.map_err(TlsError::into_service_error)
.map(|io: TlsStream<TcpStream>| {
let peer_addr = io.get_ref().0.peer_addr().ok();
... |
rust_dataset_chunk_275 | rust_dataset.txt | 275 | 512 | _err(TlsError::Service))
}
}
}
#[cfg(feature = "rustls-0_23")]
mod rustls_0_23 {
use std::io;
use actix_tls::accept::{
rustls_0_23::{reexports::ServerConfig, Acceptor, TlsStream},
TlsError,
};
use super::*;
impl<S, B, X, U> H1Service<TlsStream<TcpStream>, S, B, X, U>
... |
rust_dataset_chunk_276 | rust_dataset.txt | 276 | 512 | ,
B: MessageBody,
{
pub fn expect<X1>(self, expect: X1) -> H1Service<T, S, B, X1, U>
where
X1: ServiceFactory<Request, Response = Request>,
X1::Error: Into<Response<BoxBody>>,
X1::InitError: fmt::Debug,
{
H1Service {
expect,
cfg: self.cfg,
... |
rust_dataset_chunk_277 | rust_dataset.txt | 277 | 512 | type Error = DispatchError;
type Config = ();
type Service = H1ServiceHandler<T, S::Service, B, X::Service, U::Service>;
type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future {
let service = self.srv... |
rust_dataset_chunk_278 | rust_dataset.txt | 278 | 512 | : &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self._poll_ready(cx).map_err(|err| {
error!("HTTP/1 service readiness error: {:?}", err);
DispatchError::Service(err)
})
}
fn call(&self, (io, addr): (T, Option<net::SocketAddr>)) -> Self::Future {
let conn_d... |
rust_dataset_chunk_279 | rust_dataset.txt | 279 | 512 | impl fmt::Display for TimerState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TimerState::Disabled => f.write_str("timer is disabled"),
TimerState::Inactive => f.write_str("timer is inactive"),
TimerState::Active { timer } => {
... |
rust_dataset_chunk_280 | rust_dataset.txt | 280 | 512 | <Message<(Response<()>, BodySize)>>,
#[pin]
body: Option<B>,
#[pin]
framed: Option<Framed<T, Codec>>,
}
}
impl<T, B> SendResponse<T, B>
where
B: MessageBody,
B::Error: Into<Error>,
{
pub fn new(framed: Framed<T, Codec>, response: Response<B>) -> Self {
let (res... |
rust_dataset_chunk_281 | rust_dataset.txt | 281 | 512 | }
}
let framed = this.framed.as_mut().as_pin_mut().unwrap();
// flush write buffer
if !framed.is_write_buf_empty() {
match framed
.flush(cx)
.map_err(|err| Error::new_send_response().with_cause(err))?
... |
rust_dataset_chunk_282 | rust_dataset.txt | 282 | 512 | Option<Rc<Extensions>>,
config: ServiceConfig,
peer_addr: Option<net::SocketAddr>,
ping_pong: Option<H2PingPong>,
graceful_shutdown: Option<GracefulShutdownFuture>,
_phantom: PhantomData<B>
}
}
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
where
T: AsyncRead + AsyncWrit... |
rust_dataset_chunk_283 | rust_dataset.txt | 283 | 512 | is waiting for a reply.
in_flight: bool,
/// Timeout for pong response.
timer: Pin<Box<Sleep>>,
}
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Response<BoxBody>>,
S::Future: 'static,
S::Response:... |
rust_dataset_chunk_284 | rust_dataset.txt | 284 | 512 | }");
}
}
}
});
}
Poll::Ready(None) => return Poll::Ready(Ok(())),
Poll::Pending => match this.ping_pong.as_mut() {
Some(ping_pong) => loop {
... |
rust_dataset_chunk_285 | rust_dataset.txt | 285 | 512 | let mut body = pin!(body);
// poll response body and send chunks to client
while let Some(res) = poll_fn(|cx| body.as_mut().poll_next(cx)).await {
let mut chunk = res.map_err(|err| DispatchError::ResponseBody(err.into()))?;
'send: loop {
let chunk_size = cmp::min(chunk.len(), CHUN... |
rust_dataset_chunk_286 | rust_dataset.txt | 286 | 512 | from_static("0");
res.headers_mut().insert(CONTENT_LENGTH, HV_ZERO);
}
BodySize::Sized(len) => {
let mut buf = itoa::Buffer::new();
res.headers_mut().insert(
CONTENT_LENGTH,
HeaderValue::from_str(buf.format(*len)).unwrap(),
... |
rust_dataset_chunk_287 | rust_dataset.txt | 287 | 512 | ) -> Self {
Self { stream }
}
}
impl Stream for Payload {
type Item = Result<Bytes, PayloadError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
match ready!(Pin::new(&mut this.stream).poll_data(cx)) {
... |
rust_dataset_chunk_288 | rust_dataset.txt | 288 | 512 | ))
}
None => Poll::Pending,
},
}
}
}
#[cfg(test)]
mod tests {
use static_assertions::assert_impl_all;
use super::*;
assert_impl_all!(Payload: Unpin, Send, Sync);
}
--- FILE: actix-web/actix-http/src/h2/service.rs ---
use std::{
future::Future,... |
rust_dataset_chunk_289 | rust_dataset.txt | 289 | 512 | H2Service {
cfg,
on_connect_ext: None,
srv: service.into_factory(),
_phantom: PhantomData,
}
}
/// Set on connect callback.
pub(crate) fn on_connect_ext(mut self, f: Option<Rc<ConnectCallback<T>>>) -> Self {
self.on_connect_ext = f;
s... |
rust_dataset_chunk_290 | rust_dataset.txt | 290 | 512 | fn openssl(
self,
acceptor: SslAcceptor,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<SslError, DispatchError>,
InitError = S::InitError,
> {
let tcp_nodelay = desired_no... |
rust_dataset_chunk_291 | rust_dataset.txt | 291 | 512 | TLS acceptor service factory does not error on init")
})
.map_err(TlsError::into_service_error)
.map(move |io: TlsStream<TcpStream>| {
if let Some(nodelay) = tcp_nodelay {
set_nodelay(io.get_ref().0, nodelay);
... |
rust_dataset_chunk_292 | rust_dataset.txt | 292 | 512 | io, peer_addr)
})
.and_then(self.map_err(TlsError::Service))
}
}
}
#[cfg(feature = "rustls-0_22")]
mod rustls_0_22 {
use std::io;
use actix_tls::accept::{
rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream},
TlsError,
};
use super::*... |
rust_dataset_chunk_293 | rust_dataset.txt | 293 | 512 | };
use super::*;
impl<S, B> H2Service<TlsStream<TcpStream>, S, B>
where
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Response<BoxBody>> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'st... |
rust_dataset_chunk_294 | rust_dataset.txt | 294 | 512 | ::Service, B>;
type InitError = S::InitError;
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future {
let service = self.srv.new_service(());
let cfg = self.cfg.clone();
let on_connect_ext = self.on_connect_ext.cl... |
rust_dataset_chunk_295 | rust_dataset.txt | 295 | 512 | error!("Service readiness error: {:?}", err);
DispatchError::Service(err)
})
}
fn call(&self, (io, addr): (T, Option<net::SocketAddr>)) -> Self::Future {
let on_connect_data = OnConnectData::from_io(&io, self.on_connect_ext.as_deref());
H2ServiceHandlerResponse ... |
rust_dataset_chunk_296 | rust_dataset.txt | 296 | 512 | Established(Dispatcher::new(
conn,
srv.take().unwrap(),
config.take().unwrap(),
*peer_addr,
on_connect_data,
timer,
));
self.poll(cx)
... |
rust_dataset_chunk_297 | rust_dataset.txt | 297 | 512 | }
impl AsHeaderName for &String {}
--- FILE: actix-web/actix-http/src/header/common.rs ---
//! Common header names not defined in [`http`].
//!
//! Any headers added to this file will need to be re-exported from the list at `crate::headers`.
use http::header::HeaderName;
/// Response header field that indicates how... |
rust_dataset_chunk_298 | rust_dataset.txt | 298 | 512 | : HeaderName =
HeaderName::from_static("cross-origin-resource-policy");
/// Response header that provides a mechanism to allow and deny the use of browser features in a
/// document or within any `<iframe>` elements in the document.
pub const PERMISSIONS_POLICY: HeaderName = HeaderName::from_static("permissions-po... |
rust_dataset_chunk_299 | rust_dataset.txt | 299 | 512 | , value) = self;
let value = value
.try_into_value()
.map_err(|err| InvalidHeaderPart::Value(err.into()))?;
Ok((name, value))
}
}
impl<V> TryIntoHeaderPair for (&HeaderName, V)
where
V: TryIntoHeaderValue,
V::Error: Into<InvalidHeaderValue>,
{
type Error = Invali... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.