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_300 | rust_dataset.txt | 300 | 512 | Header> TryIntoHeaderPair for T {
type Error = <T as TryIntoHeaderValue>::Error;
#[inline]
fn try_into_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
Ok((T::name(), self.try_into_value()?))
}
}
--- FILE: actix-web/actix-http/src/header/into_value.rs ---
//! [`TryIntoHeaderVal... |
rust_dataset_chunk_301 | rust_dataset.txt | 301 | 512 | impl TryIntoHeaderValue for usize {
type Error = InvalidHeaderValue;
#[inline]
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
HeaderValue::try_from(self.to_string())
}
}
impl TryIntoHeaderValue for i64 {
type Error = InvalidHeaderValue;
#[inline]
fn try_into_value(s... |
rust_dataset_chunk_302 | rust_dataset.txt | 302 | 512 | .remove(header::ORIGIN);
/// assert_eq!(removed.next().unwrap(), "example.com");
///
/// assert!(!map.contains_key(header::ORIGIN));
/// ```
///
/// Construct a header map using the [`FromIterator`] implementation. Note that it uses the append
/// strategy, so duplicate header names are preserved.
///
/// ```
/// use a... |
rust_dataset_chunk_303 | rust_dataset.txt | 303 | 512 | 0, the map will be created without allocating.
///
/// # Examples
/// ```
/// # use actix_http::header::HeaderMap;
/// let map = HeaderMap::with_capacity(16);
///
/// assert!(map.is_empty());
/// assert!(map.capacity() >= 16);
/// ```
pub fn with_capacity(capacity: usize) -> Self... |
rust_dataset_chunk_304 | rust_dataset.txt | 304 | 512 | /// Returns the number of _keys_ stored in the map.
///
/// The number of values stored will be at least this number. See also: [`Self::len`].
///
/// # Examples
/// ```
/// # use actix_http::header::{self, HeaderMap, HeaderValue};
/// let mut map = HeaderMap::new();
/// assert_eq!(m... |
rust_dataset_chunk_305 | rust_dataset.txt | 305 | 512 | name),
}
}
/// Returns a reference to the _first_ value associated with a header name.
///
/// Returns `None` if there is no value associated with the key.
///
/// Even when multiple values are associated with the key, the "first" one is returned but is
/// not guaranteed to be chos... |
rust_dataset_chunk_306 | rust_dataset.txt | 306 | 512 | , HeaderValue::from_static("one=1"));
///
/// let mut cookie = map.get_mut(header::SET_COOKIE).unwrap();
/// assert_eq!(cookie, "one=1");
///
/// *cookie = HeaderValue::from_static("three=3");
/// assert_eq!(map.get(header::SET_COOKIE).unwrap(), "three=3");
///
/// assert!(map.get(header... |
rust_dataset_chunk_307 | rust_dataset.txt | 307 | 512 | header names will simply return false.
///
/// # Examples
/// ```
/// # use actix_http::header::{self, HeaderMap, HeaderValue};
/// let mut map = HeaderMap::new();
/// assert!(!map.contains_key(header::ACCEPT));
///
/// map.insert(header::ACCEPT, HeaderValue::from_static("text/plain"));... |
rust_dataset_chunk_308 | rust_dataset.txt | 308 | 512 | , name: HeaderName, val: HeaderValue) -> Removed {
let value = self.inner.insert(name, Value::one(val));
Removed::new(value)
}
/// Appends a name-value pair to the map.
///
/// If the map already contained this key, the new value is added to the list of values
/// currently associat... |
rust_dataset_chunk_309 | rust_dataset.txt | 309 | 512 | ///
/// A convenience method is provided on the returned iterator to check if the `remove` call
/// actually removed any values.
/// ```
/// # use actix_http::header::{self, HeaderMap, HeaderValue};
/// let mut map = HeaderMap::new();
///
/// let removed = map.remove("accept");
/// asse... |
rust_dataset_chunk_310 | rust_dataset.txt | 310 | 512 | !(map.capacity() >= 102);
///
/// assert!(map.is_empty());
/// ```
pub fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional)
}
/// An iterator over all name-value pairs.
///
/// Names will be yielded for each associated value. So, if a key has 3 associated va... |
rust_dataset_chunk_311 | rust_dataset.txt | 311 | 512 | =1"));
/// map.append(header::SET_COOKIE, HeaderValue::from_static("two=2"));
///
/// let keys = map.keys().cloned().collect::<Vec<_>>();
/// assert_eq!(keys.len(), 2);
/// assert!(keys.contains(&header::HOST));
/// assert!(keys.contains(&header::SET_COOKIE));
/// ```
pub fn keys(&self) ... |
rust_dataset_chunk_312 | rust_dataset.txt | 312 | 512 | mut iter = map.drain();
/// assert!(iter.next().is_none());
/// drop(iter);
///
/// map.append(header::SET_COOKIE, HeaderValue::from_static("one=1"));
/// map.append(header::SET_COOKIE, HeaderValue::from_static("two=2"));
///
/// let mut iter = map.drain();
/// assert_eq!(iter.next().un... |
rust_dataset_chunk_313 | rust_dataset.txt | 313 | 512 | from_iter(map)
}
}
/// Convert our `&HeaderMap` to a `http::HeaderMap`.
impl From<&HeaderMap> for http::HeaderMap {
fn from(map: &HeaderMap) -> Self {
map.to_owned().into()
}
}
/// Iterator over removed, owned values with the same associated name.
///
/// Returned from methods that remove or repla... |
rust_dataset_chunk_314 | rust_dataset.txt | 314 | 512 | Iter<'a> {
inner: hash_map::Iter<'a, HeaderName, Value>,
multi_inner: Option<(&'a HeaderName, &'a SmallVec<[HeaderValue; 4]>)>,
multi_idx: usize,
remaining: usize,
}
impl<'a> Iter<'a> {
fn new(iter: hash_map::Iter<'a, HeaderName, Value>, remaining: usize) -> Self {
Self {
inner... |
rust_dataset_chunk_315 | rust_dataset.txt | 315 | 512 | type Item = (Option<HeaderName>, HeaderValue);
fn next(&mut self) -> Option<Self::Item> {
// handle in-progress multi value iterators first
if let Some((ref mut name, ref mut vals)) = self.multi_inner {
if !vals.is_empty() {
// OPTIMIZE: array removals
... |
rust_dataset_chunk_316 | rust_dataset.txt | 316 | 512 | (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
impl ExactSizeIterator for IntoIter {}
impl iter::FusedIterator for IntoIter {}
#[cfg(test)]
mod tests {
use std::iter::FusedIterator;
use http::header;
use static_assertions::assert_impl_all;
use super::*;
assert... |
rust_dataset_chunk_317 | rust_dataset.txt | 317 | 512 | removed = map.remove(header::ACCEPT);
assert_eq!(removed.len(), 0);
assert_eq!(removed.size_hint(), (0, Some(0)));
assert!(removed.next().is_none());
assert_eq!(removed.len(), 0);
assert_eq!(removed.size_hint(), (0, Some(0)));
}
#[test]
fn contains() {
let ... |
rust_dataset_chunk_318 | rust_dataset.txt | 318 | 512 | ());
drop(iter);
assert!(map.is_empty());
}
#[test]
fn retain() {
let mut map = HeaderMap::new();
map.append(header::LOCATION, HeaderValue::from_static("/test"));
map.append(header::HOST, HeaderValue::from_static("duck.com"));
map.append(header::COOKIE, Hea... |
rust_dataset_chunk_319 | rust_dataset.txt | 319 | 512 | }
#[test]
fn iter_and_into_iter_same_order() {
let mut map = HeaderMap::new();
map.append(header::HOST, HeaderValue::from_static("duck.com"));
map.append(header::COOKIE, HeaderValue::from_static("one=1"));
map.append(header::COOKIE, HeaderValue::from_static("two=2"));
... |
rust_dataset_chunk_320 | rust_dataset.txt | 320 | 512 | _eq!(vals.next().unwrap().as_bytes(), b"1");
assert_eq!(vals.next().unwrap().as_bytes(), b"2");
assert_eq!(vals.next().unwrap().as_bytes(), b"3");
assert_eq!(vals.next().unwrap().as_bytes(), b"4");
assert_eq!(vals.next().unwrap().as_bytes(), b"5");
assert!(vals.next().is_none());... |
rust_dataset_chunk_321 | rust_dataset.txt | 321 | 512 | #[test]
fn drain_len_counts_values() {
let mut map = HeaderMap::new();
map.append(header::SET_COOKIE, HeaderValue::from_static("a=1"));
map.append(header::SET_COOKIE, HeaderValue::from_static("b=2"));
map.append(header::SET_COOKIE, HeaderValue::from_static("c=3"));
let mut ... |
rust_dataset_chunk_322 | rust_dataset.txt | 322 | 512 | SEC_WEBSOCKET_EXTENSIONS,
SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_PROTOCOL, SEC_WEBSOCKET_VERSION, SERVER, SET_COOKIE,
STRICT_TRANSPORT_SECURITY, TE, TRAILER, TRANSFER_ENCODING, UPGRADE, UPGRADE_INSECURE_REQUESTS,
USER_AGENT, VARY, VIA, WARNING, WWW_AUTHENTICATE, X_CONTENT_TYPE_OPTIONS,
X_DNS_PREFETCH_CONTROL... |
rust_dataset_chunk_323 | rust_dataset.txt | 323 | 512 | .add(b'-')
.add(b'>')
.add(b'?')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'{')
.add(b'}');
--- FILE: actix-web/actix-http/src/header/shared/charset.rs ---
use std::{fmt, str};
/// A MIME character set.
///
/// The string representation is normalized to upper case.
///
/// See <http://w... |
rust_dataset_chunk_324 | rust_dataset.txt | 324 | 512 | Koi8_R,
/// An arbitrary charset specified as a string.
Ext(String),
}
impl Charset {
fn label(&self) -> &str {
use Charset::*;
match *self {
Us_Ascii => "US-ASCII",
Iso_8859_1 => "ISO-8859-1",
Iso_8859_2 => "ISO-8859-2",
Iso_8859_3 => "... |
rust_dataset_chunk_325 | rust_dataset.txt | 325 | 512 | -ASCII") => Us_Ascii,
_ if cs.eq_ignore_ascii_case("ISO-8859-1") => Iso_8859_1,
_ if cs.eq_ignore_ascii_case("ISO-8859-2") => Iso_8859_2,
_ if cs.eq_ignore_ascii_case("ISO-8859-3") => Iso_8859_3,
_ if cs.eq_ignore_ascii_case("ISO-8859-4") => Iso_8859_4,
_ if c... |
rust_dataset_chunk_326 | rust_dataset.txt | 326 | 512 | _ascii_case("BIG5") => Big5,
_ if cs.eq_ignore_ascii_case("KOI8-R") => Koi8_R,
_ => Ext(cs.to_ascii_uppercase()),
})
}
}
#[cfg(test)]
mod tests {
use super::Charset::*;
#[test]
fn test_parse() {
assert_eq!(Us_Ascii, "us-ascii".parse().unwrap());
assert_e... |
rust_dataset_chunk_327 | rust_dataset.txt | 327 | 512 | late,
/// Gzip algorithm.
Gzip,
/// Zstd algorithm.
Zstd,
}
impl ContentEncoding {
/// Convert content encoding to string.
#[inline]
pub const fn as_str(self) -> &'static str {
match self {
ContentEncoding::Brotli => "br",
ContentEncoding::Gzip => "gzip",
... |
rust_dataset_chunk_328 | rust_dataset.txt | 328 | 512 | () -> HeaderName {
header::CONTENT_ENCODING
}
fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError> {
from_one_raw_str(msg.headers().get(Self::name()))
}
}
--- FILE: actix-web/actix-http/src/header/shared/extended.rs ---
//! Originally taken from `hyper::header::parsing`.
use std... |
rust_dataset_chunk_329 | rust_dataset.txt | 329 | 512 | quote is not included
/// ; SHOULD be registered in the IANA charset registry
///
/// language = <Language-Tag, defined in [RFC 5646 §2.1]>
///
/// value-chars = *( pct-encoded / attr-char )
///
/// pct-encoded = "%" HEXDIG HEXDIG
/// ; see [RFC 3986 §2.1]
///
/// attr-char = A... |
rust_dataset_chunk_330 | rust_dataset.txt | 330 | 512 | ExtendedValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let encoded_value = percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
if let Some(ref lang) = self.language_tag {
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
} else {
... |
rust_dataset_chunk_331 | rust_dataset.txt | 331 | 512 | From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2
let result = parse_extended_value("foo%20bar.html");
assert!(result.is_err());
}
#[test]
fn test_parse_extended_value_partially_formatted() {
let result = parse_extended_value("UTF-8'missing third part");
assert!(r... |
rust_dataset_chunk_332 | rust_dataset.txt | 332 | 512 | , ParseError> {
match httpdate::parse_http_date(s) {
Ok(sys_time) => Ok(HttpDate(sys_time)),
Err(_) => Err(ParseError::Header),
}
}
}
impl fmt::Display for HttpDate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
httpdate::HttpDate::from(self.0).fmt(... |
rust_dataset_chunk_333 | rust_dataset.txt | 333 | 512 | Tag;
mod charset;
mod content_encoding;
mod extended;
mod http_date;
mod quality;
mod quality_item;
pub use self::{
charset::Charset,
content_encoding::ContentEncoding,
extended::{parse_extended_value, ExtendedValue},
http_date::HttpDate,
quality::{q, Quality},
quality_item::QualityItem,
};
... |
rust_dataset_chunk_334 | rust_dataset.txt | 334 | 512 | quality: Quality,
}
impl<T> QualityItem<T> {
/// Constructs a new `QualityItem` from an item and a quality value.
///
/// The item can be of any type. The quality should be a value in the range [0, 1].
pub fn new(item: T, quality: Quality) -> Self {
QualityItem { item, quality }
}
///... |
rust_dataset_chunk_335 | rust_dataset.txt | 335 | 512 | ::once(b';')).enumerate() {
if escaped {
// skip escaped char
escaped = false;
continue;
}
match byte {
b'\\' if quoted => escaped = true,
b'"' => quoted = !quoted,
b';' if !quoted => {... |
rust_dataset_chunk_336 | rust_dataset.txt | 336 | 512 | }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quality_parameter_position() {
for input in [
"text/plain; q=0.2; charset=utf-8; format=flowed",
"text/plain; charset=utf-8; Q=0.2; format=flowed",
"text/plain; charset=utf-8; format=flowed; q=0.2",
... |
rust_dataset_chunk_337 | rust_dataset.txt | 337 | 512 | (), "{input}");
}
}
#[test]
fn invalid_quality_not_last() {
for quality in ["2", "invalid", "0.2739999", "NaN", "", "-1"] {
for input in [
format!("text/plain; q={quality}; charset=utf-8"),
format!("text/plain; charset=utf-8; Q={quality}; format=f... |
rust_dataset_chunk_338 | rust_dataset.txt | 338 | 512 | Formatter<'_>) -> fmt::Result {
use Encoding::*;
f.write_str(match *self {
Chunked => "chunked",
Brotli => "br",
Gzip => "gzip",
Deflate => "deflate",
Compress => "compress",
Identity => "identity",
... |
rust_dataset_chunk_339 | rust_dataset.txt | 339 | 512 | ::<QualityItem<Encoding>>().unwrap();
assert_eq!(
x,
QualityItem {
item: Encoding::Chunked,
quality: Quality(1000),
}
);
}
#[test]
fn test_quality_item_from_str3() {
let x = "gzip; q=0.5".parse::<QualityItem<Encodi... |
rust_dataset_chunk_340 | rust_dataset.txt | 340 | 512 | ("0.10", Quality(100)),
("0.100", Quality(100)),
("0.999", Quality(999)),
("1", Quality::MAX),
("1.", Quality::MAX),
("1.0", Quality::MAX),
("1.00", Quality::MAX),
("1.000", Quality::MAX),
] {
let input = format!("g... |
rust_dataset_chunk_341 | rust_dataset.txt | 341 | 512 | 7231 §5.3.1] gives more information on quality values in HTTP header fields.
///
/// # Examples
/// ```
/// use actix_http::header::{Quality, q};
/// assert_eq!(q(1.0), Quality::MAX);
///
/// assert_eq!(q(0.42).to_string(), "0.42");
/// assert_eq!(q(1.0).to_string(), "1");
/// assert_eq!(Quality::MIN.to_string(), "0.0... |
rust_dataset_chunk_342 | rust_dataset.txt | 342 | 512 | Result {
match self.0 {
0 => f.write_str("0"),
MAX_QUALITY_INT => f.write_str("1"),
// some number in the range 1–999
x => {
f.write_str("0.")?;
// This implementation avoids string allocation for removing trailing zeroes.
... |
rust_dataset_chunk_343 | rust_dataset.txt | 343 | 512 | } else {
Err(QualityOutOfBounds)
}
}
}
/// Convenience function to create a [`Quality`] from an `f32` (0.0–1.0).
///
/// Not recommended for use with user input. Rely on the `TryFrom` impls where possible.
///
/// # Panics
/// Panics if value is out of range.
///
/// # Examples
/// ```
... |
rust_dataset_chunk_344 | rust_dataset.txt | 344 | 512 | !(Quality::MIN.to_string(), "0.001");
assert_eq!(Quality::MAX.to_string(), "1");
assert_eq!(q(0.0).to_string(), "0");
assert_eq!(q(1.0).to_string(), "1");
assert_eq!(q(0.001).to_string(), "0.001");
assert_eq!(q(0.5).to_string(), "0.5");
assert_eq!(q(0.22).to_string(), "0... |
rust_dataset_chunk_345 | rust_dataset.txt | 345 | 512 | );
let mut result = Vec::with_capacity(size_guess);
for h in all {
let s = h.to_str().map_err(|_| ParseError::Header)?;
result.extend(
split_list_elements(s)
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y),
... |
rust_dataset_chunk_346 | rust_dataset.txt | 346 | 512 | ")?;
fmt::Display::fmt(part, f)?;
}
Ok(())
}
/// Percent encode a sequence of bytes with a character set defined in [RFC 5987 §3.2].
///
/// [RFC 5987 §3.2]: https://datatracker.ietf.org/doc/html/rfc5987#section-3.2
#[inline]
pub fn http_percent_encode(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt... |
rust_dataset_chunk_347 | rust_dataset.txt | 347 | 512 | res, [r#"a="x\", y""#, "b"]);
}
}
--- FILE: actix-web/actix-http/src/helpers.rs ---
use std::io;
use bytes::BufMut;
use http::Version;
const DIGITS_START: u8 = b'0';
pub(crate) fn write_status_line<B: BufMut>(version: Version, n: u16, buf: &mut B) {
match version {
Version::HTTP_11 => buf.put_slice... |
rust_dataset_chunk_348 | rust_dataset.txt | 348 | 512 | does not
/// perform a remaining length check before writing.
pub(crate) struct MutWriter<'a, B>(pub(crate) &'a mut B);
impl<B> io::Write for MutWriter<'_, B>
where
B: BufMut,
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.put_slice(buf);
Ok(buf.len())
}
fn flush(&mut... |
rust_dataset_chunk_349 | rust_dataset.txt | 349 | 512 | bytes.reserve(50);
write_content_length(100, &mut bytes, false);
assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 100\r\n"[..]);
bytes.reserve(50);
write_content_length(101, &mut bytes, false);
assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 101\r\n"[..])... |
rust_dataset_chunk_350 | rust_dataset.txt | 350 | 512 | b"\r\ncontent-length: 999999\r\n"[..]
);
bytes.reserve(50);
write_content_length(5909471, &mut bytes, false);
assert_eq!(
bytes.split().freeze(),
b"\r\ncontent-length: 5909471\r\n"[..]
);
bytes.reserve(50);
write_content_length(... |
rust_dataset_chunk_351 | rust_dataset.txt | 351 | 512 | : Sized,
{
if self.headers().contains_key(H::name()) {
H::parse(self).ok()
} else {
None
}
}
/// Read the request content type. If request did not contain a *Content-Type* header, an empty
/// string is returned.
fn content_type(&self) -> &str {
... |
rust_dataset_chunk_352 | rust_dataset.txt | 352 | 512 | mut T
where
T: HttpMessage,
{
type Stream = T::Stream;
fn headers(&self) -> &HeaderMap {
(**self).headers()
}
/// Message payload stream
fn take_payload(&mut self) -> Payload<Self::Stream> {
(**self).take_payload()
}
/// Request's extensions container
fn extensions... |
rust_dataset_chunk_353 | rust_dataset.txt | 353 | 512 | ());
}
#[test]
fn test_encoding() {
let req = TestRequest::default().finish();
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
let req = TestRequest::default()
.insert_header(("content-type", "application/json"))
.finish();
assert_eq!(UTF_8... |
rust_dataset_chunk_354 | rust_dataset.txt | 354 | 512 | ();
assert!(req.chunked().is_err());
}
}
--- FILE: actix-web/actix-http/src/keep_alive.rs ---
use std::time::Duration;
/// Connection keep-alive config.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeepAlive {
/// Keep-alive duration.
///
/// `KeepAlive::Timeout(Duration::ZERO)` is m... |
rust_dataset_chunk_355 | rust_dataset.txt | 355 | 512 | : KeepAlive = None.into();
assert_eq!(test, KeepAlive::Disabled);
}
}
--- FILE: actix-web/actix-http/src/lib.rs ---
//! HTTP types and services for the Actix ecosystem.
//!
//! ## Crate Features
//!
//! | Feature | Functionality |
//! | ------------------- | -----... |
rust_dataset_chunk_356 | rust_dataset.txt | 356 | 512 | _drop;
mod payload;
mod requests;
mod responses;
mod service;
pub mod test;
#[cfg(feature = "ws")]
pub mod ws;
#[allow(deprecated)]
pub use self::payload::PayloadStream;
#[cfg(feature = "__tls")]
pub use self::service::TlsAcceptorConfig;
pub use self::{
builder::HttpServiceBuilder,
config::{ServiceConfig, Serv... |
rust_dataset_chunk_357 | rust_dataset.txt | 357 | 512 | = 0b0000_0100;
const EXPECT = 0b0000_1000;
const NO_CHUNKING = 0b0001_0000;
const CAMEL_CASE = 0b0010_0000;
}
}
#[doc(hidden)]
pub trait Head: Default + 'static {
fn clear(&mut self);
fn with_pool<F, R>(f: F) -> R
where
F: FnOnce(&MessagePool<Self>) -> R;
}
... |
rust_dataset_chunk_358 | rust_dataset.txt | 358 | 512 | head: Rc::new(T::default()),
}
}
}
#[inline]
/// Release message instance
fn release(&self, msg: Rc<T>) {
let pool = &mut self.0.borrow_mut();
if pool.len() < 128 {
pool.push(msg);
}
}
}
--- FILE: actix-web/actix-http/src/not... |
rust_dataset_chunk_359 | rust_dataset.txt | 359 | 512 | Stream`.")]
pub type PayloadStream = BoxedPayloadStream;
#[cfg(not(feature = "http2"))]
pin_project! {
/// A streaming payload.
#[project = PayloadProj]
pub enum Payload<S = BoxedPayloadStream> {
None,
H1 { payload: crate::h1::Payload },
Stream { #[pin] payload: S },
}
}
#[cfg(... |
rust_dataset_chunk_360 | rust_dataset.txt | 360 | 512 | , Payload::None)
}
}
impl<S> Stream for Payload<S>
where
S: Stream<Item = Result<Bytes, PayloadError>>,
{
type Item = Result<Bytes, PayloadError>;
#[inline]
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.project() {
PayloadProj... |
rust_dataset_chunk_361 | rust_dataset.txt | 361 | 512 | message headers.
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
/// Mutable reference to the message headers.
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.headers
}
/// Returns whether headers should be sent in Camel-Case.
///
/// Default is `fals... |
rust_dataset_chunk_362 | rust_dataset.txt | 362 | 512 | (Flags::NO_CHUNKING)
}
#[inline]
pub fn no_chunking(&mut self, val: bool) {
if val {
self.flags.insert(Flags::NO_CHUNKING);
} else {
self.flags.remove(Flags::NO_CHUNKING);
}
}
/// Request contains `EXPECT` header.
#[inline]
pub fn expect(&sel... |
rust_dataset_chunk_363 | rust_dataset.txt | 363 | 512 | <P> {
type Stream = P;
#[inline]
fn headers(&self) -> &HeaderMap {
&self.head().headers
}
fn take_payload(&mut self) -> Payload<P> {
mem::replace(&mut self.payload, Payload::None)
}
#[inline]
fn extensions(&self) -> Ref<'_, Extensions> {
self.extensions.borrow(... |
rust_dataset_chunk_364 | rust_dataset.txt | 364 | 512 |
pub fn head(&self) -> &RequestHead {
&self.head
}
#[inline]
#[doc(hidden)]
/// Mutable reference to a HTTP message part of the request
pub fn head_mut(&mut self) -> &mut RequestHead {
&mut self.head
}
/// Mutable reference to the message's headers.
pub fn headers_m... |
rust_dataset_chunk_365 | rust_dataset.txt | 365 | 512 | eref()
.and_then(|container| container.get::<T>())
}
/// Returns the connection-level data/extensions container if an [on-connect] callback was
/// registered, leaving an empty one in its place.
///
/// [on-connect]: crate::HttpServiceBuilder::on_connect_ext
pub fn take_conn_data(&m... |
rust_dataset_chunk_366 | rust_dataset.txt | 366 | 512 | ConnectionType, Extensions, Response, StatusCode,
};
/// An HTTP response builder.
///
/// Used to construct an instance of `Response` using a builder pattern. Response builders are often
/// created using [`Response::build`].
///
/// # Examples
/// ```
/// use actix_http::{Response, ResponseBuilder, StatusCode, body... |
rust_dataset_chunk_367 | rust_dataset.txt | 367 | 512 | actix_http::{ResponseBuilder, header};
///
/// let res = ResponseBuilder::default()
/// .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
/// .insert_header(("X-TEST", "value"))
/// .finish();
///
/// assert!(res.headers().contains_key("content-type"));
/// asse... |
rust_dataset_chunk_368 | rust_dataset.txt | 368 | 512 | type to `Upgrade`.
#[inline]
pub fn upgrade<V>(&mut self, value: V) -> &mut Self
where
V: TryIntoHeaderValue,
{
if let Some(parts) = self.inner() {
parts.set_connection_type(ConnectionType::Upgrade);
}
if let Ok(value) = value.try_into_value() {
... |
rust_dataset_chunk_369 | rust_dataset.txt | 369 | 512 | ) = self.err.take() {
return Err(Error::new_http().with_cause(err));
}
let head = self.head.take().expect("Cannot reuse response builder");
Ok(Response {
head,
body,
extensions: RefCell::new(Extensions::new()),
})
}
/// Generate ... |
rust_dataset_chunk_370 | rust_dataset.txt | 370 | 512 | writeln!(f, " headers:");
for (key, val) in head.headers.iter() {
let _ = writeln!(f, " {:?}: {:?}", key, val);
}
res
}
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
use super::*;
use crate::header::{HeaderName, HeaderValue, CONTENT_TYPE};
#[test]
fn te... |
rust_dataset_chunk_371 | rust_dataset.txt | 371 | 512 | (("Content-Type", "application/octet-stream"));
let res = res.finish();
assert_eq!(
res.headers().get("Content-Type"),
Some(&HeaderValue::from_static("application/octet-stream"))
);
}
#[test]
fn response_builder_header_insert_typed() {
let mut res = ... |
rust_dataset_chunk_372 | rust_dataset.txt | 372 | 512 | `ResponseHead` type
#[inline]
pub fn new(status: StatusCode) -> ResponseHead {
ResponseHead {
status,
version: Version::HTTP_11,
headers: HeaderMap::with_capacity(12),
reason: None,
flags: Flags::empty(),
}
}
/// Read the mess... |
rust_dataset_chunk_373 | rust_dataset.txt | 373 | 512 | reason(&self) -> &str {
self.reason.unwrap_or_else(|| {
self.status
.canonical_reason()
.unwrap_or("<unknown status code>")
})
}
#[inline]
pub(crate) fn conn_type(&self) -> Option<ConnectionType> {
if self.flags.contains(Flags::CLOSE) {
... |
rust_dataset_chunk_374 | rust_dataset.txt | 374 | 512 | BoxedResponseHead {
if let Some(mut head) = self.0.borrow_mut().pop() {
head.reason = None;
head.status = status;
head.headers.clear();
head.flags = Flags::empty();
BoxedResponseHead { head: Some(head) }
} else {
BoxedResponseHead ... |
rust_dataset_chunk_375 | rust_dataset.txt | 375 | 512 | assert!(memmem::find(&data, b"Content-Length").is_some());
assert!(memmem::find(&data, b"content-length").is_none());
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
stream
.write_all(b"GET /lower HTTP/1.1\r\nHost: localhost\r\nConnection: Close\r\n\r\n")
... |
rust_dataset_chunk_376 | rust_dataset.txt | 376 | 512 | Body::new(()),
extensions: RefCell::new(Extensions::new()),
}
}
/// Constructs a new response builder.
#[inline]
pub fn build(status: StatusCode) -> ResponseBuilder {
ResponseBuilder::new(status)
}
// just a couple frequently used shortcuts
// this list should n... |
rust_dataset_chunk_377 | rust_dataset.txt | 377 | 512 | {
&mut self.head.headers
}
/// Returns true if connection upgrade is enabled.
#[inline]
pub fn upgrade(&self) -> bool {
self.head.upgrade()
}
/// Returns true if keep-alive is enabled.
#[inline]
pub fn keep_alive(&self) -> bool {
self.head.keep_alive()
}
... |
rust_dataset_chunk_378 | rust_dataset.txt | 378 | 512 | body = f(&mut self.head, self.body);
Response {
head: self.head,
body,
extensions: self.extensions,
}
}
/// Map the current body to a type-erased `BoxBody`.
#[inline]
pub fn map_into_boxed_body(self) -> Response<BoxBody>
where
B: Message... |
rust_dataset_chunk_379 | rust_dataset.txt | 379 | 512 | .try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
}
}
impl From<&'static [u8]> for Response<&'static [u8]> {
fn from(val: &'static [u8]) -> Self {
let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::APPLICATION_OCTET_STREA... |
rust_dataset_chunk_380 | rust_dataset.txt | 380 | 512 | let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
}
}
impl From<ByteString> for Response<ByteString> {
fn from(val: ByteString) -> Self {
let mut... |
rust_dataset_chunk_381 | rust_dataset.txt | 381 | 512 | .unwrap(), &b"test"[..]);
let res = Response::from("test".to_owned());
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(
res.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
assert_eq!(res.status(), Status... |
rust_dataset_chunk_382 | rust_dataset.txt | 382 | 512 | ::HttpServiceBuilder,
error::DispatchError,
h1, ConnectCallback, OnConnectData, Protocol, Request, Response, ServiceConfig,
};
#[inline]
fn desired_nodelay(tcp_nodelay: Option<bool>) -> Option<bool> {
tcp_nodelay
}
#[inline]
fn set_nodelay(stream: &TcpStream, nodelay: bool) {
let _ = stream.set_nodela... |
rust_dataset_chunk_383 | rust_dataset.txt | 383 | 512 | expect: X,
upgrade: Option<U>,
on_connect_ext: Option<Rc<ConnectCallback<T>>>,
_phantom: PhantomData<B>,
}
impl<T, S, B> HttpService<T, S, B>
where
S: ServiceFactory<Request, Config = ()>,
S::Error: Into<Response<BoxBody>> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>... |
rust_dataset_chunk_384 | rust_dataset.txt | 384 | 512 | Service<Request>>::Future: 'static,
B: MessageBody,
{
/// Sets service for `Expect: 100-Continue` handling.
///
/// An expect service is called with requests that contain an `Expect: 100-Continue` header. A
/// successful response type is also a request which will be forwarded to the main service.
... |
rust_dataset_chunk_385 | rust_dataset.txt | 385 | 512 | 'static,
B: MessageBody + 'static,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
X::Error: Into<Response<BoxBody>>,
X::InitError: fmt::Debug,
U: ServiceFactory<(Request, Framed<TcpStream, h1::Codec>), Config = (), Response = ()>,
U::Future: 'static,
... |
rust_dataset_chunk_386 | rust_dataset.txt | 386 | 512 | (nodelay) = desired_nodelay(tcp_nodelay) {
set_nodelay(&io, nodelay);
}
let peer_addr = io.peer_addr().ok();
Ok((io, proto, peer_addr))
})
.and_then(self)
}
}
/// Configuration options used when accepting TLS connection.
#[cfg(feature = "__tls")]... |
rust_dataset_chunk_387 | rust_dataset.txt | 387 | 512 | self.openssl_with_config(acceptor, TlsAcceptorConfig::default())
}
/// Create OpenSSL based service with custom TLS acceptor configuration.
pub fn openssl_with_config(
self,
acceptor: SslAcceptor,
tls_acceptor_config: TlsAcceptorConfig,
) ... |
rust_dataset_chunk_388 | rust_dataset.txt | 388 | 512 | >> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
X::Error: Into<Response<BoxBody>>,
X::InitError: fmt::Debug,
U: ServiceFactory<
... |
rust_dataset_chunk_389 | rust_dataset.txt | 389 | 512 | 1.alpn_protocol() {
if protos.windows(2).any(|window| window == b"h2") {
Protocol::Http2
} else {
Protocol::Http1
}
} else {
Protocol::Http1
... |
rust_dataset_chunk_390 | rust_dataset.txt | 390 | 512 | ::default())
}
/// Create Rustls v0.21 based service with custom TLS acceptor configuration.
pub fn rustls_021_with_config(
self,
mut config: ServerConfig,
tls_acceptor_config: TlsAcceptorConfig,
) -> impl ServiceFactory<
TcpStream,
... |
rust_dataset_chunk_391 | rust_dataset.txt | 391 | 512 | , B, X, U>
where
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Response<BoxBody>> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + ... |
rust_dataset_chunk_392 | rust_dataset.txt | 392 | 512 | acceptor
.map_init_err(|_| {
unreachable!("TLS acceptor service factory does not error on init")
})
.map_err(TlsError::into_service_error)
.and_then(move |io: TlsStream<TcpStream>| async move {
let proto ... |
rust_dataset_chunk_393 | rust_dataset.txt | 393 | 512 | pub fn rustls_0_23(
self,
config: ServerConfig,
) -> impl ServiceFactory<
TcpStream,
Config = (),
Response = (),
Error = TlsError<io::Error, DispatchError>,
InitError = (),
> {
self.rustls_0_23_with_c... |
rust_dataset_chunk_394 | rust_dataset.txt | 394 | 512 | , X, U> ServiceFactory<(T, Protocol, Option<net::SocketAddr>)>
for HttpService<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin + 'static,
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Response<BoxBody>> + 'static,
S::InitError: fmt::Debug,
S::Response: I... |
rust_dataset_chunk_395 | rust_dataset.txt | 395 | 512 | service,
expect,
upgrade,
on_connect_ext,
))
})
}
}
/// `Service` implementation for HTTP/1 and HTTP/2 transport
pub struct HttpServiceHandler<T, S, B, X, U>
where
S: Service<Request>,
X: Service<Request>,
U: Service<(R... |
rust_dataset_chunk_396 | rust_dataset.txt | 396 | 512 | upgrade: Option<U>) -> Rc<Self> {
Rc::new(Self {
service,
expect,
upgrade,
})
}
}
impl<T, S, B, X, U> Service<(T, Protocol, Option<net::SocketAddr>)>
for HttpServiceHandler<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,... |
rust_dataset_chunk_397 | rust_dataset.txt | 397 | 512 | ),
},
},
proto => unimplemented!("Unsupported HTTP version: {:?}.", proto),
}
}
}
#[cfg(not(feature = "http2"))]
pin_project! {
#[project = StateProj]
enum State<T, S, B, X, U>
where
T: AsyncRead,
T: AsyncWrite,
T: Unpin,
... |
rust_dataset_chunk_398 | rust_dataset.txt | 398 | 512 | ::Future: 'static,
S::Response: Into<Response<B>>,
S::Response: 'static,
B: MessageBody,
X: Service<Request, Response = Request>,
X::Error: Into<Response<BoxBody>>,
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
U::Error: fmt::Display,
{
... |
rust_dataset_chunk_399 | rust_dataset.txt | 399 | 512 | Various testing helpers for use in internal and app tests.
#[cfg(test)]
pub(crate) mod pending_once_write_buf;
#[cfg(test)]
mod ready_chunk_body;
mod test_buffer;
mod test_request;
mod test_seq_buffer;
#[cfg(test)]
pub(crate) mod test_services;
pub use self::{
test_buffer::TestBuffer,
test_request::TestReque... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.