text
stringlengths
0
4.1M
#![deny(warnings)] use cases::case::*; /// Converts a `&str` to camelCase `String` /// /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "fooBar".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "fooBar".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "fooBar".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "fooBar".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "fooBar".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "foo-bar"; /// let expected_string: String = "fooBar".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "fooBar".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "FooBar3"; /// let expected_string: String = "fooBar3".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::camelcase::to_camel_case; /// let mock_string: &str = "Foo-Bar"; /// let expected_string: String = "fooBar".to_string(); /// let asserted_string: String = to_camel_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_camel_case(non_camelized_string: &str) -> String { let options = CamelOptions { new_word: false, last_char: ' ', first_word: false, injectable_char: ' ', has_seperator: false, inverted: false, }; to_case_camel_like(&non_camelized_string, options) } /// Determines if a `&str` is camelCase bool`` /// /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "Foo"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "foo"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == true); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "fooBarIsAReallyReally3LongString"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == true); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == true); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::camelcase::is_camel_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_camel_case(mock_string); /// assert!(asserted_bool == false); /// ``` pub fn is_camel_case(test_string: &str) -> bool { to_camel_case(&test_string.clone()) == test_string } #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_camel0(b: &mut Bencher) { b.iter(|| { let test_string = "Foo bar"; super::to_camel_case(test_string) }); } #[bench] fn bench_camel1(b: &mut Bencher) { b.iter(|| { let test_string = "foo_bar"; super::to_camel_case(test_string) }); } #[bench] fn bench_camel2(b: &mut Bencher) { b.iter(|| { let test_string = "fooBar"; super::to_camel_case(test_string) }); } #[bench] fn bench_is_camel(b: &mut Bencher) { b.iter(|| { let test_string: &str = "Foo bar"; super::is_camel_case(test_string) }); } } #[cfg(test)] mod tests { use ::to_camel_case; use ::is_camel_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn from_case_with_loads_of_space() { let convertable_string: String = "foo bar".to_owned(); let expected: String = "fooBar".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn a_name_with_a_dot() { let convertable_string: String = "Robert C. Martin".to_owned(); let expected: String = "robertCMartin".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn random_text_with_bad_chars() { let convertable_string: String = "Random text with *(bad) chars".to_owned(); let expected: String = "randomTextWithBadChars".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn trailing_bad_chars() { let convertable_string: String = "trailing bad_chars*(()())".to_owned(); let expected: String = "trailingBadChars".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn leading_bad_chars() { let convertable_string: String = "-!#$%leading bad chars".to_owned(); let expected: String = "leadingBadChars".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn wrapped_in_bad_chars() { let convertable_string: String = "-!#$%wrapped in bad chars&*^*&(&*^&(<><?>><?><>))".to_owned(); let expected: String = "wrappedInBadChars".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn has_a_sign() { let convertable_string: String = "has a + sign".to_owned(); let expected: String = "hasASign".to_owned(); assert_eq!(to_camel_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_camel_case(&convertable_string), true) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_camel_case(&convertable_string), false) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_camel_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_camel_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_camel_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_camel_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_camel_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_camel_case(&convertable_string), false) } }
#![deny(warnings)] #[allow(unknown_lints)] #[allow(unused_imports)] use std::ascii::*; pub struct CamelOptions { pub new_word: bool, pub last_char: char, pub first_word: bool, pub injectable_char: char, pub has_seperator: bool, pub inverted: bool, } pub fn to_case_snake_like(convertable_string: &str, replace_with: &str, case: &str) -> String { let mut first_character: bool = true; let mut result: String = String::with_capacity(convertable_string.len() * 2); for char_with_index in trim_right(convertable_string).char_indices() { if char_is_seperator(&char_with_index.1) { if !first_character { first_character = true; result.push(replace_with.chars().nth(0).unwrap_or('_')); } } else if requires_seperator(char_with_index, first_character, &convertable_string) { first_character = false; result = snake_like_with_seperator(result, replace_with, &char_with_index.1, case) } else { first_character = false; result = snake_like_no_seperator(result, &char_with_index.1, case) } } result } pub fn to_case_camel_like(convertable_string: &str, camel_options: CamelOptions) -> String { let mut new_word: bool = camel_options.new_word; let mut first_word: bool = camel_options.first_word; let mut last_char: char = camel_options.last_char; let mut found_real_char: bool = false; let mut result: String = String::with_capacity(convertable_string.len() * 2); for character in trim_right(convertable_string).chars() { if char_is_seperator(&character) && found_real_char { new_word = true; } else if !found_real_char && is_not_alphanumeric(character) { continue; } else if character.is_numeric() { found_real_char = true; new_word = true; result.push(character); } else if last_char_lower_current_is_upper_or_new_word(new_word, last_char, character) { found_real_char = true; new_word = false; result = append_on_new_word(result, first_word, character, &camel_options); first_word = false; } else { found_real_char = true; last_char = character; result.push(character.to_ascii_lowercase()); } } result } #[inline] fn append_on_new_word(mut result: String, first_word: bool, character: char, camel_options: &CamelOptions) -> String { if not_first_word_and_has_seperator(first_word, camel_options.has_seperator) { result.push(camel_options.injectable_char); } if first_word_or_not_inverted(first_word, camel_options.inverted) { result.push(character.to_ascii_uppercase()); } else { result.push(character.to_ascii_lowercase()); } result } fn not_first_word_and_has_seperator(first_word: bool, has_seperator: bool) -> bool { has_seperator && !first_word } fn first_word_or_not_inverted(first_word: bool, inverted: bool) -> bool { !inverted || first_word } fn last_char_lower_current_is_upper_or_new_word(new_word: bool, last_char: char, character: char) -> bool{ new_word || ((last_char.is_lowercase() && character.is_uppercase()) && (last_char != ' ')) } fn char_is_seperator(character: &char) -> bool { is_not_alphanumeric(*character) } fn trim_right(convertable_string: &str) -> &str { convertable_string.trim_end_matches(is_not_alphanumeric) } fn is_not_alphanumeric(character: char) -> bool { !character.is_alphanumeric() } #[inline] fn requires_seperator(char_with_index: (usize, char), first_character: bool, convertable_string: &str) -> bool { !first_character && char_is_uppercase(char_with_index.1) && next_or_previous_char_is_lowercase(convertable_string, char_with_index.0) } #[inline] fn snake_like_no_seperator(mut accumlator: String, current_char: &char, case: &str) -> String { if case == "lower" { accumlator.push(current_char.to_ascii_lowercase()); accumlator } else { accumlator.push(current_char.to_ascii_uppercase()); accumlator } } #[inline] fn snake_like_with_seperator(mut accumlator: String, replace_with: &str, current_char: &char, case: &str) -> String { if case == "lower" { accumlator.push(replace_with.chars().nth(0).unwrap_or('_')); accumlator.push(current_char.to_ascii_lowercase()); accumlator } else { accumlator.push(replace_with.chars().nth(0).unwrap_or('_')); accumlator.push(current_char.to_ascii_uppercase()); accumlator } } fn next_or_previous_char_is_lowercase(convertable_string: &str, char_with_index: usize) -> bool { convertable_string.chars().nth(char_with_index + 1).unwrap_or('A').is_lowercase() || convertable_string.chars().nth(char_with_index - 1).unwrap_or('A').is_lowercase() } fn char_is_uppercase(test_char: char) -> bool { test_char == test_char.to_ascii_uppercase() } #[test] fn test_trim_bad_chars() { assert_eq!("abc", trim_right("abc----^")) } #[test] fn test_trim_bad_chars_when_none_are_bad() { assert_eq!("abc", trim_right("abc")) } #[test] fn test_is_not_alphanumeric_on_is_alphanumeric() { assert!(!is_not_alphanumeric('a')) } #[test] fn test_is_not_alphanumeric_on_is_not_alphanumeric() { assert!(is_not_alphanumeric('_')) } #[test] fn test_char_is_uppercase_when_it_is() { assert_eq!(char_is_uppercase('A'), true) } #[test] fn test_char_is_uppercase_when_it_is_not() { assert_eq!(char_is_uppercase('a'), false) } #[test] fn test_next_or_previous_char_is_lowercase_true() { assert_eq!(next_or_previous_char_is_lowercase("TestWWW", 3), true) } #[test] fn test_next_or_previous_char_is_lowercase_false() { assert_eq!(next_or_previous_char_is_lowercase("TestWWW", 5), false) } #[test] fn snake_like_with_seperator_lowers() { assert_eq!(snake_like_with_seperator("".to_owned(), "^", &'c', "lower"), "^c".to_string()) } #[test] fn snake_like_with_seperator_upper() { assert_eq!(snake_like_with_seperator("".to_owned(), "^", &'c', "upper"), "^C".to_string()) } #[test] fn snake_like_no_seperator_lower() { assert_eq!(snake_like_no_seperator("".to_owned(), &'C', "lower"), "c".to_string()) } #[test] fn snake_like_no_seperator_upper() { assert_eq!(snake_like_no_seperator("".to_owned(), &'c', "upper"), "C".to_string()) } #[test] fn requires_seperator_upper_not_first_wrap_is_safe_current_upper() { assert_eq!(requires_seperator((2, 'C'), false, "test"), true) } #[test] fn requires_seperator_upper_not_first_wrap_is_safe_current_lower() { assert_eq!(requires_seperator((2, 'c'), false, "test"), false) } #[test] fn requires_seperator_upper_first_wrap_is_safe_current_upper() { assert_eq!(requires_seperator((0, 'T'), true, "Test"), false) } #[test] fn requires_seperator_upper_first_wrap_is_safe_current_lower() { assert_eq!(requires_seperator((0, 't'), true, "Test"), false) } #[test] fn requires_seperator_upper_first_wrap_is_safe_current_lower_next_is_too() { assert_eq!(requires_seperator((0, 't'), true, "test"), false) } #[test] fn test_char_is_seperator_dash() { assert_eq!(char_is_seperator(&'-'), true) } #[test] fn test_char_is_seperator_underscore() { assert_eq!(char_is_seperator(&'_'), true) } #[test] fn test_char_is_seperator_space() { assert_eq!(char_is_seperator(&' '), true) } #[test] fn test_char_is_seperator_when_not() { assert_eq!(char_is_seperator(&'A'), false) } #[test] fn test_last_char_lower_current_is_upper_or_new_word_with_new_word() { assert_eq!(last_char_lower_current_is_upper_or_new_word(true, ' ', '-'), true) } #[test] fn test_last_char_lower_current_is_upper_or_new_word_last_char_space() { assert_eq!(last_char_lower_current_is_upper_or_new_word(false, ' ', '-'), false) } #[test] fn test_last_char_lower_current_is_upper_or_new_word_last_char_lower_current_upper() { assert_eq!(last_char_lower_current_is_upper_or_new_word(false, 'a', 'A'), true) } #[test] fn test_last_char_lower_current_is_upper_or_new_word_last_char_upper_current_upper() { assert_eq!(last_char_lower_current_is_upper_or_new_word(false, 'A', 'A'), false) } #[test] fn test_last_char_lower_current_is_upper_or_new_word_last_char_upper_current_lower() { assert_eq!(last_char_lower_current_is_upper_or_new_word(false, 'A', 'a'), false) } #[test] fn test_first_word_or_not_inverted_with_first_word() { assert_eq!(first_word_or_not_inverted(true, false), true) } #[test] fn test_first_word_or_not_inverted_not_first_word_not_inverted() { assert_eq!(first_word_or_not_inverted(false, false), true) } #[test] fn test_first_word_or_not_inverted_not_first_word_is_inverted() { assert_eq!(first_word_or_not_inverted(false, true), false) } #[test] fn test_not_first_word_and_has_seperator_is_first_and_not_seperator() { assert_eq!(not_first_word_and_has_seperator(true, false), false) } #[test] fn test_not_first_word_and_has_seperator_not_first_and_not_seperator() { assert_eq!(not_first_word_and_has_seperator(false, false), false) } #[test] fn test_not_first_word_and_has_seperator_not_first_and_has_seperator() { assert_eq!(not_first_word_and_has_seperator(false, true), true) }
#![deny(warnings)] use cases::case::*; #[cfg(feature = "heavyweight")] use string::singularize::to_singular; #[cfg(feature = "heavyweight")] /// Converts a `&str` to `ClassCase` `String` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "FooBars"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "foo-bar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "foo_bars"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::classcase::to_class_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_class_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_class_case(non_class_case_string: &str) -> String { let options = CamelOptions { new_word: true, last_char: ' ', first_word: false, injectable_char: ' ', has_seperator: false, inverted: false, }; let class_plural = to_case_camel_like(non_class_case_string, options); let split: (&str, &str) = class_plural.split_at(class_plural.rfind(char::is_uppercase).unwrap_or(0)); format!("{}{}", split.0, to_singular(split.1)) } #[cfg(feature = "heavyweight")] /// Determines if a `&str` is `ClassCase` `bool` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "Foo"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "foo"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongStrings"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "foo_bar_is_a_really_really_long_strings"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::classcase::is_class_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_class_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` pub fn is_class_case(test_string: &str) -> bool { to_class_case(&test_string.clone()) == test_string } #[cfg(all(feature = "unstable", test))] #[cfg(feature = "heavyweight")] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_class_case(b: &mut Bencher) { b.iter(|| super::to_class_case("Foo bar")); } #[bench] fn bench_is_class(b: &mut Bencher) { b.iter(|| super::is_class_case("Foo bar")); } #[bench] fn bench_class_from_snake(b: &mut Bencher) { b.iter(|| super::to_class_case("foo_bar")); } } #[cfg(test)] #[cfg(feature = "heavyweight")] mod tests { use ::to_class_case; use ::is_class_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_screaming_class_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_table_case() { let convertable_string: String = "foo_bars".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn from_case_with_loads_of_space() { let convertable_string: String = "foo bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn a_name_with_a_dot() { let convertable_string: String = "Robert C. Martin".to_owned(); let expected: String = "RobertCMartin".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn random_text_with_bad_chars() { let convertable_string: String = "Random text with *(bad) chars".to_owned(); let expected: String = "RandomTextWithBadChar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn trailing_bad_chars() { let convertable_string: String = "trailing bad_chars*(()())".to_owned(); let expected: String = "TrailingBadChar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn leading_bad_chars() { let convertable_string: String = "-!#$%leading bad chars".to_owned(); let expected: String = "LeadingBadChar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn wrapped_in_bad_chars() { let convertable_string: String = "-!#$%wrapped in bad chars&*^*&(&*^&(<><?>><?><>))".to_owned(); let expected: String = "WrappedInBadChar".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn has_a_sign() { let convertable_string: String = "has a + sign".to_owned(); let expected: String = "HasASign".to_owned(); assert_eq!(to_class_case(&convertable_string), expected) } #[test] fn is_correct_from_class_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_class_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_class_case(&convertable_string), true) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_class_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_class_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_class_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_class_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_class_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_class_case(&convertable_string), false) } #[test] fn is_correct_from_table_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_class_case(&convertable_string), true) } }
#![deny(warnings)] use cases::case::*; /// Determines if a `&str` is `kebab-case` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// let mock_string: &str = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::is_kebab_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_kebab_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` pub fn is_kebab_case(test_string: &str) -> bool { test_string == to_kebab_case(test_string.clone()) } /// Converts a `&str` to `kebab-case` `String` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// let mock_string: &str = "foo-bar"; /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::kebabcase::to_kebab_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "foo-bar".to_string(); /// let asserted_string: String = to_kebab_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_kebab_case(non_kebab_case_string: &str) -> String { to_case_snake_like(non_kebab_case_string, "-", "lower") } #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_kebab(b: &mut Bencher) { b.iter(|| super::to_kebab_case("Foo bar")); } #[bench] fn bench_is_kebab(b: &mut Bencher) { b.iter(|| super::is_kebab_case("Foo bar")); } #[bench] fn bench_kebab_from_snake(b: &mut Bencher) { b.iter(|| super::to_kebab_case("test_test_test")); } } #[cfg(test)] mod tests { use ::to_kebab_case; use ::is_kebab_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "foo-bar".to_owned(); assert_eq!(to_kebab_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "foo-bar".to_owned(); assert_eq!(to_kebab_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "foo-bar".to_owned(); assert_eq!(to_kebab_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "foo-bar".to_owned(); assert_eq!(to_kebab_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "foo-bar".to_owned(); assert_eq!(to_kebab_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "foo-bar".to_owned(); assert_eq!(to_kebab_case(&convertable_string), expected) } #[test] fn from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "foo-bar".to_owned(); assert_eq!(to_kebab_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "foo-bar".to_owned(); assert_eq!(to_kebab_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_kebab_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_kebab_case(&convertable_string), false) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_kebab_case(&convertable_string), true) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_kebab_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_kebab_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_kebab_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_kebab_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_kebab_case(&convertable_string), false) } }
mod case; /// Provides conversion to and detection of class case strings. /// /// This version singularizes strings. /// /// Example string `ClassCase` pub mod classcase; /// Provides conversion to and detection of camel case strings. /// /// Example string `camelCase` pub mod camelcase; /// Provides conversion to and detection of snake case strings. /// /// Example string `snake_case` pub mod snakecase; /// Provides conversion to and detection of screaming snake case strings. /// /// Example string `SCREAMING_SNAKE_CASE` pub mod screamingsnakecase; /// Provides conversion to and detection of kebab case strings. /// /// Example string `kebab-case` pub mod kebabcase; /// Provides conversion to and detection of train case strings. /// /// Example string `Train-Case` pub mod traincase; /// Provides conversion to and detection of sentence case strings. /// /// Example string `Sentence case` pub mod sentencecase; /// Provides conversion to and detection of title case strings. /// /// Example string `Title Case` pub mod titlecase; /// Provides conversion to and detection of table case strings. /// /// Example string `table_cases` pub mod tablecase; /// Provides conversion to pascal case strings. /// /// Example string `PascalCase` pub mod pascalcase;
#![deny(warnings)] use cases::case::*; /// Converts a `&str` to pascalCase `String` /// /// ``` /// use inflector::cases::pascalcase::to_pascal_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_pascal_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::pascalcase::to_pascal_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_pascal_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::pascalcase::to_pascal_case; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_pascal_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::pascalcase::to_pascal_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_pascal_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::pascalcase::to_pascal_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_pascal_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::pascalcase::to_pascal_case; /// let mock_string: &str = "foo-bar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_pascal_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::pascalcase::to_pascal_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "FooBar".to_string(); /// let asserted_string: String = to_pascal_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::pascalcase::to_pascal_case; /// let mock_string: &str = "FooBar3"; /// let expected_string: String = "FooBar3".to_string(); /// let asserted_string: String = to_pascal_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_pascal_case(non_pascalized_string: &str) -> String { let options = CamelOptions { new_word: true, last_char: ' ', first_word: false, injectable_char: ' ', has_seperator: false, inverted: false, }; to_case_camel_like(non_pascalized_string, options) } /// Determines if a `&str` is pascalCase bool`` /// /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "Foo"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == true); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "foo"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == true); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "FooBarIsAReallyReally3LongString"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == true); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == true); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == false); /// /// /// ``` /// ``` /// use inflector::cases::pascalcase::is_pascal_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_pascal_case(mock_string); /// assert!(asserted_bool == false); /// ``` pub fn is_pascal_case(test_string: &str) -> bool { to_pascal_case(test_string.clone()) == test_string } #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_pascal0(b: &mut Bencher) { b.iter(|| { let test_string = "Foo bar"; super::to_pascal_case(test_string) }); } #[bench] fn bench_pascal1(b: &mut Bencher) { b.iter(|| { let test_string = "foo_bar"; super::to_pascal_case(test_string) }); } #[bench] fn bench_pascal2(b: &mut Bencher) { b.iter(|| { let test_string = "fooBar"; super::to_pascal_case(test_string) }); } #[bench] fn bench_is_pascal(b: &mut Bencher) { b.iter(|| { let test_string: &str = "Foo bar"; super::is_pascal_case(test_string) }); } } #[cfg(test)] mod tests { use ::to_pascal_case; use ::is_pascal_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn from_case_with_loads_of_space() { let convertable_string: String = "foo bar".to_owned(); let expected: String = "FooBar".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn a_name_with_a_dot() { let convertable_string: String = "Robert C. Martin".to_owned(); let expected: String = "RobertCMartin".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn random_text_with_bad_chars() { let convertable_string: String = "Random text with *(bad) chars".to_owned(); let expected: String = "RandomTextWithBadChars".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn trailing_bad_chars() { let convertable_string: String = "trailing bad_chars*(()())".to_owned(); let expected: String = "TrailingBadChars".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn leading_bad_chars() { let convertable_string: String = "-!#$%leading bad chars".to_owned(); let expected: String = "LeadingBadChars".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn wrapped_in_bad_chars() { let convertable_string: String = "-!#$%wrapped in bad chars&*^*&(&*^&(<><?>><?><>))".to_owned(); let expected: String = "WrappedInBadChars".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn has_a_sign() { let convertable_string: String = "has a + sign".to_owned(); let expected: String = "HasASign".to_owned(); assert_eq!(to_pascal_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_pascal_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_pascal_case(&convertable_string), true) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_pascal_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_pascal_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_pascal_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_pascal_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_pascal_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_pascal_case(&convertable_string), false) } }
#![deny(warnings)] use cases::case::*; /// Converts a `&str` to `SCREAMING_SNAKE_CASE` `String` /// /// ``` /// use inflector::cases::screamingsnakecase::to_screaming_snake_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "FOO_BAR".to_string(); /// let asserted_string: String = to_screaming_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::to_screaming_snake_case; /// let mock_string: &str = "HTTP Foo bar"; /// let expected_string: String = "HTTP_FOO_BAR".to_string(); /// let asserted_string: String = to_screaming_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::to_screaming_snake_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "FOO_BAR".to_string(); /// let asserted_string: String = to_screaming_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::to_screaming_snake_case; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "FOO_BAR".to_string(); /// let asserted_string: String = to_screaming_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::to_screaming_snake_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "FOO_BAR".to_string(); /// let asserted_string: String = to_screaming_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::to_screaming_snake_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "FOO_BAR".to_string(); /// let asserted_string: String = to_screaming_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::to_screaming_snake_case; /// let mock_string: &str = "fooBar3"; /// let expected_string: String = "FOO_BAR_3".to_string(); /// let asserted_string: String = to_screaming_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_screaming_snake_case(non_snake_case_string: &str) -> String { to_case_snake_like(non_snake_case_string, "_", "upper") } /// Determines of a `&str` is `SCREAMING_SNAKE_CASE` /// /// ``` /// use inflector::cases::screamingsnakecase::is_screaming_snake_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_screaming_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::is_screaming_snake_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_screaming_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::is_screaming_snake_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_screaming_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::is_screaming_snake_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_screaming_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::is_screaming_snake_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_screaming_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::is_screaming_snake_case; /// let mock_string: &str = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_screaming_snake_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::is_screaming_snake_case; /// let mock_string: &str = "FOO_BAR1_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_screaming_snake_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// ``` /// use inflector::cases::screamingsnakecase::is_screaming_snake_case; /// let mock_string: &str = "FOO_BAR_1_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_screaming_snake_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` pub fn is_screaming_snake_case(test_string: &str) -> bool { test_string == to_screaming_snake_case(test_string.clone()) } #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_screaming_snake(b: &mut Bencher) { b.iter(|| super::to_screaming_snake_case("Foo bar")); } #[bench] fn bench_is_screaming_snake(b: &mut Bencher) { b.iter(|| super::is_screaming_snake_case("Foo bar")); } } #[cfg(test)] mod tests { use ::to_screaming_snake_case; use ::is_screaming_snake_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "FOO_BAR".to_owned(); assert_eq!(to_screaming_snake_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "FOO_BAR".to_owned(); assert_eq!(to_screaming_snake_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "FOO_BAR".to_owned(); assert_eq!(to_screaming_snake_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "FOO_BAR".to_owned(); assert_eq!(to_screaming_snake_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "FOO_BAR".to_owned(); assert_eq!(to_screaming_snake_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "FOO_BAR".to_owned(); assert_eq!(to_screaming_snake_case(&convertable_string), expected) } #[test] fn from_screaming_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "FOO_BAR".to_owned(); assert_eq!(to_screaming_snake_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "FOO_BAR".to_owned(); assert_eq!(to_screaming_snake_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_screaming_snake_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_screaming_snake_case(&convertable_string), false) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_screaming_snake_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_screaming_snake_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_screaming_snake_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_screaming_snake_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_screaming_snake_case(&convertable_string), true) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_screaming_snake_case(&convertable_string), false) } }
#![deny(warnings)] use cases::case::*; /// Converts a `&str` to `Sentence case` `String` /// /// ``` /// use inflector::cases::sentencecase::to_sentence_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "Foo bar".to_string(); /// let asserted_string: String = to_sentence_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::sentencecase::to_sentence_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "Foo bar".to_string(); /// let asserted_string: String = to_sentence_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::sentencecase::to_sentence_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "Foo bar".to_string(); /// let asserted_string: String = to_sentence_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::sentencecase::to_sentence_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "Foo bar".to_string(); /// let asserted_string: String = to_sentence_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::sentencecase::to_sentence_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "Foo bar".to_string(); /// let asserted_string: String = to_sentence_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::sentencecase::to_sentence_case; /// let mock_string: &str = "foo-bar"; /// let expected_string: String = "Foo bar".to_string(); /// let asserted_string: String = to_sentence_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_sentence_case(non_sentence_case_string: &str) -> String { let options = CamelOptions { new_word: true, last_char: ' ', first_word: true, injectable_char: ' ', has_seperator: true, inverted: true, }; to_case_camel_like(non_sentence_case_string, options) } /// Determines of a `&str` is `Sentence case` /// /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "Foo"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "foo"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::sentencecase::is_sentence_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_sentence_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` pub fn is_sentence_case(test_string: &str) -> bool { test_string == to_sentence_case(test_string.clone()) } #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_sentence(b: &mut Bencher) { b.iter(|| super::to_sentence_case("Foo BAR")); } #[bench] fn bench_is_sentence(b: &mut Bencher) { b.iter(|| super::is_sentence_case("Foo bar")); } #[bench] fn bench_sentence_from_snake(b: &mut Bencher) { b.iter(|| super::to_sentence_case("foo_bar")); } } #[cfg(test)] mod tests { use ::to_sentence_case; use ::is_sentence_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn from_case_with_loads_of_space() { let convertable_string: String = "foo bar".to_owned(); let expected: String = "Foo bar".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn a_name_with_a_dot() { let convertable_string: String = "Robert C. Martin".to_owned(); let expected: String = "Robert c martin".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn random_text_with_bad_chars() { let convertable_string: String = "Random text with *(bad) chars".to_owned(); let expected: String = "Random text with bad chars".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn trailing_bad_chars() { let convertable_string: String = "trailing bad_chars*(()())".to_owned(); let expected: String = "Trailing bad chars".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn leading_bad_chars() { let convertable_string: String = "-!#$%leading bad chars".to_owned(); let expected: String = "Leading bad chars".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn wrapped_in_bad_chars() { let convertable_string: String = "-!#$%wrapped in bad chars&*^*&(&*^&(<><?>><?><>))".to_owned(); let expected: String = "Wrapped in bad chars".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn has_a_sign() { let convertable_string: String = "has a + sign".to_owned(); let expected: String = "Has a sign".to_owned(); assert_eq!(to_sentence_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_sentence_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_sentence_case(&convertable_string), false) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_sentence_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_sentence_case(&convertable_string), true) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_sentence_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_sentence_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_sentence_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_sentence_case(&convertable_string), false) } }
#![deny(warnings)] use cases::case::*; /// Converts a `&str` to `snake_case` `String` /// /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "foo_bar".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "HTTP Foo bar"; /// let expected_string: String = "http_foo_bar".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "HTTPFooBar"; /// let expected_string: String = "http_foo_bar".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "foo_bar".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "foo_bar".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "foo_bar".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "foo_bar".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "foo_bar".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::snakecase::to_snake_case; /// let mock_string: &str = "fooBar3"; /// let expected_string: String = "foo_bar_3".to_string(); /// let asserted_string: String = to_snake_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_snake_case(non_snake_case_string: &str) -> String { to_case_snake_like(non_snake_case_string, "_", "lower") } /// Determines of a `&str` is `snake_case` /// /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "FOO_BAR_IS_A_REALLY_REALLY_LONG_STRING"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "foo_bar1_string_that_is_really_really_long"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::snakecase::is_snake_case; /// let mock_string: &str = "foo_bar_1_string_that_is_really_really_long"; /// let asserted_bool: bool = is_snake_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` pub fn is_snake_case(test_string: &str) -> bool { test_string == to_snake_case(test_string.clone()) } #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_snake_from_title(b: &mut Bencher) { b.iter(|| super::to_snake_case("Foo bar")); } #[bench] fn bench_snake_from_camel(b: &mut Bencher) { b.iter(|| super::to_snake_case("fooBar")); } #[bench] fn bench_snake_from_snake(b: &mut Bencher) { b.iter(|| super::to_snake_case("foo_bar_bar_bar")); } #[bench] fn bench_is_snake(b: &mut Bencher) { b.iter(|| super::is_snake_case("Foo bar")); } } #[cfg(test)] mod tests { use ::to_snake_case; use ::is_snake_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn from_case_with_loads_of_space() { let convertable_string: String = "foo bar".to_owned(); let expected: String = "foo_bar".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn a_name_with_a_dot() { let convertable_string: String = "Robert C. Martin".to_owned(); let expected: String = "robert_c_martin".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn random_text_with_bad_chars() { let convertable_string: String = "Random text with *(bad) chars".to_owned(); let expected: String = "random_text_with_bad_chars".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn trailing_bad_chars() { let convertable_string: String = "trailing bad_chars*(()())".to_owned(); let expected: String = "trailing_bad_chars".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn leading_bad_chars() { let convertable_string: String = "-!#$%leading bad chars".to_owned(); let expected: String = "leading_bad_chars".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn wrapped_in_bad_chars() { let convertable_string: String = "-!#$%wrapped in bad chars&*^*&(&*^&(<><?>><?><>))".to_owned(); let expected: String = "wrapped_in_bad_chars".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn has_a_sign() { let convertable_string: String = "has a + sign".to_owned(); let expected: String = "has_a_sign".to_owned(); assert_eq!(to_snake_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_snake_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_snake_case(&convertable_string), false) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_snake_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_snake_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_snake_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_snake_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_snake_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_snake_case(&convertable_string), true) } }
#![deny(warnings)] #[cfg(feature = "heavyweight")] use string::pluralize::to_plural; #[cfg(feature = "heavyweight")] use cases::case::*; #[cfg(feature = "heavyweight")] /// Converts a `&str` to `table-case` `String` /// /// ``` /// use inflector::cases::tablecase::to_table_case; /// let mock_string: &str = "foo-bar"; /// let expected_string: String = "foo_bars".to_string(); /// let asserted_string: String = to_table_case(mock_string); /// assert!(asserted_string == expected_string); /// ``` /// /// ``` /// use inflector::cases::tablecase::to_table_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "foo_bars".to_string(); /// let asserted_string: String = to_table_case(mock_string); /// assert!(asserted_string == expected_string); /// ``` /// /// ``` /// use inflector::cases::tablecase::to_table_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "foo_bars".to_string(); /// let asserted_string: String = to_table_case(mock_string); /// assert!(asserted_string == expected_string); /// ``` /// /// ``` /// use inflector::cases::tablecase::to_table_case; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "foo_bars".to_string(); /// let asserted_string: String = to_table_case(mock_string); /// assert!(asserted_string == expected_string); /// ``` /// /// ``` /// use inflector::cases::tablecase::to_table_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "foo_bars".to_string(); /// let asserted_string: String = to_table_case(mock_string); /// assert!(asserted_string == expected_string); /// ``` /// /// ``` /// use inflector::cases::tablecase::to_table_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "foo_bars".to_string(); /// let asserted_string: String = to_table_case(mock_string); /// assert!(asserted_string == expected_string); /// ``` /// /// ``` /// use inflector::cases::tablecase::to_table_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "foo_bars".to_string(); /// let asserted_string: String = to_table_case(mock_string); /// assert!(asserted_string == expected_string); /// ``` pub fn to_table_case(non_table_case_string: &str) -> String { let snaked: String = to_case_snake_like(non_table_case_string, "_", "lower"); let split: (&str, &str) = snaked.split_at(snaked.rfind('_').unwrap_or(0)); format!("{}{}", split.0, to_plural(split.1)) } #[cfg(feature = "heavyweight")] /// Determines if a `&str` is `table-case` /// /// ``` /// use inflector::cases::tablecase::is_table_case; /// let mock_string: &str = "foo_bar_strings"; /// let asserted_bool: bool = is_table_case(mock_string); /// assert!(asserted_bool == true); /// ``` /// /// ``` /// use inflector::cases::tablecase::is_table_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_table_case(mock_string); /// assert!(asserted_bool == false); /// ``` /// /// ``` /// use inflector::cases::tablecase::is_table_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_table_case(mock_string); /// assert!(asserted_bool == false); /// ``` /// /// ``` /// use inflector::cases::tablecase::is_table_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_table_case(mock_string); /// assert!(asserted_bool == false); /// ``` /// /// ``` /// use inflector::cases::tablecase::is_table_case; /// let mock_string: &str = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_table_case(mock_string); /// assert!(asserted_bool == false); /// ``` /// /// ``` /// use inflector::cases::tablecase::is_table_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_table_case(mock_string); /// assert!(asserted_bool == false); /// ``` /// /// ``` /// use inflector::cases::tablecase::is_table_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_table_case(mock_string); /// assert!(asserted_bool == false); /// ``` /// /// ``` /// use inflector::cases::tablecase::is_table_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_table_case(mock_string); /// assert!(asserted_bool == false); /// ``` pub fn is_table_case(test_string: &str) -> bool { to_table_case(&test_string.clone()) == test_string } #[cfg(all(feature = "unstable", test))] #[cfg(feature = "heavyweight")] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_table_case(b: &mut Bencher) { b.iter(|| super::to_table_case("Foo bar")); } #[bench] fn bench_is_table_case(b: &mut Bencher) { b.iter(|| super::is_table_case("Foo bar")); } } #[cfg(test)] #[cfg(feature = "heavyweight")] mod tests { use ::to_table_case; use ::is_table_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn from_table_case() { let convertable_string: String = "foo_bars".to_owned(); let expected: String = "foo_bars".to_owned(); assert_eq!(to_table_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_table_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_table_case(&convertable_string), false) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_table_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_table_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_table_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_table_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_table_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_table_case(&convertable_string), false) } #[test] fn is_correct_from_table_case() { let convertable_string: String = "foo_bars".to_owned(); assert_eq!(is_table_case(&convertable_string), true) } }
#![deny(warnings)] use cases::case::*; /// Converts a `&str` to `Title Case` `String` /// /// ``` /// use inflector::cases::titlecase::to_title_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "Foo Bar".to_string(); /// let asserted_string: String = to_title_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::titlecase::to_title_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "Foo Bar".to_string(); /// let asserted_string: String = to_title_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::titlecase::to_title_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "Foo Bar".to_string(); /// let asserted_string: String = to_title_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::titlecase::to_title_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "Foo Bar".to_string(); /// let asserted_string: String = to_title_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::titlecase::to_title_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "Foo Bar".to_string(); /// let asserted_string: String = to_title_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::cases::titlecase::to_title_case; /// let mock_string: &str = "foo-bar"; /// let expected_string: String = "Foo Bar".to_string(); /// let asserted_string: String = to_title_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_title_case(non_title_case_string: &str) -> String { let options = CamelOptions { new_word: true, last_char: ' ', first_word: true, injectable_char: ' ', has_seperator: true, inverted: false, }; to_case_camel_like(non_title_case_string, options) } /// Determines if a `&str` is `Title Case` /// /// ``` /// use inflector::cases::titlecase::is_title_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_title_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::titlecase::is_title_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_title_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::titlecase::is_title_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_title_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::titlecase::is_title_case; /// let mock_string: &str = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG"; /// let asserted_bool: bool = is_title_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::titlecase::is_title_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_title_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::titlecase::is_title_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_title_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::titlecase::is_title_case; /// let mock_string: &str = "foo"; /// let asserted_bool: bool = is_title_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::cases::titlecase::is_title_case; /// let mock_string: &str = "Foo Bar String That Is Really Really Long"; /// let asserted_bool: bool = is_title_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` pub fn is_title_case(test_string: &str) -> bool { test_string == to_title_case(test_string.clone()) } #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_title(b: &mut Bencher) { b.iter(|| super::to_title_case("Foo BAR")); } #[bench] fn bench_is_title(b: &mut Bencher) { b.iter(|| super::is_title_case("Foo bar")); } #[bench] fn bench_title_from_snake(b: &mut Bencher) { b.iter(|| super::to_title_case("foo_bar")); } } #[cfg(test)] mod tests { use ::to_title_case; use ::is_title_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn from_case_with_loads_of_space() { let convertable_string: String = "foo bar".to_owned(); let expected: String = "Foo Bar".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn a_name_with_a_dot() { let convertable_string: String = "Robert C. Martin".to_owned(); let expected: String = "Robert C Martin".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn random_text_with_bad_chars() { let convertable_string: String = "Random text with *(bad) chars".to_owned(); let expected: String = "Random Text With Bad Chars".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn trailing_bad_chars() { let convertable_string: String = "trailing bad_chars*(()())".to_owned(); let expected: String = "Trailing Bad Chars".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn leading_bad_chars() { let convertable_string: String = "-!#$%leading bad chars".to_owned(); let expected: String = "Leading Bad Chars".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn wrapped_in_bad_chars() { let convertable_string: String = "-!#$%wrapped in bad chars&*^*&(&*^&(<><?>><?><>))".to_owned(); let expected: String = "Wrapped In Bad Chars".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn has_a_sign() { let convertable_string: String = "has a + sign".to_owned(); let expected: String = "Has A Sign".to_owned(); assert_eq!(to_title_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_title_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_title_case(&convertable_string), false) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_title_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_title_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_title_case(&convertable_string), true) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_title_case(&convertable_string), false) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_title_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_title_case(&convertable_string), false) } }
#![deny(warnings)] use cases::case::*; /// Determines if a `&str` is `Train-Case` /// /// ``` /// use inflector::cases::traincase::is_train_case; /// let mock_string: &str = "Foo-Bar-String-That-Is-Really-Really-Long"; /// let asserted_bool: bool = is_train_case(mock_string); /// assert!(asserted_bool == true); /// /// ``` /// /// ``` /// use inflector::cases::traincase::is_train_case; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_train_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::traincase::is_train_case; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_train_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::traincase::is_train_case; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_train_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::traincase::is_train_case; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_train_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::traincase::is_train_case; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_train_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// /// ``` /// use inflector::cases::traincase::is_train_case; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_train_case(mock_string); /// assert!(asserted_bool == false); /// /// ``` pub fn is_train_case(test_string: &str) -> bool { test_string == to_train_case(test_string.clone()) } /// Converts a `&str` to `Train-Case` `String` /// /// ``` /// use inflector::cases::traincase::to_train_case; /// let mock_string: &str = "foo-bar"; /// let expected_string: String = "Foo-Bar".to_string(); /// let asserted_string: String = to_train_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::traincase::to_train_case; /// let mock_string: &str = "FOO_BAR"; /// let expected_string: String = "Foo-Bar".to_string(); /// let asserted_string: String = to_train_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::traincase::to_train_case; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "Foo-Bar".to_string(); /// let asserted_string: String = to_train_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::traincase::to_train_case; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "Foo-Bar".to_string(); /// let asserted_string: String = to_train_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::traincase::to_train_case; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "Foo-Bar".to_string(); /// let asserted_string: String = to_train_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::traincase::to_train_case; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "Foo-Bar".to_string(); /// let asserted_string: String = to_train_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// /// ``` /// use inflector::cases::traincase::to_train_case; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "Foo-Bar".to_string(); /// let asserted_string: String = to_train_case(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_train_case(non_train_case_string: &str) -> String { let options = CamelOptions { new_word: true, last_char: ' ', first_word: true, injectable_char: '-', has_seperator: true, inverted: false, }; to_case_camel_like(non_train_case_string, options) } #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; #[bench] fn bench_train(b: &mut Bencher) { b.iter(|| super::to_train_case("Foo bar")); } #[bench] fn bench_is_train(b: &mut Bencher) { b.iter(|| super::is_train_case("Foo bar")); } #[bench] fn bench_train_from_snake(b: &mut Bencher) { b.iter(|| super::to_train_case("test_test_test")); } } #[cfg(test)] mod tests { use ::to_train_case; use ::is_train_case; #[test] fn from_camel_case() { let convertable_string: String = "fooBar".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn from_case_with_loads_of_space() { let convertable_string: String = "foo bar".to_owned(); let expected: String = "Foo-Bar".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn a_name_with_a_dot() { let convertable_string: String = "Robert C. Martin".to_owned(); let expected: String = "Robert-C-Martin".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn random_text_with_bad_chars() { let convertable_string: String = "Random text with *(bad) chars".to_owned(); let expected: String = "Random-Text-With-Bad-Chars".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn trailing_bad_chars() { let convertable_string: String = "trailing bad_chars*(()())".to_owned(); let expected: String = "Trailing-Bad-Chars".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn leading_bad_chars() { let convertable_string: String = "-!#$%leading bad chars".to_owned(); let expected: String = "Leading-Bad-Chars".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn wrapped_in_bad_chars() { let convertable_string: String = "-!#$%wrapped in bad chars&*^*&(&*^&(<><?>><?><>))".to_owned(); let expected: String = "Wrapped-In-Bad-Chars".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn has_a_sign() { let convertable_string: String = "has a + sign".to_owned(); let expected: String = "Has-A-Sign".to_owned(); assert_eq!(to_train_case(&convertable_string), expected) } #[test] fn is_correct_from_camel_case() { let convertable_string: String = "fooBar".to_owned(); assert_eq!(is_train_case(&convertable_string), false) } #[test] fn is_correct_from_pascal_case() { let convertable_string: String = "FooBar".to_owned(); assert_eq!(is_train_case(&convertable_string), false) } #[test] fn is_correct_from_kebab_case() { let convertable_string: String = "foo-bar".to_owned(); assert_eq!(is_train_case(&convertable_string), false) } #[test] fn is_correct_from_sentence_case() { let convertable_string: String = "Foo bar".to_owned(); assert_eq!(is_train_case(&convertable_string), false) } #[test] fn is_correct_from_title_case() { let convertable_string: String = "Foo Bar".to_owned(); assert_eq!(is_train_case(&convertable_string), false) } #[test] fn is_correct_from_train_case() { let convertable_string: String = "Foo-Bar".to_owned(); assert_eq!(is_train_case(&convertable_string), true) } #[test] fn is_correct_from_screaming_snake_case() { let convertable_string: String = "FOO_BAR".to_owned(); assert_eq!(is_train_case(&convertable_string), false) } #[test] fn is_correct_from_snake_case() { let convertable_string: String = "foo_bar".to_owned(); assert_eq!(is_train_case(&convertable_string), false) } }
#![deny(warnings, unused_variables, missing_docs, unsafe_code, unused_extern_crates)] #![cfg_attr(feature = "unstable", feature(test))] //! Adds String based inflections for Rust. Snake, kebab, train, camel, //! sentence, class, and title cases as well as ordinalize, //! deordinalize, demodulize, deconstantize, and foreign key are supported as //! both traits and pure functions acting on String types. //! ```rust //! use inflector::Inflector; //! let camel_case_string: String = "some_string".to_camel_case(); //! let is_camel_cased: bool= camel_case_string.is_camel_case(); //! assert!(is_camel_cased == true); //! ``` #[cfg(feature = "heavyweight")] extern crate regex; #[cfg(feature = "heavyweight")] #[macro_use] extern crate lazy_static; /// Provides case inflections /// - Camel case /// - Class case /// - Kebab case /// - Train case /// - Screaming snake case /// - Table case /// - Sentence case /// - Snake case /// - Pascal case pub mod cases; /// Provides number inflections /// - Ordinalize /// - Deordinalize pub mod numbers; /// Provides suffix inflections /// - Foreign key pub mod suffix; /// Provides string inflections /// - Deconstantize /// - Demodulize /// - Pluralize /// - Singularize #[cfg(feature = "heavyweight")] pub mod string; #[cfg(feature = "heavyweight")] use cases::classcase::to_class_case; #[cfg(feature = "heavyweight")] use cases::classcase::is_class_case; use cases::camelcase::to_camel_case; use cases::camelcase::is_camel_case; use cases::pascalcase::to_pascal_case; use cases::pascalcase::is_pascal_case; use cases::snakecase::to_snake_case; use cases::snakecase::is_snake_case; use cases::screamingsnakecase::to_screaming_snake_case; use cases::screamingsnakecase::is_screaming_snake_case; use cases::kebabcase::to_kebab_case; use cases::kebabcase::is_kebab_case; use cases::traincase::to_train_case; use cases::traincase::is_train_case; use cases::sentencecase::to_sentence_case; use cases::sentencecase::is_sentence_case; use cases::titlecase::to_title_case; use cases::titlecase::is_title_case; #[cfg(feature = "heavyweight")] use cases::tablecase::to_table_case; #[cfg(feature = "heavyweight")] use cases::tablecase::is_table_case; use numbers::ordinalize::ordinalize; use numbers::deordinalize::deordinalize; use suffix::foreignkey::to_foreign_key; use suffix::foreignkey::is_foreign_key; #[cfg(feature = "heavyweight")] use string::demodulize::demodulize; #[cfg(feature = "heavyweight")] use string::deconstantize::deconstantize; #[cfg(feature = "heavyweight")] use string::pluralize::to_plural; #[cfg(feature = "heavyweight")] use string::singularize::to_singular; #[allow(missing_docs)] pub trait Inflector { fn to_camel_case(&self) -> String; fn is_camel_case(&self) -> bool; fn to_pascal_case(&self) -> String; fn is_pascal_case(&self) -> bool; fn to_snake_case(&self) -> String; fn is_snake_case(&self) -> bool; fn to_screaming_snake_case(&self) -> String; fn is_screaming_snake_case(&self) -> bool; fn to_kebab_case(&self) -> String; fn is_kebab_case(&self) -> bool; fn to_train_case(&self) -> String; fn is_train_case(&self) -> bool; fn to_sentence_case(&self) -> String; fn is_sentence_case(&self) -> bool; fn to_title_case(&self) -> String; fn is_title_case(&self) -> bool; fn ordinalize(&self) -> String; fn deordinalize(&self) -> String; fn to_foreign_key(&self) -> String; fn is_foreign_key(&self) -> bool; #[cfg(feature = "heavyweight")] fn demodulize(&self) -> String; #[cfg(feature = "heavyweight")] fn deconstantize(&self) -> String; #[cfg(feature = "heavyweight")] fn to_class_case(&self) -> String; #[cfg(feature = "heavyweight")] fn is_class_case(&self) -> bool; #[cfg(feature = "heavyweight")] fn to_table_case(&self) -> String; #[cfg(feature = "heavyweight")] fn is_table_case(&self) -> bool; #[cfg(feature = "heavyweight")] fn to_plural(&self) -> String; #[cfg(feature = "heavyweight")] fn to_singular(&self) -> String; } #[allow(missing_docs)] pub trait InflectorNumbers { fn ordinalize(&self) -> String; } macro_rules! define_implementations { ( $slf:ident; $($imp_trait:ident => $typ:ident), *) => { $( #[inline] fn $imp_trait(&$slf) -> $typ { $imp_trait($slf) } )* } } macro_rules! define_number_implementations { ( $slf:ident; $($imp_trait:ident => $typ:ident), *) => { $( #[inline] fn $imp_trait(&$slf) -> $typ { $imp_trait(&$slf.to_string()) } )* } } macro_rules! define_gated_implementations { ( $slf:ident; $($imp_trait:ident => $typ:ident), *) => { $( #[inline] #[cfg(feature = "heavyweight")] fn $imp_trait(&$slf) -> $typ { $imp_trait($slf) } )* } } macro_rules! implement_string_for { ( $trt:ident; $($typ:ident), *) => { $( impl $trt for $typ { define_implementations![self; to_camel_case => String, is_camel_case => bool, to_pascal_case => String, is_pascal_case => bool, to_screaming_snake_case => String, is_screaming_snake_case => bool, to_snake_case => String, is_snake_case => bool, to_kebab_case => String, is_kebab_case => bool, to_train_case => String, is_train_case => bool, to_sentence_case => String, is_sentence_case => bool, to_title_case => String, is_title_case => bool, to_foreign_key => String, is_foreign_key => bool, ordinalize => String, deordinalize => String ]; define_gated_implementations![self; to_class_case => String, is_class_case => bool, to_table_case => String, is_table_case => bool, to_plural => String, to_singular => String, demodulize => String, deconstantize => String ]; } )* } } macro_rules! implement_number_for { ( $trt:ident; $($typ:ident), *) => { $( impl $trt for $typ { define_number_implementations![self; ordinalize => String ]; } )* } } implement_string_for![ Inflector; String, str ]; implement_number_for![ InflectorNumbers; i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64 ]; #[cfg(all(feature = "unstable", test))] mod benchmarks { extern crate test; use self::test::Bencher; use ::Inflector; macro_rules! benchmarks { ( $($test_name:ident => $imp_trait:ident => $to_cast:expr), *) => { $( #[bench] fn $test_name(b: &mut Bencher) { b.iter(|| { $to_cast.$imp_trait() }); } )* } } benchmarks![ benchmark_str_to_camel => to_camel_case => "foo_bar", benchmark_str_is_camel => is_camel_case => "fooBar", benchmark_str_to_screaming_snake => to_screaming_snake_case => "fooBar", benchmark_str_is_screaming_snake => is_screaming_snake_case => "FOO_BAR", benchmark_str_to_snake => to_snake_case => "fooBar", benchmark_str_is_snake => is_snake_case => "foo_bar", benchmark_str_to_kebab => to_kebab_case => "fooBar", benchmark_str_is_kebab => is_kebab_case => "foo-bar", benchmark_str_to_train => to_train_case => "fooBar", benchmark_str_is_train => is_train_case => "Foo-Bar", benchmark_str_to_sentence => to_sentence_case => "fooBar", benchmark_str_is_sentence => is_sentence_case => "Foo bar", benchmark_str_to_title => to_title_case => "fooBar", benchmark_str_is_title => is_title_case => "Foo Bar", benchmark_str_ordinalize => ordinalize => "1", benchmark_str_deordinalize => deordinalize => "1st", benchmark_str_to_foreign_key => to_foreign_key => "Foo::Bar", benchmark_str_is_foreign_key => is_foreign_key => "bar_id", benchmark_string_to_camel => to_camel_case => "foo_bar".to_string(), benchmark_string_is_camel => is_camel_case => "fooBar".to_string(), benchmark_string_to_screaming_snake => to_screaming_snake_case => "fooBar".to_string(), benchmark_string_is_screaming_snake => is_screaming_snake_case => "FOO_BAR".to_string(), benchmark_string_to_snake => to_snake_case => "fooBar".to_string(), benchmark_string_is_snake => is_snake_case => "foo_bar".to_string(), benchmark_string_to_kebab => to_kebab_case => "fooBar".to_string(), benchmark_string_is_kebab => is_kebab_case => "foo-bar".to_string(), benchmark_string_to_train => to_train_case => "fooBar".to_string(), benchmark_string_is_train => is_train_case => "Foo-Bar".to_string(), benchmark_string_to_sentence => to_sentence_case => "fooBar".to_string(), benchmark_string_is_sentence => is_sentence_case => "Foo bar".to_string(), benchmark_string_to_title => to_title_case => "fooBar".to_string(), benchmark_string_is_title => is_title_case => "Foo Bar".to_string(), benchmark_string_ordinalize => ordinalize => "1".to_string(), benchmark_string_deordinalize => deordinalize => "1st".to_string(), benchmark_string_to_foreign_key => to_foreign_key => "Foo::Bar".to_string(), benchmark_string_is_foreign_key => is_foreign_key => "bar_id".to_string() ]; #[cfg(feature = "heavyweight")] benchmarks![ benchmark_str_to_class => to_class_case => "foo", benchmark_str_is_class => is_class_case => "Foo", benchmark_str_to_table => to_table_case => "fooBar", benchmark_str_is_table => is_table_case => "foo_bars", benchmark_str_pluralize => to_plural => "crate", benchmark_str_singular => to_singular => "crates", benchmark_string_to_class => to_class_case => "foo".to_string(), benchmark_string_is_class => is_class_case => "Foo".to_string(), benchmark_string_to_table => to_table_case => "fooBar".to_string(), benchmark_string_is_table => is_table_case => "foo_bars".to_string(), benchmark_string_pluralize => to_plural => "crate".to_string(), benchmark_string_singular => to_singular => "crates".to_string(), benchmark_string_demodulize => demodulize => "Foo::Bar".to_string(), benchmark_string_deconstantize => deconstantize => "Foo::Bar".to_string(), benchmark_str_demodulize => demodulize => "Foo::Bar", benchmark_str_deconstantize => deconstantize => "Foo::Bar" ]; }
/// Deorginalizes a `&str` /// /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "0.1"; /// let expected_string: String = "0.1".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "-1st"; /// let expected_string: String = "-1".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "0th"; /// let expected_string: String = "0".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "1st"; /// let expected_string: String = "1".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "2nd"; /// let expected_string: String = "2".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "3rd"; /// let expected_string: String = "3".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "9th"; /// let expected_string: String = "9".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "12th"; /// let expected_string: String = "12".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "12000th"; /// let expected_string: String = "12000".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "12001th"; /// let expected_string: String = "12001".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "12002nd"; /// let expected_string: String = "12002".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "12003rd"; /// let expected_string: String = "12003".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::deordinalize::deordinalize; /// let mock_string: &str = "12004th"; /// let expected_string: String = "12004".to_owned(); /// let asserted_string: String = deordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn deordinalize(non_ordinalized_string: &str) -> String { if non_ordinalized_string.contains('.') { non_ordinalized_string.to_owned() } else { non_ordinalized_string.trim_end_matches("st") .trim_end_matches("nd") .trim_end_matches("rd") .trim_end_matches("th") .to_owned() } }
#![deny(warnings)] /// Provides ordinalization of a string. /// /// Example string "1" becomes "1st" pub mod ordinalize; /// Provides deordinalization of a string. /// /// Example string "1st" becomes "1" pub mod deordinalize;
/// Orginalizes a `&str` /// /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "a"; /// let expected_string: String = "a".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "0.1"; /// let expected_string: String = "0.1".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "-1"; /// let expected_string: String = "-1st".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "0"; /// let expected_string: String = "0th".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "1"; /// let expected_string: String = "1st".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "2"; /// let expected_string: String = "2nd".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "3"; /// let expected_string: String = "3rd".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "9"; /// let expected_string: String = "9th".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "12"; /// let expected_string: String = "12th".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "12000"; /// let expected_string: String = "12000th".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "12001"; /// let expected_string: String = "12001st".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "12002"; /// let expected_string: String = "12002nd".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "12003"; /// let expected_string: String = "12003rd".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::numbers::ordinalize::ordinalize; /// let mock_string: &str = "12004"; /// let expected_string: String = "12004th".to_owned(); /// let asserted_string: String = ordinalize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn ordinalize(non_ordinalized_string: &str) -> String { let chars: Vec<char> = non_ordinalized_string.clone().chars().collect(); let last_number: char = chars[chars.len() - 1]; if is_ordinalizable(last_number) { return non_ordinalized_string.to_owned(); } if chars.len() > 1 { if second_last_number_is_one(chars) { return format!("{}{}", non_ordinalized_string, "th"); } else if string_contains_decimal(non_ordinalized_string.to_owned()) { return non_ordinalized_string.to_owned(); } } match last_number { '1' => format!("{}{}", non_ordinalized_string, "st"), '2' => format!("{}{}", non_ordinalized_string, "nd"), '3' => format!("{}{}", non_ordinalized_string, "rd"), _ => format!("{}{}", non_ordinalized_string, "th"), } } fn is_ordinalizable(last_number: char) -> bool { !last_number.is_numeric() } fn second_last_number_is_one(chars: Vec<char>) -> bool { let second_last_number: char = chars[chars.len() - 2]; second_last_number == '1' } fn string_contains_decimal(non_ordinalized_string: String) -> bool { non_ordinalized_string.contains('.') }
pub const UNACCONTABLE_WORDS: [&'static str; 202] = ["accommodation", "adulthood", "advertising", "advice", "aggression", "aid", "air", "aircraft", "alcohol", "anger", "applause", "arithmetic", "assistance", "athletics", "bacon", "baggage", "beef", "biology", "blood", "botany", "bread", "butter", "carbon", "cardboard", "cash", "chalk", "chaos", "chess", "crossroads", "countryside", "dancing", "deer", "dignity", "dirt", "dust", "economics", "education", "electricity", "engineering", "enjoyment", "envy", "equipment", "ethics", "evidence", "evolution", "fame", "fiction", "flour", "flu", "food", "fuel", "fun", "furniture", "gallows", "garbage", "garlic", "genetics", "gold", "golf", "gossip", "grammar", "gratitude", "grief", "guilt", "gymnastics", "happiness", "hardware", "harm", "hate", "hatred", "health", "heat", "help", "homework", "honesty", "honey", "hospitality", "housework", "humour", "hunger", "hydrogen", "ice", "importance", "inflation", "information", "innocence", "iron", "irony", "jam", "jewelry", "judo", "karate", "knowledge", "lack", "laughter", "lava", "leather", "leisure", "lightning", "linguine", "linguini", "linguistics", "literature", "litter", "livestock", "logic", "loneliness", "luck", "luggage", "macaroni", "machinery", "magic", "management", "mankind", "marble", "mathematics", "mayonnaise", "measles", "methane", "milk", "money", "mud", "music", "mumps", "nature", "news", "nitrogen", "nonsense", "nurture", "nutrition", "obedience", "obesity", "oxygen", "pasta", "patience", "physics", "poetry", "pollution", "poverty", "pride", "psychology", "publicity", "punctuation", "quartz", "racism", "relaxation", "reliability", "research", "respect", "revenge", "rice", "rubbish", "rum", "safety", "scenery", "seafood", "seaside", "series", "shame", "sheep", "shopping", "sleep", "smoke", "smoking", "snow", "soap", "software", "soil", "spaghetti", "species", "steam", "stuff", "stupidity", "sunshine", "symmetry", "tennis", "thirst", "thunder", "timber", "traffic", "transportation", "trust", "underwear", "unemployment", "unity", "validity", "veal", "vegetation", "vegetarianism", "vengeance", "violence", "vitality", "warmth", "wealth", "weather", "welfare", "wheat", "wildlife", "wisdom", "yoga", "zinc", "zoology"];
#[cfg(feature = "heavyweight")] use cases::classcase::to_class_case; #[cfg(feature = "heavyweight")] /// Deconstantizes a `&str` /// /// ``` /// use inflector::string::deconstantize::deconstantize; /// let mock_string: &str = "Bar"; /// let expected_string: String = "".to_owned(); /// let asserted_string: String = deconstantize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::deconstantize::deconstantize; /// let mock_string: &str = "::Bar"; /// let expected_string: String = "".to_owned(); /// let asserted_string: String = deconstantize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::deconstantize::deconstantize; /// let mock_string: &str = "Foo::Bar"; /// let expected_string: String = "Foo".to_owned(); /// let asserted_string: String = deconstantize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::deconstantize::deconstantize; /// let mock_string: &str = "Test::Foo::Bar"; /// let expected_string: String = "Foo".to_owned(); /// let asserted_string: String = deconstantize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn deconstantize(non_deconstantized_string: &str) -> String { if non_deconstantized_string.contains("::") { let split_string: Vec<&str> = non_deconstantized_string.split("::").collect(); if split_string.len() > 1 { to_class_case(split_string[split_string.len() - 2]) } else { "".to_owned() } } else { "".to_owned() } }
#[cfg(feature = "heavyweight")] use cases::classcase::to_class_case; #[cfg(feature = "heavyweight")] /// Demodulize a `&str` /// /// ``` /// use inflector::string::demodulize::demodulize; /// let mock_string: &str = "Bar"; /// let expected_string: String = "Bar".to_owned(); /// let asserted_string: String = demodulize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::demodulize::demodulize; /// let mock_string: &str = "::Bar"; /// let expected_string: String = "Bar".to_owned(); /// let asserted_string: String = demodulize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::demodulize::demodulize; /// let mock_string: &str = "Foo::Bar"; /// let expected_string: String = "Bar".to_owned(); /// let asserted_string: String = demodulize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::demodulize::demodulize; /// let mock_string: &str = "Test::Foo::Bar"; /// let expected_string: String = "Bar".to_owned(); /// let asserted_string: String = demodulize(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn demodulize(non_demodulize_string: &str) -> String { if non_demodulize_string.contains("::") { let split_string: Vec<&str> = non_demodulize_string.split("::").collect(); to_class_case(split_string[split_string.len() - 1]) } else { non_demodulize_string.to_owned() } }
#![deny(warnings)] /// Provides demodulize a string. /// /// Example string `Foo::Bar` becomes `Bar` #[cfg(feature = "heavyweight")] pub mod demodulize; /// Provides deconstantizea string. /// /// Example string `Foo::Bar` becomes `Foo` #[cfg(feature = "heavyweight")] pub mod deconstantize; /// Provides conversion to plural strings. /// /// Example string `FooBar` -> `FooBars` #[cfg(feature = "heavyweight")] pub mod pluralize; /// Provides conversion to singular strings. /// /// Example string `FooBars` -> `FooBar` #[cfg(feature = "heavyweight")] pub mod singularize; mod constants;
#![deny(warnings)] use regex::Regex; use string::constants::UNACCONTABLE_WORDS; macro_rules! add_rule{ ($r:ident, $rule:expr => $replace:expr) => { $r.push((Regex::new($rule).unwrap(), $replace)); } } macro_rules! rules{ ($r:ident; $($rule:expr => $replace:expr), *) => { $( add_rule!{$r, $rule => $replace} )* } } lazy_static!{ static ref RULES: Vec<(Regex, &'static str)> = { let mut r = Vec::with_capacity(24); rules![r; r"(\w*)s$" => "s", r"(\w*([^aeiou]ese))$" => "", r"(\w*(ax|test))is$" => "es", r"(\w*(alias|[^aou]us|tlas|gas|ris))$" => "es", r"(\w*(e[mn]u))s?$" => "s", r"(\w*([^l]ias|[aeiou]las|[emjzr]as|[iu]am))$" => "", r"(\w*(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat))(?:us|i)$" => "i", r"(\w*(alumn|alg|vertebr))(?:a|ae)$" => "ae", r"(\w*(seraph|cherub))(?:im)?$" => "im", r"(\w*(her|at|gr))o$" => "oes", r"(\w*(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor))(?:a|um)$" => "a", r"(\w*(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat))(?:a|on)$" => "a", r"(\w*)sis$" => "ses", r"(\w*(kni|wi|li))fe$" => "ves", r"(\w*(ar|l|ea|eo|oa|hoo))f$" => "ves", r"(\w*([^aeiouy]|qu))y$" => "ies", r"(\w*([^ch][ieo][ln]))ey$" => "ies", r"(\w*(x|ch|ss|sh|zz)es)$" => "", r"(\w*(x|ch|ss|sh|zz))$" => "es", r"(\w*(matr|cod|mur|sil|vert|ind|append))(?:ix|ex)$" => "ices", r"(\w*(m|l)(?:ice|ouse))$" => "ice", r"(\w*(pe)(?:rson|ople))$" => "ople", r"(\w*(child))(?:ren)?$" => "ren", r"(\w*eaux)$" => "" ]; r }; } macro_rules! special_cases{ ($s:ident, $($singular: expr => $plural:expr), *) => { match &$s[..] { $( $singular => { return $plural.to_owned(); }, )* _ => () } } } /// Converts a `&str` to pluralized `String` /// /// ``` /// use inflector::string::pluralize::to_plural; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "foo_bars".to_owned(); /// let asserted_string: String = to_plural(mock_string); /// assert_eq!(asserted_string, expected_string); /// /// ``` /// ``` /// use inflector::string::pluralize::to_plural; /// let mock_string: &str = "ox"; /// let expected_string: String = "oxen".to_owned(); /// let asserted_string: String = to_plural(mock_string); /// assert_eq!(asserted_string, expected_string); /// /// ``` /// ``` /// use inflector::string::pluralize::to_plural; /// let mock_string: &str = "crate"; /// let expected_string: String = "crates".to_owned(); /// let asserted_string: String = to_plural(mock_string); /// assert_eq!(asserted_string, expected_string); /// /// ``` /// ``` /// use inflector::string::pluralize::to_plural; /// let mock_string: &str = "boxes"; /// let expected_string: String = "boxes".to_owned(); /// let asserted_string: String = to_plural(mock_string); /// assert_eq!(asserted_string, expected_string); /// /// ``` /// ``` /// use inflector::string::pluralize::to_plural; /// let mock_string: &str = "vengeance"; /// let expected_string: String = "vengeance".to_owned(); /// let asserted_string: String = to_plural(mock_string); /// assert_eq!(asserted_string, expected_string); /// /// ``` /// ``` /// use inflector::string::pluralize::to_plural; /// let mock_string: &str = "yoga"; /// let expected_string: String = "yoga".to_owned(); /// let asserted_string: String = to_plural(mock_string); /// assert_eq!(asserted_string, expected_string); /// /// ``` /// ``` /// use inflector::string::pluralize::to_plural; /// let mock_string: &str = "geometry"; /// let expected_string: String = "geometries".to_owned(); /// let asserted_string: String = to_plural(mock_string); /// assert_eq!(asserted_string, expected_string); /// /// ``` /// pub fn to_plural(non_plural_string: &str) -> String { if UNACCONTABLE_WORDS.contains(&non_plural_string.as_ref()) { non_plural_string.to_owned() } else { special_cases![non_plural_string, "ox" => "oxen", "man" => "men", "woman" => "women", "die" => "dice", "yes" => "yeses", "foot" => "feet", "eave" => "eaves", "goose" => "geese", "tooth" => "teeth", "quiz" => "quizzes" ]; for &(ref rule, replace) in RULES.iter().rev() { if let Some(c) = rule.captures(&non_plural_string) { if let Some(c) = c.get(1) { return format!("{}{}", c.as_str(), replace); } } } format!("{}s", non_plural_string) } } #[cfg(test)] mod tests { macro_rules! as_item { ($i:item) => { $i }; } macro_rules! make_tests{ ($($singular:ident => $plural:ident); *) =>{ $( as_item! { #[test] fn $singular(){ assert_eq!( stringify!($plural), super::to_plural(stringify!($singular)) ); } } )* } } #[test] fn boxes() { assert_eq!("boxes", super::to_plural("box")); } make_tests!{ geometry => geometries; ox => oxen; woman => women; test => tests; axis => axes; knife => knives; agendum => agenda; elf => elves; zoology => zoology } }
use regex::Regex; use string::constants::UNACCONTABLE_WORDS; macro_rules! special_cases{ ($s:ident, $($singular: expr => $plural:expr), *) => { match &$s[..] { $( $singular => { return $plural.to_owned(); }, )* _ => () } } } /// Converts a `&str` to singularized `String` /// /// ``` /// use inflector::string::singularize::to_singular; /// let mock_string: &str = "foo_bars"; /// let expected_string: String = "foo_bar".to_owned(); /// let asserted_string: String = to_singular(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::singularize::to_singular; /// let mock_string: &str = "oxen"; /// let expected_string: String = "ox".to_owned(); /// let asserted_string: String = to_singular(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::singularize::to_singular; /// let mock_string: &str = "crates"; /// let expected_string: String = "crate".to_owned(); /// let asserted_string: String = to_singular(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::singularize::to_singular; /// let mock_string: &str = "oxen"; /// let expected_string: String = "ox".to_owned(); /// let asserted_string: String = to_singular(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::singularize::to_singular; /// let mock_string: &str = "boxes"; /// let expected_string: String = "box".to_owned(); /// let asserted_string: String = to_singular(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::singularize::to_singular; /// let mock_string: &str = "vengeance"; /// let expected_string: String = "vengeance".to_owned(); /// let asserted_string: String = to_singular(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::string::singularize::to_singular; /// let mock_string: &str = "yoga"; /// let expected_string: String = "yoga".to_owned(); /// let asserted_string: String = to_singular(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// pub fn to_singular(non_singular_string: &str) -> String { if UNACCONTABLE_WORDS.contains(&non_singular_string.as_ref()) { non_singular_string.to_owned() } else { special_cases![non_singular_string, "oxen" => "ox", "boxes" => "box", "men" => "man", "women" => "woman", "dice" => "die", "yeses" => "yes", "feet" => "foot", "eaves" => "eave", "geese" => "goose", "teeth" => "tooth", "quizzes" => "quiz" ]; for &(ref rule, replace) in RULES.iter().rev() { if let Some(captures) = rule.captures(&non_singular_string) { if let Some(c) = captures.get(1) { let mut buf = String::new(); captures.expand(&format!("{}{}", c.as_str(), replace), &mut buf); return buf; } } } format!("{}", non_singular_string) } } macro_rules! add_rule{ ($r:ident, $rule:expr => $replace:expr) => { $r.push((Regex::new($rule).unwrap(), $replace)); } } macro_rules! rules{ ($r:ident; $($rule:expr => $replace:expr), *) => { $( add_rule!{$r, $rule => $replace} )* } } lazy_static!{ static ref RULES: Vec<(Regex, &'static str)> = { let mut r = Vec::with_capacity(27); rules![r; r"(\w*)s$" => "", r"(\w*)(ss)$" => "$2", r"(n)ews$" => "ews", r"(\w*)(o)es$" => "", r"(\w*)([ti])a$" => "um", r"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$" => "sis", r"(^analy)(sis|ses)$" => "sis", r"(\w*)([^f])ves$" => "fe", r"(\w*)(hive)s$" => "", r"(\w*)(tive)s$" => "", r"(\w*)([lr])ves$" => "f", r"(\w*([^aeiouy]|qu))ies$" => "y", r"(s)eries$" => "eries", r"(m)ovies$" => "ovie", r"(\w*)(x|ch|ss|sh)es$" => "$2", r"(m|l)ice$" => "ouse", r"(bus)(es)?$" => "", r"(shoe)s$" => "", r"(cris|test)(is|es)$" => "is", r"^(a)x[ie]s$" => "xis", r"(octop|vir)(us|i)$" => "us", r"(alias|status)(es)?$" => "", r"^(ox)en" => "", r"(vert|ind)ices$" => "ex", r"(matr)ices$" => "ix", r"(quiz)zes$" => "", r"(database)s$" => "" ]; r }; } #[test] fn singularize_ies_suffix() { assert_eq!("reply", to_singular("replies")); assert_eq!("lady", to_singular("ladies")); assert_eq!("soliloquy", to_singular("soliloquies")); } #[test] fn singularize_ss_suffix() { assert_eq!("glass", to_singular("glass")); assert_eq!("access", to_singular("access")); assert_eq!("glass", to_singular("glasses")); assert_eq!("witch", to_singular("witches")); assert_eq!("dish", to_singular("dishes")); } #[test] fn singularize_string_if_a_regex_will_match() { let expected_string: String = "ox".to_owned(); let asserted_string: String = to_singular("oxen"); assert!(expected_string == asserted_string); } #[test] fn singularize_string_returns_none_option_if_no_match() { let expected_string: String = "bacon".to_owned(); let asserted_string: String = to_singular("bacon"); assert!(expected_string == asserted_string); }
use cases::snakecase::to_snake_case; /// Converts a `&str` to a `foreign_key` /// /// ``` /// use inflector::suffix::foreignkey::to_foreign_key; /// let mock_string: &str = "foo_bar"; /// let expected_string: String = "foo_bar_id".to_owned(); /// let asserted_string: String = to_foreign_key(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::to_foreign_key; /// let mock_string: &str = "Foo bar"; /// let expected_string: String = "foo_bar_id".to_owned(); /// let asserted_string: String = to_foreign_key(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::to_foreign_key; /// let mock_string: &str = "Foo Bar"; /// let expected_string: String = "foo_bar_id".to_owned(); /// let asserted_string: String = to_foreign_key(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::to_foreign_key; /// let mock_string: &str = "Foo::Bar"; /// let expected_string: String = "bar_id".to_owned(); /// let asserted_string: String = to_foreign_key(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::to_foreign_key; /// let mock_string: &str = "Test::Foo::Bar"; /// let expected_string: String = "bar_id".to_owned(); /// let asserted_string: String = to_foreign_key(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::to_foreign_key; /// let mock_string: &str = "FooBar"; /// let expected_string: String = "foo_bar_id".to_owned(); /// let asserted_string: String = to_foreign_key(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::to_foreign_key; /// let mock_string: &str = "fooBar"; /// let expected_string: String = "foo_bar_id".to_owned(); /// let asserted_string: String = to_foreign_key(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::to_foreign_key; /// let mock_string: &str = "fooBar3"; /// let expected_string: String = "foo_bar_3_id".to_owned(); /// let asserted_string: String = to_foreign_key(mock_string); /// assert!(asserted_string == expected_string); /// /// ``` pub fn to_foreign_key(non_foreign_key_string: &str) -> String { if non_foreign_key_string.contains("::") { let split_string: Vec<&str> = non_foreign_key_string.split("::").collect(); safe_convert(split_string[split_string.len() - 1]) } else { safe_convert(non_foreign_key_string) } } fn safe_convert(safe_string: &str) -> String { let snake_cased: String = to_snake_case(safe_string); if snake_cased.ends_with("_id") { snake_cased } else { format!("{}{}", snake_cased, "_id") } } /// Determines if a `&str` is a `foreign_key` /// /// ``` /// use inflector::suffix::foreignkey::is_foreign_key; /// let mock_string: &str = "Foo bar string that is really really long"; /// let asserted_bool: bool = is_foreign_key(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::is_foreign_key; /// let mock_string: &str = "foo-bar-string-that-is-really-really-long"; /// let asserted_bool: bool = is_foreign_key(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::is_foreign_key; /// let mock_string: &str = "FooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_foreign_key(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::is_foreign_key; /// let mock_string: &str = "Foo Bar Is A Really Really Long String"; /// let asserted_bool: bool = is_foreign_key(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::is_foreign_key; /// let mock_string: &str = "fooBarIsAReallyReallyLongString"; /// let asserted_bool: bool = is_foreign_key(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::is_foreign_key; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long"; /// let asserted_bool: bool = is_foreign_key(mock_string); /// assert!(asserted_bool == false); /// /// ``` /// ``` /// use inflector::suffix::foreignkey::is_foreign_key; /// let mock_string: &str = "foo_bar_string_that_is_really_really_long_id"; /// let asserted_bool: bool = is_foreign_key(mock_string); /// assert!(asserted_bool == true); /// /// ``` pub fn is_foreign_key(test_string: &str) -> bool { to_foreign_key(test_string.clone()) == test_string }
#![deny(warnings)] /// Provides foreign key conversion for String. /// /// Example string `foo` becomes `foo_id` pub mod foreignkey;
#![deny(warnings)] extern crate inflector; use inflector::Inflector; use inflector::InflectorNumbers; macro_rules! str_tests { ( $($test_name:ident => $imp_trait:ident => $to_cast:expr => $casted:expr), *) => { $( #[test] fn $test_name() { assert_eq!($to_cast.$imp_trait(), $casted) } )* } } macro_rules! string_tests { ( $($test_name:ident => $imp_trait:ident => $to_cast:expr => $casted:expr), *) => { $( #[test] fn $test_name() { assert_eq!($to_cast.to_string().$imp_trait(), $casted) } )* } } macro_rules! number_tests { ( $($test_name:ident => $imp_trait:ident => $typ:ident => $to_cast:expr => $casted:expr), *) => { $( #[test] fn $test_name() { let to_cast: $typ = $to_cast; assert_eq!(to_cast.$imp_trait(), $casted) } )* } } macro_rules! gated_str_tests { ( $($test_name:ident => $imp_trait:ident => $to_cast:expr => $casted:expr), *) => { $( #[test] #[cfg(feature = "heavyweight")] fn $test_name() { assert_eq!($to_cast.$imp_trait(), $casted) } )* } } macro_rules! gated_string_tests { ( $($test_name:ident => $imp_trait:ident => $to_cast:expr => $casted:expr), *) => { $( #[test] #[cfg(feature = "heavyweight")] fn $test_name() { assert_eq!($to_cast.to_string().$imp_trait(), $casted) } )* } } str_tests![ str_to_camel => to_camel_case => "foo_bar" => "fooBar".to_string(), str_is_camel => is_camel_case => "fooBar" => true, str_is_not_camel => is_camel_case => "foo_bar" => false, str_to_screaming_snake => to_screaming_snake_case => "fooBar" => "FOO_BAR".to_string(), str_is_screaming_snake => is_screaming_snake_case => "FOO_BAR" => true, str_is_not_screaming_snake => is_screaming_snake_case => "foo_bar" => false, str_to_snake => to_snake_case => "fooBar" => "foo_bar".to_string(), str_is_snake => is_snake_case => "foo_bar" => true, str_is_not_snake => is_snake_case => "fooBar" => false, str_to_kebab => to_kebab_case => "fooBar" => "foo-bar".to_string(), str_is_kebab => is_kebab_case => "foo-bar" => true, str_is_not_kebab => is_kebab_case => "fooBar" => false, str_to_train => to_train_case => "fooBar" => "Foo-Bar".to_string(), str_is_train => is_train_case => "Foo-Bar" => true, str_is_not_train => is_train_case => "FOO-Bar" => false, str_to_sentence => to_sentence_case => "fooBar" => "Foo bar".to_string(), str_is_sentence => is_sentence_case => "Foo bar" => true, str_is_not_sentence => is_sentence_case => "foo_bar" => false, str_to_title => to_title_case => "fooBar" => "Foo Bar".to_string(), str_is_title => is_title_case => "Foo Bar" => true, str_is_not_title => is_title_case => "Foo_Bar" => false, str_ordinalize => ordinalize => "1" => "1st".to_string(), str_deordinalize => deordinalize => "1st" => "1".to_string(), str_to_foreign_key => to_foreign_key => "Foo::Bar" => "bar_id".to_string(), str_is_foreign_key => is_foreign_key => "bar_id" => true, str_is_not_foreign_key => is_foreign_key => "bar" => false ]; gated_str_tests![ str_to_class_case => to_class_case => "foo" => "Foo".to_string(), str_is_class_case => is_class_case => "Foo" => true, str_is_not_class_case => is_class_case => "foo" => false, str_to_table => to_table_case => "fooBar" => "foo_bars".to_string(), str_is_table => is_table_case => "foo_bars" => true, str_is_not_table => is_table_case => "fooBars" => false, str_pluralize => to_plural => "crate" => "crates".to_string(), str_singular => to_singular => "crates" => "crate".to_string(), str_demodulize => demodulize => "Foo::Bar" => "Bar".to_string(), str_deconstantize => deconstantize => "Foo::Bar" => "Foo".to_string() ]; string_tests![ string_to_camel => to_camel_case => "foo_bar".to_string() => "fooBar".to_string(), string_is_camel => is_camel_case => "fooBar".to_string() => true, string_is_not_camel => is_camel_case => "foo_bar".to_string() => false, string_to_screaming_snake => to_screaming_snake_case => "fooBar".to_string() => "FOO_BAR".to_string(), string_is_screaming_snake => is_screaming_snake_case => "FOO_BAR".to_string() => true, string_is_not_screaming_snake => is_screaming_snake_case => "foo_bar".to_string() => false, string_to_snake => to_snake_case => "fooBar".to_string() => "foo_bar".to_string(), string_is_snake => is_snake_case => "foo_bar".to_string() => true, string_is_not_snake => is_snake_case => "fooBar".to_string() => false, string_to_kebab => to_kebab_case => "fooBar".to_string() => "foo-bar".to_string(), string_is_kebab => is_kebab_case => "foo-bar".to_string() => true, string_is_not_kebab => is_kebab_case => "fooBar".to_string() => false, string_to_train => to_train_case => "fooBar".to_string() => "Foo-Bar".to_string(), string_is_train => is_train_case => "Foo-Bar".to_string() => true, string_is_not_train => is_train_case => "foo-Bar".to_string() => false, string_to_sentence => to_sentence_case => "fooBar".to_string() => "Foo bar".to_string(), string_is_sentence => is_sentence_case => "Foo bar".to_string() => true, string_is_not_sentence => is_sentence_case => "fooBar".to_string() => false, string_to_title => to_title_case => "fooBar".to_string() => "Foo Bar".to_string(), string_is_title => is_title_case => "Foo Bar".to_string() => true, string_is_not_title => is_title_case => "fooBar".to_string() => false, string_ordinalize => ordinalize => "1".to_string() => "1st".to_string(), string_deordinalize => deordinalize => "1st".to_string() => "1".to_string(), string_to_foreign_key => to_foreign_key => "Foo::Bar".to_string() => "bar_id".to_string(), string_is_foreign_key => is_foreign_key => "bar_id".to_string() => true, string_is_not_foreign_key => is_foreign_key => "bar".to_string() => false ]; gated_string_tests![ string_to_class_case => to_class_case => "foo".to_string() => "Foo".to_string(), string_is_class_case => is_class_case => "Foo".to_string() => true, string_is_not_class_case => is_class_case => "ooBar".to_string() => false, string_to_table => to_table_case => "fooBar".to_string() => "foo_bars".to_string(), string_is_table => is_table_case => "foo_bars".to_string() => true, string_is_not_table => is_table_case => "fooBar".to_string() => false, string_pluralize => to_plural => "crate".to_string() => "crates".to_string(), string_singular => to_singular => "crates".to_string() => "crate".to_string(), string_demodulize => demodulize => "Foo::Bar".to_string() => "Bar".to_string(), string_deconstantize => deconstantize => "Foo::Bar".to_string() => "Foo".to_string() ]; number_tests![ i8_ordinalize => ordinalize => i8 => 1 => "1st".to_string(), i16_ordinalize => ordinalize => i16 => 1 => "1st".to_string(), i32_ordinalize => ordinalize => i32 => 1 => "1st".to_string(), i64_ordinalize => ordinalize => i64 => 1 => "1st".to_string(), u8_ordinalize => ordinalize => u8 => 1 => "1st".to_string(), u16_ordinalize => ordinalize => u16 => 1 => "1st".to_string(), u32_ordinalize => ordinalize => u32 => 1 => "1st".to_string(), u64_ordinalize => ordinalize => u64 => 1 => "1st".to_string(), isize_ordinalize => ordinalize => isize => 1 => "1st".to_string(), usize_ordinalize => ordinalize => usize => 1 => "1st".to_string(), f32_ordinalize => ordinalize => f32 => 1.0 => "1st".to_string(), f64_ordinalize => ordinalize => f64 => 1.0 => "1st".to_string() ];
use bytes::BytesMut; use criterion::{criterion_group, criterion_main, Criterion}; const INPUT: &[u8] = include_bytes!("./lorem.txt"); fn bench_lines_codec(c: &mut Criterion) { let mut decode_group = c.benchmark_group("lines decode"); decode_group.bench_function("actix", |b| { b.iter(|| { use actix_codec::Decoder as _; let mut codec = actix_codec::LinesCodec::default(); let mut buf = BytesMut::from(INPUT); while let Ok(Some(_bytes)) = codec.decode_eof(&mut buf) {} }); }); decode_group.bench_function("tokio", |b| { b.iter(|| { use tokio_util::codec::Decoder as _; let mut codec = tokio_util::codec::LinesCodec::new(); let mut buf = BytesMut::from(INPUT); while let Ok(Some(_bytes)) = codec.decode_eof(&mut buf) {} }); }); decode_group.finish(); let mut encode_group = c.benchmark_group("lines encode"); encode_group.bench_function("actix", |b| { b.iter(|| { use actix_codec::Encoder as _; let mut codec = actix_codec::LinesCodec::default(); let mut buf = BytesMut::new(); codec.encode("123", &mut buf).unwrap(); }); }); encode_group.bench_function("tokio", |b| { b.iter(|| { use tokio_util::codec::Encoder as _; let mut codec = tokio_util::codec::LinesCodec::new(); let mut buf = BytesMut::new(); codec.encode("123", &mut buf).unwrap(); }); }); encode_group.finish(); } criterion_group!(benches, bench_lines_codec); criterion_main!(benches);
use std::io; use bytes::{Buf, Bytes, BytesMut}; use super::{Decoder, Encoder}; /// Bytes codec. Reads/writes chunks of bytes from a stream. #[derive(Debug, Copy, Clone)] pub struct BytesCodec; impl Encoder<Bytes> for BytesCodec { type Error = io::Error; #[inline] fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> { dst.extend_from_slice(item.chunk()); Ok(()) } } impl Decoder for BytesCodec { type Item = BytesMut; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { if src.is_empty() { Ok(None) } else { Ok(Some(src.split())) } } }
use std::{ fmt, io, pin::Pin, task::{Context, Poll}, }; use bitflags::bitflags; use bytes::{Buf, BytesMut}; use futures_core::{ready, Stream}; use futures_sink::Sink; use pin_project_lite::pin_project; use crate::{AsyncRead, AsyncWrite, Decoder, Encoder}; /// Low-water mark const LW: usize = 1024; /// High-water mark const HW: usize = 8 * 1024; bitflags! { #[derive(Debug, Clone, Copy)] struct Flags: u8 { const EOF = 0b0001; const READABLE = 0b0010; } } pin_project! { /// A unified `Stream` and `Sink` interface to an underlying I/O object, using the `Encoder` and /// `Decoder` traits to encode and decode frames. /// /// Raw I/O objects work with byte sequences, but higher-level code usually wants to batch these /// into meaningful chunks, called "frames". This method layers framing on top of an I/O object, /// by using the `Encoder`/`Decoder` traits to handle encoding and decoding of message frames. /// Note that the incoming and outgoing frame types may be distinct. pub struct Framed<T, U> { #[pin] io: T, codec: U, flags: Flags, read_buf: BytesMut, write_buf: BytesMut, } } impl<T, U> Framed<T, U> where T: AsyncRead + AsyncWrite, U: Decoder, { /// This function returns a *single* object that is both `Stream` and `Sink`; grouping this into /// a single object is often useful for layering things like gzip or TLS, which require both /// read and write access to the underlying object. pub fn new(io: T, codec: U) -> Framed<T, U> { Framed { io, codec, flags: Flags::empty(), read_buf: BytesMut::with_capacity(HW), write_buf: BytesMut::with_capacity(HW), } } } impl<T, U> Framed<T, U> { /// Returns a reference to the underlying codec. pub fn codec_ref(&self) -> &U { &self.codec } /// Returns a mutable reference to the underlying codec. pub fn codec_mut(&mut self) -> &mut U { &mut self.codec } /// Returns a reference to the underlying I/O stream wrapped by `Frame`. /// /// Note that care should be taken to not tamper with the underlying stream of data coming in as /// it may corrupt the stream of frames otherwise being worked with. pub fn io_ref(&self) -> &T { &self.io } /// Returns a mutable reference to the underlying I/O stream. /// /// Note that care should be taken to not tamper with the underlying stream of data coming in as /// it may corrupt the stream of frames otherwise being worked with. pub fn io_mut(&mut self) -> &mut T { &mut self.io } /// Returns a `Pin` of a mutable reference to the underlying I/O stream. pub fn io_pin(self: Pin<&mut Self>) -> Pin<&mut T> { self.project().io } /// Check if read buffer is empty. pub fn is_read_buf_empty(&self) -> bool { self.read_buf.is_empty() } /// Check if write buffer is empty. pub fn is_write_buf_empty(&self) -> bool { self.write_buf.is_empty() } /// Check if write buffer is full. pub fn is_write_buf_full(&self) -> bool { self.write_buf.len() >= HW } /// Check if framed is able to write more data. /// /// `Framed` object considers ready if there is free space in write buffer. pub fn is_write_ready(&self) -> bool { self.write_buf.len() < HW } /// Consume the `Frame`, returning `Frame` with different codec. pub fn replace_codec<U2>(self, codec: U2) -> Framed<T, U2> { Framed { codec, io: self.io, flags: self.flags, read_buf: self.read_buf, write_buf: self.write_buf, } } /// Consume the `Frame`, returning `Frame` with different io. pub fn into_map_io<F, T2>(self, f: F) -> Framed<T2, U> where F: Fn(T) -> T2, { Framed { io: f(self.io), codec: self.codec, flags: self.flags, read_buf: self.read_buf, write_buf: self.write_buf, } } /// Consume the `Frame`, returning `Frame` with different codec. pub fn into_map_codec<F, U2>(self, f: F) -> Framed<T, U2> where F: Fn(U) -> U2, { Framed { io: self.io, codec: f(self.codec), flags: self.flags, read_buf: self.read_buf, write_buf: self.write_buf, } } } impl<T, U> Framed<T, U> { /// Serialize item and write to the inner buffer pub fn write<I>(mut self: Pin<&mut Self>, item: I) -> Result<(), <U as Encoder<I>>::Error> where T: AsyncWrite, U: Encoder<I>, { let this = self.as_mut().project(); let remaining = this.write_buf.capacity() - this.write_buf.len(); if remaining < LW { this.write_buf.reserve(HW - remaining); } this.codec.encode(item, this.write_buf)?; Ok(()) } /// Try to read underlying I/O stream and decode item. pub fn next_item( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<<U as Decoder>::Item, U::Error>>> where T: AsyncRead, U: Decoder, { loop { let this = self.as_mut().project(); // Repeatedly call `decode` or `decode_eof` as long as it is "readable". Readable is // defined as not having returned `None`. If the upstream has returned EOF, and the // decoder is no longer readable, it can be assumed that the decoder will never become // readable again, at which point the stream is terminated. if this.flags.contains(Flags::READABLE) { if this.flags.contains(Flags::EOF) { match this.codec.decode_eof(this.read_buf) { Ok(Some(frame)) => return Poll::Ready(Some(Ok(frame))), Ok(None) => return Poll::Ready(None), Err(err) => return Poll::Ready(Some(Err(err))), } } tracing::trace!("attempting to decode a frame"); match this.codec.decode(this.read_buf) { Ok(Some(frame)) => { tracing::trace!("frame decoded from buffer"); return Poll::Ready(Some(Ok(frame))); } Err(err) => return Poll::Ready(Some(Err(err))), _ => (), // Need more data } this.flags.remove(Flags::READABLE); } debug_assert!(!this.flags.contains(Flags::EOF)); // Otherwise, try to read more data and try again. Make sure we've got room. let remaining = this.read_buf.capacity() - this.read_buf.len(); if remaining < LW { this.read_buf.reserve(HW - remaining) } let cnt = match tokio_util::io::poll_read_buf(this.io, cx, this.read_buf) { Poll::Pending => return Poll::Pending, Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err.into()))), Poll::Ready(Ok(cnt)) => cnt, }; if cnt == 0 { this.flags.insert(Flags::EOF); } this.flags.insert(Flags::READABLE); } } /// Flush write buffer to underlying I/O stream. pub fn flush<I>(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>> where T: AsyncWrite, U: Encoder<I>, { let mut this = self.as_mut().project(); tracing::trace!("flushing framed transport"); while !this.write_buf.is_empty() { tracing::trace!("writing; remaining={}", this.write_buf.len()); let n = ready!(this.io.as_mut().poll_write(cx, this.write_buf))?; if n == 0 { return Poll::Ready(Err(io::Error::new( io::ErrorKind::WriteZero, "failed to write frame to transport", ) .into())); } // remove written data this.write_buf.advance(n); } // Try flushing the underlying IO ready!(this.io.poll_flush(cx))?; tracing::trace!("framed transport flushed"); Poll::Ready(Ok(())) } /// Flush write buffer and shutdown underlying I/O stream. pub fn close<I>(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>> where T: AsyncWrite, U: Encoder<I>, { let mut this = self.as_mut().project(); ready!(this.io.as_mut().poll_flush(cx))?; ready!(this.io.as_mut().poll_shutdown(cx))?; Poll::Ready(Ok(())) } } impl<T, U> Stream for Framed<T, U> where T: AsyncRead, U: Decoder, { type Item = Result<U::Item, U::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.next_item(cx) } } impl<T, U, I> Sink<I> for Framed<T, U> where T: AsyncWrite, U: Encoder<I>, U::Error: From<io::Error>, { type Error = U::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { if self.is_write_ready() { Poll::Ready(Ok(())) } else { self.flush(cx) } } fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> { self.write(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.close(cx) } } impl<T, U> fmt::Debug for Framed<T, U> where T: fmt::Debug, U: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Framed") .field("io", &self.io) .field("codec", &self.codec) .finish() } } impl<T, U> Framed<T, U> { /// This function returns a *single* object that is both `Stream` and `Sink`; grouping this into /// a single object is often useful for layering things like gzip or TLS, which require both /// read and write access to the underlying object. /// /// These objects take a stream, a read buffer and a write buffer. These fields can be obtained /// from an existing `Framed` with the `into_parts` method. pub fn from_parts(parts: FramedParts<T, U>) -> Framed<T, U> { Framed { io: parts.io, codec: parts.codec, flags: parts.flags, write_buf: parts.write_buf, read_buf: parts.read_buf, } } /// Consumes the `Frame`, returning its underlying I/O stream, the buffer with unprocessed data, /// and the codec. /// /// Note that care should be taken to not tamper with the underlying stream of data coming in as /// it may corrupt the stream of frames otherwise being worked with. pub fn into_parts(self) -> FramedParts<T, U> { FramedParts { io: self.io, codec: self.codec, flags: self.flags, read_buf: self.read_buf, write_buf: self.write_buf, } } } /// `FramedParts` contains an export of the data of a Framed transport. /// /// It can be used to construct a new `Framed` with a different codec. It contains all current /// buffers and the inner transport. #[derive(Debug)] pub struct FramedParts<T, U> { /// The inner transport used to read bytes to and write bytes to. pub io: T, /// The codec object. pub codec: U, /// The buffer with read but unprocessed data. pub read_buf: BytesMut, /// A buffer with unprocessed data which are not written yet. pub write_buf: BytesMut, flags: Flags, } impl<T, U> FramedParts<T, U> { /// Creates a new default `FramedParts`. pub fn new(io: T, codec: U) -> FramedParts<T, U> { FramedParts { io, codec, flags: Flags::empty(), read_buf: BytesMut::new(), write_buf: BytesMut::new(), } } /// Creates a new `FramedParts` with read buffer. pub fn with_read_buf(io: T, codec: U, read_buf: BytesMut) -> FramedParts<T, U> { FramedParts { io, codec, read_buf, flags: Flags::empty(), write_buf: BytesMut::new(), } } }
//! Codec utilities for working with framed protocols. //! //! Contains adapters to go from streams of bytes, [`AsyncRead`] and [`AsyncWrite`], to framed //! streams implementing [`Sink`] and [`Stream`]. Framed streams are also known as `transports`. //! //! [`Sink`]: futures_sink::Sink //! [`Stream`]: futures_core::Stream #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible, missing_docs)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] pub use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; pub use tokio_util::{ codec::{Decoder, Encoder}, io::poll_read_buf, }; mod bcodec; mod framed; mod lines; pub use self::{ bcodec::BytesCodec, framed::{Framed, FramedParts}, lines::LinesCodec, };
use std::io; use bytes::{Buf, BufMut, Bytes, BytesMut}; use memchr::memchr; use super::{Decoder, Encoder}; /// Lines codec. Reads/writes line delimited strings. /// /// Will split input up by LF or CRLF delimiters. Carriage return characters at the end of lines are /// not preserved. #[derive(Debug, Copy, Clone, Default)] #[non_exhaustive] pub struct LinesCodec; impl<T: AsRef<str>> Encoder<T> for LinesCodec { type Error = io::Error; #[inline] fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error> { let item = item.as_ref(); dst.reserve(item.len() + 1); dst.put_slice(item.as_bytes()); dst.put_u8(b'\n'); Ok(()) } } impl Decoder for LinesCodec { type Item = String; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { if src.is_empty() { return Ok(None); } let len = match memchr(b'\n', src) { Some(n) => n, None => { return Ok(None); } }; // split up to new line char let mut buf = src.split_to(len); debug_assert_eq!(len, buf.len()); // remove new line char from source src.advance(1); match buf.last() { // remove carriage returns at the end of buf Some(b'\r') => buf.truncate(len - 1), // line is empty None => return Ok(Some(String::new())), _ => {} } try_into_utf8(buf.freeze()) } fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { match self.decode(src)? { Some(frame) => Ok(Some(frame)), None if src.is_empty() => Ok(None), None => { let buf = match src.last() { // if last line ends in a CR then take everything up to it Some(b'\r') => src.split_to(src.len() - 1), // take all bytes from source _ => src.split(), }; if buf.is_empty() { return Ok(None); } try_into_utf8(buf.freeze()) } } } } // Attempts to convert bytes into a `String`. fn try_into_utf8(buf: Bytes) -> io::Result<Option<String>> { String::from_utf8(buf.to_vec()) .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) .map(Some) } #[cfg(test)] mod tests { use bytes::BufMut as _; use super::*; #[test] fn lines_decoder() { let mut codec = LinesCodec::default(); let mut buf = BytesMut::from("\nline 1\nline 2\r\nline 3\n\r\n\r"); assert_eq!("", codec.decode(&mut buf).unwrap().unwrap()); assert_eq!("line 1", codec.decode(&mut buf).unwrap().unwrap()); assert_eq!("line 2", codec.decode(&mut buf).unwrap().unwrap()); assert_eq!("line 3", codec.decode(&mut buf).unwrap().unwrap()); assert_eq!("", codec.decode(&mut buf).unwrap().unwrap()); assert!(codec.decode(&mut buf).unwrap().is_none()); assert!(codec.decode_eof(&mut buf).unwrap().is_none()); buf.put_slice(b"k"); assert!(codec.decode(&mut buf).unwrap().is_none()); assert_eq!("\rk", codec.decode_eof(&mut buf).unwrap().unwrap()); assert!(codec.decode(&mut buf).unwrap().is_none()); assert!(codec.decode_eof(&mut buf).unwrap().is_none()); } #[test] fn lines_encoder() { let mut codec = LinesCodec::default(); let mut buf = BytesMut::new(); codec.encode("", &mut buf).unwrap(); assert_eq!(&buf[..], b"\n"); codec.encode("test", &mut buf).unwrap(); assert_eq!(&buf[..], b"\ntest\n"); codec.encode("a\nb", &mut buf).unwrap(); assert_eq!(&buf[..], b"\ntest\na\nb\n"); } #[test] fn lines_encoder_no_overflow() { let mut codec = LinesCodec::default(); let mut buf = BytesMut::new(); codec.encode("1234567", &mut buf).unwrap(); assert_eq!(&buf[..], b"1234567\n"); let mut buf = BytesMut::new(); codec.encode("12345678", &mut buf).unwrap(); assert_eq!(&buf[..], b"12345678\n"); let mut buf = BytesMut::new(); codec.encode("123456789111213", &mut buf).unwrap(); assert_eq!(&buf[..], b"123456789111213\n"); let mut buf = BytesMut::new(); codec.encode("1234567891112131", &mut buf).unwrap(); assert_eq!(&buf[..], b"1234567891112131\n"); } }
use std::{ collections::VecDeque, io::{self, Write}, pin::Pin, task::{ Context, Poll::{self, Pending, Ready}, }, }; use actix_codec::*; use bytes::{Buf as _, BufMut as _, BytesMut}; use futures_sink::Sink; use tokio_test::{assert_ready, task}; macro_rules! bilateral { ($($x:expr,)*) => {{ let mut v = VecDeque::new(); v.extend(vec![$($x),*]); Bilateral { calls: v } }}; } macro_rules! assert_ready { ($e:expr) => {{ use core::task::Poll::*; match $e { Ready(v) => v, Pending => panic!("pending"), } }}; ($e:expr, $($msg:tt),+) => {{ use core::task::Poll::*; match $e { Ready(v) => v, Pending => { let msg = format_args!($($msg),+); panic!("pending; {}", msg) } } }}; } #[derive(Debug)] pub struct Bilateral { pub calls: VecDeque<io::Result<Vec<u8>>>, } impl Write for Bilateral { fn write(&mut self, src: &[u8]) -> io::Result<usize> { match self.calls.pop_front() { Some(Ok(data)) => { assert!(src.len() >= data.len()); assert_eq!(&data[..], &src[..data.len()]); Ok(data.len()) } Some(Err(err)) => Err(err), None => panic!("unexpected write; {:?}", src), } } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl AsyncWrite for Bilateral { fn poll_write( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { match Pin::get_mut(self).write(buf) { Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Pending, other => Ready(other), } } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { match Pin::get_mut(self).flush() { Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Pending, other => Ready(other), } } fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { unimplemented!() } } impl AsyncRead for Bilateral { fn poll_read( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<(), std::io::Error>> { use io::ErrorKind::WouldBlock; match self.calls.pop_front() { Some(Ok(data)) => { debug_assert!(buf.remaining() >= data.len()); buf.put_slice(&data); Ready(Ok(())) } Some(Err(ref err)) if err.kind() == WouldBlock => Pending, Some(Err(err)) => Ready(Err(err)), None => Ready(Ok(())), } } } pub struct U32; impl Encoder<u32> for U32 { type Error = io::Error; fn encode(&mut self, item: u32, dst: &mut BytesMut) -> io::Result<()> { // Reserve space dst.reserve(4); dst.put_u32(item); Ok(()) } } impl Decoder for U32 { type Item = u32; type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<u32>> { if buf.len() < 4 { return Ok(None); } let n = buf.split_to(4).get_u32(); Ok(Some(n)) } } #[test] fn test_write_hits_highwater_mark() { // see here for what this test is based on: // https://github.com/tokio-rs/tokio/blob/75c07770bfbfea4e5fd914af819c741ed9c3fc36/tokio-util/tests/framed_write.rs#L69 const ITER: usize = 2 * 1024; let mut bi = bilateral! { Err(io::Error::new(io::ErrorKind::WouldBlock, "not ready")), Ok(b"".to_vec()), }; for i in 0..=ITER { let mut b = BytesMut::with_capacity(4); b.put_u32(i as u32); // Append to the end match bi.calls.back_mut().unwrap() { Ok(ref mut data) => { // Write in 2kb chunks if data.len() < ITER { data.extend_from_slice(&b[..]); continue; } // else fall through and create a new buffer } _ => unreachable!(), } // Push a new new chunk bi.calls.push_back(Ok(b[..].to_vec())); } assert_eq!(bi.calls.len(), 6); let mut framed = Framed::new(bi, U32); // Send 8KB. This fills up FramedWrite2 buffer let mut task = task::spawn(()); task.enter(|cx, _| { // Send 8KB. This fills up Framed buffer for i in 0..ITER { { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); assert!(assert_ready!(framed.poll_ready(cx)).is_ok()); } #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // write the buffer assert!(framed.start_send(i as u32).is_ok()); } { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // Now we poll_ready which forces a flush. The bilateral pops the front message // and decides to block. assert!(framed.poll_ready(cx).is_pending()); } { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // We poll again, forcing another flush, which this time succeeds // The whole 8KB buffer is flushed assert!(assert_ready!(framed.poll_ready(cx)).is_ok()); } { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // Send more data. This matches the final message expected by the bilateral assert!(framed.start_send(ITER as u32).is_ok()); } { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // Flush the rest of the buffer assert!(assert_ready!(framed.poll_flush(cx)).is_ok()); } // Ensure the mock is empty assert_eq!(0, Pin::new(&framed).get_ref().io_ref().calls.len()); }); }
use std::time::SystemTime; use actix_http::header::HttpDate; use divan::{black_box, AllocProfiler, Bencher}; #[global_allocator] static ALLOC: AllocProfiler = AllocProfiler::system(); #[divan::bench] fn date_formatting(b: Bencher<'_, '_>) { let now = SystemTime::now(); b.bench(|| { black_box(HttpDate::from(black_box(now)).to_string()); }) } fn main() { divan::main(); }
use std::convert::Infallible; use actix_http::{encoding::Encoder, ContentEncoding, Request, Response, StatusCode}; use actix_service::{fn_service, Service as _}; use criterion::{black_box, criterion_group, criterion_main, Criterion}; static BODY: &[u8] = include_bytes!("../Cargo.toml"); fn compression_responses(c: &mut Criterion) { let mut group = c.benchmark_group("compression responses"); group.bench_function("identity", |b| { let rt = actix_rt::Runtime::new().unwrap(); let identity_svc = fn_service(|_: Request| async move { let mut res = Response::with_body(StatusCode::OK, ()); let body = black_box(Encoder::response( ContentEncoding::Identity, res.head_mut(), BODY, )); Ok::<_, Infallible>(black_box(res.set_body(black_box(body)))) }); b.iter(|| { rt.block_on(identity_svc.call(Request::new())).unwrap(); }); }); group.bench_function("gzip", |b| { let rt = actix_rt::Runtime::new().unwrap(); let identity_svc = fn_service(|_: Request| async move { let mut res = Response::with_body(StatusCode::OK, ()); let body = black_box(Encoder::response( ContentEncoding::Gzip, res.head_mut(), BODY, )); Ok::<_, Infallible>(black_box(res.set_body(black_box(body)))) }); b.iter(|| { rt.block_on(identity_svc.call(Request::new())).unwrap(); }); }); group.bench_function("br", |b| { let rt = actix_rt::Runtime::new().unwrap(); let identity_svc = fn_service(|_: Request| async move { let mut res = Response::with_body(StatusCode::OK, ()); let body = black_box(Encoder::response( ContentEncoding::Brotli, res.head_mut(), BODY, )); Ok::<_, Infallible>(black_box(res.set_body(black_box(body)))) }); b.iter(|| { rt.block_on(identity_svc.call(Request::new())).unwrap(); }); }); group.bench_function("zstd", |b| { let rt = actix_rt::Runtime::new().unwrap(); let identity_svc = fn_service(|_: Request| async move { let mut res = Response::with_body(StatusCode::OK, ()); let body = black_box(Encoder::response( ContentEncoding::Zstd, res.head_mut(), BODY, )); Ok::<_, Infallible>(black_box(res.set_body(black_box(body)))) }); b.iter(|| { rt.block_on(identity_svc.call(Request::new())).unwrap(); }); }); group.finish(); } criterion_group!(benches, compression_responses); criterion_main!(benches);
use actix_http::HttpService; use actix_server::Server; use actix_service::map_config; use actix_web::{dev::AppConfig, get, App, Responder}; #[get("/")] async fn index() -> impl Responder { "Hello, world. From Actix Web!" } #[tokio::main(flavor = "current_thread")] async fn main() -> std::io::Result<()> { Server::build() .bind("hello-world", "127.0.0.1:8080", || { // construct actix-web app let app = App::new().service(index); HttpService::build() // pass the app to service builder // map_config is used to map App's configuration to ServiceBuilder // h1 will configure server to only use HTTP/1.1 .h1(map_config(app, |_| AppConfig::default())) .tcp() })? .run() .await }
use std::{convert::Infallible, io, time::Duration}; use actix_http::{HttpService, Request, Response, StatusCode}; use actix_server::Server; use once_cell::sync::Lazy; static STR: Lazy<String> = Lazy::new(|| "HELLO WORLD ".repeat(20)); #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); Server::build() .bind("dispatcher-benchmark", ("127.0.0.1", 8080), || { HttpService::build() .client_request_timeout(Duration::from_secs(1)) .finish(|_: Request| async move { let mut res = Response::build(StatusCode::OK); Ok::<_, Infallible>(res.body(&**STR)) }) .tcp() })? // limiting number of workers so that bench client is not sharing as many resources .workers(4) .run() .await }
use std::{io, time::Duration}; use actix_http::{Error, HttpService, Request, Response, StatusCode}; use actix_server::Server; use bytes::BytesMut; use futures_util::StreamExt as _; use http::header::HeaderValue; use tracing::info; #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); Server::build() .bind("echo", ("127.0.0.1", 8080), || { HttpService::build() .client_request_timeout(Duration::from_secs(1)) .client_disconnect_timeout(Duration::from_secs(1)) // handles HTTP/1.1 and HTTP/2 .finish(|mut req: Request| async move { let mut body = BytesMut::new(); while let Some(item) = req.payload().next().await { body.extend_from_slice(&item?); } info!("request body: {body:?}"); let res = Response::build(StatusCode::OK) .insert_header(("x-head", HeaderValue::from_static("dummy value!"))) .body(body); Ok::<_, Error>(res) }) .tcp() // No TLS })? .run() .await }
use std::io; use actix_http::{ body::{BodyStream, MessageBody}, header, Error, HttpMessage, HttpService, Request, Response, StatusCode, }; async fn handle_request(mut req: Request) -> Result<Response<impl MessageBody>, Error> { let mut res = Response::build(StatusCode::OK); if let Some(ct) = req.headers().get(header::CONTENT_TYPE) { res.insert_header((header::CONTENT_TYPE, ct)); } // echo request payload stream as (chunked) response body let res = res.message_body(BodyStream::new(req.payload().take()))?; Ok(res) } #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); actix_server::Server::build() .bind("echo", ("127.0.0.1", 8080), || { HttpService::build() // handles HTTP/1.1 only .h1(handle_request) // No TLS .tcp() })? .run() .await }
//! An example that supports automatic selection of plaintext h1/h2c connections. //! //! Notably, both the following commands will work. //! ```console //! $ curl --http1.1 'http://localhost:8080/' //! $ curl --http2-prior-knowledge 'http://localhost:8080/' //! ``` use std::{convert::Infallible, io}; use actix_http::{body::BodyStream, HttpService, Request, Response, StatusCode}; use actix_server::Server; #[tokio::main(flavor = "current_thread")] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); Server::build() .bind("h2c-detect", ("127.0.0.1", 8080), || { HttpService::build() .finish(|_req: Request| async move { Ok::<_, Infallible>(Response::build(StatusCode::OK).body(BodyStream::new( futures_util::stream::iter([ Ok::<_, String>("123".into()), Err("wertyuikmnbvcxdfty6t".to_owned()), ]), ))) }) .tcp_auto_h2c() })? .workers(2) .run() .await }
use std::{convert::Infallible, io}; use actix_http::{HttpService, Request, Response, StatusCode}; use actix_server::Server; use once_cell::sync::Lazy; static STR: Lazy<String> = Lazy::new(|| "HELLO WORLD ".repeat(100)); #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); Server::build() .bind("h2spec", ("127.0.0.1", 8080), || { HttpService::build() .h2(|_: Request| async move { let mut res = Response::build(StatusCode::OK); Ok::<_, Infallible>(res.body(&**STR)) }) .tcp() })? .workers(4) .run() .await }
use std::{convert::Infallible, io, time::Duration}; use actix_http::{header::HeaderValue, HttpService, Request, Response, StatusCode}; use actix_server::Server; use tracing::info; #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); Server::build() .bind("hello-world", ("127.0.0.1", 8080), || { HttpService::build() .client_request_timeout(Duration::from_secs(1)) .client_disconnect_timeout(Duration::from_secs(1)) .on_connect_ext(|_, ext| { ext.insert(42u32); }) .finish(|req: Request| async move { info!("{req:?}"); let mut res = Response::build(StatusCode::OK); res.insert_header(("x-head", HeaderValue::from_static("dummy value!"))); let forty_two = req.conn_data::<u32>().unwrap().to_string(); res.insert_header(("x-forty-two", HeaderValue::from_str(&forty_two).unwrap())); Ok::<_, Infallible>(res.body("Hello world!")) }) .tcp() })? .run() .await }
//! Example showing response body (chunked) stream erroring. //! //! Test using `nc` or `curl`. //! ```sh //! $ curl -vN 127.0.0.1:8080 //! $ echo 'GET / HTTP/1.1\n\n' | nc 127.0.0.1 8080 //! ``` use std::{convert::Infallible, io, time::Duration}; use actix_http::{body::BodyStream, HttpService, Response}; use actix_server::Server; use async_stream::stream; use bytes::Bytes; use tracing::info; #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); Server::build() .bind("streaming-error", ("127.0.0.1", 8080), || { HttpService::build() .finish(|req| async move { info!("{req:?}"); let res = Response::ok(); Ok::<_, Infallible>(res.set_body(BodyStream::new(stream! { yield Ok(Bytes::from("123")); yield Ok(Bytes::from("456")); actix_rt::time::sleep(Duration::from_secs(1)).await; yield Err(io::Error::new(io::ErrorKind::Other, "abc")); }))) }) .tcp() })? .run() .await }
//! Demonstrates TLS configuration (via Rustls) for HTTP/1.1 and HTTP/2 connections. //! //! Test using cURL: //! //! ```console //! $ curl --insecure https://127.0.0.1:8443 //! Hello World! //! Protocol: HTTP/2.0 //! //! $ curl --insecure --http1.1 https://127.0.0.1:8443 //! Hello World! //! Protocol: HTTP/1.1 //! ``` extern crate tls_rustls_023 as rustls; use std::io; use actix_http::{Error, HttpService, Request, Response}; use actix_utils::future::ok; #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); tracing::info!("starting HTTP server at https://127.0.0.1:8443"); actix_server::Server::build() .bind("echo", ("127.0.0.1", 8443), || { HttpService::build() .finish(|req: Request| { let body = format!( "Hello World!\n\ Protocol: {:?}", req.head().version ); ok::<_, Error>(Response::ok().set_body(body)) }) .rustls_0_23(rustls_config()) })? .run() .await } fn rustls_config() -> rustls::ServerConfig { let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(["localhost".to_owned()]).unwrap(); let cert_file = cert.pem(); let key_file = key_pair.serialize_pem(); let cert_file = &mut io::BufReader::new(cert_file.as_bytes()); let key_file = &mut io::BufReader::new(key_file.as_bytes()); let cert_chain = rustls_pemfile::certs(cert_file) .collect::<Result<Vec<_>, _>>() .unwrap(); let mut keys = rustls_pemfile::pkcs8_private_keys(key_file) .collect::<Result<Vec<_>, _>>() .unwrap(); let mut config = rustls::ServerConfig::builder() .with_no_client_auth() .with_single_cert( cert_chain, rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)), ) .unwrap(); const H1_ALPN: &[u8] = b"http/1.1"; const H2_ALPN: &[u8] = b"h2"; config.alpn_protocols.push(H2_ALPN.to_vec()); config.alpn_protocols.push(H1_ALPN.to_vec()); config }
//! Sets up a WebSocket server over TCP and TLS. //! Sends a heartbeat message every 4 seconds but does not respond to any incoming frames. extern crate tls_rustls_023 as rustls; use std::{ io, pin::Pin, task::{Context, Poll}, time::Duration, }; use actix_http::{body::BodyStream, error::Error, ws, HttpService, Request, Response}; use actix_rt::time::{interval, Interval}; use actix_server::Server; use bytes::{Bytes, BytesMut}; use bytestring::ByteString; use futures_core::{ready, Stream}; use tokio_util::codec::Encoder; #[actix_rt::main] async fn main() -> io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); Server::build() .bind("tcp", ("127.0.0.1", 8080), || { HttpService::build().h1(handler).tcp() })? .bind("tls", ("127.0.0.1", 8443), || { HttpService::build() .finish(handler) .rustls_0_23(tls_config()) })? .run() .await } async fn handler(req: Request) -> Result<Response<BodyStream<Heartbeat>>, Error> { tracing::info!("handshaking"); let mut res = ws::handshake(req.head())?; // handshake will always fail under HTTP/2 tracing::info!("responding"); res.message_body(BodyStream::new(Heartbeat::new(ws::Codec::new()))) } struct Heartbeat { codec: ws::Codec, interval: Interval, } impl Heartbeat { fn new(codec: ws::Codec) -> Self { Self { codec, interval: interval(Duration::from_secs(4)), } } } impl Stream for Heartbeat { type Item = Result<Bytes, Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { tracing::trace!("poll"); ready!(self.as_mut().interval.poll_tick(cx)); let mut buffer = BytesMut::new(); self.as_mut() .codec .encode( ws::Message::Text(ByteString::from_static("hello world")), &mut buffer, ) .unwrap(); Poll::Ready(Some(Ok(buffer.freeze()))) } } fn tls_config() -> rustls::ServerConfig { use std::io::BufReader; use rustls_pemfile::{certs, pkcs8_private_keys}; let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(["localhost".to_owned()]).unwrap(); let cert_file = cert.pem(); let key_file = key_pair.serialize_pem(); let cert_file = &mut BufReader::new(cert_file.as_bytes()); let key_file = &mut BufReader::new(key_file.as_bytes()); let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap(); let mut keys = pkcs8_private_keys(key_file) .collect::<Result<Vec<_>, _>>() .unwrap(); let mut config = rustls::ServerConfig::builder() .with_no_client_auth() .with_single_cert( cert_chain, rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)), ) .unwrap(); config.alpn_protocols.push(b"http/1.1".to_vec()); config.alpn_protocols.push(b"h2".to_vec()); config }
use std::{ error::Error as StdError, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use futures_core::{ready, Stream}; use pin_project_lite::pin_project; use super::{BodySize, MessageBody}; pin_project! { /// Streaming response wrapper. /// /// Response does not contain `Content-Length` header and appropriate transfer encoding is used. pub struct BodyStream<S> { #[pin] stream: S, } } // TODO: from_infallible method impl<S, E> BodyStream<S> where S: Stream<Item = Result<Bytes, E>>, E: Into<Box<dyn StdError>> + 'static, { #[inline] pub fn new(stream: S) -> Self { BodyStream { stream } } } impl<S, E> MessageBody for BodyStream<S> where S: Stream<Item = Result<Bytes, E>>, E: Into<Box<dyn StdError>> + 'static, { type Error = E; #[inline] fn size(&self) -> BodySize { BodySize::Stream } /// Attempts to pull out the next value of the underlying [`Stream`]. /// /// Empty values are skipped to prevent [`BodyStream`]'s transmission being ended on a /// zero-length chunk, but rather proceed until the underlying [`Stream`] ends. fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { loop { let stream = self.as_mut().project().stream; let chunk = match ready!(stream.poll_next(cx)) { Some(Ok(ref bytes)) if bytes.is_empty() => continue, opt => opt, }; return Poll::Ready(chunk); } } } #[cfg(test)] mod tests { use std::{convert::Infallible, time::Duration}; use actix_rt::{ pin, time::{sleep, Sleep}, }; use actix_utils::future::poll_fn; use derive_more::{Display, Error}; use futures_core::ready; use futures_util::{stream, FutureExt as _}; use pin_project_lite::pin_project; use static_assertions::{assert_impl_all, assert_not_impl_any}; use super::*; use crate::body::to_bytes; assert_impl_all!(BodyStream<stream::Empty<Result<Bytes, crate::Error>>>: MessageBody); assert_impl_all!(BodyStream<stream::Empty<Result<Bytes, &'static str>>>: MessageBody); assert_impl_all!(BodyStream<stream::Repeat<Result<Bytes, &'static str>>>: MessageBody); assert_impl_all!(BodyStream<stream::Empty<Result<Bytes, Infallible>>>: MessageBody); assert_impl_all!(BodyStream<stream::Repeat<Result<Bytes, Infallible>>>: MessageBody); assert_not_impl_any!(BodyStream<stream::Empty<Bytes>>: MessageBody); assert_not_impl_any!(BodyStream<stream::Repeat<Bytes>>: MessageBody); // crate::Error is not Clone assert_not_impl_any!(BodyStream<stream::Repeat<Result<Bytes, crate::Error>>>: MessageBody); #[actix_rt::test] async fn skips_empty_chunks() { let body = BodyStream::new(stream::iter( ["1", "", "2"] .iter() .map(|&v| Ok::<_, Infallible>(Bytes::from(v))), )); pin!(body); assert_eq!( poll_fn(|cx| body.as_mut().poll_next(cx)) .await .unwrap() .ok(), Some(Bytes::from("1")), ); assert_eq!( poll_fn(|cx| body.as_mut().poll_next(cx)) .await .unwrap() .ok(), Some(Bytes::from("2")), ); } #[actix_rt::test] async fn read_to_bytes() { let body = BodyStream::new(stream::iter( ["1", "", "2"] .iter() .map(|&v| Ok::<_, Infallible>(Bytes::from(v))), )); assert_eq!(to_bytes(body).await.ok(), Some(Bytes::from("12"))); } #[derive(Debug, Display, Error)] #[display("stream error")] struct StreamErr; #[actix_rt::test] async fn stream_immediate_error() { let body = BodyStream::new(stream::once(async { Err(StreamErr) })); assert!(matches!(to_bytes(body).await, Err(StreamErr))); } #[actix_rt::test] async fn stream_string_error() { // `&'static str` does not impl `Error` // but it does impl `Into<Box<dyn Error>>` let body = BodyStream::new(stream::once(async { Err("stringy error") })); assert!(matches!(to_bytes(body).await, Err("stringy error"))); } #[actix_rt::test] async fn stream_boxed_error() { // `Box<dyn Error>` does not impl `Error` // but it does impl `Into<Box<dyn Error>>` let body = BodyStream::new(stream::once(async { Err(Box::<dyn StdError>::from("stringy error")) })); assert_eq!( to_bytes(body).await.unwrap_err().to_string(), "stringy error" ); } #[actix_rt::test] async fn stream_delayed_error() { let body = BodyStream::new(stream::iter(vec![Ok(Bytes::from("1")), Err(StreamErr)])); assert!(matches!(to_bytes(body).await, Err(StreamErr))); pin_project! { #[derive(Debug)] #[project = TimeDelayStreamProj] enum TimeDelayStream { Start, Sleep { delay: Pin<Box<Sleep>> }, Done, } } impl Stream for TimeDelayStream { type Item = Result<Bytes, StreamErr>; fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Self::Item>> { match self.as_mut().get_mut() { TimeDelayStream::Start => { let sleep = sleep(Duration::from_millis(1)); self.as_mut().set(TimeDelayStream::Sleep { delay: Box::pin(sleep), }); cx.waker().wake_by_ref(); Poll::Pending } TimeDelayStream::Sleep { ref mut delay } => { ready!(delay.poll_unpin(cx)); self.set(TimeDelayStream::Done); cx.waker().wake_by_ref(); Poll::Pending } TimeDelayStream::Done => Poll::Ready(Some(Err(StreamErr))), } } } let body = BodyStream::new(TimeDelayStream::Start); assert!(matches!(to_bytes(body).await, Err(StreamErr))); } }
use std::{ error::Error as StdError, fmt, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use super::{BodySize, MessageBody, MessageBodyMapErr}; use crate::body; /// A boxed message body with boxed errors. #[derive(Debug)] pub struct BoxBody(BoxBodyInner); enum BoxBodyInner { None(body::None), Bytes(Bytes), Stream(Pin<Box<dyn MessageBody<Error = Box<dyn StdError>>>>), } impl fmt::Debug for BoxBodyInner { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::None(arg0) => f.debug_tuple("None").field(arg0).finish(), Self::Bytes(arg0) => f.debug_tuple("Bytes").field(arg0).finish(), Self::Stream(_) => f.debug_tuple("Stream").field(&"dyn MessageBody").finish(), } } } impl BoxBody { /// Boxes body type, erasing type information. /// /// If the body type to wrap is unknown or generic it is better to use [`MessageBody::boxed`] to /// avoid double boxing. #[inline] pub fn new<B>(body: B) -> Self where B: MessageBody + 'static, { match body.size() { BodySize::None => Self(BoxBodyInner::None(body::None)), _ => match body.try_into_bytes() { Ok(bytes) => Self(BoxBodyInner::Bytes(bytes)), Err(body) => { let body = MessageBodyMapErr::new(body, Into::into); Self(BoxBodyInner::Stream(Box::pin(body))) } }, } } /// Returns a mutable pinned reference to the inner message body type. #[inline] pub fn as_pin_mut(&mut self) -> Pin<&mut Self> { Pin::new(self) } } impl MessageBody for BoxBody { type Error = Box<dyn StdError>; #[inline] fn size(&self) -> BodySize { match &self.0 { BoxBodyInner::None(none) => none.size(), BoxBodyInner::Bytes(bytes) => bytes.size(), BoxBodyInner::Stream(stream) => stream.size(), } } #[inline] fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { match &mut self.0 { BoxBodyInner::None(body) => Pin::new(body).poll_next(cx).map_err(|err| match err {}), BoxBodyInner::Bytes(body) => Pin::new(body).poll_next(cx).map_err(|err| match err {}), BoxBodyInner::Stream(body) => Pin::new(body).poll_next(cx), } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { match self.0 { BoxBodyInner::None(body) => Ok(body.try_into_bytes().unwrap()), BoxBodyInner::Bytes(body) => Ok(body.try_into_bytes().unwrap()), _ => Err(self), } } #[inline] fn boxed(self) -> BoxBody { self } } #[cfg(test)] mod tests { use static_assertions::{assert_impl_all, assert_not_impl_any}; use super::*; use crate::body::to_bytes; assert_impl_all!(BoxBody: fmt::Debug, MessageBody, Unpin); assert_not_impl_any!(BoxBody: Send, Sync); #[actix_rt::test] async fn nested_boxed_body() { let body = Bytes::from_static(&[1, 2, 3]); let boxed_body = BoxBody::new(BoxBody::new(body)); assert_eq!( to_bytes(boxed_body).await.unwrap(), Bytes::from(vec![1, 2, 3]), ); } }
use std::{ pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use pin_project_lite::pin_project; use super::{BodySize, BoxBody, MessageBody}; use crate::Error; pin_project! { /// An "either" type specialized for body types. /// /// It is common, in middleware especially, to conditionally return an inner service's unknown/ /// generic body `B` type or return early with a new response. This type's "right" variant /// defaults to `BoxBody` since error responses are the common case. /// /// For example, middleware will often have `type Response = ServiceResponse<EitherBody<B>>`. /// This means that the inner service's response body type maps to the `Left` variant and the /// middleware's own error responses use the default `Right` variant of `BoxBody`. Of course, /// there's no reason it couldn't use `EitherBody<B, String>` instead if its alternative /// responses have a known type. #[project = EitherBodyProj] #[derive(Debug, Clone)] pub enum EitherBody<L, R = BoxBody> { /// A body of type `L`. Left { #[pin] body: L }, /// A body of type `R`. Right { #[pin] body: R }, } } impl<L> EitherBody<L, BoxBody> { /// Creates new `EitherBody` left variant with a boxed right variant. /// /// If the expected `R` type will be inferred and is not `BoxBody` then use the /// [`left`](Self::left) constructor instead. #[inline] pub fn new(body: L) -> Self { Self::Left { body } } } impl<L, R> EitherBody<L, R> { /// Creates new `EitherBody` using left variant. #[inline] pub fn left(body: L) -> Self { Self::Left { body } } /// Creates new `EitherBody` using right variant. #[inline] pub fn right(body: R) -> Self { Self::Right { body } } } impl<L, R> MessageBody for EitherBody<L, R> where L: MessageBody + 'static, R: MessageBody + 'static, { type Error = Error; #[inline] fn size(&self) -> BodySize { match self { EitherBody::Left { body } => body.size(), EitherBody::Right { body } => body.size(), } } #[inline] fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { match self.project() { EitherBodyProj::Left { body } => body .poll_next(cx) .map_err(|err| Error::new_body().with_cause(err)), EitherBodyProj::Right { body } => body .poll_next(cx) .map_err(|err| Error::new_body().with_cause(err)), } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { match self { EitherBody::Left { body } => body .try_into_bytes() .map_err(|body| EitherBody::Left { body }), EitherBody::Right { body } => body .try_into_bytes() .map_err(|body| EitherBody::Right { body }), } } #[inline] fn boxed(self) -> BoxBody { match self { EitherBody::Left { body } => body.boxed(), EitherBody::Right { body } => body.boxed(), } } } #[cfg(test)] mod tests { use super::*; #[test] fn type_parameter_inference() { let _body: EitherBody<(), _> = EitherBody::new(()); let _body: EitherBody<_, ()> = EitherBody::left(()); let _body: EitherBody<(), _> = EitherBody::right(()); } }
//! [`MessageBody`] trait and foreign implementations. use std::{ convert::Infallible, error::Error as StdError, mem, pin::Pin, task::{Context, Poll}, }; use bytes::{Bytes, BytesMut}; use futures_core::ready; use pin_project_lite::pin_project; use super::{BodySize, BoxBody}; /// An interface for types that can be used as a response body. /// /// It is not usually necessary to create custom body types, this trait is already [implemented for /// a large number of sensible body types](#foreign-impls) including: /// - Empty body: `()` /// - Text-based: `String`, `&'static str`, [`ByteString`](https://docs.rs/bytestring/1). /// - Byte-based: `Bytes`, `BytesMut`, `Vec<u8>`, `&'static [u8]`; /// - Streams: [`BodyStream`](super::BodyStream), [`SizedStream`](super::SizedStream) /// /// # Examples /// ``` /// # use std::convert::Infallible; /// # use std::task::{Poll, Context}; /// # use std::pin::Pin; /// # use bytes::Bytes; /// # use actix_http::body::{BodySize, MessageBody}; /// struct Repeat { /// chunk: String, /// n_times: usize, /// } /// /// impl MessageBody for Repeat { /// type Error = Infallible; /// /// fn size(&self) -> BodySize { /// BodySize::Sized((self.chunk.len() * self.n_times) as u64) /// } /// /// fn poll_next( /// self: Pin<&mut Self>, /// _cx: &mut Context<'_>, /// ) -> Poll<Option<Result<Bytes, Self::Error>>> { /// let payload_string = self.chunk.repeat(self.n_times); /// let payload_bytes = Bytes::from(payload_string); /// Poll::Ready(Some(Ok(payload_bytes))) /// } /// } /// ``` pub trait MessageBody { /// The type of error that will be returned if streaming body fails. /// /// Since it is not appropriate to generate a response mid-stream, it only requires `Error` for /// internal use and logging. type Error: Into<Box<dyn StdError>>; /// Body size hint. /// /// If [`BodySize::None`] is returned, optimizations that skip reading the body are allowed. fn size(&self) -> BodySize; /// Attempt to pull out the next chunk of body bytes. /// /// # Return Value /// Similar to the `Stream` interface, there are several possible return values, each indicating /// a distinct state: /// - `Poll::Pending` means that this body's next chunk is not ready yet. Implementations must /// ensure that the current task will be notified when the next chunk may be ready. /// - `Poll::Ready(Some(val))` means that the body has successfully produced a chunk, `val`, /// and may produce further values on subsequent `poll_next` calls. /// - `Poll::Ready(None)` means that the body is complete, and `poll_next` should not be /// invoked again. /// /// # Panics /// Once a body is complete (i.e., `poll_next` returned `Ready(None)`), calling its `poll_next` /// method again may panic, block forever, or cause other kinds of problems; this trait places /// no requirements on the effects of such a call. However, as the `poll_next` method is not /// marked unsafe, Rust’s usual rules apply: calls must never cause UB, regardless of its state. fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>>; /// Try to convert into the complete chunk of body bytes. /// /// Override this method if the complete body can be trivially extracted. This is useful for /// optimizations where `poll_next` calls can be avoided. /// /// Body types with [`BodySize::None`] are allowed to return empty `Bytes`. Although, if calling /// this method, it is recommended to check `size` first and return early. /// /// # Errors /// The default implementation will error and return the original type back to the caller for /// further use. #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> where Self: Sized, { Err(self) } /// Wraps this body into a `BoxBody`. /// /// No-op when called on a `BoxBody`, meaning there is no risk of double boxing when calling /// this on a generic `MessageBody`. Prefer this over [`BoxBody::new`] when a boxed body /// is required. #[inline] fn boxed(self) -> BoxBody where Self: Sized + 'static, { BoxBody::new(self) } } mod foreign_impls { use std::{borrow::Cow, ops::DerefMut}; use super::*; impl<B> MessageBody for &mut B where B: MessageBody + Unpin + ?Sized, { type Error = B::Error; fn size(&self) -> BodySize { (**self).size() } fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { Pin::new(&mut **self).poll_next(cx) } } impl MessageBody for Infallible { type Error = Infallible; fn size(&self) -> BodySize { match *self {} } fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { match *self {} } } impl MessageBody for () { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(0) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { Poll::Ready(None) } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(Bytes::new()) } } impl<B> MessageBody for Box<B> where B: MessageBody + Unpin + ?Sized, { type Error = B::Error; #[inline] fn size(&self) -> BodySize { self.as_ref().size() } #[inline] fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { Pin::new(self.get_mut().as_mut()).poll_next(cx) } } impl<T, B> MessageBody for Pin<T> where T: DerefMut<Target = B> + Unpin, B: MessageBody + ?Sized, { type Error = B::Error; #[inline] fn size(&self) -> BodySize { self.as_ref().size() } #[inline] fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { self.get_mut().as_mut().poll_next(cx) } } impl MessageBody for &'static [u8] { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { if self.is_empty() { Poll::Ready(None) } else { Poll::Ready(Some(Ok(Bytes::from_static(mem::take(self.get_mut()))))) } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(Bytes::from_static(self)) } } impl MessageBody for Bytes { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { if self.is_empty() { Poll::Ready(None) } else { Poll::Ready(Some(Ok(mem::take(self.get_mut())))) } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(self) } } impl MessageBody for BytesMut { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { if self.is_empty() { Poll::Ready(None) } else { Poll::Ready(Some(Ok(mem::take(self.get_mut()).freeze()))) } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(self.freeze()) } } impl MessageBody for Vec<u8> { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { if self.is_empty() { Poll::Ready(None) } else { Poll::Ready(Some(Ok(mem::take(self.get_mut()).into()))) } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(Bytes::from(self)) } } impl MessageBody for Cow<'static, [u8]> { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { if self.is_empty() { Poll::Ready(None) } else { let bytes = match mem::take(self.get_mut()) { Cow::Borrowed(b) => Bytes::from_static(b), Cow::Owned(b) => Bytes::from(b), }; Poll::Ready(Some(Ok(bytes))) } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { match self { Cow::Borrowed(b) => Ok(Bytes::from_static(b)), Cow::Owned(b) => Ok(Bytes::from(b)), } } } impl MessageBody for &'static str { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { if self.is_empty() { Poll::Ready(None) } else { let string = mem::take(self.get_mut()); let bytes = Bytes::from_static(string.as_bytes()); Poll::Ready(Some(Ok(bytes))) } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(Bytes::from_static(self.as_bytes())) } } impl MessageBody for String { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { if self.is_empty() { Poll::Ready(None) } else { let string = mem::take(self.get_mut()); Poll::Ready(Some(Ok(Bytes::from(string)))) } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(Bytes::from(self)) } } impl MessageBody for Cow<'static, str> { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { if self.is_empty() { Poll::Ready(None) } else { let bytes = match mem::take(self.get_mut()) { Cow::Borrowed(s) => Bytes::from_static(s.as_bytes()), Cow::Owned(s) => Bytes::from(s.into_bytes()), }; Poll::Ready(Some(Ok(bytes))) } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { match self { Cow::Borrowed(s) => Ok(Bytes::from_static(s.as_bytes())), Cow::Owned(s) => Ok(Bytes::from(s.into_bytes())), } } } impl MessageBody for bytestring::ByteString { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.len() as u64) } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { let string = mem::take(self.get_mut()); Poll::Ready(Some(Ok(string.into_bytes()))) } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(self.into_bytes()) } } } pin_project! { pub(crate) struct MessageBodyMapErr<B, F> { #[pin] body: B, mapper: Option<F>, } } impl<B, F, E> MessageBodyMapErr<B, F> where B: MessageBody, F: FnOnce(B::Error) -> E, { pub(crate) fn new(body: B, mapper: F) -> Self { Self { body, mapper: Some(mapper), } } } impl<B, F, E> MessageBody for MessageBodyMapErr<B, F> where B: MessageBody, F: FnOnce(B::Error) -> E, E: Into<Box<dyn StdError>>, { type Error = E; #[inline] fn size(&self) -> BodySize { self.body.size() } fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { let this = self.as_mut().project(); match ready!(this.body.poll_next(cx)) { Some(Err(err)) => { let f = self.as_mut().project().mapper.take().unwrap(); let mapped_err = (f)(err); Poll::Ready(Some(Err(mapped_err))) } Some(Ok(val)) => Poll::Ready(Some(Ok(val))), None => Poll::Ready(None), } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { let Self { body, mapper } = self; body.try_into_bytes().map_err(|body| Self { body, mapper }) } } #[cfg(test)] mod tests { use actix_rt::pin; use actix_utils::future::poll_fn; use futures_util::stream; use super::*; use crate::body::{self, EitherBody}; macro_rules! assert_poll_next { ($pin:expr, $exp:expr) => { assert_eq!( poll_fn(|cx| $pin.as_mut().poll_next(cx)) .await .unwrap() // unwrap option .unwrap(), // unwrap result $exp ); }; } macro_rules! assert_poll_next_none { ($pin:expr) => { assert!(poll_fn(|cx| $pin.as_mut().poll_next(cx)).await.is_none()); }; } #[allow(unused_allocation)] // triggered by `Box::new(()).size()` #[actix_rt::test] async fn boxing_equivalence() { assert_eq!(().size(), BodySize::Sized(0)); assert_eq!(().size(), Box::new(()).size()); assert_eq!(().size(), Box::pin(()).size()); let pl = Box::new(()); pin!(pl); assert_poll_next_none!(pl); let mut pl = Box::pin(()); assert_poll_next_none!(pl); } #[actix_rt::test] async fn mut_equivalence() { assert_eq!(().size(), BodySize::Sized(0)); assert_eq!(().size(), (&(&mut ())).size()); let pl = &mut (); pin!(pl); assert_poll_next_none!(pl); let pl = &mut Box::new(()); pin!(pl); assert_poll_next_none!(pl); let mut body = body::SizedStream::new( 8, stream::iter([ Ok::<_, std::io::Error>(Bytes::from("1234")), Ok(Bytes::from("5678")), ]), ); let body = &mut body; assert_eq!(body.size(), BodySize::Sized(8)); pin!(body); assert_poll_next!(body, Bytes::from_static(b"1234")); assert_poll_next!(body, Bytes::from_static(b"5678")); assert_poll_next_none!(body); } #[allow(clippy::let_unit_value)] #[actix_rt::test] async fn test_unit() { let pl = (); assert_eq!(pl.size(), BodySize::Sized(0)); pin!(pl); assert_poll_next_none!(pl); } #[actix_rt::test] async fn test_static_str() { assert_eq!("".size(), BodySize::Sized(0)); assert_eq!("test".size(), BodySize::Sized(4)); let pl = "test"; pin!(pl); assert_poll_next!(pl, Bytes::from("test")); } #[actix_rt::test] async fn test_static_bytes() { assert_eq!(b"".as_ref().size(), BodySize::Sized(0)); assert_eq!(b"test".as_ref().size(), BodySize::Sized(4)); let pl = b"test".as_ref(); pin!(pl); assert_poll_next!(pl, Bytes::from("test")); } #[actix_rt::test] async fn test_vec() { assert_eq!(vec![0; 0].size(), BodySize::Sized(0)); assert_eq!(Vec::from("test").size(), BodySize::Sized(4)); let pl = Vec::from("test"); pin!(pl); assert_poll_next!(pl, Bytes::from("test")); } #[actix_rt::test] async fn test_bytes() { assert_eq!(Bytes::new().size(), BodySize::Sized(0)); assert_eq!(Bytes::from_static(b"test").size(), BodySize::Sized(4)); let pl = Bytes::from_static(b"test"); pin!(pl); assert_poll_next!(pl, Bytes::from("test")); } #[actix_rt::test] async fn test_bytes_mut() { assert_eq!(BytesMut::new().size(), BodySize::Sized(0)); assert_eq!(BytesMut::from(b"test".as_ref()).size(), BodySize::Sized(4)); let pl = BytesMut::from("test"); pin!(pl); assert_poll_next!(pl, Bytes::from("test")); } #[actix_rt::test] async fn test_string() { assert_eq!(String::new().size(), BodySize::Sized(0)); assert_eq!("test".to_owned().size(), BodySize::Sized(4)); let pl = "test".to_owned(); pin!(pl); assert_poll_next!(pl, Bytes::from("test")); } #[actix_rt::test] async fn complete_body_combinators() { let body = Bytes::from_static(b"test"); let body = BoxBody::new(body); let body = EitherBody::<_, ()>::left(body); let body = EitherBody::<(), _>::right(body); // Do not support try_into_bytes: // let body = Box::new(body); // let body = Box::pin(body); assert_eq!(body.try_into_bytes().unwrap(), Bytes::from("test")); } #[actix_rt::test] async fn complete_body_combinators_poll() { let body = Bytes::from_static(b"test"); let body = BoxBody::new(body); let body = EitherBody::<_, ()>::left(body); let body = EitherBody::<(), _>::right(body); let mut body = body; assert_eq!(body.size(), BodySize::Sized(4)); assert_poll_next!(Pin::new(&mut body), Bytes::from("test")); assert_poll_next_none!(Pin::new(&mut body)); } #[actix_rt::test] async fn none_body_combinators() { fn none_body() -> BoxBody { let body = body::None; let body = BoxBody::new(body); let body = EitherBody::<_, ()>::left(body); let body = EitherBody::<(), _>::right(body); body.boxed() } assert_eq!(none_body().size(), BodySize::None); assert_eq!(none_body().try_into_bytes().unwrap(), Bytes::new()); assert_poll_next_none!(Pin::new(&mut none_body())); } // down-casting used to be done with a method on MessageBody trait // test is kept to demonstrate equivalence of Any trait #[actix_rt::test] async fn test_body_casting() { let mut body = String::from("hello cast"); // let mut resp_body: &mut dyn MessageBody<Error = Error> = &mut body; let resp_body: &mut dyn std::any::Any = &mut body; let body = resp_body.downcast_ref::<String>().unwrap(); assert_eq!(body, "hello cast"); let body = &mut resp_body.downcast_mut::<String>().unwrap(); body.push('!'); let body = resp_body.downcast_ref::<String>().unwrap(); assert_eq!(body, "hello cast!"); let not_body = resp_body.downcast_ref::<()>(); assert!(not_body.is_none()); } #[actix_rt::test] async fn non_owning_to_bytes() { let mut body = BoxBody::new(()); let bytes = body::to_bytes(&mut body).await.unwrap(); assert_eq!(bytes, Bytes::new()); let mut body = body::BodyStream::new(stream::iter([ Ok::<_, std::io::Error>(Bytes::from("1234")), Ok(Bytes::from("5678")), ])); let bytes = body::to_bytes(&mut body).await.unwrap(); assert_eq!(bytes, Bytes::from_static(b"12345678")); } }
//! Traits and structures to aid consuming and writing HTTP payloads. //! //! "Body" and "payload" are used somewhat interchangeably in this documentation. // Though the spec kinda reads like "payload" is the possibly-transfer-encoded part of the message // and the "body" is the intended possibly-decoded version of that. mod body_stream; mod boxed; mod either; mod message_body; mod none; mod size; mod sized_stream; mod utils; pub(crate) use self::message_body::MessageBodyMapErr; pub use self::{ body_stream::BodyStream, boxed::BoxBody, either::EitherBody, message_body::MessageBody, none::None, size::BodySize, sized_stream::SizedStream, utils::{to_bytes, to_bytes_limited, BodyLimitExceeded}, };
use std::{ convert::Infallible, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use super::{BodySize, MessageBody}; /// Body type for responses that forbid payloads. /// /// This is distinct from an "empty" response which _would_ contain a `Content-Length` header. /// For an "empty" body, use `()` or `Bytes::new()`. /// /// For example, the HTTP spec forbids a payload to be sent with a `204 No Content` response. /// In this case, the payload (or lack thereof) is implicit from the status code, so a /// `Content-Length` header is not required. #[derive(Debug, Clone, Copy, Default)] #[non_exhaustive] pub struct None; impl None { /// Constructs new "none" body. #[inline] pub fn new() -> Self { None } } impl MessageBody for None { type Error = Infallible; #[inline] fn size(&self) -> BodySize { BodySize::None } #[inline] fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { Poll::Ready(Option::None) } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> { Ok(Bytes::new()) } }
/// Body size hint. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BodySize { /// Implicitly empty body. /// /// Will omit the Content-Length header. Used for responses to certain methods (e.g., `HEAD`) or /// with particular status codes (e.g., 204 No Content). Consumers that read this as a body size /// hint are allowed to make optimizations that skip reading or writing the payload. None, /// Known size body. /// /// Will write `Content-Length: N` header. Sized(u64), /// Unknown size body. /// /// Will not write Content-Length header. Can be used with chunked Transfer-Encoding. Stream, } impl BodySize { /// Equivalent to `BodySize::Sized(0)`; pub const ZERO: Self = Self::Sized(0); /// Returns true if size hint indicates omitted or empty body. /// /// Streams will return false because it cannot be known without reading the stream. /// /// ``` /// # use actix_http::body::BodySize; /// assert!(BodySize::None.is_eof()); /// assert!(BodySize::Sized(0).is_eof()); /// /// assert!(!BodySize::Sized(64).is_eof()); /// assert!(!BodySize::Stream.is_eof()); /// ``` pub fn is_eof(&self) -> bool { matches!(self, BodySize::None | BodySize::Sized(0)) } }
use std::{ error::Error as StdError, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use futures_core::{ready, Stream}; use pin_project_lite::pin_project; use super::{BodySize, MessageBody}; pin_project! { /// Known sized streaming response wrapper. /// /// This body implementation should be used if total size of stream is known. Data is sent as-is /// without using chunked transfer encoding. pub struct SizedStream<S> { size: u64, #[pin] stream: S, } } impl<S, E> SizedStream<S> where S: Stream<Item = Result<Bytes, E>>, E: Into<Box<dyn StdError>> + 'static, { #[inline] pub fn new(size: u64, stream: S) -> Self { SizedStream { size, stream } } } // TODO: from_infallible method impl<S, E> MessageBody for SizedStream<S> where S: Stream<Item = Result<Bytes, E>>, E: Into<Box<dyn StdError>> + 'static, { type Error = E; #[inline] fn size(&self) -> BodySize { BodySize::Sized(self.size) } /// Attempts to pull out the next value of the underlying [`Stream`]. /// /// Empty values are skipped to prevent [`SizedStream`]'s transmission being /// ended on a zero-length chunk, but rather proceed until the underlying /// [`Stream`] ends. fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { loop { let stream = self.as_mut().project().stream; let chunk = match ready!(stream.poll_next(cx)) { Some(Ok(ref bytes)) if bytes.is_empty() => continue, val => val, }; return Poll::Ready(chunk); } } } #[cfg(test)] mod tests { use std::convert::Infallible; use actix_rt::pin; use actix_utils::future::poll_fn; use futures_util::stream; use static_assertions::{assert_impl_all, assert_not_impl_any}; use super::*; use crate::body::to_bytes; assert_impl_all!(SizedStream<stream::Empty<Result<Bytes, crate::Error>>>: MessageBody); assert_impl_all!(SizedStream<stream::Empty<Result<Bytes, &'static str>>>: MessageBody); assert_impl_all!(SizedStream<stream::Repeat<Result<Bytes, &'static str>>>: MessageBody); assert_impl_all!(SizedStream<stream::Empty<Result<Bytes, Infallible>>>: MessageBody); assert_impl_all!(SizedStream<stream::Repeat<Result<Bytes, Infallible>>>: MessageBody); assert_not_impl_any!(SizedStream<stream::Empty<Bytes>>: MessageBody); assert_not_impl_any!(SizedStream<stream::Repeat<Bytes>>: MessageBody); // crate::Error is not Clone assert_not_impl_any!(SizedStream<stream::Repeat<Result<Bytes, crate::Error>>>: MessageBody); #[actix_rt::test] async fn skips_empty_chunks() { let body = SizedStream::new( 2, stream::iter( ["1", "", "2"] .iter() .map(|&v| Ok::<_, Infallible>(Bytes::from(v))), ), ); pin!(body); assert_eq!( poll_fn(|cx| body.as_mut().poll_next(cx)) .await .unwrap() .ok(), Some(Bytes::from("1")), ); assert_eq!( poll_fn(|cx| body.as_mut().poll_next(cx)) .await .unwrap() .ok(), Some(Bytes::from("2")), ); } #[actix_rt::test] async fn read_to_bytes() { let body = SizedStream::new( 2, stream::iter( ["1", "", "2"] .iter() .map(|&v| Ok::<_, Infallible>(Bytes::from(v))), ), ); assert_eq!(to_bytes(body).await.ok(), Some(Bytes::from("12"))); } #[actix_rt::test] async fn stream_string_error() { // `&'static str` does not impl `Error` // but it does impl `Into<Box<dyn Error>>` let body = SizedStream::new(0, stream::once(async { Err("stringy error") })); assert_eq!(to_bytes(body).await, Ok(Bytes::new())); let body = SizedStream::new(1, stream::once(async { Err("stringy error") })); assert!(matches!(to_bytes(body).await, Err("stringy error"))); } #[actix_rt::test] async fn stream_boxed_error() { // `Box<dyn Error>` does not impl `Error` // but it does impl `Into<Box<dyn Error>>` let body = SizedStream::new( 0, stream::once(async { Err(Box::<dyn StdError>::from("stringy error")) }), ); assert_eq!(to_bytes(body).await.unwrap(), Bytes::new()); let body = SizedStream::new( 1, stream::once(async { Err(Box::<dyn StdError>::from("stringy error")) }), ); assert_eq!( to_bytes(body).await.unwrap_err().to_string(), "stringy error" ); } }
use std::task::Poll; use actix_rt::pin; use actix_utils::future::poll_fn; use bytes::{Bytes, BytesMut}; use derive_more::{Display, Error}; use futures_core::ready; use super::{BodySize, MessageBody}; /// Collects all the bytes produced by `body`. /// /// Any errors produced by the body stream are returned immediately. /// /// Consider using [`to_bytes_limited`] instead to protect against memory exhaustion. /// /// # Examples /// /// ``` /// use actix_http::body::{self, to_bytes}; /// use bytes::Bytes; /// /// # actix_rt::System::new().block_on(async { /// let body = body::None::new(); /// let bytes = to_bytes(body).await.unwrap(); /// assert!(bytes.is_empty()); /// /// let body = Bytes::from_static(b"123"); /// let bytes = to_bytes(body).await.unwrap(); /// assert_eq!(bytes, "123"); /// # }); /// ``` pub async fn to_bytes<B: MessageBody>(body: B) -> Result<Bytes, B::Error> { to_bytes_limited(body, usize::MAX) .await .expect("body should never yield more than usize::MAX bytes") } /// Error type returned from [`to_bytes_limited`] when body produced exceeds limit. #[derive(Debug, Display, Error)] #[display("limit exceeded while collecting body bytes")] #[non_exhaustive] pub struct BodyLimitExceeded; /// Collects the bytes produced by `body`, up to `limit` bytes. /// /// If a chunk read from `poll_next` causes the total number of bytes read to exceed `limit`, an /// `Err(BodyLimitExceeded)` is returned. /// /// Any errors produced by the body stream are returned immediately as `Ok(Err(B::Error))`. /// /// # Examples /// /// ``` /// use actix_http::body::{self, to_bytes_limited}; /// use bytes::Bytes; /// /// # actix_rt::System::new().block_on(async { /// let body = body::None::new(); /// let bytes = to_bytes_limited(body, 10).await.unwrap().unwrap(); /// assert!(bytes.is_empty()); /// /// let body = Bytes::from_static(b"123"); /// let bytes = to_bytes_limited(body, 10).await.unwrap().unwrap(); /// assert_eq!(bytes, "123"); /// /// let body = Bytes::from_static(b"123"); /// assert!(to_bytes_limited(body, 2).await.is_err()); /// # }); /// ``` pub async fn to_bytes_limited<B: MessageBody>( body: B, limit: usize, ) -> Result<Result<Bytes, B::Error>, BodyLimitExceeded> { /// Sensible default (32kB) for initial, bounded allocation when collecting body bytes. const INITIAL_ALLOC_BYTES: usize = 32 * 1024; let cap = match body.size() { BodySize::None | BodySize::Sized(0) => return Ok(Ok(Bytes::new())), BodySize::Sized(size) if size as usize > limit => return Err(BodyLimitExceeded), BodySize::Sized(size) => (size as usize).min(INITIAL_ALLOC_BYTES), BodySize::Stream => INITIAL_ALLOC_BYTES, }; let mut exceeded_limit = false; let mut buf = BytesMut::with_capacity(cap); pin!(body); match poll_fn(|cx| loop { let body = body.as_mut(); match ready!(body.poll_next(cx)) { Some(Ok(bytes)) => { // if limit is exceeded... if buf.len() + bytes.len() > limit { // ...set flag to true and break out of poll_fn exceeded_limit = true; return Poll::Ready(Ok(())); } buf.extend_from_slice(&bytes) } None => return Poll::Ready(Ok(())), Some(Err(err)) => return Poll::Ready(Err(err)), } }) .await { // propagate error returned from body poll Err(err) => Ok(Err(err)), // limit was exceeded while reading body Ok(()) if exceeded_limit => Err(BodyLimitExceeded), // otherwise return body buffer Ok(()) => Ok(Ok(buf.freeze())), } } #[cfg(test)] mod tests { use std::io; use futures_util::{stream, StreamExt as _}; use super::*; use crate::{ body::{BodyStream, SizedStream}, Error, }; #[actix_rt::test] async fn to_bytes_complete() { let bytes = to_bytes(()).await.unwrap(); assert!(bytes.is_empty()); let body = Bytes::from_static(b"123"); let bytes = to_bytes(body).await.unwrap(); assert_eq!(bytes, b"123"[..]); } #[actix_rt::test] async fn to_bytes_streams() { let stream = stream::iter(vec![Bytes::from_static(b"123"), Bytes::from_static(b"abc")]) .map(Ok::<_, Error>); let body = BodyStream::new(stream); let bytes = to_bytes(body).await.unwrap(); assert_eq!(bytes, b"123abc"[..]); } #[actix_rt::test] async fn to_bytes_limited_complete() { let bytes = to_bytes_limited((), 0).await.unwrap().unwrap(); assert!(bytes.is_empty()); let bytes = to_bytes_limited((), 1).await.unwrap().unwrap(); assert!(bytes.is_empty()); assert!(to_bytes_limited(Bytes::from_static(b"12"), 0) .await .is_err()); assert!(to_bytes_limited(Bytes::from_static(b"12"), 1) .await .is_err()); assert!(to_bytes_limited(Bytes::from_static(b"12"), 2).await.is_ok()); assert!(to_bytes_limited(Bytes::from_static(b"12"), 3).await.is_ok()); } #[actix_rt::test] async fn to_bytes_limited_streams() { // hinting a larger body fails let body = SizedStream::new(8, stream::empty().map(Ok::<_, Error>)); assert!(to_bytes_limited(body, 3).await.is_err()); // hinting a smaller body is okay let body = SizedStream::new(3, stream::empty().map(Ok::<_, Error>)); assert!(to_bytes_limited(body, 3).await.unwrap().unwrap().is_empty()); // hinting a smaller body then returning a larger one fails let stream = stream::iter(vec![Bytes::from_static(b"1234")]).map(Ok::<_, Error>); let body = SizedStream::new(3, stream); assert!(to_bytes_limited(body, 3).await.is_err()); let stream = stream::iter(vec![Bytes::from_static(b"123"), Bytes::from_static(b"abc")]) .map(Ok::<_, Error>); let body = BodyStream::new(stream); assert!(to_bytes_limited(body, 3).await.is_err()); } #[actix_rt::test] async fn to_body_limit_error() { let err_stream = stream::once(async { Err(io::Error::new(io::ErrorKind::Other, "")) }); let body = SizedStream::new(8, err_stream); // not too big, but propagates error from body stream assert!(to_bytes_limited(body, 10).await.unwrap().is_err()); } }
use std::{fmt, marker::PhantomData, net, rc::Rc, time::Duration}; use actix_codec::Framed; use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use crate::{ body::{BoxBody, MessageBody}, h1::{self, ExpectHandler, H1Service, UpgradeHandler}, service::HttpService, ConnectCallback, Extensions, KeepAlive, Request, Response, ServiceConfig, }; /// An HTTP service builder. /// /// This type can construct an instance of [`HttpService`] through a builder-like pattern. pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler> { keep_alive: KeepAlive, client_request_timeout: Duration, client_disconnect_timeout: Duration, secure: bool, local_addr: Option<net::SocketAddr>, expect: X, upgrade: Option<U>, on_connect_ext: Option<Rc<ConnectCallback<T>>>, _phantom: PhantomData<S>, } impl<T, S> Default for HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler> where S: ServiceFactory<Request, Config = ()>, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, <S::Service as Service<Request>>::Future: 'static, { fn default() -> Self { HttpServiceBuilder { // ServiceConfig parts (make sure defaults match) keep_alive: KeepAlive::default(), client_request_timeout: Duration::from_secs(5), client_disconnect_timeout: Duration::ZERO, secure: false, local_addr: None, // dispatcher parts expect: ExpectHandler, upgrade: None, on_connect_ext: None, _phantom: PhantomData, } } } impl<T, S, X, U> HttpServiceBuilder<T, S, X, U> where S: ServiceFactory<Request, Config = ()>, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, <S::Service as Service<Request>>::Future: 'static, X: ServiceFactory<Request, Config = (), Response = Request>, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory<(Request, Framed<T, h1::Codec>), Config = (), Response = ()>, U::Error: fmt::Display, U::InitError: fmt::Debug, { /// Set connection keep-alive setting. /// /// Applies to HTTP/1.1 keep-alive and HTTP/2 ping-pong. /// /// By default keep-alive is 5 seconds. pub fn keep_alive<W: Into<KeepAlive>>(mut self, val: W) -> Self { self.keep_alive = val.into(); self } /// Set connection secure state pub fn secure(mut self) -> Self { self.secure = true; self } /// Set the local address that this service is bound to. pub fn local_addr(mut self, addr: net::SocketAddr) -> Self { self.local_addr = Some(addr); self } /// Set client request timeout (for first request). /// /// Defines a timeout for reading client request header. If the client does not transmit the /// request head within this duration, the connection is terminated with a `408 Request Timeout` /// response error. /// /// A duration of zero disables the timeout. /// /// By default, the client timeout is 5 seconds. pub fn client_request_timeout(mut self, dur: Duration) -> Self { self.client_request_timeout = dur; self } #[doc(hidden)] #[deprecated(since = "3.0.0", note = "Renamed to `client_request_timeout`.")] pub fn client_timeout(self, dur: Duration) -> Self { self.client_request_timeout(dur) } /// Set client connection disconnect timeout. /// /// Defines a timeout for disconnect connection. If a disconnect procedure does not complete /// within this time, the request get dropped. This timeout affects secure connections. /// /// A duration of zero disables the timeout. /// /// By default, the disconnect timeout is disabled. pub fn client_disconnect_timeout(mut self, dur: Duration) -> Self { self.client_disconnect_timeout = dur; self } #[doc(hidden)] #[deprecated(since = "3.0.0", note = "Renamed to `client_disconnect_timeout`.")] pub fn client_disconnect(self, dur: Duration) -> Self { self.client_disconnect_timeout(dur) } /// Provide service for `EXPECT: 100-Continue` support. /// /// Service get called with request that contains `EXPECT` header. /// Service must return request in case of success, in that case /// request will be forwarded to main service. pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U> where F: IntoServiceFactory<X1, Request>, X1: ServiceFactory<Request, Config = (), Response = Request>, X1::Error: Into<Response<BoxBody>>, X1::InitError: fmt::Debug, { HttpServiceBuilder { keep_alive: self.keep_alive, client_request_timeout: self.client_request_timeout, client_disconnect_timeout: self.client_disconnect_timeout, secure: self.secure, local_addr: self.local_addr, expect: expect.into_factory(), upgrade: self.upgrade, on_connect_ext: self.on_connect_ext, _phantom: PhantomData, } } /// Provide service for custom `Connection: UPGRADE` support. /// /// If service is provided then normal requests handling get halted /// and this service get called with original request and framed object. pub fn upgrade<F, U1>(self, upgrade: F) -> HttpServiceBuilder<T, S, X, U1> where F: IntoServiceFactory<U1, (Request, Framed<T, h1::Codec>)>, U1: ServiceFactory<(Request, Framed<T, h1::Codec>), Config = (), Response = ()>, U1::Error: fmt::Display, U1::InitError: fmt::Debug, { HttpServiceBuilder { keep_alive: self.keep_alive, client_request_timeout: self.client_request_timeout, client_disconnect_timeout: self.client_disconnect_timeout, secure: self.secure, local_addr: self.local_addr, expect: self.expect, upgrade: Some(upgrade.into_factory()), on_connect_ext: self.on_connect_ext, _phantom: PhantomData, } } /// Sets the callback to be run on connection establishment. /// /// Has mutable access to a data container that will be merged into request extensions. /// This enables transport layer data (like client certificates) to be accessed in middleware /// and handlers. pub fn on_connect_ext<F>(mut self, f: F) -> Self where F: Fn(&T, &mut Extensions) + 'static, { self.on_connect_ext = Some(Rc::new(f)); self } /// Finish service configuration and create a service for the HTTP/1 protocol. pub fn h1<F, B>(self, service: F) -> H1Service<T, S, B, X, U> where B: MessageBody, F: IntoServiceFactory<S, Request>, S::Error: Into<Response<BoxBody>>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, { let cfg = ServiceConfig::new( self.keep_alive, self.client_request_timeout, self.client_disconnect_timeout, self.secure, self.local_addr, ); H1Service::with_config(cfg, service.into_factory()) .expect(self.expect) .upgrade(self.upgrade) .on_connect_ext(self.on_connect_ext) } /// Finish service configuration and create a service for the HTTP/2 protocol. #[cfg(feature = "http2")] pub fn h2<F, B>(self, service: F) -> crate::h2::H2Service<T, S, B> where F: IntoServiceFactory<S, Request>, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, B: MessageBody + 'static, { let cfg = ServiceConfig::new( self.keep_alive, self.client_request_timeout, self.client_disconnect_timeout, self.secure, self.local_addr, ); crate::h2::H2Service::with_config(cfg, service.into_factory()) .on_connect_ext(self.on_connect_ext) } /// Finish service configuration and create `HttpService` instance. pub fn finish<F, B>(self, service: F) -> HttpService<T, S, B, X, U> where F: IntoServiceFactory<S, Request>, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, B: MessageBody + 'static, { let cfg = ServiceConfig::new( self.keep_alive, self.client_request_timeout, self.client_disconnect_timeout, self.secure, self.local_addr, ); HttpService::with_config(cfg, service.into_factory()) .expect(self.expect) .upgrade(self.upgrade) .on_connect_ext(self.on_connect_ext) } }
use std::{ net, rc::Rc, time::{Duration, Instant}, }; use bytes::BytesMut; use crate::{date::DateService, KeepAlive}; /// HTTP service configuration. #[derive(Debug, Clone)] pub struct ServiceConfig(Rc<Inner>); #[derive(Debug)] struct Inner { keep_alive: KeepAlive, client_request_timeout: Duration, client_disconnect_timeout: Duration, secure: bool, local_addr: Option<std::net::SocketAddr>, date_service: DateService, } impl Default for ServiceConfig { fn default() -> Self { Self::new( KeepAlive::default(), Duration::from_secs(5), Duration::ZERO, false, None, ) } } impl ServiceConfig { /// Create instance of `ServiceConfig`. pub fn new( keep_alive: KeepAlive, client_request_timeout: Duration, client_disconnect_timeout: Duration, secure: bool, local_addr: Option<net::SocketAddr>, ) -> ServiceConfig { ServiceConfig(Rc::new(Inner { keep_alive: keep_alive.normalize(), client_request_timeout, client_disconnect_timeout, secure, local_addr, date_service: DateService::new(), })) } /// Returns `true` if connection is secure (i.e., using TLS / HTTPS). #[inline] pub fn secure(&self) -> bool { self.0.secure } /// Returns the local address that this server is bound to. /// /// Returns `None` for connections via UDS (Unix Domain Socket). #[inline] pub fn local_addr(&self) -> Option<net::SocketAddr> { self.0.local_addr } /// Connection keep-alive setting. #[inline] pub fn keep_alive(&self) -> KeepAlive { self.0.keep_alive } /// Creates a time object representing the deadline for this connection's keep-alive period, if /// enabled. /// /// When [`KeepAlive::Os`] or [`KeepAlive::Disabled`] is set, this will return `None`. pub fn keep_alive_deadline(&self) -> Option<Instant> { match self.keep_alive() { KeepAlive::Timeout(dur) => Some(self.now() + dur), KeepAlive::Os => None, KeepAlive::Disabled => None, } } /// Creates a time object representing the deadline for the client to finish sending the head of /// its first request. /// /// Returns `None` if this `ServiceConfig was` constructed with `client_request_timeout: 0`. pub fn client_request_deadline(&self) -> Option<Instant> { let timeout = self.0.client_request_timeout; (timeout != Duration::ZERO).then(|| self.now() + timeout) } /// Creates a time object representing the deadline for the client to disconnect. pub fn client_disconnect_deadline(&self) -> Option<Instant> { let timeout = self.0.client_disconnect_timeout; (timeout != Duration::ZERO).then(|| self.now() + timeout) } pub(crate) fn now(&self) -> Instant { self.0.date_service.now() } /// Writes date header to `dst` buffer. /// /// Low-level method that utilizes the built-in efficient date service, requiring fewer syscalls /// than normal. Note that a CRLF (`\r\n`) is included in what is written. #[doc(hidden)] pub fn write_date_header(&self, dst: &mut BytesMut, camel_case: bool) { let mut buf: [u8; 37] = [0; 37]; buf[..6].copy_from_slice(if camel_case { b"Date: " } else { b"date: " }); self.0 .date_service .with_date(|date| buf[6..35].copy_from_slice(&date.bytes)); buf[35..].copy_from_slice(b"\r\n"); dst.extend_from_slice(&buf); } #[allow(unused)] // used with `http2` feature flag pub(crate) fn write_date_header_value(&self, dst: &mut BytesMut) { self.0 .date_service .with_date(|date| dst.extend_from_slice(&date.bytes)); } } #[cfg(test)] mod tests { use actix_rt::{ task::yield_now, time::{sleep, sleep_until}, }; use memchr::memmem; use super::*; use crate::{date::DATE_VALUE_LENGTH, notify_on_drop}; #[actix_rt::test] async fn test_date_service_update() { let settings = ServiceConfig::new(KeepAlive::Os, Duration::ZERO, Duration::ZERO, false, None); yield_now().await; let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); settings.write_date_header(&mut buf1, false); let now1 = settings.now(); sleep_until((Instant::now() + Duration::from_secs(2)).into()).await; yield_now().await; let now2 = settings.now(); let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); settings.write_date_header(&mut buf2, false); assert_ne!(now1, now2); assert_ne!(buf1, buf2); drop(settings); // Ensure the task will drop eventually let mut times = 0; while !notify_on_drop::is_dropped() { sleep(Duration::from_millis(100)).await; times += 1; assert!(times < 10, "Timeout waiting for task drop"); } } #[actix_rt::test] async fn test_date_service_drop() { let service = Rc::new(DateService::new()); // yield so date service have a chance to register the spawned timer update task. yield_now().await; let clone1 = service.clone(); let clone2 = service.clone(); let clone3 = service.clone(); drop(clone1); assert!(!notify_on_drop::is_dropped()); drop(clone2); assert!(!notify_on_drop::is_dropped()); drop(clone3); assert!(!notify_on_drop::is_dropped()); drop(service); // Ensure the task will drop eventually let mut times = 0; while !notify_on_drop::is_dropped() { sleep(Duration::from_millis(100)).await; times += 1; assert!(times < 10, "Timeout waiting for task drop"); } } #[test] fn test_date_len() { assert_eq!(DATE_VALUE_LENGTH, "Sun, 06 Nov 1994 08:49:37 GMT".len()); } #[actix_rt::test] async fn test_date() { let settings = ServiceConfig::default(); let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); settings.write_date_header(&mut buf1, false); let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); settings.write_date_header(&mut buf2, false); assert_eq!(buf1, buf2); } #[actix_rt::test] async fn test_date_camel_case() { let settings = ServiceConfig::default(); let mut buf = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); settings.write_date_header(&mut buf, false); assert!(memmem::find(&buf, b"date:").is_some()); let mut buf = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); settings.write_date_header(&mut buf, true); assert!(memmem::find(&buf, b"Date:").is_some()); } }
use std::{ cell::Cell, fmt::{self, Write}, rc::Rc, time::{Duration, Instant, SystemTime}, }; use actix_rt::{task::JoinHandle, time::interval}; /// "Thu, 01 Jan 1970 00:00:00 GMT".len() pub(crate) const DATE_VALUE_LENGTH: usize = 29; #[derive(Clone, Copy)] pub(crate) struct Date { pub(crate) bytes: [u8; DATE_VALUE_LENGTH], pos: usize, } impl Date { fn new() -> Date { let mut date = Date { bytes: [0; DATE_VALUE_LENGTH], pos: 0, }; date.update(); date } fn update(&mut self) { self.pos = 0; write!(self, "{}", httpdate::HttpDate::from(SystemTime::now())).unwrap(); } } impl fmt::Write for Date { fn write_str(&mut self, s: &str) -> fmt::Result { let len = s.len(); self.bytes[self.pos..self.pos + len].copy_from_slice(s.as_bytes()); self.pos += len; Ok(()) } } /// Service for update Date and Instant periodically at 500 millis interval. pub(crate) struct DateService { current: Rc<Cell<(Date, Instant)>>, handle: JoinHandle<()>, } impl DateService { pub(crate) fn new() -> Self { // shared date and timer for DateService and update async task. let current = Rc::new(Cell::new((Date::new(), Instant::now()))); let current_clone = Rc::clone(&current); // spawn an async task sleep for 500 millis and update current date/timer in a loop. // handle is used to stop the task on DateService drop. let handle = actix_rt::spawn(async move { #[cfg(test)] let _notify = crate::notify_on_drop::NotifyOnDrop::new(); let mut interval = interval(Duration::from_millis(500)); loop { let now = interval.tick().await; let date = Date::new(); current_clone.set((date, now.into_std())); } }); DateService { current, handle } } pub(crate) fn now(&self) -> Instant { self.current.get().1 } pub(crate) fn with_date<F: FnMut(&Date)>(&self, mut f: F) { f(&self.current.get().0); } } impl fmt::Debug for DateService { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("DateService").finish_non_exhaustive() } } impl Drop for DateService { fn drop(&mut self) { // stop the timer update async task on drop. self.handle.abort(); } }
//! Stream decoders. use std::{ future::Future, io::{self, Write as _}, pin::Pin, task::{Context, Poll}, }; use actix_rt::task::{spawn_blocking, JoinHandle}; use bytes::Bytes; #[cfg(feature = "compress-gzip")] use flate2::write::{GzDecoder, ZlibDecoder}; use futures_core::{ready, Stream}; #[cfg(feature = "compress-zstd")] use zstd::stream::write::Decoder as ZstdDecoder; use crate::{ encoding::Writer, error::PayloadError, header::{ContentEncoding, HeaderMap, CONTENT_ENCODING}, }; const MAX_CHUNK_SIZE_DECODE_IN_PLACE: usize = 2049; pin_project_lite::pin_project! { pub struct Decoder<S> { decoder: Option<ContentDecoder>, #[pin] stream: S, eof: bool, fut: Option<JoinHandle<Result<(Option<Bytes>, ContentDecoder), io::Error>>>, } } impl<S> Decoder<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { /// Construct a decoder. #[inline] pub fn new(stream: S, encoding: ContentEncoding) -> Decoder<S> { let decoder = match encoding { #[cfg(feature = "compress-brotli")] ContentEncoding::Brotli => Some(ContentDecoder::Brotli(Box::new( brotli::DecompressorWriter::new(Writer::new(), 8_096), ))), #[cfg(feature = "compress-gzip")] ContentEncoding::Deflate => Some(ContentDecoder::Deflate(Box::new(ZlibDecoder::new( Writer::new(), )))), #[cfg(feature = "compress-gzip")] ContentEncoding::Gzip => Some(ContentDecoder::Gzip(Box::new(GzDecoder::new( Writer::new(), )))), #[cfg(feature = "compress-zstd")] ContentEncoding::Zstd => Some(ContentDecoder::Zstd(Box::new( ZstdDecoder::new(Writer::new()).expect( "Failed to create zstd decoder. This is a bug. \ Please report it to the actix-web repository.", ), ))), _ => None, }; Decoder { decoder, stream, fut: None, eof: false, } } /// Construct decoder based on headers. #[inline] pub fn from_headers(stream: S, headers: &HeaderMap) -> Decoder<S> { // check content-encoding let encoding = headers .get(&CONTENT_ENCODING) .and_then(|val| val.to_str().ok()) .and_then(|x| x.parse().ok()) .unwrap_or(ContentEncoding::Identity); Self::new(stream, encoding) } } impl<S> Stream for Decoder<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { type Item = Result<Bytes, PayloadError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); loop { if let Some(ref mut fut) = this.fut { let (chunk, decoder) = ready!(Pin::new(fut).poll(cx)).map_err(|_| { PayloadError::Io(io::Error::new( io::ErrorKind::Other, "Blocking task was cancelled unexpectedly", )) })??; *this.decoder = Some(decoder); this.fut.take(); if let Some(chunk) = chunk { return Poll::Ready(Some(Ok(chunk))); } } if *this.eof { return Poll::Ready(None); } match ready!(this.stream.as_mut().poll_next(cx)) { Some(Err(err)) => return Poll::Ready(Some(Err(err))), Some(Ok(chunk)) => { if let Some(mut decoder) = this.decoder.take() { if chunk.len() < MAX_CHUNK_SIZE_DECODE_IN_PLACE { let chunk = decoder.feed_data(chunk)?; *this.decoder = Some(decoder); if let Some(chunk) = chunk { return Poll::Ready(Some(Ok(chunk))); } } else { *this.fut = Some(spawn_blocking(move || { let chunk = decoder.feed_data(chunk)?; Ok((chunk, decoder)) })); } continue; } else { return Poll::Ready(Some(Ok(chunk))); } } None => { *this.eof = true; return if let Some(mut decoder) = this.decoder.take() { match decoder.feed_eof() { Ok(Some(res)) => Poll::Ready(Some(Ok(res))), Ok(None) => Poll::Ready(None), Err(err) => Poll::Ready(Some(Err(err.into()))), } } else { Poll::Ready(None) }; } } } } } enum ContentDecoder { #[cfg(feature = "compress-gzip")] Deflate(Box<ZlibDecoder<Writer>>), #[cfg(feature = "compress-gzip")] Gzip(Box<GzDecoder<Writer>>), #[cfg(feature = "compress-brotli")] Brotli(Box<brotli::DecompressorWriter<Writer>>), // We need explicit 'static lifetime here because ZstdDecoder need lifetime // argument, and we use `spawn_blocking` in `Decoder::poll_next` that require `FnOnce() -> R + Send + 'static` #[cfg(feature = "compress-zstd")] Zstd(Box<ZstdDecoder<'static, Writer>>), } impl ContentDecoder { fn feed_eof(&mut self) -> io::Result<Option<Bytes>> { match self { #[cfg(feature = "compress-brotli")] ContentDecoder::Brotli(ref mut decoder) => match decoder.flush() { Ok(()) => { let b = decoder.get_mut().take(); if !b.is_empty() { Ok(Some(b)) } else { Ok(None) } } Err(err) => Err(err), }, #[cfg(feature = "compress-gzip")] ContentDecoder::Gzip(ref mut decoder) => match decoder.try_finish() { Ok(_) => { let b = decoder.get_mut().take(); if !b.is_empty() { Ok(Some(b)) } else { Ok(None) } } Err(err) => Err(err), }, #[cfg(feature = "compress-gzip")] ContentDecoder::Deflate(ref mut decoder) => match decoder.try_finish() { Ok(_) => { let b = decoder.get_mut().take(); if !b.is_empty() { Ok(Some(b)) } else { Ok(None) } } Err(err) => Err(err), }, #[cfg(feature = "compress-zstd")] ContentDecoder::Zstd(ref mut decoder) => match decoder.flush() { Ok(_) => { let b = decoder.get_mut().take(); if !b.is_empty() { Ok(Some(b)) } else { Ok(None) } } Err(err) => Err(err), }, } } fn feed_data(&mut self, data: Bytes) -> io::Result<Option<Bytes>> { match self { #[cfg(feature = "compress-brotli")] ContentDecoder::Brotli(ref mut decoder) => match decoder.write_all(&data) { Ok(_) => { decoder.flush()?; let b = decoder.get_mut().take(); if !b.is_empty() { Ok(Some(b)) } else { Ok(None) } } Err(err) => Err(err), }, #[cfg(feature = "compress-gzip")] ContentDecoder::Gzip(ref mut decoder) => match decoder.write_all(&data) { Ok(_) => { decoder.flush()?; let b = decoder.get_mut().take(); if !b.is_empty() { Ok(Some(b)) } else { Ok(None) } } Err(err) => Err(err), }, #[cfg(feature = "compress-gzip")] ContentDecoder::Deflate(ref mut decoder) => match decoder.write_all(&data) { Ok(_) => { decoder.flush()?; let b = decoder.get_mut().take(); if !b.is_empty() { Ok(Some(b)) } else { Ok(None) } } Err(err) => Err(err), }, #[cfg(feature = "compress-zstd")] ContentDecoder::Zstd(ref mut decoder) => match decoder.write_all(&data) { Ok(_) => { decoder.flush()?; let b = decoder.get_mut().take(); if !b.is_empty() { Ok(Some(b)) } else { Ok(None) } } Err(err) => Err(err), }, } } }
//! Stream encoders. use std::{ error::Error as StdError, future::Future, io::{self, Write as _}, pin::Pin, task::{Context, Poll}, }; use actix_rt::task::{spawn_blocking, JoinHandle}; use bytes::Bytes; use derive_more::Display; #[cfg(feature = "compress-gzip")] use flate2::write::{GzEncoder, ZlibEncoder}; use futures_core::ready; use pin_project_lite::pin_project; use tracing::trace; #[cfg(feature = "compress-zstd")] use zstd::stream::write::Encoder as ZstdEncoder; use super::Writer; use crate::{ body::{self, BodySize, MessageBody}, header::{self, ContentEncoding, HeaderValue, CONTENT_ENCODING}, ResponseHead, StatusCode, }; const MAX_CHUNK_SIZE_ENCODE_IN_PLACE: usize = 1024; pin_project! { pub struct Encoder<B> { #[pin] body: EncoderBody<B>, encoder: Option<ContentEncoder>, fut: Option<JoinHandle<Result<ContentEncoder, io::Error>>>, eof: bool, } } impl<B: MessageBody> Encoder<B> { fn none() -> Self { Encoder { body: EncoderBody::None { body: body::None::new(), }, encoder: None, fut: None, eof: true, } } fn empty() -> Self { Encoder { body: EncoderBody::Full { body: Bytes::new() }, encoder: None, fut: None, eof: true, } } pub fn response(encoding: ContentEncoding, head: &mut ResponseHead, body: B) -> Self { // no need to compress empty bodies match body.size() { BodySize::None => return Self::none(), BodySize::Sized(0) => return Self::empty(), _ => {} } let should_encode = !(head.headers().contains_key(&CONTENT_ENCODING) || head.status == StatusCode::SWITCHING_PROTOCOLS || head.status == StatusCode::NO_CONTENT || encoding == ContentEncoding::Identity); let body = match body.try_into_bytes() { Ok(body) => EncoderBody::Full { body }, Err(body) => EncoderBody::Stream { body }, }; if should_encode { // wrap body only if encoder is feature-enabled if let Some(enc) = ContentEncoder::select(encoding) { update_head(encoding, head); return Encoder { body, encoder: Some(enc), fut: None, eof: false, }; } } Encoder { body, encoder: None, fut: None, eof: false, } } } pin_project! { #[project = EncoderBodyProj] enum EncoderBody<B> { None { body: body::None }, Full { body: Bytes }, Stream { #[pin] body: B }, } } impl<B> MessageBody for EncoderBody<B> where B: MessageBody, { type Error = EncoderError; #[inline] fn size(&self) -> BodySize { match self { EncoderBody::None { body } => body.size(), EncoderBody::Full { body } => body.size(), EncoderBody::Stream { body } => body.size(), } } fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { match self.project() { EncoderBodyProj::None { body } => { Pin::new(body).poll_next(cx).map_err(|err| match err {}) } EncoderBodyProj::Full { body } => { Pin::new(body).poll_next(cx).map_err(|err| match err {}) } EncoderBodyProj::Stream { body } => body .poll_next(cx) .map_err(|err| EncoderError::Body(err.into())), } } #[inline] fn try_into_bytes(self) -> Result<Bytes, Self> where Self: Sized, { match self { EncoderBody::None { body } => Ok(body.try_into_bytes().unwrap()), EncoderBody::Full { body } => Ok(body.try_into_bytes().unwrap()), _ => Err(self), } } } impl<B> MessageBody for Encoder<B> where B: MessageBody, { type Error = EncoderError; #[inline] fn size(&self) -> BodySize { if self.encoder.is_some() { BodySize::Stream } else { self.body.size() } } fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { let mut this = self.project(); loop { if *this.eof { return Poll::Ready(None); } if let Some(ref mut fut) = this.fut { let mut encoder = ready!(Pin::new(fut).poll(cx)) .map_err(|_| { EncoderError::Io(io::Error::new( io::ErrorKind::Other, "Blocking task was cancelled unexpectedly", )) })? .map_err(EncoderError::Io)?; let chunk = encoder.take(); *this.encoder = Some(encoder); this.fut.take(); if !chunk.is_empty() { return Poll::Ready(Some(Ok(chunk))); } } let result = ready!(this.body.as_mut().poll_next(cx)); match result { Some(Err(err)) => return Poll::Ready(Some(Err(err))), Some(Ok(chunk)) => { if let Some(mut encoder) = this.encoder.take() { if chunk.len() < MAX_CHUNK_SIZE_ENCODE_IN_PLACE { encoder.write(&chunk).map_err(EncoderError::Io)?; let chunk = encoder.take(); *this.encoder = Some(encoder); if !chunk.is_empty() { return Poll::Ready(Some(Ok(chunk))); } } else { *this.fut = Some(spawn_blocking(move || { encoder.write(&chunk)?; Ok(encoder) })); } } else { return Poll::Ready(Some(Ok(chunk))); } } None => { if let Some(encoder) = this.encoder.take() { let chunk = encoder.finish().map_err(EncoderError::Io)?; if chunk.is_empty() { return Poll::Ready(None); } else { *this.eof = true; return Poll::Ready(Some(Ok(chunk))); } } else { return Poll::Ready(None); } } } } } #[inline] fn try_into_bytes(mut self) -> Result<Bytes, Self> where Self: Sized, { if self.encoder.is_some() { Err(self) } else { match self.body.try_into_bytes() { Ok(body) => Ok(body), Err(body) => { self.body = body; Err(self) } } } } } fn update_head(encoding: ContentEncoding, head: &mut ResponseHead) { head.headers_mut() .insert(header::CONTENT_ENCODING, encoding.to_header_value()); head.headers_mut() .append(header::VARY, HeaderValue::from_static("accept-encoding")); head.no_chunking(false); } enum ContentEncoder { #[cfg(feature = "compress-gzip")] Deflate(ZlibEncoder<Writer>), #[cfg(feature = "compress-gzip")] Gzip(GzEncoder<Writer>), #[cfg(feature = "compress-brotli")] Brotli(Box<brotli::CompressorWriter<Writer>>), // Wwe need explicit 'static lifetime here because ZstdEncoder needs a lifetime argument and we // use `spawn_blocking` in `Encoder::poll_next` that requires `FnOnce() -> R + Send + 'static`. #[cfg(feature = "compress-zstd")] Zstd(ZstdEncoder<'static, Writer>), } impl ContentEncoder { fn select(encoding: ContentEncoding) -> Option<Self> { match encoding { #[cfg(feature = "compress-gzip")] ContentEncoding::Deflate => Some(ContentEncoder::Deflate(ZlibEncoder::new( Writer::new(), flate2::Compression::fast(), ))), #[cfg(feature = "compress-gzip")] ContentEncoding::Gzip => Some(ContentEncoder::Gzip(GzEncoder::new( Writer::new(), flate2::Compression::fast(), ))), #[cfg(feature = "compress-brotli")] ContentEncoding::Brotli => Some(ContentEncoder::Brotli(new_brotli_compressor())), #[cfg(feature = "compress-zstd")] ContentEncoding::Zstd => { let encoder = ZstdEncoder::new(Writer::new(), 3).ok()?; Some(ContentEncoder::Zstd(encoder)) } _ => None, } } #[inline] pub(crate) fn take(&mut self) -> Bytes { match *self { #[cfg(feature = "compress-brotli")] ContentEncoder::Brotli(ref mut encoder) => encoder.get_mut().take(), #[cfg(feature = "compress-gzip")] ContentEncoder::Deflate(ref mut encoder) => encoder.get_mut().take(), #[cfg(feature = "compress-gzip")] ContentEncoder::Gzip(ref mut encoder) => encoder.get_mut().take(), #[cfg(feature = "compress-zstd")] ContentEncoder::Zstd(ref mut encoder) => encoder.get_mut().take(), } } fn finish(self) -> Result<Bytes, io::Error> { match self { #[cfg(feature = "compress-brotli")] ContentEncoder::Brotli(mut encoder) => match encoder.flush() { Ok(()) => Ok(encoder.into_inner().buf.freeze()), Err(err) => Err(err), }, #[cfg(feature = "compress-gzip")] ContentEncoder::Gzip(encoder) => match encoder.finish() { Ok(writer) => Ok(writer.buf.freeze()), Err(err) => Err(err), }, #[cfg(feature = "compress-gzip")] ContentEncoder::Deflate(encoder) => match encoder.finish() { Ok(writer) => Ok(writer.buf.freeze()), Err(err) => Err(err), }, #[cfg(feature = "compress-zstd")] ContentEncoder::Zstd(encoder) => match encoder.finish() { Ok(writer) => Ok(writer.buf.freeze()), Err(err) => Err(err), }, } } fn write(&mut self, data: &[u8]) -> Result<(), io::Error> { match *self { #[cfg(feature = "compress-brotli")] ContentEncoder::Brotli(ref mut encoder) => match encoder.write_all(data) { Ok(_) => Ok(()), Err(err) => { trace!("Error decoding br encoding: {}", err); Err(err) } }, #[cfg(feature = "compress-gzip")] ContentEncoder::Gzip(ref mut encoder) => match encoder.write_all(data) { Ok(_) => Ok(()), Err(err) => { trace!("Error decoding gzip encoding: {}", err); Err(err) } }, #[cfg(feature = "compress-gzip")] ContentEncoder::Deflate(ref mut encoder) => match encoder.write_all(data) { Ok(_) => Ok(()), Err(err) => { trace!("Error decoding deflate encoding: {}", err); Err(err) } }, #[cfg(feature = "compress-zstd")] ContentEncoder::Zstd(ref mut encoder) => match encoder.write_all(data) { Ok(_) => Ok(()), Err(err) => { trace!("Error decoding ztsd encoding: {}", err); Err(err) } }, } } } #[cfg(feature = "compress-brotli")] fn new_brotli_compressor() -> Box<brotli::CompressorWriter<Writer>> { Box::new(brotli::CompressorWriter::new( Writer::new(), 32 * 1024, // 32 KiB buffer 3, // BROTLI_PARAM_QUALITY 22, // BROTLI_PARAM_LGWIN )) } #[derive(Debug, Display)] #[non_exhaustive] pub enum EncoderError { /// Wrapped body stream error. #[display("body")] Body(Box<dyn StdError>), /// Generic I/O error. #[display("io")] Io(io::Error), } impl StdError for EncoderError { fn source(&self) -> Option<&(dyn StdError + 'static)> { match self { EncoderError::Body(err) => Some(&**err), EncoderError::Io(err) => Some(err), } } } impl From<EncoderError> for crate::Error { fn from(err: EncoderError) -> Self { crate::Error::new_encoder().with_cause(err) } }
//! Content-Encoding support. use std::io; use bytes::{Bytes, BytesMut}; mod decoder; mod encoder; pub use self::{decoder::Decoder, encoder::Encoder}; /// Special-purpose writer for streaming (de-)compression. /// /// Pre-allocates 8KiB of capacity. struct Writer { buf: BytesMut, } impl Writer { fn new() -> Writer { Writer { buf: BytesMut::with_capacity(8192), } } fn take(&mut self) -> Bytes { self.buf.split().freeze() } } impl io::Write for Writer { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.buf.extend_from_slice(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
//! Error and Result module use std::{error::Error as StdError, fmt, io, str::Utf8Error, string::FromUtf8Error}; use derive_more::{Display, Error, From}; pub use http::{status::InvalidStatusCode, Error as HttpError}; use http::{uri::InvalidUri, StatusCode}; use crate::{body::BoxBody, Response}; pub struct Error { inner: Box<ErrorInner>, } pub(crate) struct ErrorInner { #[allow(dead_code)] kind: Kind, cause: Option<Box<dyn StdError>>, } impl Error { fn new(kind: Kind) -> Self { Self { inner: Box::new(ErrorInner { kind, cause: None }), } } pub(crate) fn with_cause(mut self, cause: impl Into<Box<dyn StdError>>) -> Self { self.inner.cause = Some(cause.into()); self } pub(crate) fn new_http() -> Self { Self::new(Kind::Http) } pub(crate) fn new_parse() -> Self { Self::new(Kind::Parse) } pub(crate) fn new_payload() -> Self { Self::new(Kind::Payload) } pub(crate) fn new_body() -> Self { Self::new(Kind::Body) } pub(crate) fn new_send_response() -> Self { Self::new(Kind::SendResponse) } #[allow(unused)] // available for future use pub(crate) fn new_io() -> Self { Self::new(Kind::Io) } #[allow(unused)] // used in encoder behind feature flag so ignore unused warning pub(crate) fn new_encoder() -> Self { Self::new(Kind::Encoder) } #[allow(unused)] // used with `ws` feature flag pub(crate) fn new_ws() -> Self { Self::new(Kind::Ws) } } impl From<Error> for Response<BoxBody> { fn from(err: Error) -> Self { // TODO: more appropriate error status codes, usage assessment needed let status_code = match err.inner.kind { Kind::Parse => StatusCode::BAD_REQUEST, _ => StatusCode::INTERNAL_SERVER_ERROR, }; Response::new(status_code).set_body(BoxBody::new(err.to_string())) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Display)] pub(crate) enum Kind { #[display("error processing HTTP")] Http, #[display("error parsing HTTP message")] Parse, #[display("request payload read error")] Payload, #[display("response body write error")] Body, #[display("send response error")] SendResponse, #[display("error in WebSocket process")] Ws, #[display("connection error")] Io, #[display("encoder error")] Encoder, } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("actix_http::Error") .field("kind", &self.inner.kind) .field("cause", &self.inner.cause) .finish() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.inner.cause.as_ref() { Some(err) => write!(f, "{}: {}", &self.inner.kind, err), None => write!(f, "{}", &self.inner.kind), } } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { self.inner.cause.as_ref().map(Box::as_ref) } } impl From<std::convert::Infallible> for Error { fn from(err: std::convert::Infallible) -> Self { match err {} } } impl From<HttpError> for Error { fn from(err: HttpError) -> Self { Self::new_http().with_cause(err) } } #[cfg(feature = "ws")] impl From<crate::ws::HandshakeError> for Error { fn from(err: crate::ws::HandshakeError) -> Self { Self::new_ws().with_cause(err) } } #[cfg(feature = "ws")] impl From<crate::ws::ProtocolError> for Error { fn from(err: crate::ws::ProtocolError) -> Self { Self::new_ws().with_cause(err) } } /// A set of errors that can occur during parsing HTTP streams. #[derive(Debug, Display, Error)] #[non_exhaustive] pub enum ParseError { /// An invalid `Method`, such as `GE.T`. #[display("invalid method specified")] Method, /// An invalid `Uri`, such as `exam ple.domain`. #[display("URI error: {}", _0)] Uri(InvalidUri), /// An invalid `HttpVersion`, such as `HTP/1.1` #[display("invalid HTTP version specified")] Version, /// An invalid `Header`. #[display("invalid Header provided")] Header, /// A message head is too large to be reasonable. #[display("message head is too large")] TooLarge, /// A message reached EOF, but is not complete. #[display("message is incomplete")] Incomplete, /// An invalid `Status`, such as `1337 ELITE`. #[display("invalid status provided")] Status, /// A timeout occurred waiting for an IO event. #[allow(dead_code)] #[display("timeout")] Timeout, /// An I/O error that occurred while trying to read or write to a network stream. #[display("I/O error: {}", _0)] Io(io::Error), /// Parsing a field as string failed. #[display("UTF-8 error: {}", _0)] Utf8(Utf8Error), } impl From<io::Error> for ParseError { fn from(err: io::Error) -> ParseError { ParseError::Io(err) } } impl From<InvalidUri> for ParseError { fn from(err: InvalidUri) -> ParseError { ParseError::Uri(err) } } impl From<Utf8Error> for ParseError { fn from(err: Utf8Error) -> ParseError { ParseError::Utf8(err) } } impl From<FromUtf8Error> for ParseError { fn from(err: FromUtf8Error) -> ParseError { ParseError::Utf8(err.utf8_error()) } } impl From<httparse::Error> for ParseError { fn from(err: httparse::Error) -> ParseError { match err { httparse::Error::HeaderName | httparse::Error::HeaderValue | httparse::Error::NewLine | httparse::Error::Token => ParseError::Header, httparse::Error::Status => ParseError::Status, httparse::Error::TooManyHeaders => ParseError::TooLarge, httparse::Error::Version => ParseError::Version, } } } impl From<ParseError> for Error { fn from(err: ParseError) -> Self { Self::new_parse().with_cause(err) } } impl From<ParseError> for Response<BoxBody> { fn from(err: ParseError) -> Self { Error::from(err).into() } } /// A set of errors that can occur during payload parsing. #[derive(Debug, Display)] #[non_exhaustive] pub enum PayloadError { /// A payload reached EOF, but is not complete. #[display("payload reached EOF before completing: {:?}", _0)] Incomplete(Option<io::Error>), /// Content encoding stream corruption. #[display("can not decode content-encoding")] EncodingCorrupted, /// Payload reached size limit. #[display("payload reached size limit")] Overflow, /// Payload length is unknown. #[display("payload length is unknown")] UnknownLength, /// HTTP/2 payload error. #[cfg(feature = "http2")] #[display("{}", _0)] Http2Payload(::h2::Error), /// Generic I/O error. #[display("{}", _0)] Io(io::Error), } impl std::error::Error for PayloadError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { PayloadError::Incomplete(None) => None, PayloadError::Incomplete(Some(err)) => Some(err), PayloadError::EncodingCorrupted => None, PayloadError::Overflow => None, PayloadError::UnknownLength => None, #[cfg(feature = "http2")] PayloadError::Http2Payload(err) => Some(err), PayloadError::Io(err) => Some(err), } } } #[cfg(feature = "http2")] impl From<::h2::Error> for PayloadError { fn from(err: ::h2::Error) -> Self { PayloadError::Http2Payload(err) } } impl From<Option<io::Error>> for PayloadError { fn from(err: Option<io::Error>) -> Self { PayloadError::Incomplete(err) } } impl From<io::Error> for PayloadError { fn from(err: io::Error) -> Self { PayloadError::Incomplete(Some(err)) } } impl From<PayloadError> for Error { fn from(err: PayloadError) -> Self { Self::new_payload().with_cause(err) } } /// A set of errors that can occur during dispatching HTTP requests. #[derive(Debug, Display, From)] #[non_exhaustive] pub enum DispatchError { /// Service error. #[display("service error")] Service(Response<BoxBody>), /// Body streaming error. #[display("body error: {}", _0)] Body(Box<dyn StdError>), /// Upgrade service error. #[display("upgrade error")] Upgrade, /// An `io::Error` that occurred while trying to read or write to a network stream. #[display("I/O error: {}", _0)] Io(io::Error), /// Request parse error. #[display("request parse error: {}", _0)] Parse(ParseError), /// HTTP/2 error. #[display("{}", _0)] #[cfg(feature = "http2")] H2(h2::Error), /// The first request did not complete within the specified timeout. #[display("request did not complete within the specified timeout")] SlowRequestTimeout, /// Disconnect timeout. Makes sense for TLS streams. #[display("connection shutdown timeout")] DisconnectTimeout, /// Handler dropped payload before reading EOF. #[display("handler dropped payload before reading EOF")] HandlerDroppedPayload, /// Internal error. #[display("internal error")] InternalError, } impl StdError for DispatchError { fn source(&self) -> Option<&(dyn StdError + 'static)> { match self { DispatchError::Service(_res) => None, DispatchError::Body(err) => Some(&**err), DispatchError::Io(err) => Some(err), DispatchError::Parse(err) => Some(err), #[cfg(feature = "http2")] DispatchError::H2(err) => Some(err), _ => None, } } } /// A set of error that can occur during parsing content type. #[derive(Debug, Display, Error)] #[cfg_attr(test, derive(PartialEq, Eq))] #[non_exhaustive] pub enum ContentTypeError { /// Can not parse content type. #[display("could not parse content type")] ParseError, /// Unknown content encoding. #[display("unknown content encoding")] UnknownEncoding, } #[cfg(test)] mod tests { use http::Error as HttpError; use super::*; #[test] fn test_into_response() { let resp: Response<BoxBody> = ParseError::Incomplete.into(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into(); let resp: Response<BoxBody> = Error::new_http().with_cause(err).into(); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } #[test] fn test_as_response() { let orig = io::Error::new(io::ErrorKind::Other, "other"); let err: Error = ParseError::Io(orig).into(); assert_eq!( format!("{}", err), "error parsing HTTP message: I/O error: other" ); } #[test] fn test_error_display() { let orig = io::Error::new(io::ErrorKind::Other, "other"); let err = Error::new_io().with_cause(orig); assert_eq!("connection error: other", err.to_string()); } #[test] fn test_error_http_response() { let orig = io::Error::new(io::ErrorKind::Other, "other"); let err = Error::new_io().with_cause(orig); let resp: Response<BoxBody> = err.into(); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } #[test] fn test_payload_error() { let err: PayloadError = io::Error::new(io::ErrorKind::Other, "ParseError").into(); assert!(err.to_string().contains("ParseError")); let err = PayloadError::Incomplete(None); assert_eq!( err.to_string(), "payload reached EOF before completing: None" ); } macro_rules! from { ($from:expr => $error:pat) => { match ParseError::from($from) { err @ $error => { assert!(err.to_string().len() >= 5); } err => unreachable!("{:?}", err), } }; } macro_rules! from_and_cause { ($from:expr => $error:pat) => { match ParseError::from($from) { e @ $error => { let desc = format!("{}", e); assert_eq!(desc, format!("I/O error: {}", $from)); } _ => unreachable!("{:?}", $from), } }; } #[test] fn test_from() { from_and_cause!(io::Error::new(io::ErrorKind::Other, "other") => ParseError::Io(..)); from!(httparse::Error::HeaderName => ParseError::Header); from!(httparse::Error::HeaderName => ParseError::Header); from!(httparse::Error::HeaderValue => ParseError::Header); from!(httparse::Error::NewLine => ParseError::Header); from!(httparse::Error::Status => ParseError::Status); from!(httparse::Error::Token => ParseError::Header); from!(httparse::Error::TooManyHeaders => ParseError::TooLarge); from!(httparse::Error::Version => ParseError::Version); } }
use std::{ any::{Any, TypeId}, collections::HashMap, fmt, hash::{BuildHasherDefault, Hasher}, }; /// A hasher for `TypeId`s that takes advantage of its known characteristics. /// /// Author of `anymap` crate has done research on the topic: /// https://github.com/chris-morgan/anymap/blob/2e9a5704/src/lib.rs#L599 #[derive(Debug, Default)] struct NoOpHasher(u64); impl Hasher for NoOpHasher { fn write(&mut self, _bytes: &[u8]) { unimplemented!("This NoOpHasher can only handle u64s") } fn write_u64(&mut self, i: u64) { self.0 = i; } fn finish(&self) -> u64 { self.0 } } /// A type map for request extensions. /// /// All entries into this map must be owned types (or static references). #[derive(Default)] pub struct Extensions { // use no-op hasher with a std HashMap with for faster lookups on the small `TypeId` keys map: HashMap<TypeId, Box<dyn Any>, BuildHasherDefault<NoOpHasher>>, } impl Extensions { /// Creates an empty `Extensions`. #[inline] pub fn new() -> Extensions { Extensions { map: HashMap::default(), } } /// Insert an item into the map. /// /// If an item of this type was already stored, it will be replaced and returned. /// /// ``` /// # use actix_http::Extensions; /// let mut map = Extensions::new(); /// assert_eq!(map.insert(""), None); /// assert_eq!(map.insert(1u32), None); /// assert_eq!(map.insert(2u32), Some(1u32)); /// assert_eq!(*map.get::<u32>().unwrap(), 2u32); /// ``` pub fn insert<T: 'static>(&mut self, val: T) -> Option<T> { self.map .insert(TypeId::of::<T>(), Box::new(val)) .and_then(downcast_owned) } /// Check if map contains an item of a given type. /// /// ``` /// # use actix_http::Extensions; /// let mut map = Extensions::new(); /// assert!(!map.contains::<u32>()); /// /// assert_eq!(map.insert(1u32), None); /// assert!(map.contains::<u32>()); /// ``` pub fn contains<T: 'static>(&self) -> bool { self.map.contains_key(&TypeId::of::<T>()) } /// Get a reference to an item of a given type. /// /// ``` /// # use actix_http::Extensions; /// let mut map = Extensions::new(); /// map.insert(1u32); /// assert_eq!(map.get::<u32>(), Some(&1u32)); /// ``` pub fn get<T: 'static>(&self) -> Option<&T> { self.map .get(&TypeId::of::<T>()) .and_then(|boxed| boxed.downcast_ref()) } /// Get a mutable reference to an item of a given type. /// /// ``` /// # use actix_http::Extensions; /// let mut map = Extensions::new(); /// map.insert(1u32); /// assert_eq!(map.get_mut::<u32>(), Some(&mut 1u32)); /// ``` pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> { self.map .get_mut(&TypeId::of::<T>()) .and_then(|boxed| boxed.downcast_mut()) } /// Inserts the given `value` into the extensions if it is not present, then returns a reference /// to the value in the extensions. /// /// ``` /// # use actix_http::Extensions; /// let mut map = Extensions::new(); /// assert_eq!(map.get::<Vec<u32>>(), None); /// /// map.get_or_insert(Vec::<u32>::new()).push(1); /// assert_eq!(map.get::<Vec<u32>>(), Some(&vec![1])); /// /// map.get_or_insert(Vec::<u32>::new()).push(2); /// assert_eq!(map.get::<Vec<u32>>(), Some(&vec![1,2])); /// ``` pub fn get_or_insert<T: 'static>(&mut self, value: T) -> &mut T { self.get_or_insert_with(|| value) } /// Inserts a value computed from `f` into the extensions if the given `value` is not present, /// then returns a reference to the value in the extensions. /// /// ``` /// # use actix_http::Extensions; /// let mut map = Extensions::new(); /// assert_eq!(map.get::<Vec<u32>>(), None); /// /// map.get_or_insert_with(Vec::<u32>::new).push(1); /// assert_eq!(map.get::<Vec<u32>>(), Some(&vec![1])); /// /// map.get_or_insert_with(Vec::<u32>::new).push(2); /// assert_eq!(map.get::<Vec<u32>>(), Some(&vec![1,2])); /// ``` pub fn get_or_insert_with<T: 'static, F: FnOnce() -> T>(&mut self, default: F) -> &mut T { self.map .entry(TypeId::of::<T>()) .or_insert_with(|| Box::new(default())) .downcast_mut() .expect("extensions map should now contain a T value") } /// Remove an item from the map of a given type. /// /// If an item of this type was already stored, it will be returned. /// /// ``` /// # use actix_http::Extensions; /// let mut map = Extensions::new(); /// /// map.insert(1u32); /// assert_eq!(map.get::<u32>(), Some(&1u32)); /// /// assert_eq!(map.remove::<u32>(), Some(1u32)); /// assert!(!map.contains::<u32>()); /// ``` pub fn remove<T: 'static>(&mut self) -> Option<T> { self.map.remove(&TypeId::of::<T>()).and_then(downcast_owned) } /// Clear the `Extensions` of all inserted extensions. /// /// ``` /// # use actix_http::Extensions; /// let mut map = Extensions::new(); /// /// map.insert(1u32); /// assert!(map.contains::<u32>()); /// /// map.clear(); /// assert!(!map.contains::<u32>()); /// ``` #[inline] pub fn clear(&mut self) { self.map.clear(); } /// Extends self with the items from another `Extensions`. pub fn extend(&mut self, other: Extensions) { self.map.extend(other.map); } } impl fmt::Debug for Extensions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Extensions").finish() } } fn downcast_owned<T: 'static>(boxed: Box<dyn Any>) -> Option<T> { boxed.downcast().ok().map(|boxed| *boxed) } #[cfg(test)] mod tests { use super::*; #[test] fn test_remove() { let mut map = Extensions::new(); map.insert::<i8>(123); assert!(map.get::<i8>().is_some()); map.remove::<i8>(); assert!(map.get::<i8>().is_none()); } #[test] fn test_clear() { let mut map = Extensions::new(); map.insert::<i8>(8); map.insert::<i16>(16); map.insert::<i32>(32); assert!(map.contains::<i8>()); assert!(map.contains::<i16>()); assert!(map.contains::<i32>()); map.clear(); assert!(!map.contains::<i8>()); assert!(!map.contains::<i16>()); assert!(!map.contains::<i32>()); map.insert::<i8>(10); assert_eq!(*map.get::<i8>().unwrap(), 10); } #[test] fn test_integers() { static A: u32 = 8; let mut map = Extensions::new(); map.insert::<i8>(8); map.insert::<i16>(16); map.insert::<i32>(32); map.insert::<i64>(64); map.insert::<i128>(128); map.insert::<u8>(8); map.insert::<u16>(16); map.insert::<u32>(32); map.insert::<u64>(64); map.insert::<u128>(128); map.insert::<&'static u32>(&A); assert!(map.get::<i8>().is_some()); assert!(map.get::<i16>().is_some()); assert!(map.get::<i32>().is_some()); assert!(map.get::<i64>().is_some()); assert!(map.get::<i128>().is_some()); assert!(map.get::<u8>().is_some()); assert!(map.get::<u16>().is_some()); assert!(map.get::<u32>().is_some()); assert!(map.get::<u64>().is_some()); assert!(map.get::<u128>().is_some()); assert!(map.get::<&'static u32>().is_some()); } #[test] fn test_composition() { struct Magi<T>(pub T); struct Madoka { pub god: bool, } struct Homura { pub attempts: usize, } struct Mami { pub guns: usize, } let mut map = Extensions::new(); map.insert(Magi(Madoka { god: false })); map.insert(Magi(Homura { attempts: 0 })); map.insert(Magi(Mami { guns: 999 })); assert!(!map.get::<Magi<Madoka>>().unwrap().0.god); assert_eq!(0, map.get::<Magi<Homura>>().unwrap().0.attempts); assert_eq!(999, map.get::<Magi<Mami>>().unwrap().0.guns); } #[test] fn test_extensions() { #[derive(Debug, PartialEq)] struct MyType(i32); let mut extensions = Extensions::new(); extensions.insert(5i32); extensions.insert(MyType(10)); assert_eq!(extensions.get(), Some(&5i32)); assert_eq!(extensions.get_mut(), Some(&mut 5i32)); assert_eq!(extensions.remove::<i32>(), Some(5i32)); assert!(extensions.get::<i32>().is_none()); assert_eq!(extensions.get::<bool>(), None); assert_eq!(extensions.get(), Some(&MyType(10))); } #[test] fn test_extend() { #[derive(Debug, PartialEq)] struct MyType(i32); let mut extensions = Extensions::new(); extensions.insert(5i32); extensions.insert(MyType(10)); let mut other = Extensions::new(); other.insert(15i32); other.insert(20u8); extensions.extend(other); assert_eq!(extensions.get(), Some(&15i32)); assert_eq!(extensions.get_mut(), Some(&mut 15i32)); assert_eq!(extensions.remove::<i32>(), Some(15i32)); assert!(extensions.get::<i32>().is_none()); assert_eq!(extensions.get::<bool>(), None); assert_eq!(extensions.get(), Some(&MyType(10))); assert_eq!(extensions.get(), Some(&20u8)); assert_eq!(extensions.get_mut(), Some(&mut 20u8)); } }
use std::{io, task::Poll}; use bytes::{Buf as _, Bytes, BytesMut}; use tracing::{debug, trace}; macro_rules! byte ( ($rdr:ident) => ({ if $rdr.len() > 0 { let b = $rdr[0]; $rdr.advance(1); b } else { return Poll::Pending } }) ); #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum ChunkedState { Size, SizeLws, Extension, SizeLf, Body, BodyCr, BodyLf, EndCr, EndLf, End, } impl ChunkedState { pub(super) fn step( &self, body: &mut BytesMut, size: &mut u64, buf: &mut Option<Bytes>, ) -> Poll<Result<ChunkedState, io::Error>> { use self::ChunkedState::*; match *self { Size => ChunkedState::read_size(body, size), SizeLws => ChunkedState::read_size_lws(body), Extension => ChunkedState::read_extension(body), SizeLf => ChunkedState::read_size_lf(body, *size), Body => ChunkedState::read_body(body, size, buf), BodyCr => ChunkedState::read_body_cr(body), BodyLf => ChunkedState::read_body_lf(body), EndCr => ChunkedState::read_end_cr(body), EndLf => ChunkedState::read_end_lf(body), End => Poll::Ready(Ok(ChunkedState::End)), } } fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<Result<ChunkedState, io::Error>> { let radix = 16; let rem = match byte!(rdr) { b @ b'0'..=b'9' => b - b'0', b @ b'a'..=b'f' => b + 10 - b'a', b @ b'A'..=b'F' => b + 10 - b'A', b'\t' | b' ' => return Poll::Ready(Ok(ChunkedState::SizeLws)), b';' => return Poll::Ready(Ok(ChunkedState::Extension)), b'\r' => return Poll::Ready(Ok(ChunkedState::SizeLf)), _ => { return Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk size line: Invalid Size", ))); } }; match size.checked_mul(radix) { Some(n) => { *size = n; *size += rem as u64; Poll::Ready(Ok(ChunkedState::Size)) } None => { debug!("chunk size would overflow u64"); Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk size line: Size is too big", ))) } } } fn read_size_lws(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> { match byte!(rdr) { // LWS can follow the chunk size, but no more digits can come b'\t' | b' ' => Poll::Ready(Ok(ChunkedState::SizeLws)), b';' => Poll::Ready(Ok(ChunkedState::Extension)), b'\r' => Poll::Ready(Ok(ChunkedState::SizeLf)), _ => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk size linear white space", ))), } } fn read_extension(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> { match byte!(rdr) { b'\r' => Poll::Ready(Ok(ChunkedState::SizeLf)), // strictly 0x20 (space) should be disallowed but we don't parse quoted strings here 0x00..=0x08 | 0x0a..=0x1f | 0x7f => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid character in chunk extension", ))), _ => Poll::Ready(Ok(ChunkedState::Extension)), // no supported extensions } } fn read_size_lf(rdr: &mut BytesMut, size: u64) -> Poll<Result<ChunkedState, io::Error>> { match byte!(rdr) { b'\n' if size > 0 => Poll::Ready(Ok(ChunkedState::Body)), b'\n' if size == 0 => Poll::Ready(Ok(ChunkedState::EndCr)), _ => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk size LF", ))), } } fn read_body( rdr: &mut BytesMut, rem: &mut u64, buf: &mut Option<Bytes>, ) -> Poll<Result<ChunkedState, io::Error>> { trace!("Chunked read, remaining={:?}", rem); let len = rdr.len() as u64; if len == 0 { Poll::Ready(Ok(ChunkedState::Body)) } else { let slice; if *rem > len { slice = rdr.split().freeze(); *rem -= len; } else { slice = rdr.split_to(*rem as usize).freeze(); *rem = 0; } *buf = Some(slice); if *rem > 0 { Poll::Ready(Ok(ChunkedState::Body)) } else { Poll::Ready(Ok(ChunkedState::BodyCr)) } } } fn read_body_cr(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> { match byte!(rdr) { b'\r' => Poll::Ready(Ok(ChunkedState::BodyLf)), _ => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk body CR", ))), } } fn read_body_lf(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> { match byte!(rdr) { b'\n' => Poll::Ready(Ok(ChunkedState::Size)), _ => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk body LF", ))), } } fn read_end_cr(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> { match byte!(rdr) { b'\r' => Poll::Ready(Ok(ChunkedState::EndLf)), _ => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk end CR", ))), } } fn read_end_lf(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, io::Error>> { match byte!(rdr) { b'\n' => Poll::Ready(Ok(ChunkedState::End)), _ => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk end LF", ))), } } } #[cfg(test)] mod tests { use actix_codec::Decoder as _; use bytes::{Bytes, BytesMut}; use http::Method; use crate::{ error::ParseError, h1::decoder::{MessageDecoder, PayloadItem}, HttpMessage as _, Request, }; macro_rules! parse_ready { ($e:expr) => {{ match MessageDecoder::<Request>::default().decode($e) { Ok(Some((msg, _))) => msg, Ok(_) => unreachable!("Eof during parsing http request"), Err(err) => unreachable!("Error during parsing http request: {:?}", err), } }}; } macro_rules! expect_parse_err { ($e:expr) => {{ match MessageDecoder::<Request>::default().decode($e) { Err(err) => match err { ParseError::Io(_) => unreachable!("Parse error expected"), _ => {} }, _ => unreachable!("Error expected"), } }}; } #[test] fn test_parse_chunked_payload_chunk_extension() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\ \r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (msg, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); assert!(msg.chunked().unwrap()); buf.extend(b"4;test\r\ndata\r\n4\r\nline\r\n0\r\n\r\n"); // test: test\r\n\r\n") let chunk = pl.decode(&mut buf).unwrap().unwrap().chunk(); assert_eq!(chunk, Bytes::from_static(b"data")); let chunk = pl.decode(&mut buf).unwrap().unwrap().chunk(); assert_eq!(chunk, Bytes::from_static(b"line")); let msg = pl.decode(&mut buf).unwrap().unwrap(); assert!(msg.eof()); } #[test] fn test_request_chunked() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\r\n", ); let req = parse_ready!(&mut buf); if let Ok(val) = req.chunked() { assert!(val); } else { unreachable!("Error"); } // intentional typo in "chunked" let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ transfer-encoding: chnked\r\n\r\n", ); expect_parse_err!(&mut buf); } #[test] fn test_http_request_chunked_payload() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (req, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); assert!(req.chunked().unwrap()); buf.extend(b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n"); assert_eq!( pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(), b"data" ); assert_eq!( pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(), b"line" ); assert!(pl.decode(&mut buf).unwrap().unwrap().eof()); } #[test] fn test_http_request_chunked_payload_and_next_message() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (req, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); assert!(req.chunked().unwrap()); buf.extend( b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n\ POST /test2 HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\r\n" .iter(), ); let msg = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(msg.chunk().as_ref(), b"data"); let msg = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(msg.chunk().as_ref(), b"line"); let msg = pl.decode(&mut buf).unwrap().unwrap(); assert!(msg.eof()); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert!(req.chunked().unwrap()); assert_eq!(*req.method(), Method::POST); assert!(req.chunked().unwrap()); } #[test] fn test_http_request_chunked_payload_chunks() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (req, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); assert!(req.chunked().unwrap()); buf.extend(b"4\r\n1111\r\n"); let msg = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(msg.chunk().as_ref(), b"1111"); buf.extend(b"4\r\ndata\r"); let msg = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(msg.chunk().as_ref(), b"data"); buf.extend(b"\n4"); assert!(pl.decode(&mut buf).unwrap().is_none()); buf.extend(b"\r"); assert!(pl.decode(&mut buf).unwrap().is_none()); buf.extend(b"\n"); assert!(pl.decode(&mut buf).unwrap().is_none()); buf.extend(b"li"); let msg = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(msg.chunk().as_ref(), b"li"); //trailers //buf.feed_data("test: test\r\n"); //not_ready!(reader.parse(&mut buf, &mut readbuf)); buf.extend(b"ne\r\n0\r\n"); let msg = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(msg.chunk().as_ref(), b"ne"); assert!(pl.decode(&mut buf).unwrap().is_none()); buf.extend(b"\r\n"); assert!(pl.decode(&mut buf).unwrap().unwrap().eof()); } #[test] fn chunk_extension_quoted() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Transfer-Encoding: chunked\r\n\ \r\n\ 2;hello=b;one=\"1 2 3\"\r\n\ xx", ); let mut reader = MessageDecoder::<Request>::default(); let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); let chunk = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"xx"))); } #[test] fn hrs_chunk_extension_invalid() { let mut buf = BytesMut::from( "GET / HTTP/1.1\r\n\ Host: localhost:8080\r\n\ Transfer-Encoding: chunked\r\n\ \r\n\ 2;x\nx\r\n\ 4c\r\n\ 0\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); let err = pl.decode(&mut buf).unwrap_err(); assert!(err .to_string() .contains("Invalid character in chunk extension")); } #[test] fn hrs_chunk_size_overflow() { let mut buf = BytesMut::from( "GET / HTTP/1.1\r\n\ Host: example.com\r\n\ Transfer-Encoding: chunked\r\n\ \r\n\ f0000000000000003\r\n\ abc\r\n\ 0\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); let err = pl.decode(&mut buf).unwrap_err(); assert!(err .to_string() .contains("Invalid chunk size line: Size is too big")); } }
use std::{fmt, io}; use bitflags::bitflags; use bytes::{Bytes, BytesMut}; use http::{Method, Version}; use tokio_util::codec::{Decoder, Encoder}; use super::{ decoder::{self, PayloadDecoder, PayloadItem, PayloadType}, encoder, reserve_readbuf, Message, MessageType, }; use crate::{ body::BodySize, error::{ParseError, PayloadError}, ConnectionType, RequestHeadType, ResponseHead, ServiceConfig, }; bitflags! { #[derive(Debug, Clone, Copy)] struct Flags: u8 { const HEAD = 0b0000_0001; const KEEP_ALIVE_ENABLED = 0b0000_1000; const STREAM = 0b0001_0000; } } /// HTTP/1 Codec pub struct ClientCodec { inner: ClientCodecInner, } /// HTTP/1 Payload Codec pub struct ClientPayloadCodec { inner: ClientCodecInner, } struct ClientCodecInner { config: ServiceConfig, decoder: decoder::MessageDecoder<ResponseHead>, payload: Option<PayloadDecoder>, version: Version, conn_type: ConnectionType, // encoder part flags: Flags, encoder: encoder::MessageEncoder<RequestHeadType>, } impl Default for ClientCodec { fn default() -> Self { ClientCodec::new(ServiceConfig::default()) } } impl fmt::Debug for ClientCodec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("h1::ClientCodec") .field("flags", &self.inner.flags) .finish_non_exhaustive() } } impl ClientCodec { /// Create HTTP/1 codec. /// /// `keepalive_enabled` how response `connection` header get generated. pub fn new(config: ServiceConfig) -> Self { let flags = if config.keep_alive().enabled() { Flags::KEEP_ALIVE_ENABLED } else { Flags::empty() }; ClientCodec { inner: ClientCodecInner { config, decoder: decoder::MessageDecoder::default(), payload: None, version: Version::HTTP_11, conn_type: ConnectionType::Close, flags, encoder: encoder::MessageEncoder::default(), }, } } /// Check if request is upgrade pub fn upgrade(&self) -> bool { self.inner.conn_type == ConnectionType::Upgrade } /// Check if last response is keep-alive pub fn keep_alive(&self) -> bool { self.inner.conn_type == ConnectionType::KeepAlive } /// Check last request's message type pub fn message_type(&self) -> MessageType { if self.inner.flags.contains(Flags::STREAM) { MessageType::Stream } else if self.inner.payload.is_none() { MessageType::None } else { MessageType::Payload } } /// Convert message codec to a payload codec pub fn into_payload_codec(self) -> ClientPayloadCodec { ClientPayloadCodec { inner: self.inner } } } impl ClientPayloadCodec { /// Check if last response is keep-alive pub fn keep_alive(&self) -> bool { self.inner.conn_type == ConnectionType::KeepAlive } /// Transform payload codec to a message codec pub fn into_message_codec(self) -> ClientCodec { ClientCodec { inner: self.inner } } } impl Decoder for ClientCodec { type Item = ResponseHead; type Error = ParseError; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { debug_assert!( self.inner.payload.is_none(), "Payload decoder should not be set" ); if let Some((req, payload)) = self.inner.decoder.decode(src)? { if let Some(conn_type) = req.conn_type() { // do not use peer's keep-alive self.inner.conn_type = if conn_type == ConnectionType::KeepAlive { self.inner.conn_type } else { conn_type }; } if !self.inner.flags.contains(Flags::HEAD) { match payload { PayloadType::None => self.inner.payload = None, PayloadType::Payload(pl) => self.inner.payload = Some(pl), PayloadType::Stream(pl) => { self.inner.payload = Some(pl); self.inner.flags.insert(Flags::STREAM); } } } else { self.inner.payload = None; } reserve_readbuf(src); Ok(Some(req)) } else { Ok(None) } } } impl Decoder for ClientPayloadCodec { type Item = Option<Bytes>; type Error = PayloadError; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { debug_assert!( self.inner.payload.is_some(), "Payload decoder is not specified" ); Ok(match self.inner.payload.as_mut().unwrap().decode(src)? { Some(PayloadItem::Chunk(chunk)) => { reserve_readbuf(src); Some(Some(chunk)) } Some(PayloadItem::Eof) => { self.inner.payload.take(); Some(None) } None => None, }) } } impl Encoder<Message<(RequestHeadType, BodySize)>> for ClientCodec { type Error = io::Error; fn encode( &mut self, item: Message<(RequestHeadType, BodySize)>, dst: &mut BytesMut, ) -> Result<(), Self::Error> { match item { Message::Item((mut head, length)) => { let inner = &mut self.inner; inner.version = head.as_ref().version; inner .flags .set(Flags::HEAD, head.as_ref().method == Method::HEAD); // connection status inner.conn_type = match head.as_ref().connection_type() { ConnectionType::KeepAlive => { if inner.flags.contains(Flags::KEEP_ALIVE_ENABLED) { ConnectionType::KeepAlive } else { ConnectionType::Close } } ConnectionType::Upgrade => ConnectionType::Upgrade, ConnectionType::Close => ConnectionType::Close, }; inner.encoder.encode( dst, &mut head, false, false, inner.version, length, inner.conn_type, &inner.config, )?; } Message::Chunk(Some(bytes)) => { self.inner.encoder.encode_chunk(bytes.as_ref(), dst)?; } Message::Chunk(None) => { self.inner.encoder.encode_eof(dst)?; } } Ok(()) } }
use std::{fmt, io}; use bitflags::bitflags; use bytes::BytesMut; use http::{Method, Version}; use tokio_util::codec::{Decoder, Encoder}; use super::{ decoder::{self, PayloadDecoder, PayloadItem, PayloadType}, encoder, Message, MessageType, }; use crate::{body::BodySize, error::ParseError, ConnectionType, Request, Response, ServiceConfig}; bitflags! { #[derive(Debug, Clone, Copy)] struct Flags: u8 { const HEAD = 0b0000_0001; const KEEP_ALIVE_ENABLED = 0b0000_0010; const STREAM = 0b0000_0100; } } /// HTTP/1 Codec pub struct Codec { config: ServiceConfig, decoder: decoder::MessageDecoder<Request>, payload: Option<PayloadDecoder>, version: Version, conn_type: ConnectionType, // encoder part flags: Flags, encoder: encoder::MessageEncoder<Response<()>>, } impl Default for Codec { fn default() -> Self { Codec::new(ServiceConfig::default()) } } impl fmt::Debug for Codec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("h1::Codec") .field("flags", &self.flags) .finish_non_exhaustive() } } impl Codec { /// Create HTTP/1 codec. /// /// `keepalive_enabled` how response `connection` header get generated. pub fn new(config: ServiceConfig) -> Self { let flags = if config.keep_alive().enabled() { Flags::KEEP_ALIVE_ENABLED } else { Flags::empty() }; Codec { config, flags, decoder: decoder::MessageDecoder::default(), payload: None, version: Version::HTTP_11, conn_type: ConnectionType::Close, encoder: encoder::MessageEncoder::default(), } } /// Check if request is upgrade. #[inline] pub fn upgrade(&self) -> bool { self.conn_type == ConnectionType::Upgrade } /// Check if last response is keep-alive. #[inline] pub fn keep_alive(&self) -> bool { self.conn_type == ConnectionType::KeepAlive } /// Check if keep-alive enabled on server level. #[inline] pub fn keep_alive_enabled(&self) -> bool { self.flags.contains(Flags::KEEP_ALIVE_ENABLED) } /// Check last request's message type. #[inline] pub fn message_type(&self) -> MessageType { if self.flags.contains(Flags::STREAM) { MessageType::Stream } else if self.payload.is_none() { MessageType::None } else { MessageType::Payload } } #[inline] pub fn config(&self) -> &ServiceConfig { &self.config } } impl Decoder for Codec { type Item = Message<Request>; type Error = ParseError; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { if let Some(ref mut payload) = self.payload { Ok(match payload.decode(src)? { Some(PayloadItem::Chunk(chunk)) => Some(Message::Chunk(Some(chunk))), Some(PayloadItem::Eof) => { self.payload.take(); Some(Message::Chunk(None)) } None => None, }) } else if let Some((req, payload)) = self.decoder.decode(src)? { let head = req.head(); self.flags.set(Flags::HEAD, head.method == Method::HEAD); self.version = head.version; self.conn_type = head.connection_type(); if self.conn_type == ConnectionType::KeepAlive && !self.flags.contains(Flags::KEEP_ALIVE_ENABLED) { self.conn_type = ConnectionType::Close } match payload { PayloadType::None => self.payload = None, PayloadType::Payload(pl) => self.payload = Some(pl), PayloadType::Stream(pl) => { self.payload = Some(pl); self.flags.insert(Flags::STREAM); } } Ok(Some(Message::Item(req))) } else { Ok(None) } } } impl Encoder<Message<(Response<()>, BodySize)>> for Codec { type Error = io::Error; fn encode( &mut self, item: Message<(Response<()>, BodySize)>, dst: &mut BytesMut, ) -> Result<(), Self::Error> { match item { Message::Item((mut res, length)) => { // set response version res.head_mut().version = self.version; // connection status self.conn_type = if let Some(ct) = res.head().conn_type() { if ct == ConnectionType::KeepAlive { self.conn_type } else { ct } } else { self.conn_type }; // encode message self.encoder.encode( dst, &mut res, self.flags.contains(Flags::HEAD), self.flags.contains(Flags::STREAM), self.version, length, self.conn_type, &self.config, )?; } Message::Chunk(Some(bytes)) => { self.encoder.encode_chunk(bytes.as_ref(), dst)?; } Message::Chunk(None) => { self.encoder.encode_eof(dst)?; } } Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::HttpMessage as _; #[actix_rt::test] async fn test_http_request_chunked_payload_and_next_message() { let mut codec = Codec::default(); let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\r\n", ); let item = codec.decode(&mut buf).unwrap().unwrap(); let req = item.message(); assert_eq!(req.method(), Method::GET); assert!(req.chunked().unwrap()); buf.extend( b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n\ POST /test2 HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\r\n" .iter(), ); let msg = codec.decode(&mut buf).unwrap().unwrap(); assert_eq!(msg.chunk().as_ref(), b"data"); let msg = codec.decode(&mut buf).unwrap().unwrap(); assert_eq!(msg.chunk().as_ref(), b"line"); let msg = codec.decode(&mut buf).unwrap().unwrap(); assert!(msg.eof()); // decode next message let item = codec.decode(&mut buf).unwrap().unwrap(); let req = item.message(); assert_eq!(*req.method(), Method::POST); assert!(req.chunked().unwrap()); } }
use std::{io, marker::PhantomData, mem::MaybeUninit, task::Poll}; use actix_codec::Decoder; use bytes::{Bytes, BytesMut}; use http::{ header::{self, HeaderName, HeaderValue}, Method, StatusCode, Uri, Version, }; use tracing::{debug, error, trace}; use super::chunked::ChunkedState; use crate::{error::ParseError, header::HeaderMap, ConnectionType, Request, ResponseHead}; pub(crate) const MAX_BUFFER_SIZE: usize = 131_072; const MAX_HEADERS: usize = 96; /// Incoming message decoder pub(crate) struct MessageDecoder<T: MessageType>(PhantomData<T>); #[derive(Debug)] /// Incoming request type pub(crate) enum PayloadType { None, Payload(PayloadDecoder), Stream(PayloadDecoder), } impl<T: MessageType> Default for MessageDecoder<T> { fn default() -> Self { MessageDecoder(PhantomData) } } impl<T: MessageType> Decoder for MessageDecoder<T> { type Item = (T, PayloadType); type Error = ParseError; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { T::decode(src) } } pub(crate) enum PayloadLength { Payload(PayloadType), UpgradeWebSocket, None, } impl PayloadLength { /// Returns true if variant is `None`. fn is_none(&self) -> bool { matches!(self, Self::None) } /// Returns true if variant is represents zero-length (not none) payload. fn is_zero(&self) -> bool { matches!( self, PayloadLength::Payload(PayloadType::Payload(PayloadDecoder { kind: Kind::Length(0) })) ) } } pub(crate) trait MessageType: Sized { fn set_connection_type(&mut self, conn_type: Option<ConnectionType>); fn set_expect(&mut self); fn headers_mut(&mut self) -> &mut HeaderMap; fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError>; fn set_headers( &mut self, slice: &Bytes, raw_headers: &[HeaderIndex], version: Version, ) -> Result<PayloadLength, ParseError> { let mut ka = None; let mut has_upgrade_websocket = false; let mut expect = false; let mut chunked = false; let mut seen_te = false; let mut content_length = None; { let headers = self.headers_mut(); for idx in raw_headers.iter() { let name = HeaderName::from_bytes(&slice[idx.name.0..idx.name.1]).unwrap(); // SAFETY: httparse already checks header value is only visible ASCII bytes // from_maybe_shared_unchecked contains debug assertions so they are omitted here let value = unsafe { HeaderValue::from_maybe_shared_unchecked(slice.slice(idx.value.0..idx.value.1)) }; match name { header::CONTENT_LENGTH if content_length.is_some() => { debug!("multiple Content-Length"); return Err(ParseError::Header); } header::CONTENT_LENGTH => match value.to_str().map(str::trim) { Ok(val) if val.starts_with('+') => { debug!("illegal Content-Length: {:?}", val); return Err(ParseError::Header); } Ok(val) => { if let Ok(len) = val.parse::<u64>() { // accept 0 lengths here and remove them in `decode` after all // headers have been processed to prevent request smuggling issues content_length = Some(len); } else { debug!("illegal Content-Length: {:?}", val); return Err(ParseError::Header); } } Err(_) => { debug!("illegal Content-Length: {:?}", value); return Err(ParseError::Header); } }, // transfer-encoding header::TRANSFER_ENCODING if seen_te => { debug!("multiple Transfer-Encoding not allowed"); return Err(ParseError::Header); } header::TRANSFER_ENCODING if version == Version::HTTP_11 => { seen_te = true; if let Ok(val) = value.to_str().map(str::trim) { if val.eq_ignore_ascii_case("chunked") { chunked = true; } else if val.eq_ignore_ascii_case("identity") { // allow silently since multiple TE headers are already checked } else { debug!("illegal Transfer-Encoding: {:?}", val); return Err(ParseError::Header); } } else { return Err(ParseError::Header); } } // connection keep-alive state header::CONNECTION => { ka = if let Ok(conn) = value.to_str().map(str::trim) { if conn.eq_ignore_ascii_case("keep-alive") { Some(ConnectionType::KeepAlive) } else if conn.eq_ignore_ascii_case("close") { Some(ConnectionType::Close) } else if conn.eq_ignore_ascii_case("upgrade") { Some(ConnectionType::Upgrade) } else { None } } else { None }; } header::UPGRADE => { if let Ok(val) = value.to_str().map(str::trim) { if val.eq_ignore_ascii_case("websocket") { has_upgrade_websocket = true; } } } header::EXPECT => { let bytes = value.as_bytes(); if bytes.len() >= 4 && &bytes[0..4] == b"100-" { expect = true; } } _ => {} } headers.append(name, value); } } self.set_connection_type(ka); if expect { self.set_expect() } // https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3 if chunked { // Chunked encoding Ok(PayloadLength::Payload(PayloadType::Payload( PayloadDecoder::chunked(), ))) } else if has_upgrade_websocket { Ok(PayloadLength::UpgradeWebSocket) } else if let Some(len) = content_length { // Content-Length Ok(PayloadLength::Payload(PayloadType::Payload( PayloadDecoder::length(len), ))) } else { Ok(PayloadLength::None) } } } impl MessageType for Request { fn set_connection_type(&mut self, conn_type: Option<ConnectionType>) { if let Some(ctype) = conn_type { self.head_mut().set_connection_type(ctype); } } fn set_expect(&mut self) { self.head_mut().set_expect(); } fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.head_mut().headers } fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> { let mut headers: [HeaderIndex; MAX_HEADERS] = EMPTY_HEADER_INDEX_ARRAY; let (len, method, uri, ver, h_len) = { // SAFETY: // Create an uninitialized array of `MaybeUninit`. The `assume_init` is safe because the // type we are claiming to have initialized here is a bunch of `MaybeUninit`s, which // do not require initialization. let mut parsed = unsafe { MaybeUninit::<[MaybeUninit<httparse::Header<'_>>; MAX_HEADERS]>::uninit() .assume_init() }; let mut req = httparse::Request::new(&mut []); match req.parse_with_uninit_headers(src, &mut parsed)? { httparse::Status::Complete(len) => { let method = Method::from_bytes(req.method.unwrap().as_bytes()) .map_err(|_| ParseError::Method)?; let uri = Uri::try_from(req.path.unwrap())?; let version = if req.version.unwrap() == 1 { Version::HTTP_11 } else { Version::HTTP_10 }; HeaderIndex::record(src, req.headers, &mut headers); (len, method, uri, version, req.headers.len()) } httparse::Status::Partial => { return if src.len() >= MAX_BUFFER_SIZE { trace!("MAX_BUFFER_SIZE unprocessed data reached, closing"); Err(ParseError::TooLarge) } else { // Return None to notify more read are needed for parsing request Ok(None) }; } } }; let mut msg = Request::new(); // convert headers let mut length = msg.set_headers(&src.split_to(len).freeze(), &headers[..h_len], ver)?; // disallow HTTP/1.0 POST requests that do not contain a Content-Length headers // see https://datatracker.ietf.org/doc/html/rfc1945#section-7.2.2 if ver == Version::HTTP_10 && method == Method::POST && length.is_none() { debug!("no Content-Length specified for HTTP/1.0 POST request"); return Err(ParseError::Header); } // Remove CL value if 0 now that all headers and HTTP/1.0 special cases are processed. // Protects against some request smuggling attacks. // See https://github.com/actix/actix-web/issues/2767. if length.is_zero() { length = PayloadLength::None; } // payload decoder let decoder = match length { PayloadLength::Payload(pl) => pl, PayloadLength::UpgradeWebSocket => { // upgrade (WebSocket) PayloadType::Stream(PayloadDecoder::eof()) } PayloadLength::None => { if method == Method::CONNECT { PayloadType::Stream(PayloadDecoder::eof()) } else { PayloadType::None } } }; let head = msg.head_mut(); head.uri = uri; head.method = method; head.version = ver; Ok(Some((msg, decoder))) } } impl MessageType for ResponseHead { fn set_connection_type(&mut self, conn_type: Option<ConnectionType>) { if let Some(ctype) = conn_type { ResponseHead::set_connection_type(self, ctype); } } fn set_expect(&mut self) {} fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.headers } fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> { let mut headers: [HeaderIndex; MAX_HEADERS] = EMPTY_HEADER_INDEX_ARRAY; let (len, ver, status, h_len) = { // SAFETY: // Create an uninitialized array of `MaybeUninit`. The `assume_init` is safe because the // type we are claiming to have initialized here is a bunch of `MaybeUninit`s, which // do not require initialization. let mut parsed = unsafe { MaybeUninit::<[MaybeUninit<httparse::Header<'_>>; MAX_HEADERS]>::uninit() .assume_init() }; let mut res = httparse::Response::new(&mut []); let mut config = httparse::ParserConfig::default(); config.allow_spaces_after_header_name_in_responses(true); match config.parse_response_with_uninit_headers(&mut res, src, &mut parsed)? { httparse::Status::Complete(len) => { let version = if res.version.unwrap() == 1 { Version::HTTP_11 } else { Version::HTTP_10 }; let status = StatusCode::from_u16(res.code.unwrap()).map_err(|_| ParseError::Status)?; HeaderIndex::record(src, res.headers, &mut headers); (len, version, status, res.headers.len()) } httparse::Status::Partial => { return if src.len() >= MAX_BUFFER_SIZE { error!("MAX_BUFFER_SIZE unprocessed data reached, closing"); Err(ParseError::TooLarge) } else { Ok(None) } } } }; let mut msg = ResponseHead::new(status); msg.version = ver; // convert headers let mut length = msg.set_headers(&src.split_to(len).freeze(), &headers[..h_len], ver)?; // Remove CL value if 0 now that all headers and HTTP/1.0 special cases are processed. // Protects against some request smuggling attacks. // See https://github.com/actix/actix-web/issues/2767. if length.is_zero() { length = PayloadLength::None; } // message payload let decoder = if let PayloadLength::Payload(pl) = length { pl } else if status == StatusCode::SWITCHING_PROTOCOLS { // switching protocol or connect PayloadType::Stream(PayloadDecoder::eof()) } else { // for HTTP/1.0 read to eof and close connection if msg.version == Version::HTTP_10 { msg.set_connection_type(ConnectionType::Close); PayloadType::Payload(PayloadDecoder::eof()) } else { PayloadType::None } }; Ok(Some((msg, decoder))) } } #[derive(Clone, Copy)] pub(crate) struct HeaderIndex { pub(crate) name: (usize, usize), pub(crate) value: (usize, usize), } pub(crate) const EMPTY_HEADER_INDEX: HeaderIndex = HeaderIndex { name: (0, 0), value: (0, 0), }; pub(crate) const EMPTY_HEADER_INDEX_ARRAY: [HeaderIndex; MAX_HEADERS] = [EMPTY_HEADER_INDEX; MAX_HEADERS]; impl HeaderIndex { pub(crate) fn record( bytes: &[u8], headers: &[httparse::Header<'_>], indices: &mut [HeaderIndex], ) { let bytes_ptr = bytes.as_ptr() as usize; for (header, indices) in headers.iter().zip(indices.iter_mut()) { let name_start = header.name.as_ptr() as usize - bytes_ptr; let name_end = name_start + header.name.len(); indices.name = (name_start, name_end); let value_start = header.value.as_ptr() as usize - bytes_ptr; let value_end = value_start + header.value.len(); indices.value = (value_start, value_end); } } } #[derive(Debug, Clone, PartialEq, Eq)] /// Chunk type yielded while decoding a payload. pub enum PayloadItem { Chunk(Bytes), Eof, } /// Decoder that can handle different payload types. /// /// If a message body does not use `Transfer-Encoding`, it should include a `Content-Length`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PayloadDecoder { kind: Kind, } impl PayloadDecoder { /// Constructs a fixed-length payload decoder. pub fn length(x: u64) -> PayloadDecoder { PayloadDecoder { kind: Kind::Length(x), } } /// Constructs a chunked encoding decoder. pub fn chunked() -> PayloadDecoder { PayloadDecoder { kind: Kind::Chunked(ChunkedState::Size, 0), } } /// Creates an decoder that yields chunks until the stream returns EOF. pub fn eof() -> PayloadDecoder { PayloadDecoder { kind: Kind::Eof } } } #[derive(Debug, Clone, PartialEq, Eq)] enum Kind { /// A reader used when a `Content-Length` header is passed with a positive integer. Length(u64), /// A reader used when `Transfer-Encoding` is `chunked`. Chunked(ChunkedState, u64), /// A reader used for responses that don't indicate a length or chunked. /// /// Note: This should only used for `Response`s. It is illegal for a `Request` to be made /// without either of `Content-Length` and `Transfer-Encoding: chunked` missing, as explained /// in [RFC 7230 §3.3.3]: /// /// > If a Transfer-Encoding header field is present in a response and the chunked transfer /// > coding is not the final encoding, the message body length is determined by reading the /// > connection until it is closed by the server. If a Transfer-Encoding header field is /// > present in a request and the chunked transfer coding is not the final encoding, the /// > message body length cannot be determined reliably; the server MUST respond with the 400 /// > (Bad Request) status code and then close the connection. /// /// [RFC 7230 §3.3.3]: https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3 Eof, } impl Decoder for PayloadDecoder { type Item = PayloadItem; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { match self.kind { Kind::Length(ref mut remaining) => { if *remaining == 0 { Ok(Some(PayloadItem::Eof)) } else { if src.is_empty() { return Ok(None); } let len = src.len() as u64; let buf; if *remaining > len { buf = src.split().freeze(); *remaining -= len; } else { buf = src.split_to(*remaining as usize).freeze(); *remaining = 0; }; trace!("Length read: {}", buf.len()); Ok(Some(PayloadItem::Chunk(buf))) } } Kind::Chunked(ref mut state, ref mut size) => { loop { let mut buf = None; // advances the chunked state *state = match state.step(src, size, &mut buf) { Poll::Pending => return Ok(None), Poll::Ready(Ok(state)) => state, Poll::Ready(Err(err)) => return Err(err), }; if *state == ChunkedState::End { trace!("End of chunked stream"); return Ok(Some(PayloadItem::Eof)); } if let Some(buf) = buf { return Ok(Some(PayloadItem::Chunk(buf))); } if src.is_empty() { return Ok(None); } } } Kind::Eof => { if src.is_empty() { Ok(None) } else { Ok(Some(PayloadItem::Chunk(src.split().freeze()))) } } } } } #[cfg(test)] mod tests { use super::*; use crate::{header::SET_COOKIE, HttpMessage as _}; impl PayloadType { pub(crate) fn unwrap(self) -> PayloadDecoder { match self { PayloadType::Payload(pl) => pl, _ => panic!(), } } pub(crate) fn is_unhandled(&self) -> bool { matches!(self, PayloadType::Stream(_)) } } impl PayloadItem { pub(crate) fn chunk(self) -> Bytes { match self { PayloadItem::Chunk(chunk) => chunk, _ => panic!("error"), } } pub(crate) fn eof(&self) -> bool { matches!(*self, PayloadItem::Eof) } } macro_rules! parse_ready { ($e:expr) => {{ match MessageDecoder::<Request>::default().decode($e) { Ok(Some((msg, _))) => msg, Ok(_) => unreachable!("Eof during parsing http request"), Err(err) => unreachable!("Error during parsing http request: {:?}", err), } }}; } macro_rules! expect_parse_err { ($e:expr) => {{ match MessageDecoder::<Request>::default().decode($e) { Err(err) => match err { ParseError::Io(_) => unreachable!("Parse error expected"), _ => {} }, _ => unreachable!("Error expected"), } }}; } #[test] fn test_parse() { let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n\r\n"); let mut reader = MessageDecoder::<Request>::default(); match reader.decode(&mut buf) { Ok(Some((req, _))) => { assert_eq!(req.version(), Version::HTTP_11); assert_eq!(*req.method(), Method::GET); assert_eq!(req.path(), "/test"); } Ok(_) | Err(_) => unreachable!("Error during parsing http request"), } } #[test] fn test_parse_partial() { let mut buf = BytesMut::from("PUT /test HTTP/1"); let mut reader = MessageDecoder::<Request>::default(); assert!(reader.decode(&mut buf).unwrap().is_none()); buf.extend(b".1\r\n\r\n"); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.version(), Version::HTTP_11); assert_eq!(*req.method(), Method::PUT); assert_eq!(req.path(), "/test"); } #[test] fn parse_h09_reject() { let mut buf = BytesMut::from( "GET /test1 HTTP/0.9\r\n\ \r\n", ); let mut reader = MessageDecoder::<Request>::default(); reader.decode(&mut buf).unwrap_err(); let mut buf = BytesMut::from( "POST /test2 HTTP/0.9\r\n\ Content-Length: 3\r\n\ \r\n abc", ); let mut reader = MessageDecoder::<Request>::default(); reader.decode(&mut buf).unwrap_err(); } #[test] fn parse_h10_get() { let mut buf = BytesMut::from( "GET /test1 HTTP/1.0\r\n\ \r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.version(), Version::HTTP_10); assert_eq!(*req.method(), Method::GET); assert_eq!(req.path(), "/test1"); let mut buf = BytesMut::from( "GET /test2 HTTP/1.0\r\n\ Content-Length: 0\r\n\ \r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.version(), Version::HTTP_10); assert_eq!(*req.method(), Method::GET); assert_eq!(req.path(), "/test2"); let mut buf = BytesMut::from( "GET /test3 HTTP/1.0\r\n\ Content-Length: 3\r\n\ \r\n abc", ); let mut reader = MessageDecoder::<Request>::default(); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.version(), Version::HTTP_10); assert_eq!(*req.method(), Method::GET); assert_eq!(req.path(), "/test3"); } #[test] fn parse_h10_post() { let mut buf = BytesMut::from( "POST /test1 HTTP/1.0\r\n\ Content-Length: 3\r\n\ \r\n\ abc", ); let mut reader = MessageDecoder::<Request>::default(); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.version(), Version::HTTP_10); assert_eq!(*req.method(), Method::POST); assert_eq!(req.path(), "/test1"); let mut buf = BytesMut::from( "POST /test2 HTTP/1.0\r\n\ Content-Length: 0\r\n\ \r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.version(), Version::HTTP_10); assert_eq!(*req.method(), Method::POST); assert_eq!(req.path(), "/test2"); let mut buf = BytesMut::from( "POST /test3 HTTP/1.0\r\n\ \r\n", ); let mut reader = MessageDecoder::<Request>::default(); let err = reader.decode(&mut buf).unwrap_err(); assert!(err.to_string().contains("Header")) } #[test] fn test_parse_body() { let mut buf = BytesMut::from("GET /test HTTP/1.1\r\nContent-Length: 4\r\n\r\nbody"); let mut reader = MessageDecoder::<Request>::default(); let (req, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); assert_eq!(req.version(), Version::HTTP_11); assert_eq!(*req.method(), Method::GET); assert_eq!(req.path(), "/test"); assert_eq!( pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(), b"body" ); } #[test] fn test_parse_body_crlf() { let mut buf = BytesMut::from("\r\nGET /test HTTP/1.1\r\nContent-Length: 4\r\n\r\nbody"); let mut reader = MessageDecoder::<Request>::default(); let (req, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); assert_eq!(req.version(), Version::HTTP_11); assert_eq!(*req.method(), Method::GET); assert_eq!(req.path(), "/test"); assert_eq!( pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(), b"body" ); } #[test] fn test_parse_partial_eof() { let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n"); let mut reader = MessageDecoder::<Request>::default(); assert!(reader.decode(&mut buf).unwrap().is_none()); buf.extend(b"\r\n"); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.version(), Version::HTTP_11); assert_eq!(*req.method(), Method::GET); assert_eq!(req.path(), "/test"); } #[test] fn test_headers_split_field() { let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n"); let mut reader = MessageDecoder::<Request>::default(); assert! { reader.decode(&mut buf).unwrap().is_none() } buf.extend(b"t"); assert! { reader.decode(&mut buf).unwrap().is_none() } buf.extend(b"es"); assert! { reader.decode(&mut buf).unwrap().is_none() } buf.extend(b"t: value\r\n\r\n"); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.version(), Version::HTTP_11); assert_eq!(*req.method(), Method::GET); assert_eq!(req.path(), "/test"); assert_eq!( req.headers() .get(HeaderName::try_from("test").unwrap()) .unwrap() .as_bytes(), b"value" ); } #[test] fn test_headers_multi_value() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ Set-Cookie: c1=cookie1\r\n\ Set-Cookie: c2=cookie2\r\n\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); let val: Vec<_> = req .headers() .get_all(SET_COOKIE) .map(|v| v.to_str().unwrap().to_owned()) .collect(); assert_eq!(val[0], "c1=cookie1"); assert_eq!(val[1], "c2=cookie2"); } #[test] fn test_conn_default_1_0() { let req = parse_ready!(&mut BytesMut::from("GET /test HTTP/1.0\r\n\r\n")); assert_eq!(req.head().connection_type(), ConnectionType::Close); } #[test] fn test_conn_default_1_1() { let req = parse_ready!(&mut BytesMut::from("GET /test HTTP/1.1\r\n\r\n")); assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive); } #[test] fn test_conn_close() { let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ connection: close\r\n\r\n", )); assert_eq!(req.head().connection_type(), ConnectionType::Close); let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ connection: Close\r\n\r\n", )); assert_eq!(req.head().connection_type(), ConnectionType::Close); } #[test] fn test_conn_close_1_0() { let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.0\r\n\ connection: close\r\n\r\n", )); assert_eq!(req.head().connection_type(), ConnectionType::Close); } #[test] fn test_conn_keep_alive_1_0() { let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.0\r\n\ connection: keep-alive\r\n\r\n", )); assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive); let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.0\r\n\ connection: Keep-Alive\r\n\r\n", )); assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive); } #[test] fn test_conn_keep_alive_1_1() { let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ connection: keep-alive\r\n\r\n", )); assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive); } #[test] fn test_conn_other_1_0() { let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.0\r\n\ connection: other\r\n\r\n", )); assert_eq!(req.head().connection_type(), ConnectionType::Close); } #[test] fn test_conn_other_1_1() { let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ connection: other\r\n\r\n", )); assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive); } #[test] fn test_conn_upgrade() { let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ upgrade: websockets\r\n\ connection: upgrade\r\n\r\n", )); assert!(req.upgrade()); assert_eq!(req.head().connection_type(), ConnectionType::Upgrade); let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ upgrade: Websockets\r\n\ connection: Upgrade\r\n\r\n", )); assert!(req.upgrade()); assert_eq!(req.head().connection_type(), ConnectionType::Upgrade); } #[test] fn test_conn_upgrade_connect_method() { let req = parse_ready!(&mut BytesMut::from( "CONNECT /test HTTP/1.1\r\n\ content-type: text/plain\r\n\r\n", )); assert!(req.upgrade()); } #[test] fn test_headers_bad_content_length() { // string CL expect_parse_err!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ content-length: line\r\n\r\n", )); // negative CL expect_parse_err!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ content-length: -1\r\n\r\n", )); } #[test] fn octal_ish_cl_parsed_as_decimal() { let mut buf = BytesMut::from( "POST /test HTTP/1.1\r\n\ content-length: 011\r\n\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (_req, pl) = reader.decode(&mut buf).unwrap().unwrap(); assert!(matches!( pl, PayloadType::Payload(pl) if pl == PayloadDecoder::length(11) )); } #[test] fn test_invalid_header() { expect_parse_err!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ test line\r\n\r\n", )); } #[test] fn test_invalid_name() { expect_parse_err!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ test[]: line\r\n\r\n", )); } #[test] fn test_http_request_bad_status_line() { expect_parse_err!(&mut BytesMut::from("getpath \r\n\r\n")); } #[test] fn test_http_request_upgrade_websocket() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ connection: upgrade\r\n\ upgrade: websocket\r\n\r\n\ some raw data", ); let mut reader = MessageDecoder::<Request>::default(); let (req, pl) = reader.decode(&mut buf).unwrap().unwrap(); assert_eq!(req.head().connection_type(), ConnectionType::Upgrade); assert!(req.upgrade()); assert!(pl.is_unhandled()); } #[test] fn test_http_request_upgrade_h2c() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ connection: upgrade, http2-settings\r\n\ upgrade: h2c\r\n\ http2-settings: dummy\r\n\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (req, pl) = reader.decode(&mut buf).unwrap().unwrap(); // `connection: upgrade, http2-settings` doesn't work properly.. // see MessageType::set_headers(). // // The line below should be: // assert_eq!(req.head().connection_type(), ConnectionType::Upgrade); assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive); assert!(req.upgrade()); assert!(!pl.is_unhandled()); } #[test] fn test_http_request_parser_utf8() { let req = parse_ready!(&mut BytesMut::from( "GET /test HTTP/1.1\r\n\ x-test: тест\r\n\r\n", )); assert_eq!( req.headers().get("x-test").unwrap().as_bytes(), "тест".as_bytes() ); } #[test] fn test_http_request_parser_two_slashes() { let req = parse_ready!(&mut BytesMut::from("GET //path HTTP/1.1\r\n\r\n")); assert_eq!(req.path(), "//path"); } #[test] fn test_http_request_parser_bad_method() { expect_parse_err!(&mut BytesMut::from("!12%()+=~$ /get HTTP/1.1\r\n\r\n")); } #[test] fn test_http_request_parser_bad_version() { expect_parse_err!(&mut BytesMut::from("GET //get HT/11\r\n\r\n")); } #[test] fn test_response_http10_read_until_eof() { let mut buf = BytesMut::from("HTTP/1.0 200 Ok\r\n\r\ntest data"); let mut reader = MessageDecoder::<ResponseHead>::default(); let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); let chunk = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"test data"))); } #[test] fn hrs_multiple_content_length() { expect_parse_err!(&mut BytesMut::from( "GET / HTTP/1.1\r\n\ Host: example.com\r\n\ Content-Length: 4\r\n\ Content-Length: 2\r\n\ \r\n\ abcd", )); expect_parse_err!(&mut BytesMut::from( "GET / HTTP/1.1\r\n\ Host: example.com\r\n\ Content-Length: 0\r\n\ Content-Length: 2\r\n\ \r\n\ ab", )); } #[test] fn hrs_content_length_plus() { expect_parse_err!(&mut BytesMut::from( "GET / HTTP/1.1\r\n\ Host: example.com\r\n\ Content-Length: +3\r\n\ \r\n\ 000", )); } #[test] fn hrs_te_http10() { // in HTTP/1.0 transfer encoding is ignored and must therefore contain a CL header expect_parse_err!(&mut BytesMut::from( "POST / HTTP/1.0\r\n\ Host: example.com\r\n\ Transfer-Encoding: chunked\r\n\ \r\n\ 3\r\n\ aaa\r\n\ 0\r\n\ ", )); } #[test] fn hrs_cl_and_te_http10() { // in HTTP/1.0 transfer encoding is simply ignored so it's fine to have both let mut buf = BytesMut::from( "GET / HTTP/1.0\r\n\ Host: example.com\r\n\ Content-Length: 3\r\n\ Transfer-Encoding: chunked\r\n\ \r\n\ 000", ); parse_ready!(&mut buf); } #[test] fn hrs_unknown_transfer_encoding() { let mut buf = BytesMut::from( "GET / HTTP/1.1\r\n\ Host: example.com\r\n\ Transfer-Encoding: JUNK\r\n\ Transfer-Encoding: chunked\r\n\ \r\n\ 5\r\n\ hello\r\n\ 0", ); expect_parse_err!(&mut buf); } #[test] fn hrs_multiple_transfer_encoding() { let mut buf = BytesMut::from( "GET / HTTP/1.1\r\n\ Host: example.com\r\n\ Content-Length: 51\r\n\ Transfer-Encoding: identity\r\n\ Transfer-Encoding: chunked\r\n\ \r\n\ 0\r\n\ \r\n\ GET /forbidden HTTP/1.1\r\n\ Host: example.com\r\n\r\n", ); expect_parse_err!(&mut buf); } #[test] fn transfer_encoding_agrees() { let mut buf = BytesMut::from( "GET /test HTTP/1.1\r\n\ Host: example.com\r\n\ Content-Length: 3\r\n\ Transfer-Encoding: identity\r\n\ \r\n\ 0\r\n", ); let mut reader = MessageDecoder::<Request>::default(); let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap(); let mut pl = pl.unwrap(); let chunk = pl.decode(&mut buf).unwrap().unwrap(); assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"0\r\n"))); } }
use std::{ collections::VecDeque, fmt, future::Future, io, mem, net, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_codec::{Framed, FramedParts}; use actix_rt::time::sleep_until; use actix_service::Service; use bitflags::bitflags; use bytes::{Buf, BytesMut}; use futures_core::ready; use pin_project_lite::pin_project; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_util::codec::{Decoder as _, Encoder as _}; use tracing::{error, trace}; use super::{ codec::Codec, decoder::MAX_BUFFER_SIZE, payload::{Payload, PayloadSender, PayloadStatus}, timer::TimerState, Message, MessageType, }; use crate::{ body::{BodySize, BoxBody, MessageBody}, config::ServiceConfig, error::{DispatchError, ParseError, PayloadError}, service::HttpFlow, Error, Extensions, OnConnectData, Request, Response, StatusCode, }; const LW_BUFFER_SIZE: usize = 1024; const HW_BUFFER_SIZE: usize = 1024 * 8; const MAX_PIPELINED_MESSAGES: usize = 16; bitflags! { #[derive(Debug, Clone, Copy)] pub struct Flags: u8 { /// Set when stream is read for first time. const STARTED = 0b0000_0001; /// Set when full request-response cycle has occurred. const FINISHED = 0b0000_0010; /// Set if connection is in keep-alive (inactive) state. const KEEP_ALIVE = 0b0000_0100; /// Set if in shutdown procedure. const SHUTDOWN = 0b0000_1000; /// Set if read-half is disconnected. const READ_DISCONNECT = 0b0001_0000; /// Set if write-half is disconnected. const WRITE_DISCONNECT = 0b0010_0000; } } // there's 2 versions of Dispatcher state because of: // https://github.com/taiki-e/pin-project-lite/issues/3 // // tl;dr: pin-project-lite doesn't play well with other attribute macros #[cfg(not(test))] pin_project! { /// Dispatcher for HTTP/1.1 protocol pub struct Dispatcher<T, S, B, X, U> where S: Service<Request>, S::Error: Into<Response<BoxBody>>, B: MessageBody, X: Service<Request, Response = Request>, X::Error: Into<Response<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: Service<Request>, S::Error: Into<Response<BoxBody>>, B: MessageBody, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, Codec>), Response = ()>, U::Error: fmt::Display, { #[pin] pub(super) inner: DispatcherState<T, S, B, X, U>, // used in tests pub(super) poll_count: u64, } } pin_project! { #[project = DispatcherStateProj] pub(super) enum DispatcherState<T, S, B, X, U> where S: Service<Request>, S::Error: Into<Response<BoxBody>>, B: MessageBody, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, Codec>), Response = ()>, U::Error: fmt::Display, { Normal { #[pin] inner: InnerDispatcher<T, S, B, X, U> }, Upgrade { #[pin] fut: U::Future }, } } pin_project! { #[project = InnerDispatcherProj] pub(super) struct InnerDispatcher<T, S, B, X, U> where S: Service<Request>, S::Error: Into<Response<BoxBody>>, B: MessageBody, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, Codec>), Response = ()>, U::Error: fmt::Display, { flow: Rc<HttpFlow<S, X, U>>, pub(super) flags: Flags, peer_addr: Option<net::SocketAddr>, conn_data: Option<Rc<Extensions>>, config: ServiceConfig, error: Option<DispatchError>, #[pin] pub(super) state: State<S, B, X>, // when Some(_) dispatcher is in state of receiving request payload payload: Option<PayloadSender>, messages: VecDeque<DispatcherMessage>, head_timer: TimerState, ka_timer: TimerState, shutdown_timer: TimerState, pub(super) io: Option<T>, read_buf: BytesMut, write_buf: BytesMut, codec: Codec, } } enum DispatcherMessage { Item(Request), Upgrade(Request), Error(Response<()>), } pin_project! { #[project = StateProj] pub(super) enum State<S, B, X> where S: Service<Request>, X: Service<Request, Response = Request>, B: MessageBody, { None, ExpectCall { #[pin] fut: X::Future }, ServiceCall { #[pin] fut: S::Future }, SendPayload { #[pin] body: B }, SendErrorPayload { #[pin] body: BoxBody }, } } impl<S, B, X> State<S, B, X> where S: Service<Request>, X: Service<Request, Response = Request>, B: MessageBody, { pub(super) fn is_none(&self) -> bool { matches!(self, State::None) } } impl<S, B, X> fmt::Debug for State<S, B, X> where S: Service<Request>, X: Service<Request, Response = Request>, B: MessageBody, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::None => write!(f, "State::None"), Self::ExpectCall { .. } => f.debug_struct("State::ExpectCall").finish_non_exhaustive(), Self::ServiceCall { .. } => { f.debug_struct("State::ServiceCall").finish_non_exhaustive() } Self::SendPayload { .. } => { f.debug_struct("State::SendPayload").finish_non_exhaustive() } Self::SendErrorPayload { .. } => f .debug_struct("State::SendErrorPayload") .finish_non_exhaustive(), } } } #[derive(Debug)] enum PollResponse { Upgrade(Request), DoNothing, DrainWriteBuf, } impl<T, S, B, X, U> Dispatcher<T, 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 = ()>, U::Error: fmt::Display, { /// Create HTTP/1 dispatcher. pub(crate) fn new( io: T, flow: Rc<HttpFlow<S, X, U>>, config: ServiceConfig, peer_addr: Option<net::SocketAddr>, conn_data: OnConnectData, ) -> Self { Dispatcher { inner: DispatcherState::Normal { inner: InnerDispatcher { flow, flags: Flags::empty(), peer_addr, conn_data: conn_data.0.map(Rc::new), config: config.clone(), error: None, state: State::None, payload: None, messages: VecDeque::new(), head_timer: TimerState::new(config.client_request_deadline().is_some()), ka_timer: TimerState::new(config.keep_alive().enabled()), shutdown_timer: TimerState::new(config.client_disconnect_deadline().is_some()), io: Some(io), read_buf: BytesMut::with_capacity(HW_BUFFER_SIZE), write_buf: BytesMut::with_capacity(HW_BUFFER_SIZE), codec: Codec::new(config), }, }, #[cfg(test)] poll_count: 0, } } } impl<T, S, B, X, U> InnerDispatcher<T, 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 = ()>, 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 { info.need_read(cx) == PayloadStatus::Read } else { true } } fn client_disconnected(self: Pin<&mut Self>) { let this = self.project(); this.flags .insert(Flags::READ_DISCONNECT | Flags::WRITE_DISCONNECT); if let Some(mut payload) = this.payload.take() { payload.set_error(PayloadError::Incomplete(None)); } } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { let InnerDispatcherProj { io, write_buf, .. } = self.project(); let mut io = Pin::new(io.as_mut().unwrap()); let len = write_buf.len(); let mut written = 0; while written < len { match io.as_mut().poll_write(cx, &write_buf[written..])? { Poll::Ready(0) => { error!("write zero; closing"); return Poll::Ready(Err(io::Error::new(io::ErrorKind::WriteZero, ""))); } Poll::Ready(n) => written += n, Poll::Pending => { write_buf.advance(written); return Poll::Pending; } } } // everything has written to I/O; clear buffer write_buf.clear(); // flush the I/O and check if get blocked io.poll_flush(cx) } fn send_response_inner( self: Pin<&mut Self>, res: Response<()>, body: &impl MessageBody, ) -> Result<BodySize, DispatchError> { let this = self.project(); let size = body.size(); this.codec .encode(Message::Item((res, size)), this.write_buf) .map_err(|err| { if let Some(mut payload) = this.payload.take() { payload.set_error(PayloadError::Incomplete(None)); } DispatchError::Io(err) })?; Ok(size) } fn send_response( mut self: Pin<&mut Self>, res: Response<()>, body: B, ) -> Result<(), DispatchError> { let size = self.as_mut().send_response_inner(res, &body)?; let mut this = self.project(); this.state.set(match size { BodySize::None | BodySize::Sized(0) => { this.flags.insert(Flags::FINISHED); State::None } _ => State::SendPayload { body }, }); Ok(()) } fn send_error_response( mut self: Pin<&mut Self>, res: Response<()>, body: BoxBody, ) -> Result<(), DispatchError> { let size = self.as_mut().send_response_inner(res, &body)?; let mut this = self.project(); this.state.set(match size { BodySize::None | BodySize::Sized(0) => { this.flags.insert(Flags::FINISHED); State::None } _ => State::SendErrorPayload { body }, }); Ok(()) } fn send_continue(self: Pin<&mut Self>) { self.project() .write_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().project() { // no future is in InnerDispatcher state; pop next message StateProj::None => match this.messages.pop_front() { // handle request message Some(DispatcherMessage::Item(req)) => { // Handle `EXPECT: 100-Continue` header if req.head().expect() { // set InnerDispatcher state and continue loop to poll it let fut = this.flow.expect.call(req); this.state.set(State::ExpectCall { fut }); } else { // set InnerDispatcher state and continue loop to poll it let fut = this.flow.service.call(req); this.state.set(State::ServiceCall { fut }); }; } // handle error message Some(DispatcherMessage::Error(res)) => { // send_response would update InnerDispatcher state to SendPayload or None // (If response body is empty) // continue loop to poll it self.as_mut().send_error_response(res, BoxBody::new(()))?; } // return with upgrade request and poll it exclusively Some(DispatcherMessage::Upgrade(req)) => return Ok(PollResponse::Upgrade(req)), // all messages are dealt with None => { // start keep-alive if last request allowed it this.flags.set(Flags::KEEP_ALIVE, this.codec.keep_alive()); return Ok(PollResponse::DoNothing); } }, StateProj::ServiceCall { fut } => { match fut.poll(cx) { // service call resolved. send response. Poll::Ready(Ok(res)) => { let (res, body) = res.into().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(); let (res, body) = res.replace_body(()); self.as_mut().send_error_response(res, body)?; } // service call pending and could be waiting for more chunk messages // (pipeline message limit and/or payload can_read limit) Poll::Pending => { // no new message is decoded and no new payload is fed // nothing to do except waiting for new incoming data from client if !self.as_mut().poll_request(cx)? { return Ok(PollResponse::DoNothing); } // else loop } } } StateProj::SendPayload { mut body } => { // keep populate writer buffer until buffer size limit hit, // get blocked or finished. while this.write_buf.len() < super::payload::MAX_BUFFER_SIZE { match body.as_mut().poll_next(cx) { Poll::Ready(Some(Ok(item))) => { this.codec .encode(Message::Chunk(Some(item)), this.write_buf)?; } Poll::Ready(None) => { this.codec.encode(Message::Chunk(None), this.write_buf)?; // payload stream finished. // set state to None and handle next message this.state.set(State::None); this.flags.insert(Flags::FINISHED); continue 'res; } Poll::Ready(Some(Err(err))) => { let err = err.into(); tracing::error!("Response payload stream error: {err:?}"); this.flags.insert(Flags::FINISHED); return Err(DispatchError::Body(err)); } Poll::Pending => return Ok(PollResponse::DoNothing), } } // buffer is beyond max size // return and try to write the whole buffer to I/O stream. return Ok(PollResponse::DrainWriteBuf); } StateProj::SendErrorPayload { mut body } => { // TODO: de-dupe impl with SendPayload // keep populate writer buffer until buffer size limit hit, // get blocked or finished. while this.write_buf.len() < super::payload::MAX_BUFFER_SIZE { match body.as_mut().poll_next(cx) { Poll::Ready(Some(Ok(item))) => { this.codec .encode(Message::Chunk(Some(item)), this.write_buf)?; } Poll::Ready(None) => { this.codec.encode(Message::Chunk(None), this.write_buf)?; // payload stream finished // set state to None and handle next message this.state.set(State::None); this.flags.insert(Flags::FINISHED); continue 'res; } Poll::Ready(Some(Err(err))) => { tracing::error!("Response payload stream error: {err:?}"); this.flags.insert(Flags::FINISHED); return Err(DispatchError::Body( Error::new_body().with_cause(err).into(), )); } Poll::Pending => return Ok(PollResponse::DoNothing), } } // buffer is beyond max size // return and try to write the whole buffer to stream return Ok(PollResponse::DrainWriteBuf); } StateProj::ExpectCall { fut } => { trace!(" calling expect service"); match fut.poll(cx) { // expect resolved. write continue to buffer and set InnerDispatcher state // to service call. Poll::Ready(Ok(req)) => { this.write_buf .extend_from_slice(b"HTTP/1.1 100 Continue\r\n\r\n"); let fut = this.flow.service.call(req); this.state.set(State::ServiceCall { fut }); } // send expect error as response Poll::Ready(Err(err)) => { let res: Response<BoxBody> = err.into(); let (res, body) = res.replace_body(()); self.as_mut().send_error_response(res, body)?; } // expect must be solved before progress can be made. Poll::Pending => return Ok(PollResponse::DoNothing), } } } } } fn handle_request( mut self: Pin<&mut Self>, req: Request, cx: &mut Context<'_>, ) -> Result<(), DispatchError> { // initialize dispatcher state { let mut this = self.as_mut().project(); // Handle `EXPECT: 100-Continue` header if req.head().expect() { // set dispatcher state to call expect handler let fut = this.flow.expect.call(req); this.state.set(State::ExpectCall { fut }); } else { // set dispatcher state to call service handler let fut = this.flow.service.call(req); 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(cx) { // expect is resolved; continue loop and poll the service call branch. Poll::Ready(Ok(req)) => { self.as_mut().send_continue(); let mut this = self.as_mut().project(); let fut = this.flow.service.call(req); this.state.set(State::ServiceCall { fut }); continue; } // future is error; send response and return a result // on success to notify the dispatcher a new state is set and the outer loop // should be continued Poll::Ready(Err(err)) => { let res: Response<BoxBody> = err.into(); let (res, body) = res.replace_body(()); return self.send_error_response(res, body); } // future is pending; return Ok(()) to notify that a new state is // set and the outer loop should be continue. Poll::Pending => return Ok(()), } } StateProj::ServiceCall { fut } => { // return no matter the service call future's result. return match fut.poll(cx) { // Future is resolved. Send response and return a result. On success // to notify the dispatcher a new state is set and the outer loop // should be continue. Poll::Ready(Ok(res)) => { let (res, body) = res.into().replace_body(()); self.as_mut().send_response(res, body) } // see the comment on ExpectCall state branch's Pending Poll::Pending => Ok(()), // see the comment on ExpectCall state branch's Ready(Err(_)) Poll::Ready(Err(err)) => { let res: Response<BoxBody> = err.into(); let (res, body) = res.replace_body(()); self.as_mut().send_error_response(res, body) } }; } _ => { unreachable!("State must be set to ServiceCall or ExceptCall in handle_request") } } } } /// Process one incoming request. /// /// Returns true if any meaningful work was done. fn poll_request(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Result<bool, DispatchError> { let pipeline_queue_full = self.messages.len() >= MAX_PIPELINED_MESSAGES; let can_not_read = !self.can_read(cx); // limit amount of non-processed requests if pipeline_queue_full || can_not_read { return Ok(false); } let mut this = self.as_mut().project(); let mut updated = false; // decode from read buf as many full requests as possible loop { match this.codec.decode(this.read_buf) { Ok(Some(msg)) => { updated = true; match msg { Message::Item(mut req) => { // head timer only applies to first request on connection this.head_timer.clear(line!()); req.head_mut().peer_addr = *this.peer_addr; req.conn_data.clone_from(this.conn_data); match this.codec.message_type() { // request has no payload MessageType::None => {} // Request is upgradable. Add upgrade message and break. // Everything remaining in read buffer will be handed to // upgraded Request. MessageType::Stream if this.flow.upgrade.is_some() => { this.messages.push_back(DispatcherMessage::Upgrade(req)); break; } // request is not upgradable MessageType::Payload | MessageType::Stream => { // PayloadSender and Payload are smart pointers share the // same state. PayloadSender is attached to dispatcher and used // to sink new chunked request data to state. Payload is // attached to Request and passed to Service::call where the // state can be collected and consumed. let (sender, payload) = Payload::create(false); *req.payload() = crate::Payload::H1 { payload }; *this.payload = Some(sender); } } // handle request early when no future in InnerDispatcher state. if this.state.is_none() { self.as_mut().handle_request(req, cx)?; this = self.as_mut().project(); } else { this.messages.push_back(DispatcherMessage::Item(req)); } } Message::Chunk(Some(chunk)) => { if let Some(ref mut payload) = this.payload { payload.feed_data(chunk); } else { error!("Internal server error: unexpected payload chunk"); this.flags.insert(Flags::READ_DISCONNECT); this.messages.push_back(DispatcherMessage::Error( Response::internal_server_error().drop_body(), )); *this.error = Some(DispatchError::InternalError); break; } } Message::Chunk(None) => { if let Some(mut payload) = this.payload.take() { payload.feed_eof(); } else { error!("Internal server error: unexpected eof"); this.flags.insert(Flags::READ_DISCONNECT); this.messages.push_back(DispatcherMessage::Error( Response::internal_server_error().drop_body(), )); *this.error = Some(DispatchError::InternalError); break; } } } } // decode is partial and buffer is not full yet // break and wait for more read Ok(None) => break, Err(ParseError::Io(err)) => { trace!("I/O error: {}", &err); self.as_mut().client_disconnected(); this = self.as_mut().project(); *this.error = Some(DispatchError::Io(err)); break; } Err(ParseError::TooLarge) => { trace!("request head was too big; returning 431 response"); if let Some(mut payload) = this.payload.take() { payload.set_error(PayloadError::Overflow); } // request heads that overflow buffer size return a 431 error this.messages .push_back(DispatcherMessage::Error(Response::with_body( StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE, (), ))); this.flags.insert(Flags::READ_DISCONNECT); *this.error = Some(ParseError::TooLarge.into()); break; } Err(err) => { 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.messages.push_back(DispatcherMessage::Error( Response::bad_request().drop_body(), )); this.flags.insert(Flags::READ_DISCONNECT); *this.error = Some(err.into()); break; } } } Ok(updated) } fn poll_head_timer( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Result<(), DispatchError> { let this = self.as_mut().project(); if let TimerState::Active { timer } = this.head_timer { if timer.as_mut().poll(cx).is_ready() { // timeout on first request (slow request) return 408 trace!("timed out on slow request; replying with 408 and closing connection"); let _ = self.as_mut().send_error_response( Response::with_body(StatusCode::REQUEST_TIMEOUT, ()), BoxBody::new(()), ); self.project().flags.insert(Flags::SHUTDOWN); } }; Ok(()) } fn poll_ka_timer(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Result<(), DispatchError> { let this = self.as_mut().project(); if let TimerState::Active { timer } = this.ka_timer { debug_assert!( this.flags.contains(Flags::KEEP_ALIVE), "keep-alive flag should be set when timer is active", ); debug_assert!( this.state.is_none(), "dispatcher should not be in keep-alive phase if state is not none: {:?}", this.state, ); // Assert removed by @robjtede on account of issue #2655. There are cases where an I/O // flush can be pending after entering the keep-alive state causing the subsequent flush // wake up to panic here. This appears to be a Linux-only problem. Leaving original code // below for posterity because a simple and reliable test could not be found to trigger // the behavior. // debug_assert!( // this.write_buf.is_empty(), // "dispatcher should not be in keep-alive phase if write_buf is not empty", // ); // keep-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() { // start shutdown timeout if enabled this.shutdown_timer .set_and_init(cx, sleep_until(deadline.into()), line!()); } else { // no shutdown timeout, drop socket this.flags.insert(Flags::WRITE_DISCONNECT); } } } Ok(()) } fn poll_shutdown_timer( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Result<(), DispatchError> { let this = self.as_mut().project(); if let TimerState::Active { timer } = this.shutdown_timer { debug_assert!( this.flags.contains(Flags::SHUTDOWN), "shutdown flag should be set when timer is active", ); // timed-out during shutdown; drop connection if timer.as_mut().poll(cx).is_ready() { trace!("timed-out during shutdown"); return Err(DispatchError::DisconnectTimeout); } } Ok(()) } /// Poll head, keep-alive, and disconnect timer. fn poll_timers(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Result<(), DispatchError> { self.as_mut().poll_head_timer(cx)?; self.as_mut().poll_ka_timer(cx)?; 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)] // TODO: bench this inline fn read_available(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Result<bool, DispatchError> { let this = self.project(); if this.flags.contains(Flags::READ_DISCONNECT) { return Ok(false); }; let mut io = Pin::new(this.io.as_mut().unwrap()); let mut read_some = false; loop { // Return early when read buf exceed decoder's max buffer size. if this.read_buf.len() >= MAX_BUFFER_SIZE { // At this point it's not known IO stream is still scheduled to be waked up so // force wake up dispatcher just in case. // // Reason: // AsyncRead mostly would only have guarantee wake up when the poll_read // return Poll::Pending. // // Case: // When read_buf is beyond max buffer size the early return could be successfully // be parsed as a new Request. This case would not generate ParseError::TooLarge and // at this point IO stream is not fully read to Pending and would result in // dispatcher stuck until timeout (keep-alive). // // Note: // This is a perf choice to reduce branch on <Request as MessageType>::decode. // // A Request head too large to parse is only checked on `httparse::Status::Partial`. match this.payload { // When dispatcher has a payload the responsibility of wake ups is shifted to // `h1::payload::Payload` unless the payload is needing a read, in which case it // might not have access to the waker and could result in the dispatcher // getting stuck until timeout. // // Reason: // Self wake up when there is payload would waste poll and/or result in // over read. // // Case: // When payload is (partial) dropped by user there is no need to do // read anymore. At this case read_buf could always remain beyond // MAX_BUFFER_SIZE and self wake up would be busy poll dispatcher and // waste resources. Some(ref p) if p.need_read(cx) != PayloadStatus::Read => {} _ => cx.waker().wake_by_ref(), } return Ok(false); } // grow buffer if necessary. let remaining = this.read_buf.capacity() - this.read_buf.len(); if remaining < LW_BUFFER_SIZE { this.read_buf.reserve(HW_BUFFER_SIZE - remaining); } match tokio_util::io::poll_read_buf(io.as_mut(), cx, this.read_buf) { Poll::Ready(Ok(n)) => { this.flags.remove(Flags::FINISHED); if n == 0 { return Ok(true); } read_some = true; } Poll::Pending => { return Ok(false); } Poll::Ready(Err(err)) => { return match err.kind() { // convert WouldBlock error to the same as Pending return io::ErrorKind::WouldBlock => Ok(false), // connection reset after partial read io::ErrorKind::ConnectionReset if read_some => Ok(true), _ => Err(DispatchError::Io(err)), }; } } } } /// call upgrade service with request. fn upgrade(self: Pin<&mut Self>, req: Request) -> U::Future { let this = self.project(); let mut parts = FramedParts::with_read_buf( this.io.take().unwrap(), mem::take(this.codec), mem::take(this.read_buf), ); parts.write_buf = mem::take(this.write_buf); let framed = Framed::from_parts(parts); this.flow.upgrade.as_ref().unwrap().call((req, framed)) } } 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::Response: Into<Response<B>>, B: MessageBody, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, Codec>), Response = ()>, U::Error: fmt::Display, { type Output = Result<(), DispatchError>; #[inline] fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.as_mut().project(); #[cfg(test)] { *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 }), DispatcherStateProj::Normal { mut inner } => { trace!("start flags: {:?}", &inner.flags); trace_timer_states( "start", &inner.head_timer, &inner.ka_timer, &inner.shutdown_timer, ); inner.as_mut().poll_timers(cx)?; let poll = if inner.flags.contains(Flags::SHUTDOWN) { if inner.flags.contains(Flags::WRITE_DISCONNECT) { Poll::Ready(Ok(())) } else { // flush buffer and wait on blocked ready!(inner.as_mut().poll_flush(cx))?; Pin::new(inner.as_mut().project().io.as_mut().unwrap()) .poll_shutdown(cx) .map_err(DispatchError::from) } } else { // read from I/O stream and fill read buffer let should_disconnect = inner.as_mut().read_available(cx)?; // after reading something from stream, clear keep-alive timer if !inner.read_buf.is_empty() && inner.flags.contains(Flags::KEEP_ALIVE) { let inner = inner.as_mut().project(); inner.flags.remove(Flags::KEEP_ALIVE); inner.ka_timer.clear(line!()); } if !inner.flags.contains(Flags::STARTED) { inner.as_mut().project().flags.insert(Flags::STARTED); if let Some(deadline) = inner.config.client_request_deadline() { inner.as_mut().project().head_timer.set_and_init( cx, sleep_until(deadline.into()), line!(), ); } } inner.as_mut().poll_request(cx)?; if should_disconnect { // I/O stream should to be closed let inner = inner.as_mut().project(); inner.flags.insert(Flags::READ_DISCONNECT); if let Some(mut payload) = inner.payload.take() { payload.feed_eof(); } }; loop { // poll response to populate write buffer // drain indicates whether write buffer should be emptied before next run let drain = match inner.as_mut().poll_response(cx)? { PollResponse::DrainWriteBuf => true, PollResponse::DoNothing => { // KEEP_ALIVE is set in send_response_inner if client allows it // FINISHED is set after writing last chunk of response if inner.flags.contains(Flags::KEEP_ALIVE | Flags::FINISHED) { if let Some(timer) = inner.config.keep_alive_deadline() { inner.as_mut().project().ka_timer.set_and_init( cx, sleep_until(timer.into()), line!(), ); } } false } // upgrade request and goes Upgrade variant of DispatcherState. PollResponse::Upgrade(req) => { let upgrade = inner.upgrade(req); self.as_mut() .project() .inner .set(DispatcherState::Upgrade { fut: upgrade }); return self.poll(cx); } }; // we didn't get WouldBlock from write operation, so data get written to // kernel completely (macOS) and we have to write again otherwise response // can get stuck // // TODO: want to find a reference for this behavior // see introduced commit: 3872d3ba let flush_was_ready = inner.as_mut().poll_flush(cx)?.is_ready(); // this assert seems to always be true but not willing to commit to it until // we understand what Nikolay meant when writing the above comment // debug_assert!(flush_was_ready); if !flush_was_ready || !drain { break; } } // client is gone if inner.flags.contains(Flags::WRITE_DISCONNECT) { trace!("client is gone; disconnecting"); return Poll::Ready(Ok(())); } let inner_p = inner.as_mut().project(); let state_is_none = inner_p.state.is_none(); // read half is closed; we do not process any responses if inner_p.flags.contains(Flags::READ_DISCONNECT) && state_is_none { trace!("read half closed; start shutdown"); inner_p.flags.insert(Flags::SHUTDOWN); } // keep-alive and stream errors if state_is_none && inner_p.write_buf.is_empty() { if let Some(err) = inner_p.error.take() { error!("stream error: {}", &err); return Poll::Ready(Err(err)); } // disconnect if keep-alive is not enabled if inner_p.flags.contains(Flags::FINISHED) && !inner_p.flags.contains(Flags::KEEP_ALIVE) { inner_p.flags.remove(Flags::FINISHED); inner_p.flags.insert(Flags::SHUTDOWN); return self.poll(cx); } // disconnect if shutdown if inner_p.flags.contains(Flags::SHUTDOWN) { return self.poll(cx); } } trace_timer_states( "end", inner_p.head_timer, inner_p.ka_timer, inner_p.shutdown_timer, ); Poll::Pending }; trace!("end flags: {:?}", &inner.flags); poll } } } } #[allow(dead_code)] fn trace_timer_states( label: &str, head_timer: &TimerState, ka_timer: &TimerState, shutdown_timer: &TimerState, ) { trace!("{} timers:", label); if head_timer.is_enabled() { trace!(" head {}", &head_timer); } if ka_timer.is_enabled() { trace!(" keep-alive {}", &ka_timer); } if shutdown_timer.is_enabled() { trace!(" shutdown {}", &shutdown_timer); } }
use std::{future::Future, str, task::Poll, time::Duration}; use actix_codec::Framed; use actix_rt::{pin, time::sleep}; use actix_service::{fn_service, Service}; use actix_utils::future::{ready, Ready}; use bytes::{Buf, Bytes, BytesMut}; use futures_util::future::lazy; use super::dispatcher::{Dispatcher, DispatcherState, DispatcherStateProj, Flags}; use crate::{ body::MessageBody, config::ServiceConfig, h1::{Codec, ExpectHandler, UpgradeHandler}, service::HttpFlow, test::{TestBuffer, TestSeqBuffer}, Error, HttpMessage, KeepAlive, Method, OnConnectData, Request, Response, StatusCode, }; fn find_slice(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> { memchr::memmem::find(&haystack[from..], needle) } fn stabilize_date_header(payload: &mut [u8]) { let mut from = 0; while let Some(pos) = find_slice(payload, b"date", from) { payload[(from + pos)..(from + pos + 35)] .copy_from_slice(b"date: Thu, 01 Jan 1970 12:34:56 UTC"); from += 35; } } fn ok_service() -> impl Service<Request, Response = Response<impl MessageBody>, Error = Error> { status_service(StatusCode::OK) } fn status_service( status: StatusCode, ) -> impl Service<Request, Response = Response<impl MessageBody>, Error = Error> { fn_service(move |_req: Request| ready(Ok::<_, Error>(Response::new(status)))) } fn echo_path_service() -> impl Service<Request, Response = Response<impl MessageBody>, Error = Error> { fn_service(|req: Request| { let path = req.path().as_bytes(); ready(Ok::<_, Error>( Response::ok().set_body(Bytes::copy_from_slice(path)), )) }) } fn drop_payload_service() -> impl Service<Request, Response = Response<&'static str>, Error = Error> { fn_service(|mut req: Request| async move { let _ = req.take_payload(); Ok::<_, Error>(Response::with_body(StatusCode::OK, "payload dropped")) }) } fn echo_payload_service() -> impl Service<Request, Response = Response<Bytes>, Error = Error> { fn_service(|mut req: Request| { Box::pin(async move { use futures_util::StreamExt as _; let mut pl = req.take_payload(); let mut body = BytesMut::new(); while let Some(chunk) = pl.next().await { body.extend_from_slice(chunk.unwrap().chunk()) } Ok::<_, Error>(Response::ok().set_body(body.freeze())) }) }) } #[actix_rt::test] async fn late_request() { let mut 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( buf.clone(), services, cfg, None, OnConnectData::default(), ); pin!(h1); lazy(|cx| { assert!(matches!(&h1.inner, DispatcherState::Normal { .. })); match h1.as_mut().poll(cx) { Poll::Ready(_) => panic!("first poll should not be ready"), Poll::Pending => {} } // polls: initial assert_eq!(h1.poll_count, 1); buf.extend_read_buf("GET /abcd HTTP/1.1\r\nConnection: close\r\n\r\n"); match h1.as_mut().poll(cx) { Poll::Pending => panic!("second poll should not be pending"), Poll::Ready(res) => assert!(res.is_ok()), } // polls: initial pending => handle req => shutdown assert_eq!(h1.poll_count, 3); 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: 0\r\n\ connection: close\r\n\ date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\r\n\ "; assert_eq!( res, exp, "\nexpected response not in write buffer:\n\ response: {:?}\n\ expected: {:?}", String::from_utf8_lossy(res), String::from_utf8_lossy(exp) ); }) .await; } #[actix_rt::test] async fn oneshot_connection() { let buf = TestBuffer::new("GET /abcd HTTP/1.1\r\n\r\n"); let cfg = ServiceConfig::new( KeepAlive::Disabled, Duration::from_millis(100), Duration::ZERO, false, None, ); let services = HttpFlow::new(echo_path_service(), ExpectHandler, None); let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new( buf.clone(), services, cfg, None, OnConnectData::default(), ); pin!(h1); lazy(|cx| { 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_ok()), } // polls: initial => shutdown assert_eq!(h1.poll_count, 2); let mut res = buf.take_write_buf().to_vec(); stabilize_date_header(&mut res); let res = &res[..]; let exp = http_msg( r" HTTP/1.1 200 OK content-length: 5 connection: close date: Thu, 01 Jan 1970 12:34:56 UTC /abcd ", ); assert_eq!( res, exp, "\nexpected response not in write buffer:\n\ response: {:?}\n\ expected: {:?}", String::from_utf8_lossy(res), String::from_utf8_lossy(&exp) ); }) .await; } #[actix_rt::test] async fn keep_alive_timeout() { let buf = TestBuffer::new("GET /abcd HTTP/1.1\r\n\r\n"); let cfg = ServiceConfig::new( KeepAlive::Timeout(Duration::from_millis(200)), Duration::from_millis(100), Duration::ZERO, false, None, ); let services = HttpFlow::new(echo_path_service(), ExpectHandler, None); let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new( buf.clone(), services, cfg, None, OnConnectData::default(), ); pin!(h1); lazy(|cx| { assert!(matches!(&h1.inner, DispatcherState::Normal { .. })); assert!( 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"\ HTTP/1.1 200 OK\r\n\ content-length: 5\r\n\ date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\r\n\ /abcd\ "; assert_eq!( res, exp, "\nexpected response not in write buffer:\n\ response: {:?}\n\ expected: {:?}", String::from_utf8_lossy(res), String::from_utf8_lossy(exp) ); }) .await; // sleep slightly longer than keep-alive timeout sleep(Duration::from_millis(250)).await; lazy(|cx| { assert!( h1.as_mut().poll(cx).is_ready(), "keep-alive should have resolved", ); // polls: initial => keep-alive wake-up shutdown assert_eq!(h1.poll_count, 2); if let DispatcherStateProj::Normal { inner } = h1.project().inner.project() { // connection closed assert!(inner.flags.contains(Flags::SHUTDOWN)); assert!(inner.flags.contains(Flags::WRITE_DISCONNECT)); // and nothing added to write buffer assert!(buf.write_buf_slice().is_empty()); } }) .await; } #[actix_rt::test] async fn keep_alive_follow_up_req() { let mut buf = TestBuffer::new("GET /abcd HTTP/1.1\r\n\r\n"); let cfg = ServiceConfig::new( KeepAlive::Timeout(Duration::from_millis(500)), Duration::from_millis(100), Duration::ZERO, false, None, ); let services = HttpFlow::new(echo_path_service(), ExpectHandler, None); let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new( buf.clone(), services, cfg, None, OnConnectData::default(), ); pin!(h1); lazy(|cx| { assert!(matches!(&h1.inner, DispatcherState::Normal { .. })); assert!( 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"\ HTTP/1.1 200 OK\r\n\ content-length: 5\r\n\ date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\r\n\ /abcd\ "; assert_eq!( res, exp, "\nexpected response not in write buffer:\n\ response: {:?}\n\ expected: {:?}", String::from_utf8_lossy(res), String::from_utf8_lossy(exp) ); }) .await; // sleep for less than KA timeout sleep(Duration::from_millis(100)).await; lazy(|cx| { assert!( h1.as_mut().poll(cx).is_pending(), "keep-alive should not have resolved dispatcher yet", ); // polls: initial => manual assert_eq!(h1.poll_count, 2); if let DispatcherStateProj::Normal { inner } = h1.as_mut().project().inner.project() { // connection not closed assert!(!inner.flags.contains(Flags::SHUTDOWN)); assert!(!inner.flags.contains(Flags::WRITE_DISCONNECT)); // and nothing added to write buffer assert!(buf.write_buf_slice().is_empty()); } }) .await; lazy(|cx| { buf.extend_read_buf( "\ GET /efg HTTP/1.1\r\n\ Connection: close\r\n\ \r\n\r\n", ); assert!( h1.as_mut().poll(cx).is_ready(), "connection close header should override keep-alive setting", ); // polls: initial => manual => follow-up req => shutdown assert_eq!(h1.poll_count, 4); if let DispatcherStateProj::Normal { inner } = h1.as_mut().project().inner.project() { // connection closed assert!(inner.flags.contains(Flags::SHUTDOWN)); assert!(!inner.flags.contains(Flags::WRITE_DISCONNECT)); } 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: 4\r\n\ connection: close\r\n\ date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\r\n\ /efg\ "; assert_eq!( res, exp, "\nexpected response not in write buffer:\n\ response: {:?}\n\ expected: {:?}", String::from_utf8_lossy(res), String::from_utf8_lossy(exp) ); }) .await; } #[actix_rt::test] async fn req_parse_err() { lazy(|cx| { let buf = TestBuffer::new("GET /test HTTP/1\r\n\r\n"); let services = HttpFlow::new(ok_service(), ExpectHandler, None); let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new( buf.clone(), services, ServiceConfig::default(), None, OnConnectData::default(), ); pin!(h1); match h1.as_mut().poll(cx) { Poll::Pending => panic!(), Poll::Ready(res) => assert!(res.is_err()), } if let DispatcherStateProj::Normal { inner } = h1.project().inner.project() { assert!(inner.flags.contains(Flags::READ_DISCONNECT)); assert_eq!( &buf.write_buf_slice()[..26], b"HTTP/1.1 400 Bad Request\r\n" ); } }) .await; } #[actix_rt::test] async fn pipelining_ok_then_ok() { lazy(|cx| { let buf = TestBuffer::new( "\ GET /abcd HTTP/1.1\r\n\r\n\ GET /def HTTP/1.1\r\n\r\n\ ", ); let cfg = ServiceConfig::new( KeepAlive::Disabled, Duration::from_millis(1), Duration::from_millis(1), false, None, ); let services = HttpFlow::new(echo_path_service(), ExpectHandler, None); let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new( buf.clone(), services, cfg, None, OnConnectData::default(), ); pin!(h1); 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_ok()), } // polls: initial => shutdown assert_eq!(h1.poll_count, 2); let mut res = buf.write_buf_slice_mut(); stabilize_date_header(&mut res); let res = &res[..]; let exp = b"\ HTTP/1.1 200 OK\r\n\ content-length: 5\r\n\ connection: close\r\n\ date: Thu, 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, exp, "\nexpected response not in write buffer:\n\ response: {:?}\n\ expected: {:?}", String::from_utf8_lossy(res), String::from_utf8_lossy(exp) ); }) .await; } #[actix_rt::test] async fn pipelining_ok_then_bad() { lazy(|cx| { let buf = TestBuffer::new( "\ GET /abcd HTTP/1.1\r\n\r\n\ GET /def HTTP/1\r\n\r\n\ ", ); let cfg = ServiceConfig::new( KeepAlive::Disabled, Duration::from_millis(1), Duration::from_millis(1), false, None, ); let services = HttpFlow::new(echo_path_service(), ExpectHandler, None); let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new( buf.clone(), services, cfg, None, OnConnectData::default(), ); pin!(h1); 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); let mut res = buf.write_buf_slice_mut(); stabilize_date_header(&mut res); let res = &res[..]; let exp = b"\ HTTP/1.1 200 OK\r\n\ content-length: 5\r\n\ connection: close\r\n\ date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\r\n\ /abcd\ HTTP/1.1 400 Bad Request\r\n\ content-length: 0\r\n\ connection: close\r\n\ date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\r\n\ "; assert_eq!( res, exp, "\nexpected response not in write buffer:\n\ response: {:?}\n\ expected: {:?}", String::from_utf8_lossy(res), String::from_utf8_lossy(exp) ); }) .await; } #[actix_rt::test] async fn expect_handling() { lazy(|cx| { let mut buf = TestSeqBuffer::empty(); let cfg = ServiceConfig::new( KeepAlive::Disabled, Duration::ZERO, Duration::ZERO, false, None, ); let services = HttpFlow::new(echo_payload_service(), ExpectHandler, None); let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new( buf.clone(), services, cfg, None, OnConnectData::default(), ); buf.extend_read_buf( "\ POST /upload HTTP/1.1\r\n\ Content-Length: 5\r\n\ Expect: 100-continue\r\n\ \r\n\ ", ); pin!(h1); assert!(h1.as_mut().poll(cx).is_pending()); assert!(matches!(&h1.inner, DispatcherState::Normal { .. })); // polls: manual assert_eq!(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" ); } buf.extend_read_buf("12345"); assert!(h1.as_mut().poll(cx).is_ready()); // polls: manual manual shutdown assert_eq!(h1.poll_count, 3); 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); assert_eq!( str::from_utf8(&res).unwrap(), "\ HTTP/1.1 100 Continue\r\n\ \r\n\ HTTP/1.1 200 OK\r\n\ content-length: 5\r\n\ connection: close\r\n\ date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\ \r\n\ 12345\ " ); } }) .await; } #[actix_rt::test] async fn expect_eager() { lazy(|cx| { let mut buf = TestSeqBuffer::empty(); let cfg = ServiceConfig::new( KeepAlive::Disabled, Duration::ZERO, Duration::ZERO, false, None, ); let services = HttpFlow::new(echo_path_service(), ExpectHandler, None); let h1 = Dispatcher::<_, _, _, _, UpgradeHandler>::new( buf.clone(), services, cfg, None, OnConnectData::default(), ); buf.extend_read_buf( "\ POST /upload HTTP/1.1\r\n\ Content-Length: 5\r\n\ Expect: 100-continue\r\n\ \r\n\ ", ); pin!(h1); assert!(h1.as_mut().poll(cx).is_ready()); assert!(matches!(&h1.inner, DispatcherState::Normal { .. })); // polls: manual shutdown assert_eq!(h1.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 has not // been sent, this test expects a complete service response since the payload // is not used at all. The service passed to dispatcher is path echo and doesn't // consume payload bytes. assert_eq!( str::from_utf8(&res).unwrap(), "\ HTTP/1.1 100 Continue\r\n\ \r\n\ HTTP/1.1 200 OK\r\n\ content-length: 7\r\n\ connection: close\r\n\ date: Thu, 01 Jan 1970 12:34:56 UTC\r\n\ \r\n\ /upload\ " ); } }) .await; } #[actix_rt::test] async fn upgrade_handling() { struct TestUpgrade; impl<T> Service<(Request, Framed<T, Codec>)> for TestUpgrade { type Response = (); type Error = Error; type Future = Ready<Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, (req, _framed): (Request, Framed<T, Codec>)) -> Self::Future { assert_eq!(req.method(), Method::GET); assert!(req.upgrade()); assert_eq!(req.headers().get("upgrade").unwrap(), "websocket"); ready(Ok(())) } } lazy(|cx| { let mut buf = TestSeqBuffer::empty(); let cfg = ServiceConfig::new( KeepAlive::Disabled, Duration::ZERO, Duration::ZERO, false, None, ); let services = HttpFlow::new(ok_service(), ExpectHandler, Some(TestUpgrade)); let h1 = Dispatcher::<_, _, _, _, TestUpgrade>::new( buf.clone(), services, cfg, None, OnConnectData::default(), ); buf.extend_read_buf( "\ GET /ws HTTP/1.1\r\n\ Connection: Upgrade\r\n\ Upgrade: websocket\r\n\ \r\n\ ", ); 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; } // fix in #2624 reverted temporarily // complete fix tracked in #2745 #[ignore] #[actix_rt::test] async fn handler_drop_payload() { let _ = env_logger::try_init(); let mut buf = TestBuffer::new(http_msg( r" POST /drop-payload HTTP/1.1 Content-Length: 3 abc ", )); let services = HttpFlow::new( drop_payload_service(), ExpectHandler, None::<UpgradeHandler>, ); let h1 = Dispatcher::new( buf.clone(), services, ServiceConfig::default(), None, OnConnectData::default(), ); pin!(h1); lazy(|cx| { assert!(h1.as_mut().poll(cx).is_pending()); // polls: manual assert_eq!(h1.poll_count, 1); let mut res = BytesMut::from(buf.take_write_buf().as_ref()); stabilize_date_header(&mut res); let res = &res[..]; let exp = http_msg( r" HTTP/1.1 200 OK content-length: 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(res), String::from_utf8_lossy(&exp) ); if let DispatcherStateProj::Normal { inner } = h1.as_mut().project().inner.project() { assert!(inner.state.is_none()); } }) .await; lazy(|cx| { // add message that claims to have payload longer than provided buf.extend_read_buf(http_msg( r" POST /drop-payload HTTP/1.1 Content-Length: 200 abc ", )); assert!(h1.as_mut().poll(cx).is_pending()); // polls: manual => manual assert_eq!(h1.poll_count, 2); let mut res = BytesMut::from(buf.take_write_buf().as_ref()); stabilize_date_header(&mut res); let res = &res[..]; // expect response immediately even though request side has not finished reading payload let exp = http_msg( r" HTTP/1.1 200 OK content-length: 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(res), String::from_utf8_lossy(&exp) ); }) .await; lazy(|cx| { assert!(h1.as_mut().poll(cx).is_ready()); // polls: manual => manual => manual assert_eq!(h1.poll_count, 3); let mut res = BytesMut::from(buf.take_write_buf().as_ref()); stabilize_date_header(&mut res); let res = &res[..]; // expect that unrequested error response is sent back since connection could not be cleaned let exp = http_msg( r" HTTP/1.1 500 Internal Server Error content-length: 0 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(res), String::from_utf8_lossy(&exp) ); }) .await; } fn http_msg(msg: impl AsRef<str>) -> BytesMut { let mut msg = msg .as_ref() .trim() .split('\n') .map(|line| [line.trim_start(), "\r"].concat()) .collect::<Vec<_>>() .join("\n"); // remove trailing \r msg.pop(); if !msg.is_empty() && !msg.contains("\r\n\r\n") { msg.push_str("\r\n\r\n"); } BytesMut::from(msg.as_bytes()) } #[test] fn http_msg_creates_msg() { assert_eq!(http_msg(r""), ""); assert_eq!( http_msg( r" POST / HTTP/1.1 Content-Length: 3 abc " ), "POST / HTTP/1.1\r\nContent-Length: 3\r\n\r\nabc" ); assert_eq!( http_msg( r" GET / HTTP/1.1 Content-Length: 3 " ), "GET / HTTP/1.1\r\nContent-Length: 3\r\n\r\n" ); }
use std::{ cmp, io::{self, Write as _}, marker::PhantomData, ptr::copy_nonoverlapping, slice::from_raw_parts_mut, }; use bytes::{BufMut, BytesMut}; use crate::{ body::BodySize, header::{ map::Value, HeaderMap, HeaderName, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, }, helpers, ConnectionType, RequestHeadType, Response, ServiceConfig, StatusCode, Version, }; const AVERAGE_HEADER_SIZE: usize = 30; #[derive(Debug)] pub(crate) struct MessageEncoder<T: MessageType> { #[allow(dead_code)] pub length: BodySize, pub te: TransferEncoding, _phantom: PhantomData<T>, } impl<T: MessageType> Default for MessageEncoder<T> { fn default() -> Self { MessageEncoder { length: BodySize::None, te: TransferEncoding::empty(), _phantom: PhantomData, } } } pub(crate) trait MessageType: Sized { fn status(&self) -> Option<StatusCode>; fn headers(&self) -> &HeaderMap; fn extra_headers(&self) -> Option<&HeaderMap>; fn camel_case(&self) -> bool { false } fn chunked(&self) -> bool; fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()>; fn encode_headers( &mut self, dst: &mut BytesMut, version: Version, mut length: BodySize, conn_type: ConnectionType, config: &ServiceConfig, ) -> io::Result<()> { let chunked = self.chunked(); let mut skip_len = length != BodySize::Stream; let camel_case = self.camel_case(); // Content length if let Some(status) = self.status() { match status { StatusCode::CONTINUE | StatusCode::SWITCHING_PROTOCOLS | StatusCode::PROCESSING | StatusCode::NO_CONTENT => { // skip content-length and transfer-encoding headers // see https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.1 // and https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2 skip_len = true; length = BodySize::None } StatusCode::NOT_MODIFIED => { // 304 responses should never have a body but should retain a manually set // content-length header // see https://datatracker.ietf.org/doc/html/rfc7232#section-4.1 skip_len = false; length = BodySize::None; } _ => {} } } match length { BodySize::Stream => { if chunked { skip_len = true; if camel_case { dst.put_slice(b"\r\nTransfer-Encoding: chunked\r\n") } else { dst.put_slice(b"\r\ntransfer-encoding: chunked\r\n") } } else { skip_len = false; dst.put_slice(b"\r\n"); } } BodySize::Sized(0) if camel_case => dst.put_slice(b"\r\nContent-Length: 0\r\n"), BodySize::Sized(0) => dst.put_slice(b"\r\ncontent-length: 0\r\n"), BodySize::Sized(len) => helpers::write_content_length(len, dst, camel_case), BodySize::None => dst.put_slice(b"\r\n"), } // Connection match conn_type { ConnectionType::Upgrade => dst.put_slice(b"connection: upgrade\r\n"), ConnectionType::KeepAlive if version < Version::HTTP_11 => { if camel_case { dst.put_slice(b"Connection: keep-alive\r\n") } else { dst.put_slice(b"connection: keep-alive\r\n") } } ConnectionType::Close if version >= Version::HTTP_11 => { if camel_case { dst.put_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 = dst.capacity() - dst.len(); // tracks bytes written since last buffer resize // since buf is a raw pointer to a bytes container storage but is written to without the // container's knowledge, this is used to sync the containers cursor after data is written let mut pos = 0; self.write_headers(|key, value| { match *key { CONNECTION => return, TRANSFER_ENCODING | CONTENT_LENGTH if skip_len => return, DATE => has_date = true, _ => {} } let k = key.as_str().as_bytes(); let k_len = k.len(); for val in value.iter() { let v = val.as_ref(); let v_len = v.len(); // key length + value length + colon + space + \r\n let len = k_len + v_len + 4; if len > remaining { // SAFETY: all the bytes written up to position "pos" are initialized // the written byte count and pointer advancement are kept in sync unsafe { dst.advance_mut(pos); } pos = 0; dst.reserve(len * 2); remaining = dst.capacity() - dst.len(); // re-assign buf raw pointer since it's possible that the buffer was // reallocated and/or resized buf = dst.chunk_mut().as_mut_ptr(); } // SAFETY: on each write, it is enough to ensure that the advancement of // the cursor matches the number of bytes written unsafe { if camel_case { // use Camel-Case headers write_camel_case(k, buf, k_len); } else { write_data(k, buf, k_len); } buf = buf.add(k_len); write_data(b": ", buf, 2); buf = buf.add(2); write_data(v, buf, v_len); buf = buf.add(v_len); write_data(b"\r\n", buf, 2); buf = buf.add(2); }; pos += 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 { dst.advance_mut(pos); } if !has_date { // optimized date header, write_date_header writes its own \r\n config.write_date_header(dst, camel_case); } // end-of-headers marker dst.extend_from_slice(b"\r\n"); Ok(()) } fn write_headers<F>(&mut self, mut f: F) where F: FnMut(&HeaderName, &Value), { match self.extra_headers() { Some(headers) => { // merging headers from head and extra headers. self.headers() .inner .iter() .filter(|(name, _)| !headers.contains_key(*name)) .chain(headers.inner.iter()) .for_each(|(k, v)| f(k, v)) } None => self.headers().inner.iter().for_each(|(k, v)| f(k, v)), } } } impl MessageType for Response<()> { fn status(&self) -> Option<StatusCode> { Some(self.head().status) } fn chunked(&self) -> bool { self.head().chunked() } fn headers(&self) -> &HeaderMap { &self.head().headers } fn extra_headers(&self) -> Option<&HeaderMap> { None } fn camel_case(&self) -> bool { self.head() .flags .contains(crate::message::Flags::CAMEL_CASE) } fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()> { let head = self.head(); let reason = head.reason().as_bytes(); dst.reserve(256 + head.headers.len() * AVERAGE_HEADER_SIZE + reason.len()); // status line helpers::write_status_line(head.version, head.status.as_u16(), dst); dst.put_slice(reason); Ok(()) } } impl MessageType for RequestHeadType { fn status(&self) -> Option<StatusCode> { None } fn chunked(&self) -> bool { self.as_ref().chunked() } 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::Result<()> { let head = self.as_ref(); dst.reserve(256 + head.headers.len() * AVERAGE_HEADER_SIZE); write!( helpers::MutWriter(dst), "{} {} {}", head.method, head.uri.path_and_query().map(|u| u.as_str()).unwrap_or("/"), match head.version { Version::HTTP_09 => "HTTP/0.9", Version::HTTP_10 => "HTTP/1.0", Version::HTTP_11 => "HTTP/1.1", Version::HTTP_2 => "HTTP/2.0", Version::HTTP_3 => "HTTP/3.0", _ => return Err(io::Error::new(io::ErrorKind::Other, "unsupported version")), } ) .map_err(|err| io::Error::new(io::ErrorKind::Other, err)) } } impl<T: MessageType> MessageEncoder<T> { /// Encode chunk. pub fn encode_chunk(&mut self, msg: &[u8], buf: &mut BytesMut) -> io::Result<bool> { self.te.encode(msg, buf) } /// Encode EOF. pub fn encode_eof(&mut self, buf: &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, config: &ServiceConfig, ) -> io::Result<()> { // transfer encoding if !head { self.te = match length { BodySize::Sized(0) => TransferEncoding::empty(), BodySize::Sized(len) => TransferEncoding::length(len), BodySize::Stream => { if message.chunked() && !stream { TransferEncoding::chunked() } else { TransferEncoding::eof() } } BodySize::None => TransferEncoding::empty(), }; } else { self.te = TransferEncoding::empty(); } message.encode_status(dst)?; message.encode_headers(dst, version, length, conn_type, config) } } /// Encoders to handle different Transfer-Encodings. #[derive(Debug)] pub(crate) struct TransferEncoding { kind: TransferEncodingKind, } #[derive(Debug, PartialEq, Clone)] enum TransferEncodingKind { /// An Encoder for when Transfer-Encoding includes `chunked`. Chunked(bool), /// An Encoder for when Content-Length is set. /// /// Enforces that the body is not longer than the Content-Length header. Length(u64), /// An Encoder for when Content-Length is not known. /// /// Application decides when to stop writing. Eof, } impl TransferEncoding { #[inline] pub fn empty() -> TransferEncoding { TransferEncoding { kind: TransferEncodingKind::Length(0), } } #[inline] pub fn eof() -> TransferEncoding { TransferEncoding { kind: TransferEncodingKind::Eof, } } #[inline] pub fn chunked() -> TransferEncoding { TransferEncoding { kind: TransferEncodingKind::Chunked(false), } } #[inline] pub fn length(len: u64) -> TransferEncoding { TransferEncoding { kind: TransferEncodingKind::Length(len), } } /// Encode message. Return `EOF` state of encoder #[inline] pub fn encode(&mut self, msg: &[u8], buf: &mut BytesMut) -> io::Result<bool> { match self.kind { TransferEncodingKind::Eof => { let eof = msg.is_empty(); buf.extend_from_slice(msg); Ok(eof) } TransferEncodingKind::Chunked(ref mut eof) => { if *eof { return Ok(true); } if msg.is_empty() { *eof = true; buf.extend_from_slice(b"0\r\n\r\n"); } else { writeln!(helpers::MutWriter(buf), "{:X}\r", msg.len()) .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; buf.reserve(msg.len() + 2); buf.extend_from_slice(msg); buf.extend_from_slice(b"\r\n"); } Ok(*eof) } TransferEncodingKind::Length(ref mut remaining) => { if *remaining > 0 { if msg.is_empty() { return Ok(*remaining == 0); } let len = cmp::min(*remaining, msg.len() as u64); buf.extend_from_slice(&msg[..len as usize]); *remaining -= len; Ok(*remaining == 0) } else { Ok(true) } } } } /// Encode eof. Return `EOF` state of encoder #[inline] pub fn encode_eof(&mut self, buf: &mut BytesMut) -> io::Result<()> { match self.kind { TransferEncodingKind::Eof => Ok(()), TransferEncodingKind::Length(rem) => { if rem != 0 { Err(io::Error::new(io::ErrorKind::UnexpectedEof, "")) } else { Ok(()) } } TransferEncodingKind::Chunked(ref mut eof) => { if !*eof { *eof = true; buf.extend_from_slice(b"0\r\n\r\n"); } Ok(()) } } } } /// # Safety /// 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 /// 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_camel_case(value: &[u8], buf: *mut u8, len: usize) { // first copy entire (potentially wrong) slice to output write_data(value, buf, len); // SAFETY: We just initialized the buffer with `value` let buffer = from_raw_parts_mut(buf, len); let mut iter = value.iter(); // first character should be uppercase if let Some(c @ b'a'..=b'z') = iter.next() { buffer[0] = c & 0b1101_1111; } // track 1 ahead of the current position since that's the location being assigned to let mut index = 2; // remaining characters after hyphens should also be uppercase while let Some(&c) = iter.next() { if c == b'-' { // advance iter by one and uppercase if needed if let Some(c @ b'a'..=b'z') = iter.next() { buffer[index] = c & 0b1101_1111; } index += 1; } index += 1; } } #[cfg(test)] mod tests { use std::rc::Rc; use bytes::Bytes; use http::header::{AUTHORIZATION, UPGRADE_INSECURE_REQUESTS}; use super::*; use crate::{ header::{HeaderValue, CONTENT_TYPE}, RequestHead, }; #[test] fn test_chunked_te() { let mut bytes = BytesMut::new(); let mut enc = TransferEncoding::chunked(); { assert!(!enc.encode(b"test", &mut bytes).ok().unwrap()); assert!(enc.encode(b"", &mut bytes).ok().unwrap()); } assert_eq!( bytes.split().freeze(), Bytes::from_static(b"4\r\ntest\r\n0\r\n\r\n") ); } #[actix_rt::test] async fn test_camel_case() { let mut bytes = BytesMut::with_capacity(2048); let mut head = RequestHead::default(); head.set_camel_case_headers(true); head.headers.insert(DATE, HeaderValue::from_static("date")); head.headers .insert(CONTENT_TYPE, HeaderValue::from_static("plain/text")); head.headers .insert(UPGRADE_INSECURE_REQUESTS, HeaderValue::from_static("1")); let mut head = RequestHeadType::Owned(head); let _ = head.encode_headers( &mut bytes, Version::HTTP_11, BodySize::Sized(0), ConnectionType::Close, &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.contains("Connection: close\r\n")); assert!(data.contains("Content-Type: plain/text\r\n")); assert!(data.contains("Date: date\r\n")); assert!(data.contains("Upgrade-Insecure-Requests: 1\r\n")); let _ = head.encode_headers( &mut bytes, Version::HTTP_11, BodySize::Stream, ConnectionType::KeepAlive, &ServiceConfig::default(), ); let data = String::from_utf8(Vec::from(bytes.split().freeze().as_ref())).unwrap(); assert!(data.contains("Transfer-Encoding: chunked\r\n")); assert!(data.contains("Content-Type: plain/text\r\n")); assert!(data.contains("Date: date\r\n")); let mut head = RequestHead::default(); head.set_camel_case_headers(false); head.headers.insert(DATE, HeaderValue::from_static("date")); head.headers .insert(CONTENT_TYPE, HeaderValue::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, ConnectionType::KeepAlive, &ServiceConfig::default(), ); let data = String::from_utf8(Vec::from(bytes.split().freeze().as_ref())).unwrap(); assert!(data.contains("transfer-encoding: chunked\r\n")); assert!(data.contains("content-type: xml\r\n")); assert!(data.contains("content-type: plain/text\r\n")); assert!(data.contains("date: date\r\n")); } #[actix_rt::test] async fn test_extra_headers() { let mut bytes = BytesMut::with_capacity(2048); let mut head = RequestHead::default(); head.headers.insert( AUTHORIZATION, HeaderValue::from_static("some authorization"), ); let mut extra_headers = HeaderMap::new(); extra_headers.insert( AUTHORIZATION, HeaderValue::from_static("another authorization"), ); extra_headers.insert(DATE, HeaderValue::from_static("date")); let mut head = RequestHeadType::Rc(Rc::new(head), Some(extra_headers)); let _ = head.encode_headers( &mut bytes, Version::HTTP_11, BodySize::Sized(0), ConnectionType::Close, &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.contains("connection: close\r\n")); assert!(data.contains("authorization: another authorization\r\n")); assert!(data.contains("date: date\r\n")); } #[actix_rt::test] async fn test_no_content_length() { let mut bytes = BytesMut::with_capacity(2048); let mut res = Response::with_body(StatusCode::SWITCHING_PROTOCOLS, ()); res.headers_mut().insert(DATE, HeaderValue::from_static("")); res.headers_mut() .insert(CONTENT_LENGTH, HeaderValue::from_static("0")); let _ = res.encode_headers( &mut bytes, 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.contains("transfer-encoding: chunked\r\n")); } }
use actix_service::{Service, ServiceFactory}; use actix_utils::future::{ready, Ready}; use crate::{Error, Request}; pub struct ExpectHandler; impl ServiceFactory<Request> for ExpectHandler { type Response = Request; type Error = Error; type Config = (); type Service = ExpectHandler; type InitError = Error; type Future = Ready<Result<Self::Service, Self::InitError>>; fn new_service(&self, _: Self::Config) -> Self::Future { ready(Ok(ExpectHandler)) } } impl Service<Request> for ExpectHandler { type Response = Request; type Error = Error; type Future = Ready<Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, req: Request) -> Self::Future { ready(Ok(req)) // TODO: add some way to trigger error // Err(error::ErrorExpectationFailed("test")) } }
//! HTTP/1 protocol implementation. use bytes::{Bytes, BytesMut}; mod chunked; mod client; mod codec; mod decoder; mod dispatcher; #[cfg(test)] mod dispatcher_tests; mod encoder; mod expect; mod payload; mod service; mod timer; mod upgrade; mod utils; pub use self::{ client::{ClientCodec, ClientPayloadCodec}, codec::Codec, dispatcher::Dispatcher, expect::ExpectHandler, payload::Payload, service::{H1Service, H1ServiceHandler}, upgrade::UpgradeHandler, utils::SendResponse, }; #[derive(Debug)] /// Codec message pub enum Message<T> { /// HTTP message. Item(T), /// Payload chunk. 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; pub(crate) fn reserve_readbuf(src: &mut BytesMut) { let cap = src.capacity(); if cap < LW { src.reserve(HW - cap); } } #[cfg(test)] mod tests { use super::*; use crate::Request; impl Message<Request> { pub fn message(self) -> Request { match self { Message::Item(req) => req, _ => panic!("error"), } } pub fn chunk(self) -> Bytes { match self { Message::Chunk(Some(data)) => data, _ => panic!("error"), } } pub fn eof(self) -> bool { match self { Message::Chunk(None) => true, Message::Chunk(Some(_)) => false, _ => panic!("error"), } } } }
//! Payload stream use std::{ cell::RefCell, collections::VecDeque, pin::Pin, rc::{Rc, Weak}, task::{Context, Poll, Waker}, }; use bytes::Bytes; use futures_core::Stream; use crate::error::PayloadError; /// max buffer size 32k pub(crate) const MAX_BUFFER_SIZE: usize = 32_768; #[derive(Debug, PartialEq, Eq)] pub enum PayloadStatus { Read, Pause, Dropped, } /// Buffered stream of bytes chunks /// /// Payload stores chunks in a vector. First chunk can be received with `poll_next`. Payload does /// not notify current task when new data is available. /// /// Payload can be used as `Response` body stream. #[derive(Debug)] pub struct Payload { inner: Rc<RefCell<Inner>>, } impl Payload { /// Creates a payload stream. /// /// This method construct two objects responsible for bytes stream generation: /// - `PayloadSender` - *Sender* side of the stream /// - `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. pub(crate) fn empty() -> Payload { Payload { inner: Rc::new(RefCell::new(Inner::new(true))), } } /// Length of the data in this payload #[cfg(test)] pub fn len(&self) -> usize { self.inner.borrow().len() } /// Is payload empty #[cfg(test)] pub fn is_empty(&self) -> bool { self.inner.borrow().len() == 0 } /// Put unused data back to payload #[inline] pub fn unread_data(&mut self, data: Bytes) { self.inner.borrow_mut().unread_data(data); } } impl Stream for Payload { type Item = Result<Bytes, PayloadError>; fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, PayloadError>>> { Pin::new(&mut *self.inner.borrow_mut()).poll_next(cx) } } /// Sender part of the payload stream pub struct PayloadSender { inner: Weak<RefCell<Inner>>, } impl PayloadSender { fn new(inner: Weak<RefCell<Inner>>) -> Self { Self { inner } } #[inline] pub fn set_error(&mut self, err: PayloadError) { if let Some(shared) = self.inner.upgrade() { shared.borrow_mut().set_error(err) } } #[inline] pub fn feed_eof(&mut self) { if let Some(shared) = self.inner.upgrade() { shared.borrow_mut().feed_eof() } } #[inline] pub fn feed_data(&mut self, data: Bytes) { if let Some(shared) = self.inner.upgrade() { shared.borrow_mut().feed_data(data) } } #[allow(clippy::needless_pass_by_ref_mut)] #[inline] pub fn need_read(&self, cx: &mut Context<'_>) -> PayloadStatus { // 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); PayloadStatus::Pause } } else { PayloadStatus::Dropped } } } #[derive(Debug)] struct Inner { len: usize, eof: bool, err: Option<PayloadError>, need_read: bool, items: VecDeque<Bytes>, task: Option<Waker>, io_task: Option<Waker>, } impl Inner { fn new(eof: bool) -> Self { Inner { eof, len: 0, err: None, items: VecDeque::new(), need_read: true, task: None, io_task: None, } } /// Wake up future waiting for payload data to be available. fn wake(&mut self) { if let Some(waker) = self.task.take() { waker.wake(); } } /// Wake up future feeding data to Payload. fn wake_io(&mut self) { if let Some(waker) = self.io_task.take() { waker.wake(); } } /// Register future waiting data from payload. /// Waker would be used in `Inner::wake` fn register(&mut self, cx: &Context<'_>) { if self .task .as_ref() .map_or(true, |w| !cx.waker().will_wake(w)) { self.task = Some(cx.waker().clone()); } } // Register future feeding data to payload. /// Waker would be used in `Inner::wake_io` fn register_io(&mut self, cx: &Context<'_>) { if self .io_task .as_ref() .map_or(true, |w| !cx.waker().will_wake(w)) { self.io_task = Some(cx.waker().clone()); } } #[inline] fn set_error(&mut self, err: PayloadError) { self.err = Some(err); } #[inline] fn feed_eof(&mut self) { self.eof = true; } #[inline] fn feed_data(&mut self, data: Bytes) { self.len += data.len(); self.items.push_back(data); self.need_read = self.len < MAX_BUFFER_SIZE; self.wake(); } #[cfg(test)] fn len(&self) -> usize { self.len } fn poll_next( mut self: Pin<&mut Self>, cx: &Context<'_>, ) -> Poll<Option<Result<Bytes, PayloadError>>> { if let Some(data) = self.items.pop_front() { self.len -= data.len(); self.need_read = self.len < MAX_BUFFER_SIZE; if self.need_read && !self.eof { self.register(cx); } self.wake_io(); Poll::Ready(Some(Ok(data))) } else if let Some(err) = self.err.take() { Poll::Ready(Some(Err(err))) } else if self.eof { Poll::Ready(None) } else { self.need_read = true; self.register(cx); self.wake_io(); Poll::Pending } } fn unread_data(&mut self, data: Bytes) { self.len += data.len(); self.items.push_front(data); } } #[cfg(test)] mod tests { use actix_utils::future::poll_fn; use static_assertions::{assert_impl_all, assert_not_impl_any}; use super::*; assert_impl_all!(Payload: Unpin); assert_not_impl_any!(Payload: Send, Sync); assert_impl_all!(Inner: Unpin, Send, Sync); #[actix_rt::test] async fn test_unread_data() { let (_, mut payload) = Payload::create(false); payload.unread_data(Bytes::from("data")); assert!(!payload.is_empty()); assert_eq!(payload.len(), 4); assert_eq!( Bytes::from("data"), poll_fn(|cx| Pin::new(&mut payload).poll_next(cx)) .await .unwrap() .unwrap() ); } }
use std::{ fmt, marker::PhantomData, net, rc::Rc, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_rt::net::TcpStream; use actix_service::{ fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _, }; use actix_utils::future::ready; use futures_core::future::LocalBoxFuture; use tracing::error; use super::{codec::Codec, dispatcher::Dispatcher, ExpectHandler, UpgradeHandler}; use crate::{ body::{BoxBody, MessageBody}, config::ServiceConfig, error::DispatchError, service::HttpServiceHandler, ConnectCallback, OnConnectData, Request, Response, }; /// `ServiceFactory` implementation for HTTP1 transport pub struct H1Service<T, S, B, X = ExpectHandler, U = UpgradeHandler> { srv: S, cfg: ServiceConfig, expect: X, upgrade: Option<U>, on_connect_ext: Option<Rc<ConnectCallback<T>>>, _phantom: PhantomData<B>, } impl<T, S, B> H1Service<T, S, B> where S: ServiceFactory<Request, Config = ()>, S::Error: Into<Response<BoxBody>>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, B: MessageBody, { /// Create new `HttpService` instance with config. pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>( 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<TcpStream, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, B: MessageBody, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory<(Request, Framed<TcpStream, Codec>), Config = (), Response = ()>, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { /// Create simple tcp stream service pub fn tcp( self, ) -> impl ServiceFactory<TcpStream, Config = (), Response = (), Error = DispatchError, InitError = ()> { fn_service(|io: TcpStream| { let peer_addr = io.peer_addr().ok(); ready(Ok((io, peer_addr))) }) .and_then(self) } } #[cfg(feature = "openssl")] mod openssl { use actix_tls::accept::{ openssl::{ reexports::{Error as SslError, SslAcceptor}, Acceptor, TlsStream, }, TlsError, }; use super::*; impl<S, B, X, U> H1Service<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, B: MessageBody, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, 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>>, U::InitError: fmt::Debug, { /// Create OpenSSL based service. pub fn openssl( self, acceptor: SslAcceptor, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<SslError, DispatchError>, InitError = (), > { Acceptor::new(acceptor) .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().peer_addr().ok(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_20")] mod rustls_0_20 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_20::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; use super::*; impl<S, B, X, U> H1Service<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, B: MessageBody, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, 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>>, U::InitError: fmt::Debug, { /// Create Rustls v0.20 based service. pub fn rustls( self, config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { Acceptor::new(config) .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(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_21")] mod rustls_0_21 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_21::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; use super::*; impl<S, B, X, U> H1Service<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, B: MessageBody, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, 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>>, U::InitError: fmt::Debug, { /// Create Rustls v0.21 based service. pub fn rustls_021( self, config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { Acceptor::new(config) .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(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_22")] mod rustls_0_22 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; use super::*; impl<S, B, X, U> H1Service<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, B: MessageBody, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, 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>>, U::InitError: fmt::Debug, { /// Create Rustls v0.22 based service. pub fn rustls_0_22( self, config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { Acceptor::new(config) .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(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_23")] mod rustls_0_23 { use std::io; use actix_service::ServiceFactoryExt as _; 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> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, B: MessageBody, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, 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>>, U::InitError: fmt::Debug, { /// Create Rustls v0.23 based service. pub fn rustls_0_23( self, config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { Acceptor::new(config) .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(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } impl<T, S, B, X, U> H1Service<T, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Error: Into<Response<BoxBody>>, S::Response: Into<Response<B>>, S::InitError: fmt::Debug, 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, srv: self.srv, upgrade: self.upgrade, on_connect_ext: self.on_connect_ext, _phantom: PhantomData, } } pub fn upgrade<U1>(self, upgrade: Option<U1>) -> H1Service<T, S, B, X, U1> where U1: ServiceFactory<(Request, Framed<T, Codec>), Response = ()>, U1::Error: fmt::Display, U1::InitError: fmt::Debug, { H1Service { upgrade, cfg: self.cfg, srv: self.srv, expect: self.expect, on_connect_ext: self.on_connect_ext, _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; self } } impl<T, S, B, X, U> ServiceFactory<(T, Option<net::SocketAddr>)> for H1Service<T, S, B, X, U> where T: AsyncRead + AsyncWrite + Unpin + 'static, S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, S::Response: Into<Response<B>>, S::InitError: fmt::Debug, B: MessageBody, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory<(Request, Framed<T, Codec>), Config = (), Response = ()>, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { type Response = (); 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.new_service(()); let expect = self.expect.new_service(()); let upgrade = self.upgrade.as_ref().map(|s| s.new_service(())); let on_connect_ext = self.on_connect_ext.clone(); let cfg = self.cfg.clone(); Box::pin(async move { let expect = expect.await.map_err(|err| { tracing::error!("Initialization of HTTP expect service error: {err:?}"); })?; let upgrade = match upgrade { Some(upgrade) => { let upgrade = upgrade.await.map_err(|err| { tracing::error!("Initialization of HTTP upgrade service error: {err:?}"); })?; Some(upgrade) } None => None, }; let service = service .await .map_err(|err| error!("Initialization of HTTP service error: {err:?}"))?; Ok(H1ServiceHandler::new( cfg, service, expect, upgrade, on_connect_ext, )) }) } } /// `Service` implementation for HTTP/1 transport pub type H1ServiceHandler<T, S, B, X, U> = HttpServiceHandler<T, S, B, X, U>; impl<T, S, B, X, U> Service<(T, Option<net::SocketAddr>)> for HttpServiceHandler<T, 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 = ()>, U::Error: fmt::Display + Into<Response<BoxBody>>, { type Response = (); type Error = DispatchError; type Future = Dispatcher<T, S, B, X, U>; fn poll_ready(&self, cx: &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_data = OnConnectData::from_io(&io, self.on_connect_ext.as_deref()); Dispatcher::new(io, Rc::clone(&self.flow), self.cfg.clone(), addr, conn_data) } }
use std::{fmt, future::Future, pin::Pin, task::Context}; use actix_rt::time::{Instant, Sleep}; use tracing::trace; #[derive(Debug)] pub(super) enum TimerState { Disabled, Inactive, Active { timer: Pin<Box<Sleep>> }, } impl TimerState { pub(super) fn new(enabled: bool) -> Self { if enabled { Self::Inactive } else { Self::Disabled } } pub(super) fn is_enabled(&self) -> bool { matches!(self, Self::Active { .. } | Self::Inactive) } pub(super) fn set(&mut self, timer: Sleep, line: u32) { if matches!(self, Self::Disabled) { trace!("setting disabled timer from line {}", line); } *self = Self::Active { timer: Box::pin(timer), }; } pub(super) fn set_and_init(&mut self, cx: &mut Context<'_>, timer: Sleep, line: u32) { self.set(timer, line); self.init(cx); } pub(super) fn clear(&mut self, line: u32) { if matches!(self, Self::Disabled) { trace!("trying to clear a disabled timer from line {}", line); } if matches!(self, Self::Inactive) { trace!("trying to clear an inactive timer from line {}", line); } *self = Self::Inactive; } pub(super) fn init(&mut self, cx: &mut Context<'_>) { if let TimerState::Active { timer } = self { let _ = timer.as_mut().poll(cx); } } } 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 } => { let deadline = timer.deadline(); let now = Instant::now(); if deadline < now { f.write_str("timer is active and has reached deadline") } else { write!( f, "timer is active and due to expire in {} milliseconds", ((deadline - now).as_secs_f32() * 1000.0) ) } } } } }
use actix_codec::Framed; use actix_service::{Service, ServiceFactory}; use futures_core::future::LocalBoxFuture; use crate::{h1::Codec, Error, Request}; pub struct UpgradeHandler; impl<T> ServiceFactory<(Request, Framed<T, Codec>)> for UpgradeHandler { type Response = (); type Error = Error; type Config = (); type Service = UpgradeHandler; type InitError = Error; type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { unimplemented!() } } impl<T> Service<(Request, Framed<T, Codec>)> for UpgradeHandler { type Response = (); type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, _: (Request, Framed<T, Codec>)) -> Self::Future { unimplemented!() } }
use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use pin_project_lite::pin_project; use crate::{ body::{BodySize, MessageBody}, h1::{Codec, Message}, Error, Response, }; pin_project! { /// Send HTTP/1 response pub struct SendResponse<T, B> { res: Option<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, body) = response.into_parts(); SendResponse { res: Some((res, body.size()).into()), body: Some(body), framed: Some(framed), } } } impl<T, B> Future for SendResponse<T, B> where T: AsyncRead + AsyncWrite + Unpin, B: MessageBody, B::Error: Into<Error>, { type Output = Result<Framed<T, Codec>, Error>; // TODO: rethink if we need loops in polls fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.as_mut().project(); let mut body_done = this.body.is_none(); loop { let mut body_ready = !body_done; // send body if this.res.is_none() && body_ready { while body_ready && !body_done && !this .framed .as_ref() .as_pin_ref() .unwrap() .is_write_buf_full() { let next = match this.body.as_mut().as_pin_mut().unwrap().poll_next(cx) { Poll::Ready(Some(Ok(item))) => Poll::Ready(Some(item)), Poll::Ready(Some(Err(err))) => return Poll::Ready(Err(err.into())), Poll::Ready(None) => Poll::Ready(None), Poll::Pending => Poll::Pending, }; match next { Poll::Ready(item) => { // body is done when item is None body_done = item.is_none(); if body_done { this.body.set(None); } let framed = this.framed.as_mut().as_pin_mut().unwrap(); framed .write(Message::Chunk(item)) .map_err(|err| Error::new_send_response().with_cause(err))?; } Poll::Pending => body_ready = false, } } } 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))? { Poll::Ready(_) => { if body_ready { continue; } else { return Poll::Pending; } } Poll::Pending => return Poll::Pending, } } // send response if let Some(res) = this.res.take() { framed .write(res) .map_err(|err| Error::new_send_response().with_cause(err))?; continue; } if !body_done { if body_ready { continue; } else { return Poll::Pending; } } else { break; } } let framed = this.framed.take().unwrap(); Poll::Ready(Ok(framed)) } }
use std::{ cmp, error::Error as StdError, future::Future, marker::PhantomData, net, pin::{pin, Pin}, rc::Rc, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite}; use actix_rt::time::{sleep, Sleep}; use actix_service::Service; use actix_utils::future::poll_fn; use bytes::{Bytes, BytesMut}; use futures_core::ready; use h2::{ server::{Connection, SendResponse}, Ping, PingPong, }; use pin_project_lite::pin_project; use crate::{ body::{BodySize, BoxBody, MessageBody}, config::ServiceConfig, header::{ HeaderName, HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, UPGRADE, }, service::HttpFlow, Extensions, Method, OnConnectData, Payload, Request, Response, ResponseHead, }; const CHUNK_SIZE: usize = 16_384; pin_project! { /// Dispatcher for HTTP/2 protocol. pub struct Dispatcher<T, S, B, X, U> { flow: Rc<HttpFlow<S, X, U>>, connection: Connection<T, Bytes>, conn_data: Option<Rc<Extensions>>, config: ServiceConfig, peer_addr: Option<net::SocketAddr>, ping_pong: Option<H2PingPong>, _phantom: PhantomData<B> } } impl<T, S, B, X, U> Dispatcher<T, S, B, X, U> where T: AsyncRead + AsyncWrite + Unpin, { pub(crate) fn new( mut conn: Connection<T, Bytes>, flow: Rc<HttpFlow<S, X, U>>, config: ServiceConfig, peer_addr: Option<net::SocketAddr>, conn_data: OnConnectData, timer: Option<Pin<Box<Sleep>>>, ) -> Self { let ping_pong = config.keep_alive().duration().map(|dur| H2PingPong { timer: timer .map(|mut timer| { // reuse timer slot if it was initialized for handshake timer.as_mut().reset((config.now() + dur).into()); timer }) .unwrap_or_else(|| Box::pin(sleep(dur))), in_flight: false, ping_pong: conn.ping_pong().unwrap(), }); Self { flow, config, peer_addr, connection: conn, conn_data: conn_data.0.map(Rc::new), ping_pong, _phantom: PhantomData, } } } struct H2PingPong { /// Handle to send ping frames from the peer. ping_pong: PingPong, /// True when a ping has been sent and 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: Into<Response<B>>, B: MessageBody, { type Output = Result<(), crate::error::DispatchError>; #[inline] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); loop { match Pin::new(&mut this.connection).poll_accept(cx)? { Poll::Ready(Some((req, tx))) => { let (parts, body) = req.into_parts(); let payload = crate::h2::Payload::new(body); let pl = Payload::H2 { payload }; let mut req = Request::with_payload(pl); let head_req = parts.method == Method::HEAD; let head = req.head_mut(); head.uri = parts.uri; head.method = parts.method; head.version = parts.version; head.headers = parts.headers.into(); head.peer_addr = this.peer_addr; req.conn_data.clone_from(&this.conn_data); let fut = this.flow.service.call(req); let config = this.config.clone(); // multiplex request handling with spawn task actix_rt::spawn(async move { // resolve service call and send response. let res = match fut.await { Ok(res) => handle_response(res.into(), tx, config, head_req).await, Err(err) => { let res: Response<BoxBody> = err.into(); handle_response(res, tx, config, head_req).await } }; // log error. if let Err(err) = res { match err { DispatchError::SendResponse(err) => { tracing::trace!("Error sending response: {err:?}"); } DispatchError::SendData(err) => { tracing::warn!("Send data error: {err:?}"); } DispatchError::ResponseBody(err) => { tracing::error!("Response payload stream error: {err:?}"); } } } }); } Poll::Ready(None) => return Poll::Ready(Ok(())), Poll::Pending => match this.ping_pong.as_mut() { Some(ping_pong) => loop { if ping_pong.in_flight { // When there is an in-flight ping-pong, poll pong and and keep-alive // timer. On successful pong received, update keep-alive timer to // determine the next timing of ping pong. match ping_pong.ping_pong.poll_pong(cx)? { Poll::Ready(_) => { ping_pong.in_flight = false; let dead_line = this.config.keep_alive_deadline().unwrap(); ping_pong.timer.as_mut().reset(dead_line.into()); } Poll::Pending => { return ping_pong.timer.as_mut().poll(cx).map(|_| Ok(())); } } } else { // When there is no in-flight ping-pong, keep-alive timer is used to // wait for next timing of ping-pong. Therefore, at this point it serves // as an interval instead. ready!(ping_pong.timer.as_mut().poll(cx)); ping_pong.ping_pong.send_ping(Ping::opaque())?; let dead_line = this.config.keep_alive_deadline().unwrap(); ping_pong.timer.as_mut().reset(dead_line.into()); ping_pong.in_flight = true; } }, None => return Poll::Pending, }, } } } } enum DispatchError { SendResponse(h2::Error), SendData(h2::Error), ResponseBody(Box<dyn StdError>), } async fn handle_response<B>( res: Response<B>, mut tx: SendResponse<Bytes>, config: ServiceConfig, head_req: bool, ) -> Result<(), DispatchError> where B: MessageBody, { let (res, body) = res.replace_body(()); // prepare response. let mut size = body.size(); let res = prepare_response(config, res.head(), &mut size); let eof_or_head = size.is_eof() || head_req; // send response head and return on eof. let mut stream = tx .send_response(res, eof_or_head) .map_err(DispatchError::SendResponse)?; if eof_or_head { return Ok(()); } 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(), CHUNK_SIZE); // reserve enough space and wait for stream ready. stream.reserve_capacity(chunk_size); match poll_fn(|cx| stream.poll_capacity(cx)).await { // No capacity left. drop body and return. None => return Ok(()), Some(Err(err)) => return Err(DispatchError::SendData(err)), Some(Ok(cap)) => { // split chunk to writeable size and send to client let len = chunk.len(); let bytes = chunk.split_to(cmp::min(len, cap)); stream .send_data(bytes, false) .map_err(DispatchError::SendData)?; // Current chuck completely sent. break send loop and poll next one. if chunk.is_empty() { break 'send; } } } } } // response body streaming finished. send end of stream and return. stream .send_data(Bytes::new(), true) .map_err(DispatchError::SendData)?; Ok(()) } fn prepare_response( config: ServiceConfig, head: &ResponseHead, size: &mut BodySize, ) -> http::Response<()> { let mut has_date = false; let mut skip_len = size != &BodySize::Stream; let mut res = http::Response::new(()); *res.status_mut() = head.status; *res.version_mut() = http::Version::HTTP_2; // Content length match head.status { http::StatusCode::NO_CONTENT | http::StatusCode::CONTINUE | http::StatusCode::PROCESSING => *size = BodySize::None, http::StatusCode::SWITCHING_PROTOCOLS => { skip_len = true; *size = BodySize::Stream; } _ => {} } match size { BodySize::None | BodySize::Stream => {} BodySize::Sized(0) => { #[allow(clippy::declare_interior_mutable_const)] const HV_ZERO: HeaderValue = HeaderValue::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(), ); } }; // copy headers for (key, value) in head.headers.iter() { match key { // omit HTTP/1.x only headers according to: // https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2.2 &CONNECTION | &TRANSFER_ENCODING | &UPGRADE => continue, &CONTENT_LENGTH if skip_len => continue, &DATE => has_date = true, // omit HTTP/1.x only headers according to: // https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2.2 hdr if hdr == HeaderName::from_static("keep-alive") || hdr == HeaderName::from_static("proxy-connection") => { continue } _ => {} } res.headers_mut().append(key, value.clone()); } // set date header if !has_date { let mut bytes = BytesMut::with_capacity(29); config.write_date_header_value(&mut bytes); res.headers_mut().insert( DATE, // SAFETY: serialized date-times are known ASCII strings unsafe { HeaderValue::from_maybe_shared_unchecked(bytes.freeze()) }, ); } res }
//! HTTP/2 protocol. use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite}; use actix_rt::time::{sleep_until, Sleep}; use bytes::Bytes; use futures_core::{ready, Stream}; use h2::{ server::{handshake, Connection, Handshake}, RecvStream, }; use crate::{ config::ServiceConfig, error::{DispatchError, PayloadError}, }; mod dispatcher; mod service; pub use self::{dispatcher::Dispatcher, service::H2Service}; /// HTTP/2 peer stream. pub struct Payload { stream: RecvStream, } impl Payload { pub(crate) fn new(stream: RecvStream) -> 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)) { Some(Ok(chunk)) => { let len = chunk.len(); match this.stream.flow_control().release_capacity(len) { Ok(()) => Poll::Ready(Some(Ok(chunk))), Err(err) => Poll::Ready(Some(Err(err.into()))), } } Some(Err(err)) => Poll::Ready(Some(Err(err.into()))), None => Poll::Ready(None), } } } pub(crate) fn handshake_with_timeout<T>(io: T, config: &ServiceConfig) -> HandshakeWithTimeout<T> where T: AsyncRead + AsyncWrite + Unpin, { HandshakeWithTimeout { handshake: handshake(io), timer: config .client_request_deadline() .map(|deadline| Box::pin(sleep_until(deadline.into()))), } } pub(crate) struct HandshakeWithTimeout<T: AsyncRead + AsyncWrite + Unpin> { handshake: Handshake<T>, timer: Option<Pin<Box<Sleep>>>, } impl<T> Future for HandshakeWithTimeout<T> where T: AsyncRead + AsyncWrite + Unpin, { type Output = Result<(Connection<T, Bytes>, Option<Pin<Box<Sleep>>>), DispatchError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); match Pin::new(&mut this.handshake).poll(cx)? { // return the timer on success handshake; its slot can be re-used for h2 ping-pong Poll::Ready(conn) => Poll::Ready(Ok((conn, this.timer.take()))), Poll::Pending => match this.timer.as_mut() { Some(timer) => { ready!(timer.as_mut().poll(cx)); Poll::Ready(Err(DispatchError::SlowRequestTimeout)) } None => Poll::Pending, }, } } } #[cfg(test)] mod tests { use static_assertions::assert_impl_all; use super::*; assert_impl_all!(Payload: Unpin, Send, Sync); }
use std::{ future::Future, marker::PhantomData, mem, net, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite}; use actix_rt::net::TcpStream; use actix_service::{ fn_factory, fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _, }; use actix_utils::future::ready; use futures_core::{future::LocalBoxFuture, ready}; use tracing::{error, trace}; use super::{dispatcher::Dispatcher, handshake_with_timeout, HandshakeWithTimeout}; use crate::{ body::{BoxBody, MessageBody}, config::ServiceConfig, error::DispatchError, service::HttpFlow, ConnectCallback, OnConnectData, Request, Response, }; /// `ServiceFactory` implementation for HTTP/2 transport pub struct H2Service<T, S, B> { srv: S, cfg: ServiceConfig, on_connect_ext: Option<Rc<ConnectCallback<T>>>, _phantom: PhantomData<(T, B)>, } impl<T, S, B> H2Service<T, S, B> where S: ServiceFactory<Request, Config = ()>, S::Error: Into<Response<BoxBody>> + 'static, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, { /// Create new `H2Service` instance with config. pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>( cfg: ServiceConfig, service: F, ) -> Self { 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; self } } impl<S, B> H2Service<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: 'static, B: MessageBody + 'static, { /// Create plain TCP based service pub fn tcp( self, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = DispatchError, InitError = S::InitError, > { fn_factory(|| { ready(Ok::<_, S::InitError>(fn_service(|io: TcpStream| { let peer_addr = io.peer_addr().ok(); ready(Ok::<_, DispatchError>((io, peer_addr))) }))) }) .and_then(self) } } #[cfg(feature = "openssl")] mod openssl { use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ openssl::{ reexports::{Error as SslError, SslAcceptor}, Acceptor, TlsStream, }, TlsError, }; 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: 'static, B: MessageBody + 'static, { /// Create OpenSSL based service. pub fn openssl( self, acceptor: SslAcceptor, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<SslError, DispatchError>, InitError = S::InitError, > { Acceptor::new(acceptor) .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().peer_addr().ok(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_20")] mod rustls_0_20 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; 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: 'static, B: MessageBody + 'static, { /// Create Rustls v0.20 based service. pub fn rustls( self, mut config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = S::InitError, > { let mut protos = vec![b"h2".to_vec()]; protos.extend_from_slice(&config.alpn_protocols); config.alpn_protocols = protos; Acceptor::new(config) .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(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_21")] mod rustls_0_21 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_21::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; 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: 'static, B: MessageBody + 'static, { /// Create Rustls v0.21 based service. pub fn rustls_021( self, mut config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = S::InitError, > { let mut protos = vec![b"h2".to_vec()]; protos.extend_from_slice(&config.alpn_protocols); config.alpn_protocols = protos; Acceptor::new(config) .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(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_22")] mod rustls_0_22 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; 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: 'static, B: MessageBody + 'static, { /// Create Rustls v0.22 based service. pub fn rustls_0_22( self, mut config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = S::InitError, > { let mut protos = vec![b"h2".to_vec()]; protos.extend_from_slice(&config.alpn_protocols); config.alpn_protocols = protos; Acceptor::new(config) .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(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_23")] mod rustls_0_23 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_23::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; 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: 'static, B: MessageBody + 'static, { /// Create Rustls v0.23 based service. pub fn rustls_0_23( self, mut config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = S::InitError, > { let mut protos = vec![b"h2".to_vec()]; protos.extend_from_slice(&config.alpn_protocols); config.alpn_protocols = protos; Acceptor::new(config) .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(); (io, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B> where T: AsyncRead + AsyncWrite + Unpin + 'static, 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: 'static, B: MessageBody + 'static, { type Response = (); type Error = DispatchError; type Config = (); type Service = H2ServiceHandler<T, S::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.clone(); Box::pin(async move { let service = service.await?; Ok(H2ServiceHandler::new(cfg, on_connect_ext, service)) }) } } /// `Service` implementation for HTTP/2 transport pub struct H2ServiceHandler<T, S, B> where S: Service<Request>, { flow: Rc<HttpFlow<S, (), ()>>, cfg: ServiceConfig, on_connect_ext: Option<Rc<ConnectCallback<T>>>, _phantom: PhantomData<B>, } impl<T, S, B> H2ServiceHandler<T, S, B> where S: Service<Request>, S::Error: Into<Response<BoxBody>> + 'static, S::Future: 'static, S::Response: Into<Response<B>> + 'static, B: MessageBody + 'static, { fn new( cfg: ServiceConfig, on_connect_ext: Option<Rc<ConnectCallback<T>>>, service: S, ) -> H2ServiceHandler<T, S, B> { H2ServiceHandler { flow: HttpFlow::new(service, (), None), cfg, on_connect_ext, _phantom: PhantomData, } } } impl<T, S, B> Service<(T, Option<net::SocketAddr>)> for H2ServiceHandler<T, S, B> where T: AsyncRead + AsyncWrite + Unpin, S: Service<Request>, S::Error: Into<Response<BoxBody>> + 'static, S::Future: 'static, S::Response: Into<Response<B>> + 'static, B: MessageBody + 'static, { type Response = (); type Error = DispatchError; type Future = H2ServiceHandlerResponse<T, S, B>; fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.flow.service.poll_ready(cx).map_err(|err| { let err = err.into(); 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 { state: State::Handshake( Some(Rc::clone(&self.flow)), Some(self.cfg.clone()), addr, on_connect_data, handshake_with_timeout(io, &self.cfg), ), } } } enum State<T, S: Service<Request>, B: MessageBody> where T: AsyncRead + AsyncWrite + Unpin, S::Future: 'static, { Handshake( Option<Rc<HttpFlow<S, (), ()>>>, Option<ServiceConfig>, Option<net::SocketAddr>, OnConnectData, HandshakeWithTimeout<T>, ), Established(Dispatcher<T, S, B, (), ()>), } pub struct H2ServiceHandlerResponse<T, S, B> where T: AsyncRead + AsyncWrite + Unpin, S: Service<Request>, S::Error: Into<Response<BoxBody>> + 'static, S::Future: 'static, S::Response: Into<Response<B>> + 'static, B: MessageBody + 'static, { state: State<T, S, B>, } impl<T, S, B> Future for H2ServiceHandlerResponse<T, S, B> where T: AsyncRead + AsyncWrite + Unpin, S: Service<Request>, S::Error: Into<Response<BoxBody>> + 'static, S::Future: 'static, S::Response: Into<Response<B>> + 'static, B: MessageBody, { type Output = Result<(), DispatchError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match self.state { State::Handshake( ref mut srv, ref mut config, ref peer_addr, ref mut conn_data, ref mut handshake, ) => match ready!(Pin::new(handshake).poll(cx)) { Ok((conn, timer)) => { let on_connect_data = mem::take(conn_data); self.state = State::Established(Dispatcher::new( conn, srv.take().unwrap(), config.take().unwrap(), *peer_addr, on_connect_data, timer, )); self.poll(cx) } Err(err) => { trace!("H2 handshake error: {}", err); Poll::Ready(Err(err)) } }, State::Established(ref mut disp) => Pin::new(disp).poll(cx), } } }
//! Sealed [`AsHeaderName`] trait and implementations. use std::{borrow::Cow, str::FromStr as _}; use http::header::{HeaderName, InvalidHeaderName}; /// Sealed trait implemented for types that can be effectively borrowed as a [`HeaderValue`]. /// /// [`HeaderValue`]: super::HeaderValue pub trait AsHeaderName: Sealed {} pub struct Seal; pub trait Sealed { fn try_as_name(&self, seal: Seal) -> Result<Cow<'_, HeaderName>, InvalidHeaderName>; } impl Sealed for HeaderName { #[inline] fn try_as_name(&self, _: Seal) -> Result<Cow<'_, HeaderName>, InvalidHeaderName> { Ok(Cow::Borrowed(self)) } } impl AsHeaderName for HeaderName {} impl Sealed for &HeaderName { #[inline] fn try_as_name(&self, _: Seal) -> Result<Cow<'_, HeaderName>, InvalidHeaderName> { Ok(Cow::Borrowed(*self)) } } impl AsHeaderName for &HeaderName {} impl Sealed for &str { #[inline] fn try_as_name(&self, _: Seal) -> Result<Cow<'_, HeaderName>, InvalidHeaderName> { HeaderName::from_str(self).map(Cow::Owned) } } impl AsHeaderName for &str {} impl Sealed for String { #[inline] fn try_as_name(&self, _: Seal) -> Result<Cow<'_, HeaderName>, InvalidHeaderName> { HeaderName::from_str(self).map(Cow::Owned) } } impl AsHeaderName for String {} impl Sealed for &String { #[inline] fn try_as_name(&self, _: Seal) -> Result<Cow<'_, HeaderName>, InvalidHeaderName> { HeaderName::from_str(self).map(Cow::Owned) } } impl AsHeaderName for &String {}
//! 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 caches have handled that response and its corresponding /// request. /// /// See [RFC 9211](https://www.rfc-editor.org/rfc/rfc9211) for full semantics. // TODO(breaking): replace with http's version pub const CACHE_STATUS: HeaderName = HeaderName::from_static("cache-status"); /// Response header field that allows origin servers to control the behavior of CDN caches /// interposed between them and clients separately from other caches that might handle the response. /// /// See [RFC 9213](https://www.rfc-editor.org/rfc/rfc9213) for full semantics. // TODO(breaking): replace with http's version pub const CDN_CACHE_CONTROL: HeaderName = HeaderName::from_static("cdn-cache-control"); /// Response header field that sends a signal to the user agent that it ought to remove all data of /// a certain set of types. /// /// See the [W3C Clear-Site-Data spec] for full semantics. /// /// [W3C Clear-Site-Data spec]: https://www.w3.org/TR/clear-site-data/#header pub const CLEAR_SITE_DATA: HeaderName = HeaderName::from_static("clear-site-data"); /// Response header that prevents a document from loading any cross-origin resources that don't /// explicitly grant the document permission (using [CORP] or [CORS]). /// /// [CORP]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cross-Origin_Resource_Policy_(CORP) /// [CORS]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS pub const CROSS_ORIGIN_EMBEDDER_POLICY: HeaderName = HeaderName::from_static("cross-origin-embedder-policy"); /// Response header that allows you to ensure a top-level document does not share a browsing context /// group with cross-origin documents. pub const CROSS_ORIGIN_OPENER_POLICY: HeaderName = HeaderName::from_static("cross-origin-opener-policy"); /// Response header that conveys a desire that the browser blocks no-cors cross-origin/cross-site /// requests to the given resource. pub const CROSS_ORIGIN_RESOURCE_POLICY: 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-policy"); /// Request header (de-facto standard) for identifying the originating IP address of a client /// connecting to a web server through a proxy server. pub const X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for"); /// Request header (de-facto standard) for identifying the original host requested by the client in /// the `Host` HTTP request header. pub const X_FORWARDED_HOST: HeaderName = HeaderName::from_static("x-forwarded-host"); /// Request header (de-facto standard) for identifying the protocol that a client used to connect to /// your proxy or load balancer. pub const X_FORWARDED_PROTO: HeaderName = HeaderName::from_static("x-forwarded-proto");
//! [`TryIntoHeaderPair`] trait and implementations. use super::{ Header, HeaderName, HeaderValue, InvalidHeaderName, InvalidHeaderValue, TryIntoHeaderValue, }; use crate::error::HttpError; /// An interface for types that can be converted into a [`HeaderName`] + [`HeaderValue`] pair for /// insertion into a [`HeaderMap`]. /// /// [`HeaderMap`]: super::HeaderMap pub trait TryIntoHeaderPair: Sized { type Error: Into<HttpError>; fn try_into_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error>; } #[derive(Debug)] pub enum InvalidHeaderPart { Name(InvalidHeaderName), Value(InvalidHeaderValue), } impl From<InvalidHeaderPart> for HttpError { fn from(part_err: InvalidHeaderPart) -> Self { match part_err { InvalidHeaderPart::Name(err) => err.into(), InvalidHeaderPart::Value(err) => err.into(), } } } impl<V> TryIntoHeaderPair for (HeaderName, V) where V: TryIntoHeaderValue, V::Error: Into<InvalidHeaderValue>, { type Error = InvalidHeaderPart; fn try_into_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> { let (name, 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 = InvalidHeaderPart; fn try_into_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> { let (name, value) = self; let value = value .try_into_value() .map_err(|err| InvalidHeaderPart::Value(err.into()))?; Ok((name.clone(), value)) } } impl<V> TryIntoHeaderPair for (&[u8], V) where V: TryIntoHeaderValue, V::Error: Into<InvalidHeaderValue>, { type Error = InvalidHeaderPart; fn try_into_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> { let (name, value) = self; let name = HeaderName::try_from(name).map_err(InvalidHeaderPart::Name)?; let value = value .try_into_value() .map_err(|err| InvalidHeaderPart::Value(err.into()))?; Ok((name, value)) } } impl<V> TryIntoHeaderPair for (&str, V) where V: TryIntoHeaderValue, V::Error: Into<InvalidHeaderValue>, { type Error = InvalidHeaderPart; fn try_into_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> { let (name, value) = self; let name = HeaderName::try_from(name).map_err(InvalidHeaderPart::Name)?; let value = value .try_into_value() .map_err(|err| InvalidHeaderPart::Value(err.into()))?; Ok((name, value)) } } impl<V> TryIntoHeaderPair for (String, V) where V: TryIntoHeaderValue, V::Error: Into<InvalidHeaderValue>, { type Error = InvalidHeaderPart; #[inline] fn try_into_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> { let (name, value) = self; (name.as_str(), value).try_into_pair() } } impl<T: 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()?)) } }
//! [`TryIntoHeaderValue`] trait and implementations. use bytes::Bytes; use http::{header::InvalidHeaderValue, Error as HttpError, HeaderValue}; use mime::Mime; /// An interface for types that can be converted into a [`HeaderValue`]. pub trait TryIntoHeaderValue: Sized { /// The type returned in the event of a conversion error. type Error: Into<HttpError>; /// Try to convert value to a HeaderValue. fn try_into_value(self) -> Result<HeaderValue, Self::Error>; } impl TryIntoHeaderValue for HeaderValue { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { Ok(self) } } impl TryIntoHeaderValue for &HeaderValue { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { Ok(self.clone()) } } impl TryIntoHeaderValue for &str { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { self.parse() } } impl TryIntoHeaderValue for &[u8] { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { HeaderValue::from_bytes(self) } } impl TryIntoHeaderValue for Bytes { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { HeaderValue::from_maybe_shared(self) } } impl TryIntoHeaderValue for Vec<u8> { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { HeaderValue::try_from(self) } } impl TryIntoHeaderValue for String { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { HeaderValue::try_from(self) } } 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(self) -> Result<HeaderValue, Self::Error> { HeaderValue::try_from(self.to_string()) } } impl TryIntoHeaderValue for u64 { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { HeaderValue::try_from(self.to_string()) } } impl TryIntoHeaderValue for i32 { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { HeaderValue::try_from(self.to_string()) } } impl TryIntoHeaderValue for u32 { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { HeaderValue::try_from(self.to_string()) } } impl TryIntoHeaderValue for Mime { type Error = InvalidHeaderValue; #[inline] fn try_into_value(self) -> Result<HeaderValue, Self::Error> { HeaderValue::from_str(self.as_ref()) } }
//! A multi-value [`HeaderMap`] and its iterators. use std::{borrow::Cow, collections::hash_map, iter, ops}; use foldhash::{HashMap as FoldHashMap, HashMapExt as _}; use http::header::{HeaderName, HeaderValue}; use smallvec::{smallvec, SmallVec}; use super::AsHeaderName; /// A multi-map of HTTP headers. /// /// `HeaderMap` is a "multi-map" of [`HeaderName`] to one or more [`HeaderValue`]s. /// /// # Examples /// /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// /// let mut map = HeaderMap::new(); /// /// map.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain")); /// map.insert(header::ORIGIN, HeaderValue::from_static("example.com")); /// /// assert!(map.contains_key(header::CONTENT_TYPE)); /// assert!(map.contains_key(header::ORIGIN)); /// /// let mut removed = map.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 actix_http::header::{self, HeaderMap, HeaderValue}; /// /// let headers = HeaderMap::from_iter([ /// (header::CONTENT_TYPE, HeaderValue::from_static("text/plain")), /// (header::COOKIE, HeaderValue::from_static("foo=1")), /// (header::COOKIE, HeaderValue::from_static("bar=1")), /// ]); /// /// assert_eq!(headers.len(), 3); /// ``` #[derive(Debug, Clone, Default)] pub struct HeaderMap { pub(crate) inner: FoldHashMap<HeaderName, Value>, } /// A bespoke non-empty list for HeaderMap values. #[derive(Debug, Clone)] pub(crate) struct Value { inner: SmallVec<[HeaderValue; 4]>, } impl Value { fn one(val: HeaderValue) -> Self { Self { inner: smallvec![val], } } fn first(&self) -> &HeaderValue { &self.inner[0] } fn first_mut(&mut self) -> &mut HeaderValue { &mut self.inner[0] } fn append(&mut self, new_val: HeaderValue) { self.inner.push(new_val) } } impl ops::Deref for Value { type Target = SmallVec<[HeaderValue; 4]>; fn deref(&self) -> &Self::Target { &self.inner } } impl HeaderMap { /// Create an empty `HeaderMap`. /// /// The map will be created without any capacity; this function will not allocate. /// /// # Examples /// ``` /// # use actix_http::header::HeaderMap; /// let map = HeaderMap::new(); /// /// assert!(map.is_empty()); /// assert_eq!(0, map.capacity()); /// ``` pub fn new() -> Self { HeaderMap::default() } /// Create an empty `HeaderMap` with the specified capacity. /// /// The map will be able to hold at least `capacity` elements without needing to reallocate. /// If `capacity` is 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 { HeaderMap { inner: FoldHashMap::with_capacity(capacity), } } /// Create new `HeaderMap` from a `http::HeaderMap`-like drain. pub(crate) fn from_drain<I>(mut drain: I) -> Self where I: Iterator<Item = (Option<HeaderName>, HeaderValue)>, { let (first_name, first_value) = match drain.next() { None => return HeaderMap::new(), Some((name, val)) => { let name = name.expect("drained first item had no name"); (name, val) } }; let (lb, ub) = drain.size_hint(); let capacity = ub.unwrap_or(lb); let mut map = HeaderMap::with_capacity(capacity); map.append(first_name.clone(), first_value); let (map, _) = drain.fold((map, first_name), |(mut map, prev_name), (name, value)| { let name = name.unwrap_or(prev_name); map.append(name.clone(), value); (map, name) }); map } /// Returns the number of values stored in the map. /// /// See also: [`len_keys`](Self::len_keys). /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// assert_eq!(map.len(), 0); /// /// map.insert(header::ACCEPT, HeaderValue::from_static("text/plain")); /// map.insert(header::SET_COOKIE, HeaderValue::from_static("one=1")); /// assert_eq!(map.len(), 2); /// /// map.append(header::SET_COOKIE, HeaderValue::from_static("two=2")); /// assert_eq!(map.len(), 3); /// ``` pub fn len(&self) -> usize { self.inner.values().map(|vals| vals.len()).sum() } /// 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!(map.len_keys(), 0); /// /// map.insert(header::ACCEPT, HeaderValue::from_static("text/plain")); /// map.insert(header::SET_COOKIE, HeaderValue::from_static("one=1")); /// assert_eq!(map.len_keys(), 2); /// /// map.append(header::SET_COOKIE, HeaderValue::from_static("two=2")); /// assert_eq!(map.len_keys(), 2); /// ``` pub fn len_keys(&self) -> usize { self.inner.len() } /// Returns true if the map contains no elements. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// assert!(map.is_empty()); /// /// map.insert(header::ACCEPT, HeaderValue::from_static("text/plain")); /// assert!(!map.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.inner.len() == 0 } /// Clears the map, removing all name-value pairs. /// /// Keeps the allocated memory for reuse. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// map.insert(header::ACCEPT, HeaderValue::from_static("text/plain")); /// map.insert(header::SET_COOKIE, HeaderValue::from_static("one=1")); /// assert_eq!(map.len(), 2); /// /// map.clear(); /// assert!(map.is_empty()); /// ``` pub fn clear(&mut self) { self.inner.clear(); } fn get_value(&self, key: impl AsHeaderName) -> Option<&Value> { match key.try_as_name(super::as_name::Seal).ok()? { Cow::Borrowed(name) => self.inner.get(name), Cow::Owned(name) => self.inner.get(&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 chosen with any particular order; though, the returned item will be /// consistent for each call to `get` if the map has not changed. /// /// See also: [`get_all`](Self::get_all). /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// map.insert(header::SET_COOKIE, HeaderValue::from_static("one=1")); /// /// let cookie = map.get(header::SET_COOKIE).unwrap(); /// assert_eq!(cookie, "one=1"); /// /// map.append(header::SET_COOKIE, HeaderValue::from_static("two=2")); /// assert_eq!(map.get(header::SET_COOKIE).unwrap(), "one=1"); /// /// assert_eq!(map.get(header::SET_COOKIE), map.get("set-cookie")); /// assert_eq!(map.get(header::SET_COOKIE), map.get("Set-Cookie")); /// /// assert!(map.get(header::HOST).is_none()); /// assert!(map.get("INVALID HEADER NAME").is_none()); /// ``` pub fn get(&self, key: impl AsHeaderName) -> Option<&HeaderValue> { self.get_value(key).map(Value::first) } /// Returns a mutable reference to the _first_ value associated 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 chosen with any particular order; though, the returned item will be /// consistent for each call to `get_mut` if the map has not changed. /// /// See also: [`get_all`](Self::get_all). /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// map.insert(header::SET_COOKIE, 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::HOST).is_none()); /// assert!(map.get("INVALID HEADER NAME").is_none()); /// ``` pub fn get_mut(&mut self, key: impl AsHeaderName) -> Option<&mut HeaderValue> { match key.try_as_name(super::as_name::Seal).ok()? { Cow::Borrowed(name) => self.inner.get_mut(name).map(Value::first_mut), Cow::Owned(name) => self.inner.get_mut(&name).map(Value::first_mut), } } /// Returns an iterator over all values associated with a header name. /// /// The returned iterator does not incur any allocations and will yield no items if there are no /// values associated with the key. Iteration order is guaranteed to be the same as /// insertion order. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// let mut none_iter = map.get_all(header::ORIGIN); /// assert!(none_iter.next().is_none()); /// /// map.insert(header::SET_COOKIE, HeaderValue::from_static("one=1")); /// map.append(header::SET_COOKIE, HeaderValue::from_static("two=2")); /// /// let mut set_cookies_iter = map.get_all(header::SET_COOKIE); /// assert_eq!(set_cookies_iter.next().unwrap(), "one=1"); /// assert_eq!(set_cookies_iter.next().unwrap(), "two=2"); /// assert!(set_cookies_iter.next().is_none()); /// ``` pub fn get_all(&self, key: impl AsHeaderName) -> std::slice::Iter<'_, HeaderValue> { match self.get_value(key) { Some(value) => value.iter(), None => [].iter(), } } // TODO: get_all_mut ? /// Returns `true` if the map contains a value for the specified key. /// /// Invalid 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")); /// assert!(map.contains_key(header::ACCEPT)); /// ``` pub fn contains_key(&self, key: impl AsHeaderName) -> bool { match key.try_as_name(super::as_name::Seal) { Ok(Cow::Borrowed(name)) => self.inner.contains_key(name), Ok(Cow::Owned(name)) => self.inner.contains_key(&name), Err(_) => false, } } /// Inserts (overrides) a name-value pair in the map. /// /// If the map already contained this key, the new value is associated with the key and all /// previous values are removed and returned as a `Removed` iterator. The key is not updated; /// this matters for types that can be `==` without being identical. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// map.insert(header::ACCEPT, HeaderValue::from_static("text/plain")); /// assert!(map.contains_key(header::ACCEPT)); /// assert_eq!(map.len(), 1); /// /// let mut removed = map.insert(header::ACCEPT, HeaderValue::from_static("text/csv")); /// assert_eq!(removed.next().unwrap(), "text/plain"); /// assert!(removed.next().is_none()); /// /// assert_eq!(map.len(), 1); /// ``` /// /// A convenience method is provided on the returned iterator to check if the insertion replaced /// any values. /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// let removed = map.insert(header::ACCEPT, HeaderValue::from_static("text/plain")); /// assert!(removed.is_empty()); /// /// let removed = map.insert(header::ACCEPT, HeaderValue::from_static("text/html")); /// assert!(!removed.is_empty()); /// ``` pub fn insert(&mut self, 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 associated with the key. The key is not updated; this matters for types that can /// be `==` without being identical. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// map.append(header::HOST, HeaderValue::from_static("example.com")); /// assert_eq!(map.len(), 1); /// /// map.append(header::ACCEPT, HeaderValue::from_static("text/csv")); /// assert_eq!(map.len(), 2); /// /// map.append(header::ACCEPT, HeaderValue::from_static("text/html")); /// assert_eq!(map.len(), 3); /// ``` pub fn append(&mut self, key: HeaderName, value: HeaderValue) { match self.inner.entry(key) { hash_map::Entry::Occupied(mut entry) => { entry.get_mut().append(value); } hash_map::Entry::Vacant(entry) => { entry.insert(Value::one(value)); } }; } /// Removes all headers for a particular header name from the map. /// /// Providing an invalid header names (as a string argument) will have no effect and return /// without error. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// map.append(header::SET_COOKIE, HeaderValue::from_static("one=1")); /// map.append(header::SET_COOKIE, HeaderValue::from_static("one=2")); /// /// assert_eq!(map.len(), 2); /// /// let mut removed = map.remove(header::SET_COOKIE); /// assert_eq!(removed.next().unwrap(), "one=1"); /// assert_eq!(removed.next().unwrap(), "one=2"); /// assert!(removed.next().is_none()); /// /// assert!(map.is_empty()); /// ``` /// /// 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"); /// assert!(removed.is_empty()); /// /// map.insert(header::ACCEPT, HeaderValue::from_static("text/html")); /// let removed = map.remove("accept"); /// assert!(!removed.is_empty()); /// ``` pub fn remove(&mut self, key: impl AsHeaderName) -> Removed { let value = match key.try_as_name(super::as_name::Seal) { Ok(Cow::Borrowed(name)) => self.inner.remove(name), Ok(Cow::Owned(name)) => self.inner.remove(&name), Err(_) => None, }; Removed::new(value) } /// Returns the number of single-value headers the map can hold without needing to reallocate. /// /// Since this is a multi-value map, the actual capacity is much larger when considering /// each header name can be associated with an arbitrary number of values. The effect is that /// the size of `len` may be greater than `capacity` since it counts all the values. /// Conversely, [`len_keys`](Self::len_keys) will never be larger than capacity. /// /// # Examples /// ``` /// # use actix_http::header::HeaderMap; /// let map = HeaderMap::with_capacity(16); /// /// assert!(map.is_empty()); /// assert!(map.capacity() >= 16); /// ``` pub fn capacity(&self) -> usize { self.inner.capacity() } /// Reserves capacity for at least `additional` more headers to be inserted in the map. /// /// The header map may reserve more space to avoid frequent reallocations. Additional capacity /// only considers single-value headers. /// /// # Panics /// Panics if the new allocation size overflows usize. /// /// # Examples /// ``` /// # use actix_http::header::HeaderMap; /// let mut map = HeaderMap::with_capacity(2); /// assert!(map.capacity() >= 2); /// /// map.reserve(100); /// assert!(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 values, it /// will be yielded 3 times. The iteration order should be considered arbitrary. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// let mut iter = map.iter(); /// assert!(iter.next().is_none()); /// /// map.append(header::HOST, HeaderValue::from_static("duck.com")); /// map.append(header::SET_COOKIE, HeaderValue::from_static("one=1")); /// map.append(header::SET_COOKIE, HeaderValue::from_static("two=2")); /// /// let mut iter = map.iter(); /// assert!(iter.next().is_some()); /// assert!(iter.next().is_some()); /// assert!(iter.next().is_some()); /// assert!(iter.next().is_none()); /// /// let pairs = map.iter().collect::<Vec<_>>(); /// assert!(pairs.contains(&(&header::HOST, &HeaderValue::from_static("duck.com")))); /// assert!(pairs.contains(&(&header::SET_COOKIE, &HeaderValue::from_static("one=1")))); /// assert!(pairs.contains(&(&header::SET_COOKIE, &HeaderValue::from_static("two=2")))); /// ``` pub fn iter(&self) -> Iter<'_> { Iter::new(self.inner.iter()) } /// An iterator over all contained header names. /// /// Each name will only be yielded once even if it has multiple associated values. The iteration /// order should be considered arbitrary. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// let mut iter = map.keys(); /// assert!(iter.next().is_none()); /// /// map.append(header::HOST, HeaderValue::from_static("duck.com")); /// map.append(header::SET_COOKIE, HeaderValue::from_static("one=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) -> Keys<'_> { Keys(self.inner.keys()) } /// Retains only the headers specified by the predicate. /// /// In other words, removes all headers `(name, val)` for which `retain_fn(&name, &mut val)` /// returns false. /// /// The order in which headers are visited should be considered arbitrary. /// /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// map.append(header::HOST, HeaderValue::from_static("duck.com")); /// map.append(header::SET_COOKIE, HeaderValue::from_static("one=1")); /// map.append(header::SET_COOKIE, HeaderValue::from_static("two=2")); /// /// map.retain(|name, val| val.as_bytes().starts_with(b"one")); /// /// assert_eq!(map.len(), 1); /// assert!(map.contains_key(&header::SET_COOKIE)); /// ``` pub fn retain<F>(&mut self, mut retain_fn: F) where F: FnMut(&HeaderName, &mut HeaderValue) -> bool, { self.inner.retain(|name, vals| { vals.inner.retain(|val| retain_fn(name, val)); // invariant: make sure newly empty value lists are removed !vals.is_empty() }) } /// Clears the map, returning all name-value sets as an iterator. /// /// Header names will only be yielded for the first value in each set. All items that are /// yielded without a name and after an item with a name are associated with that same name. /// The first item will always contain a name. /// /// Keeps the allocated memory for reuse. /// # Examples /// ``` /// # use actix_http::header::{self, HeaderMap, HeaderValue}; /// let mut map = HeaderMap::new(); /// /// let 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().unwrap(), (Some(header::SET_COOKIE), HeaderValue::from_static("one=1"))); /// assert_eq!(iter.next().unwrap(), (None, HeaderValue::from_static("two=2"))); /// drop(iter); /// /// assert!(map.is_empty()); /// ``` pub fn drain(&mut self) -> Drain<'_> { Drain::new(self.inner.drain()) } } /// Note that this implementation will clone a [HeaderName] for each value. Consider using /// [`drain`](Self::drain) to control header name cloning. impl IntoIterator for HeaderMap { type Item = (HeaderName, HeaderValue); type IntoIter = IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { IntoIter::new(self.inner.into_iter()) } } impl<'a> IntoIterator for &'a HeaderMap { type Item = (&'a HeaderName, &'a HeaderValue); type IntoIter = Iter<'a>; #[inline] fn into_iter(self) -> Self::IntoIter { Iter::new(self.inner.iter()) } } impl FromIterator<(HeaderName, HeaderValue)> for HeaderMap { fn from_iter<T: IntoIterator<Item = (HeaderName, HeaderValue)>>(iter: T) -> Self { iter.into_iter() .fold(Self::new(), |mut map, (name, value)| { map.append(name, value); map }) } } /// Convert a `http::HeaderMap` to our `HeaderMap`. impl From<http::HeaderMap> for HeaderMap { fn from(mut map: http::HeaderMap) -> Self { Self::from_drain(map.drain()) } } /// Convert our `HeaderMap` to a `http::HeaderMap`. impl From<HeaderMap> for http::HeaderMap { fn from(map: HeaderMap) -> Self { Self::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 replace items. See [`HeaderMap::insert`] /// and [`HeaderMap::remove`]. #[derive(Debug)] pub struct Removed { inner: Option<smallvec::IntoIter<[HeaderValue; 4]>>, } impl Removed { fn new(value: Option<Value>) -> Self { let inner = value.map(|value| value.inner.into_iter()); Self { inner } } /// Returns true if iterator contains no elements, without consuming it. /// /// If called immediately after [`HeaderMap::insert`] or [`HeaderMap::remove`], it will indicate /// whether any items were actually replaced or removed, respectively. pub fn is_empty(&self) -> bool { match self.inner { // size hint lower bound of smallvec is the correct length Some(ref iter) => iter.size_hint().0 == 0, None => true, } } } impl Iterator for Removed { type Item = HeaderValue; #[inline] fn next(&mut self) -> Option<Self::Item> { self.inner.as_mut()?.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { match self.inner { Some(ref iter) => iter.size_hint(), None => (0, None), } } } impl ExactSizeIterator for Removed {} impl iter::FusedIterator for Removed {} /// Iterator over all names in the map. #[derive(Debug)] pub struct Keys<'a>(hash_map::Keys<'a, HeaderName, Value>); impl<'a> Iterator for Keys<'a> { type Item = &'a HeaderName; #[inline] fn next(&mut self) -> Option<Self::Item> { self.0.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() } } impl ExactSizeIterator for Keys<'_> {} impl iter::FusedIterator for Keys<'_> {} /// Iterator over borrowed name-value pairs. #[derive(Debug)] pub struct Iter<'a> { inner: hash_map::Iter<'a, HeaderName, Value>, multi_inner: Option<(&'a HeaderName, &'a SmallVec<[HeaderValue; 4]>)>, multi_idx: usize, } impl<'a> Iter<'a> { fn new(iter: hash_map::Iter<'a, HeaderName, Value>) -> Self { Self { inner: iter, multi_idx: 0, multi_inner: None, } } } impl<'a> Iterator for Iter<'a> { type Item = (&'a HeaderName, &'a HeaderValue); fn next(&mut self) -> Option<Self::Item> { // handle in-progress multi value lists first if let Some((name, ref mut vals)) = self.multi_inner { match vals.get(self.multi_idx) { Some(val) => { self.multi_idx += 1; return Some((name, val)); } None => { // no more items in value list; reset state self.multi_idx = 0; self.multi_inner = None; } } } let (name, value) = self.inner.next()?; // set up new inner iter and recurse into it self.multi_inner = Some((name, &value.inner)); self.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { // take inner lower bound // make no attempt at an upper bound (self.inner.size_hint().0, None) } } impl ExactSizeIterator for Iter<'_> {} impl iter::FusedIterator for Iter<'_> {} /// Iterator over drained name-value pairs. /// /// Iterator items are `(Option<HeaderName>, HeaderValue)` to avoid cloning. #[derive(Debug)] pub struct Drain<'a> { inner: hash_map::Drain<'a, HeaderName, Value>, multi_inner: Option<(Option<HeaderName>, SmallVec<[HeaderValue; 4]>)>, multi_idx: usize, } impl<'a> Drain<'a> { fn new(iter: hash_map::Drain<'a, HeaderName, Value>) -> Self { Self { inner: iter, multi_inner: None, multi_idx: 0, } } } impl Iterator for Drain<'_> { 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 return Some((name.take(), vals.remove(0))); } else { // no more items in value iterator; reset state self.multi_inner = None; self.multi_idx = 0; } } let (name, value) = self.inner.next()?; // set up new inner iter and recurse into it self.multi_inner = Some((Some(name), value.inner)); self.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { // take inner lower bound // make no attempt at an upper bound (self.inner.size_hint().0, None) } } impl ExactSizeIterator for Drain<'_> {} impl iter::FusedIterator for Drain<'_> {} /// Iterator over owned name-value pairs. /// /// Implementation necessarily clones header names for each value. #[derive(Debug)] pub struct IntoIter { inner: hash_map::IntoIter<HeaderName, Value>, multi_inner: Option<(HeaderName, smallvec::IntoIter<[HeaderValue; 4]>)>, } impl IntoIter { fn new(inner: hash_map::IntoIter<HeaderName, Value>) -> Self { Self { inner, multi_inner: None, } } } impl Iterator for IntoIter { type Item = (HeaderName, HeaderValue); fn next(&mut self) -> Option<Self::Item> { // handle in-progress multi value iterators first if let Some((ref name, ref mut vals)) = self.multi_inner { match vals.next() { Some(val) => { return Some((name.clone(), val)); } None => { // no more items in value iterator; reset state self.multi_inner = None; } } } let (name, value) = self.inner.next()?; // set up new inner iter and recurse into it self.multi_inner = Some((name, value.inner.into_iter())); self.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { // take inner lower bound // make no attempt at an upper bound (self.inner.size_hint().0, None) } } 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_impl_all!(HeaderMap: IntoIterator); assert_impl_all!(Keys<'_>: Iterator, ExactSizeIterator, FusedIterator); assert_impl_all!(std::slice::Iter<'_, HeaderValue>: Iterator, ExactSizeIterator, FusedIterator); assert_impl_all!(Removed: Iterator, ExactSizeIterator, FusedIterator); assert_impl_all!(Iter<'_>: Iterator, ExactSizeIterator, FusedIterator); assert_impl_all!(IntoIter: Iterator, ExactSizeIterator, FusedIterator); assert_impl_all!(Drain<'_>: Iterator, ExactSizeIterator, FusedIterator); #[test] fn create() { let map = HeaderMap::new(); assert_eq!(map.len(), 0); assert_eq!(map.capacity(), 0); let map = HeaderMap::with_capacity(16); assert_eq!(map.len(), 0); assert!(map.capacity() >= 16); } #[test] fn insert() { let mut map = HeaderMap::new(); map.insert(header::LOCATION, HeaderValue::from_static("/test")); assert_eq!(map.len(), 1); } #[test] fn contains() { let mut map = HeaderMap::new(); assert!(!map.contains_key(header::LOCATION)); map.insert(header::LOCATION, HeaderValue::from_static("/test")); assert!(map.contains_key(header::LOCATION)); assert!(map.contains_key("Location")); assert!(map.contains_key("Location".to_owned())); assert!(map.contains_key("location")); } #[test] fn entries_iter() { 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")); let mut iter = map.iter(); assert!(iter.next().is_some()); assert!(iter.next().is_some()); assert!(iter.next().is_some()); assert!(iter.next().is_none()); let pairs = map.iter().collect::<Vec<_>>(); assert!(pairs.contains(&(&header::HOST, &HeaderValue::from_static("duck.com")))); assert!(pairs.contains(&(&header::COOKIE, &HeaderValue::from_static("one=1")))); assert!(pairs.contains(&(&header::COOKIE, &HeaderValue::from_static("two=2")))); } #[test] fn drain_iter() { let mut map = HeaderMap::new(); map.append(header::COOKIE, HeaderValue::from_static("one=1")); map.append(header::COOKIE, HeaderValue::from_static("two=2")); let mut vals = vec![]; let mut iter = map.drain(); let (name, val) = iter.next().unwrap(); assert_eq!(name, Some(header::COOKIE)); vals.push(val); let (name, val) = iter.next().unwrap(); assert!(name.is_none()); vals.push(val); assert!(vals.contains(&HeaderValue::from_static("one=1"))); assert!(vals.contains(&HeaderValue::from_static("two=2"))); assert!(iter.next().is_none()); 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, HeaderValue::from_static("one=1")); map.append(header::COOKIE, HeaderValue::from_static("two=2")); assert_eq!(map.len(), 4); // by value map.retain(|_, val| !val.as_bytes().contains(&b'/')); assert_eq!(map.len(), 3); // by name map.retain(|name, _| name.as_str() != "cookie"); assert_eq!(map.len(), 1); // keep but mutate value map.retain(|_, val| { *val = HeaderValue::from_static("replaced"); true }); assert_eq!(map.len(), 1); assert_eq!(map.get("host").unwrap(), "replaced"); } #[test] fn retain_removes_empty_value_lists() { let mut map = HeaderMap::with_capacity(3); map.append(header::HOST, HeaderValue::from_static("duck.com")); map.append(header::HOST, HeaderValue::from_static("duck.com")); assert_eq!(map.len(), 2); assert_eq!(map.len_keys(), 1); assert_eq!(map.inner.len(), 1); assert_eq!(map.capacity(), 3); // remove everything map.retain(|_n, _v| false); assert_eq!(map.len(), 0); assert_eq!(map.len_keys(), 0); assert_eq!(map.inner.len(), 0); assert_eq!(map.capacity(), 3); } #[test] fn entries_into_iter() { 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")); let mut iter = map.into_iter(); assert!(iter.next().is_some()); assert!(iter.next().is_some()); assert!(iter.next().is_some()); assert!(iter.next().is_none()); } #[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")); let mut iter = map.iter(); let mut into_iter = map.clone().into_iter(); assert_eq!(iter.next().map(owned_pair), into_iter.next()); assert_eq!(iter.next().map(owned_pair), into_iter.next()); assert_eq!(iter.next().map(owned_pair), into_iter.next()); assert_eq!(iter.next().map(owned_pair), into_iter.next()); } #[test] fn get_all_and_remove_same_order() { let mut map = HeaderMap::new(); map.append(header::COOKIE, HeaderValue::from_static("one=1")); map.append(header::COOKIE, HeaderValue::from_static("two=2")); let mut vals = map.get_all(header::COOKIE); let mut removed = map.clone().remove(header::COOKIE); assert_eq!(vals.next(), removed.next().as_ref()); assert_eq!(vals.next(), removed.next().as_ref()); assert_eq!(vals.next(), removed.next().as_ref()); } #[test] fn get_all_iteration_order_matches_insertion_order() { let mut map = HeaderMap::new(); let mut vals = map.get_all(header::COOKIE); assert!(vals.next().is_none()); map.append(header::COOKIE, HeaderValue::from_static("1")); let mut vals = map.get_all(header::COOKIE); assert_eq!(vals.next().unwrap().as_bytes(), b"1"); assert!(vals.next().is_none()); map.append(header::COOKIE, HeaderValue::from_static("2")); let mut vals = map.get_all(header::COOKIE); assert_eq!(vals.next().unwrap().as_bytes(), b"1"); assert_eq!(vals.next().unwrap().as_bytes(), b"2"); assert!(vals.next().is_none()); map.append(header::COOKIE, HeaderValue::from_static("3")); map.append(header::COOKIE, HeaderValue::from_static("4")); map.append(header::COOKIE, HeaderValue::from_static("5")); let mut vals = map.get_all(header::COOKIE); assert_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()); let _ = map.insert(header::COOKIE, HeaderValue::from_static("6")); let mut vals = map.get_all(header::COOKIE); assert_eq!(vals.next().unwrap().as_bytes(), b"6"); assert!(vals.next().is_none()); let _ = map.insert(header::COOKIE, HeaderValue::from_static("7")); let _ = map.insert(header::COOKIE, HeaderValue::from_static("8")); let mut vals = map.get_all(header::COOKIE); assert_eq!(vals.next().unwrap().as_bytes(), b"8"); assert!(vals.next().is_none()); map.append(header::COOKIE, HeaderValue::from_static("9")); let mut vals = map.get_all(header::COOKIE); assert_eq!(vals.next().unwrap().as_bytes(), b"8"); assert_eq!(vals.next().unwrap().as_bytes(), b"9"); assert!(vals.next().is_none()); // check for fused-ness assert!(vals.next().is_none()); } fn owned_pair<'a>((name, val): (&'a HeaderName, &'a HeaderValue)) -> (HeaderName, HeaderValue) { (name.clone(), val.clone()) } }
//! Pre-defined `HeaderName`s, traits for parsing and conversion, and other header utility methods. // declaring new header consts will yield this error #![allow(clippy::declare_interior_mutable_const)] // re-export from http except header map related items pub use ::http::header::{ HeaderName, HeaderValue, InvalidHeaderName, InvalidHeaderValue, ToStrError, }; // re-export const header names, list is explicit so that any updates to `common` module do not // conflict with this set pub use ::http::header::{ ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCEPT_RANGES, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_MAX_AGE, ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, AGE, ALLOW, ALT_SVC, AUTHORIZATION, CACHE_CONTROL, CONNECTION, CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_LOCATION, CONTENT_RANGE, CONTENT_SECURITY_POLICY, CONTENT_SECURITY_POLICY_REPORT_ONLY, CONTENT_TYPE, COOKIE, DATE, DNT, ETAG, EXPECT, EXPIRES, FORWARDED, FROM, HOST, IF_MATCH, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, IF_UNMODIFIED_SINCE, LAST_MODIFIED, LINK, LOCATION, MAX_FORWARDS, ORIGIN, PRAGMA, PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, PUBLIC_KEY_PINS, PUBLIC_KEY_PINS_REPORT_ONLY, RANGE, REFERER, REFERRER_POLICY, REFRESH, RETRY_AFTER, SEC_WEBSOCKET_ACCEPT, 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, X_FRAME_OPTIONS, X_XSS_PROTECTION, }; use percent_encoding::{AsciiSet, CONTROLS}; use crate::{error::ParseError, HttpMessage}; mod as_name; mod common; mod into_pair; mod into_value; pub mod map; mod shared; mod utils; pub use self::{ as_name::AsHeaderName, // re-export list is explicit so that any updates to `http` do not conflict with this set common::{ CACHE_STATUS, CDN_CACHE_CONTROL, CLEAR_SITE_DATA, CROSS_ORIGIN_EMBEDDER_POLICY, CROSS_ORIGIN_OPENER_POLICY, CROSS_ORIGIN_RESOURCE_POLICY, PERMISSIONS_POLICY, X_FORWARDED_FOR, X_FORWARDED_HOST, X_FORWARDED_PROTO, }, into_pair::TryIntoHeaderPair, into_value::TryIntoHeaderValue, map::HeaderMap, shared::{ parse_extended_value, q, Charset, ContentEncoding, ExtendedValue, HttpDate, LanguageTag, Quality, QualityItem, }, utils::{fmt_comma_delimited, from_comma_delimited, from_one_raw_str, http_percent_encode}, }; /// An interface for types that already represent a valid header. pub trait Header: TryIntoHeaderValue { /// Returns the name of the header field. fn name() -> HeaderName; /// Parse the header from a HTTP message. fn parse<M: HttpMessage>(msg: &M) -> Result<Self, ParseError>; } /// This encode set is used for HTTP header values and is defined at /// <https://datatracker.ietf.org/doc/html/rfc5987#section-3.2>. pub(crate) const HTTP_VALUE: &AsciiSet = &CONTROLS .add(b' ') .add(b'"') .add(b'%') .add(b'\'') .add(b'(') .add(b')') .add(b'*') .add(b',') .add(b'/') .add(b':') .add(b';') .add(b'<') .add(b'-') .add(b'>') .add(b'?') .add(b'[') .add(b'\\') .add(b']') .add(b'{') .add(b'}');
use std::{fmt, str}; use self::Charset::*; /// A MIME character set. /// /// The string representation is normalized to upper case. /// /// See <http://www.iana.org/assignments/character-sets/character-sets.xhtml>. #[derive(Debug, Clone, PartialEq, Eq)] #[allow(non_camel_case_types)] pub enum Charset { /// US ASCII Us_Ascii, /// ISO-8859-1 Iso_8859_1, /// ISO-8859-2 Iso_8859_2, /// ISO-8859-3 Iso_8859_3, /// ISO-8859-4 Iso_8859_4, /// ISO-8859-5 Iso_8859_5, /// ISO-8859-6 Iso_8859_6, /// ISO-8859-7 Iso_8859_7, /// ISO-8859-8 Iso_8859_8, /// ISO-8859-9 Iso_8859_9, /// ISO-8859-10 Iso_8859_10, /// Shift_JIS Shift_Jis, /// EUC-JP Euc_Jp, /// ISO-2022-KR Iso_2022_Kr, /// EUC-KR Euc_Kr, /// ISO-2022-JP Iso_2022_Jp, /// ISO-2022-JP-2 Iso_2022_Jp_2, /// ISO-8859-6-E Iso_8859_6_E, /// ISO-8859-6-I Iso_8859_6_I, /// ISO-8859-8-E Iso_8859_8_E, /// ISO-8859-8-I Iso_8859_8_I, /// GB2312 Gb2312, /// Big5 Big5, /// KOI8-R Koi8_R, /// An arbitrary charset specified as a string Ext(String), } impl Charset { fn label(&self) -> &str { match *self { Us_Ascii => "US-ASCII", Iso_8859_1 => "ISO-8859-1", Iso_8859_2 => "ISO-8859-2", Iso_8859_3 => "ISO-8859-3", Iso_8859_4 => "ISO-8859-4", Iso_8859_5 => "ISO-8859-5", Iso_8859_6 => "ISO-8859-6", Iso_8859_7 => "ISO-8859-7", Iso_8859_8 => "ISO-8859-8", Iso_8859_9 => "ISO-8859-9", Iso_8859_10 => "ISO-8859-10", Shift_Jis => "Shift-JIS", Euc_Jp => "EUC-JP", Iso_2022_Kr => "ISO-2022-KR", Euc_Kr => "EUC-KR", Iso_2022_Jp => "ISO-2022-JP", Iso_2022_Jp_2 => "ISO-2022-JP-2", Iso_8859_6_E => "ISO-8859-6-E", Iso_8859_6_I => "ISO-8859-6-I", Iso_8859_8_E => "ISO-8859-8-E", Iso_8859_8_I => "ISO-8859-8-I", Gb2312 => "GB2312", Big5 => "Big5", Koi8_R => "KOI8-R", Ext(ref s) => s, } } } impl fmt::Display for Charset { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.label()) } } impl str::FromStr for Charset { type Err = crate::Error; fn from_str(s: &str) -> Result<Charset, crate::Error> { Ok(match s.to_ascii_uppercase().as_ref() { "US-ASCII" => Us_Ascii, "ISO-8859-1" => Iso_8859_1, "ISO-8859-2" => Iso_8859_2, "ISO-8859-3" => Iso_8859_3, "ISO-8859-4" => Iso_8859_4, "ISO-8859-5" => Iso_8859_5, "ISO-8859-6" => Iso_8859_6, "ISO-8859-7" => Iso_8859_7, "ISO-8859-8" => Iso_8859_8, "ISO-8859-9" => Iso_8859_9, "ISO-8859-10" => Iso_8859_10, "SHIFT-JIS" => Shift_Jis, "EUC-JP" => Euc_Jp, "ISO-2022-KR" => Iso_2022_Kr, "EUC-KR" => Euc_Kr, "ISO-2022-JP" => Iso_2022_Jp, "ISO-2022-JP-2" => Iso_2022_Jp_2, "ISO-8859-6-E" => Iso_8859_6_E, "ISO-8859-6-I" => Iso_8859_6_I, "ISO-8859-8-E" => Iso_8859_8_E, "ISO-8859-8-I" => Iso_8859_8_I, "GB2312" => Gb2312, "BIG5" => Big5, "KOI8-R" => Koi8_R, s => Ext(s.to_owned()), }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse() { assert_eq!(Us_Ascii, "us-ascii".parse().unwrap()); assert_eq!(Us_Ascii, "US-Ascii".parse().unwrap()); assert_eq!(Us_Ascii, "US-ASCII".parse().unwrap()); assert_eq!(Shift_Jis, "Shift-JIS".parse().unwrap()); assert_eq!(Ext("ABCD".to_owned()), "abcd".parse().unwrap()); } #[test] fn test_display() { assert_eq!("US-ASCII", format!("{}", Us_Ascii)); assert_eq!("ABCD", format!("{}", Ext("ABCD".to_owned()))); } }
use std::str::FromStr; use derive_more::{Display, Error}; use http::header::InvalidHeaderValue; use crate::{ error::ParseError, header::{self, from_one_raw_str, Header, HeaderName, HeaderValue, TryIntoHeaderValue}, HttpMessage, }; /// Error returned when a content encoding is unknown. #[derive(Debug, Display, Error)] #[display("unsupported content encoding")] pub struct ContentEncodingParseError; /// Represents a supported content encoding. /// /// Includes a commonly-used subset of media types appropriate for use as HTTP content encodings. /// See [IANA HTTP Content Coding Registry]. /// /// [IANA HTTP Content Coding Registry]: https://www.iana.org/assignments/http-parameters/http-parameters.xhtml #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ContentEncoding { /// Indicates the no-op identity encoding. /// /// I.e., no compression or modification. Identity, /// A format using the Brotli algorithm. Brotli, /// A format using the zlib structure with deflate algorithm. Deflate, /// 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", ContentEncoding::Deflate => "deflate", ContentEncoding::Zstd => "zstd", ContentEncoding::Identity => "identity", } } /// Convert content encoding to header value. #[inline] pub const fn to_header_value(self) -> HeaderValue { match self { ContentEncoding::Brotli => HeaderValue::from_static("br"), ContentEncoding::Gzip => HeaderValue::from_static("gzip"), ContentEncoding::Deflate => HeaderValue::from_static("deflate"), ContentEncoding::Zstd => HeaderValue::from_static("zstd"), ContentEncoding::Identity => HeaderValue::from_static("identity"), } } } impl Default for ContentEncoding { #[inline] fn default() -> Self { Self::Identity } } impl FromStr for ContentEncoding { type Err = ContentEncodingParseError; fn from_str(enc: &str) -> Result<Self, Self::Err> { let enc = enc.trim(); if enc.eq_ignore_ascii_case("br") { Ok(ContentEncoding::Brotli) } else if enc.eq_ignore_ascii_case("gzip") { Ok(ContentEncoding::Gzip) } else if enc.eq_ignore_ascii_case("deflate") { Ok(ContentEncoding::Deflate) } else if enc.eq_ignore_ascii_case("identity") { Ok(ContentEncoding::Identity) } else if enc.eq_ignore_ascii_case("zstd") { Ok(ContentEncoding::Zstd) } else { Err(ContentEncodingParseError) } } } impl TryFrom<&str> for ContentEncoding { type Error = ContentEncodingParseError; fn try_from(val: &str) -> Result<Self, Self::Error> { val.parse() } } impl TryIntoHeaderValue for ContentEncoding { type Error = InvalidHeaderValue; fn try_into_value(self) -> Result<http::HeaderValue, Self::Error> { Ok(HeaderValue::from_static(self.as_str())) } } impl Header for ContentEncoding { fn name() -> HeaderName { header::CONTENT_ENCODING } fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError> { from_one_raw_str(msg.headers().get(Self::name())) } }
//! Originally taken from `hyper::header::parsing`. use std::{fmt, str::FromStr}; use language_tags::LanguageTag; use crate::header::{Charset, HTTP_VALUE}; /// The value part of an extended parameter consisting of three parts: /// - The REQUIRED character set name (`charset`). /// - The OPTIONAL language information (`language_tag`). /// - A character sequence representing the actual value (`value`), separated by single quotes. /// /// It is defined in [RFC 5987 §3.2](https://datatracker.ietf.org/doc/html/rfc5987#section-3.2). #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExtendedValue { /// The character set that is used to encode the `value` to a string. pub charset: Charset, /// The human language details of the `value`, if available. pub language_tag: Option<LanguageTag>, /// The parameter value, as expressed in octets. pub value: Vec<u8>, } /// Parses extended header parameter values (`ext-value`), as defined /// in [RFC 5987 §3.2](https://datatracker.ietf.org/doc/html/rfc5987#section-3.2). /// /// Extended values are denoted by parameter names that end with `*`. /// /// ## ABNF /// /// ```plain /// ext-value = charset "'" [ language ] "'" value-chars /// ; like RFC 2231's <extended-initial-value> /// ; (see [RFC 2231 §7]) /// /// charset = "UTF-8" / "ISO-8859-1" / mime-charset /// /// mime-charset = 1*mime-charsetc /// mime-charsetc = ALPHA / DIGIT /// / "!" / "#" / "$" / "%" / "&" /// / "+" / "-" / "^" / "_" / "`" /// / "{" / "}" / "~" /// ; as <mime-charset> in [RFC 2978 §2.3] /// ; except that the single 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 = ALPHA / DIGIT /// / "!" / "#" / "$" / "&" / "+" / "-" / "." /// / "^" / "_" / "`" / "|" / "~" /// ; token except ( "*" / "'" / "%" ) /// ``` /// /// [RFC 2231 §7]: https://datatracker.ietf.org/doc/html/rfc2231#section-7 /// [RFC 2978 §2.3]: https://datatracker.ietf.org/doc/html/rfc2978#section-2.3 /// [RFC 3986 §2.1]: https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 pub fn parse_extended_value(val: &str) -> Result<ExtendedValue, crate::error::ParseError> { // Break into three pieces separated by the single-quote character let mut parts = val.splitn(3, '\''); // Interpret the first piece as a Charset let charset: Charset = match parts.next() { None => return Err(crate::error::ParseError::Header), Some(n) => FromStr::from_str(n).map_err(|_| crate::error::ParseError::Header)?, }; // Interpret the second piece as a language tag let language_tag: Option<LanguageTag> = match parts.next() { None => return Err(crate::error::ParseError::Header), Some("") => None, Some(s) => match s.parse() { Ok(lt) => Some(lt), Err(_) => return Err(crate::error::ParseError::Header), }, }; // Interpret the third piece as a sequence of value characters let value: Vec<u8> = match parts.next() { None => return Err(crate::error::ParseError::Header), Some(v) => percent_encoding::percent_decode(v.as_bytes()).collect(), }; Ok(ExtendedValue { charset, language_tag, value, }) } impl fmt::Display for 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 { write!(f, "{}''{}", self.charset, encoded_value) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_extended_value_with_encoding_and_language_tag() { let expected_language_tag = "en".parse::<LanguageTag>().unwrap(); // RFC 5987, Section 3.2.2 // Extended notation, using the Unicode character U+00A3 (POUND SIGN) let result = parse_extended_value("iso-8859-1'en'%A3%20rates"); assert!(result.is_ok()); let extended_value = result.unwrap(); assert_eq!(Charset::Iso_8859_1, extended_value.charset); assert!(extended_value.language_tag.is_some()); assert_eq!(expected_language_tag, extended_value.language_tag.unwrap()); assert_eq!( vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value ); } #[test] fn test_parse_extended_value_with_encoding() { // RFC 5987, Section 3.2.2 // Extended notation, using the Unicode characters U+00A3 (POUND SIGN) // and U+20AC (EURO SIGN) let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates"); assert!(result.is_ok()); let extended_value = result.unwrap(); assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset); assert!(extended_value.language_tag.is_none()); assert_eq!( vec![ 194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's', ], extended_value.value ); } #[test] fn test_parse_extended_value_missing_language_tag_and_encoding() { // 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!(result.is_err()); } #[test] fn test_parse_extended_value_partially_formatted_blank() { let result = parse_extended_value("blank second part'"); assert!(result.is_err()); } #[test] fn test_fmt_extended_value_with_encoding_and_language_tag() { let extended_value = ExtendedValue { charset: Charset::Iso_8859_1, language_tag: Some("en".parse().expect("Could not parse language tag")), value: vec![163, b' ', b'r', b'a', b't', b'e', b's'], }; assert_eq!("ISO-8859-1'en'%A3%20rates", format!("{}", extended_value)); } #[test] fn test_fmt_extended_value_with_encoding() { let extended_value = ExtendedValue { charset: Charset::Ext("UTF-8".to_string()), language_tag: None, value: vec![ 194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's', ], }; assert_eq!( "UTF-8''%C2%A3%20and%20%E2%82%AC%20rates", format!("{}", extended_value) ); } }
use std::{fmt, io::Write, str::FromStr, time::SystemTime}; use bytes::BytesMut; use http::header::{HeaderValue, InvalidHeaderValue}; use crate::{ date::DATE_VALUE_LENGTH, error::ParseError, header::TryIntoHeaderValue, helpers::MutWriter, }; /// A timestamp with HTTP-style formatting and parsing. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct HttpDate(SystemTime); impl FromStr for HttpDate { type Err = ParseError; fn from_str(s: &str) -> Result<HttpDate, 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(f) } } impl TryIntoHeaderValue for HttpDate { type Error = InvalidHeaderValue; fn try_into_value(self) -> Result<HeaderValue, Self::Error> { let mut buf = BytesMut::with_capacity(DATE_VALUE_LENGTH); let mut wrt = MutWriter(&mut buf); // unwrap: date output is known to be well formed and of known length write!(wrt, "{}", self).unwrap(); HeaderValue::from_maybe_shared(buf.split().freeze()) } } impl From<SystemTime> for HttpDate { fn from(sys_time: SystemTime) -> HttpDate { HttpDate(sys_time) } } impl From<HttpDate> for SystemTime { fn from(HttpDate(sys_time): HttpDate) -> SystemTime { sys_time } } #[cfg(test)] mod tests { use std::time::Duration; use super::*; #[test] fn date_header() { macro_rules! assert_parsed_date { ($case:expr, $exp:expr) => { assert_eq!($case.parse::<HttpDate>().unwrap(), $exp); }; } // 784198117 = SystemTime::from(datetime!(1994-11-07 08:48:37).assume_utc()).duration_since(SystemTime::UNIX_EPOCH)); let nov_07 = HttpDate(SystemTime::UNIX_EPOCH + Duration::from_secs(784198117)); assert_parsed_date!("Mon, 07 Nov 1994 08:48:37 GMT", nov_07); assert_parsed_date!("Monday, 07-Nov-94 08:48:37 GMT", nov_07); assert_parsed_date!("Mon Nov 7 08:48:37 1994", nov_07); assert!("this-is-no-date".parse::<HttpDate>().is_err()); } }
//! Originally taken from `hyper::header::shared`. pub use language_tags::LanguageTag; 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, };
use std::fmt; use derive_more::{Display, Error}; const MAX_QUALITY_INT: u16 = 1000; const MAX_QUALITY_FLOAT: f32 = 1.0; /// Represents a quality used in q-factor values. /// /// The default value is equivalent to `q=1.0` (the [max](Self::MAX) value). /// /// # Implementation notes /// The quality value is defined as a number between 0.0 and 1.0 with three decimal places. /// This means there are 1001 possible values. Since floating point numbers are not exact and the /// smallest floating point data type (`f32`) consumes four bytes, we use an `u16` value to store /// the quality internally. /// /// [RFC 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.001"); /// assert_eq!(Quality::ZERO.to_string(), "0"); /// ``` /// /// [RFC 7231 §5.3.1]: https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Quality(pub(super) u16); impl Quality { /// The maximum quality value, equivalent to `q=1.0`. pub const MAX: Quality = Quality(MAX_QUALITY_INT); /// The minimum, non-zero quality value, equivalent to `q=0.001`. pub const MIN: Quality = Quality(1); /// The zero quality value, equivalent to `q=0.0`. pub const ZERO: Quality = Quality(0); /// Converts a float in the range 0.0–1.0 to a `Quality`. /// /// Intentionally private. External uses should rely on the `TryFrom` impl. /// /// # Panics /// Panics in debug mode when value is not in the range 0.0 <= n <= 1.0. fn from_f32(value: f32) -> Self { // Check that `value` is within range should be done before calling this method. // Just in case, this debug_assert should catch if we were forgetful. debug_assert!( (0.0..=MAX_QUALITY_FLOAT).contains(&value), "q value must be between 0.0 and 1.0" ); Quality((value * MAX_QUALITY_INT as f32) as u16) } } /// The default value is [`Quality::MAX`]. impl Default for Quality { fn default() -> Quality { Quality::MAX } } impl fmt::Display for Quality { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::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. // In benchmarks it is twice as fast as approach using something like // `format!("{}").trim_end_matches('0')` for non-fast-path quality values. if x < 10 { // x in is range 1–9 f.write_str("00")?; // 0 is already handled so it's not possible to have a trailing 0 in this range // we can just write the integer itoa_fmt(f, x) } else if x < 100 { // x in is range 10–99 f.write_str("0")?; if x % 10 == 0 { // trailing 0, divide by 10 and write itoa_fmt(f, x / 10) } else { itoa_fmt(f, x) } } else { // x is in range 100–999 if x % 100 == 0 { // two trailing 0s, divide by 100 and write itoa_fmt(f, x / 100) } else if x % 10 == 0 { // one trailing 0, divide by 10 and write itoa_fmt(f, x / 10) } else { itoa_fmt(f, x) } } } } } } /// Write integer to a `fmt::Write`. pub fn itoa_fmt<W: fmt::Write, V: itoa::Integer>(mut wr: W, value: V) -> fmt::Result { let mut buf = itoa::Buffer::new(); wr.write_str(buf.format(value)) } #[derive(Debug, Clone, Display, Error)] #[display("quality out of bounds")] #[non_exhaustive] pub struct QualityOutOfBounds; impl TryFrom<f32> for Quality { type Error = QualityOutOfBounds; #[inline] fn try_from(value: f32) -> Result<Self, Self::Error> { if (0.0..=MAX_QUALITY_FLOAT).contains(&value) { Ok(Quality::from_f32(value)) } 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 /// ``` /// # use actix_http::header::{q, Quality}; /// let q1 = q(1.0); /// assert_eq!(q1, Quality::MAX); /// /// let q2 = q(0.001); /// assert_eq!(q2, Quality::MIN); /// /// let q3 = q(0.0); /// assert_eq!(q3, Quality::ZERO); /// /// let q4 = q(0.42); /// ``` /// /// An out-of-range `f32` quality will panic. /// ```should_panic /// # use actix_http::header::q; /// let _q2 = q(1.42); /// ``` #[inline] pub fn q<T>(quality: T) -> Quality where T: TryInto<Quality>, T::Error: fmt::Debug, { quality.try_into().expect("quality value was out of bounds") } #[cfg(test)] mod tests { use super::*; #[test] fn q_helper() { assert_eq!(q(0.5), Quality(500)); } #[test] fn display_output() { assert_eq!(Quality::ZERO.to_string(), "0"); assert_eq!(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.22"); assert_eq!(q(0.123).to_string(), "0.123"); assert_eq!(q(0.999).to_string(), "0.999"); for x in 0..=1000 { // if trailing zeroes are handled correctly, we would not expect the serialized length // to ever exceed "0." + 3 decimal places = 5 in length assert!(q(x as f32 / 1000.0).to_string().len() <= 5); } } #[test] #[should_panic] fn negative_quality() { q(-1.0); } #[test] #[should_panic] fn quality_out_of_bounds() { q(2.0); } }
use std::{cmp, fmt, str}; use super::Quality; use crate::error::ParseError; /// Represents an item with a quality value as defined /// in [RFC 7231 §5.3.1](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1). /// /// # Parsing and Formatting /// This wrapper be used to parse header value items that have a q-factor annotation as well as /// serialize items with a their q-factor. /// /// # Ordering /// Since this context of use for this type is header value items, ordering is defined for /// `QualityItem`s but _only_ considers the item's quality. Order of appearance should be used as /// the secondary sorting parameter; i.e., a stable sort over the quality values will produce a /// correctly sorted sequence. /// /// # Examples /// ``` /// # use actix_http::header::{QualityItem, q}; /// let q_item: QualityItem<String> = "hello;q=0.3".parse().unwrap(); /// assert_eq!(&q_item.item, "hello"); /// assert_eq!(q_item.quality, q(0.3)); /// /// // note that format is normalized compared to parsed item /// assert_eq!(q_item.to_string(), "hello; q=0.3"); /// /// // item with q=0.3 is greater than item with q=0.1 /// let q_item_fallback: QualityItem<String> = "abc;q=0.1".parse().unwrap(); /// assert!(q_item > q_item_fallback); /// ``` #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct QualityItem<T> { /// The wrapped contents of the field. pub item: T, /// The quality (client or server preference) for the value. pub 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 } } /// Constructs a new `QualityItem` from an item, using the maximum q-value. pub fn max(item: T) -> Self { Self::new(item, Quality::MAX) } /// Constructs a new `QualityItem` from an item, using the minimum, non-zero q-value. pub fn min(item: T) -> Self { Self::new(item, Quality::MIN) } /// Constructs a new `QualityItem` from an item, using zero q-value of zero. pub fn zero(item: T) -> Self { Self::new(item, Quality::ZERO) } } impl<T: PartialEq> PartialOrd for QualityItem<T> { fn partial_cmp(&self, other: &QualityItem<T>) -> Option<cmp::Ordering> { self.quality.partial_cmp(&other.quality) } } impl<T: fmt::Display> fmt::Display for QualityItem<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.item, f)?; match self.quality { // q-factor value is implied for max value Quality::MAX => Ok(()), // fast path for zero Quality::ZERO => f.write_str("; q=0"), // quality formatting is already using itoa q => write!(f, "; q={}", q), } } } impl<T: str::FromStr> str::FromStr for QualityItem<T> { type Err = ParseError; fn from_str(q_item_str: &str) -> Result<Self, Self::Err> { if !q_item_str.is_ascii() { return Err(ParseError::Header); } // set defaults used if quality-item parsing fails, i.e., item has no q attribute let mut raw_item = q_item_str; let mut quality = Quality::MAX; let parts = q_item_str .rsplit_once(';') .map(|(item, q_attr)| (item.trim(), q_attr.trim())); if let Some((val, q_attr)) = parts { // example for item with q-factor: // // gzip;q=0.65 // ^^^^ val // ^^^^^^ q_attr // ^^ q // ^^^^ q_val if q_attr.len() < 2 { // Can't possibly be an attribute since an attribute needs at least a name followed // by an equals sign. And bare identifiers are forbidden. return Err(ParseError::Header); } let q = &q_attr[0..2]; if q == "q=" || q == "Q=" { let q_val = &q_attr[2..]; if q_val.len() > 5 { // longer than 5 indicates an over-precise q-factor return Err(ParseError::Header); } let q_value = q_val.parse::<f32>().map_err(|_| ParseError::Header)?; let q_value = Quality::try_from(q_value).map_err(|_| ParseError::Header)?; quality = q_value; raw_item = val; } } let item = raw_item.parse::<T>().map_err(|_| ParseError::Header)?; Ok(QualityItem::new(item, quality)) } } #[cfg(test)] mod tests { use super::*; // copy of encoding from actix-web headers #[allow(clippy::enum_variant_names)] // allow Encoding prefix on EncodingExt #[derive(Debug, Clone, PartialEq, Eq)] pub enum Encoding { Chunked, Brotli, Gzip, Deflate, Compress, Identity, Trailers, EncodingExt(String), } impl fmt::Display for Encoding { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Encoding::*; f.write_str(match *self { Chunked => "chunked", Brotli => "br", Gzip => "gzip", Deflate => "deflate", Compress => "compress", Identity => "identity", Trailers => "trailers", EncodingExt(ref s) => s.as_ref(), }) } } impl str::FromStr for Encoding { type Err = crate::error::ParseError; fn from_str(s: &str) -> Result<Encoding, crate::error::ParseError> { use Encoding::*; match s { "chunked" => Ok(Chunked), "br" => Ok(Brotli), "deflate" => Ok(Deflate), "gzip" => Ok(Gzip), "compress" => Ok(Compress), "identity" => Ok(Identity), "trailers" => Ok(Trailers), _ => Ok(EncodingExt(s.to_owned())), } } } #[test] fn test_quality_item_fmt_q_1() { use Encoding::*; let x = QualityItem::max(Chunked); assert_eq!(format!("{}", x), "chunked"); } #[test] fn test_quality_item_fmt_q_0001() { use Encoding::*; let x = QualityItem::new(Chunked, Quality(1)); assert_eq!(format!("{}", x), "chunked; q=0.001"); } #[test] fn test_quality_item_fmt_q_05() { use Encoding::*; // Custom value let x = QualityItem { item: EncodingExt("identity".to_owned()), quality: Quality(500), }; assert_eq!(format!("{}", x), "identity; q=0.5"); } #[test] fn test_quality_item_fmt_q_0() { use Encoding::*; // Custom value let x = QualityItem { item: EncodingExt("identity".to_owned()), quality: Quality(0), }; assert_eq!(x.to_string(), "identity; q=0"); } #[test] fn test_quality_item_from_str1() { use Encoding::*; let x: Result<QualityItem<Encoding>, _> = "chunked".parse(); assert_eq!( x.unwrap(), QualityItem { item: Chunked, quality: Quality(1000), } ); } #[test] fn test_quality_item_from_str2() { use Encoding::*; let x: Result<QualityItem<Encoding>, _> = "chunked; q=1".parse(); assert_eq!( x.unwrap(), QualityItem { item: Chunked, quality: Quality(1000), } ); } #[test] fn test_quality_item_from_str3() { use Encoding::*; let x: Result<QualityItem<Encoding>, _> = "gzip; q=0.5".parse(); assert_eq!( x.unwrap(), QualityItem { item: Gzip, quality: Quality(500), } ); } #[test] fn test_quality_item_from_str4() { use Encoding::*; let x: Result<QualityItem<Encoding>, _> = "gzip; q=0.273".parse(); assert_eq!( x.unwrap(), QualityItem { item: Gzip, quality: Quality(273), } ); } #[test] fn test_quality_item_from_str5() { let x: Result<QualityItem<Encoding>, _> = "gzip; q=0.2739999".parse(); assert!(x.is_err()); } #[test] fn test_quality_item_from_str6() { let x: Result<QualityItem<Encoding>, _> = "gzip; q=2".parse(); assert!(x.is_err()); } #[test] fn test_quality_item_ordering() { let x: QualityItem<Encoding> = "gzip; q=0.5".parse().ok().unwrap(); let y: QualityItem<Encoding> = "gzip; q=0.273".parse().ok().unwrap(); let comparison_result: bool = x.gt(&y); assert!(comparison_result) } #[test] fn test_fuzzing_bugs() { assert!("99999;".parse::<QualityItem<String>>().is_err()); assert!("\x0d;;;=\u{d6aa}==".parse::<QualityItem<String>>().is_err()) } }
//! Header parsing utilities. use std::{fmt, str::FromStr}; use super::HeaderValue; use crate::{error::ParseError, header::HTTP_VALUE}; /// Reads a comma-delimited raw header into a Vec. #[inline] pub fn from_comma_delimited<'a, I, T>(all: I) -> Result<Vec<T>, ParseError> where I: Iterator<Item = &'a HeaderValue> + 'a, T: FromStr, { let size_guess = all.size_hint().1.unwrap_or(2); let mut result = Vec::with_capacity(size_guess); for h in all { let s = h.to_str().map_err(|_| ParseError::Header)?; result.extend( s.split(',') .filter_map(|x| match x.trim() { "" => None, y => Some(y), }) .filter_map(|x| x.trim().parse().ok()), ) } Ok(result) } /// Reads a single string when parsing a header. #[inline] pub fn from_one_raw_str<T: FromStr>(val: Option<&HeaderValue>) -> Result<T, ParseError> { if let Some(line) = val { let line = line.to_str().map_err(|_| ParseError::Header)?; if !line.is_empty() { return T::from_str(line).or(Err(ParseError::Header)); } } Err(ParseError::Header) } /// Format an array into a comma-delimited string. #[inline] pub fn fmt_comma_delimited<T>(f: &mut fmt::Formatter<'_>, parts: &[T]) -> fmt::Result where T: fmt::Display, { let mut iter = parts.iter(); if let Some(part) = iter.next() { fmt::Display::fmt(part, f)?; } for part in iter { f.write_str(", ")?; 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::Result { let encoded = percent_encoding::percent_encode(bytes, HTTP_VALUE); fmt::Display::fmt(&encoded, f) } #[cfg(test)] mod tests { use super::*; #[test] fn comma_delimited_parsing() { let headers = []; let res: Vec<usize> = from_comma_delimited(headers.iter()).unwrap(); assert_eq!(res, vec![0; 0]); let headers = [ HeaderValue::from_static("1, 2"), HeaderValue::from_static("3,4"), ]; let res: Vec<usize> = from_comma_delimited(headers.iter()).unwrap(); assert_eq!(res, vec![1, 2, 3, 4]); let headers = [ HeaderValue::from_static(""), HeaderValue::from_static(","), HeaderValue::from_static(" "), HeaderValue::from_static("1 ,"), HeaderValue::from_static(""), ]; let res: Vec<usize> = from_comma_delimited(headers.iter()).unwrap(); assert_eq!(res, vec![1]); } }
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(b"HTTP/1.1 "), Version::HTTP_10 => buf.put_slice(b"HTTP/1.0 "), Version::HTTP_09 => buf.put_slice(b"HTTP/0.9 "), _ => { // other HTTP version handlers do not use this method } } let d100 = (n / 100) as u8; let d10 = ((n / 10) % 10) as u8; let d1 = (n % 10) as u8; buf.put_u8(DIGITS_START + d100); buf.put_u8(DIGITS_START + d10); buf.put_u8(DIGITS_START + d1); // trailing space before reason buf.put_u8(b' '); } /// Write out content length header. /// /// Buffer must to contain enough space or be implicitly extendable. pub fn write_content_length<B: BufMut>(n: u64, buf: &mut B, camel_case: bool) { if n == 0 { if camel_case { buf.put_slice(b"\r\nContent-Length: 0\r\n"); } else { buf.put_slice(b"\r\ncontent-length: 0\r\n"); } return; } let mut buffer = itoa::Buffer::new(); if camel_case { buf.put_slice(b"\r\nContent-Length: "); } else { buf.put_slice(b"\r\ncontent-length: "); } buf.put_slice(buffer.format(n).as_bytes()); buf.put_slice(b"\r\n"); } /// An `io::Write`r that only requires mutable reference and assumes that there is space available /// in the buffer for every write operation or that it can be extended implicitly (like /// `bytes::BytesMut`, for example). /// /// This is slightly faster (~10%) than `bytes::buf::Writer` in such cases because it 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 self) -> io::Result<()> { Ok(()) } } #[cfg(test)] mod tests { use std::str::from_utf8; use bytes::BytesMut; use super::*; #[test] fn test_status_line() { let mut bytes = BytesMut::new(); bytes.reserve(50); write_status_line(Version::HTTP_11, 200, &mut bytes); assert_eq!(from_utf8(&bytes.split().freeze()).unwrap(), "HTTP/1.1 200 "); let mut bytes = BytesMut::new(); bytes.reserve(50); write_status_line(Version::HTTP_09, 404, &mut bytes); assert_eq!(from_utf8(&bytes.split().freeze()).unwrap(), "HTTP/0.9 404 "); let mut bytes = BytesMut::new(); bytes.reserve(50); write_status_line(Version::HTTP_09, 515, &mut bytes); assert_eq!(from_utf8(&bytes.split().freeze()).unwrap(), "HTTP/0.9 515 "); } #[test] fn test_write_content_length() { let mut bytes = BytesMut::new(); bytes.reserve(50); write_content_length(0, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 0\r\n"[..]); bytes.reserve(50); write_content_length(9, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 9\r\n"[..]); bytes.reserve(50); write_content_length(10, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 10\r\n"[..]); bytes.reserve(50); write_content_length(99, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 99\r\n"[..]); 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"[..]); bytes.reserve(50); write_content_length(998, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 998\r\n"[..]); bytes.reserve(50); write_content_length(1000, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 1000\r\n"[..]); bytes.reserve(50); write_content_length(1001, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 1001\r\n"[..]); bytes.reserve(50); write_content_length(5909, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 5909\r\n"[..]); bytes.reserve(50); write_content_length(9999, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 9999\r\n"[..]); bytes.reserve(50); write_content_length(10001, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 10001\r\n"[..]); bytes.reserve(50); write_content_length(59094, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 59094\r\n"[..]); bytes.reserve(50); write_content_length(99999, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 99999\r\n"[..]); bytes.reserve(50); write_content_length(590947, &mut bytes, false); assert_eq!( bytes.split().freeze(), b"\r\ncontent-length: 590947\r\n"[..] ); bytes.reserve(50); write_content_length(999999, &mut bytes, false); assert_eq!( bytes.split().freeze(), 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(59094718, &mut bytes, false); assert_eq!( bytes.split().freeze(), b"\r\ncontent-length: 59094718\r\n"[..] ); bytes.reserve(50); write_content_length(4294973728, &mut bytes, false); assert_eq!( bytes.split().freeze(), b"\r\ncontent-length: 4294973728\r\n"[..] ); } #[test] fn write_content_length_camel_case() { let mut bytes = BytesMut::new(); write_content_length(0, &mut bytes, false); assert_eq!(bytes.split().freeze(), b"\r\ncontent-length: 0\r\n"[..]); let mut bytes = BytesMut::new(); write_content_length(0, &mut bytes, true); assert_eq!(bytes.split().freeze(), b"\r\nContent-Length: 0\r\n"[..]); } }
use std::{ cell::{Ref, RefMut}, str, }; use encoding_rs::{Encoding, UTF_8}; use http::header; use mime::Mime; use crate::{ error::{ContentTypeError, ParseError}, header::{Header, HeaderMap}, payload::Payload, Extensions, }; /// Trait that implements general purpose operations on HTTP messages. pub trait HttpMessage: Sized { /// Type of message payload stream type Stream; /// Read the message headers. fn headers(&self) -> &HeaderMap; /// Message payload stream fn take_payload(&mut self) -> Payload<Self::Stream>; /// Returns a reference to the request-local data/extensions container. fn extensions(&self) -> Ref<'_, Extensions>; /// Returns a mutable reference to the request-local data/extensions container. fn extensions_mut(&self) -> RefMut<'_, Extensions>; /// Get a header. #[doc(hidden)] fn get_header<H: Header>(&self) -> Option<H> where Self: 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 { if let Some(content_type) = self.headers().get(header::CONTENT_TYPE) { if let Ok(content_type) = content_type.to_str() { return content_type.split(';').next().unwrap().trim(); } } "" } /// Get content type encoding. /// /// UTF-8 is used by default, If request charset is not set. fn encoding(&self) -> Result<&'static Encoding, ContentTypeError> { if let Some(mime_type) = self.mime_type()? { if let Some(charset) = mime_type.get_param("charset") { if let Some(enc) = Encoding::for_label_no_replacement(charset.as_str().as_bytes()) { Ok(enc) } else { Err(ContentTypeError::UnknownEncoding) } } else { Ok(UTF_8) } } else { Ok(UTF_8) } } /// Convert the request content type to a known mime type. fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError> { if let Some(content_type) = self.headers().get(header::CONTENT_TYPE) { if let Ok(content_type) = content_type.to_str() { return match content_type.parse() { Ok(mt) => Ok(Some(mt)), Err(_) => Err(ContentTypeError::ParseError), }; } else { return Err(ContentTypeError::ParseError); } } Ok(None) } /// Check if request has chunked transfer encoding. fn chunked(&self) -> Result<bool, ParseError> { if let Some(encodings) = self.headers().get(header::TRANSFER_ENCODING) { if let Ok(s) = encodings.to_str() { Ok(s.to_lowercase().contains("chunked")) } else { Err(ParseError::Header) } } else { Ok(false) } } } impl<T> HttpMessage for &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(&self) -> Ref<'_, Extensions> { (**self).extensions() } /// Mutable reference to a the request's extensions container fn extensions_mut(&self) -> RefMut<'_, Extensions> { (**self).extensions_mut() } } #[cfg(test)] mod tests { use bytes::Bytes; use encoding_rs::ISO_8859_2; use super::*; use crate::test::TestRequest; #[test] fn test_content_type() { let req = TestRequest::default() .insert_header(("content-type", "text/plain")) .finish(); assert_eq!(req.content_type(), "text/plain"); let req = TestRequest::default() .insert_header(("content-type", "application/json; charset=utf-8")) .finish(); assert_eq!(req.content_type(), "application/json"); let req = TestRequest::default().finish(); assert_eq!(req.content_type(), ""); } #[test] fn test_mime_type() { let req = TestRequest::default() .insert_header(("content-type", "application/json")) .finish(); assert_eq!(req.mime_type().unwrap(), Some(mime::APPLICATION_JSON)); let req = TestRequest::default().finish(); assert_eq!(req.mime_type().unwrap(), None); let req = TestRequest::default() .insert_header(("content-type", "application/json; charset=utf-8")) .finish(); let mt = req.mime_type().unwrap().unwrap(); assert_eq!(mt.get_param(mime::CHARSET), Some(mime::UTF_8)); assert_eq!(mt.type_(), mime::APPLICATION); assert_eq!(mt.subtype(), mime::JSON); } #[test] fn test_mime_type_error() { let req = TestRequest::default() .insert_header(("content-type", "applicationadfadsfasdflknadsfklnadsfjson")) .finish(); assert_eq!(Err(ContentTypeError::ParseError), req.mime_type()); } #[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.name(), req.encoding().unwrap().name()); let req = TestRequest::default() .insert_header(("content-type", "application/json; charset=ISO-8859-2")) .finish(); assert_eq!(ISO_8859_2, req.encoding().unwrap()); } #[test] fn test_encoding_error() { let req = TestRequest::default() .insert_header(("content-type", "applicatjson")) .finish(); assert_eq!(Some(ContentTypeError::ParseError), req.encoding().err()); let req = TestRequest::default() .insert_header(("content-type", "application/json; charset=kkkttktk")) .finish(); assert_eq!( Some(ContentTypeError::UnknownEncoding), req.encoding().err() ); } #[test] fn test_chunked() { let req = TestRequest::default().finish(); assert!(!req.chunked().unwrap()); let req = TestRequest::default() .insert_header((header::TRANSFER_ENCODING, "chunked")) .finish(); assert!(req.chunked().unwrap()); let req = TestRequest::default() .insert_header(( header::TRANSFER_ENCODING, Bytes::from_static(b"some va\xadscc\xacas0xsdasdlue"), )) .finish(); assert!(req.chunked().is_err()); } }
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 mapped to `KeepAlive::Disabled`. Timeout(Duration), /// Rely on OS to shutdown TCP connection. /// /// Some defaults can be very long, check your OS documentation. Os, /// Keep-alive is disabled. /// /// Connections will be closed immediately. Disabled, } impl KeepAlive { pub(crate) fn enabled(&self) -> bool { !matches!(self, Self::Disabled) } #[allow(unused)] // used with `http2` feature flag pub(crate) fn duration(&self) -> Option<Duration> { match self { KeepAlive::Timeout(dur) => Some(*dur), _ => None, } } /// Map zero duration to disabled. pub(crate) fn normalize(self) -> KeepAlive { match self { KeepAlive::Timeout(Duration::ZERO) => KeepAlive::Disabled, ka => ka, } } } impl Default for KeepAlive { fn default() -> Self { Self::Timeout(Duration::from_secs(5)) } } impl From<Duration> for KeepAlive { fn from(dur: Duration) -> Self { KeepAlive::Timeout(dur).normalize() } } impl From<Option<Duration>> for KeepAlive { fn from(ka_dur: Option<Duration>) -> Self { match ka_dur { Some(dur) => KeepAlive::from(dur), None => KeepAlive::Disabled, } .normalize() } } #[cfg(test)] mod tests { use super::*; #[test] fn from_impls() { let test: KeepAlive = Duration::from_secs(1).into(); assert_eq!(test, KeepAlive::Timeout(Duration::from_secs(1))); let test: KeepAlive = Duration::from_secs(0).into(); assert_eq!(test, KeepAlive::Disabled); let test: KeepAlive = Some(Duration::from_secs(0)).into(); assert_eq!(test, KeepAlive::Disabled); let test: KeepAlive = None.into(); assert_eq!(test, KeepAlive::Disabled); } }
//! HTTP types and services for the Actix ecosystem. //! //! ## Crate Features //! //! | Feature | Functionality | //! | ------------------- | ------------------------------------------- | //! | `http2` | HTTP/2 support via [h2]. | //! | `openssl` | TLS support via [OpenSSL]. | //! | `rustls-0_20` | TLS support via rustls 0.20. | //! | `rustls-0_21` | TLS support via rustls 0.21. | //! | `rustls-0_22` | TLS support via rustls 0.22. | //! | `rustls-0_23` | TLS support via [rustls] 0.23. | //! | `compress-brotli` | Payload compression support: Brotli. | //! | `compress-gzip` | Payload compression support: Deflate, Gzip. | //! | `compress-zstd` | Payload compression support: Zstd. | //! | `trust-dns` | Use [trust-dns] as the client DNS resolver. | //! //! [h2]: https://crates.io/crates/h2 //! [OpenSSL]: https://crates.io/crates/openssl //! [rustls]: https://crates.io/crates/rustls //! [trust-dns]: https://crates.io/crates/trust-dns #![allow( clippy::type_complexity, clippy::too_many_arguments, clippy::borrow_interior_mutable_const )] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_auto_cfg))] pub use http::{uri, uri::Uri, Method, StatusCode, Version}; pub mod body; mod builder; mod config; mod date; #[cfg(feature = "__compress")] pub mod encoding; pub mod error; mod extensions; pub mod h1; #[cfg(feature = "http2")] pub mod h2; pub mod header; mod helpers; mod http_message; mod keep_alive; mod message; #[cfg(test)] mod notify_on_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, error::Error, extensions::Extensions, header::ContentEncoding, http_message::HttpMessage, keep_alive::KeepAlive, message::{ConnectionType, Message}, payload::{BoxedPayloadStream, Payload}, requests::{Request, RequestHead, RequestHeadType}, responses::{Response, ResponseBuilder, ResponseHead}, service::HttpService, }; /// A major HTTP protocol version. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Protocol { Http1, Http2, Http3, } type ConnectCallback<IO> = dyn Fn(&IO, &mut Extensions); /// Container for data that extract with ConnectCallback. /// /// # Implementation Details /// Uses Option to reduce necessary allocations when merging with request extensions. #[derive(Default)] pub(crate) struct OnConnectData(Option<Extensions>); impl OnConnectData { /// Construct by calling the on-connect callback with the underlying transport I/O. pub(crate) fn from_io<T>(io: &T, on_connect_ext: Option<&ConnectCallback<T>>) -> Self { let ext = on_connect_ext.map(|handler| { let mut extensions = Extensions::default(); handler(io, &mut extensions); extensions }); Self(ext) } }
use std::{cell::RefCell, ops, rc::Rc}; use bitflags::bitflags; /// Represents various types of connection #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ConnectionType { /// Close connection after response. Close, /// Keep connection alive after response. KeepAlive, /// Connection is upgraded to different type. Upgrade, } bitflags! { #[derive(Debug, Clone, Copy)] pub(crate) struct Flags: u8 { const CLOSE = 0b0000_0001; const KEEP_ALIVE = 0b0000_0010; const UPGRADE = 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; } pub struct Message<T: Head> { /// Rc here should not be cloned by anyone. /// It's used to reuse allocation of T and no shared ownership is allowed. head: Rc<T>, } impl<T: Head> Message<T> { /// Get new message from the pool of objects #[allow(clippy::new_without_default)] pub fn new() -> Self { T::with_pool(MessagePool::get_message) } } impl<T: Head> ops::Deref for Message<T> { type Target = T; fn deref(&self) -> &Self::Target { self.head.as_ref() } } impl<T: Head> ops::DerefMut for Message<T> { fn deref_mut(&mut self) -> &mut Self::Target { Rc::get_mut(&mut self.head).expect("Multiple copies exist") } } impl<T: Head> Drop for Message<T> { fn drop(&mut self) { T::with_pool(|p| p.release(Rc::clone(&self.head))) } } /// Generic `Head` object pool. #[doc(hidden)] pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>); impl<T: Head> MessagePool<T> { pub(crate) fn create() -> MessagePool<T> { MessagePool(RefCell::new(Vec::with_capacity(128))) } /// Get message from the pool #[inline] fn get_message(&self) -> Message<T> { if let Some(mut msg) = self.0.borrow_mut().pop() { // Message is put in pool only when it's the last copy. // which means it's guaranteed to be unique when popped out. Rc::get_mut(&mut msg) .expect("Multiple copies exist") .clear(); Message { head: msg } } else { Message { 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); } } }
/// Test Module for checking the drop state of certain async tasks that are spawned /// with `actix_rt::spawn` /// /// The target task must explicitly generate `NotifyOnDrop` when spawn the task use std::cell::RefCell; thread_local! { static NOTIFY_DROPPED: RefCell<Option<bool>> = const { RefCell::new(None) }; } /// Check if the spawned task is dropped. /// /// # Panics /// Panics when there was no `NotifyOnDrop` instance on current thread. pub(crate) fn is_dropped() -> bool { NOTIFY_DROPPED.with(|bool| { bool.borrow() .expect("No NotifyOnDrop existed on current thread") }) } pub(crate) struct NotifyOnDrop; impl NotifyOnDrop { /// # Panics /// Panics hen construct multiple instances on any given thread. pub(crate) fn new() -> Self { NOTIFY_DROPPED.with(|bool| { let mut bool = bool.borrow_mut(); if bool.is_some() { panic!("NotifyOnDrop existed on current thread"); } else { *bool = Some(false); } }); NotifyOnDrop } } impl Drop for NotifyOnDrop { fn drop(&mut self) { NOTIFY_DROPPED.with(|bool| { if let Some(b) = bool.borrow_mut().as_mut() { *b = true; } }); } }
use std::{ mem, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use futures_core::Stream; use pin_project_lite::pin_project; use crate::error::PayloadError; /// A boxed payload stream. pub type BoxedPayloadStream = Pin<Box<dyn Stream<Item = Result<Bytes, PayloadError>>>>; #[doc(hidden)] #[deprecated(since = "3.0.0", note = "Renamed to `BoxedPayloadStream`.")] 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(feature = "http2")] pin_project! { /// A streaming payload. #[project = PayloadProj] pub enum Payload<S = BoxedPayloadStream> { None, H1 { payload: crate::h1::Payload }, H2 { payload: crate::h2::Payload }, Stream { #[pin] payload: S }, } } impl<S> From<crate::h1::Payload> for Payload<S> { #[inline] fn from(payload: crate::h1::Payload) -> Self { Payload::H1 { payload } } } impl<S> From<Bytes> for Payload<S> { #[inline] fn from(bytes: Bytes) -> Self { let (_, mut pl) = crate::h1::Payload::create(true); pl.unread_data(bytes); self::Payload::from(pl) } } impl<S> From<Vec<u8>> for Payload<S> { #[inline] fn from(vec: Vec<u8>) -> Self { Payload::from(Bytes::from(vec)) } } #[cfg(feature = "http2")] impl<S> From<crate::h2::Payload> for Payload<S> { #[inline] fn from(payload: crate::h2::Payload) -> Self { Payload::H2 { payload } } } #[cfg(feature = "http2")] impl<S> From<::h2::RecvStream> for Payload<S> { #[inline] fn from(stream: ::h2::RecvStream) -> Self { Payload::H2 { payload: crate::h2::Payload::new(stream), } } } impl From<BoxedPayloadStream> for Payload { #[inline] fn from(payload: BoxedPayloadStream) -> Self { Payload::Stream { payload } } } impl<S> Payload<S> { /// Takes current payload and replaces it with `None` value. #[must_use] pub fn take(&mut self) -> Payload<S> { mem::replace(self, 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::None => Poll::Ready(None), PayloadProj::H1 { payload } => Pin::new(payload).poll_next(cx), #[cfg(feature = "http2")] PayloadProj::H2 { payload } => Pin::new(payload).poll_next(cx), PayloadProj::Stream { payload } => payload.poll_next(cx), } } } #[cfg(test)] mod tests { use static_assertions::{assert_impl_all, assert_not_impl_any}; use super::*; assert_impl_all!(Payload: Unpin); assert_not_impl_any!(Payload: Send, Sync); }
use std::{net, rc::Rc}; use crate::{ header::{self, HeaderMap}, message::{Flags, Head, MessagePool}, ConnectionType, Method, Uri, Version, }; thread_local! { static REQUEST_POOL: MessagePool<RequestHead> = MessagePool::<RequestHead>::create() } #[derive(Debug, Clone)] pub struct RequestHead { pub method: Method, pub uri: Uri, pub version: Version, pub headers: HeaderMap, /// Will only be None when called in unit tests unless set manually. pub peer_addr: Option<net::SocketAddr>, flags: Flags, } impl Default for RequestHead { fn default() -> RequestHead { RequestHead { method: Method::default(), uri: Uri::default(), version: Version::HTTP_11, headers: HeaderMap::with_capacity(16), peer_addr: None, flags: Flags::empty(), } } } impl Head for RequestHead { fn clear(&mut self) { self.flags = Flags::empty(); self.headers.clear(); } fn with_pool<F, R>(f: F) -> R where F: FnOnce(&MessagePool<Self>) -> R, { REQUEST_POOL.with(|p| f(p)) } } impl RequestHead { /// Read the 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 } /// Is to uppercase headers with Camel-Case. /// Default is `false` #[inline] pub fn camel_case_headers(&self) -> bool { self.flags.contains(Flags::CAMEL_CASE) } /// Set `true` to send headers which are formatted as Camel-Case. #[inline] pub fn set_camel_case_headers(&mut self, val: bool) { if val { self.flags.insert(Flags::CAMEL_CASE); } else { self.flags.remove(Flags::CAMEL_CASE); } } #[inline] /// Set connection type of the message pub fn set_connection_type(&mut self, ctype: ConnectionType) { match ctype { ConnectionType::Close => self.flags.insert(Flags::CLOSE), ConnectionType::KeepAlive => self.flags.insert(Flags::KEEP_ALIVE), ConnectionType::Upgrade => self.flags.insert(Flags::UPGRADE), } } #[inline] /// Connection type pub fn connection_type(&self) -> ConnectionType { if self.flags.contains(Flags::CLOSE) { ConnectionType::Close } else if self.flags.contains(Flags::KEEP_ALIVE) { ConnectionType::KeepAlive } else if self.flags.contains(Flags::UPGRADE) { ConnectionType::Upgrade } else if self.version < Version::HTTP_11 { ConnectionType::Close } else { ConnectionType::KeepAlive } } /// Connection upgrade status pub fn upgrade(&self) -> bool { self.headers() .get(header::CONNECTION) .map(|hdr| { if let Ok(s) = hdr.to_str() { s.to_ascii_lowercase().contains("upgrade") } else { false } }) .unwrap_or(false) } #[inline] /// Get response body chunking state pub fn chunked(&self) -> bool { !self.flags.contains(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(&self) -> bool { self.flags.contains(Flags::EXPECT) } #[inline] pub(crate) fn set_expect(&mut self) { self.flags.insert(Flags::EXPECT); } } #[allow(clippy::large_enum_variant)] #[derive(Debug)] pub enum RequestHeadType { Owned(RequestHead), Rc(Rc<RequestHead>, Option<HeaderMap>), } impl RequestHeadType { pub fn extra_headers(&self) -> Option<&HeaderMap> { match self { RequestHeadType::Owned(_) => None, RequestHeadType::Rc(_, headers) => headers.as_ref(), } } } impl AsRef<RequestHead> for RequestHeadType { fn as_ref(&self) -> &RequestHead { match self { RequestHeadType::Owned(head) => head, RequestHeadType::Rc(head, _) => head.as_ref(), } } } impl From<RequestHead> for RequestHeadType { fn from(head: RequestHead) -> Self { RequestHeadType::Owned(head) } }
//! HTTP requests. mod head; mod request; pub use self::{ head::{RequestHead, RequestHeadType}, request::Request, };