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_600 | rust_dataset.txt | 600 | 512 | : Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
let value_seq = ValueSeq::new(self.value);
if len == value_seq.len() {
visitor.visit_seq... |
rust_dataset_chunk_601 | rust_dataset.txt | 601 | 512 | Owned(value) => visitor.visit_string(value),
}
}
unsupported_type!(deserialize_map, "map");
unsupported_type!(deserialize_identifier, "identifier");
}
struct ParamsSeq<'de, T: ResourcePath> {
params: PathIter<'de, T>,
}
impl<'de, T: ResourcePath> de::SeqAccess<'de> for ParamsSeq<'de, T> {
... |
rust_dataset_chunk_602 | rust_dataset.txt | 602 | 512 | , char>,
}
impl<'de> ValueSeq<'de> {
fn new(value: &'de str) -> Self {
Self {
elems: value.split('/'),
}
}
fn len(&self) -> usize {
self.elems.clone().filter(|s| !s.is_empty()).count()
}
}
impl<'de> de::SeqAccess<'de> for ValueSeq<'de> {
type Error = de::value:... |
rust_dataset_chunk_603 | rust_dataset.txt | 603 | 512 | let mut router = Router::<()>::build();
router.path("/{key}/{value}/", ());
let router = router.finish();
let mut path = Path::new("/name/user1/");
assert!(router.recognize(&mut path).is_some());
let s: MyStruct = de::Deserialize::deserialize(PathDeserializer::new(&path... |
rust_dataset_chunk_604 | rust_dataset.txt | 604 | 512 | de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(unit_struct, UnitPath);
let newtype: NewtypePath =
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(newtype, NewtypePath("32".to_owned()));
}
#[test]
fn test_... |
rust_dataset_chunk_605 | rust_dataset.txt | 605 | 512 | value::Error> =
de::Deserialize::deserialize(PathDeserializer::new(&path));
assert!(structure.unwrap_err().to_string().contains("not supported"));
}
#[test]
fn test_extract_enum_value() {
let mut router = Router::<()>::build();
router.path("/{val}/", ());
let rou... |
rust_dataset_chunk_606 | rust_dataset.txt | 606 | 512 | vec![Some("tail/with/slash/es".to_owned())]);
let ignored: Vec<de::IgnoredAny> =
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(ignored.len(), 1);
let units: Vec<()> = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
ass... |
rust_dataset_chunk_607 | rust_dataset.txt | 607 | 512 | assert!(resource.capture_match_info(&mut path));
let bytes: Bytes = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(bytes, Bytes(b"bytes".to_vec()));
let mut path = Path::new("/%62ytes");
assert!(resource.capture_match_info(&mut path));
l... |
rust_dataset_chunk_608 | rust_dataset.txt | 608 | 512 | mut router = Router::<()>::build();
router.path("/{value}/", ());
let router = router.finish();
let mut path = Path::new("/name/");
assert!(router.recognize(&mut path).is_some());
let s: Result<Test1, de::value::Error> =
de::Deserialize::deserialize(PathDeserialize... |
rust_dataset_chunk_609 | rust_dataset.txt | 609 | 512 | () {
let rdef = ResourceDef::new("/{key}");
let mut path = Path::new("/%25");
rdef.capture_match_info(&mut path);
let de = PathDeserializer::new(&path);
let segment: String = serde::Deserialize::deserialize(de).unwrap();
assert_eq!(segment, "%");
let mut path = ... |
rust_dataset_chunk_610 | rust_dataset.txt | 610 | 512 | ::new(&path));
assert!(vals.unwrap_err().to_string().contains("Unexpected"));
let vals =
serde::Deserializer::deserialize_map(PathDeserializer::new(&path), ValueBeforeKey);
assert!(vals.unwrap_err().to_string().contains("unexpected item"));
}
#[test]
fn deserialize_path... |
rust_dataset_chunk_611 | rust_dataset.txt | 611 | 512 | erializer.deserialize_any(Vis)
}
}
#[derive(Debug, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum AnyEnumDerive {
String(String),
Int(u32),
Other,
}
// single
let rdef = ResourceDef::new("/{key}");
l... |
rust_dataset_chunk_612 | rust_dataset.txt | 612 | 512 | some str: 4294967296".to_string())
);
let mut path = Path::new("/-123");
rdef.capture_match_info(&mut path);
let segment: AnyEnumCustom =
serde::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(segment, AnyEnumCustom::String("some str: -123... |
rust_dataset_chunk_613 | rust_dataset.txt | 613 | 512 | value}/")));
// macro_rules! test_single_value {
// ($value:expr, $expected:expr) => {{
// let req = TestRequest::with_uri($value).finish();
// let info = router.recognize(&req, &(), 0);
// let req = req.with_route_info(info);
// asser... |
rust_dataset_chunk_614 | rust_dataset.txt | 614 | 512 | Path::<(String, String)>::from_request(&req, &PathConfig::default()).unwrap();
// assert_eq!(s.0, "%");
// assert_eq!(s.1, "7");
// }
// #[test]
// fn test_extract_path_no_decode() {
// let mut router = Router::<()>::default();
// router.register_resource(Resource::new(Reso... |
rust_dataset_chunk_615 | rust_dataset.txt | 615 | 512 | path representation.
path: T,
/// Number of characters in `path` that have been processed into `segments`.
pub(crate) skip: u16,
/// List of processed dynamic segments; name->value pairs.
pub(crate) segments: Vec<(Cow<'static, str>, PathItem)>,
}
impl<T: ResourcePath> Path<T> {
pub fn new(pa... |
rust_dataset_chunk_616 | rust_dataset.txt | 616 | 512 | ) -> u16,
{
self.skip = reindex(self.skip);
for (_, item) in &mut self.segments {
if let PathItem::Segment(start, end) = item {
*start = reindex(*start);
*end = reindex(*end);
if *start > *end {
*start = *end;
... |
rust_dataset_chunk_617 | rust_dataset.txt | 617 | 512 | name == seg_name {
return match val {
PathItem::Static(ref seg) => Some(seg),
PathItem::Segment(start, end) => {
Some(&self.path.path()[(*start as usize)..(*end as usize)])
}
};
}
}
... |
rust_dataset_chunk_618 | rust_dataset.txt | 618 | 512 | type Output = str;
fn index(&self, name: &'a str) -> &str {
self.get(name)
.expect("Value for parameter is not available")
}
}
impl<T: ResourcePath> Index<usize> for Path<T> {
type Output = str;
fn index(&self, idx: usize) -> &str {
match self.segments[idx].1 {
... |
rust_dataset_chunk_619 | rust_dataset.txt | 619 | 512 | path.segment_count(), 1);
assert_eq!(path.get("kind"), Some("user"));
assert_eq!(path.query("kind"), "user");
assert_eq!(path.query("missing"), "");
assert_eq!(&path["kind"], "user");
assert_eq!(&path[0], "user");
assert_eq!(path.iter().collect::<Vec<_>>(), vec![("kind", ... |
rust_dataset_chunk_620 | rust_dataset.txt | 620 | 512 | assert_eq!(id, 123);
}
}
--- FILE: actix-web/actix-router/src/pattern.rs ---
/// One or many patterns.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Patterns {
Single(String),
List(Vec<String>),
}
impl Patterns {
pub fn is_empty(&self) -> bool {
match self {
Patter... |
rust_dataset_chunk_621 | rust_dataset.txt | 621 | 512 | _multiple!(&str, |&v| v.to_owned(), 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16);
array_patterns_single!(String);
array_patterns_multiple!(String, |v| v.clone(), 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16);
#[cfg(test)]
mod tests {
use bytestring::ByteString;
use super::*;
#[test]
fn empty_patterns_are_distingui... |
rust_dataset_chunk_622 | rust_dataset.txt | 622 | 512 | to_owned(), "/two".to_owned()])
);
assert_eq!(
["/one".to_owned()].patterns(),
Patterns::Single("/one".to_owned())
);
assert_eq!(
["/one".to_owned(), "/two".to_owned()].patterns(),
Patterns::List(vec!["/one".to_owned(), "/two".to_owned()])
... |
rust_dataset_chunk_623 | rust_dataset.txt | 623 | 512 | .bit_at(ch)))
{
*val = rem;
return Some((prev, ch));
}
}
}
None
}
/// Partially percent-decodes the given bytes.
///
/// Escape sequences of the protected set are *not* decoded.
///
/// Returns ... |
rust_dataset_chunk_624 | rust_dataset.txt | 624 | 512 | left shift high nibble by 4 bits
Some(((d_high as u8) << 4) | (d_low as u8))
}
#[derive(Debug, Default, Clone)]
struct AsciiBitmap {
array: [u8; 16],
}
impl AsciiBitmap {
/// Sets bit in given bit-map to 1=true.
///
/// # Panics
/// Panics if `ch` index is out of bounds.
fn set_bit(&mut s... |
rust_dataset_chunk_625 | rust_dataset.txt | 625 | 512 | let q = Quoter::new(b"%+", b"/");
assert_eq!(q.requote(b"/a%2x%2X%%"), None);
assert_eq!(q.requote(b"/a%20%2X%%").unwrap(), b"/a %2X%%");
}
#[test]
fn quoter_no_modification() {
let q = Quoter::new(b"", b"");
assert_eq!(q.requote(b"/abc/../efg"), None);
}
}
---... |
rust_dataset_chunk_626 | rust_dataset.txt | 626 | 512 | : &str) -> Option<usize> {
cfg_if! {
if #[cfg(feature = "unicode")] {
self.0.matches(path).into_iter().next()
} else {
Some(self.0.iter().enumerate().find(|(_, re)| re.is_match(path))?.0)
}
}
}
}
--- FILE: actix-web/actix-router/s... |
rust_dataset_chunk_627 | rust_dataset.txt | 627 | 512 | assert_eq!(<http::Uri as ResourcePath>::path(&uri), "/resource");
}
}
--- FILE: actix-web/actix-router/src/resource.rs ---
use std::{
borrow::{Borrow, Cow},
collections::HashMap,
hash::{BuildHasher, Hash, Hasher},
mem,
};
use tracing::error;
use crate::{
path::PathItem,
regex_set::{esca... |
rust_dataset_chunk_628 | rust_dataset.txt | 628 | 512 | actix_router::ResourceDef;
/// let resource = ResourceDef::new("/home");
///
/// assert!(resource.is_match("/home"));
///
/// assert!(!resource.is_match("/home/"));
/// assert!(!resource.is_match("/home/new"));
/// assert!(!resource.is_match("/homes"));
/// assert!(!resource.is_match("/search"));
/// ```
///
/// # Dyn... |
rust_dataset_chunk_629 | rust_dataset.txt | 629 | 512 | an unexpected, though correct, behavior.
/// They define and therefore require an empty segment in order to match. It is easier to understand
/// this behavior after reading the [matching behavior section]. Examples are given below.
///
/// The empty pattern (`""`), as a prefix, matches any path.
///
/// Prefix resour... |
rust_dataset_chunk_630 | rust_dataset.txt | 630 | 512 | regex for matching _all_ remaining characters (not just those
/// up until a `/` character), there is a special pattern to match (and capture) the remaining
/// path portion.
///
/// To do this, use the segment pattern: `{name}*`. Since a tail segment also has a name, values are
/// extracted in the same way as non-ta... |
rust_dataset_chunk_631 | rust_dataset.txt | 631 | 512 |
#[derive(Clone, Debug)]
pub struct ResourceDef {
id: u16,
/// Optional name of resource.
name: Option<String>,
/// Pattern that generated the resource definition.
patterns: Patterns,
is_prefix: bool,
/// Pattern type.
pat_type: PatternType,
/// List of segments that compose the... |
rust_dataset_chunk_632 | rust_dataset.txt | 632 | 512 | .
///
/// Although it will compile and run correctly, it is meaningless to construct a prefix
/// resource definition with a tail segment; use [`new`][Self::new] in this case.
///
/// # Panics
/// Panics if path pattern is malformed.
///
/// # Examples
/// ```
/// use actix_route... |
rust_dataset_chunk_633 | rust_dataset.txt | 633 | 512 | /// ```
pub fn id(&self) -> u16 {
self.id
}
/// Set numeric resource ID.
///
/// # Examples
/// ```
/// # use actix_router::ResourceDef;
/// let mut resource = ResourceDef::new("/root");
/// resource.set_id(42);
/// assert_eq!(resource.id(), 42);
/// ```
pub ... |
rust_dataset_chunk_634 | rust_dataset.txt | 634 | 512 | mut resource = ResourceDef::new("/user/{id}");
/// assert_eq!(resource.pattern().unwrap(), "/user/{id}");
///
/// let mut resource = ResourceDef::new(["/profile", "/user/{id}"]);
/// assert_eq!(resource.pattern(), Some("/profile"));
pub fn pattern(&self) -> Option<&str> {
match &self.patter... |
rust_dataset_chunk_635 | rust_dataset.txt | 635 | 512 | .len())),
}
}
}
PatternIter {
patterns: &self.patterns,
list_idx: 0,
done: false,
}
}
/// Joins two resources.
///
/// Resulting resource is prefix if `other` is prefix.
///
/// # Examples
/// ```
/... |
rust_dataset_chunk_636 | rust_dataset.txt | 636 | 512 | ResourceDef::prefix("/root");
/// assert!(resource.is_match("/root"));
/// assert!(resource.is_match("/root/leaf"));
/// assert!(!resource.is_match("/roots"));
///
/// // more examples are shown in the `ResourceDef` struct docs
/// ```
#[inline]
pub fn is_match(&self, path: &str) -> boo... |
rust_dataset_chunk_637 | rust_dataset.txt | 637 | 512 | /{id}", "/profile/{id}"]);
/// assert_eq!(resource.find_match("/user/123"), Some(9));
/// assert_eq!(resource.find_match("/profile/1234"), Some(13));
/// ```
pub fn find_match(&self, path: &str) -> Option<usize> {
match &self.pat_type {
PatternType::Static(pattern) => self.static_mat... |
rust_dataset_chunk_638 | rust_dataset.txt | 638 | 512 | ///
/// fn try_match(resource: &ResourceDef, path: &mut Path<&str>) -> bool {
/// let admin_allowed = std::env::var("ADMIN_ALLOWED").is_ok();
///
/// resource.capture_match_info_fn(
/// path,
/// // when env var is not set, reject when path contains "admin"
/// ... |
rust_dataset_chunk_639 | rust_dataset.txt | 639 | 512 | 1].len(), Some(names))
}
PatternType::DynamicSet(re, params) => {
let path = path.unprocessed();
let (pattern, names) = match re.first_match_idx(path) {
Some(idx) => ¶ms[idx],
_ => return false,
};
... |
rust_dataset_chunk_640 | rust_dataset.txt | 640 | 512 | }");
///
/// assert!(resource.resource_path_from_iter(&mut s, &["123", "my-post"]));
/// assert_eq!(s, "/user/123/post/my-post");
/// ```
pub fn resource_path_from_iter<I>(&self, path: &mut String, values: I) -> bool
where
I: IntoIterator,
I::Item: AsRef<str>,
{
let m... |
rust_dataset_chunk_641 | rust_dataset.txt | 641 | 512 | => None,
}
}
fn construct<T: IntoPatterns>(paths: T, is_prefix: bool) -> Self {
let patterns = paths.patterns();
let (pat_type, segments) = match &patterns {
Patterns::Single(pattern) => ResourceDef::parse(pattern, is_prefix, false),
// since zero length patte... |
rust_dataset_chunk_642 | rust_dataset.txt | 642 | 512 | 1;
params_nesting == 0
}
_ => false,
})
.unwrap_or_else(|| {
panic!(
r#"Pattern "{}" contains malformed dynamic segment"#,
pattern
)
});
let (mut para... |
rust_dataset_chunk_643 | rust_dataset.txt | 643 | 512 | _segment = false;
while let Some(idx) = unprocessed.find('{') {
let (prefix, rem) = unprocessed.split_at(idx);
segments.push(PatternSegment::Const(prefix.to_owned()));
re.push_str(&escape(prefix));
let (param_pattern, re_part, rem, tail) = Self::parse_param(rem... |
rust_dataset_chunk_644 | rust_dataset.txt | 644 | 512 | ),
};
// `Bok::leak(Box::new(name))` is an intentional memory leak. In typical applications the
// routing table is only constructed once (per worker) so leak is bounded. If you are
// constructing `ResourceDef`s more than once in your application's lifecycle you would
// expect... |
rust_dataset_chunk_645 | rust_dataset.txt | 645 | 512 | "), ResourceDef::new(vec!["/"]));
assert_eq!(
ResourceDef::from("/from-str"),
ResourceDef::new("/from-str")
);
assert_eq!(
ResourceDef::from("/from-string".to_owned()),
ResourceDef::new("/from-string")
);
assert_ne!(ResourceDef::ne... |
rust_dataset_chunk_646 | rust_dataset.txt | 646 | 512 | Def::new("/root");
first.set_id(1);
first.set_name("first");
let mut second = ResourceDef::new("/root");
second.set_id(2);
second.set_name("second");
assert_eq!(first, second);
assert_eq!(hash(&first), hash(&second));
}
#[test]
#[should_panic(expect... |
rust_dataset_chunk_647 | rust_dataset.txt | 647 | 512 | user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
let mut path = Path::new("/user/profile");
assert!(re.capture_match_info(&mut path));
assert_eq!(path.get("id").unwrap(), "profile");
assert_eq!(path.unprocessed(), "");
let mut path = Path::new("/user/1245125");
... |
rust_dataset_chunk_648 | rust_dataset.txt | 648 | 512 | let mut path = Path::new("/user/1245125");
assert!(re.capture_match_info(&mut path));
assert_eq!(path.get("id").unwrap(), "1245125");
assert_eq!(path.unprocessed(), "");
assert!(re.is_match("/v1/resource/320120"));
assert!(!re.is_match("/v/resource/1"));
assert!(... |
rust_dataset_chunk_649 | rust_dataset.txt | 649 | 512 | ("/u/abc/123"), Some(6));
assert_eq!(re.find_match("/s/user/profile"), None);
assert_eq!(re.find_match("/123"), Some(4));
assert_eq!(re.find_match("/123/456"), Some(4));
assert_eq!(re.find_match("/12345"), None);
let mut path = Path::new("/151/res");
assert!(re.capture_... |
rust_dataset_chunk_650 | rust_dataset.txt | 650 | 512 | }*");
assert!(!re.is_match("/user/2345"));
let mut path = Path::new("/user/2345/sdg");
assert!(re.capture_match_info(&mut path));
assert_eq!(path.get("id").unwrap(), "2345");
assert_eq!(path.get("tail").unwrap(), "sdg");
assert_eq!(path.unprocessed(), "");
}
#[te... |
rust_dataset_chunk_651 | rust_dataset.txt | 651 | 512 | /a\nb");
assert!(re.capture_match_info(&mut path));
assert_eq!(path.get("id").unwrap(), "a\nb/a\nb");
}
#[cfg(feature = "http")]
#[test]
fn parse_urlencoded_param() {
let re = ResourceDef::new("/user/{id}/test");
let mut path = Path::new("/user/2345/test");
asse... |
rust_dataset_chunk_652 | rust_dataset.txt | 652 | 512 | let mut path = Path::new("/name//gs");
assert!(re.capture_match_info(&mut path));
assert_eq!(path.unprocessed(), "/gs");
let re = ResourceDef::root_prefix("name/");
assert!(re.is_match("/name/"));
assert!(re.is_match("/name//gs"));
assert!(!re.is_match("/name/gs"));
... |
rust_dataset_chunk_653 | rust_dataset.txt | 653 | 512 | "/user/user1/test");
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}/test");
assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter()));
assert_eq!(s, "/user/item/item2/test");
let mut s = String::new();
let resou... |
rust_dataset_chunk_654 | rust_dataset.txt | 654 | 512 | mut path));
assert!(path.get("id").is_some());
let resource = ResourceDef::new(["/user/{id}", "/profile/{uid}"]);
let mut path = Path::new("/user/123");
assert!(resource.capture_match_info(&mut path));
assert!(path.get("id").is_some());
assert!(path.get("uid").is_none()... |
rust_dataset_chunk_655 | rust_dataset.txt | 655 | 512 | ();
map.insert("item1", "item");
assert!(resource.resource_path_from_map(&mut s, &map));
assert_eq!(s, "/user/item");
}
#[test]
fn prefix_trailing_slash() {
// The prefix "/abc/" matches two segments: ["user", ""]
// These are not prefixes
let re = ResourceD... |
rust_dataset_chunk_656 | rust_dataset.txt | 656 | 512 | {:?}; mismatch on \"{}\"; seq={:?}; join={:?}",
pat1, pat2, _path, _seq, _join
);
assert!(re1.join(&re2).is_prefix());
})+
}}
}
join_test!("", "" => "", "/hello", "/");
join_test!("/user", "" => "", "/u... |
rust_dataset_chunk_657 | rust_dataset.txt | 657 | 512 | "/v", "/v1", "/v222", "/foo");
match_methods_agree!(["/v{v}", "/version/{v}"] => "/v", "/v1", "/version", "/version/1", "/foo");
match_methods_agree!("/path{tail}*" => "/path", "/path1", "/path/123");
match_methods_agree!("/path/{tail}*" => "/path", "/path1", "/path/123");
match_metho... |
rust_dataset_chunk_658 | rust_dataset.txt | 658 | 512 | ("/user/{id}*");
}
}
--- FILE: actix-web/actix-router/src/router.rs ---
use crate::{IntoPatterns, Resource, ResourceDef};
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ResourceId(pub u16);
/// Resource router.
///
/// It matches a [routing resource](Resource) to an ordered list of _routes_. Each is de... |
rust_dataset_chunk_659 | rust_dataset.txt | 659 | 512 | pub fn recognize_fn<R, F>(&self, resource: &mut R, mut check: F) -> Option<(&T, ResourceId)>
where
R: Resource,
F: FnMut(&R, &U) -> bool,
{
for (rdef, val, ctx) in self.routes.iter() {
if rdef.capture_match_info_fn(resource, |res| check(res, ctx)) {
return... |
rust_dataset_chunk_660 | rust_dataset.txt | 660 | 512 | where
U: Default,
{
/// Registers resource for specified path.
pub fn path(&mut self, path: impl IntoPatterns, val: T) -> (&mut ResourceDef, &mut T, &mut U) {
self.push(ResourceDef::new(path), val, U::default())
}
/// Registers resource for specified path prefix.
pub fn prefix(
... |
rust_dataset_chunk_661 | rust_dataset.txt | 661 | 512 | let mut path = Path::new("/name/value");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 11);
assert_eq!(info, ResourceId(1));
assert_eq!(path.get("val").unwrap(), "value");
assert_eq!(&path["val"], "value");
let mut path = Path::new("/name/valu... |
rust_dataset_chunk_662 | rust_dataset.txt | 662 | 512 | _eq!(path.get("test").unwrap(), "bbb");
}
#[test]
fn test_recognizer_2() {
let mut router = Router::<usize>::build();
router.path("/index.json", 10);
router.path("/{source}.json", 11);
let mut router = router.finish();
let mut path = Path::new("/index.json");
... |
rust_dataset_chunk_663 | rust_dataset.txt | 663 | 512 | path = Path::new("/test2/name-test");
path.skip(6);
assert!(router.recognize_mut(&mut path).is_none());
let mut path = Path::new("/test2/name/ttt");
path.skip(6);
let (h, _) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 11);
assert_eq!(&path["val"],... |
rust_dataset_chunk_664 | rust_dataset.txt | 664 | 512 | exact");
}
#[test]
fn recognize_mut_fn_returns_mutable_values() {
let mut builder = Router::<u8, bool>::build();
let (resource, _, context) = builder.prefix("/prefix", 2);
resource.set_id(7);
*context = true;
let mut router = builder.finish();
let mut path =... |
rust_dataset_chunk_665 | rust_dataset.txt | 665 | 512 | ) {
self.uri = uri.clone();
self.path = quoter.requote_str_lossy(uri.path());
}
}
impl ResourcePath for Url {
#[inline]
fn path(&self) -> &str {
self.path()
}
}
#[cfg(test)]
mod tests {
use std::fmt::Write as _;
use http::Uri;
use super::*;
use crate::{Path, R... |
rust_dataset_chunk_666 | rust_dataset.txt | 666 | 512 | as u8)))
.collect::<String>();
let encoded = percent_encode(non_protected_ascii.as_bytes());
let path = match_url("/user/{id}/test", format!("/user/{}/test", encoded));
assert_eq!(path.get("id").unwrap(), &non_protected_ascii);
}
#[test]
fn valid_utf8_multi_byte() {
... |
rust_dataset_chunk_667 | rust_dataset.txt | 667 | 512 | _path() {
let default = Url::default();
assert_eq!(default.uri(), &Uri::default());
assert_eq!(default.path(), "/");
}
}
--- FILE: actix-web/actix-test/src/lib.rs ---
//! Integration testing tools for Actix Web applications.
//!
//! The main integration testing tool is [`TestServer`]. It s... |
rust_dataset_chunk_668 | rust_dataset.txt | 668 | 512 | , Connector};
use futures_core::Stream;
use tokio::sync::mpsc;
/// Start default [`TestServer`].
///
/// # Examples
/// ```
/// use actix_web::{get, web, test, App, HttpResponse, Error, Responder};
///
/// #[get("/")]
/// async fn my_handler() -> Result<impl Responder, Error> {
/// Ok(HttpResponse::Ok())
/// }
///... |
rust_dataset_chunk_669 | rust_dataset.txt | 669 | 512 | static,
I: IntoServiceFactory<S, Request>,
S: ServiceFactory<Request, Config = AppConfig> + 'static,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
{
// for ... |
rust_dataset_chunk_670 | rust_dataset.txt | 670 | 512 | |_| app_cfg.clone()))
.tcp()
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
... |
rust_dataset_chunk_671 | rust_dataset.txt | 671 | 512 | .clone()))
.openssl(acceptor.clone())
}),
},
#[cfg(feature = "rustls-0_20")]
StreamType::Rustls020(config) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
... |
rust_dataset_chunk_672 | rust_dataset.txt | 672 | 512 | .into_factory()
.map_err(|err| err.into().error_response());
HttpService::build()
.client_request_timeout(timeout)
.h2(map_config(fac, move |_| app_cfg.clone()))
... |
rust_dataset_chunk_673 | rust_dataset.txt | 673 | 512 | Rustls023(config) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let app_cfg =
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
let fac = factory()
... |
rust_dataset_chunk_674 | rust_dataset.txt | 674 | 512 | builder
.set_alpn_protos(b"\x02h2\x08http/1.1")
.map_err(|err| log::error!("Can not set alpn protocol: {err:?}"));
Connector::new()
.conn_lifetime(Duration::from_secs(0))
.timeout(Duration::from_millis(30000))
... |
rust_dataset_chunk_675 | rust_dataset.txt | 675 | 512 | : HttpVer::Both,
stream: StreamType::Tcp,
client_request_timeout: Duration::from_secs(5),
listen_address: "127.0.0.1".to_string(),
port: 0,
workers: 1,
disable_redirects: false,
}
}
/// Accepts HTTP/1.1 only.
pub fn h1(mut self... |
rust_dataset_chunk_676 | rust_dataset.txt | 676 | 512 | ls v0.22.
#[cfg(feature = "rustls-0_22")]
pub fn rustls_0_22(mut self, config: tls_rustls_0_22::ServerConfig) -> Self {
self.stream = StreamType::Rustls022(config);
self
}
/// Accepts secure connections via Rustls v0.23.
#[cfg(feature = "rustls-0_23")]
pub fn rustls_0_23(mut sel... |
rust_dataset_chunk_677 | rust_dataset.txt | 677 | 512 |
}
/// Construct test server url
pub fn url(&self, uri: &str) -> String {
let scheme = if self.tls { "https" } else { "http" };
if uri.starts_with('/') {
format!("{}://{}{}", scheme, self.addr, uri)
} else {
format!("{}://{}/{}", scheme, self.addr, uri)
... |
rust_dataset_chunk_678 | rust_dataset.txt | 678 | 512 | <web::Bytes, PayloadError>> + Unpin + 'static,
{
response.body().limit(10_485_760).await
}
/// Connect to WebSocket server at a given path.
pub async fn ws_at(
&mut self,
path: &str,
) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, awc::error::WsClientError> {
... |
rust_dataset_chunk_679 | rust_dataset.txt | 679 | 512 | ::ActorFuture,
Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, SpawnHandle,
};
use actix_web::error::Error;
use bytes::Bytes;
use futures_core::Stream;
use tokio::sync::oneshot::Sender;
/// Execution context for HTTP actors
///
/// # Example
///
/// A demonstration of [server-sent events](ht... |
rust_dataset_chunk_680 | rust_dataset.txt | 680 | 512 | self.inner.stop();
}
fn terminate(&mut self) {
self.inner.terminate()
}
fn state(&self) -> ActorState {
self.inner.state()
}
}
impl<A> AsyncContext<A> for HttpContext<A>
where
A: Actor<Context = Self>,
{
#[inline]
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
where
... |
rust_dataset_chunk_681 | rust_dataset.txt | 681 | 512 | data: Bytes) {
self.stream.push_back(Some(data));
}
/// Indicate end of streaming payload. Also this method calls `Self::close`.
#[inline]
pub fn write_eof(&mut self) {
self.stream.push_back(None);
}
/// Handle of the running future
///
/// SpawnHandle is the handle re... |
rust_dataset_chunk_682 | rust_dataset.txt | 682 | 512 | , init_service, read_body, TestRequest},
web, App, HttpResponse,
};
use super::*;
struct MyActor {
count: usize,
}
impl Actor for MyActor {
type Context = HttpContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
ctx.run_later(Duration::from_... |
rust_dataset_chunk_683 | rust_dataset.txt | 683 | 512 | {
//! Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
//! Ok(ws::Message::Text(text)) => ctx.text(text),
//! Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
//! _ => (),
//! }
//! }
//! }
//!
//! #[get("/ws")]
//! async fn index(req: HttpRequest, stream: web::... |
rust_dataset_chunk_684 | rust_dataset.txt | 684 | 512 | //! fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
//! match msg {
//! Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
//! Ok(ws::Message::Text(text)) => ctx.text(text),
//! Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
//! ... |
rust_dataset_chunk_685 | rust_dataset.txt | 685 | 512 | , HttpResponseBuilder,
};
use bytes::{Bytes, BytesMut};
use bytestring::ByteString;
use futures_core::Stream;
use pin_project_lite::pin_project;
use tokio::sync::oneshot;
use tokio_util::codec::{Decoder as _, Encoder as _};
/// Builder for Websocket session response.
///
/// # Examples
///
/// ```no_run
/// # use acti... |
rust_dataset_chunk_686 | rust_dataset.txt | 686 | 512 | /// ```
pub struct WsResponseBuilder<'a, A, T>
where
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Result<Message, ProtocolError>>,
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
actor: A,
req: &'a HttpRequest,
stream: T,
codec: Option<Codec>,
protocols: Option<&'a [&'a... |
rust_dataset_chunk_687 | rust_dataset.txt | 687 | 512 | // modify existing codec's max frame size
let orig_codec = mem::take(codec);
*codec = orig_codec.max_size(frame_size);
}
None => {
// create a new codec with the given size
self.codec = Some(Codec::new().ma... |
rust_dataset_chunk_688 | rust_dataset.txt | 688 | 512 | /// Perform WebSocket handshake and start actor.
///
/// `req` is an [`HttpRequest`] that should be requesting a websocket protocol change.
/// `stream` should be a [`Bytes`] stream (such as `actix_web::web::Payload`) that contains a
/// stream of the body request.
///
/// If there is a prob... |
rust_dataset_chunk_689 | rust_dataset.txt | 689 | 512 | T>(
actor: A,
req: &HttpRequest,
stream: T,
) -> Result<(Addr<A>, HttpResponse), Error>
where
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Result<Message, ProtocolError>>,
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
let mut res = handshake(req)?;
let (addr, out_str... |
rust_dataset_chunk_690 | rust_dataset.txt | 690 | 512 | } else {
false
}
} else {
false
};
if !has_hdr {
return Err(HandshakeError::NoWebsocketUpgrade);
}
// Upgrade connection
if !req.head().upgrade() {
return Err(HandshakeError::NoConnectionUpgrade);
}
// check supported version
if !req.hea... |
rust_dataset_chunk_691 | rust_dataset.txt | 691 | 512 | self.inner.stop();
}
fn terminate(&mut self) {
self.inner.terminate()
}
fn state(&self) -> ActorState {
self.inner.state()
}
}
impl<A> AsyncContext<A> for WebsocketContext<A>
where
A: Actor<Context = Self>,
{
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
where
... |
rust_dataset_chunk_692 | rust_dataset.txt | 692 | 512 | let mut ctx = WebsocketContext {
inner: ContextParts::new(mb.sender_producer()),
messages: VecDeque::new(),
};
ctx.add_stream(WsStream::new(stream, Codec::new()));
let addr = ctx.address();
(addr, WebsocketContextFut::new(ctx, actor, mb, Codec::new()))
}
... |
rust_dataset_chunk_693 | rust_dataset.txt | 693 | 512 | .messages.push_back(Some(msg));
}
/// Send text frame
#[inline]
pub fn text(&mut self, text: impl Into<ByteString>) {
self.write_raw(Message::Text(text.into()));
}
/// Send binary frame
#[inline]
pub fn binary(&mut self, data: impl Into<Bytes>) {
self.write_raw(Message:... |
rust_dataset_chunk_694 | rust_dataset.txt | 694 | 512 | >
where
A: Actor<Context = WebsocketContext<A>>,
{
type Item = Result<Bytes, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.fut.alive() {
let _ = Pin::new(&mut this.fut).poll(cx);
}
... |
rust_dataset_chunk_695 | rust_dataset.txt | 695 | 512 | ) {
Poll::Ready(Some(Ok(chunk))) => {
this.buf.extend_from_slice(&chunk[..]);
}
Poll::Ready(None) => {
*this.closed = true;
break;
}
Poll::Pending =... |
rust_dataset_chunk_696 | rust_dataset.txt | 696 | 512 | insert_header((
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
))
.insert_header((
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
))
.to_http_request();
assert_eq!(
... |
rust_dataset_chunk_697 | rust_dataset.txt | 697 | 512 | OCKET_KEY,
header::HeaderValue::from_static("13"),
))
.to_http_request();
let resp = handshake(&req).unwrap().finish();
assert_eq!(StatusCode::SWITCHING_PROTOCOLS, resp.status());
assert_eq!(None, resp.headers().get(&header::CONTENT_LENGTH));
asse... |
rust_dataset_chunk_698 | rust_dataset.txt | 698 | 512 | ()
);
assert_eq!(
Some(&header::HeaderValue::from_static("p2")),
handshake_with_protocols(&req, &protocols)
.unwrap()
.finish()
.headers()
.get(&header::SEC_WEBSOCKET_PROTOCOL)
);
let req = TestReque... |
rust_dataset_chunk_699 | rust_dataset.txt | 699 | 512 | _ => ctx.close(Some(ws::CloseCode::Error.into())),
}
}
}
const MAX_FRAME_SIZE: usize = 10_000;
const DEFAULT_FRAME_SIZE: usize = 10;
async fn common_test_code(mut srv: actix_test::TestServer, frame_size: usize) {
// client service
let mut framed = srv.ws().await.unwrap();
framed.s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.