file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
htmliframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLIFrameElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::document::AbstractDocument; use dom::element::HTMLIframeElementTypeId; use dom::htmlelement::HTMLElement; use dom::node::{AbstractNode, Node}; use dom::windowproxy::WindowProxy; use extra::url::Url; use servo_msg::constellation_msg::{PipelineId, SubpageId}; use std::ascii::StrAsciiExt; enum SandboxAllowance { AllowNothing = 0x00, AllowSameOrigin = 0x01, AllowTopNavigation = 0x02, AllowForms = 0x04, AllowScripts = 0x08, AllowPointerLock = 0x10, AllowPopups = 0x20 } pub struct HTMLIFrameElement { htmlelement: HTMLElement, frame: Option<Url>, size: Option<IFrameSize>, sandbox: Option<u8> } pub struct IFrameSize { pipeline_id: PipelineId, subpage_id: SubpageId, } impl HTMLIFrameElement { pub fn is_sandboxed(&self) -> bool { self.sandbox.is_some() } } impl HTMLIFrameElement { pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLIFrameElement { HTMLIFrameElement { htmlelement: HTMLElement::new_inherited(HTMLIframeElementTypeId, localName, document), frame: None, size: None, sandbox: None, } } pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode { let element = HTMLIFrameElement::new_inherited(localName, document); Node::reflect_node(@mut element, document, HTMLIFrameElementBinding::Wrap) } } impl HTMLIFrameElement { pub fn Src(&self) -> DOMString { ~"" } pub fn SetSrc(&mut self, _src: DOMString) -> ErrorResult { Ok(()) } pub fn Srcdoc(&self) -> DOMString { ~"" } pub fn SetSrcdoc(&mut self, _srcdoc: DOMString) -> ErrorResult
pub fn Name(&self) -> DOMString { ~"" } pub fn SetName(&mut self, _name: DOMString) -> ErrorResult { Ok(()) } pub fn Sandbox(&self, _abstract_self: AbstractNode) -> DOMString { match self.htmlelement.element.GetAttribute(~"sandbox") { Some(s) => s.to_owned(), None => ~"", } } pub fn SetSandbox(&mut self, abstract_self: AbstractNode, sandbox: DOMString) { self.htmlelement.element.SetAttribute(abstract_self, ~"sandbox", sandbox); } pub fn AfterSetAttr(&mut self, name: DOMString, value: DOMString) { if "sandbox" == name { let mut modes = AllowNothing as u8; for word in value.split_iter(' ') { // FIXME: Workaround for https://github.com/mozilla/rust/issues/10683 let word_lower = word.to_ascii_lower(); modes |= match word_lower.as_slice() { "allow-same-origin" => AllowSameOrigin, "allow-forms" => AllowForms, "allow-pointer-lock" => AllowPointerLock, "allow-popups" => AllowPopups, "allow-scripts" => AllowScripts, "allow-top-navigation" => AllowTopNavigation, _ => AllowNothing } as u8; } self.sandbox = Some(modes); } } pub fn AllowFullscreen(&self) -> bool { false } pub fn SetAllowFullscreen(&mut self, _allow: bool) -> ErrorResult { Ok(()) } pub fn Width(&self) -> DOMString { ~"" } pub fn SetWidth(&mut self, _width: DOMString) -> ErrorResult { Ok(()) } pub fn Height(&self) -> DOMString { ~"" } pub fn SetHeight(&mut self, _height: DOMString) -> ErrorResult { Ok(()) } pub fn GetContentDocument(&self) -> Option<AbstractDocument> { None } pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> { None } pub fn Align(&self) -> DOMString { ~"" } pub fn SetAlign(&mut self, _align: DOMString) -> ErrorResult { Ok(()) } pub fn Scrolling(&self) -> DOMString { ~"" } pub fn SetScrolling(&mut self, _scrolling: DOMString) -> ErrorResult { Ok(()) } pub fn FrameBorder(&self) -> DOMString { ~"" } pub fn SetFrameBorder(&mut self, _frameborder: DOMString) -> ErrorResult { Ok(()) } pub fn LongDesc(&self) -> DOMString { ~"" } pub fn SetLongDesc(&mut self, _longdesc: DOMString) -> ErrorResult { Ok(()) } pub fn MarginHeight(&self) -> DOMString { ~"" } pub fn SetMarginHeight(&mut self, _marginheight: DOMString) -> ErrorResult { Ok(()) } pub fn MarginWidth(&self) -> DOMString { ~"" } pub fn SetMarginWidth(&mut self, _marginwidth: DOMString) -> ErrorResult { Ok(()) } pub fn GetSVGDocument(&self) -> Option<AbstractDocument> { None } }
{ Ok(()) }
identifier_body
htmliframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLIFrameElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::document::AbstractDocument; use dom::element::HTMLIframeElementTypeId; use dom::htmlelement::HTMLElement; use dom::node::{AbstractNode, Node};
use dom::windowproxy::WindowProxy; use extra::url::Url; use servo_msg::constellation_msg::{PipelineId, SubpageId}; use std::ascii::StrAsciiExt; enum SandboxAllowance { AllowNothing = 0x00, AllowSameOrigin = 0x01, AllowTopNavigation = 0x02, AllowForms = 0x04, AllowScripts = 0x08, AllowPointerLock = 0x10, AllowPopups = 0x20 } pub struct HTMLIFrameElement { htmlelement: HTMLElement, frame: Option<Url>, size: Option<IFrameSize>, sandbox: Option<u8> } pub struct IFrameSize { pipeline_id: PipelineId, subpage_id: SubpageId, } impl HTMLIFrameElement { pub fn is_sandboxed(&self) -> bool { self.sandbox.is_some() } } impl HTMLIFrameElement { pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLIFrameElement { HTMLIFrameElement { htmlelement: HTMLElement::new_inherited(HTMLIframeElementTypeId, localName, document), frame: None, size: None, sandbox: None, } } pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode { let element = HTMLIFrameElement::new_inherited(localName, document); Node::reflect_node(@mut element, document, HTMLIFrameElementBinding::Wrap) } } impl HTMLIFrameElement { pub fn Src(&self) -> DOMString { ~"" } pub fn SetSrc(&mut self, _src: DOMString) -> ErrorResult { Ok(()) } pub fn Srcdoc(&self) -> DOMString { ~"" } pub fn SetSrcdoc(&mut self, _srcdoc: DOMString) -> ErrorResult { Ok(()) } pub fn Name(&self) -> DOMString { ~"" } pub fn SetName(&mut self, _name: DOMString) -> ErrorResult { Ok(()) } pub fn Sandbox(&self, _abstract_self: AbstractNode) -> DOMString { match self.htmlelement.element.GetAttribute(~"sandbox") { Some(s) => s.to_owned(), None => ~"", } } pub fn SetSandbox(&mut self, abstract_self: AbstractNode, sandbox: DOMString) { self.htmlelement.element.SetAttribute(abstract_self, ~"sandbox", sandbox); } pub fn AfterSetAttr(&mut self, name: DOMString, value: DOMString) { if "sandbox" == name { let mut modes = AllowNothing as u8; for word in value.split_iter(' ') { // FIXME: Workaround for https://github.com/mozilla/rust/issues/10683 let word_lower = word.to_ascii_lower(); modes |= match word_lower.as_slice() { "allow-same-origin" => AllowSameOrigin, "allow-forms" => AllowForms, "allow-pointer-lock" => AllowPointerLock, "allow-popups" => AllowPopups, "allow-scripts" => AllowScripts, "allow-top-navigation" => AllowTopNavigation, _ => AllowNothing } as u8; } self.sandbox = Some(modes); } } pub fn AllowFullscreen(&self) -> bool { false } pub fn SetAllowFullscreen(&mut self, _allow: bool) -> ErrorResult { Ok(()) } pub fn Width(&self) -> DOMString { ~"" } pub fn SetWidth(&mut self, _width: DOMString) -> ErrorResult { Ok(()) } pub fn Height(&self) -> DOMString { ~"" } pub fn SetHeight(&mut self, _height: DOMString) -> ErrorResult { Ok(()) } pub fn GetContentDocument(&self) -> Option<AbstractDocument> { None } pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> { None } pub fn Align(&self) -> DOMString { ~"" } pub fn SetAlign(&mut self, _align: DOMString) -> ErrorResult { Ok(()) } pub fn Scrolling(&self) -> DOMString { ~"" } pub fn SetScrolling(&mut self, _scrolling: DOMString) -> ErrorResult { Ok(()) } pub fn FrameBorder(&self) -> DOMString { ~"" } pub fn SetFrameBorder(&mut self, _frameborder: DOMString) -> ErrorResult { Ok(()) } pub fn LongDesc(&self) -> DOMString { ~"" } pub fn SetLongDesc(&mut self, _longdesc: DOMString) -> ErrorResult { Ok(()) } pub fn MarginHeight(&self) -> DOMString { ~"" } pub fn SetMarginHeight(&mut self, _marginheight: DOMString) -> ErrorResult { Ok(()) } pub fn MarginWidth(&self) -> DOMString { ~"" } pub fn SetMarginWidth(&mut self, _marginwidth: DOMString) -> ErrorResult { Ok(()) } pub fn GetSVGDocument(&self) -> Option<AbstractDocument> { None } }
random_line_split
htmliframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLIFrameElementBinding; use dom::bindings::utils::{DOMString, ErrorResult}; use dom::document::AbstractDocument; use dom::element::HTMLIframeElementTypeId; use dom::htmlelement::HTMLElement; use dom::node::{AbstractNode, Node}; use dom::windowproxy::WindowProxy; use extra::url::Url; use servo_msg::constellation_msg::{PipelineId, SubpageId}; use std::ascii::StrAsciiExt; enum SandboxAllowance { AllowNothing = 0x00, AllowSameOrigin = 0x01, AllowTopNavigation = 0x02, AllowForms = 0x04, AllowScripts = 0x08, AllowPointerLock = 0x10, AllowPopups = 0x20 } pub struct HTMLIFrameElement { htmlelement: HTMLElement, frame: Option<Url>, size: Option<IFrameSize>, sandbox: Option<u8> } pub struct IFrameSize { pipeline_id: PipelineId, subpage_id: SubpageId, } impl HTMLIFrameElement { pub fn is_sandboxed(&self) -> bool { self.sandbox.is_some() } } impl HTMLIFrameElement { pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLIFrameElement { HTMLIFrameElement { htmlelement: HTMLElement::new_inherited(HTMLIframeElementTypeId, localName, document), frame: None, size: None, sandbox: None, } } pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode { let element = HTMLIFrameElement::new_inherited(localName, document); Node::reflect_node(@mut element, document, HTMLIFrameElementBinding::Wrap) } } impl HTMLIFrameElement { pub fn Src(&self) -> DOMString { ~"" } pub fn SetSrc(&mut self, _src: DOMString) -> ErrorResult { Ok(()) } pub fn Srcdoc(&self) -> DOMString { ~"" } pub fn SetSrcdoc(&mut self, _srcdoc: DOMString) -> ErrorResult { Ok(()) } pub fn Name(&self) -> DOMString { ~"" } pub fn SetName(&mut self, _name: DOMString) -> ErrorResult { Ok(()) } pub fn Sandbox(&self, _abstract_self: AbstractNode) -> DOMString { match self.htmlelement.element.GetAttribute(~"sandbox") { Some(s) => s.to_owned(), None => ~"", } } pub fn SetSandbox(&mut self, abstract_self: AbstractNode, sandbox: DOMString) { self.htmlelement.element.SetAttribute(abstract_self, ~"sandbox", sandbox); } pub fn AfterSetAttr(&mut self, name: DOMString, value: DOMString) { if "sandbox" == name { let mut modes = AllowNothing as u8; for word in value.split_iter(' ') { // FIXME: Workaround for https://github.com/mozilla/rust/issues/10683 let word_lower = word.to_ascii_lower(); modes |= match word_lower.as_slice() { "allow-same-origin" => AllowSameOrigin, "allow-forms" => AllowForms, "allow-pointer-lock" => AllowPointerLock, "allow-popups" => AllowPopups, "allow-scripts" => AllowScripts, "allow-top-navigation" => AllowTopNavigation, _ => AllowNothing } as u8; } self.sandbox = Some(modes); } } pub fn AllowFullscreen(&self) -> bool { false } pub fn SetAllowFullscreen(&mut self, _allow: bool) -> ErrorResult { Ok(()) } pub fn Width(&self) -> DOMString { ~"" } pub fn SetWidth(&mut self, _width: DOMString) -> ErrorResult { Ok(()) } pub fn Height(&self) -> DOMString { ~"" } pub fn SetHeight(&mut self, _height: DOMString) -> ErrorResult { Ok(()) } pub fn GetContentDocument(&self) -> Option<AbstractDocument> { None } pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> { None } pub fn Align(&self) -> DOMString { ~"" } pub fn SetAlign(&mut self, _align: DOMString) -> ErrorResult { Ok(()) } pub fn Scrolling(&self) -> DOMString { ~"" } pub fn SetScrolling(&mut self, _scrolling: DOMString) -> ErrorResult { Ok(()) } pub fn FrameBorder(&self) -> DOMString { ~"" } pub fn SetFrameBorder(&mut self, _frameborder: DOMString) -> ErrorResult { Ok(()) } pub fn
(&self) -> DOMString { ~"" } pub fn SetLongDesc(&mut self, _longdesc: DOMString) -> ErrorResult { Ok(()) } pub fn MarginHeight(&self) -> DOMString { ~"" } pub fn SetMarginHeight(&mut self, _marginheight: DOMString) -> ErrorResult { Ok(()) } pub fn MarginWidth(&self) -> DOMString { ~"" } pub fn SetMarginWidth(&mut self, _marginwidth: DOMString) -> ErrorResult { Ok(()) } pub fn GetSVGDocument(&self) -> Option<AbstractDocument> { None } }
LongDesc
identifier_name
parse.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cg; use quote::Tokens; use syn::DeriveInput; use synstructure; use to_css::CssVariantAttrs; pub fn derive(input: DeriveInput) -> Tokens { let name = &input.ident; let mut match_body = quote! {}; let style = synstructure::BindStyle::Ref.into(); synstructure::each_variant(&input, &style, |bindings, variant| { assert!( bindings.is_empty(), "Parse is only supported for single-variant enums for now" ); let variant_attrs = cg::parse_variant_attrs::<CssVariantAttrs>(variant); let identifier = cg::to_css_identifier( &variant_attrs.keyword.as_ref().unwrap_or(&variant.ident).as_ref(), ); let ident = &variant.ident; match_body = quote! { #match_body #identifier => Ok(#name::#ident), }; let aliases = match variant_attrs.aliases { Some(aliases) => aliases, None => return, }; for alias in aliases.split(",") { match_body = quote! { #match_body #alias => Ok(#name::#ident), }; } }); let parse_trait_impl = quote! { impl ::parser::Parse for #name { #[inline] fn parse<'i, 't>( _: &::parser::ParserContext, input: &mut ::cssparser::Parser<'i, 't>, ) -> Result<Self, ::style_traits::ParseError<'i>> { Self::parse(input) } } }; // TODO(emilio): It'd be nice to get rid of these, but that makes the // conversion harder... let methods_impl = quote! { impl #name { /// Parse this keyword. #[inline] pub fn parse<'i, 't>( input: &mut ::cssparser::Parser<'i, 't>, ) -> Result<Self, ::style_traits::ParseError<'i>> { let location = input.current_source_location(); let ident = input.expect_ident()?; Self::from_ident(ident.as_ref()).map_err(|()| { location.new_unexpected_token_error( ::cssparser::Token::Ident(ident.clone()) ) })
} /// Parse this keyword from a string slice. #[inline] pub fn from_ident(ident: &str) -> Result<Self, ()> { match_ignore_ascii_case! { ident, #match_body _ => Err(()), } } } }; quote! { #parse_trait_impl #methods_impl } }
random_line_split
parse.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cg; use quote::Tokens; use syn::DeriveInput; use synstructure; use to_css::CssVariantAttrs; pub fn
(input: DeriveInput) -> Tokens { let name = &input.ident; let mut match_body = quote! {}; let style = synstructure::BindStyle::Ref.into(); synstructure::each_variant(&input, &style, |bindings, variant| { assert!( bindings.is_empty(), "Parse is only supported for single-variant enums for now" ); let variant_attrs = cg::parse_variant_attrs::<CssVariantAttrs>(variant); let identifier = cg::to_css_identifier( &variant_attrs.keyword.as_ref().unwrap_or(&variant.ident).as_ref(), ); let ident = &variant.ident; match_body = quote! { #match_body #identifier => Ok(#name::#ident), }; let aliases = match variant_attrs.aliases { Some(aliases) => aliases, None => return, }; for alias in aliases.split(",") { match_body = quote! { #match_body #alias => Ok(#name::#ident), }; } }); let parse_trait_impl = quote! { impl ::parser::Parse for #name { #[inline] fn parse<'i, 't>( _: &::parser::ParserContext, input: &mut ::cssparser::Parser<'i, 't>, ) -> Result<Self, ::style_traits::ParseError<'i>> { Self::parse(input) } } }; // TODO(emilio): It'd be nice to get rid of these, but that makes the // conversion harder... let methods_impl = quote! { impl #name { /// Parse this keyword. #[inline] pub fn parse<'i, 't>( input: &mut ::cssparser::Parser<'i, 't>, ) -> Result<Self, ::style_traits::ParseError<'i>> { let location = input.current_source_location(); let ident = input.expect_ident()?; Self::from_ident(ident.as_ref()).map_err(|()| { location.new_unexpected_token_error( ::cssparser::Token::Ident(ident.clone()) ) }) } /// Parse this keyword from a string slice. #[inline] pub fn from_ident(ident: &str) -> Result<Self, ()> { match_ignore_ascii_case! { ident, #match_body _ => Err(()), } } } }; quote! { #parse_trait_impl #methods_impl } }
derive
identifier_name
parse.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cg; use quote::Tokens; use syn::DeriveInput; use synstructure; use to_css::CssVariantAttrs; pub fn derive(input: DeriveInput) -> Tokens
#identifier => Ok(#name::#ident), }; let aliases = match variant_attrs.aliases { Some(aliases) => aliases, None => return, }; for alias in aliases.split(",") { match_body = quote! { #match_body #alias => Ok(#name::#ident), }; } }); let parse_trait_impl = quote! { impl ::parser::Parse for #name { #[inline] fn parse<'i, 't>( _: &::parser::ParserContext, input: &mut ::cssparser::Parser<'i, 't>, ) -> Result<Self, ::style_traits::ParseError<'i>> { Self::parse(input) } } }; // TODO(emilio): It'd be nice to get rid of these, but that makes the // conversion harder... let methods_impl = quote! { impl #name { /// Parse this keyword. #[inline] pub fn parse<'i, 't>( input: &mut ::cssparser::Parser<'i, 't>, ) -> Result<Self, ::style_traits::ParseError<'i>> { let location = input.current_source_location(); let ident = input.expect_ident()?; Self::from_ident(ident.as_ref()).map_err(|()| { location.new_unexpected_token_error( ::cssparser::Token::Ident(ident.clone()) ) }) } /// Parse this keyword from a string slice. #[inline] pub fn from_ident(ident: &str) -> Result<Self, ()> { match_ignore_ascii_case! { ident, #match_body _ => Err(()), } } } }; quote! { #parse_trait_impl #methods_impl } }
{ let name = &input.ident; let mut match_body = quote! {}; let style = synstructure::BindStyle::Ref.into(); synstructure::each_variant(&input, &style, |bindings, variant| { assert!( bindings.is_empty(), "Parse is only supported for single-variant enums for now" ); let variant_attrs = cg::parse_variant_attrs::<CssVariantAttrs>(variant); let identifier = cg::to_css_identifier( &variant_attrs.keyword.as_ref().unwrap_or(&variant.ident).as_ref(), ); let ident = &variant.ident; match_body = quote! { #match_body
identifier_body
main.rs
use PlanetaryMonster::MarsMonster; enum Compass { North, South, East, West
VenusMonster(species, i32), MarsMonster(species, i32) } fn main() { let direction = Compass::West; let martian = PlanetaryMonster::MarsMonster("Chela", 42); let martian = MarsMonster("Chela", 42); // using enum values: // error: binary operation `==` cannot be applied to type `Compass` // if direction == Compass::East { // println!("Go to the east"); // } match direction { Compass::North => println!("Go to the North!"), Compass::East => println!("Go to the East!"), Compass::South => println!("Go to the South!"), Compass::West => println!("Go to the West!"), } } // Go to the West!
} type species = &'static str; enum PlanetaryMonster {
random_line_split
main.rs
use PlanetaryMonster::MarsMonster; enum Compass { North, South, East, West } type species = &'static str; enum PlanetaryMonster { VenusMonster(species, i32), MarsMonster(species, i32) } fn
() { let direction = Compass::West; let martian = PlanetaryMonster::MarsMonster("Chela", 42); let martian = MarsMonster("Chela", 42); // using enum values: // error: binary operation `==` cannot be applied to type `Compass` // if direction == Compass::East { // println!("Go to the east"); // } match direction { Compass::North => println!("Go to the North!"), Compass::East => println!("Go to the East!"), Compass::South => println!("Go to the South!"), Compass::West => println!("Go to the West!"), } } // Go to the West!
main
identifier_name
parsing_quirks_test.rs
#[test] fn test_parsing_css() { let text = " div { font-weight: bold; } "; assert_template_result!(text, text); } #[test] fn test_raise_on_single_close_bracet() { assert_parse_error!("text {{method} oh nos!"); } #[test] fn test_raise_on_label_and_no_close_bracets() { assert_parse_error!("TEST {{ "); } #[test] fn
() { assert_parse_error!("TEST {% "); } #[test] fn test_error_on_empty_filter() { // Implementation specific: lax parser assert_parse_error!("{{|test}}"); assert_parse_error!("{{test |a|b|}}"); } #[test] fn test_meaningless_parens_error() { assert_parse_error!( "{% if a == 'foo' or (b == 'bar' and c == 'baz') or false %} YES {% endif %}", ); } #[test] fn test_unexpected_characters_syntax_error() { assert_parse_error!("{% if true && false %} YES {% endif %}"); assert_parse_error!("{% if false || true %} YES {% endif %}"); } #[test] #[should_panic] fn test_no_error_on_lax_empty_filter() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_meaningless_parens_lax() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_unexpected_characters_silently_eat_logic_lax() { panic!("Implementation specific: lax parser"); } #[test] fn test_raise_on_invalid_tag_delimiter() { assert_parse_error!("{% end %}"); } #[test] #[should_panic] fn test_unanchored_filter_arguments() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_invalid_variables_work() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_extra_dots_in_ranges() { panic!("Implementation specific: lax parser"); } #[test] fn test_contains_in_id() { assert_template_result!( " YES ", "{% if containsallshipments == true %} YES {% endif %}", o!({"containsallshipments": true}), ); }
test_raise_on_label_and_no_close_bracets_percent
identifier_name
parsing_quirks_test.rs
#[test] fn test_parsing_css() { let text = " div { font-weight: bold; } "; assert_template_result!(text, text); } #[test] fn test_raise_on_single_close_bracet() { assert_parse_error!("text {{method} oh nos!"); } #[test] fn test_raise_on_label_and_no_close_bracets() { assert_parse_error!("TEST {{ "); } #[test] fn test_raise_on_label_and_no_close_bracets_percent() { assert_parse_error!("TEST {% "); } #[test] fn test_error_on_empty_filter()
#[test] fn test_meaningless_parens_error() { assert_parse_error!( "{% if a == 'foo' or (b == 'bar' and c == 'baz') or false %} YES {% endif %}", ); } #[test] fn test_unexpected_characters_syntax_error() { assert_parse_error!("{% if true && false %} YES {% endif %}"); assert_parse_error!("{% if false || true %} YES {% endif %}"); } #[test] #[should_panic] fn test_no_error_on_lax_empty_filter() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_meaningless_parens_lax() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_unexpected_characters_silently_eat_logic_lax() { panic!("Implementation specific: lax parser"); } #[test] fn test_raise_on_invalid_tag_delimiter() { assert_parse_error!("{% end %}"); } #[test] #[should_panic] fn test_unanchored_filter_arguments() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_invalid_variables_work() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_extra_dots_in_ranges() { panic!("Implementation specific: lax parser"); } #[test] fn test_contains_in_id() { assert_template_result!( " YES ", "{% if containsallshipments == true %} YES {% endif %}", o!({"containsallshipments": true}), ); }
{ // Implementation specific: lax parser assert_parse_error!("{{|test}}"); assert_parse_error!("{{test |a|b|}}"); }
identifier_body
parsing_quirks_test.rs
#[test] fn test_parsing_css() { let text = " div { font-weight: bold; } "; assert_template_result!(text, text); } #[test] fn test_raise_on_single_close_bracet() { assert_parse_error!("text {{method} oh nos!"); } #[test] fn test_raise_on_label_and_no_close_bracets() { assert_parse_error!("TEST {{ "); } #[test] fn test_raise_on_label_and_no_close_bracets_percent() { assert_parse_error!("TEST {% "); } #[test] fn test_error_on_empty_filter() { // Implementation specific: lax parser assert_parse_error!("{{|test}}"); assert_parse_error!("{{test |a|b|}}"); } #[test] fn test_meaningless_parens_error() { assert_parse_error!( "{% if a == 'foo' or (b == 'bar' and c == 'baz') or false %} YES {% endif %}", ); } #[test] fn test_unexpected_characters_syntax_error() { assert_parse_error!("{% if true && false %} YES {% endif %}"); assert_parse_error!("{% if false || true %} YES {% endif %}"); } #[test] #[should_panic] fn test_no_error_on_lax_empty_filter() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_meaningless_parens_lax() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_unexpected_characters_silently_eat_logic_lax() { panic!("Implementation specific: lax parser"); }
#[test] #[should_panic] fn test_unanchored_filter_arguments() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_invalid_variables_work() { panic!("Implementation specific: lax parser"); } #[test] #[should_panic] fn test_extra_dots_in_ranges() { panic!("Implementation specific: lax parser"); } #[test] fn test_contains_in_id() { assert_template_result!( " YES ", "{% if containsallshipments == true %} YES {% endif %}", o!({"containsallshipments": true}), ); }
#[test] fn test_raise_on_invalid_tag_delimiter() { assert_parse_error!("{% end %}"); }
random_line_split
util.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use std::fmt; pub static LATIN1_LCASE_TABLE: [u8; 256] = [ // 0x00-0x0f 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, // 0x10-0x1f 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, // 0x20-0x2f b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'', b'(', b')', b'*', b'+', b',', b'-', b'.', b'/', // 0x30-0x3f b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', b';', b'<', b'=', b'>', b'?', // 0x40-0x4f b'@', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', // 0x50-0x5f b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z', b'[', b'\\',b']', b'^', b'_', // 0x60-0x6f b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', // 0x70-0x7f b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f, // 0x80-0x8f 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, // 0x90-0x9f 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, // 0xa0-0xaf 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, // 0xb0-0xbf 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, // 0xc0-0xcf 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, // 0xd0-0xdf 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xd7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xdf, // 0xe0-0xef 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, // 0xf0-0xff 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]; // Ensure this table is UTF-8! pub static LATIN1_PRETTYPRINT_TABLE: [&str; 256] = [ // 0x00-0x0f "␀", "␁", "␂", "␃", "␄", "␅", "␆", "␇", "␈", "␉", "␊", "␋", "␌", "␍", "␎", "␏", // 0x10-0x1f "␐", "␑", "␒", "␓", "␔", "␕", "␖", "␗", "␘", "␙", "␚", "␛", "␜", "␝", "␞", "␟", // 0x20-0x2f " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", // 0x30-0x3f "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", // 0x40-0x4f "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", // 0x50-0x5f "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", // 0x60-0x6f "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", // 0x70-0x7f "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "␡", // 0x80-0x8f "\\x80", "\\x81", "\\x82", "\\x83", "\\x84", "\\x85", "\\x86", "\\x87", "\\x88", "\\x89", "\\x8a", "\\x8b", "\\x8c", "\\x8d", "\\x8e", "\\x8f", // 0x90-0x9f "\\x90", "\\x91", "\\x92", "\\x93", "\\x94", "\\x95", "\\x96", "\\x97", "\\x98", "\\x99", "\\x9a", "\\x9b", "\\x9c", "\\x9d", "\\x9e", "\\x9f", // 0xa0-0xaf "\\xa0", "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "\\xad", "®", "¯", // 0xb0-0xbf "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", // 0xc0-0xcf "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", // 0xd0-0xdf "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", // 0xe0-0xef "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", // 0xf0-0xff "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", ]; fn char_valid_for_basic_id(c: u8) -> bool { match c { // Upper-case letters 0x41...0x5a => true, 0xc0...0xd6 => true, 0xd8...0xde => true, // Lower-case letters 0x61...0x7a => true, 0xdf...0xf6 => true, 0xf8...0xff => true, // Underscore 0x5f => true, // Digits 0x30...0x39 => true, _ => false } } fn char_valid_for_ext_id(c: u8) -> bool { match c { // Cannot be C0 controls 0x00...0x1f => false, // Cannot be C1 controls 0x8
// Cannot be delete 0x7f => false, _ => true } } pub fn get_chr_escaped(c: u8) -> String { match c { 0x20...0x21 | 0x23...0x5b | 0x5D...0x7e => (c as char).to_string(), _ => format!("\\u00{:02x}", c), } } pub struct Latin1Str<'a> { bytes: &'a [u8], } impl<'a> Latin1Str<'a> { pub fn new(inp: &[u8]) -> Latin1Str { Latin1Str {bytes: inp} } pub fn raw_name(&self) -> &[u8] { self.bytes } pub fn pretty_name(&self) -> String { let mut utf8str = String::new(); for c in self.bytes { utf8str.push_str(LATIN1_PRETTYPRINT_TABLE[*c as usize]); } utf8str } pub fn debug_escaped_name(&self) -> String { let mut ret = String::new(); for c in self.bytes { ret += &get_chr_escaped(*c); } ret } pub fn valid_for_basic_id(&self) -> bool { // Needs to be at least one character long if self.bytes.len() == 0 { return false; } // Validate all characters for c in self.bytes { if!(char_valid_for_basic_id(*c)) { return false; } } // First character cannot be a digit or underscore if!(match self.bytes[0] { 0x30...0x39 => false, 0x5f => false, _ => true }) { return false; } // Cannot have consecutive underscores for i in 1..self.bytes.len() { if self.bytes[i - 1] == 0x5f && self.bytes[i] == 0x5f { return false; } } // Cannot end with an underscore if self.bytes[self.bytes.len() - 1] == 0x5f { return false; } true } pub fn valid_for_ext_id(&self) -> bool { // Needs to be at least one character long if self.bytes.len() == 0 { return false; } // Validate all characters for c in self.bytes { if!(char_valid_for_ext_id(*c)) { return false; } } true } } impl<'a> fmt::Display for Latin1Str<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.pretty_name()) } } #[cfg(test)] mod tests { use super::*; #[test] fn latin1_pretty_name() { let x = Latin1Str::new(b"test"); assert_eq!(x.pretty_name(), "test"); assert_eq!(x.raw_name(), b"test"); let x = Latin1Str::new(b"te\xC0st\xFE"); assert_eq!(x.raw_name(), b"te\xC0st\xFE"); assert_eq!(x.pretty_name(), "teÀstþ"); } #[test] fn basic_id_validator() { assert!((Latin1Str::new(b"foo").valid_for_basic_id())); assert!((Latin1Str::new(b"foo012").valid_for_basic_id())); assert!((Latin1Str::new(b"foo_012").valid_for_basic_id())); assert!(!(Latin1Str::new(b"f__oo").valid_for_basic_id())); assert!(!(Latin1Str::new(b"foo_").valid_for_basic_id())); assert!(!(Latin1Str::new(b"_foo").valid_for_basic_id())); } }
0...0x9f => false,
identifier_name
util.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use std::fmt; pub static LATIN1_LCASE_TABLE: [u8; 256] = [ // 0x00-0x0f 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, // 0x10-0x1f 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, // 0x20-0x2f b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'', b'(', b')', b'*', b'+', b',', b'-', b'.', b'/', // 0x30-0x3f b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', b';', b'<', b'=', b'>', b'?', // 0x40-0x4f b'@', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', // 0x50-0x5f b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z', b'[', b'\\',b']', b'^', b'_', // 0x60-0x6f b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', // 0x70-0x7f b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f, // 0x80-0x8f 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, // 0x90-0x9f 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, // 0xa0-0xaf 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, // 0xb0-0xbf 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, // 0xc0-0xcf 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, // 0xd0-0xdf 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xd7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xdf, // 0xe0-0xef 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, // 0xf0-0xff 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]; // Ensure this table is UTF-8! pub static LATIN1_PRETTYPRINT_TABLE: [&str; 256] = [ // 0x00-0x0f "␀", "␁", "␂", "␃", "␄", "␅", "␆", "␇", "␈", "␉", "␊", "␋", "␌", "␍", "␎", "␏", // 0x10-0x1f "␐", "␑", "␒", "␓", "␔", "␕", "␖", "␗", "␘", "␙", "␚", "␛", "␜", "␝", "␞", "␟", // 0x20-0x2f " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", // 0x30-0x3f "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", // 0x40-0x4f "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", // 0x50-0x5f "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", // 0x60-0x6f "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", // 0x70-0x7f "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "␡", // 0x80-0x8f "\\x80", "\\x81", "\\x82", "\\x83", "\\x84", "\\x85", "\\x86", "\\x87", "\\x88", "\\x89", "\\x8a", "\\x8b", "\\x8c", "\\x8d", "\\x8e", "\\x8f", // 0x90-0x9f "\\x90", "\\x91", "\\x92", "\\x93", "\\x94", "\\x95", "\\x96", "\\x97", "\\x98", "\\x99", "\\x9a", "\\x9b", "\\x9c", "\\x9d", "\\x9e", "\\x9f", // 0xa0-0xaf "\\xa0", "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "\\xad", "®", "¯", // 0xb0-0xbf "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", // 0xc0-0xcf "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", // 0xd0-0xdf "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", // 0xe0-0xef "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", // 0xf0-0xff "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", ]; fn char_valid_for_basic_id(c: u8) -> bool { match c { // Upper-case letters 0x41...0x5a => true, 0xc0...0xd6 => true, 0xd8...0xde => true, // Lower-case letters 0x61...0x7a => true, 0xdf...0xf6 => true, 0xf8...0xff => true, // Underscore 0x5f => true, // Digits 0x30...0x39 => true, _ => false } } fn char_valid_for_ext_id(c: u8) -> bool { match c { // Cannot be C0 controls 0x00...0x1f => false, // Cannot be C1 controls 0x80...0x9f => false, // Cannot be delete 0x7f => false, _ => true } } pub fn get_chr_escaped(c: u8) -> String { match c { 0x20...0x21 | 0x23...0x5b | 0x5D...0x7e => (c as char).to_string(), _ => format!("\\u00{:02x}", c), } } pub struct Latin1Str<'a> { bytes: &'a [u8], } impl<'a> Latin1Str<'a> { pub fn new(inp: &[u8]) -> Latin1Str { Latin1Str {bytes: inp} } pub fn raw_name(&self) -> &[u8] { self.bytes } pub fn pretty_name(&self) -> String { let mut utf8str = String::new(); for c in self.bytes { utf8str.push_str(LATIN1_PRETTYPRINT_TABLE[*c as usize]); }
pub fn debug_escaped_name(&self) -> String { let mut ret = String::new(); for c in self.bytes { ret += &get_chr_escaped(*c); } ret } pub fn valid_for_basic_id(&self) -> bool { // Needs to be at least one character long if self.bytes.len() == 0 { return false; } // Validate all characters for c in self.bytes { if!(char_valid_for_basic_id(*c)) { return false; } } // First character cannot be a digit or underscore if!(match self.bytes[0] { 0x30...0x39 => false, 0x5f => false, _ => true }) { return false; } // Cannot have consecutive underscores for i in 1..self.bytes.len() { if self.bytes[i - 1] == 0x5f && self.bytes[i] == 0x5f { return false; } } // Cannot end with an underscore if self.bytes[self.bytes.len() - 1] == 0x5f { return false; } true } pub fn valid_for_ext_id(&self) -> bool { // Needs to be at least one character long if self.bytes.len() == 0 { return false; } // Validate all characters for c in self.bytes { if!(char_valid_for_ext_id(*c)) { return false; } } true } } impl<'a> fmt::Display for Latin1Str<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.pretty_name()) } } #[cfg(test)] mod tests { use super::*; #[test] fn latin1_pretty_name() { let x = Latin1Str::new(b"test"); assert_eq!(x.pretty_name(), "test"); assert_eq!(x.raw_name(), b"test"); let x = Latin1Str::new(b"te\xC0st\xFE"); assert_eq!(x.raw_name(), b"te\xC0st\xFE"); assert_eq!(x.pretty_name(), "teÀstþ"); } #[test] fn basic_id_validator() { assert!((Latin1Str::new(b"foo").valid_for_basic_id())); assert!((Latin1Str::new(b"foo012").valid_for_basic_id())); assert!((Latin1Str::new(b"foo_012").valid_for_basic_id())); assert!(!(Latin1Str::new(b"f__oo").valid_for_basic_id())); assert!(!(Latin1Str::new(b"foo_").valid_for_basic_id())); assert!(!(Latin1Str::new(b"_foo").valid_for_basic_id())); } }
utf8str }
random_line_split
buffer.rs
use std::ptr; use std::io::Read; /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modifies /// results in those bytes being marked as used by the buffer. pub trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input<F: FnMut(&[u8])>(&mut self, input: &[u8], func: F); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: usize); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next(&mut self, len: usize) -> &mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer(&mut self) -> &[u8]; /// Get the current buffer. fn current_buffer(&self) -> &[u8]; /// Get the current position of the buffer. fn position(&self) -> usize; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> usize; /// Get the size of the buffer fn size() -> usize; } macro_rules! impl_fixed_buffer( ($name:ident, $size:expr) => ( pub struct $name { buffer: [u8; $size], position: usize, } impl $name { /// Create a new buffer pub fn new() -> Self { $name { buffer: [0u8; $size], position: 0 } } } impl FixedBuffer for $name { fn input<F: FnMut(&[u8])>(&mut self, mut input: &[u8], mut func: F) { while let Ok(size) = input.read(&mut self.buffer[self.position..$size]) { if (size + self.position) < $size { self.position += size; break } func(&self.buffer); self.position = 0; } } fn reset(&mut self) { self.position = 0; } fn zero_until(&mut self, idx: usize) { assert!(idx >= self.position); zero(&mut self.buffer[self.position..idx]); self.position = idx; } fn next(&mut self, len: usize) -> &mut [u8] { self.position += len; &mut self.buffer[self.position - len..self.position] }
&self.buffer[..$size] } fn current_buffer(&self) -> &[u8] { &self.buffer[..self.position] } fn position(&self) -> usize { self.position } fn remaining(&self) -> usize { $size - self.position } fn size() -> usize { $size } } )); /// A fixed size buffer of 64 bytes useful for cryptographic operations. impl_fixed_buffer!(FixedBuffer64, 64); /// A fixed size buffer of 64 bytes useful for cryptographic operations. impl_fixed_buffer!(FixedBuffer128, 128); /// The StandardPadding trait adds a method useful for various hash algorithms to a FixedBuffer /// struct. pub trait StandardPadding { /// Add standard padding to the buffer. The buffer must not be full when this method is called /// and is guaranteed to have exactly rem remaining bytes when it returns. If there are not at /// least rem bytes available, the buffer will be zero padded, processed, cleared, and then /// filled with zeros again until only rem bytes are remaining. fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, func: F); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, mut func: F) { let size = Self::size(); self.next(1)[0] = 0b10000000; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// Zero all bytes in dst #[inline] pub fn zero(dst: &mut [u8]) { unsafe { ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len()); } }
fn full_buffer(&mut self) -> &[u8] { assert!(self.position == $size); self.position = 0;
random_line_split
buffer.rs
use std::ptr; use std::io::Read; /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modifies /// results in those bytes being marked as used by the buffer. pub trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input<F: FnMut(&[u8])>(&mut self, input: &[u8], func: F); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: usize); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next(&mut self, len: usize) -> &mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer(&mut self) -> &[u8]; /// Get the current buffer. fn current_buffer(&self) -> &[u8]; /// Get the current position of the buffer. fn position(&self) -> usize; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> usize; /// Get the size of the buffer fn size() -> usize; } macro_rules! impl_fixed_buffer( ($name:ident, $size:expr) => ( pub struct $name { buffer: [u8; $size], position: usize, } impl $name { /// Create a new buffer pub fn new() -> Self { $name { buffer: [0u8; $size], position: 0 } } } impl FixedBuffer for $name { fn input<F: FnMut(&[u8])>(&mut self, mut input: &[u8], mut func: F) { while let Ok(size) = input.read(&mut self.buffer[self.position..$size]) { if (size + self.position) < $size { self.position += size; break } func(&self.buffer); self.position = 0; } } fn reset(&mut self) { self.position = 0; } fn zero_until(&mut self, idx: usize) { assert!(idx >= self.position); zero(&mut self.buffer[self.position..idx]); self.position = idx; } fn next(&mut self, len: usize) -> &mut [u8] { self.position += len; &mut self.buffer[self.position - len..self.position] } fn full_buffer(&mut self) -> &[u8] { assert!(self.position == $size); self.position = 0; &self.buffer[..$size] } fn current_buffer(&self) -> &[u8] { &self.buffer[..self.position] } fn position(&self) -> usize { self.position } fn remaining(&self) -> usize { $size - self.position } fn size() -> usize { $size } } )); /// A fixed size buffer of 64 bytes useful for cryptographic operations. impl_fixed_buffer!(FixedBuffer64, 64); /// A fixed size buffer of 64 bytes useful for cryptographic operations. impl_fixed_buffer!(FixedBuffer128, 128); /// The StandardPadding trait adds a method useful for various hash algorithms to a FixedBuffer /// struct. pub trait StandardPadding { /// Add standard padding to the buffer. The buffer must not be full when this method is called /// and is guaranteed to have exactly rem remaining bytes when it returns. If there are not at /// least rem bytes available, the buffer will be zero padded, processed, cleared, and then /// filled with zeros again until only rem bytes are remaining. fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, func: F); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, mut func: F) { let size = Self::size(); self.next(1)[0] = 0b10000000; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// Zero all bytes in dst #[inline] pub fn
(dst: &mut [u8]) { unsafe { ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len()); } }
zero
identifier_name
buffer.rs
use std::ptr; use std::io::Read; /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modifies /// results in those bytes being marked as used by the buffer. pub trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input<F: FnMut(&[u8])>(&mut self, input: &[u8], func: F); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: usize); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next(&mut self, len: usize) -> &mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer(&mut self) -> &[u8]; /// Get the current buffer. fn current_buffer(&self) -> &[u8]; /// Get the current position of the buffer. fn position(&self) -> usize; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> usize; /// Get the size of the buffer fn size() -> usize; } macro_rules! impl_fixed_buffer( ($name:ident, $size:expr) => ( pub struct $name { buffer: [u8; $size], position: usize, } impl $name { /// Create a new buffer pub fn new() -> Self { $name { buffer: [0u8; $size], position: 0 } } } impl FixedBuffer for $name { fn input<F: FnMut(&[u8])>(&mut self, mut input: &[u8], mut func: F) { while let Ok(size) = input.read(&mut self.buffer[self.position..$size]) { if (size + self.position) < $size { self.position += size; break } func(&self.buffer); self.position = 0; } } fn reset(&mut self) { self.position = 0; } fn zero_until(&mut self, idx: usize) { assert!(idx >= self.position); zero(&mut self.buffer[self.position..idx]); self.position = idx; } fn next(&mut self, len: usize) -> &mut [u8] { self.position += len; &mut self.buffer[self.position - len..self.position] } fn full_buffer(&mut self) -> &[u8] { assert!(self.position == $size); self.position = 0; &self.buffer[..$size] } fn current_buffer(&self) -> &[u8] { &self.buffer[..self.position] } fn position(&self) -> usize { self.position } fn remaining(&self) -> usize { $size - self.position } fn size() -> usize { $size } } )); /// A fixed size buffer of 64 bytes useful for cryptographic operations. impl_fixed_buffer!(FixedBuffer64, 64); /// A fixed size buffer of 64 bytes useful for cryptographic operations. impl_fixed_buffer!(FixedBuffer128, 128); /// The StandardPadding trait adds a method useful for various hash algorithms to a FixedBuffer /// struct. pub trait StandardPadding { /// Add standard padding to the buffer. The buffer must not be full when this method is called /// and is guaranteed to have exactly rem remaining bytes when it returns. If there are not at /// least rem bytes available, the buffer will be zero padded, processed, cleared, and then /// filled with zeros again until only rem bytes are remaining. fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, func: F); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, mut func: F) { let size = Self::size(); self.next(1)[0] = 0b10000000; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// Zero all bytes in dst #[inline] pub fn zero(dst: &mut [u8])
{ unsafe { ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len()); } }
identifier_body
buffer.rs
use std::ptr; use std::io::Read; /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modifies /// results in those bytes being marked as used by the buffer. pub trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input<F: FnMut(&[u8])>(&mut self, input: &[u8], func: F); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: usize); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next(&mut self, len: usize) -> &mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer(&mut self) -> &[u8]; /// Get the current buffer. fn current_buffer(&self) -> &[u8]; /// Get the current position of the buffer. fn position(&self) -> usize; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> usize; /// Get the size of the buffer fn size() -> usize; } macro_rules! impl_fixed_buffer( ($name:ident, $size:expr) => ( pub struct $name { buffer: [u8; $size], position: usize, } impl $name { /// Create a new buffer pub fn new() -> Self { $name { buffer: [0u8; $size], position: 0 } } } impl FixedBuffer for $name { fn input<F: FnMut(&[u8])>(&mut self, mut input: &[u8], mut func: F) { while let Ok(size) = input.read(&mut self.buffer[self.position..$size]) { if (size + self.position) < $size { self.position += size; break } func(&self.buffer); self.position = 0; } } fn reset(&mut self) { self.position = 0; } fn zero_until(&mut self, idx: usize) { assert!(idx >= self.position); zero(&mut self.buffer[self.position..idx]); self.position = idx; } fn next(&mut self, len: usize) -> &mut [u8] { self.position += len; &mut self.buffer[self.position - len..self.position] } fn full_buffer(&mut self) -> &[u8] { assert!(self.position == $size); self.position = 0; &self.buffer[..$size] } fn current_buffer(&self) -> &[u8] { &self.buffer[..self.position] } fn position(&self) -> usize { self.position } fn remaining(&self) -> usize { $size - self.position } fn size() -> usize { $size } } )); /// A fixed size buffer of 64 bytes useful for cryptographic operations. impl_fixed_buffer!(FixedBuffer64, 64); /// A fixed size buffer of 64 bytes useful for cryptographic operations. impl_fixed_buffer!(FixedBuffer128, 128); /// The StandardPadding trait adds a method useful for various hash algorithms to a FixedBuffer /// struct. pub trait StandardPadding { /// Add standard padding to the buffer. The buffer must not be full when this method is called /// and is guaranteed to have exactly rem remaining bytes when it returns. If there are not at /// least rem bytes available, the buffer will be zero padded, processed, cleared, and then /// filled with zeros again until only rem bytes are remaining. fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, func: F); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, mut func: F) { let size = Self::size(); self.next(1)[0] = 0b10000000; if self.remaining() < rem
self.zero_until(size - rem); } } /// Zero all bytes in dst #[inline] pub fn zero(dst: &mut [u8]) { unsafe { ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len()); } }
{ self.zero_until(size); func(self.full_buffer()); }
conditional_block
http.rs
use url::Url; use url::ParseError as UrlError; use method; use status::StatusCode; use uri; use uri::RequestUri::{AbsolutePath, AbsoluteUri, Authority, Star}; use version::HttpVersion; use version::HttpVersion::{Http09, Http10, Http11, Http20}; use HttpError::{HttpHeaderError, HttpIoError, HttpMethodError, HttpStatusError, HttpUriError, HttpVersionError}; use HttpResult; use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader}; use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; /// Readers to handle different Transfer-Encodings. /// /// If a message body does not include a Transfer-Encoding, it *should* /// include a Content-Length header. pub enum HttpReader<R> { /// A Reader used when a Content-Length header is passed with a positive integer. SizedReader(R, u64), /// A Reader used when Transfer-Encoding is `chunked`. ChunkedReader(R, Option<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 with both `Content-Length` and /// `Transfer-Encoding: chunked` missing, as explained from the spec: /// /// > 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. EofReader(R), /// A Reader used for messages that should never have a body. /// /// See https://tools.ietf.org/html/rfc7230#section-3.3.3 EmptyReader(R), } impl<R: Reader> HttpReader<R> { /// Unwraps this HttpReader and returns the underlying Reader. pub fn unwrap(self) -> R { match self { SizedReader(r, _) => r, ChunkedReader(r, _) => r, EofReader(r) => r, EmptyReader(r) => r, } } } impl<R: Reader> Reader for HttpReader<R> { fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { match *self { SizedReader(ref mut body, ref mut remaining) => { debug!("Sized read, remaining={:?}", remaining); if *remaining == 0 { Err(old_io::standard_error(old_io::EndOfFile)) } else { let num = try!(body.read(buf)) as u64; if num > *remaining { *remaining = 0; } else { *remaining -= num; } Ok(num as usize) } }, ChunkedReader(ref mut body, ref mut opt_remaining) => { let mut rem = match *opt_remaining { Some(ref rem) => *rem, // None means we don't know the size of the next chunk None => try!(read_chunk_size(body)) }; debug!("Chunked read, remaining={:?}", rem); if rem == 0 { *opt_remaining = Some(0); // chunk of size 0 signals the end of the chunked stream // if the 0 digit was missing from the stream, it would // be an InvalidInput error instead. debug!("end of chunked"); return Err(old_io::standard_error(old_io::EndOfFile)); } let to_read = min(rem as usize, buf.len()); let count = try!(body.read(&mut buf[..to_read])) as u64; rem -= count; *opt_remaining = if rem > 0 { Some(rem) } else { try!(eat(body, LINE_ENDING.as_bytes())); None }; Ok(count as usize) }, EofReader(ref mut body) => { body.read(buf) }, EmptyReader(_) => Err(old_io::standard_error(old_io::EndOfFile)) } } } fn eat<R: Reader>(rdr: &mut R, bytes: &[u8]) -> IoResult<()> { for &b in bytes.iter() { match try!(rdr.read_byte()) { byte if byte == b => (), _ => return Err(old_io::standard_error(old_io::InvalidInput)) } } Ok(()) } /// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk. fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<u64> { let mut size = 0u64; let radix = 16; let mut in_ext = false; let mut in_chunk_size = true; loop { match try!(rdr.read_byte()) { b@b'0'...b'9' if in_chunk_size => { size *= radix; size += (b - b'0') as u64; }, b@b'a'...b'f' if in_chunk_size => { size *= radix; size += (b + 10 - b'a') as u64; }, b@b'A'...b'F' if in_chunk_size => { size *= radix; size += (b + 10 - b'A') as u64; }, CR => { match try!(rdr.read_byte()) { LF => break, _ => return Err(old_io::standard_error(old_io::InvalidInput)) } }, // If we weren't in the extension yet, the ";" signals its start b';' if!in_ext => { in_ext = true; in_chunk_size = false; }, // "Linear white space" is ignored between the chunk size and the // extension separator token (";") due to the "implied *LWS rule". b'\t' | b''if!in_ext &!in_chunk_size => {}, // LWS can follow the chunk size, but no more digits can come b'\t' | b''if in_chunk_size => in_chunk_size = false, // We allow any arbitrary octet once we are in the extension, since // they all get ignored anyway. According to the HTTP spec, valid // extensions would have a more strict syntax: // (token ["=" (token | quoted-string)]) // but we gain nothing by rejecting an otherwise valid chunk size. ext if in_ext => { todo!("chunk extension byte={}", ext); }, // Finally, if we aren't in the extension and we're reading any // other octet, the chunk size line is invalid! _ => { return Err(old_io::standard_error(old_io::InvalidInput)); } } } debug!("chunk size={:?}", size); Ok(size) } /// Writers to handle different Transfer-Encodings. pub enum HttpWriter<W: Writer> { /// A no-op Writer, used initially before Transfer-Encoding is determined. ThroughWriter(W), /// A Writer for when Transfer-Encoding includes `chunked`. ChunkedWriter(W), /// A Writer for when Content-Length is set. /// /// Enforces that the body is not longer than the Content-Length header. SizedWriter(W, u64), /// A writer that should not write any body. EmptyWriter(W), } impl<W: Writer> HttpWriter<W> { /// Unwraps the HttpWriter and returns the underlying Writer. #[inline] pub fn unwrap(self) -> W { match self { ThroughWriter(w) => w, ChunkedWriter(w) => w, SizedWriter(w, _) => w, EmptyWriter(w) => w, } } /// Access the inner Writer. #[inline] pub fn get_ref<'a>(&'a self) -> &'a W { match *self { ThroughWriter(ref w) => w, ChunkedWriter(ref w) => w, SizedWriter(ref w, _) => w, EmptyWriter(ref w) => w, } } /// Access the inner Writer mutably. /// /// Warning: You should not write to this directly, as you can corrupt /// the state. #[inline] pub fn get_mut<'a>(&'a mut self) -> &'a mut W { match *self { ThroughWriter(ref mut w) => w, ChunkedWriter(ref mut w) => w, SizedWriter(ref mut w, _) => w, EmptyWriter(ref mut w) => w, } } /// Ends the HttpWriter, and returns the underlying Writer. /// /// A final `write_all()` is called with an empty message, and then flushed. /// The ChunkedWriter variant will use this to write the 0-sized last-chunk. #[inline] pub fn end(mut self) -> IoResult<W> { try!(self.write_all(&[])); try!(self.flush()); Ok(self.unwrap()) } } impl<W: Writer> Writer for HttpWriter<W> { #[inline] fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { match *self { ThroughWriter(ref mut w) => w.write_all(msg), ChunkedWriter(ref mut w) => { let chunk_size = msg.len(); debug!("chunked write, size = {:?}", chunk_size); try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING)); try!(w.write_all(msg)); w.write_str(LINE_ENDING) }, SizedWriter(ref mut w, ref mut remaining) => { let len = msg.len() as u64; if len > *remaining { let len = *remaining; *remaining = 0; try!(w.write_all(&msg[..len as usize])); Err(old_io::standard_error(old_io::ShortWrite(len as usize))) } else { *remaining -= len; w.write_all(msg) } }, EmptyWriter(..) => { let bytes = msg.len(); if bytes == 0 { Ok(()) } else { Err(old_io::IoError { kind: old_io::ShortWrite(bytes), desc: "EmptyWriter cannot write any bytes", detail: Some("Cannot include a body with this kind of message".to_string()) }) } } } } #[inline] fn flush(&mut self) -> IoResult<()> { match *self { ThroughWriter(ref mut w) => w.flush(), ChunkedWriter(ref mut w) => w.flush(), SizedWriter(ref mut w, _) => w.flush(), EmptyWriter(ref mut w) => w.flush(), } } } pub const SP: u8 = b' '; pub const CR: u8 = b'\r'; pub const LF: u8 = b'\n'; pub const STAR: u8 = b'*'; pub const LINE_ENDING: &'static str = "\r\n"; /// Determines if byte is a token char. /// /// > ```notrust /// > token = 1*tchar /// > /// > tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" /// > / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" /// > / DIGIT / ALPHA /// > ; any VCHAR, except delimiters /// > ``` #[inline] pub fn is_token(b: u8) -> bool { match b { b'a'...b'z' | b'A'...b'Z' | b'0'...b'9' | b'!' | b'#' | b'$' | b'%' | b'&' | b'\''| b'*' | b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~' => true, _ => false } } /// Read token bytes from `stream` into `buf` until a space is encountered. /// Returns `Ok(true)` if we read until a space, /// `Ok(false)` if we got to the end of `buf` without encountering a space, /// otherwise returns any error encountered reading the stream. /// /// The remaining contents of `buf` are left untouched. fn read_token_until_space<R: Reader>(stream: &mut R, buf: &mut [u8]) -> HttpResult<bool> { use std::old_io::BufWriter; let mut bufwrt = BufWriter::new(buf); loop { let byte = try!(stream.read_byte()); if byte == SP { break; } else if!is_token(byte) { return Err(HttpMethodError); // Read to end but there's still more } else if bufwrt.write_u8(byte).is_err() { return Ok(false); } } if bufwrt.tell().unwrap() == 0 { return Err(HttpMethodError); } Ok(true) } /// Read a `Method` from a raw stream, such as `GET`. /// ### Note: /// Extension methods are only parsed to 16 characters. pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { let mut buf = [SP; 16]; if!try!(read_token_until_space(stream, &mut buf)) { return Err(HttpMethodError); } let maybe_method = match &buf[0..7] { b"GET " => Some(method::Method::Get), b"PUT " => Some(method::Method::Put), b"POST " => Some(method::Method::Post), b"HEAD " => Some(method::Method::Head), b"PATCH " => Some(method::Method::Patch), b"TRACE " => Some(method::Method::Trace), b"DELETE " => Some(method::Method::Delete), b"CONNECT" => Some(method::Method::Connect), b"OPTIONS" => Some(method::Method::Options), _ => None, }; debug!("maybe_method = {:?}", maybe_method); match (maybe_method, &buf[]) { (Some(method), _) => Ok(method), (None, ext) => { // We already checked that the buffer is ASCII Ok(method::Method::Extension(unsafe { str::from_utf8_unchecked(ext) }.trim().to_string())) }, } } /// Read a `RequestUri` from a raw stream. pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> { let mut b = try!(stream.read_byte()); while b == SP { b = try!(stream.read_byte()); } let mut s = String::new(); if b == STAR { try!(expect(stream.read_byte(), SP)); return Ok(Star) } else { s.push(b as char); loop { match try!(stream.read_byte()) { SP => { break; }, CR | LF => { return Err(HttpUriError(UrlError::InvalidCharacter)) }, b => s.push(b as char) } } } debug!("uri buf = {:?}", s); if s.as_slice().starts_with("/") { Ok(AbsolutePath(s)) } else if s.as_slice().contains("/") { Ok(AbsoluteUri(try!(Url::parse(s.as_slice())))) } else { let mut temp = "http://".to_string(); temp.push_str(s.as_slice()); try!(Url::parse(temp.as_slice())); todo!("compare vs u.authority()"); Ok(Authority(s)) } } /// Read the `HttpVersion` from a raw stream, such as `HTTP/1.1`. pub fn read_http_version<R: Reader>(stream: &mut R) -> HttpResult<HttpVersion> { try!(expect(stream.read_byte(), b'H')); try!(expect(stream.read_byte(), b'T')); try!(expect(stream.read_byte(), b'T')); try!(expect(stream.read_byte(), b'P')); try!(expect(stream.read_byte(), b'/')); match try!(stream.read_byte()) { b'0' => { try!(expect(stream.read_byte(), b'.')); try!(expect(stream.read_byte(), b'9')); Ok(Http09) }, b'1' => { try!(expect(stream.read_byte(), b'.')); match try!(stream.read_byte()) { b'0' => Ok(Http10), b'1' => Ok(Http11), _ => Err(HttpVersionError) } }, b'2' => { try!(expect(stream.read_byte(), b'.')); try!(expect(stream.read_byte(), b'0')); Ok(Http20) }, _ => Err(HttpVersionError) } } const MAX_HEADER_NAME_LENGTH: usize = 100; const MAX_HEADER_FIELD_LENGTH: usize = 4096; /// The raw bytes when parsing a header line. /// /// A String and Vec<u8>, divided by COLON (`:`). The String is guaranteed /// to be all `token`s. See `is_token` source for all valid characters. pub type RawHeaderLine = (String, Vec<u8>); /// Read a RawHeaderLine from a Reader. /// /// From [spec](https://tools.ietf.org/html/http#section-3.2): /// /// > Each header field consists of a case-insensitive field name followed /// > by a colon (":"), optional leading whitespace, the field value, and /// > optional trailing whitespace. /// > /// > ```notrust /// > header-field = field-name ":" OWS field-value OWS /// > /// > field-name = token /// > field-value = *( field-content / obs-fold ) /// > field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] /// > field-vchar = VCHAR / obs-text /// > /// > obs-fold = CRLF 1*( SP / HTAB ) /// > ; obsolete line folding /// > ; see Section 3.2.4 /// > ``` pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine>> { let mut name = String::new(); let mut value = vec![]; loop { match try!(stream.read_byte()) { CR if name.len() == 0 => { match try!(stream.read_byte()) { LF => return Ok(None), _ => return Err(HttpHeaderError) } }, b':' => break, b if is_token(b) => { if name.len() > MAX_HEADER_NAME_LENGTH { return Err(HttpHeaderError); } name.push(b as char) },
use std::num::from_u16; use std::str::{self, FromStr}; use std::string::CowString;
random_line_split
http.rs
n(); debug!("chunked write, size = {:?}", chunk_size); try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING)); try!(w.write_all(msg)); w.write_str(LINE_ENDING) }, SizedWriter(ref mut w, ref mut remaining) => { let len = msg.len() as u64; if len > *remaining { let len = *remaining; *remaining = 0; try!(w.write_all(&msg[..len as usize])); Err(old_io::standard_error(old_io::ShortWrite(len as usize))) } else { *remaining -= len; w.write_all(msg) } }, EmptyWriter(..) => { let bytes = msg.len(); if bytes == 0 { Ok(()) } else { Err(old_io::IoError { kind: old_io::ShortWrite(bytes), desc: "EmptyWriter cannot write any bytes", detail: Some("Cannot include a body with this kind of message".to_string()) }) } } } } #[inline] fn flush(&mut self) -> IoResult<()> { match *self { ThroughWriter(ref mut w) => w.flush(), ChunkedWriter(ref mut w) => w.flush(), SizedWriter(ref mut w, _) => w.flush(), EmptyWriter(ref mut w) => w.flush(), } } } pub const SP: u8 = b' '; pub const CR: u8 = b'\r'; pub const LF: u8 = b'\n'; pub const STAR: u8 = b'*'; pub const LINE_ENDING: &'static str = "\r\n"; /// Determines if byte is a token char. /// /// > ```notrust /// > token = 1*tchar /// > /// > tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" /// > / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" /// > / DIGIT / ALPHA /// > ; any VCHAR, except delimiters /// > ``` #[inline] pub fn is_token(b: u8) -> bool { match b { b'a'...b'z' | b'A'...b'Z' | b'0'...b'9' | b'!' | b'#' | b'$' | b'%' | b'&' | b'\''| b'*' | b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~' => true, _ => false } } /// Read token bytes from `stream` into `buf` until a space is encountered. /// Returns `Ok(true)` if we read until a space, /// `Ok(false)` if we got to the end of `buf` without encountering a space, /// otherwise returns any error encountered reading the stream. /// /// The remaining contents of `buf` are left untouched. fn read_token_until_space<R: Reader>(stream: &mut R, buf: &mut [u8]) -> HttpResult<bool> { use std::old_io::BufWriter; let mut bufwrt = BufWriter::new(buf); loop { let byte = try!(stream.read_byte()); if byte == SP { break; } else if!is_token(byte) { return Err(HttpMethodError); // Read to end but there's still more } else if bufwrt.write_u8(byte).is_err() { return Ok(false); } } if bufwrt.tell().unwrap() == 0 { return Err(HttpMethodError); } Ok(true) } /// Read a `Method` from a raw stream, such as `GET`. /// ### Note: /// Extension methods are only parsed to 16 characters. pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { let mut buf = [SP; 16]; if!try!(read_token_until_space(stream, &mut buf)) { return Err(HttpMethodError); } let maybe_method = match &buf[0..7] { b"GET " => Some(method::Method::Get), b"PUT " => Some(method::Method::Put), b"POST " => Some(method::Method::Post), b"HEAD " => Some(method::Method::Head), b"PATCH " => Some(method::Method::Patch), b"TRACE " => Some(method::Method::Trace), b"DELETE " => Some(method::Method::Delete), b"CONNECT" => Some(method::Method::Connect), b"OPTIONS" => Some(method::Method::Options), _ => None, }; debug!("maybe_method = {:?}", maybe_method); match (maybe_method, &buf[]) { (Some(method), _) => Ok(method), (None, ext) => { // We already checked that the buffer is ASCII Ok(method::Method::Extension(unsafe { str::from_utf8_unchecked(ext) }.trim().to_string())) }, } } /// Read a `RequestUri` from a raw stream. pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> { let mut b = try!(stream.read_byte()); while b == SP { b = try!(stream.read_byte()); } let mut s = String::new(); if b == STAR { try!(expect(stream.read_byte(), SP)); return Ok(Star) } else { s.push(b as char); loop { match try!(stream.read_byte()) { SP => { break; }, CR | LF => { return Err(HttpUriError(UrlError::InvalidCharacter)) }, b => s.push(b as char) } } } debug!("uri buf = {:?}", s); if s.as_slice().starts_with("/") { Ok(AbsolutePath(s)) } else if s.as_slice().contains("/") { Ok(AbsoluteUri(try!(Url::parse(s.as_slice())))) } else { let mut temp = "http://".to_string(); temp.push_str(s.as_slice()); try!(Url::parse(temp.as_slice())); todo!("compare vs u.authority()"); Ok(Authority(s)) } } /// Read the `HttpVersion` from a raw stream, such as `HTTP/1.1`. pub fn read_http_version<R: Reader>(stream: &mut R) -> HttpResult<HttpVersion> { try!(expect(stream.read_byte(), b'H')); try!(expect(stream.read_byte(), b'T')); try!(expect(stream.read_byte(), b'T')); try!(expect(stream.read_byte(), b'P')); try!(expect(stream.read_byte(), b'/')); match try!(stream.read_byte()) { b'0' => { try!(expect(stream.read_byte(), b'.')); try!(expect(stream.read_byte(), b'9')); Ok(Http09) }, b'1' => { try!(expect(stream.read_byte(), b'.')); match try!(stream.read_byte()) { b'0' => Ok(Http10), b'1' => Ok(Http11), _ => Err(HttpVersionError) } }, b'2' => { try!(expect(stream.read_byte(), b'.')); try!(expect(stream.read_byte(), b'0')); Ok(Http20) }, _ => Err(HttpVersionError) } } const MAX_HEADER_NAME_LENGTH: usize = 100; const MAX_HEADER_FIELD_LENGTH: usize = 4096; /// The raw bytes when parsing a header line. /// /// A String and Vec<u8>, divided by COLON (`:`). The String is guaranteed /// to be all `token`s. See `is_token` source for all valid characters. pub type RawHeaderLine = (String, Vec<u8>); /// Read a RawHeaderLine from a Reader. /// /// From [spec](https://tools.ietf.org/html/http#section-3.2): /// /// > Each header field consists of a case-insensitive field name followed /// > by a colon (":"), optional leading whitespace, the field value, and /// > optional trailing whitespace. /// > /// > ```notrust /// > header-field = field-name ":" OWS field-value OWS /// > /// > field-name = token /// > field-value = *( field-content / obs-fold ) /// > field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] /// > field-vchar = VCHAR / obs-text /// > /// > obs-fold = CRLF 1*( SP / HTAB ) /// > ; obsolete line folding /// > ; see Section 3.2.4 /// > ``` pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine>> { let mut name = String::new(); let mut value = vec![]; loop { match try!(stream.read_byte()) { CR if name.len() == 0 => { match try!(stream.read_byte()) { LF => return Ok(None), _ => return Err(HttpHeaderError) } }, b':' => break, b if is_token(b) => { if name.len() > MAX_HEADER_NAME_LENGTH { return Err(HttpHeaderError); } name.push(b as char) }, _nontoken => return Err(HttpHeaderError) }; } debug!("header name = {:?}", name); let mut ows = true; //optional whitespace todo!("handle obs-folding (gross!)"); loop { match try!(stream.read_byte()) { CR => break, LF => return Err(HttpHeaderError), b''if ows => {}, b => { ows = false; if value.len() > MAX_HEADER_FIELD_LENGTH { return Err(HttpHeaderError); } value.push(b) } }; } // Remove optional trailing whitespace let real_len = value.len() - value.iter().rev().take_while(|&&x| b''== x).count(); value.truncate(real_len); match try!(stream.read_byte()) { LF => Ok(Some((name, value))), _ => Err(HttpHeaderError) } } /// `request-line = method SP request-target SP HTTP-version CRLF` pub type RequestLine = (method::Method, uri::RequestUri, HttpVersion); /// Read the `RequestLine`, such as `GET / HTTP/1.1`. pub fn read_request_line<R: Reader>(stream: &mut R) -> HttpResult<RequestLine> { debug!("read request line"); let method = try!(read_method(stream)); debug!("method = {:?}", method); let uri = try!(read_uri(stream)); debug!("uri = {:?}", uri); let version = try!(read_http_version(stream)); debug!("version = {:?}", version); if try!(stream.read_byte())!= CR { return Err(HttpVersionError); } if try!(stream.read_byte())!= LF { return Err(HttpVersionError); } Ok((method, uri, version)) } /// `status-line = HTTP-version SP status-code SP reason-phrase CRLF` /// /// However, reason-phrase is absolutely useless, so its tossed. pub type StatusLine = (HttpVersion, RawStatus); /// The raw status code and reason-phrase. #[derive(PartialEq, Show)] pub struct RawStatus(pub u16, pub CowString<'static>); impl Clone for RawStatus { fn clone(&self) -> RawStatus { RawStatus(self.0, self.1.clone().into_cow()) } } /// Read the StatusLine, such as `HTTP/1.1 200 OK`. /// /// > The first line of a response message is the status-line, consisting /// > of the protocol version, a space (SP), the status code, another /// > space, a possibly empty textual phrase describing the status code, /// > and ending with CRLF. /// > /// >```notrust /// > status-line = HTTP-version SP status-code SP reason-phrase CRLF /// > status-code = 3DIGIT /// > reason-phrase = *( HTAB / SP / VCHAR / obs-text ) /// >``` pub fn read_status_line<R: Reader>(stream: &mut R) -> HttpResult<StatusLine> { let version = try!(read_http_version(stream)); if try!(stream.read_byte())!= SP { return Err(HttpVersionError); } let code = try!(read_status(stream)); Ok((version, code)) } /// Read the StatusCode from a stream. pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { let code = [ try!(stream.read_byte()), try!(stream.read_byte()), try!(stream.read_byte()), ]; let code = match str::from_utf8(code.as_slice()).ok().and_then(FromStr::from_str) { Some(num) => num, None => return Err(HttpStatusError) }; match try!(stream.read_byte()) { b''=> (), _ => return Err(HttpStatusError) } let mut buf = [b' '; 32]; { let mut bufwrt = BufWriter::new(&mut buf); 'read: loop { match try!(stream.read_byte()) { CR => match try!(stream.read_byte()) { LF => break, _ => return Err(HttpStatusError) }, b => match bufwrt.write_u8(b) { Ok(_) => (), Err(_) => { for _ in 0u8..128 { match try!(stream.read_byte()) { CR => match try!(stream.read_byte()) { LF => break'read, _ => return Err(HttpStatusError) }, _ => { /* ignore */ } } } return Err(HttpStatusError) } } } } } let reason = match str::from_utf8(&buf[]) { Ok(s) => s.trim(), Err(_) => return Err(HttpStatusError) }; let reason = match from_u16::<StatusCode>(code) { Some(status) => match status.canonical_reason() { Some(phrase) => { if phrase == reason { Borrowed(phrase) } else { Owned(reason.to_string()) } } _ => Owned(reason.to_string()) }, None => return Err(HttpStatusError) }; Ok(RawStatus(code, reason)) } #[inline] fn expect(r: IoResult<u8>, expected: u8) -> HttpResult<()> { match r { Ok(b) if b == expected => Ok(()), Ok(_) => Err(HttpVersionError), Err(e) => Err(HttpIoError(e)) } } #[cfg(test)] mod tests { use std::old_io::{self, MemReader, MemWriter, IoResult}; use std::borrow::Cow::{Borrowed, Owned}; use test::Bencher; use uri::RequestUri; use uri::RequestUri::{Star, AbsoluteUri, AbsolutePath, Authority}; use method; use version::HttpVersion; use version::HttpVersion::{Http10, Http11, Http20}; use HttpError::{HttpVersionError, HttpMethodError}; use HttpResult; use url::Url; use super::{read_method, read_uri, read_http_version, read_header, RawHeaderLine, read_status, RawStatus, read_chunk_size}; fn mem(s: &str) -> MemReader { MemReader::new(s.as_bytes().to_vec()) } #[test] fn test_read_method() { fn read(s: &str, result: HttpResult<method::Method>) { assert_eq!(read_method(&mut mem(s)), result); } read("GET /", Ok(method::Method::Get)); read("POST /", Ok(method::Method::Post)); read("PUT /", Ok(method::Method::Put)); read("HEAD /", Ok(method::Method::Head)); read("OPTIONS /", Ok(method::Method::Options)); read("CONNECT /", Ok(method::Method::Connect)); read("TRACE /", Ok(method::Method::Trace)); read("PATCH /", Ok(method::Method::Patch)); read("FOO /", Ok(method::Method::Extension("FOO".to_string()))); read("akemi!~#HOMURA /", Ok(method::Method::Extension("akemi!~#HOMURA".to_string()))); read(" ", Err(HttpMethodError)); } #[test] fn test_read_uri() { fn read(s: &str, result: HttpResult<RequestUri>) { assert_eq!(read_uri(&mut mem(s)), result); } read("* ", Ok(Star)); read("http://hyper.rs/ ", Ok(AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()))); read("hyper.rs ", Ok(Authority("hyper.rs".to_string()))); read("/ ", Ok(AbsolutePath("/".to_string()))); } #[test] fn test_read_http_version() { fn read(s: &str, result: HttpResult<HttpVersion>) { assert_eq!(read_http_version(&mut mem(s)), result); } read("HTTP/1.0", Ok(Http10)); read("HTTP/1.1", Ok(Http11)); read("HTTP/2.0", Ok(Http20)); read("HTP/2.0", Err(HttpVersionError)); read("HTTP.2.0", Err(HttpVersionError)); read("HTTP 2.0", Err(HttpVersionError)); read("TTP 2.0", Err(HttpVersionError)); } #[test] fn test_read_status() { fn read(s: &str, result: HttpResult<RawStatus>) { assert_eq!(read_status(&mut mem(s)), result); } fn read_ignore_string(s: &str, result: HttpResult<RawStatus>) { match (read_status(&mut mem(s)), result) { (Ok(RawStatus(ref c1, _)), Ok(RawStatus(ref c2, _))) => { assert_eq!(c1, c2); }, (r1, r2) => assert_eq!(r1, r2) } } read("200 OK\r\n", Ok(RawStatus(200, Borrowed("OK")))); read("404 Not Found\r\n", Ok(RawStatus(404, Borrowed("Not Found")))); read("200 crazy pants\r\n", Ok(RawStatus(200, Owned("crazy pants".to_string())))); read("301 Moved Permanently\r\n", Ok(RawStatus(301, Owned("Moved Permanently".to_string())))); read_ignore_string("301 Unreasonably long header that should not happen, \ but some men just want to watch the world burn\r\n", Ok(RawStatus(301, Owned("Ignored".to_string())))); } #[test] fn test_read_header() { fn read(s: &str, result: HttpResult<Option<RawHeaderLine>>) { assert_eq!(read_header(&mut mem(s)), result); } read("Host: rust-lang.org\r\n", Ok(Some(("Host".to_string(), b"rust-lang.org".to_vec())))); } #[test] fn
test_write_chunked
identifier_name
http.rs
} impl<R: Reader> Reader for HttpReader<R> { fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { match *self { SizedReader(ref mut body, ref mut remaining) => { debug!("Sized read, remaining={:?}", remaining); if *remaining == 0 { Err(old_io::standard_error(old_io::EndOfFile)) } else { let num = try!(body.read(buf)) as u64; if num > *remaining { *remaining = 0; } else { *remaining -= num; } Ok(num as usize) } }, ChunkedReader(ref mut body, ref mut opt_remaining) => { let mut rem = match *opt_remaining { Some(ref rem) => *rem, // None means we don't know the size of the next chunk None => try!(read_chunk_size(body)) }; debug!("Chunked read, remaining={:?}", rem); if rem == 0 { *opt_remaining = Some(0); // chunk of size 0 signals the end of the chunked stream // if the 0 digit was missing from the stream, it would // be an InvalidInput error instead. debug!("end of chunked"); return Err(old_io::standard_error(old_io::EndOfFile)); } let to_read = min(rem as usize, buf.len()); let count = try!(body.read(&mut buf[..to_read])) as u64; rem -= count; *opt_remaining = if rem > 0 { Some(rem) } else { try!(eat(body, LINE_ENDING.as_bytes())); None }; Ok(count as usize) }, EofReader(ref mut body) => { body.read(buf) }, EmptyReader(_) => Err(old_io::standard_error(old_io::EndOfFile)) } } } fn eat<R: Reader>(rdr: &mut R, bytes: &[u8]) -> IoResult<()> { for &b in bytes.iter() { match try!(rdr.read_byte()) { byte if byte == b => (), _ => return Err(old_io::standard_error(old_io::InvalidInput)) } } Ok(()) } /// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk. fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<u64> { let mut size = 0u64; let radix = 16; let mut in_ext = false; let mut in_chunk_size = true; loop { match try!(rdr.read_byte()) { b@b'0'...b'9' if in_chunk_size => { size *= radix; size += (b - b'0') as u64; }, b@b'a'...b'f' if in_chunk_size => { size *= radix; size += (b + 10 - b'a') as u64; }, b@b'A'...b'F' if in_chunk_size => { size *= radix; size += (b + 10 - b'A') as u64; }, CR => { match try!(rdr.read_byte()) { LF => break, _ => return Err(old_io::standard_error(old_io::InvalidInput)) } }, // If we weren't in the extension yet, the ";" signals its start b';' if!in_ext => { in_ext = true; in_chunk_size = false; }, // "Linear white space" is ignored between the chunk size and the // extension separator token (";") due to the "implied *LWS rule". b'\t' | b''if!in_ext &!in_chunk_size => {}, // LWS can follow the chunk size, but no more digits can come b'\t' | b''if in_chunk_size => in_chunk_size = false, // We allow any arbitrary octet once we are in the extension, since // they all get ignored anyway. According to the HTTP spec, valid // extensions would have a more strict syntax: // (token ["=" (token | quoted-string)]) // but we gain nothing by rejecting an otherwise valid chunk size. ext if in_ext => { todo!("chunk extension byte={}", ext); }, // Finally, if we aren't in the extension and we're reading any // other octet, the chunk size line is invalid! _ => { return Err(old_io::standard_error(old_io::InvalidInput)); } } } debug!("chunk size={:?}", size); Ok(size) } /// Writers to handle different Transfer-Encodings. pub enum HttpWriter<W: Writer> { /// A no-op Writer, used initially before Transfer-Encoding is determined. ThroughWriter(W), /// A Writer for when Transfer-Encoding includes `chunked`. ChunkedWriter(W), /// A Writer for when Content-Length is set. /// /// Enforces that the body is not longer than the Content-Length header. SizedWriter(W, u64), /// A writer that should not write any body. EmptyWriter(W), } impl<W: Writer> HttpWriter<W> { /// Unwraps the HttpWriter and returns the underlying Writer. #[inline] pub fn unwrap(self) -> W { match self { ThroughWriter(w) => w, ChunkedWriter(w) => w, SizedWriter(w, _) => w, EmptyWriter(w) => w, } } /// Access the inner Writer. #[inline] pub fn get_ref<'a>(&'a self) -> &'a W { match *self { ThroughWriter(ref w) => w, ChunkedWriter(ref w) => w, SizedWriter(ref w, _) => w, EmptyWriter(ref w) => w, } } /// Access the inner Writer mutably. /// /// Warning: You should not write to this directly, as you can corrupt /// the state. #[inline] pub fn get_mut<'a>(&'a mut self) -> &'a mut W { match *self { ThroughWriter(ref mut w) => w, ChunkedWriter(ref mut w) => w, SizedWriter(ref mut w, _) => w, EmptyWriter(ref mut w) => w, } } /// Ends the HttpWriter, and returns the underlying Writer. /// /// A final `write_all()` is called with an empty message, and then flushed. /// The ChunkedWriter variant will use this to write the 0-sized last-chunk. #[inline] pub fn end(mut self) -> IoResult<W> { try!(self.write_all(&[])); try!(self.flush()); Ok(self.unwrap()) } } impl<W: Writer> Writer for HttpWriter<W> { #[inline] fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { match *self { ThroughWriter(ref mut w) => w.write_all(msg), ChunkedWriter(ref mut w) => { let chunk_size = msg.len(); debug!("chunked write, size = {:?}", chunk_size); try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING)); try!(w.write_all(msg)); w.write_str(LINE_ENDING) }, SizedWriter(ref mut w, ref mut remaining) => { let len = msg.len() as u64; if len > *remaining { let len = *remaining; *remaining = 0; try!(w.write_all(&msg[..len as usize])); Err(old_io::standard_error(old_io::ShortWrite(len as usize))) } else { *remaining -= len; w.write_all(msg) } }, EmptyWriter(..) => { let bytes = msg.len(); if bytes == 0 { Ok(()) } else { Err(old_io::IoError { kind: old_io::ShortWrite(bytes), desc: "EmptyWriter cannot write any bytes", detail: Some("Cannot include a body with this kind of message".to_string()) }) } } } } #[inline] fn flush(&mut self) -> IoResult<()> { match *self { ThroughWriter(ref mut w) => w.flush(), ChunkedWriter(ref mut w) => w.flush(), SizedWriter(ref mut w, _) => w.flush(), EmptyWriter(ref mut w) => w.flush(), } } } pub const SP: u8 = b' '; pub const CR: u8 = b'\r'; pub const LF: u8 = b'\n'; pub const STAR: u8 = b'*'; pub const LINE_ENDING: &'static str = "\r\n"; /// Determines if byte is a token char. /// /// > ```notrust /// > token = 1*tchar /// > /// > tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" /// > / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" /// > / DIGIT / ALPHA /// > ; any VCHAR, except delimiters /// > ``` #[inline] pub fn is_token(b: u8) -> bool { match b { b'a'...b'z' | b'A'...b'Z' | b'0'...b'9' | b'!' | b'#' | b'$' | b'%' | b'&' | b'\''| b'*' | b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~' => true, _ => false } } /// Read token bytes from `stream` into `buf` until a space is encountered. /// Returns `Ok(true)` if we read until a space, /// `Ok(false)` if we got to the end of `buf` without encountering a space, /// otherwise returns any error encountered reading the stream. /// /// The remaining contents of `buf` are left untouched. fn read_token_until_space<R: Reader>(stream: &mut R, buf: &mut [u8]) -> HttpResult<bool> { use std::old_io::BufWriter; let mut bufwrt = BufWriter::new(buf); loop { let byte = try!(stream.read_byte()); if byte == SP { break; } else if!is_token(byte) { return Err(HttpMethodError); // Read to end but there's still more } else if bufwrt.write_u8(byte).is_err() { return Ok(false); } } if bufwrt.tell().unwrap() == 0 { return Err(HttpMethodError); } Ok(true) } /// Read a `Method` from a raw stream, such as `GET`. /// ### Note: /// Extension methods are only parsed to 16 characters. pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { let mut buf = [SP; 16]; if!try!(read_token_until_space(stream, &mut buf)) { return Err(HttpMethodError); } let maybe_method = match &buf[0..7] { b"GET " => Some(method::Method::Get), b"PUT " => Some(method::Method::Put), b"POST " => Some(method::Method::Post), b"HEAD " => Some(method::Method::Head), b"PATCH " => Some(method::Method::Patch), b"TRACE " => Some(method::Method::Trace), b"DELETE " => Some(method::Method::Delete), b"CONNECT" => Some(method::Method::Connect), b"OPTIONS" => Some(method::Method::Options), _ => None, }; debug!("maybe_method = {:?}", maybe_method); match (maybe_method, &buf[]) { (Some(method), _) => Ok(method), (None, ext) => { // We already checked that the buffer is ASCII Ok(method::Method::Extension(unsafe { str::from_utf8_unchecked(ext) }.trim().to_string())) }, } } /// Read a `RequestUri` from a raw stream. pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> { let mut b = try!(stream.read_byte()); while b == SP { b = try!(stream.read_byte()); } let mut s = String::new(); if b == STAR { try!(expect(stream.read_byte(), SP)); return Ok(Star) } else { s.push(b as char); loop { match try!(stream.read_byte()) { SP => { break; }, CR | LF => { return Err(HttpUriError(UrlError::InvalidCharacter)) }, b => s.push(b as char) } } } debug!("uri buf = {:?}", s); if s.as_slice().starts_with("/") { Ok(AbsolutePath(s)) } else if s.as_slice().contains("/") { Ok(AbsoluteUri(try!(Url::parse(s.as_slice())))) } else { let mut temp = "http://".to_string(); temp.push_str(s.as_slice()); try!(Url::parse(temp.as_slice())); todo!("compare vs u.authority()"); Ok(Authority(s)) } } /// Read the `HttpVersion` from a raw stream, such as `HTTP/1.1`. pub fn read_http_version<R: Reader>(stream: &mut R) -> HttpResult<HttpVersion> { try!(expect(stream.read_byte(), b'H')); try!(expect(stream.read_byte(), b'T')); try!(expect(stream.read_byte(), b'T')); try!(expect(stream.read_byte(), b'P')); try!(expect(stream.read_byte(), b'/')); match try!(stream.read_byte()) { b'0' => { try!(expect(stream.read_byte(), b'.')); try!(expect(stream.read_byte(), b'9')); Ok(Http09) }, b'1' => { try!(expect(stream.read_byte(), b'.')); match try!(stream.read_byte()) { b'0' => Ok(Http10), b'1' => Ok(Http11), _ => Err(HttpVersionError) } }, b'2' => { try!(expect(stream.read_byte(), b'.')); try!(expect(stream.read_byte(), b'0')); Ok(Http20) }, _ => Err(HttpVersionError) } } const MAX_HEADER_NAME_LENGTH: usize = 100; const MAX_HEADER_FIELD_LENGTH: usize = 4096; /// The raw bytes when parsing a header line. /// /// A String and Vec<u8>, divided by COLON (`:`). The String is guaranteed /// to be all `token`s. See `is_token` source for all valid characters. pub type RawHeaderLine = (String, Vec<u8>); /// Read a RawHeaderLine from a Reader. /// /// From [spec](https://tools.ietf.org/html/http#section-3.2): /// /// > Each header field consists of a case-insensitive field name followed /// > by a colon (":"), optional leading whitespace, the field value, and /// > optional trailing whitespace. /// > /// > ```notrust /// > header-field = field-name ":" OWS field-value OWS /// > /// > field-name = token /// > field-value = *( field-content / obs-fold ) /// > field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] /// > field-vchar = VCHAR / obs-text /// > /// > obs-fold = CRLF 1*( SP / HTAB ) /// > ; obsolete line folding /// > ; see Section 3.2.4 /// > ``` pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine>> { let mut name = String::new(); let mut value = vec![]; loop { match try!(stream.read_byte()) { CR if name.len() == 0 => { match try!(stream.read_byte()) { LF => return Ok(None), _ => return Err(HttpHeaderError) } }, b':' => break, b if is_token(b) => { if name.len() > MAX_HEADER_NAME_LENGTH { return Err(HttpHeaderError); } name.push(b as char) }, _nontoken => return Err(HttpHeaderError) }; } debug!("header name = {:?}", name); let mut ows = true; //optional whitespace todo!("handle obs-folding (gross!)"); loop { match try!(stream.read_byte()) { CR => break, LF => return Err(HttpHeaderError), b''if ows => {}, b => { ows = false; if value.len() > MAX_HEADER_FIELD_LENGTH { return Err(HttpHeaderError); } value.push(b) } }; } // Remove optional trailing whitespace let real_len = value.len() - value.iter().rev().take_while(|&&x| b''== x).count(); value.truncate(real_len); match try!(stream.read_byte()) { LF => Ok(Some((name, value))), _ => Err(HttpHeaderError) } } /// `request-line = method SP request-target SP HTTP-version CRLF` pub type RequestLine = (method::Method, uri::RequestUri, HttpVersion); /// Read the `RequestLine`, such as `GET / HTTP/1.1`. pub fn read_request_line<R: Reader>(stream: &mut R) -> HttpResult<RequestLine> { debug!("read request line"); let method = try!(read_method(stream)); debug!("method = {:?}", method); let uri = try!(read_uri(stream)); debug!("uri = {:?}", uri); let version = try!(read_http_version(stream)); debug!("version = {:?}", version); if try!(stream.read_byte())!= CR { return Err(HttpVersionError); } if try!(stream.read_byte())!= LF { return Err(HttpVersionError); }
{ match self { SizedReader(r, _) => r, ChunkedReader(r, _) => r, EofReader(r) => r, EmptyReader(r) => r, } }
identifier_body
response.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use body::{BodyOperations, BodyType, consume_body, consume_body_with_promise}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods}; use dom::bindings::codegen::Bindings::ResponseBinding; use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType}; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit; use dom::bindings::error::{Error, Fallible}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::bindings::str::{ByteString, USVString}; use dom::globalscope::GlobalScope; use dom::headers::{Headers, Guard}; use dom::headers::{is_vchar, is_obs_text}; use dom::promise::Promise; use dom::xmlhttprequest::Extractable; use dom_struct::dom_struct; use hyper::header::Headers as HyperHeaders; use hyper::status::StatusCode; use hyper_serde::Serde; use net_traits::response::{ResponseBody as NetTraitsResponseBody}; use servo_url::ServoUrl; use std::cell::{Cell, Ref}; use std::mem; use std::rc::Rc; use std::str::FromStr; use url::Position; #[dom_struct] pub struct Response { reflector_: Reflector, headers_reflector: MutNullableDom<Headers>, mime_type: DomRefCell<Vec<u8>>, body_used: Cell<bool>, /// `None` can be considered a StatusCode of `0`. #[ignore_malloc_size_of = "Defined in hyper"] status: DomRefCell<Option<StatusCode>>, raw_status: DomRefCell<Option<(u16, Vec<u8>)>>, response_type: DomRefCell<DOMResponseType>, url: DomRefCell<Option<ServoUrl>>, url_list: DomRefCell<Vec<ServoUrl>>, // For now use the existing NetTraitsResponseBody enum body: DomRefCell<NetTraitsResponseBody>, #[ignore_malloc_size_of = "Rc"] body_promise: DomRefCell<Option<(Rc<Promise>, BodyType)>>, } impl Response { pub fn new_inherited() -> Response { Response { reflector_: Reflector::new(), headers_reflector: Default::default(), mime_type: DomRefCell::new("".to_string().into_bytes()), body_used: Cell::new(false), status: DomRefCell::new(Some(StatusCode::Ok)), raw_status: DomRefCell::new(Some((200, b"OK".to_vec()))), response_type: DomRefCell::new(DOMResponseType::Default), url: DomRefCell::new(None), url_list: DomRefCell::new(vec![]), body: DomRefCell::new(NetTraitsResponseBody::Empty), body_promise: DomRefCell::new(None), } } // https://fetch.spec.whatwg.org/#dom-response pub fn new(global: &GlobalScope) -> DomRoot<Response> { reflect_dom_object( Box::new(Response::new_inherited()), global, ResponseBinding::Wrap, ) } pub fn Constructor( global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit, ) -> Fallible<DomRoot<Response>> { // Step 1 if init.status < 200 || init.status > 599 { return Err(Error::Range(format!( "init's status member should be in the range 200 to 599, inclusive, but is {}", init.status ))); } // Step 2 if!is_valid_status_text(&init.statusText) { return Err(Error::Type( "init's statusText member does not match the reason-phrase token production" .to_string(), )); } // Step 3 let r = Response::new(global); // Step 4 *r.status.borrow_mut() = Some(StatusCode::from_u16(init.status)); // Step 5 *r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into())); // Step 6 if let Some(ref headers_member) = init.headers { // Step 6.1 r.Headers().empty_header_list(); // Step 6.2 r.Headers().fill(Some(headers_member.clone()))?; } // Step 7 if let Some(ref body) = body { // Step 7.1 if is_null_body_status(init.status) { return Err(Error::Type( "Body is non-null but init's status member is a null body status".to_string(), )); }; // Step 7.3 let (extracted_body, content_type) = body.extract(); *r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body); // Step 7.4 if let Some(content_type_contents) = content_type { if!r .Headers() .Has(ByteString::new(b"Content-Type".to_vec())) .unwrap() { r.Headers().Append( ByteString::new(b"Content-Type".to_vec()), ByteString::new(content_type_contents.as_bytes().to_vec()), )?; } }; } // Step 8 *r.mime_type.borrow_mut() = r.Headers().extract_mime_type(); // Step 9 // TODO: `entry settings object` is not implemented in Servo yet. // Step 10 // TODO: Write this step once Promises are merged in // Step 11 Ok(r) } // https://fetch.spec.whatwg.org/#dom-response-error pub fn Error(global: &GlobalScope) -> DomRoot<Response> { let r = Response::new(global); *r.response_type.borrow_mut() = DOMResponseType::Error; r.Headers().set_guard(Guard::Immutable); *r.raw_status.borrow_mut() = Some((0, b"".to_vec())); r } // https://fetch.spec.whatwg.org/#dom-response-redirect pub fn
( global: &GlobalScope, url: USVString, status: u16, ) -> Fallible<DomRoot<Response>> { // Step 1 let base_url = global.api_base_url(); let parsed_url = base_url.join(&url.0); // Step 2 let url = match parsed_url { Ok(url) => url, Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())), }; // Step 3 if!is_redirect_status(status) { return Err(Error::Range("status is not a redirect status".to_string())); } // Step 4 // see Step 4 continued let r = Response::new(global); // Step 5 *r.status.borrow_mut() = Some(StatusCode::from_u16(status)); *r.raw_status.borrow_mut() = Some((status, b"".to_vec())); // Step 6 let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec())); r.Headers() .Set(ByteString::new(b"Location".to_vec()), url_bytestring)?; // Step 4 continued // Headers Guard is set to Immutable here to prevent error in Step 6 r.Headers().set_guard(Guard::Immutable); // Step 7 Ok(r) } // https://fetch.spec.whatwg.org/#concept-body-locked fn locked(&self) -> bool { // TODO: ReadableStream is unimplemented. Just return false // for now. false } } impl BodyOperations for Response { fn get_body_used(&self) -> bool { self.BodyUsed() } fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) { assert!(self.body_promise.borrow().is_none()); self.body_used.set(true); *self.body_promise.borrow_mut() = Some((p.clone(), body_type)); } fn is_locked(&self) -> bool { self.locked() } fn take_body(&self) -> Option<Vec<u8>> { let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty); match body { NetTraitsResponseBody::Done(bytes) => Some(bytes), body => { mem::replace(&mut *self.body.borrow_mut(), body); None }, } } fn get_mime_type(&self) -> Ref<Vec<u8>> { self.mime_type.borrow() } } // https://fetch.spec.whatwg.org/#redirect-status fn is_redirect_status(status: u16) -> bool { status == 301 || status == 302 || status == 303 || status == 307 || status == 308 } // https://tools.ietf.org/html/rfc7230#section-3.1.2 fn is_valid_status_text(status_text: &ByteString) -> bool { // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) for byte in status_text.iter() { if!(*byte == b'\t' || *byte == b''|| is_vchar(*byte) || is_obs_text(*byte)) { return false; } } true } // https://fetch.spec.whatwg.org/#null-body-status fn is_null_body_status(status: u16) -> bool { status == 101 || status == 204 || status == 205 || status == 304 } impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-type fn Type(&self) -> DOMResponseType { *self.response_type.borrow() //into() } // https://fetch.spec.whatwg.org/#dom-response-url fn Url(&self) -> USVString { USVString(String::from( (*self.url.borrow()) .as_ref() .map(|u| serialize_without_fragment(u)) .unwrap_or(""), )) } // https://fetch.spec.whatwg.org/#dom-response-redirected fn Redirected(&self) -> bool { let url_list_len = self.url_list.borrow().len(); url_list_len > 1 } // https://fetch.spec.whatwg.org/#dom-response-status fn Status(&self) -> u16 { match *self.raw_status.borrow() { Some((s, _)) => s, None => 0, } } // https://fetch.spec.whatwg.org/#dom-response-ok fn Ok(&self) -> bool { match *self.status.borrow() { Some(s) => { let status_num = s.to_u16(); return status_num >= 200 && status_num <= 299; }, None => false, } } // https://fetch.spec.whatwg.org/#dom-response-statustext fn StatusText(&self) -> ByteString { match *self.raw_status.borrow() { Some((_, ref st)) => ByteString::new(st.clone()), None => ByteString::new(b"OK".to_vec()), } } // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> DomRoot<Headers> { self.headers_reflector .or_init(|| Headers::for_response(&self.global())) } // https://fetch.spec.whatwg.org/#dom-response-clone fn Clone(&self) -> Fallible<DomRoot<Response>> { // Step 1 if self.is_locked() || self.body_used.get() { return Err(Error::Type("cannot clone a disturbed response".to_string())); } // Step 2 let new_response = Response::new(&self.global()); new_response.Headers().set_guard(self.Headers().get_guard()); new_response .Headers() .fill(Some(HeadersInit::Headers(self.Headers())))?; // https://fetch.spec.whatwg.org/#concept-response-clone // Instead of storing a net_traits::Response internally, we // only store the relevant fields, and only clone them here *new_response.response_type.borrow_mut() = self.response_type.borrow().clone(); *new_response.status.borrow_mut() = self.status.borrow().clone(); *new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone(); *new_response.url.borrow_mut() = self.url.borrow().clone(); *new_response.url_list.borrow_mut() = self.url_list.borrow().clone(); if *self.body.borrow()!= NetTraitsResponseBody::Empty { *new_response.body.borrow_mut() = self.body.borrow().clone(); } // Step 3 // TODO: This step relies on promises, which are still unimplemented. // Step 4 Ok(new_response) } // https://fetch.spec.whatwg.org/#dom-body-bodyused fn BodyUsed(&self) -> bool { self.body_used.get() } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-text fn Text(&self) -> Rc<Promise> { consume_body(self, BodyType::Text) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-blob fn Blob(&self) -> Rc<Promise> { consume_body(self, BodyType::Blob) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-formdata fn FormData(&self) -> Rc<Promise> { consume_body(self, BodyType::FormData) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-json fn Json(&self) -> Rc<Promise> { consume_body(self, BodyType::Json) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-arraybuffer fn ArrayBuffer(&self) -> Rc<Promise> { consume_body(self, BodyType::ArrayBuffer) } } fn serialize_without_fragment(url: &ServoUrl) -> &str { &url[..Position::AfterQuery] } impl Response { pub fn set_type(&self, new_response_type: DOMResponseType) { *self.response_type.borrow_mut() = new_response_type; } pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) { self.Headers().set_headers(match option_hyper_headers { Some(hyper_headers) => hyper_headers.into_inner(), None => HyperHeaders::new(), }); } pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) { *self.raw_status.borrow_mut() = status; } pub fn set_final_url(&self, final_url: ServoUrl) { *self.url.borrow_mut() = Some(final_url); } #[allow(unrooted_must_root)] pub fn finish(&self, body: Vec<u8>) { *self.body.borrow_mut() = NetTraitsResponseBody::Done(body); if let Some((p, body_type)) = self.body_promise.borrow_mut().take() { consume_body_with_promise(self, body_type, &p); } } }
Redirect
identifier_name
response.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use body::{BodyOperations, BodyType, consume_body, consume_body_with_promise}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods}; use dom::bindings::codegen::Bindings::ResponseBinding; use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType}; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit; use dom::bindings::error::{Error, Fallible}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::bindings::str::{ByteString, USVString}; use dom::globalscope::GlobalScope; use dom::headers::{Headers, Guard}; use dom::headers::{is_vchar, is_obs_text}; use dom::promise::Promise; use dom::xmlhttprequest::Extractable; use dom_struct::dom_struct; use hyper::header::Headers as HyperHeaders; use hyper::status::StatusCode; use hyper_serde::Serde; use net_traits::response::{ResponseBody as NetTraitsResponseBody}; use servo_url::ServoUrl; use std::cell::{Cell, Ref}; use std::mem; use std::rc::Rc; use std::str::FromStr; use url::Position; #[dom_struct] pub struct Response { reflector_: Reflector, headers_reflector: MutNullableDom<Headers>, mime_type: DomRefCell<Vec<u8>>, body_used: Cell<bool>, /// `None` can be considered a StatusCode of `0`. #[ignore_malloc_size_of = "Defined in hyper"] status: DomRefCell<Option<StatusCode>>, raw_status: DomRefCell<Option<(u16, Vec<u8>)>>, response_type: DomRefCell<DOMResponseType>, url: DomRefCell<Option<ServoUrl>>, url_list: DomRefCell<Vec<ServoUrl>>, // For now use the existing NetTraitsResponseBody enum body: DomRefCell<NetTraitsResponseBody>, #[ignore_malloc_size_of = "Rc"] body_promise: DomRefCell<Option<(Rc<Promise>, BodyType)>>, } impl Response { pub fn new_inherited() -> Response { Response { reflector_: Reflector::new(), headers_reflector: Default::default(), mime_type: DomRefCell::new("".to_string().into_bytes()), body_used: Cell::new(false), status: DomRefCell::new(Some(StatusCode::Ok)), raw_status: DomRefCell::new(Some((200, b"OK".to_vec()))), response_type: DomRefCell::new(DOMResponseType::Default), url: DomRefCell::new(None), url_list: DomRefCell::new(vec![]), body: DomRefCell::new(NetTraitsResponseBody::Empty), body_promise: DomRefCell::new(None), } } // https://fetch.spec.whatwg.org/#dom-response pub fn new(global: &GlobalScope) -> DomRoot<Response> { reflect_dom_object( Box::new(Response::new_inherited()), global, ResponseBinding::Wrap, ) } pub fn Constructor( global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit, ) -> Fallible<DomRoot<Response>> { // Step 1 if init.status < 200 || init.status > 599 { return Err(Error::Range(format!( "init's status member should be in the range 200 to 599, inclusive, but is {}", init.status ))); } // Step 2 if!is_valid_status_text(&init.statusText) { return Err(Error::Type( "init's statusText member does not match the reason-phrase token production" .to_string(), )); } // Step 3 let r = Response::new(global); // Step 4 *r.status.borrow_mut() = Some(StatusCode::from_u16(init.status)); // Step 5 *r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into())); // Step 6 if let Some(ref headers_member) = init.headers { // Step 6.1 r.Headers().empty_header_list(); // Step 6.2 r.Headers().fill(Some(headers_member.clone()))?; } // Step 7 if let Some(ref body) = body { // Step 7.1 if is_null_body_status(init.status) { return Err(Error::Type( "Body is non-null but init's status member is a null body status".to_string(), )); }; // Step 7.3 let (extracted_body, content_type) = body.extract(); *r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body); // Step 7.4 if let Some(content_type_contents) = content_type { if!r .Headers() .Has(ByteString::new(b"Content-Type".to_vec())) .unwrap() { r.Headers().Append( ByteString::new(b"Content-Type".to_vec()), ByteString::new(content_type_contents.as_bytes().to_vec()), )?; } }; } // Step 8 *r.mime_type.borrow_mut() = r.Headers().extract_mime_type(); // Step 9 // TODO: `entry settings object` is not implemented in Servo yet. // Step 10 // TODO: Write this step once Promises are merged in // Step 11 Ok(r) }
pub fn Error(global: &GlobalScope) -> DomRoot<Response> { let r = Response::new(global); *r.response_type.borrow_mut() = DOMResponseType::Error; r.Headers().set_guard(Guard::Immutable); *r.raw_status.borrow_mut() = Some((0, b"".to_vec())); r } // https://fetch.spec.whatwg.org/#dom-response-redirect pub fn Redirect( global: &GlobalScope, url: USVString, status: u16, ) -> Fallible<DomRoot<Response>> { // Step 1 let base_url = global.api_base_url(); let parsed_url = base_url.join(&url.0); // Step 2 let url = match parsed_url { Ok(url) => url, Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())), }; // Step 3 if!is_redirect_status(status) { return Err(Error::Range("status is not a redirect status".to_string())); } // Step 4 // see Step 4 continued let r = Response::new(global); // Step 5 *r.status.borrow_mut() = Some(StatusCode::from_u16(status)); *r.raw_status.borrow_mut() = Some((status, b"".to_vec())); // Step 6 let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec())); r.Headers() .Set(ByteString::new(b"Location".to_vec()), url_bytestring)?; // Step 4 continued // Headers Guard is set to Immutable here to prevent error in Step 6 r.Headers().set_guard(Guard::Immutable); // Step 7 Ok(r) } // https://fetch.spec.whatwg.org/#concept-body-locked fn locked(&self) -> bool { // TODO: ReadableStream is unimplemented. Just return false // for now. false } } impl BodyOperations for Response { fn get_body_used(&self) -> bool { self.BodyUsed() } fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) { assert!(self.body_promise.borrow().is_none()); self.body_used.set(true); *self.body_promise.borrow_mut() = Some((p.clone(), body_type)); } fn is_locked(&self) -> bool { self.locked() } fn take_body(&self) -> Option<Vec<u8>> { let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty); match body { NetTraitsResponseBody::Done(bytes) => Some(bytes), body => { mem::replace(&mut *self.body.borrow_mut(), body); None }, } } fn get_mime_type(&self) -> Ref<Vec<u8>> { self.mime_type.borrow() } } // https://fetch.spec.whatwg.org/#redirect-status fn is_redirect_status(status: u16) -> bool { status == 301 || status == 302 || status == 303 || status == 307 || status == 308 } // https://tools.ietf.org/html/rfc7230#section-3.1.2 fn is_valid_status_text(status_text: &ByteString) -> bool { // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) for byte in status_text.iter() { if!(*byte == b'\t' || *byte == b''|| is_vchar(*byte) || is_obs_text(*byte)) { return false; } } true } // https://fetch.spec.whatwg.org/#null-body-status fn is_null_body_status(status: u16) -> bool { status == 101 || status == 204 || status == 205 || status == 304 } impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-type fn Type(&self) -> DOMResponseType { *self.response_type.borrow() //into() } // https://fetch.spec.whatwg.org/#dom-response-url fn Url(&self) -> USVString { USVString(String::from( (*self.url.borrow()) .as_ref() .map(|u| serialize_without_fragment(u)) .unwrap_or(""), )) } // https://fetch.spec.whatwg.org/#dom-response-redirected fn Redirected(&self) -> bool { let url_list_len = self.url_list.borrow().len(); url_list_len > 1 } // https://fetch.spec.whatwg.org/#dom-response-status fn Status(&self) -> u16 { match *self.raw_status.borrow() { Some((s, _)) => s, None => 0, } } // https://fetch.spec.whatwg.org/#dom-response-ok fn Ok(&self) -> bool { match *self.status.borrow() { Some(s) => { let status_num = s.to_u16(); return status_num >= 200 && status_num <= 299; }, None => false, } } // https://fetch.spec.whatwg.org/#dom-response-statustext fn StatusText(&self) -> ByteString { match *self.raw_status.borrow() { Some((_, ref st)) => ByteString::new(st.clone()), None => ByteString::new(b"OK".to_vec()), } } // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> DomRoot<Headers> { self.headers_reflector .or_init(|| Headers::for_response(&self.global())) } // https://fetch.spec.whatwg.org/#dom-response-clone fn Clone(&self) -> Fallible<DomRoot<Response>> { // Step 1 if self.is_locked() || self.body_used.get() { return Err(Error::Type("cannot clone a disturbed response".to_string())); } // Step 2 let new_response = Response::new(&self.global()); new_response.Headers().set_guard(self.Headers().get_guard()); new_response .Headers() .fill(Some(HeadersInit::Headers(self.Headers())))?; // https://fetch.spec.whatwg.org/#concept-response-clone // Instead of storing a net_traits::Response internally, we // only store the relevant fields, and only clone them here *new_response.response_type.borrow_mut() = self.response_type.borrow().clone(); *new_response.status.borrow_mut() = self.status.borrow().clone(); *new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone(); *new_response.url.borrow_mut() = self.url.borrow().clone(); *new_response.url_list.borrow_mut() = self.url_list.borrow().clone(); if *self.body.borrow()!= NetTraitsResponseBody::Empty { *new_response.body.borrow_mut() = self.body.borrow().clone(); } // Step 3 // TODO: This step relies on promises, which are still unimplemented. // Step 4 Ok(new_response) } // https://fetch.spec.whatwg.org/#dom-body-bodyused fn BodyUsed(&self) -> bool { self.body_used.get() } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-text fn Text(&self) -> Rc<Promise> { consume_body(self, BodyType::Text) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-blob fn Blob(&self) -> Rc<Promise> { consume_body(self, BodyType::Blob) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-formdata fn FormData(&self) -> Rc<Promise> { consume_body(self, BodyType::FormData) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-json fn Json(&self) -> Rc<Promise> { consume_body(self, BodyType::Json) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-arraybuffer fn ArrayBuffer(&self) -> Rc<Promise> { consume_body(self, BodyType::ArrayBuffer) } } fn serialize_without_fragment(url: &ServoUrl) -> &str { &url[..Position::AfterQuery] } impl Response { pub fn set_type(&self, new_response_type: DOMResponseType) { *self.response_type.borrow_mut() = new_response_type; } pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) { self.Headers().set_headers(match option_hyper_headers { Some(hyper_headers) => hyper_headers.into_inner(), None => HyperHeaders::new(), }); } pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) { *self.raw_status.borrow_mut() = status; } pub fn set_final_url(&self, final_url: ServoUrl) { *self.url.borrow_mut() = Some(final_url); } #[allow(unrooted_must_root)] pub fn finish(&self, body: Vec<u8>) { *self.body.borrow_mut() = NetTraitsResponseBody::Done(body); if let Some((p, body_type)) = self.body_promise.borrow_mut().take() { consume_body_with_promise(self, body_type, &p); } } }
// https://fetch.spec.whatwg.org/#dom-response-error
random_line_split
response.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use body::{BodyOperations, BodyType, consume_body, consume_body_with_promise}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods}; use dom::bindings::codegen::Bindings::ResponseBinding; use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType}; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit; use dom::bindings::error::{Error, Fallible}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::bindings::str::{ByteString, USVString}; use dom::globalscope::GlobalScope; use dom::headers::{Headers, Guard}; use dom::headers::{is_vchar, is_obs_text}; use dom::promise::Promise; use dom::xmlhttprequest::Extractable; use dom_struct::dom_struct; use hyper::header::Headers as HyperHeaders; use hyper::status::StatusCode; use hyper_serde::Serde; use net_traits::response::{ResponseBody as NetTraitsResponseBody}; use servo_url::ServoUrl; use std::cell::{Cell, Ref}; use std::mem; use std::rc::Rc; use std::str::FromStr; use url::Position; #[dom_struct] pub struct Response { reflector_: Reflector, headers_reflector: MutNullableDom<Headers>, mime_type: DomRefCell<Vec<u8>>, body_used: Cell<bool>, /// `None` can be considered a StatusCode of `0`. #[ignore_malloc_size_of = "Defined in hyper"] status: DomRefCell<Option<StatusCode>>, raw_status: DomRefCell<Option<(u16, Vec<u8>)>>, response_type: DomRefCell<DOMResponseType>, url: DomRefCell<Option<ServoUrl>>, url_list: DomRefCell<Vec<ServoUrl>>, // For now use the existing NetTraitsResponseBody enum body: DomRefCell<NetTraitsResponseBody>, #[ignore_malloc_size_of = "Rc"] body_promise: DomRefCell<Option<(Rc<Promise>, BodyType)>>, } impl Response { pub fn new_inherited() -> Response { Response { reflector_: Reflector::new(), headers_reflector: Default::default(), mime_type: DomRefCell::new("".to_string().into_bytes()), body_used: Cell::new(false), status: DomRefCell::new(Some(StatusCode::Ok)), raw_status: DomRefCell::new(Some((200, b"OK".to_vec()))), response_type: DomRefCell::new(DOMResponseType::Default), url: DomRefCell::new(None), url_list: DomRefCell::new(vec![]), body: DomRefCell::new(NetTraitsResponseBody::Empty), body_promise: DomRefCell::new(None), } } // https://fetch.spec.whatwg.org/#dom-response pub fn new(global: &GlobalScope) -> DomRoot<Response> { reflect_dom_object( Box::new(Response::new_inherited()), global, ResponseBinding::Wrap, ) } pub fn Constructor( global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit, ) -> Fallible<DomRoot<Response>> { // Step 1 if init.status < 200 || init.status > 599
// Step 2 if!is_valid_status_text(&init.statusText) { return Err(Error::Type( "init's statusText member does not match the reason-phrase token production" .to_string(), )); } // Step 3 let r = Response::new(global); // Step 4 *r.status.borrow_mut() = Some(StatusCode::from_u16(init.status)); // Step 5 *r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into())); // Step 6 if let Some(ref headers_member) = init.headers { // Step 6.1 r.Headers().empty_header_list(); // Step 6.2 r.Headers().fill(Some(headers_member.clone()))?; } // Step 7 if let Some(ref body) = body { // Step 7.1 if is_null_body_status(init.status) { return Err(Error::Type( "Body is non-null but init's status member is a null body status".to_string(), )); }; // Step 7.3 let (extracted_body, content_type) = body.extract(); *r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body); // Step 7.4 if let Some(content_type_contents) = content_type { if!r .Headers() .Has(ByteString::new(b"Content-Type".to_vec())) .unwrap() { r.Headers().Append( ByteString::new(b"Content-Type".to_vec()), ByteString::new(content_type_contents.as_bytes().to_vec()), )?; } }; } // Step 8 *r.mime_type.borrow_mut() = r.Headers().extract_mime_type(); // Step 9 // TODO: `entry settings object` is not implemented in Servo yet. // Step 10 // TODO: Write this step once Promises are merged in // Step 11 Ok(r) } // https://fetch.spec.whatwg.org/#dom-response-error pub fn Error(global: &GlobalScope) -> DomRoot<Response> { let r = Response::new(global); *r.response_type.borrow_mut() = DOMResponseType::Error; r.Headers().set_guard(Guard::Immutable); *r.raw_status.borrow_mut() = Some((0, b"".to_vec())); r } // https://fetch.spec.whatwg.org/#dom-response-redirect pub fn Redirect( global: &GlobalScope, url: USVString, status: u16, ) -> Fallible<DomRoot<Response>> { // Step 1 let base_url = global.api_base_url(); let parsed_url = base_url.join(&url.0); // Step 2 let url = match parsed_url { Ok(url) => url, Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())), }; // Step 3 if!is_redirect_status(status) { return Err(Error::Range("status is not a redirect status".to_string())); } // Step 4 // see Step 4 continued let r = Response::new(global); // Step 5 *r.status.borrow_mut() = Some(StatusCode::from_u16(status)); *r.raw_status.borrow_mut() = Some((status, b"".to_vec())); // Step 6 let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec())); r.Headers() .Set(ByteString::new(b"Location".to_vec()), url_bytestring)?; // Step 4 continued // Headers Guard is set to Immutable here to prevent error in Step 6 r.Headers().set_guard(Guard::Immutable); // Step 7 Ok(r) } // https://fetch.spec.whatwg.org/#concept-body-locked fn locked(&self) -> bool { // TODO: ReadableStream is unimplemented. Just return false // for now. false } } impl BodyOperations for Response { fn get_body_used(&self) -> bool { self.BodyUsed() } fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) { assert!(self.body_promise.borrow().is_none()); self.body_used.set(true); *self.body_promise.borrow_mut() = Some((p.clone(), body_type)); } fn is_locked(&self) -> bool { self.locked() } fn take_body(&self) -> Option<Vec<u8>> { let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty); match body { NetTraitsResponseBody::Done(bytes) => Some(bytes), body => { mem::replace(&mut *self.body.borrow_mut(), body); None }, } } fn get_mime_type(&self) -> Ref<Vec<u8>> { self.mime_type.borrow() } } // https://fetch.spec.whatwg.org/#redirect-status fn is_redirect_status(status: u16) -> bool { status == 301 || status == 302 || status == 303 || status == 307 || status == 308 } // https://tools.ietf.org/html/rfc7230#section-3.1.2 fn is_valid_status_text(status_text: &ByteString) -> bool { // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) for byte in status_text.iter() { if!(*byte == b'\t' || *byte == b''|| is_vchar(*byte) || is_obs_text(*byte)) { return false; } } true } // https://fetch.spec.whatwg.org/#null-body-status fn is_null_body_status(status: u16) -> bool { status == 101 || status == 204 || status == 205 || status == 304 } impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-type fn Type(&self) -> DOMResponseType { *self.response_type.borrow() //into() } // https://fetch.spec.whatwg.org/#dom-response-url fn Url(&self) -> USVString { USVString(String::from( (*self.url.borrow()) .as_ref() .map(|u| serialize_without_fragment(u)) .unwrap_or(""), )) } // https://fetch.spec.whatwg.org/#dom-response-redirected fn Redirected(&self) -> bool { let url_list_len = self.url_list.borrow().len(); url_list_len > 1 } // https://fetch.spec.whatwg.org/#dom-response-status fn Status(&self) -> u16 { match *self.raw_status.borrow() { Some((s, _)) => s, None => 0, } } // https://fetch.spec.whatwg.org/#dom-response-ok fn Ok(&self) -> bool { match *self.status.borrow() { Some(s) => { let status_num = s.to_u16(); return status_num >= 200 && status_num <= 299; }, None => false, } } // https://fetch.spec.whatwg.org/#dom-response-statustext fn StatusText(&self) -> ByteString { match *self.raw_status.borrow() { Some((_, ref st)) => ByteString::new(st.clone()), None => ByteString::new(b"OK".to_vec()), } } // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> DomRoot<Headers> { self.headers_reflector .or_init(|| Headers::for_response(&self.global())) } // https://fetch.spec.whatwg.org/#dom-response-clone fn Clone(&self) -> Fallible<DomRoot<Response>> { // Step 1 if self.is_locked() || self.body_used.get() { return Err(Error::Type("cannot clone a disturbed response".to_string())); } // Step 2 let new_response = Response::new(&self.global()); new_response.Headers().set_guard(self.Headers().get_guard()); new_response .Headers() .fill(Some(HeadersInit::Headers(self.Headers())))?; // https://fetch.spec.whatwg.org/#concept-response-clone // Instead of storing a net_traits::Response internally, we // only store the relevant fields, and only clone them here *new_response.response_type.borrow_mut() = self.response_type.borrow().clone(); *new_response.status.borrow_mut() = self.status.borrow().clone(); *new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone(); *new_response.url.borrow_mut() = self.url.borrow().clone(); *new_response.url_list.borrow_mut() = self.url_list.borrow().clone(); if *self.body.borrow()!= NetTraitsResponseBody::Empty { *new_response.body.borrow_mut() = self.body.borrow().clone(); } // Step 3 // TODO: This step relies on promises, which are still unimplemented. // Step 4 Ok(new_response) } // https://fetch.spec.whatwg.org/#dom-body-bodyused fn BodyUsed(&self) -> bool { self.body_used.get() } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-text fn Text(&self) -> Rc<Promise> { consume_body(self, BodyType::Text) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-blob fn Blob(&self) -> Rc<Promise> { consume_body(self, BodyType::Blob) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-formdata fn FormData(&self) -> Rc<Promise> { consume_body(self, BodyType::FormData) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-json fn Json(&self) -> Rc<Promise> { consume_body(self, BodyType::Json) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-arraybuffer fn ArrayBuffer(&self) -> Rc<Promise> { consume_body(self, BodyType::ArrayBuffer) } } fn serialize_without_fragment(url: &ServoUrl) -> &str { &url[..Position::AfterQuery] } impl Response { pub fn set_type(&self, new_response_type: DOMResponseType) { *self.response_type.borrow_mut() = new_response_type; } pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) { self.Headers().set_headers(match option_hyper_headers { Some(hyper_headers) => hyper_headers.into_inner(), None => HyperHeaders::new(), }); } pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) { *self.raw_status.borrow_mut() = status; } pub fn set_final_url(&self, final_url: ServoUrl) { *self.url.borrow_mut() = Some(final_url); } #[allow(unrooted_must_root)] pub fn finish(&self, body: Vec<u8>) { *self.body.borrow_mut() = NetTraitsResponseBody::Done(body); if let Some((p, body_type)) = self.body_promise.borrow_mut().take() { consume_body_with_promise(self, body_type, &p); } } }
{ return Err(Error::Range(format!( "init's status member should be in the range 200 to 599, inclusive, but is {}", init.status ))); }
conditional_block
response.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use body::{BodyOperations, BodyType, consume_body, consume_body_with_promise}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods}; use dom::bindings::codegen::Bindings::ResponseBinding; use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType}; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit; use dom::bindings::error::{Error, Fallible}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::bindings::str::{ByteString, USVString}; use dom::globalscope::GlobalScope; use dom::headers::{Headers, Guard}; use dom::headers::{is_vchar, is_obs_text}; use dom::promise::Promise; use dom::xmlhttprequest::Extractable; use dom_struct::dom_struct; use hyper::header::Headers as HyperHeaders; use hyper::status::StatusCode; use hyper_serde::Serde; use net_traits::response::{ResponseBody as NetTraitsResponseBody}; use servo_url::ServoUrl; use std::cell::{Cell, Ref}; use std::mem; use std::rc::Rc; use std::str::FromStr; use url::Position; #[dom_struct] pub struct Response { reflector_: Reflector, headers_reflector: MutNullableDom<Headers>, mime_type: DomRefCell<Vec<u8>>, body_used: Cell<bool>, /// `None` can be considered a StatusCode of `0`. #[ignore_malloc_size_of = "Defined in hyper"] status: DomRefCell<Option<StatusCode>>, raw_status: DomRefCell<Option<(u16, Vec<u8>)>>, response_type: DomRefCell<DOMResponseType>, url: DomRefCell<Option<ServoUrl>>, url_list: DomRefCell<Vec<ServoUrl>>, // For now use the existing NetTraitsResponseBody enum body: DomRefCell<NetTraitsResponseBody>, #[ignore_malloc_size_of = "Rc"] body_promise: DomRefCell<Option<(Rc<Promise>, BodyType)>>, } impl Response { pub fn new_inherited() -> Response { Response { reflector_: Reflector::new(), headers_reflector: Default::default(), mime_type: DomRefCell::new("".to_string().into_bytes()), body_used: Cell::new(false), status: DomRefCell::new(Some(StatusCode::Ok)), raw_status: DomRefCell::new(Some((200, b"OK".to_vec()))), response_type: DomRefCell::new(DOMResponseType::Default), url: DomRefCell::new(None), url_list: DomRefCell::new(vec![]), body: DomRefCell::new(NetTraitsResponseBody::Empty), body_promise: DomRefCell::new(None), } } // https://fetch.spec.whatwg.org/#dom-response pub fn new(global: &GlobalScope) -> DomRoot<Response> { reflect_dom_object( Box::new(Response::new_inherited()), global, ResponseBinding::Wrap, ) } pub fn Constructor( global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit, ) -> Fallible<DomRoot<Response>> { // Step 1 if init.status < 200 || init.status > 599 { return Err(Error::Range(format!( "init's status member should be in the range 200 to 599, inclusive, but is {}", init.status ))); } // Step 2 if!is_valid_status_text(&init.statusText) { return Err(Error::Type( "init's statusText member does not match the reason-phrase token production" .to_string(), )); } // Step 3 let r = Response::new(global); // Step 4 *r.status.borrow_mut() = Some(StatusCode::from_u16(init.status)); // Step 5 *r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into())); // Step 6 if let Some(ref headers_member) = init.headers { // Step 6.1 r.Headers().empty_header_list(); // Step 6.2 r.Headers().fill(Some(headers_member.clone()))?; } // Step 7 if let Some(ref body) = body { // Step 7.1 if is_null_body_status(init.status) { return Err(Error::Type( "Body is non-null but init's status member is a null body status".to_string(), )); }; // Step 7.3 let (extracted_body, content_type) = body.extract(); *r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body); // Step 7.4 if let Some(content_type_contents) = content_type { if!r .Headers() .Has(ByteString::new(b"Content-Type".to_vec())) .unwrap() { r.Headers().Append( ByteString::new(b"Content-Type".to_vec()), ByteString::new(content_type_contents.as_bytes().to_vec()), )?; } }; } // Step 8 *r.mime_type.borrow_mut() = r.Headers().extract_mime_type(); // Step 9 // TODO: `entry settings object` is not implemented in Servo yet. // Step 10 // TODO: Write this step once Promises are merged in // Step 11 Ok(r) } // https://fetch.spec.whatwg.org/#dom-response-error pub fn Error(global: &GlobalScope) -> DomRoot<Response> { let r = Response::new(global); *r.response_type.borrow_mut() = DOMResponseType::Error; r.Headers().set_guard(Guard::Immutable); *r.raw_status.borrow_mut() = Some((0, b"".to_vec())); r } // https://fetch.spec.whatwg.org/#dom-response-redirect pub fn Redirect( global: &GlobalScope, url: USVString, status: u16, ) -> Fallible<DomRoot<Response>> { // Step 1 let base_url = global.api_base_url(); let parsed_url = base_url.join(&url.0); // Step 2 let url = match parsed_url { Ok(url) => url, Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())), }; // Step 3 if!is_redirect_status(status) { return Err(Error::Range("status is not a redirect status".to_string())); } // Step 4 // see Step 4 continued let r = Response::new(global); // Step 5 *r.status.borrow_mut() = Some(StatusCode::from_u16(status)); *r.raw_status.borrow_mut() = Some((status, b"".to_vec())); // Step 6 let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec())); r.Headers() .Set(ByteString::new(b"Location".to_vec()), url_bytestring)?; // Step 4 continued // Headers Guard is set to Immutable here to prevent error in Step 6 r.Headers().set_guard(Guard::Immutable); // Step 7 Ok(r) } // https://fetch.spec.whatwg.org/#concept-body-locked fn locked(&self) -> bool { // TODO: ReadableStream is unimplemented. Just return false // for now. false } } impl BodyOperations for Response { fn get_body_used(&self) -> bool { self.BodyUsed() } fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType)
fn is_locked(&self) -> bool { self.locked() } fn take_body(&self) -> Option<Vec<u8>> { let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty); match body { NetTraitsResponseBody::Done(bytes) => Some(bytes), body => { mem::replace(&mut *self.body.borrow_mut(), body); None }, } } fn get_mime_type(&self) -> Ref<Vec<u8>> { self.mime_type.borrow() } } // https://fetch.spec.whatwg.org/#redirect-status fn is_redirect_status(status: u16) -> bool { status == 301 || status == 302 || status == 303 || status == 307 || status == 308 } // https://tools.ietf.org/html/rfc7230#section-3.1.2 fn is_valid_status_text(status_text: &ByteString) -> bool { // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) for byte in status_text.iter() { if!(*byte == b'\t' || *byte == b''|| is_vchar(*byte) || is_obs_text(*byte)) { return false; } } true } // https://fetch.spec.whatwg.org/#null-body-status fn is_null_body_status(status: u16) -> bool { status == 101 || status == 204 || status == 205 || status == 304 } impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-type fn Type(&self) -> DOMResponseType { *self.response_type.borrow() //into() } // https://fetch.spec.whatwg.org/#dom-response-url fn Url(&self) -> USVString { USVString(String::from( (*self.url.borrow()) .as_ref() .map(|u| serialize_without_fragment(u)) .unwrap_or(""), )) } // https://fetch.spec.whatwg.org/#dom-response-redirected fn Redirected(&self) -> bool { let url_list_len = self.url_list.borrow().len(); url_list_len > 1 } // https://fetch.spec.whatwg.org/#dom-response-status fn Status(&self) -> u16 { match *self.raw_status.borrow() { Some((s, _)) => s, None => 0, } } // https://fetch.spec.whatwg.org/#dom-response-ok fn Ok(&self) -> bool { match *self.status.borrow() { Some(s) => { let status_num = s.to_u16(); return status_num >= 200 && status_num <= 299; }, None => false, } } // https://fetch.spec.whatwg.org/#dom-response-statustext fn StatusText(&self) -> ByteString { match *self.raw_status.borrow() { Some((_, ref st)) => ByteString::new(st.clone()), None => ByteString::new(b"OK".to_vec()), } } // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> DomRoot<Headers> { self.headers_reflector .or_init(|| Headers::for_response(&self.global())) } // https://fetch.spec.whatwg.org/#dom-response-clone fn Clone(&self) -> Fallible<DomRoot<Response>> { // Step 1 if self.is_locked() || self.body_used.get() { return Err(Error::Type("cannot clone a disturbed response".to_string())); } // Step 2 let new_response = Response::new(&self.global()); new_response.Headers().set_guard(self.Headers().get_guard()); new_response .Headers() .fill(Some(HeadersInit::Headers(self.Headers())))?; // https://fetch.spec.whatwg.org/#concept-response-clone // Instead of storing a net_traits::Response internally, we // only store the relevant fields, and only clone them here *new_response.response_type.borrow_mut() = self.response_type.borrow().clone(); *new_response.status.borrow_mut() = self.status.borrow().clone(); *new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone(); *new_response.url.borrow_mut() = self.url.borrow().clone(); *new_response.url_list.borrow_mut() = self.url_list.borrow().clone(); if *self.body.borrow()!= NetTraitsResponseBody::Empty { *new_response.body.borrow_mut() = self.body.borrow().clone(); } // Step 3 // TODO: This step relies on promises, which are still unimplemented. // Step 4 Ok(new_response) } // https://fetch.spec.whatwg.org/#dom-body-bodyused fn BodyUsed(&self) -> bool { self.body_used.get() } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-text fn Text(&self) -> Rc<Promise> { consume_body(self, BodyType::Text) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-blob fn Blob(&self) -> Rc<Promise> { consume_body(self, BodyType::Blob) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-formdata fn FormData(&self) -> Rc<Promise> { consume_body(self, BodyType::FormData) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-json fn Json(&self) -> Rc<Promise> { consume_body(self, BodyType::Json) } #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#dom-body-arraybuffer fn ArrayBuffer(&self) -> Rc<Promise> { consume_body(self, BodyType::ArrayBuffer) } } fn serialize_without_fragment(url: &ServoUrl) -> &str { &url[..Position::AfterQuery] } impl Response { pub fn set_type(&self, new_response_type: DOMResponseType) { *self.response_type.borrow_mut() = new_response_type; } pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) { self.Headers().set_headers(match option_hyper_headers { Some(hyper_headers) => hyper_headers.into_inner(), None => HyperHeaders::new(), }); } pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) { *self.raw_status.borrow_mut() = status; } pub fn set_final_url(&self, final_url: ServoUrl) { *self.url.borrow_mut() = Some(final_url); } #[allow(unrooted_must_root)] pub fn finish(&self, body: Vec<u8>) { *self.body.borrow_mut() = NetTraitsResponseBody::Done(body); if let Some((p, body_type)) = self.body_promise.borrow_mut().take() { consume_body_with_promise(self, body_type, &p); } } }
{ assert!(self.body_promise.borrow().is_none()); self.body_used.set(true); *self.body_promise.borrow_mut() = Some((p.clone(), body_type)); }
identifier_body
outline.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" />
additional_methods=[Method("outline_has_nonzero_width", "bool")]) %> // TODO(pcwalton): `invert` ${helpers.predefined_type("outline-color", "CSSColor", "::cssparser::Color::CurrentColor")} <%helpers:longhand name="outline-style" need_clone="True"> pub use values::specified::BorderStyle as SpecifiedValue; pub fn get_initial_value() -> SpecifiedValue { SpecifiedValue::none } pub mod computed_value { pub use values::specified::BorderStyle as T; } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { match SpecifiedValue::parse(input) { Ok(SpecifiedValue::hidden) => Err(()), result => result } } </%helpers:longhand> <%helpers:longhand name="outline-width"> use app_units::Au; use cssparser::ToCss; use std::fmt; use values::AuExtensionMethods; impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { specified::parse_border_width(input).map(SpecifiedValue) } #[derive(Debug, Clone, PartialEq, HeapSizeOf)] pub struct SpecifiedValue(pub specified::Length); pub mod computed_value { use app_units::Au; pub type T = Au; } pub use super::border_top_width::get_initial_value; impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T { self.0.to_computed_value(context) } } </%helpers:longhand> ${helpers.predefined_type("outline-offset", "Length", "Au(0)")}
<% from data import Method %> <% data.new_style_struct("Outline", inherited=False,
random_line_split
outline.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Outline", inherited=False, additional_methods=[Method("outline_has_nonzero_width", "bool")]) %> // TODO(pcwalton): `invert` ${helpers.predefined_type("outline-color", "CSSColor", "::cssparser::Color::CurrentColor")} <%helpers:longhand name="outline-style" need_clone="True"> pub use values::specified::BorderStyle as SpecifiedValue; pub fn get_initial_value() -> SpecifiedValue { SpecifiedValue::none } pub mod computed_value { pub use values::specified::BorderStyle as T; } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { match SpecifiedValue::parse(input) { Ok(SpecifiedValue::hidden) => Err(()), result => result } } </%helpers:longhand> <%helpers:longhand name="outline-width"> use app_units::Au; use cssparser::ToCss; use std::fmt; use values::AuExtensionMethods; impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write
} pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { specified::parse_border_width(input).map(SpecifiedValue) } #[derive(Debug, Clone, PartialEq, HeapSizeOf)] pub struct SpecifiedValue(pub specified::Length); pub mod computed_value { use app_units::Au; pub type T = Au; } pub use super::border_top_width::get_initial_value; impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T { self.0.to_computed_value(context) } } </%helpers:longhand> ${helpers.predefined_type("outline-offset", "Length", "Au(0)")}
{ self.0.to_css(dest) }
identifier_body
outline.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Outline", inherited=False, additional_methods=[Method("outline_has_nonzero_width", "bool")]) %> // TODO(pcwalton): `invert` ${helpers.predefined_type("outline-color", "CSSColor", "::cssparser::Color::CurrentColor")} <%helpers:longhand name="outline-style" need_clone="True"> pub use values::specified::BorderStyle as SpecifiedValue; pub fn get_initial_value() -> SpecifiedValue { SpecifiedValue::none } pub mod computed_value { pub use values::specified::BorderStyle as T; } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { match SpecifiedValue::parse(input) { Ok(SpecifiedValue::hidden) => Err(()), result => result } } </%helpers:longhand> <%helpers:longhand name="outline-width"> use app_units::Au; use cssparser::ToCss; use std::fmt; use values::AuExtensionMethods; impl ToCss for SpecifiedValue { fn
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { specified::parse_border_width(input).map(SpecifiedValue) } #[derive(Debug, Clone, PartialEq, HeapSizeOf)] pub struct SpecifiedValue(pub specified::Length); pub mod computed_value { use app_units::Au; pub type T = Au; } pub use super::border_top_width::get_initial_value; impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T { self.0.to_computed_value(context) } } </%helpers:longhand> ${helpers.predefined_type("outline-offset", "Length", "Au(0)")}
to_css
identifier_name
border.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth. use app_units::Au; use crate::display_list::ToLayout; use euclid::{Rect, SideOffsets2D, Size2D}; use style::computed_values::border_image_outset::T as BorderImageOutset; use style::properties::style_structs::Border; use style::values::computed::NumberOrPercentage; use style::values::computed::{BorderCornerRadius, BorderImageWidth}; use style::values::computed::{BorderImageSideWidth, LengthOrNumber}; use style::values::generics::border::BorderImageSideWidth as GenericBorderImageSideWidth; use style::values::generics::rect::Rect as StyleRect; use style::values::Either; use webrender_api::{BorderRadius, BorderSide, BorderStyle, ColorF}; use webrender_api::{LayoutSideOffsets, LayoutSize, NormalBorder}; /// Computes a border radius size against the containing size. /// /// Note that percentages in `border-radius` are resolved against the relevant /// box dimension instead of only against the width per [1]: /// /// > Percentages: Refer to corresponding dimension of the border box. /// /// [1]: https://drafts.csswg.org/css-backgrounds-3/#border-radius fn corner_radius(radius: BorderCornerRadius, containing_size: Size2D<Au>) -> Size2D<Au> { let w = radius.0.width().to_used_value(containing_size.width); let h = radius.0.height().to_used_value(containing_size.height); Size2D::new(w, h) } fn scaled_radii(radii: BorderRadius, factor: f32) -> BorderRadius { BorderRadius { top_left: radii.top_left * factor, top_right: radii.top_right * factor, bottom_left: radii.bottom_left * factor, bottom_right: radii.bottom_right * factor, } } fn overlapping_radii(size: LayoutSize, radii: BorderRadius) -> BorderRadius { // No two corners' border radii may add up to more than the length of the edge // between them. To prevent that, all radii are scaled down uniformly. fn scale_factor(radius_a: f32, radius_b: f32, edge_length: f32) -> f32 { let required = radius_a + radius_b; if required <= edge_length { 1.0 } else { edge_length / required } } let top_factor = scale_factor(radii.top_left.width, radii.top_right.width, size.width); let bottom_factor = scale_factor( radii.bottom_left.width, radii.bottom_right.width, size.width, ); let left_factor = scale_factor(radii.top_left.height, radii.bottom_left.height, size.height); let right_factor = scale_factor( radii.top_right.height, radii.bottom_right.height, size.height, ); let min_factor = top_factor .min(bottom_factor) .min(left_factor) .min(right_factor); if min_factor < 1.0 { scaled_radii(radii, min_factor) } else { radii } } /// Determine the four corner radii of a border. /// /// Radii may either be absolute or relative to the absolute bounds. /// Each corner radius has a width and a height which may differ. /// Lastly overlapping radii are shrank so they don't collide anymore. pub fn radii(abs_bounds: Rect<Au>, border_style: &Border) -> BorderRadius { // TODO(cgaebel): Support border radii even in the case of multiple border widths. // This is an extension of supporting elliptical radii. For now, all percentage // radii will be relative to the width. overlapping_radii( abs_bounds.size.to_layout(), BorderRadius { top_left: corner_radius(border_style.border_top_left_radius, abs_bounds.size) .to_layout(), top_right: corner_radius(border_style.border_top_right_radius, abs_bounds.size) .to_layout(), bottom_right: corner_radius(border_style.border_bottom_right_radius, abs_bounds.size) .to_layout(), bottom_left: corner_radius(border_style.border_bottom_left_radius, abs_bounds.size) .to_layout(), }, ) } /// Calculates radii for the inner side. /// /// Radii usually describe the outer side of a border but for the lines to look nice /// the inner radii need to be smaller depending on the line width. /// /// This is used to determine clipping areas. pub fn inner_radii(mut radii: BorderRadius, offsets: SideOffsets2D<Au>) -> BorderRadius { fn inner_length(x: f32, offset: Au) -> f32 { 0.0_f32.max(x - offset.to_f32_px()) } radii.top_left.width = inner_length(radii.top_left.width, offsets.left); radii.bottom_left.width = inner_length(radii.bottom_left.width, offsets.left); radii.top_right.width = inner_length(radii.top_right.width, offsets.right); radii.bottom_right.width = inner_length(radii.bottom_right.width, offsets.right); radii.top_left.height = inner_length(radii.top_left.height, offsets.top); radii.top_right.height = inner_length(radii.top_right.height, offsets.top); radii.bottom_left.height = inner_length(radii.bottom_left.height, offsets.bottom); radii.bottom_right.height = inner_length(radii.bottom_right.height, offsets.bottom); radii } /// Creates a four-sided border with square corners and uniform color and width. pub fn simple(color: ColorF, style: BorderStyle) -> NormalBorder { let side = BorderSide { color, style }; NormalBorder { left: side, right: side, top: side, bottom: side, radius: BorderRadius::zero(), do_aa: true, } } fn side_image_outset(outset: LengthOrNumber, border_width: Au) -> Au { match outset { Either::First(length) => length.into(), Either::Second(factor) => border_width.scale_by(factor), } } /// Compute the additional border-image area. pub fn image_outset(outset: BorderImageOutset, border: SideOffsets2D<Au>) -> SideOffsets2D<Au> { SideOffsets2D::new( side_image_outset(outset.0, border.top), side_image_outset(outset.1, border.right),
} fn side_image_width( border_image_width: BorderImageSideWidth, border_width: f32, total_length: Au, ) -> f32 { match border_image_width { GenericBorderImageSideWidth::Length(v) => v.to_used_value(total_length).to_f32_px(), GenericBorderImageSideWidth::Number(x) => border_width * x, GenericBorderImageSideWidth::Auto => border_width, } } pub fn image_width( width: &BorderImageWidth, border: LayoutSideOffsets, border_area: Size2D<Au>, ) -> LayoutSideOffsets { LayoutSideOffsets::new( side_image_width(width.0, border.top, border_area.height), side_image_width(width.1, border.right, border_area.width), side_image_width(width.2, border.bottom, border_area.height), side_image_width(width.3, border.left, border_area.width), ) } fn resolve_percentage(value: NumberOrPercentage, length: u32) -> u32 { match value { NumberOrPercentage::Percentage(p) => (p.0 * length as f32).round() as u32, NumberOrPercentage::Number(n) => n.round() as u32, } } pub fn image_slice( border_image_slice: &StyleRect<NumberOrPercentage>, width: u32, height: u32, ) -> SideOffsets2D<u32> { SideOffsets2D::new( resolve_percentage(border_image_slice.0, height), resolve_percentage(border_image_slice.1, width), resolve_percentage(border_image_slice.2, height), resolve_percentage(border_image_slice.3, width), ) }
side_image_outset(outset.2, border.bottom), side_image_outset(outset.3, border.left), )
random_line_split
border.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth. use app_units::Au; use crate::display_list::ToLayout; use euclid::{Rect, SideOffsets2D, Size2D}; use style::computed_values::border_image_outset::T as BorderImageOutset; use style::properties::style_structs::Border; use style::values::computed::NumberOrPercentage; use style::values::computed::{BorderCornerRadius, BorderImageWidth}; use style::values::computed::{BorderImageSideWidth, LengthOrNumber}; use style::values::generics::border::BorderImageSideWidth as GenericBorderImageSideWidth; use style::values::generics::rect::Rect as StyleRect; use style::values::Either; use webrender_api::{BorderRadius, BorderSide, BorderStyle, ColorF}; use webrender_api::{LayoutSideOffsets, LayoutSize, NormalBorder}; /// Computes a border radius size against the containing size. /// /// Note that percentages in `border-radius` are resolved against the relevant /// box dimension instead of only against the width per [1]: /// /// > Percentages: Refer to corresponding dimension of the border box. /// /// [1]: https://drafts.csswg.org/css-backgrounds-3/#border-radius fn corner_radius(radius: BorderCornerRadius, containing_size: Size2D<Au>) -> Size2D<Au> { let w = radius.0.width().to_used_value(containing_size.width); let h = radius.0.height().to_used_value(containing_size.height); Size2D::new(w, h) } fn scaled_radii(radii: BorderRadius, factor: f32) -> BorderRadius { BorderRadius { top_left: radii.top_left * factor, top_right: radii.top_right * factor, bottom_left: radii.bottom_left * factor, bottom_right: radii.bottom_right * factor, } } fn overlapping_radii(size: LayoutSize, radii: BorderRadius) -> BorderRadius { // No two corners' border radii may add up to more than the length of the edge // between them. To prevent that, all radii are scaled down uniformly. fn scale_factor(radius_a: f32, radius_b: f32, edge_length: f32) -> f32 { let required = radius_a + radius_b; if required <= edge_length
else { edge_length / required } } let top_factor = scale_factor(radii.top_left.width, radii.top_right.width, size.width); let bottom_factor = scale_factor( radii.bottom_left.width, radii.bottom_right.width, size.width, ); let left_factor = scale_factor(radii.top_left.height, radii.bottom_left.height, size.height); let right_factor = scale_factor( radii.top_right.height, radii.bottom_right.height, size.height, ); let min_factor = top_factor .min(bottom_factor) .min(left_factor) .min(right_factor); if min_factor < 1.0 { scaled_radii(radii, min_factor) } else { radii } } /// Determine the four corner radii of a border. /// /// Radii may either be absolute or relative to the absolute bounds. /// Each corner radius has a width and a height which may differ. /// Lastly overlapping radii are shrank so they don't collide anymore. pub fn radii(abs_bounds: Rect<Au>, border_style: &Border) -> BorderRadius { // TODO(cgaebel): Support border radii even in the case of multiple border widths. // This is an extension of supporting elliptical radii. For now, all percentage // radii will be relative to the width. overlapping_radii( abs_bounds.size.to_layout(), BorderRadius { top_left: corner_radius(border_style.border_top_left_radius, abs_bounds.size) .to_layout(), top_right: corner_radius(border_style.border_top_right_radius, abs_bounds.size) .to_layout(), bottom_right: corner_radius(border_style.border_bottom_right_radius, abs_bounds.size) .to_layout(), bottom_left: corner_radius(border_style.border_bottom_left_radius, abs_bounds.size) .to_layout(), }, ) } /// Calculates radii for the inner side. /// /// Radii usually describe the outer side of a border but for the lines to look nice /// the inner radii need to be smaller depending on the line width. /// /// This is used to determine clipping areas. pub fn inner_radii(mut radii: BorderRadius, offsets: SideOffsets2D<Au>) -> BorderRadius { fn inner_length(x: f32, offset: Au) -> f32 { 0.0_f32.max(x - offset.to_f32_px()) } radii.top_left.width = inner_length(radii.top_left.width, offsets.left); radii.bottom_left.width = inner_length(radii.bottom_left.width, offsets.left); radii.top_right.width = inner_length(radii.top_right.width, offsets.right); radii.bottom_right.width = inner_length(radii.bottom_right.width, offsets.right); radii.top_left.height = inner_length(radii.top_left.height, offsets.top); radii.top_right.height = inner_length(radii.top_right.height, offsets.top); radii.bottom_left.height = inner_length(radii.bottom_left.height, offsets.bottom); radii.bottom_right.height = inner_length(radii.bottom_right.height, offsets.bottom); radii } /// Creates a four-sided border with square corners and uniform color and width. pub fn simple(color: ColorF, style: BorderStyle) -> NormalBorder { let side = BorderSide { color, style }; NormalBorder { left: side, right: side, top: side, bottom: side, radius: BorderRadius::zero(), do_aa: true, } } fn side_image_outset(outset: LengthOrNumber, border_width: Au) -> Au { match outset { Either::First(length) => length.into(), Either::Second(factor) => border_width.scale_by(factor), } } /// Compute the additional border-image area. pub fn image_outset(outset: BorderImageOutset, border: SideOffsets2D<Au>) -> SideOffsets2D<Au> { SideOffsets2D::new( side_image_outset(outset.0, border.top), side_image_outset(outset.1, border.right), side_image_outset(outset.2, border.bottom), side_image_outset(outset.3, border.left), ) } fn side_image_width( border_image_width: BorderImageSideWidth, border_width: f32, total_length: Au, ) -> f32 { match border_image_width { GenericBorderImageSideWidth::Length(v) => v.to_used_value(total_length).to_f32_px(), GenericBorderImageSideWidth::Number(x) => border_width * x, GenericBorderImageSideWidth::Auto => border_width, } } pub fn image_width( width: &BorderImageWidth, border: LayoutSideOffsets, border_area: Size2D<Au>, ) -> LayoutSideOffsets { LayoutSideOffsets::new( side_image_width(width.0, border.top, border_area.height), side_image_width(width.1, border.right, border_area.width), side_image_width(width.2, border.bottom, border_area.height), side_image_width(width.3, border.left, border_area.width), ) } fn resolve_percentage(value: NumberOrPercentage, length: u32) -> u32 { match value { NumberOrPercentage::Percentage(p) => (p.0 * length as f32).round() as u32, NumberOrPercentage::Number(n) => n.round() as u32, } } pub fn image_slice( border_image_slice: &StyleRect<NumberOrPercentage>, width: u32, height: u32, ) -> SideOffsets2D<u32> { SideOffsets2D::new( resolve_percentage(border_image_slice.0, height), resolve_percentage(border_image_slice.1, width), resolve_percentage(border_image_slice.2, height), resolve_percentage(border_image_slice.3, width), ) }
{ 1.0 }
conditional_block
border.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth. use app_units::Au; use crate::display_list::ToLayout; use euclid::{Rect, SideOffsets2D, Size2D}; use style::computed_values::border_image_outset::T as BorderImageOutset; use style::properties::style_structs::Border; use style::values::computed::NumberOrPercentage; use style::values::computed::{BorderCornerRadius, BorderImageWidth}; use style::values::computed::{BorderImageSideWidth, LengthOrNumber}; use style::values::generics::border::BorderImageSideWidth as GenericBorderImageSideWidth; use style::values::generics::rect::Rect as StyleRect; use style::values::Either; use webrender_api::{BorderRadius, BorderSide, BorderStyle, ColorF}; use webrender_api::{LayoutSideOffsets, LayoutSize, NormalBorder}; /// Computes a border radius size against the containing size. /// /// Note that percentages in `border-radius` are resolved against the relevant /// box dimension instead of only against the width per [1]: /// /// > Percentages: Refer to corresponding dimension of the border box. /// /// [1]: https://drafts.csswg.org/css-backgrounds-3/#border-radius fn corner_radius(radius: BorderCornerRadius, containing_size: Size2D<Au>) -> Size2D<Au> { let w = radius.0.width().to_used_value(containing_size.width); let h = radius.0.height().to_used_value(containing_size.height); Size2D::new(w, h) } fn scaled_radii(radii: BorderRadius, factor: f32) -> BorderRadius { BorderRadius { top_left: radii.top_left * factor, top_right: radii.top_right * factor, bottom_left: radii.bottom_left * factor, bottom_right: radii.bottom_right * factor, } } fn overlapping_radii(size: LayoutSize, radii: BorderRadius) -> BorderRadius { // No two corners' border radii may add up to more than the length of the edge // between them. To prevent that, all radii are scaled down uniformly. fn scale_factor(radius_a: f32, radius_b: f32, edge_length: f32) -> f32 { let required = radius_a + radius_b; if required <= edge_length { 1.0 } else { edge_length / required } } let top_factor = scale_factor(radii.top_left.width, radii.top_right.width, size.width); let bottom_factor = scale_factor( radii.bottom_left.width, radii.bottom_right.width, size.width, ); let left_factor = scale_factor(radii.top_left.height, radii.bottom_left.height, size.height); let right_factor = scale_factor( radii.top_right.height, radii.bottom_right.height, size.height, ); let min_factor = top_factor .min(bottom_factor) .min(left_factor) .min(right_factor); if min_factor < 1.0 { scaled_radii(radii, min_factor) } else { radii } } /// Determine the four corner radii of a border. /// /// Radii may either be absolute or relative to the absolute bounds. /// Each corner radius has a width and a height which may differ. /// Lastly overlapping radii are shrank so they don't collide anymore. pub fn
(abs_bounds: Rect<Au>, border_style: &Border) -> BorderRadius { // TODO(cgaebel): Support border radii even in the case of multiple border widths. // This is an extension of supporting elliptical radii. For now, all percentage // radii will be relative to the width. overlapping_radii( abs_bounds.size.to_layout(), BorderRadius { top_left: corner_radius(border_style.border_top_left_radius, abs_bounds.size) .to_layout(), top_right: corner_radius(border_style.border_top_right_radius, abs_bounds.size) .to_layout(), bottom_right: corner_radius(border_style.border_bottom_right_radius, abs_bounds.size) .to_layout(), bottom_left: corner_radius(border_style.border_bottom_left_radius, abs_bounds.size) .to_layout(), }, ) } /// Calculates radii for the inner side. /// /// Radii usually describe the outer side of a border but for the lines to look nice /// the inner radii need to be smaller depending on the line width. /// /// This is used to determine clipping areas. pub fn inner_radii(mut radii: BorderRadius, offsets: SideOffsets2D<Au>) -> BorderRadius { fn inner_length(x: f32, offset: Au) -> f32 { 0.0_f32.max(x - offset.to_f32_px()) } radii.top_left.width = inner_length(radii.top_left.width, offsets.left); radii.bottom_left.width = inner_length(radii.bottom_left.width, offsets.left); radii.top_right.width = inner_length(radii.top_right.width, offsets.right); radii.bottom_right.width = inner_length(radii.bottom_right.width, offsets.right); radii.top_left.height = inner_length(radii.top_left.height, offsets.top); radii.top_right.height = inner_length(radii.top_right.height, offsets.top); radii.bottom_left.height = inner_length(radii.bottom_left.height, offsets.bottom); radii.bottom_right.height = inner_length(radii.bottom_right.height, offsets.bottom); radii } /// Creates a four-sided border with square corners and uniform color and width. pub fn simple(color: ColorF, style: BorderStyle) -> NormalBorder { let side = BorderSide { color, style }; NormalBorder { left: side, right: side, top: side, bottom: side, radius: BorderRadius::zero(), do_aa: true, } } fn side_image_outset(outset: LengthOrNumber, border_width: Au) -> Au { match outset { Either::First(length) => length.into(), Either::Second(factor) => border_width.scale_by(factor), } } /// Compute the additional border-image area. pub fn image_outset(outset: BorderImageOutset, border: SideOffsets2D<Au>) -> SideOffsets2D<Au> { SideOffsets2D::new( side_image_outset(outset.0, border.top), side_image_outset(outset.1, border.right), side_image_outset(outset.2, border.bottom), side_image_outset(outset.3, border.left), ) } fn side_image_width( border_image_width: BorderImageSideWidth, border_width: f32, total_length: Au, ) -> f32 { match border_image_width { GenericBorderImageSideWidth::Length(v) => v.to_used_value(total_length).to_f32_px(), GenericBorderImageSideWidth::Number(x) => border_width * x, GenericBorderImageSideWidth::Auto => border_width, } } pub fn image_width( width: &BorderImageWidth, border: LayoutSideOffsets, border_area: Size2D<Au>, ) -> LayoutSideOffsets { LayoutSideOffsets::new( side_image_width(width.0, border.top, border_area.height), side_image_width(width.1, border.right, border_area.width), side_image_width(width.2, border.bottom, border_area.height), side_image_width(width.3, border.left, border_area.width), ) } fn resolve_percentage(value: NumberOrPercentage, length: u32) -> u32 { match value { NumberOrPercentage::Percentage(p) => (p.0 * length as f32).round() as u32, NumberOrPercentage::Number(n) => n.round() as u32, } } pub fn image_slice( border_image_slice: &StyleRect<NumberOrPercentage>, width: u32, height: u32, ) -> SideOffsets2D<u32> { SideOffsets2D::new( resolve_percentage(border_image_slice.0, height), resolve_percentage(border_image_slice.1, width), resolve_percentage(border_image_slice.2, height), resolve_percentage(border_image_slice.3, width), ) }
radii
identifier_name
border.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth. use app_units::Au; use crate::display_list::ToLayout; use euclid::{Rect, SideOffsets2D, Size2D}; use style::computed_values::border_image_outset::T as BorderImageOutset; use style::properties::style_structs::Border; use style::values::computed::NumberOrPercentage; use style::values::computed::{BorderCornerRadius, BorderImageWidth}; use style::values::computed::{BorderImageSideWidth, LengthOrNumber}; use style::values::generics::border::BorderImageSideWidth as GenericBorderImageSideWidth; use style::values::generics::rect::Rect as StyleRect; use style::values::Either; use webrender_api::{BorderRadius, BorderSide, BorderStyle, ColorF}; use webrender_api::{LayoutSideOffsets, LayoutSize, NormalBorder}; /// Computes a border radius size against the containing size. /// /// Note that percentages in `border-radius` are resolved against the relevant /// box dimension instead of only against the width per [1]: /// /// > Percentages: Refer to corresponding dimension of the border box. /// /// [1]: https://drafts.csswg.org/css-backgrounds-3/#border-radius fn corner_radius(radius: BorderCornerRadius, containing_size: Size2D<Au>) -> Size2D<Au> { let w = radius.0.width().to_used_value(containing_size.width); let h = radius.0.height().to_used_value(containing_size.height); Size2D::new(w, h) } fn scaled_radii(radii: BorderRadius, factor: f32) -> BorderRadius { BorderRadius { top_left: radii.top_left * factor, top_right: radii.top_right * factor, bottom_left: radii.bottom_left * factor, bottom_right: radii.bottom_right * factor, } } fn overlapping_radii(size: LayoutSize, radii: BorderRadius) -> BorderRadius { // No two corners' border radii may add up to more than the length of the edge // between them. To prevent that, all radii are scaled down uniformly. fn scale_factor(radius_a: f32, radius_b: f32, edge_length: f32) -> f32 { let required = radius_a + radius_b; if required <= edge_length { 1.0 } else { edge_length / required } } let top_factor = scale_factor(radii.top_left.width, radii.top_right.width, size.width); let bottom_factor = scale_factor( radii.bottom_left.width, radii.bottom_right.width, size.width, ); let left_factor = scale_factor(radii.top_left.height, radii.bottom_left.height, size.height); let right_factor = scale_factor( radii.top_right.height, radii.bottom_right.height, size.height, ); let min_factor = top_factor .min(bottom_factor) .min(left_factor) .min(right_factor); if min_factor < 1.0 { scaled_radii(radii, min_factor) } else { radii } } /// Determine the four corner radii of a border. /// /// Radii may either be absolute or relative to the absolute bounds. /// Each corner radius has a width and a height which may differ. /// Lastly overlapping radii are shrank so they don't collide anymore. pub fn radii(abs_bounds: Rect<Au>, border_style: &Border) -> BorderRadius { // TODO(cgaebel): Support border radii even in the case of multiple border widths. // This is an extension of supporting elliptical radii. For now, all percentage // radii will be relative to the width. overlapping_radii( abs_bounds.size.to_layout(), BorderRadius { top_left: corner_radius(border_style.border_top_left_radius, abs_bounds.size) .to_layout(), top_right: corner_radius(border_style.border_top_right_radius, abs_bounds.size) .to_layout(), bottom_right: corner_radius(border_style.border_bottom_right_radius, abs_bounds.size) .to_layout(), bottom_left: corner_radius(border_style.border_bottom_left_radius, abs_bounds.size) .to_layout(), }, ) } /// Calculates radii for the inner side. /// /// Radii usually describe the outer side of a border but for the lines to look nice /// the inner radii need to be smaller depending on the line width. /// /// This is used to determine clipping areas. pub fn inner_radii(mut radii: BorderRadius, offsets: SideOffsets2D<Au>) -> BorderRadius { fn inner_length(x: f32, offset: Au) -> f32 { 0.0_f32.max(x - offset.to_f32_px()) } radii.top_left.width = inner_length(radii.top_left.width, offsets.left); radii.bottom_left.width = inner_length(radii.bottom_left.width, offsets.left); radii.top_right.width = inner_length(radii.top_right.width, offsets.right); radii.bottom_right.width = inner_length(radii.bottom_right.width, offsets.right); radii.top_left.height = inner_length(radii.top_left.height, offsets.top); radii.top_right.height = inner_length(radii.top_right.height, offsets.top); radii.bottom_left.height = inner_length(radii.bottom_left.height, offsets.bottom); radii.bottom_right.height = inner_length(radii.bottom_right.height, offsets.bottom); radii } /// Creates a four-sided border with square corners and uniform color and width. pub fn simple(color: ColorF, style: BorderStyle) -> NormalBorder { let side = BorderSide { color, style }; NormalBorder { left: side, right: side, top: side, bottom: side, radius: BorderRadius::zero(), do_aa: true, } } fn side_image_outset(outset: LengthOrNumber, border_width: Au) -> Au { match outset { Either::First(length) => length.into(), Either::Second(factor) => border_width.scale_by(factor), } } /// Compute the additional border-image area. pub fn image_outset(outset: BorderImageOutset, border: SideOffsets2D<Au>) -> SideOffsets2D<Au>
fn side_image_width( border_image_width: BorderImageSideWidth, border_width: f32, total_length: Au, ) -> f32 { match border_image_width { GenericBorderImageSideWidth::Length(v) => v.to_used_value(total_length).to_f32_px(), GenericBorderImageSideWidth::Number(x) => border_width * x, GenericBorderImageSideWidth::Auto => border_width, } } pub fn image_width( width: &BorderImageWidth, border: LayoutSideOffsets, border_area: Size2D<Au>, ) -> LayoutSideOffsets { LayoutSideOffsets::new( side_image_width(width.0, border.top, border_area.height), side_image_width(width.1, border.right, border_area.width), side_image_width(width.2, border.bottom, border_area.height), side_image_width(width.3, border.left, border_area.width), ) } fn resolve_percentage(value: NumberOrPercentage, length: u32) -> u32 { match value { NumberOrPercentage::Percentage(p) => (p.0 * length as f32).round() as u32, NumberOrPercentage::Number(n) => n.round() as u32, } } pub fn image_slice( border_image_slice: &StyleRect<NumberOrPercentage>, width: u32, height: u32, ) -> SideOffsets2D<u32> { SideOffsets2D::new( resolve_percentage(border_image_slice.0, height), resolve_percentage(border_image_slice.1, width), resolve_percentage(border_image_slice.2, height), resolve_percentage(border_image_slice.3, width), ) }
{ SideOffsets2D::new( side_image_outset(outset.0, border.top), side_image_outset(outset.1, border.right), side_image_outset(outset.2, border.bottom), side_image_outset(outset.3, border.left), ) }
identifier_body
mod.rs
pub use self::index_pool::IndexPool; pub use self::debug_draw::DebugDraw; pub use self::timer::Timer; use cgmath::*; use std::ops::Mul; use std::f32; mod index_pool; mod timer; pub mod debug_draw; // // Global tuning constants based on meters-kilograms-seconds (MKS) units. // // Collision /// The maximum number of vertices on a convex polygon. pub const MAX_POLYGON_VERTICES: usize = 8; /// This is used to fatten Aabbs in the dynamic tree. This allows proxies to move by a small /// amount without triggering a tree adjustment. This is in meters pub const AABB_EXTENSION: f32 = 0.1; /// A small length used as a collision and constraint tolerance. Usually it is chosen to be /// numerically significant, but visually insignificant. pub const LINEAR_SLOP: f32 = 0.005; /// The radius of the polygon/edge shape skin. This should not be modified. Making this smaller /// means polygons will have an insufficient buffer for continues collision. Making it larger /// may create artifacts for vertex collision. pub const POLYGON_RADIUS: f32 = 2.0 * LINEAR_SLOP; /// Maximum number of sub-steps per contact in continuous physics simulation. pub const MAX_SUB_STEPS: u32 = 8; // Dynamics /// Maximum number of iterations per TOI impact. pub const MAX_TOI_ITERATIONS: usize = 20; /// Maximum number of contacts to be handled to solve a TOI impact. pub const MAX_TOI_CONTACTS: usize = 32; /// A velocity threshold for elastic collisions. Any collision with a relative linear velocity /// below this threshold will be treated as inelasti pub const VELOCITY_THRESHOLD: f32 = 1.0; /// The maximum linear position correction used when solving constraints. This helps to /// prevent overshoot. pub const MAX_LINEAR_CORRECTION: f32 = 0.2; /// The maximum linear velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. pub const MAX_TRANSLATION: f32 = 2.0; pub const MAX_TRANSLATION_SQUARED: f32 = MAX_TRANSLATION * MAX_TRANSLATION; /// The maximum angular velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. pub const MAX_ROTATION: f32 = 0.5 * f32::consts::PI; pub const MAX_ROTATION_SQUARED: f32 = MAX_ROTATION * MAX_ROTATION; /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so /// that overlap is removed in one time step. However, using values close to 1 often lead /// to overshoot. pub const BAUMGARTE: f32 = 0.2; pub const TOI_BAUMGARTE: f32 = 0.75; /// Performs the cross product on a vector and a scalar. In 2D this produces a vector. pub fn cross_v_s(v: &Vector2<f32>, s: f32) -> Vector2<f32> { Vector2::<f32> { x: s * v.y, y: -s * v.x, } }
/// Performs the cross product on a scalar and a vector. In 2D this produces a vector. pub fn cross_s_v(s: f32, v: &Vector2<f32>) -> Vector2<f32> { Vector2::<f32> { x: -s * v.y, y: s * v.x, } } pub fn clamp_f32(s: f32, low: f32, high: f32) -> f32 { f32::max(low, f32::min(s, high)) } #[derive(Clone, Copy, Debug)] pub struct Rotation2d { sin: f32, cos: f32, } impl Default for Rotation2d { /// Constructs a new identity rotation. fn default() -> Rotation2d { Rotation2d { sin: 0.0, cos: 1.0, } } } impl Rotation2d { /// Constructs a new rotation from an angle. pub fn new(angle: f32) -> Self { Rotation2d { sin: angle.sin(), cos: angle.cos(), } } /// Sets the rotation from an angle. pub fn set_angle(&mut self, angle: f32) { self.sin = angle.sin(); self.cos = angle.cos(); } /// Returns the angle in radians. pub fn get_angle(&self) -> f32 { f32::atan2(self.sin, self.cos) } /// Multiplies this rotation with the supplied one. pub fn mul(&self, rhs: &Rotation2d) -> Rotation2d { // q = self, r = rhs // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] Rotation2d { sin: self.sin * rhs.cos + self.cos * rhs.sin, cos: self.cos * rhs.cos - self.sin * rhs.sin, } } /// Multiplies the transpose of this rotation with the supplied one pub fn mul_t(&self, rhs: &Rotation2d) -> Rotation2d { // q = self, r = rhs // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] Rotation2d { sin: self.cos * rhs.sin - self.sin * rhs.cos, cos: self.cos * rhs.cos + self.sin * rhs.sin, } } /// Rotates a vector pub fn apply(&self, v: &Vector2<f32>) -> Vector2<f32> { // q = self // [qc -qs] * [x] = [qc*x - qs*y] // [qs qc] [y] [qs*x + qc*y] Vector2::<f32> { x: self.cos * v.x - self.sin * v.y, y: self.sin * v.x + self.cos * v.y, } } /// Inverse rotates a vector pub fn apply_t(&self, v: &Vector2<f32>) -> Vector2<f32> { // q = self // [ qc qs] * [x] = [qc*x + qs*y] // [-qs qc] [y] [qs*x + qc*y] Vector2::<f32> { x: self.cos * v.x + self.sin * v.y, y: -self.sin * v.x + self.cos * v.y, } } } /// A transform contains translation and rotation. It is used to represent the position /// and orientation of rigid frames. #[derive(Clone, Copy, Debug)] pub struct Transform2d { pub position: Vector2<f32>, pub rotation: Rotation2d, } impl Default for Transform2d { /// Constructs a new identity transform. fn default() -> Transform2d { Transform2d { position: Vector2::zero(), rotation: Default::default(), } } } impl Transform2d { /// Constructs a new transform with the given position and rotation. pub fn new(position: Vector2<f32>, rotation: Rotation2d) -> Self { Transform2d { position: position, rotation: rotation, } } pub fn mul(&self, rhs: &Transform2d) -> Transform2d { Transform2d { position: self.rotation.apply(&rhs.position) + self.position, rotation: self.rotation.mul(&rhs.rotation), } } pub fn mul_t(&self, rhs: &Transform2d) -> Transform2d { Transform2d { position: self.rotation.apply_t(&(rhs.position - self.position)), rotation: self.rotation.mul_t(&rhs.rotation), } } pub fn apply(&self, v: &Vector2<f32>) -> Vector2<f32> { Vector2::<f32> { x: self.rotation.cos * v.x - self.rotation.sin * v.y + self.position.x, y: self.rotation.sin * v.x + self.rotation.cos * v.y + self.position.y, } } pub fn apply_t(&self, v: &Vector2<f32>) -> Vector2<f32> { let p = v - self.position; Vector2::<f32> { x: self.rotation.cos * p.x + self.rotation.sin * p.y, y: -self.rotation.sin * p.x + self.rotation.cos * p.y, } } } /// This describes the motion of a body/shape for TOI computation. Shapes are defined /// with respect to the body origin, which may not coincide with the center of mass. /// However, to support dynamics we must interpolate the center of mass position. #[derive(Clone, Copy)] pub struct Sweep { /// Local center of mass position pub local_center: Vector2<f32>, /// center world position at `alpha0` pub c0: Vector2<f32>, /// center world position pub c: Vector2<f32>, /// world angle at `alpha0` pub a0: f32, /// world angle pub a: f32, /// Fraction of the current time step in the range [0, 1] pub alpha0: f32, } impl Default for Sweep { fn default() -> Sweep { Sweep { local_center: Vector2::zero(), c0: Vector2::zero(), c: Vector2::zero(), a0: 0.0, a: 0.0, alpha0: 0.0, } } } impl Sweep { /// Get the interpolated transform at a specific time. `beta` is a factor in [0, 1], /// where 0 indicates `alpha0` pub fn get_transform(&self, beta: f32) -> Transform2d { let mut result = Transform2d::new( self.c0 * (1.0 - beta) + self.c * beta, Rotation2d::new(self.a0 * (1.0 - beta) + self.a * beta), ); /*let mut result = Transform2d::default(); result.position = self.c0 * (1.0 - beta) + self.c * beta; result.rotation.set_angle(self.a0 * (1.0 - beta) + self.a * beta);*/ // Shift to origin. result.position -= result.rotation.apply(&self.local_center); result } /// Advance the sweep forward, yielding a new initial state. `alpha` is the new /// initial time. pub fn advance(&mut self, alpha: f32) { assert!(self.alpha0 < 1.0); let beta = (alpha - self.alpha0) / (1.0 - self.alpha0); self.c0 += (self.c - self.c0) * beta; self.a0 += (self.a - self.a0) * beta; self.alpha0 = alpha; } /// Normalize the angles. pub fn normalize(&mut self) { let two_pi = 2.0 * f32::consts::PI; let d = two_pi * (self.a0 / two_pi).floor(); self.a0 -= d; self.a -= d; } }
random_line_split
mod.rs
pub use self::index_pool::IndexPool; pub use self::debug_draw::DebugDraw; pub use self::timer::Timer; use cgmath::*; use std::ops::Mul; use std::f32; mod index_pool; mod timer; pub mod debug_draw; // // Global tuning constants based on meters-kilograms-seconds (MKS) units. // // Collision /// The maximum number of vertices on a convex polygon. pub const MAX_POLYGON_VERTICES: usize = 8; /// This is used to fatten Aabbs in the dynamic tree. This allows proxies to move by a small /// amount without triggering a tree adjustment. This is in meters pub const AABB_EXTENSION: f32 = 0.1; /// A small length used as a collision and constraint tolerance. Usually it is chosen to be /// numerically significant, but visually insignificant. pub const LINEAR_SLOP: f32 = 0.005; /// The radius of the polygon/edge shape skin. This should not be modified. Making this smaller /// means polygons will have an insufficient buffer for continues collision. Making it larger /// may create artifacts for vertex collision. pub const POLYGON_RADIUS: f32 = 2.0 * LINEAR_SLOP; /// Maximum number of sub-steps per contact in continuous physics simulation. pub const MAX_SUB_STEPS: u32 = 8; // Dynamics /// Maximum number of iterations per TOI impact. pub const MAX_TOI_ITERATIONS: usize = 20; /// Maximum number of contacts to be handled to solve a TOI impact. pub const MAX_TOI_CONTACTS: usize = 32; /// A velocity threshold for elastic collisions. Any collision with a relative linear velocity /// below this threshold will be treated as inelasti pub const VELOCITY_THRESHOLD: f32 = 1.0; /// The maximum linear position correction used when solving constraints. This helps to /// prevent overshoot. pub const MAX_LINEAR_CORRECTION: f32 = 0.2; /// The maximum linear velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. pub const MAX_TRANSLATION: f32 = 2.0; pub const MAX_TRANSLATION_SQUARED: f32 = MAX_TRANSLATION * MAX_TRANSLATION; /// The maximum angular velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. pub const MAX_ROTATION: f32 = 0.5 * f32::consts::PI; pub const MAX_ROTATION_SQUARED: f32 = MAX_ROTATION * MAX_ROTATION; /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so /// that overlap is removed in one time step. However, using values close to 1 often lead /// to overshoot. pub const BAUMGARTE: f32 = 0.2; pub const TOI_BAUMGARTE: f32 = 0.75; /// Performs the cross product on a vector and a scalar. In 2D this produces a vector. pub fn cross_v_s(v: &Vector2<f32>, s: f32) -> Vector2<f32> { Vector2::<f32> { x: s * v.y, y: -s * v.x, } } /// Performs the cross product on a scalar and a vector. In 2D this produces a vector. pub fn cross_s_v(s: f32, v: &Vector2<f32>) -> Vector2<f32> { Vector2::<f32> { x: -s * v.y, y: s * v.x, } } pub fn clamp_f32(s: f32, low: f32, high: f32) -> f32 { f32::max(low, f32::min(s, high)) } #[derive(Clone, Copy, Debug)] pub struct Rotation2d { sin: f32, cos: f32, } impl Default for Rotation2d { /// Constructs a new identity rotation. fn default() -> Rotation2d { Rotation2d { sin: 0.0, cos: 1.0, } } } impl Rotation2d { /// Constructs a new rotation from an angle. pub fn new(angle: f32) -> Self { Rotation2d { sin: angle.sin(), cos: angle.cos(), } } /// Sets the rotation from an angle. pub fn set_angle(&mut self, angle: f32) { self.sin = angle.sin(); self.cos = angle.cos(); } /// Returns the angle in radians. pub fn get_angle(&self) -> f32 { f32::atan2(self.sin, self.cos) } /// Multiplies this rotation with the supplied one. pub fn mul(&self, rhs: &Rotation2d) -> Rotation2d { // q = self, r = rhs // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] Rotation2d { sin: self.sin * rhs.cos + self.cos * rhs.sin, cos: self.cos * rhs.cos - self.sin * rhs.sin, } } /// Multiplies the transpose of this rotation with the supplied one pub fn
(&self, rhs: &Rotation2d) -> Rotation2d { // q = self, r = rhs // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] Rotation2d { sin: self.cos * rhs.sin - self.sin * rhs.cos, cos: self.cos * rhs.cos + self.sin * rhs.sin, } } /// Rotates a vector pub fn apply(&self, v: &Vector2<f32>) -> Vector2<f32> { // q = self // [qc -qs] * [x] = [qc*x - qs*y] // [qs qc] [y] [qs*x + qc*y] Vector2::<f32> { x: self.cos * v.x - self.sin * v.y, y: self.sin * v.x + self.cos * v.y, } } /// Inverse rotates a vector pub fn apply_t(&self, v: &Vector2<f32>) -> Vector2<f32> { // q = self // [ qc qs] * [x] = [qc*x + qs*y] // [-qs qc] [y] [qs*x + qc*y] Vector2::<f32> { x: self.cos * v.x + self.sin * v.y, y: -self.sin * v.x + self.cos * v.y, } } } /// A transform contains translation and rotation. It is used to represent the position /// and orientation of rigid frames. #[derive(Clone, Copy, Debug)] pub struct Transform2d { pub position: Vector2<f32>, pub rotation: Rotation2d, } impl Default for Transform2d { /// Constructs a new identity transform. fn default() -> Transform2d { Transform2d { position: Vector2::zero(), rotation: Default::default(), } } } impl Transform2d { /// Constructs a new transform with the given position and rotation. pub fn new(position: Vector2<f32>, rotation: Rotation2d) -> Self { Transform2d { position: position, rotation: rotation, } } pub fn mul(&self, rhs: &Transform2d) -> Transform2d { Transform2d { position: self.rotation.apply(&rhs.position) + self.position, rotation: self.rotation.mul(&rhs.rotation), } } pub fn mul_t(&self, rhs: &Transform2d) -> Transform2d { Transform2d { position: self.rotation.apply_t(&(rhs.position - self.position)), rotation: self.rotation.mul_t(&rhs.rotation), } } pub fn apply(&self, v: &Vector2<f32>) -> Vector2<f32> { Vector2::<f32> { x: self.rotation.cos * v.x - self.rotation.sin * v.y + self.position.x, y: self.rotation.sin * v.x + self.rotation.cos * v.y + self.position.y, } } pub fn apply_t(&self, v: &Vector2<f32>) -> Vector2<f32> { let p = v - self.position; Vector2::<f32> { x: self.rotation.cos * p.x + self.rotation.sin * p.y, y: -self.rotation.sin * p.x + self.rotation.cos * p.y, } } } /// This describes the motion of a body/shape for TOI computation. Shapes are defined /// with respect to the body origin, which may not coincide with the center of mass. /// However, to support dynamics we must interpolate the center of mass position. #[derive(Clone, Copy)] pub struct Sweep { /// Local center of mass position pub local_center: Vector2<f32>, /// center world position at `alpha0` pub c0: Vector2<f32>, /// center world position pub c: Vector2<f32>, /// world angle at `alpha0` pub a0: f32, /// world angle pub a: f32, /// Fraction of the current time step in the range [0, 1] pub alpha0: f32, } impl Default for Sweep { fn default() -> Sweep { Sweep { local_center: Vector2::zero(), c0: Vector2::zero(), c: Vector2::zero(), a0: 0.0, a: 0.0, alpha0: 0.0, } } } impl Sweep { /// Get the interpolated transform at a specific time. `beta` is a factor in [0, 1], /// where 0 indicates `alpha0` pub fn get_transform(&self, beta: f32) -> Transform2d { let mut result = Transform2d::new( self.c0 * (1.0 - beta) + self.c * beta, Rotation2d::new(self.a0 * (1.0 - beta) + self.a * beta), ); /*let mut result = Transform2d::default(); result.position = self.c0 * (1.0 - beta) + self.c * beta; result.rotation.set_angle(self.a0 * (1.0 - beta) + self.a * beta);*/ // Shift to origin. result.position -= result.rotation.apply(&self.local_center); result } /// Advance the sweep forward, yielding a new initial state. `alpha` is the new /// initial time. pub fn advance(&mut self, alpha: f32) { assert!(self.alpha0 < 1.0); let beta = (alpha - self.alpha0) / (1.0 - self.alpha0); self.c0 += (self.c - self.c0) * beta; self.a0 += (self.a - self.a0) * beta; self.alpha0 = alpha; } /// Normalize the angles. pub fn normalize(&mut self) { let two_pi = 2.0 * f32::consts::PI; let d = two_pi * (self.a0 / two_pi).floor(); self.a0 -= d; self.a -= d; } }
mul_t
identifier_name
mod.rs
pub use self::index_pool::IndexPool; pub use self::debug_draw::DebugDraw; pub use self::timer::Timer; use cgmath::*; use std::ops::Mul; use std::f32; mod index_pool; mod timer; pub mod debug_draw; // // Global tuning constants based on meters-kilograms-seconds (MKS) units. // // Collision /// The maximum number of vertices on a convex polygon. pub const MAX_POLYGON_VERTICES: usize = 8; /// This is used to fatten Aabbs in the dynamic tree. This allows proxies to move by a small /// amount without triggering a tree adjustment. This is in meters pub const AABB_EXTENSION: f32 = 0.1; /// A small length used as a collision and constraint tolerance. Usually it is chosen to be /// numerically significant, but visually insignificant. pub const LINEAR_SLOP: f32 = 0.005; /// The radius of the polygon/edge shape skin. This should not be modified. Making this smaller /// means polygons will have an insufficient buffer for continues collision. Making it larger /// may create artifacts for vertex collision. pub const POLYGON_RADIUS: f32 = 2.0 * LINEAR_SLOP; /// Maximum number of sub-steps per contact in continuous physics simulation. pub const MAX_SUB_STEPS: u32 = 8; // Dynamics /// Maximum number of iterations per TOI impact. pub const MAX_TOI_ITERATIONS: usize = 20; /// Maximum number of contacts to be handled to solve a TOI impact. pub const MAX_TOI_CONTACTS: usize = 32; /// A velocity threshold for elastic collisions. Any collision with a relative linear velocity /// below this threshold will be treated as inelasti pub const VELOCITY_THRESHOLD: f32 = 1.0; /// The maximum linear position correction used when solving constraints. This helps to /// prevent overshoot. pub const MAX_LINEAR_CORRECTION: f32 = 0.2; /// The maximum linear velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. pub const MAX_TRANSLATION: f32 = 2.0; pub const MAX_TRANSLATION_SQUARED: f32 = MAX_TRANSLATION * MAX_TRANSLATION; /// The maximum angular velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. pub const MAX_ROTATION: f32 = 0.5 * f32::consts::PI; pub const MAX_ROTATION_SQUARED: f32 = MAX_ROTATION * MAX_ROTATION; /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so /// that overlap is removed in one time step. However, using values close to 1 often lead /// to overshoot. pub const BAUMGARTE: f32 = 0.2; pub const TOI_BAUMGARTE: f32 = 0.75; /// Performs the cross product on a vector and a scalar. In 2D this produces a vector. pub fn cross_v_s(v: &Vector2<f32>, s: f32) -> Vector2<f32> { Vector2::<f32> { x: s * v.y, y: -s * v.x, } } /// Performs the cross product on a scalar and a vector. In 2D this produces a vector. pub fn cross_s_v(s: f32, v: &Vector2<f32>) -> Vector2<f32> { Vector2::<f32> { x: -s * v.y, y: s * v.x, } } pub fn clamp_f32(s: f32, low: f32, high: f32) -> f32
#[derive(Clone, Copy, Debug)] pub struct Rotation2d { sin: f32, cos: f32, } impl Default for Rotation2d { /// Constructs a new identity rotation. fn default() -> Rotation2d { Rotation2d { sin: 0.0, cos: 1.0, } } } impl Rotation2d { /// Constructs a new rotation from an angle. pub fn new(angle: f32) -> Self { Rotation2d { sin: angle.sin(), cos: angle.cos(), } } /// Sets the rotation from an angle. pub fn set_angle(&mut self, angle: f32) { self.sin = angle.sin(); self.cos = angle.cos(); } /// Returns the angle in radians. pub fn get_angle(&self) -> f32 { f32::atan2(self.sin, self.cos) } /// Multiplies this rotation with the supplied one. pub fn mul(&self, rhs: &Rotation2d) -> Rotation2d { // q = self, r = rhs // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] Rotation2d { sin: self.sin * rhs.cos + self.cos * rhs.sin, cos: self.cos * rhs.cos - self.sin * rhs.sin, } } /// Multiplies the transpose of this rotation with the supplied one pub fn mul_t(&self, rhs: &Rotation2d) -> Rotation2d { // q = self, r = rhs // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] Rotation2d { sin: self.cos * rhs.sin - self.sin * rhs.cos, cos: self.cos * rhs.cos + self.sin * rhs.sin, } } /// Rotates a vector pub fn apply(&self, v: &Vector2<f32>) -> Vector2<f32> { // q = self // [qc -qs] * [x] = [qc*x - qs*y] // [qs qc] [y] [qs*x + qc*y] Vector2::<f32> { x: self.cos * v.x - self.sin * v.y, y: self.sin * v.x + self.cos * v.y, } } /// Inverse rotates a vector pub fn apply_t(&self, v: &Vector2<f32>) -> Vector2<f32> { // q = self // [ qc qs] * [x] = [qc*x + qs*y] // [-qs qc] [y] [qs*x + qc*y] Vector2::<f32> { x: self.cos * v.x + self.sin * v.y, y: -self.sin * v.x + self.cos * v.y, } } } /// A transform contains translation and rotation. It is used to represent the position /// and orientation of rigid frames. #[derive(Clone, Copy, Debug)] pub struct Transform2d { pub position: Vector2<f32>, pub rotation: Rotation2d, } impl Default for Transform2d { /// Constructs a new identity transform. fn default() -> Transform2d { Transform2d { position: Vector2::zero(), rotation: Default::default(), } } } impl Transform2d { /// Constructs a new transform with the given position and rotation. pub fn new(position: Vector2<f32>, rotation: Rotation2d) -> Self { Transform2d { position: position, rotation: rotation, } } pub fn mul(&self, rhs: &Transform2d) -> Transform2d { Transform2d { position: self.rotation.apply(&rhs.position) + self.position, rotation: self.rotation.mul(&rhs.rotation), } } pub fn mul_t(&self, rhs: &Transform2d) -> Transform2d { Transform2d { position: self.rotation.apply_t(&(rhs.position - self.position)), rotation: self.rotation.mul_t(&rhs.rotation), } } pub fn apply(&self, v: &Vector2<f32>) -> Vector2<f32> { Vector2::<f32> { x: self.rotation.cos * v.x - self.rotation.sin * v.y + self.position.x, y: self.rotation.sin * v.x + self.rotation.cos * v.y + self.position.y, } } pub fn apply_t(&self, v: &Vector2<f32>) -> Vector2<f32> { let p = v - self.position; Vector2::<f32> { x: self.rotation.cos * p.x + self.rotation.sin * p.y, y: -self.rotation.sin * p.x + self.rotation.cos * p.y, } } } /// This describes the motion of a body/shape for TOI computation. Shapes are defined /// with respect to the body origin, which may not coincide with the center of mass. /// However, to support dynamics we must interpolate the center of mass position. #[derive(Clone, Copy)] pub struct Sweep { /// Local center of mass position pub local_center: Vector2<f32>, /// center world position at `alpha0` pub c0: Vector2<f32>, /// center world position pub c: Vector2<f32>, /// world angle at `alpha0` pub a0: f32, /// world angle pub a: f32, /// Fraction of the current time step in the range [0, 1] pub alpha0: f32, } impl Default for Sweep { fn default() -> Sweep { Sweep { local_center: Vector2::zero(), c0: Vector2::zero(), c: Vector2::zero(), a0: 0.0, a: 0.0, alpha0: 0.0, } } } impl Sweep { /// Get the interpolated transform at a specific time. `beta` is a factor in [0, 1], /// where 0 indicates `alpha0` pub fn get_transform(&self, beta: f32) -> Transform2d { let mut result = Transform2d::new( self.c0 * (1.0 - beta) + self.c * beta, Rotation2d::new(self.a0 * (1.0 - beta) + self.a * beta), ); /*let mut result = Transform2d::default(); result.position = self.c0 * (1.0 - beta) + self.c * beta; result.rotation.set_angle(self.a0 * (1.0 - beta) + self.a * beta);*/ // Shift to origin. result.position -= result.rotation.apply(&self.local_center); result } /// Advance the sweep forward, yielding a new initial state. `alpha` is the new /// initial time. pub fn advance(&mut self, alpha: f32) { assert!(self.alpha0 < 1.0); let beta = (alpha - self.alpha0) / (1.0 - self.alpha0); self.c0 += (self.c - self.c0) * beta; self.a0 += (self.a - self.a0) * beta; self.alpha0 = alpha; } /// Normalize the angles. pub fn normalize(&mut self) { let two_pi = 2.0 * f32::consts::PI; let d = two_pi * (self.a0 / two_pi).floor(); self.a0 -= d; self.a -= d; } }
{ f32::max(low, f32::min(s, high)) }
identifier_body
tup.rs
//! A tuple for pattern matching purposes, until vector pattern matching is enabled in stable. //! //! This code is not very pretty at all but it compiles without enabling any experimental features. #[derive(Debug)] pub enum Tup<A,B,C,D,E,F,G,H,I> { T0, T1(A), T2(A, B), T3(A, B, C), T4(A, B, C, D), T5(A, B, C, D, E), T6(A, B, C, D, E, F), T7(A, B, C, D, E, F, G), T8(A, B, C, D, E, F, G, H), T9(A, B, C, D, E, F, G, H, I), } pub type TupT<T> = Tup<T,T,T,T,T,T,T,T,T>; pub fn vec_to_tup<T: Clone>(vec: &Vec<T>) -> Option<Tup<T,T,T,T,T,T,T,T,T>> { match vec.len() { 0 => Some(Tup::T0),
5 => Some(Tup::T5(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone())), 6 => Some(Tup::T6(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone())), 7 => Some(Tup::T7(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone(), vec[6].clone())), 8 => Some(Tup::T8(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone(), vec[6].clone(), vec[7].clone())), 9 => Some(Tup::T9(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone(), vec[6].clone(), vec[7].clone(), vec[8].clone())), _ => None, } }
1 => Some(Tup::T1(vec[0].clone())), 2 => Some(Tup::T2(vec[0].clone(), vec[1].clone())), 3 => Some(Tup::T3(vec[0].clone(), vec[1].clone(), vec[2].clone())), 4 => Some(Tup::T4(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone())),
random_line_split
tup.rs
//! A tuple for pattern matching purposes, until vector pattern matching is enabled in stable. //! //! This code is not very pretty at all but it compiles without enabling any experimental features. #[derive(Debug)] pub enum
<A,B,C,D,E,F,G,H,I> { T0, T1(A), T2(A, B), T3(A, B, C), T4(A, B, C, D), T5(A, B, C, D, E), T6(A, B, C, D, E, F), T7(A, B, C, D, E, F, G), T8(A, B, C, D, E, F, G, H), T9(A, B, C, D, E, F, G, H, I), } pub type TupT<T> = Tup<T,T,T,T,T,T,T,T,T>; pub fn vec_to_tup<T: Clone>(vec: &Vec<T>) -> Option<Tup<T,T,T,T,T,T,T,T,T>> { match vec.len() { 0 => Some(Tup::T0), 1 => Some(Tup::T1(vec[0].clone())), 2 => Some(Tup::T2(vec[0].clone(), vec[1].clone())), 3 => Some(Tup::T3(vec[0].clone(), vec[1].clone(), vec[2].clone())), 4 => Some(Tup::T4(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone())), 5 => Some(Tup::T5(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone())), 6 => Some(Tup::T6(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone())), 7 => Some(Tup::T7(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone(), vec[6].clone())), 8 => Some(Tup::T8(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone(), vec[6].clone(), vec[7].clone())), 9 => Some(Tup::T9(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone(), vec[6].clone(), vec[7].clone(), vec[8].clone())), _ => None, } }
Tup
identifier_name
classes.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct cat { meows : uint, how_hungry : int, name : String, } impl cat { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl cat { fn
(&mut self) { println!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let mut nyan = cat(0u, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
meow
identifier_name
classes.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct cat { meows : uint, how_hungry : int, name : String, } impl cat { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else
} } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let mut nyan = cat(0u, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
{ println!("Not hungry!"); return false; }
conditional_block
classes.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct cat { meows : uint, how_hungry : int, name : String, } impl cat { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl cat { fn meow(&mut self)
} fn cat(in_x : uint, in_y : int, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let mut nyan = cat(0u, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
{ println!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } }
identifier_body
classes.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct cat { meows : uint, how_hungry : int, name : String, } impl cat { pub fn speak(&mut self) { self.meow(); } pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } }
meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let mut nyan = cat(0u, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
} fn cat(in_x : uint, in_y : int, in_name: String) -> cat { cat {
random_line_split
save.rs
#[cfg(test)] #[path = "./save_tests.rs"] pub mod save_tests; use arrayvec::ArrayVec; use dice::Dice; pub fn save( dice: &mut Dice, save: Option<i32>, rend: i32, reroll_save_triggers: ArrayVec<[fn(i32, i32) -> bool; ::MAX_CALLBACKS]>, ) -> bool { match save { Some(save) => { let mut save_roll = dice.roll_d6() as i32; let modified_save = save - rend; if reroll_save_triggers.into_iter().any(|trigger| trigger(save_roll, modified_save)) { save_roll = dice.roll_d6() as i32; } let save_roll = save_roll; if save_roll == 1 { false } else
}, None => false, } }
{ save_roll >= modified_save }
conditional_block
save.rs
#[cfg(test)] #[path = "./save_tests.rs"] pub mod save_tests; use arrayvec::ArrayVec; use dice::Dice; pub fn save( dice: &mut Dice, save: Option<i32>, rend: i32, reroll_save_triggers: ArrayVec<[fn(i32, i32) -> bool; ::MAX_CALLBACKS]>, ) -> bool { match save { Some(save) => {
let save_roll = save_roll; if save_roll == 1 { false } else { save_roll >= modified_save } }, None => false, } }
let mut save_roll = dice.roll_d6() as i32; let modified_save = save - rend; if reroll_save_triggers.into_iter().any(|trigger| trigger(save_roll, modified_save)) { save_roll = dice.roll_d6() as i32; }
random_line_split
save.rs
#[cfg(test)] #[path = "./save_tests.rs"] pub mod save_tests; use arrayvec::ArrayVec; use dice::Dice; pub fn save( dice: &mut Dice, save: Option<i32>, rend: i32, reroll_save_triggers: ArrayVec<[fn(i32, i32) -> bool; ::MAX_CALLBACKS]>, ) -> bool
{ match save { Some(save) => { let mut save_roll = dice.roll_d6() as i32; let modified_save = save - rend; if reroll_save_triggers.into_iter().any(|trigger| trigger(save_roll, modified_save)) { save_roll = dice.roll_d6() as i32; } let save_roll = save_roll; if save_roll == 1 { false } else { save_roll >= modified_save } }, None => false, } }
identifier_body
save.rs
#[cfg(test)] #[path = "./save_tests.rs"] pub mod save_tests; use arrayvec::ArrayVec; use dice::Dice; pub fn
( dice: &mut Dice, save: Option<i32>, rend: i32, reroll_save_triggers: ArrayVec<[fn(i32, i32) -> bool; ::MAX_CALLBACKS]>, ) -> bool { match save { Some(save) => { let mut save_roll = dice.roll_d6() as i32; let modified_save = save - rend; if reroll_save_triggers.into_iter().any(|trigger| trigger(save_roll, modified_save)) { save_roll = dice.roll_d6() as i32; } let save_roll = save_roll; if save_roll == 1 { false } else { save_roll >= modified_save } }, None => false, } }
save
identifier_name
lru_cache.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A cache that holds a limited number of key-value pairs. When the //! capacity of the cache is exceeded, the least-recently-used //! (where "used" means a look-up or putting the pair into the cache) //! pair is automatically removed. //! //! # Example //! //! ```rust //! use collections::LruCache; //! //! let mut cache: LruCache<int, int> = LruCache::new(2); //! cache.put(1, 10); //! cache.put(2, 20); //! cache.put(3, 30); //! assert!(cache.get(&1).is_none()); //! assert_eq!(*cache.get(&2).unwrap(), 20); //! assert_eq!(*cache.get(&3).unwrap(), 30); //! //! cache.put(2, 22); //! assert_eq!(*cache.get(&2).unwrap(), 22); //! //! cache.put(6, 60); //! assert!(cache.get(&3).is_none()); //! //! cache.change_capacity(1); //! assert!(cache.get(&2).is_none()); //! ``` use std::cast; use std::container::Container; use std::hash::Hash; use std::fmt; use std::mem; use std::ptr; use HashMap; struct KeyRef<K> { k: *K } struct LruEntry<K, V> { next: *mut LruEntry<K, V>, prev: *mut LruEntry<K, V>, key: K, value: V, } /// An LRU Cache. pub struct LruCache<K, V> { map: HashMap<KeyRef<K>, Box<LruEntry<K, V>>>, max_size: uint, head: *mut LruEntry<K, V>, } impl<S, K: Hash<S>> Hash<S> for KeyRef<K> { fn hash(&self, state: &mut S) { unsafe { (*self.k).hash(state) } } } impl<K: Eq> Eq for KeyRef<K> { fn eq(&self, other: &KeyRef<K>) -> bool { unsafe{ (*self.k).eq(&*other.k) } } } impl<K: TotalEq> TotalEq for KeyRef<K> {} impl<K, V> LruEntry<K, V> { fn new(k: K, v: V) -> LruEntry<K, V> { LruEntry { key: k, value: v, next: ptr::mut_null(), prev: ptr::mut_null(), } } } impl<K: Hash + TotalEq, V> LruCache<K, V> { /// Create an LRU Cache that holds at most `capacity` items. pub fn new(capacity: uint) -> LruCache<K, V> { let cache = LruCache { map: HashMap::new(), max_size: capacity, head: unsafe{ cast::transmute(box mem::uninit::<LruEntry<K, V>>()) }, }; unsafe { (*cache.head).next = cache.head; (*cache.head).prev = cache.head; } return cache; } /// Put a key-value pair into cache. pub fn put(&mut self, k: K, v: V) { let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) { Some(node) => { node.value = v; let node_ptr: *mut LruEntry<K, V> = &mut **node; (node_ptr, None) } None => { let mut node = box LruEntry::new(k, v); let node_ptr: *mut LruEntry<K, V> = &mut *node; (node_ptr, Some(node)) } }; match node_opt { None => { // Existing node, just update LRU position self.detach(node_ptr); self.attach(node_ptr); } Some(node) => { let keyref = unsafe { &(*node_ptr).key }; self.map.swap(KeyRef{k: keyref}, node); self.attach(node_ptr); if self.len() > self.capacity() { self.remove_lru(); } } } } /// Return a value corresponding to the key in the cache. pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> { let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) { None => (None, None), Some(node) => { let node_ptr: *mut LruEntry<K, V> = &mut **node; (Some(unsafe { &(*node_ptr).value }), Some(node_ptr)) } }; match node_ptr_opt { None => (), Some(node_ptr) => { self.detach(node_ptr); self.attach(node_ptr); } } return value; } /// Remove and return a value corresponding to the key from the cache. pub fn pop(&mut self, k: &K) -> Option<V> { match self.map.pop(&KeyRef{k: k}) { None => None, Some(lru_entry) => Some(lru_entry.value) } } /// Return the maximum number of key-value pairs the cache can hold. pub fn capacity(&self) -> uint
/// Change the number of key-value pairs the cache can hold. Remove /// least-recently-used key-value pairs if necessary. pub fn change_capacity(&mut self, capacity: uint) { for _ in range(capacity, self.len()) { self.remove_lru(); } self.max_size = capacity; } #[inline] fn remove_lru(&mut self) { if self.len() > 0 { let lru = unsafe { (*self.head).prev }; self.detach(lru); self.map.pop(&KeyRef{k: unsafe { &(*lru).key }}); } } #[inline] fn detach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*(*node).prev).next = (*node).next; (*(*node).next).prev = (*node).prev; } } #[inline] fn attach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*node).next = (*self.head).next; (*node).prev = self.head; (*self.head).next = node; (*(*node).next).prev = node; } } } impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> { /// Return a string that lists the key-value pairs from most-recently /// used to least-recently used. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f.buf, r"\{")); let mut cur = self.head; for i in range(0, self.len()) { if i > 0 { try!(write!(f.buf, ", ")) } unsafe { cur = (*cur).next; try!(write!(f.buf, "{}", (*cur).key)); } try!(write!(f.buf, ": ")); unsafe { try!(write!(f.buf, "{}", (*cur).value)); } } write!(f.buf, r"\}") } } impl<K: Hash + TotalEq, V> Container for LruCache<K, V> { /// Return the number of key-value pairs in the cache. fn len(&self) -> uint { self.map.len() } } impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> { /// Clear the cache of all key-value pairs. fn clear(&mut self) { self.map.clear(); } } #[unsafe_destructor] impl<K, V> Drop for LruCache<K, V> { fn drop(&mut self) { unsafe { let node: Box<LruEntry<K, V>> = cast::transmute(self.head); // Prevent compiler from trying to drop the un-initialized field in the sigil node. let box LruEntry { key: k, value: v,.. } = node; cast::forget(k); cast::forget(v); } } } #[cfg(test)] mod tests { use super::LruCache; fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) { assert!(opt.is_some()); assert!(opt.unwrap() == &v); } #[test] fn test_put_and_get() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); assert_opt_eq(cache.get(&1), 10); assert_opt_eq(cache.get(&2), 20); assert_eq!(cache.len(), 2); } #[test] fn test_put_update() { let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1); cache.put("1".to_owned(), vec![10, 10]); cache.put("1".to_owned(), vec![10, 19]); assert_opt_eq(cache.get(&"1".to_owned()), vec![10, 19]); assert_eq!(cache.len(), 1); } #[test] fn test_expire_lru() { let mut cache: LruCache<~str, ~str> = LruCache::new(2); cache.put("foo1".to_owned(), "bar1".to_owned()); cache.put("foo2".to_owned(), "bar2".to_owned()); cache.put("foo3".to_owned(), "bar3".to_owned()); assert!(cache.get(&"foo1".to_owned()).is_none()); cache.put("foo2".to_owned(), "bar2update".to_owned()); cache.put("foo4".to_owned(), "bar4".to_owned()); assert!(cache.get(&"foo3".to_owned()).is_none()); } #[test] fn test_pop() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); assert_eq!(cache.len(), 2); let opt1 = cache.pop(&1); assert!(opt1.is_some()); assert_eq!(opt1.unwrap(), 10); assert!(cache.get(&1).is_none()); assert_eq!(cache.len(), 1); } #[test] fn test_change_capacity() { let mut cache: LruCache<int, int> = LruCache::new(2); assert_eq!(cache.capacity(), 2); cache.put(1, 10); cache.put(2, 20); cache.change_capacity(1); assert!(cache.get(&1).is_none()); assert_eq!(cache.capacity(), 1); } #[test] fn test_to_str() { let mut cache: LruCache<int, int> = LruCache::new(3); cache.put(1, 10); cache.put(2, 20); cache.put(3, 30); assert_eq!(cache.to_str(), "{3: 30, 2: 20, 1: 10}".to_owned()); cache.put(2, 22); assert_eq!(cache.to_str(), "{2: 22, 3: 30, 1: 10}".to_owned()); cache.put(6, 60); assert_eq!(cache.to_str(), "{6: 60, 2: 22, 3: 30}".to_owned()); cache.get(&3); assert_eq!(cache.to_str(), "{3: 30, 6: 60, 2: 22}".to_owned()); cache.change_capacity(2); assert_eq!(cache.to_str(), "{3: 30, 6: 60}".to_owned()); } #[test] fn test_clear() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); cache.clear(); assert!(cache.get(&1).is_none()); assert!(cache.get(&2).is_none()); assert_eq!(cache.to_str(), "{}".to_owned()); } }
{ self.max_size }
identifier_body
lru_cache.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A cache that holds a limited number of key-value pairs. When the //! capacity of the cache is exceeded, the least-recently-used //! (where "used" means a look-up or putting the pair into the cache) //! pair is automatically removed. //! //! # Example //! //! ```rust //! use collections::LruCache; //! //! let mut cache: LruCache<int, int> = LruCache::new(2); //! cache.put(1, 10); //! cache.put(2, 20); //! cache.put(3, 30); //! assert!(cache.get(&1).is_none()); //! assert_eq!(*cache.get(&2).unwrap(), 20); //! assert_eq!(*cache.get(&3).unwrap(), 30); //! //! cache.put(2, 22); //! assert_eq!(*cache.get(&2).unwrap(), 22); //! //! cache.put(6, 60); //! assert!(cache.get(&3).is_none()); //! //! cache.change_capacity(1); //! assert!(cache.get(&2).is_none()); //! ``` use std::cast; use std::container::Container; use std::hash::Hash; use std::fmt; use std::mem; use std::ptr; use HashMap; struct KeyRef<K> { k: *K } struct LruEntry<K, V> { next: *mut LruEntry<K, V>, prev: *mut LruEntry<K, V>, key: K, value: V, } /// An LRU Cache. pub struct LruCache<K, V> { map: HashMap<KeyRef<K>, Box<LruEntry<K, V>>>, max_size: uint, head: *mut LruEntry<K, V>, } impl<S, K: Hash<S>> Hash<S> for KeyRef<K> { fn hash(&self, state: &mut S) { unsafe { (*self.k).hash(state) } } } impl<K: Eq> Eq for KeyRef<K> { fn eq(&self, other: &KeyRef<K>) -> bool { unsafe{ (*self.k).eq(&*other.k) } } } impl<K: TotalEq> TotalEq for KeyRef<K> {} impl<K, V> LruEntry<K, V> { fn new(k: K, v: V) -> LruEntry<K, V> { LruEntry { key: k, value: v, next: ptr::mut_null(), prev: ptr::mut_null(), } } } impl<K: Hash + TotalEq, V> LruCache<K, V> { /// Create an LRU Cache that holds at most `capacity` items. pub fn new(capacity: uint) -> LruCache<K, V> { let cache = LruCache { map: HashMap::new(), max_size: capacity, head: unsafe{ cast::transmute(box mem::uninit::<LruEntry<K, V>>()) }, }; unsafe { (*cache.head).next = cache.head; (*cache.head).prev = cache.head; } return cache; } /// Put a key-value pair into cache. pub fn put(&mut self, k: K, v: V) { let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) { Some(node) => { node.value = v; let node_ptr: *mut LruEntry<K, V> = &mut **node; (node_ptr, None) } None => { let mut node = box LruEntry::new(k, v); let node_ptr: *mut LruEntry<K, V> = &mut *node; (node_ptr, Some(node)) } }; match node_opt { None => { // Existing node, just update LRU position self.detach(node_ptr); self.attach(node_ptr); } Some(node) => { let keyref = unsafe { &(*node_ptr).key }; self.map.swap(KeyRef{k: keyref}, node); self.attach(node_ptr); if self.len() > self.capacity() { self.remove_lru(); } } } } /// Return a value corresponding to the key in the cache. pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> { let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) { None => (None, None), Some(node) => { let node_ptr: *mut LruEntry<K, V> = &mut **node; (Some(unsafe { &(*node_ptr).value }), Some(node_ptr)) } }; match node_ptr_opt { None => (), Some(node_ptr) => { self.detach(node_ptr); self.attach(node_ptr); } } return value; } /// Remove and return a value corresponding to the key from the cache. pub fn pop(&mut self, k: &K) -> Option<V> { match self.map.pop(&KeyRef{k: k}) { None => None, Some(lru_entry) => Some(lru_entry.value) } } /// Return the maximum number of key-value pairs the cache can hold. pub fn capacity(&self) -> uint { self.max_size } /// Change the number of key-value pairs the cache can hold. Remove /// least-recently-used key-value pairs if necessary. pub fn change_capacity(&mut self, capacity: uint) { for _ in range(capacity, self.len()) { self.remove_lru(); } self.max_size = capacity; } #[inline] fn remove_lru(&mut self) { if self.len() > 0 { let lru = unsafe { (*self.head).prev }; self.detach(lru); self.map.pop(&KeyRef{k: unsafe { &(*lru).key }}); } } #[inline] fn detach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*(*node).prev).next = (*node).next; (*(*node).next).prev = (*node).prev; } } #[inline] fn attach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*node).next = (*self.head).next; (*node).prev = self.head; (*self.head).next = node; (*(*node).next).prev = node; } } } impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> { /// Return a string that lists the key-value pairs from most-recently /// used to least-recently used. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f.buf, r"\{")); let mut cur = self.head; for i in range(0, self.len()) { if i > 0 { try!(write!(f.buf, ", ")) } unsafe { cur = (*cur).next; try!(write!(f.buf, "{}", (*cur).key)); } try!(write!(f.buf, ": ")); unsafe { try!(write!(f.buf, "{}", (*cur).value)); } } write!(f.buf, r"\}") } } impl<K: Hash + TotalEq, V> Container for LruCache<K, V> { /// Return the number of key-value pairs in the cache. fn
(&self) -> uint { self.map.len() } } impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> { /// Clear the cache of all key-value pairs. fn clear(&mut self) { self.map.clear(); } } #[unsafe_destructor] impl<K, V> Drop for LruCache<K, V> { fn drop(&mut self) { unsafe { let node: Box<LruEntry<K, V>> = cast::transmute(self.head); // Prevent compiler from trying to drop the un-initialized field in the sigil node. let box LruEntry { key: k, value: v,.. } = node; cast::forget(k); cast::forget(v); } } } #[cfg(test)] mod tests { use super::LruCache; fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) { assert!(opt.is_some()); assert!(opt.unwrap() == &v); } #[test] fn test_put_and_get() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); assert_opt_eq(cache.get(&1), 10); assert_opt_eq(cache.get(&2), 20); assert_eq!(cache.len(), 2); } #[test] fn test_put_update() { let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1); cache.put("1".to_owned(), vec![10, 10]); cache.put("1".to_owned(), vec![10, 19]); assert_opt_eq(cache.get(&"1".to_owned()), vec![10, 19]); assert_eq!(cache.len(), 1); } #[test] fn test_expire_lru() { let mut cache: LruCache<~str, ~str> = LruCache::new(2); cache.put("foo1".to_owned(), "bar1".to_owned()); cache.put("foo2".to_owned(), "bar2".to_owned()); cache.put("foo3".to_owned(), "bar3".to_owned()); assert!(cache.get(&"foo1".to_owned()).is_none()); cache.put("foo2".to_owned(), "bar2update".to_owned()); cache.put("foo4".to_owned(), "bar4".to_owned()); assert!(cache.get(&"foo3".to_owned()).is_none()); } #[test] fn test_pop() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); assert_eq!(cache.len(), 2); let opt1 = cache.pop(&1); assert!(opt1.is_some()); assert_eq!(opt1.unwrap(), 10); assert!(cache.get(&1).is_none()); assert_eq!(cache.len(), 1); } #[test] fn test_change_capacity() { let mut cache: LruCache<int, int> = LruCache::new(2); assert_eq!(cache.capacity(), 2); cache.put(1, 10); cache.put(2, 20); cache.change_capacity(1); assert!(cache.get(&1).is_none()); assert_eq!(cache.capacity(), 1); } #[test] fn test_to_str() { let mut cache: LruCache<int, int> = LruCache::new(3); cache.put(1, 10); cache.put(2, 20); cache.put(3, 30); assert_eq!(cache.to_str(), "{3: 30, 2: 20, 1: 10}".to_owned()); cache.put(2, 22); assert_eq!(cache.to_str(), "{2: 22, 3: 30, 1: 10}".to_owned()); cache.put(6, 60); assert_eq!(cache.to_str(), "{6: 60, 2: 22, 3: 30}".to_owned()); cache.get(&3); assert_eq!(cache.to_str(), "{3: 30, 6: 60, 2: 22}".to_owned()); cache.change_capacity(2); assert_eq!(cache.to_str(), "{3: 30, 6: 60}".to_owned()); } #[test] fn test_clear() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); cache.clear(); assert!(cache.get(&1).is_none()); assert!(cache.get(&2).is_none()); assert_eq!(cache.to_str(), "{}".to_owned()); } }
len
identifier_name
lru_cache.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A cache that holds a limited number of key-value pairs. When the //! capacity of the cache is exceeded, the least-recently-used //! (where "used" means a look-up or putting the pair into the cache) //! pair is automatically removed. //! //! # Example //! //! ```rust //! use collections::LruCache; //! //! let mut cache: LruCache<int, int> = LruCache::new(2); //! cache.put(1, 10); //! cache.put(2, 20); //! cache.put(3, 30); //! assert!(cache.get(&1).is_none()); //! assert_eq!(*cache.get(&2).unwrap(), 20); //! assert_eq!(*cache.get(&3).unwrap(), 30); //! //! cache.put(2, 22); //! assert_eq!(*cache.get(&2).unwrap(), 22); //! //! cache.put(6, 60); //! assert!(cache.get(&3).is_none()); //! //! cache.change_capacity(1); //! assert!(cache.get(&2).is_none()); //! ``` use std::cast; use std::container::Container; use std::hash::Hash; use std::fmt; use std::mem; use std::ptr; use HashMap; struct KeyRef<K> { k: *K } struct LruEntry<K, V> { next: *mut LruEntry<K, V>, prev: *mut LruEntry<K, V>, key: K, value: V, } /// An LRU Cache. pub struct LruCache<K, V> { map: HashMap<KeyRef<K>, Box<LruEntry<K, V>>>, max_size: uint, head: *mut LruEntry<K, V>, } impl<S, K: Hash<S>> Hash<S> for KeyRef<K> { fn hash(&self, state: &mut S) { unsafe { (*self.k).hash(state) } } } impl<K: Eq> Eq for KeyRef<K> { fn eq(&self, other: &KeyRef<K>) -> bool { unsafe{ (*self.k).eq(&*other.k) } } } impl<K: TotalEq> TotalEq for KeyRef<K> {} impl<K, V> LruEntry<K, V> { fn new(k: K, v: V) -> LruEntry<K, V> { LruEntry { key: k, value: v, next: ptr::mut_null(), prev: ptr::mut_null(), } } } impl<K: Hash + TotalEq, V> LruCache<K, V> { /// Create an LRU Cache that holds at most `capacity` items. pub fn new(capacity: uint) -> LruCache<K, V> { let cache = LruCache { map: HashMap::new(), max_size: capacity, head: unsafe{ cast::transmute(box mem::uninit::<LruEntry<K, V>>()) }, }; unsafe { (*cache.head).next = cache.head; (*cache.head).prev = cache.head; } return cache; } /// Put a key-value pair into cache. pub fn put(&mut self, k: K, v: V) { let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) { Some(node) => { node.value = v; let node_ptr: *mut LruEntry<K, V> = &mut **node; (node_ptr, None) } None => { let mut node = box LruEntry::new(k, v); let node_ptr: *mut LruEntry<K, V> = &mut *node; (node_ptr, Some(node)) } }; match node_opt { None =>
Some(node) => { let keyref = unsafe { &(*node_ptr).key }; self.map.swap(KeyRef{k: keyref}, node); self.attach(node_ptr); if self.len() > self.capacity() { self.remove_lru(); } } } } /// Return a value corresponding to the key in the cache. pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> { let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) { None => (None, None), Some(node) => { let node_ptr: *mut LruEntry<K, V> = &mut **node; (Some(unsafe { &(*node_ptr).value }), Some(node_ptr)) } }; match node_ptr_opt { None => (), Some(node_ptr) => { self.detach(node_ptr); self.attach(node_ptr); } } return value; } /// Remove and return a value corresponding to the key from the cache. pub fn pop(&mut self, k: &K) -> Option<V> { match self.map.pop(&KeyRef{k: k}) { None => None, Some(lru_entry) => Some(lru_entry.value) } } /// Return the maximum number of key-value pairs the cache can hold. pub fn capacity(&self) -> uint { self.max_size } /// Change the number of key-value pairs the cache can hold. Remove /// least-recently-used key-value pairs if necessary. pub fn change_capacity(&mut self, capacity: uint) { for _ in range(capacity, self.len()) { self.remove_lru(); } self.max_size = capacity; } #[inline] fn remove_lru(&mut self) { if self.len() > 0 { let lru = unsafe { (*self.head).prev }; self.detach(lru); self.map.pop(&KeyRef{k: unsafe { &(*lru).key }}); } } #[inline] fn detach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*(*node).prev).next = (*node).next; (*(*node).next).prev = (*node).prev; } } #[inline] fn attach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*node).next = (*self.head).next; (*node).prev = self.head; (*self.head).next = node; (*(*node).next).prev = node; } } } impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> { /// Return a string that lists the key-value pairs from most-recently /// used to least-recently used. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f.buf, r"\{")); let mut cur = self.head; for i in range(0, self.len()) { if i > 0 { try!(write!(f.buf, ", ")) } unsafe { cur = (*cur).next; try!(write!(f.buf, "{}", (*cur).key)); } try!(write!(f.buf, ": ")); unsafe { try!(write!(f.buf, "{}", (*cur).value)); } } write!(f.buf, r"\}") } } impl<K: Hash + TotalEq, V> Container for LruCache<K, V> { /// Return the number of key-value pairs in the cache. fn len(&self) -> uint { self.map.len() } } impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> { /// Clear the cache of all key-value pairs. fn clear(&mut self) { self.map.clear(); } } #[unsafe_destructor] impl<K, V> Drop for LruCache<K, V> { fn drop(&mut self) { unsafe { let node: Box<LruEntry<K, V>> = cast::transmute(self.head); // Prevent compiler from trying to drop the un-initialized field in the sigil node. let box LruEntry { key: k, value: v,.. } = node; cast::forget(k); cast::forget(v); } } } #[cfg(test)] mod tests { use super::LruCache; fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) { assert!(opt.is_some()); assert!(opt.unwrap() == &v); } #[test] fn test_put_and_get() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); assert_opt_eq(cache.get(&1), 10); assert_opt_eq(cache.get(&2), 20); assert_eq!(cache.len(), 2); } #[test] fn test_put_update() { let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1); cache.put("1".to_owned(), vec![10, 10]); cache.put("1".to_owned(), vec![10, 19]); assert_opt_eq(cache.get(&"1".to_owned()), vec![10, 19]); assert_eq!(cache.len(), 1); } #[test] fn test_expire_lru() { let mut cache: LruCache<~str, ~str> = LruCache::new(2); cache.put("foo1".to_owned(), "bar1".to_owned()); cache.put("foo2".to_owned(), "bar2".to_owned()); cache.put("foo3".to_owned(), "bar3".to_owned()); assert!(cache.get(&"foo1".to_owned()).is_none()); cache.put("foo2".to_owned(), "bar2update".to_owned()); cache.put("foo4".to_owned(), "bar4".to_owned()); assert!(cache.get(&"foo3".to_owned()).is_none()); } #[test] fn test_pop() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); assert_eq!(cache.len(), 2); let opt1 = cache.pop(&1); assert!(opt1.is_some()); assert_eq!(opt1.unwrap(), 10); assert!(cache.get(&1).is_none()); assert_eq!(cache.len(), 1); } #[test] fn test_change_capacity() { let mut cache: LruCache<int, int> = LruCache::new(2); assert_eq!(cache.capacity(), 2); cache.put(1, 10); cache.put(2, 20); cache.change_capacity(1); assert!(cache.get(&1).is_none()); assert_eq!(cache.capacity(), 1); } #[test] fn test_to_str() { let mut cache: LruCache<int, int> = LruCache::new(3); cache.put(1, 10); cache.put(2, 20); cache.put(3, 30); assert_eq!(cache.to_str(), "{3: 30, 2: 20, 1: 10}".to_owned()); cache.put(2, 22); assert_eq!(cache.to_str(), "{2: 22, 3: 30, 1: 10}".to_owned()); cache.put(6, 60); assert_eq!(cache.to_str(), "{6: 60, 2: 22, 3: 30}".to_owned()); cache.get(&3); assert_eq!(cache.to_str(), "{3: 30, 6: 60, 2: 22}".to_owned()); cache.change_capacity(2); assert_eq!(cache.to_str(), "{3: 30, 6: 60}".to_owned()); } #[test] fn test_clear() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); cache.clear(); assert!(cache.get(&1).is_none()); assert!(cache.get(&2).is_none()); assert_eq!(cache.to_str(), "{}".to_owned()); } }
{ // Existing node, just update LRU position self.detach(node_ptr); self.attach(node_ptr); }
conditional_block
lru_cache.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A cache that holds a limited number of key-value pairs. When the //! capacity of the cache is exceeded, the least-recently-used //! (where "used" means a look-up or putting the pair into the cache) //! pair is automatically removed. //! //! # Example //! //! ```rust //! use collections::LruCache; //! //! let mut cache: LruCache<int, int> = LruCache::new(2); //! cache.put(1, 10); //! cache.put(2, 20); //! cache.put(3, 30); //! assert!(cache.get(&1).is_none()); //! assert_eq!(*cache.get(&2).unwrap(), 20); //! assert_eq!(*cache.get(&3).unwrap(), 30); //! //! cache.put(2, 22); //! assert_eq!(*cache.get(&2).unwrap(), 22); //! //! cache.put(6, 60); //! assert!(cache.get(&3).is_none()); //! //! cache.change_capacity(1); //! assert!(cache.get(&2).is_none()); //! ``` use std::cast; use std::container::Container; use std::hash::Hash; use std::fmt; use std::mem; use std::ptr; use HashMap; struct KeyRef<K> { k: *K } struct LruEntry<K, V> { next: *mut LruEntry<K, V>, prev: *mut LruEntry<K, V>, key: K, value: V, } /// An LRU Cache. pub struct LruCache<K, V> { map: HashMap<KeyRef<K>, Box<LruEntry<K, V>>>, max_size: uint, head: *mut LruEntry<K, V>, } impl<S, K: Hash<S>> Hash<S> for KeyRef<K> { fn hash(&self, state: &mut S) { unsafe { (*self.k).hash(state) } } } impl<K: Eq> Eq for KeyRef<K> { fn eq(&self, other: &KeyRef<K>) -> bool { unsafe{ (*self.k).eq(&*other.k) } } } impl<K: TotalEq> TotalEq for KeyRef<K> {} impl<K, V> LruEntry<K, V> { fn new(k: K, v: V) -> LruEntry<K, V> { LruEntry { key: k, value: v, next: ptr::mut_null(), prev: ptr::mut_null(), } } } impl<K: Hash + TotalEq, V> LruCache<K, V> { /// Create an LRU Cache that holds at most `capacity` items. pub fn new(capacity: uint) -> LruCache<K, V> { let cache = LruCache { map: HashMap::new(), max_size: capacity, head: unsafe{ cast::transmute(box mem::uninit::<LruEntry<K, V>>()) }, }; unsafe { (*cache.head).next = cache.head; (*cache.head).prev = cache.head; } return cache; } /// Put a key-value pair into cache. pub fn put(&mut self, k: K, v: V) { let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) { Some(node) => { node.value = v; let node_ptr: *mut LruEntry<K, V> = &mut **node; (node_ptr, None) } None => { let mut node = box LruEntry::new(k, v); let node_ptr: *mut LruEntry<K, V> = &mut *node; (node_ptr, Some(node)) } }; match node_opt { None => { // Existing node, just update LRU position self.detach(node_ptr); self.attach(node_ptr); } Some(node) => { let keyref = unsafe { &(*node_ptr).key }; self.map.swap(KeyRef{k: keyref}, node); self.attach(node_ptr); if self.len() > self.capacity() { self.remove_lru(); } } } } /// Return a value corresponding to the key in the cache. pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> { let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) { None => (None, None), Some(node) => {
match node_ptr_opt { None => (), Some(node_ptr) => { self.detach(node_ptr); self.attach(node_ptr); } } return value; } /// Remove and return a value corresponding to the key from the cache. pub fn pop(&mut self, k: &K) -> Option<V> { match self.map.pop(&KeyRef{k: k}) { None => None, Some(lru_entry) => Some(lru_entry.value) } } /// Return the maximum number of key-value pairs the cache can hold. pub fn capacity(&self) -> uint { self.max_size } /// Change the number of key-value pairs the cache can hold. Remove /// least-recently-used key-value pairs if necessary. pub fn change_capacity(&mut self, capacity: uint) { for _ in range(capacity, self.len()) { self.remove_lru(); } self.max_size = capacity; } #[inline] fn remove_lru(&mut self) { if self.len() > 0 { let lru = unsafe { (*self.head).prev }; self.detach(lru); self.map.pop(&KeyRef{k: unsafe { &(*lru).key }}); } } #[inline] fn detach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*(*node).prev).next = (*node).next; (*(*node).next).prev = (*node).prev; } } #[inline] fn attach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*node).next = (*self.head).next; (*node).prev = self.head; (*self.head).next = node; (*(*node).next).prev = node; } } } impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> { /// Return a string that lists the key-value pairs from most-recently /// used to least-recently used. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f.buf, r"\{")); let mut cur = self.head; for i in range(0, self.len()) { if i > 0 { try!(write!(f.buf, ", ")) } unsafe { cur = (*cur).next; try!(write!(f.buf, "{}", (*cur).key)); } try!(write!(f.buf, ": ")); unsafe { try!(write!(f.buf, "{}", (*cur).value)); } } write!(f.buf, r"\}") } } impl<K: Hash + TotalEq, V> Container for LruCache<K, V> { /// Return the number of key-value pairs in the cache. fn len(&self) -> uint { self.map.len() } } impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> { /// Clear the cache of all key-value pairs. fn clear(&mut self) { self.map.clear(); } } #[unsafe_destructor] impl<K, V> Drop for LruCache<K, V> { fn drop(&mut self) { unsafe { let node: Box<LruEntry<K, V>> = cast::transmute(self.head); // Prevent compiler from trying to drop the un-initialized field in the sigil node. let box LruEntry { key: k, value: v,.. } = node; cast::forget(k); cast::forget(v); } } } #[cfg(test)] mod tests { use super::LruCache; fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) { assert!(opt.is_some()); assert!(opt.unwrap() == &v); } #[test] fn test_put_and_get() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); assert_opt_eq(cache.get(&1), 10); assert_opt_eq(cache.get(&2), 20); assert_eq!(cache.len(), 2); } #[test] fn test_put_update() { let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1); cache.put("1".to_owned(), vec![10, 10]); cache.put("1".to_owned(), vec![10, 19]); assert_opt_eq(cache.get(&"1".to_owned()), vec![10, 19]); assert_eq!(cache.len(), 1); } #[test] fn test_expire_lru() { let mut cache: LruCache<~str, ~str> = LruCache::new(2); cache.put("foo1".to_owned(), "bar1".to_owned()); cache.put("foo2".to_owned(), "bar2".to_owned()); cache.put("foo3".to_owned(), "bar3".to_owned()); assert!(cache.get(&"foo1".to_owned()).is_none()); cache.put("foo2".to_owned(), "bar2update".to_owned()); cache.put("foo4".to_owned(), "bar4".to_owned()); assert!(cache.get(&"foo3".to_owned()).is_none()); } #[test] fn test_pop() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); assert_eq!(cache.len(), 2); let opt1 = cache.pop(&1); assert!(opt1.is_some()); assert_eq!(opt1.unwrap(), 10); assert!(cache.get(&1).is_none()); assert_eq!(cache.len(), 1); } #[test] fn test_change_capacity() { let mut cache: LruCache<int, int> = LruCache::new(2); assert_eq!(cache.capacity(), 2); cache.put(1, 10); cache.put(2, 20); cache.change_capacity(1); assert!(cache.get(&1).is_none()); assert_eq!(cache.capacity(), 1); } #[test] fn test_to_str() { let mut cache: LruCache<int, int> = LruCache::new(3); cache.put(1, 10); cache.put(2, 20); cache.put(3, 30); assert_eq!(cache.to_str(), "{3: 30, 2: 20, 1: 10}".to_owned()); cache.put(2, 22); assert_eq!(cache.to_str(), "{2: 22, 3: 30, 1: 10}".to_owned()); cache.put(6, 60); assert_eq!(cache.to_str(), "{6: 60, 2: 22, 3: 30}".to_owned()); cache.get(&3); assert_eq!(cache.to_str(), "{3: 30, 6: 60, 2: 22}".to_owned()); cache.change_capacity(2); assert_eq!(cache.to_str(), "{3: 30, 6: 60}".to_owned()); } #[test] fn test_clear() { let mut cache: LruCache<int, int> = LruCache::new(2); cache.put(1, 10); cache.put(2, 20); cache.clear(); assert!(cache.get(&1).is_none()); assert!(cache.get(&2).is_none()); assert_eq!(cache.to_str(), "{}".to_owned()); } }
let node_ptr: *mut LruEntry<K, V> = &mut **node; (Some(unsafe { &(*node_ptr).value }), Some(node_ptr)) } };
random_line_split
027.rs
// Copyright (C) 2014 Jorge Aparicio extern crate num; use num::Integer; use std::iter::{count,range_inclusive}; fn main() { let limit = 999;
let len = prime_length(a, b); if len > max { max = len; ans = a * b; } } } println!("{}", ans); } fn prime_length(a:int, b: int) -> uint { count(0u, 1).skip_while(|&n| { let p = polyval(a, b, n as int); p > 1 && is_prime(p as uint) }).next().unwrap() } fn polyval(a: int, b: int, n: int) -> int { n * n + a * n + b } fn is_prime(n: uint) -> bool { let mut p = 2; loop { if p * p > n { break } if n % p == 0 { return false } p += if p.is_even() { 1 } else { 2 }; } true }
let (mut ans, mut max) = (0, 0); for a in range_inclusive(-limit, limit) { for b in range_inclusive(-limit, limit) {
random_line_split
027.rs
// Copyright (C) 2014 Jorge Aparicio extern crate num; use num::Integer; use std::iter::{count,range_inclusive}; fn main() { let limit = 999; let (mut ans, mut max) = (0, 0); for a in range_inclusive(-limit, limit) { for b in range_inclusive(-limit, limit) { let len = prime_length(a, b); if len > max { max = len; ans = a * b; } } } println!("{}", ans); } fn
(a:int, b: int) -> uint { count(0u, 1).skip_while(|&n| { let p = polyval(a, b, n as int); p > 1 && is_prime(p as uint) }).next().unwrap() } fn polyval(a: int, b: int, n: int) -> int { n * n + a * n + b } fn is_prime(n: uint) -> bool { let mut p = 2; loop { if p * p > n { break } if n % p == 0 { return false } p += if p.is_even() { 1 } else { 2 }; } true }
prime_length
identifier_name
027.rs
// Copyright (C) 2014 Jorge Aparicio extern crate num; use num::Integer; use std::iter::{count,range_inclusive}; fn main()
fn prime_length(a:int, b: int) -> uint { count(0u, 1).skip_while(|&n| { let p = polyval(a, b, n as int); p > 1 && is_prime(p as uint) }).next().unwrap() } fn polyval(a: int, b: int, n: int) -> int { n * n + a * n + b } fn is_prime(n: uint) -> bool { let mut p = 2; loop { if p * p > n { break } if n % p == 0 { return false } p += if p.is_even() { 1 } else { 2 }; } true }
{ let limit = 999; let (mut ans, mut max) = (0, 0); for a in range_inclusive(-limit, limit) { for b in range_inclusive(-limit, limit) { let len = prime_length(a, b); if len > max { max = len; ans = a * b; } } } println!("{}", ans); }
identifier_body
027.rs
// Copyright (C) 2014 Jorge Aparicio extern crate num; use num::Integer; use std::iter::{count,range_inclusive}; fn main() { let limit = 999; let (mut ans, mut max) = (0, 0); for a in range_inclusive(-limit, limit) { for b in range_inclusive(-limit, limit) { let len = prime_length(a, b); if len > max { max = len; ans = a * b; } } } println!("{}", ans); } fn prime_length(a:int, b: int) -> uint { count(0u, 1).skip_while(|&n| { let p = polyval(a, b, n as int); p > 1 && is_prime(p as uint) }).next().unwrap() } fn polyval(a: int, b: int, n: int) -> int { n * n + a * n + b } fn is_prime(n: uint) -> bool { let mut p = 2; loop { if p * p > n { break } if n % p == 0 { return false } p += if p.is_even()
else { 2 }; } true }
{ 1 }
conditional_block
mod.rs
#![allow(non_camel_case_types)] pub mod libtsm { use std::num::{FromPrimitive}; use libc::{c_void, c_uint, c_int, size_t, uint32_t, c_char}; use collections::enum_set::{EnumSet,CLike}; static RGB_LEVELS : &'static [u8] = &[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]; #[deriving(PartialEq,Show,Clone,FromPrimitive)] #[repr(u8)] pub enum AttributeFlags { Bold, Underline, Inverse, Protect, Blink } #[deriving(PartialEq,Show,Clone,FromPrimitive)] #[repr(u8)] pub enum ScreenFlags { TSM_SCREEN_INSERT_MODE, TSM_SCREEN_AUTO_WRAP, TSM_SCREEN_REL_ORIGIN, TSM_SCREEN_INVERSE, TSM_SCREEN_HIDE_CURSOR, TSM_SCREEN_FIXED_POS, TSM_SCREEN_ALTERNATE } impl CLike for AttributeFlags { fn to_uint(&self) -> uint { *self as uint } fn from_uint(v: uint) -> AttributeFlags { FromPrimitive::from_uint(v).expect("Decoding of uint into AttributeFlags failed!") } } impl CLike for ScreenFlags { fn to_uint(&self) -> uint { *self as uint } fn from_uint(v: uint) -> ScreenFlags { FromPrimitive::from_uint(v).expect("Decoding of uint into ScreenFlags failed!") } } #[deriving(PartialEq,Show,Clone)] pub struct tsm_screen_attr { pub fccode: i8, /* foreground color code or <0 for rgb */ pub bccode: i8, /* background color code or <0 for rgb */ pub fr: u8, /* foreground red */ pub fg: u8, /* foreground green */ pub fb: u8, /* foreground blue */ pub br: u8, /* background red */ pub bg: u8, /* background green */ pub bb: u8, /* background blue */ pub flags: EnumSet<AttributeFlags>, /* misc flags */ } fn get_color(code: i8, r: u8, g: u8, b: u8) -> Option<u8> { if code < 0 { Some(get_rgb_color(r, g, b)) } else if code >= 0 && code < 16 { Some(code.to_u8().unwrap()) } else { None } } fn get_rgb_color(r: u8, g: u8, b: u8) -> u8 { if r == g && g == b && (r - 8) % 10 == 0 { return 232 + (r - 8) / 10; } else { return 16 + get_rgb_index(r) * 36 + get_rgb_index(g) * 6 + get_rgb_index(b); } } fn get_rgb_index(value: u8) -> u8 { RGB_LEVELS.iter().position(|level| *level == value).expect("No index for value found").to_u8().unwrap() } impl tsm_screen_attr { pub fn get_fg(&self) -> Option<u8> { get_color(self.fccode, self.fr, self.fg, self.fb) } pub fn get_bg(&self) -> Option<u8> { get_color(self.bccode, self.br, self.bg, self.bb) } pub fn
(&self, flag: AttributeFlags) -> bool { self.flags.contains_elem(flag) } } pub struct tsm_screen; pub struct tsm_vte; pub struct log_data; pub struct tsm_vte_write_cb; pub struct va_list; pub type tsm_age_t = u32; pub type tsm_write_cb = extern "C" fn(*const tsm_vte, *const u8, size_t, c_void); pub type tsm_screen_draw_cb = extern "C" fn( con: *const tsm_screen, id: u32, ch: *const uint32_t, len: size_t, width: c_uint, posx: c_uint, posy: c_uint, attr: *const tsm_screen_attr, age: tsm_age_t, data: *mut c_void ); pub type tsm_log_t = extern "C" fn( data: *mut c_void, line: c_int, func: *const c_char, subs: *const c_char, sev: c_uint, format: *const c_char, args: va_list ); #[link(name = "tsm")] extern { pub fn tsm_screen_new(out: *mut *mut tsm_screen, log: Option<tsm_log_t>, log_data: *mut c_void) -> c_int; pub fn tsm_screen_resize(con: *mut tsm_screen, x: c_uint, y: c_uint) -> c_int; pub fn tsm_vte_new(out: *mut *mut tsm_vte, con: *mut tsm_screen, write_cb: tsm_write_cb, data: *mut c_void, log: Option<tsm_log_t>, log_data: *mut c_void) -> c_int; pub fn tsm_vte_input(vte: *mut tsm_vte, input: *const u8, len: size_t); pub fn tsm_screen_draw(con: *mut tsm_screen, draw_cb: tsm_screen_draw_cb, data: *mut c_void) -> tsm_age_t; pub fn tsm_screen_get_cursor_x(con: *mut tsm_screen) -> c_uint; pub fn tsm_screen_get_cursor_y(con: *mut tsm_screen) -> c_uint; pub fn tsm_screen_get_flags(con: *mut tsm_screen) -> EnumSet<ScreenFlags>; } }
get_flag
identifier_name
mod.rs
#![allow(non_camel_case_types)] pub mod libtsm { use std::num::{FromPrimitive}; use libc::{c_void, c_uint, c_int, size_t, uint32_t, c_char}; use collections::enum_set::{EnumSet,CLike}; static RGB_LEVELS : &'static [u8] = &[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]; #[deriving(PartialEq,Show,Clone,FromPrimitive)] #[repr(u8)] pub enum AttributeFlags { Bold, Underline, Inverse, Protect, Blink } #[deriving(PartialEq,Show,Clone,FromPrimitive)] #[repr(u8)] pub enum ScreenFlags { TSM_SCREEN_INSERT_MODE, TSM_SCREEN_AUTO_WRAP, TSM_SCREEN_REL_ORIGIN, TSM_SCREEN_INVERSE, TSM_SCREEN_HIDE_CURSOR, TSM_SCREEN_FIXED_POS, TSM_SCREEN_ALTERNATE } impl CLike for AttributeFlags { fn to_uint(&self) -> uint
fn from_uint(v: uint) -> AttributeFlags { FromPrimitive::from_uint(v).expect("Decoding of uint into AttributeFlags failed!") } } impl CLike for ScreenFlags { fn to_uint(&self) -> uint { *self as uint } fn from_uint(v: uint) -> ScreenFlags { FromPrimitive::from_uint(v).expect("Decoding of uint into ScreenFlags failed!") } } #[deriving(PartialEq,Show,Clone)] pub struct tsm_screen_attr { pub fccode: i8, /* foreground color code or <0 for rgb */ pub bccode: i8, /* background color code or <0 for rgb */ pub fr: u8, /* foreground red */ pub fg: u8, /* foreground green */ pub fb: u8, /* foreground blue */ pub br: u8, /* background red */ pub bg: u8, /* background green */ pub bb: u8, /* background blue */ pub flags: EnumSet<AttributeFlags>, /* misc flags */ } fn get_color(code: i8, r: u8, g: u8, b: u8) -> Option<u8> { if code < 0 { Some(get_rgb_color(r, g, b)) } else if code >= 0 && code < 16 { Some(code.to_u8().unwrap()) } else { None } } fn get_rgb_color(r: u8, g: u8, b: u8) -> u8 { if r == g && g == b && (r - 8) % 10 == 0 { return 232 + (r - 8) / 10; } else { return 16 + get_rgb_index(r) * 36 + get_rgb_index(g) * 6 + get_rgb_index(b); } } fn get_rgb_index(value: u8) -> u8 { RGB_LEVELS.iter().position(|level| *level == value).expect("No index for value found").to_u8().unwrap() } impl tsm_screen_attr { pub fn get_fg(&self) -> Option<u8> { get_color(self.fccode, self.fr, self.fg, self.fb) } pub fn get_bg(&self) -> Option<u8> { get_color(self.bccode, self.br, self.bg, self.bb) } pub fn get_flag(&self, flag: AttributeFlags) -> bool { self.flags.contains_elem(flag) } } pub struct tsm_screen; pub struct tsm_vte; pub struct log_data; pub struct tsm_vte_write_cb; pub struct va_list; pub type tsm_age_t = u32; pub type tsm_write_cb = extern "C" fn(*const tsm_vte, *const u8, size_t, c_void); pub type tsm_screen_draw_cb = extern "C" fn( con: *const tsm_screen, id: u32, ch: *const uint32_t, len: size_t, width: c_uint, posx: c_uint, posy: c_uint, attr: *const tsm_screen_attr, age: tsm_age_t, data: *mut c_void ); pub type tsm_log_t = extern "C" fn( data: *mut c_void, line: c_int, func: *const c_char, subs: *const c_char, sev: c_uint, format: *const c_char, args: va_list ); #[link(name = "tsm")] extern { pub fn tsm_screen_new(out: *mut *mut tsm_screen, log: Option<tsm_log_t>, log_data: *mut c_void) -> c_int; pub fn tsm_screen_resize(con: *mut tsm_screen, x: c_uint, y: c_uint) -> c_int; pub fn tsm_vte_new(out: *mut *mut tsm_vte, con: *mut tsm_screen, write_cb: tsm_write_cb, data: *mut c_void, log: Option<tsm_log_t>, log_data: *mut c_void) -> c_int; pub fn tsm_vte_input(vte: *mut tsm_vte, input: *const u8, len: size_t); pub fn tsm_screen_draw(con: *mut tsm_screen, draw_cb: tsm_screen_draw_cb, data: *mut c_void) -> tsm_age_t; pub fn tsm_screen_get_cursor_x(con: *mut tsm_screen) -> c_uint; pub fn tsm_screen_get_cursor_y(con: *mut tsm_screen) -> c_uint; pub fn tsm_screen_get_flags(con: *mut tsm_screen) -> EnumSet<ScreenFlags>; } }
{ *self as uint }
identifier_body
mod.rs
#![allow(non_camel_case_types)] pub mod libtsm { use std::num::{FromPrimitive}; use libc::{c_void, c_uint, c_int, size_t, uint32_t, c_char}; use collections::enum_set::{EnumSet,CLike}; static RGB_LEVELS : &'static [u8] = &[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]; #[deriving(PartialEq,Show,Clone,FromPrimitive)] #[repr(u8)] pub enum AttributeFlags { Bold, Underline, Inverse, Protect, Blink } #[deriving(PartialEq,Show,Clone,FromPrimitive)] #[repr(u8)] pub enum ScreenFlags { TSM_SCREEN_INSERT_MODE, TSM_SCREEN_AUTO_WRAP, TSM_SCREEN_REL_ORIGIN, TSM_SCREEN_INVERSE, TSM_SCREEN_HIDE_CURSOR, TSM_SCREEN_FIXED_POS, TSM_SCREEN_ALTERNATE } impl CLike for AttributeFlags { fn to_uint(&self) -> uint { *self as uint } fn from_uint(v: uint) -> AttributeFlags { FromPrimitive::from_uint(v).expect("Decoding of uint into AttributeFlags failed!") } } impl CLike for ScreenFlags { fn to_uint(&self) -> uint { *self as uint } fn from_uint(v: uint) -> ScreenFlags { FromPrimitive::from_uint(v).expect("Decoding of uint into ScreenFlags failed!") } } #[deriving(PartialEq,Show,Clone)] pub struct tsm_screen_attr { pub fccode: i8, /* foreground color code or <0 for rgb */ pub bccode: i8, /* background color code or <0 for rgb */ pub fr: u8, /* foreground red */ pub fg: u8, /* foreground green */
pub bb: u8, /* background blue */ pub flags: EnumSet<AttributeFlags>, /* misc flags */ } fn get_color(code: i8, r: u8, g: u8, b: u8) -> Option<u8> { if code < 0 { Some(get_rgb_color(r, g, b)) } else if code >= 0 && code < 16 { Some(code.to_u8().unwrap()) } else { None } } fn get_rgb_color(r: u8, g: u8, b: u8) -> u8 { if r == g && g == b && (r - 8) % 10 == 0 { return 232 + (r - 8) / 10; } else { return 16 + get_rgb_index(r) * 36 + get_rgb_index(g) * 6 + get_rgb_index(b); } } fn get_rgb_index(value: u8) -> u8 { RGB_LEVELS.iter().position(|level| *level == value).expect("No index for value found").to_u8().unwrap() } impl tsm_screen_attr { pub fn get_fg(&self) -> Option<u8> { get_color(self.fccode, self.fr, self.fg, self.fb) } pub fn get_bg(&self) -> Option<u8> { get_color(self.bccode, self.br, self.bg, self.bb) } pub fn get_flag(&self, flag: AttributeFlags) -> bool { self.flags.contains_elem(flag) } } pub struct tsm_screen; pub struct tsm_vte; pub struct log_data; pub struct tsm_vte_write_cb; pub struct va_list; pub type tsm_age_t = u32; pub type tsm_write_cb = extern "C" fn(*const tsm_vte, *const u8, size_t, c_void); pub type tsm_screen_draw_cb = extern "C" fn( con: *const tsm_screen, id: u32, ch: *const uint32_t, len: size_t, width: c_uint, posx: c_uint, posy: c_uint, attr: *const tsm_screen_attr, age: tsm_age_t, data: *mut c_void ); pub type tsm_log_t = extern "C" fn( data: *mut c_void, line: c_int, func: *const c_char, subs: *const c_char, sev: c_uint, format: *const c_char, args: va_list ); #[link(name = "tsm")] extern { pub fn tsm_screen_new(out: *mut *mut tsm_screen, log: Option<tsm_log_t>, log_data: *mut c_void) -> c_int; pub fn tsm_screen_resize(con: *mut tsm_screen, x: c_uint, y: c_uint) -> c_int; pub fn tsm_vte_new(out: *mut *mut tsm_vte, con: *mut tsm_screen, write_cb: tsm_write_cb, data: *mut c_void, log: Option<tsm_log_t>, log_data: *mut c_void) -> c_int; pub fn tsm_vte_input(vte: *mut tsm_vte, input: *const u8, len: size_t); pub fn tsm_screen_draw(con: *mut tsm_screen, draw_cb: tsm_screen_draw_cb, data: *mut c_void) -> tsm_age_t; pub fn tsm_screen_get_cursor_x(con: *mut tsm_screen) -> c_uint; pub fn tsm_screen_get_cursor_y(con: *mut tsm_screen) -> c_uint; pub fn tsm_screen_get_flags(con: *mut tsm_screen) -> EnumSet<ScreenFlags>; } }
pub fb: u8, /* foreground blue */ pub br: u8, /* background red */ pub bg: u8, /* background green */
random_line_split
mod.rs
#![allow(non_camel_case_types)] pub mod libtsm { use std::num::{FromPrimitive}; use libc::{c_void, c_uint, c_int, size_t, uint32_t, c_char}; use collections::enum_set::{EnumSet,CLike}; static RGB_LEVELS : &'static [u8] = &[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]; #[deriving(PartialEq,Show,Clone,FromPrimitive)] #[repr(u8)] pub enum AttributeFlags { Bold, Underline, Inverse, Protect, Blink } #[deriving(PartialEq,Show,Clone,FromPrimitive)] #[repr(u8)] pub enum ScreenFlags { TSM_SCREEN_INSERT_MODE, TSM_SCREEN_AUTO_WRAP, TSM_SCREEN_REL_ORIGIN, TSM_SCREEN_INVERSE, TSM_SCREEN_HIDE_CURSOR, TSM_SCREEN_FIXED_POS, TSM_SCREEN_ALTERNATE } impl CLike for AttributeFlags { fn to_uint(&self) -> uint { *self as uint } fn from_uint(v: uint) -> AttributeFlags { FromPrimitive::from_uint(v).expect("Decoding of uint into AttributeFlags failed!") } } impl CLike for ScreenFlags { fn to_uint(&self) -> uint { *self as uint } fn from_uint(v: uint) -> ScreenFlags { FromPrimitive::from_uint(v).expect("Decoding of uint into ScreenFlags failed!") } } #[deriving(PartialEq,Show,Clone)] pub struct tsm_screen_attr { pub fccode: i8, /* foreground color code or <0 for rgb */ pub bccode: i8, /* background color code or <0 for rgb */ pub fr: u8, /* foreground red */ pub fg: u8, /* foreground green */ pub fb: u8, /* foreground blue */ pub br: u8, /* background red */ pub bg: u8, /* background green */ pub bb: u8, /* background blue */ pub flags: EnumSet<AttributeFlags>, /* misc flags */ } fn get_color(code: i8, r: u8, g: u8, b: u8) -> Option<u8> { if code < 0 { Some(get_rgb_color(r, g, b)) } else if code >= 0 && code < 16 { Some(code.to_u8().unwrap()) } else
} fn get_rgb_color(r: u8, g: u8, b: u8) -> u8 { if r == g && g == b && (r - 8) % 10 == 0 { return 232 + (r - 8) / 10; } else { return 16 + get_rgb_index(r) * 36 + get_rgb_index(g) * 6 + get_rgb_index(b); } } fn get_rgb_index(value: u8) -> u8 { RGB_LEVELS.iter().position(|level| *level == value).expect("No index for value found").to_u8().unwrap() } impl tsm_screen_attr { pub fn get_fg(&self) -> Option<u8> { get_color(self.fccode, self.fr, self.fg, self.fb) } pub fn get_bg(&self) -> Option<u8> { get_color(self.bccode, self.br, self.bg, self.bb) } pub fn get_flag(&self, flag: AttributeFlags) -> bool { self.flags.contains_elem(flag) } } pub struct tsm_screen; pub struct tsm_vte; pub struct log_data; pub struct tsm_vte_write_cb; pub struct va_list; pub type tsm_age_t = u32; pub type tsm_write_cb = extern "C" fn(*const tsm_vte, *const u8, size_t, c_void); pub type tsm_screen_draw_cb = extern "C" fn( con: *const tsm_screen, id: u32, ch: *const uint32_t, len: size_t, width: c_uint, posx: c_uint, posy: c_uint, attr: *const tsm_screen_attr, age: tsm_age_t, data: *mut c_void ); pub type tsm_log_t = extern "C" fn( data: *mut c_void, line: c_int, func: *const c_char, subs: *const c_char, sev: c_uint, format: *const c_char, args: va_list ); #[link(name = "tsm")] extern { pub fn tsm_screen_new(out: *mut *mut tsm_screen, log: Option<tsm_log_t>, log_data: *mut c_void) -> c_int; pub fn tsm_screen_resize(con: *mut tsm_screen, x: c_uint, y: c_uint) -> c_int; pub fn tsm_vte_new(out: *mut *mut tsm_vte, con: *mut tsm_screen, write_cb: tsm_write_cb, data: *mut c_void, log: Option<tsm_log_t>, log_data: *mut c_void) -> c_int; pub fn tsm_vte_input(vte: *mut tsm_vte, input: *const u8, len: size_t); pub fn tsm_screen_draw(con: *mut tsm_screen, draw_cb: tsm_screen_draw_cb, data: *mut c_void) -> tsm_age_t; pub fn tsm_screen_get_cursor_x(con: *mut tsm_screen) -> c_uint; pub fn tsm_screen_get_cursor_y(con: *mut tsm_screen) -> c_uint; pub fn tsm_screen_get_flags(con: *mut tsm_screen) -> EnumSet<ScreenFlags>; } }
{ None }
conditional_block
disamb-stmt-expr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pp-exact // Here we check that the parentheses around the body of `wsucc()` are // preserved. They are needed to disambiguate `{return n+1}; - 0` from // `({return n+1}-0)`. fn id(f: || -> int) -> int { f() } fn wsucc(_n: int) -> int { id(|| { 1 }) - 0 } fn main() { }
// http://rust-lang.org/COPYRIGHT. //
random_line_split
disamb-stmt-expr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pp-exact // Here we check that the parentheses around the body of `wsucc()` are // preserved. They are needed to disambiguate `{return n+1}; - 0` from // `({return n+1}-0)`. fn id(f: || -> int) -> int
fn wsucc(_n: int) -> int { id(|| { 1 }) - 0 } fn main() { }
{ f() }
identifier_body
disamb-stmt-expr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pp-exact // Here we check that the parentheses around the body of `wsucc()` are // preserved. They are needed to disambiguate `{return n+1}; - 0` from // `({return n+1}-0)`. fn id(f: || -> int) -> int { f() } fn wsucc(_n: int) -> int { id(|| { 1 }) - 0 } fn
() { }
main
identifier_name
nested-non-tuple-tuple-struct.rs
pub struct S(f32, f32); pub enum E { V(f32, f32), } fn
() { let _x = (S { x: 1.0, y: 2.0 }, S { x: 3.0, y: 4.0 }); //~^ ERROR struct `S` has no field named `x` //~| ERROR struct `S` has no field named `y` //~| ERROR struct `S` has no field named `x` //~| ERROR struct `S` has no field named `y` let _y = (E::V { x: 1.0, y: 2.0 }, E::V { x: 3.0, y: 4.0 }); //~^ ERROR variant `E::V` has no field named `x` //~| ERROR variant `E::V` has no field named `y` //~| ERROR variant `E::V` has no field named `x` //~| ERROR variant `E::V` has no field named `y` }
main
identifier_name
nested-non-tuple-tuple-struct.rs
} fn main() { let _x = (S { x: 1.0, y: 2.0 }, S { x: 3.0, y: 4.0 }); //~^ ERROR struct `S` has no field named `x` //~| ERROR struct `S` has no field named `y` //~| ERROR struct `S` has no field named `x` //~| ERROR struct `S` has no field named `y` let _y = (E::V { x: 1.0, y: 2.0 }, E::V { x: 3.0, y: 4.0 }); //~^ ERROR variant `E::V` has no field named `x` //~| ERROR variant `E::V` has no field named `y` //~| ERROR variant `E::V` has no field named `x` //~| ERROR variant `E::V` has no field named `y` }
pub struct S(f32, f32); pub enum E { V(f32, f32),
random_line_split
window.rs
use std::fs::File; use std::io::*; use std::mem; use std::slice; use std::thread; use std::to_num::ToNum; use super::Event; use super::Color; /// A window pub struct Window { /// The x coordinate of the window x: i32, /// The y coordinate of the window y: i32, /// The width of the window w: u32, /// The height of the window h: u32, /// The title of the window t: String, /// The input scheme file: File, /// Font file font: Vec<u8>, /// Window data data: Vec<u32>, } impl Window { /// Create a new window pub fn new(x: i32, y: i32, w: u32, h: u32, title: &str) -> Option<Box<Self>> { let mut font = Vec::new(); if let Ok(mut font_file) = File::open("file:/ui/unifont.font") { font_file.read_to_end(&mut font); } match File::open(&format!("orbital:///{}/{}/{}/{}/{}", x, y, w, h, title)) { Ok(file) => { Some(box Window { x: x, y: y, w: w, h: h, t: title.to_string(), file: file, font: font, data: vec![0; (w * h * 4) as usize], }) } Err(_) => None, } } // TODO: Replace with smarter mechanism, maybe a move event? pub fn sync_path(&mut self) { if let Ok(path) = self.file.path()
} /// Get x // TODO: Sync with window movements pub fn x(&self) -> i32 { self.x } /// Get y // TODO: Sync with window movements pub fn y(&self) -> i32 { self.y } /// Get width pub fn width(&self) -> u32 { self.w } /// Get height pub fn height(&self) -> u32 { self.h } /// Get title pub fn title(&self) -> String { self.t.clone() } /// Set title pub fn set_title(&mut self, _: &str) { // TODO } /// Draw a pixel pub fn pixel(&mut self, x: i32, y: i32, color: Color) { if x >= 0 && y >= 0 && x < self.w as i32 && y < self.h as i32 { let offset = y as u32 * self.w + x as u32; self.data[offset as usize] = color.data; } } /// Draw a character, using the loaded font pub fn char(&mut self, x: i32, y: i32, c: char, color: Color) { let mut offset = (c as usize) * 16; for row in 0..16 { let row_data; if offset < self.font.len() { row_data = self.font[offset]; } else { row_data = 0; } for col in 0..8 { let pixel = (row_data >> (7 - col)) & 1; if pixel > 0 { self.pixel(x + col as i32, y + row as i32, color); } } offset += 1; } } // TODO move, resize, set_title /// Set entire window to a color // TODO: Improve speed #[allow(unused_variables)] pub fn set(&mut self, color: Color) { let w = self.w; let h = self.h; self.rect(0, 0, w, h, color); } /// Draw rectangle // TODO: Improve speed #[allow(unused_variables)] pub fn rect(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, color: Color) { for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { self.pixel(x, y, color); } } } /// Display an image // TODO: Improve speed pub fn image(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, data: &[Color]) { let mut i = 0; for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { if i < data.len() { self.pixel(x, y, data[i]) } i += 1; } } } /// Poll for an event // TODO: clean this up pub fn poll(&mut self) -> Option<Event> { let mut event = Event::new(); let event_ptr: *mut Event = &mut event; loop { match self.file.read(&mut unsafe { slice::from_raw_parts_mut(event_ptr as *mut u8, mem::size_of::<Event>()) }) { Ok(0) => thread::yield_now(), Ok(_) => return Some(event), Err(_) => return None, } } } /// Flip the window buffer pub fn sync(&mut self) -> bool { self.file.seek(SeekFrom::Start(0)); self.file.write(&unsafe { slice::from_raw_parts(self.data.as_ptr() as *const u8, self.data.len() * mem::size_of::<u32>()) }); return self.file.sync_all().is_ok(); } /// Return a iterator over events pub fn event_iter<'a>(&'a mut self) -> EventIter<'a> { EventIter { window: self } } } /// Event iterator pub struct EventIter<'a> { window: &'a mut Window, } impl<'a> Iterator for EventIter<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { self.window.poll() } }
{ // orbital://x/y/w/h/t if let Some(path_str) = path.to_str() { let parts: Vec<&str> = path_str.split('/').collect(); if let Some(x) = parts.get(3) { self.x = x.to_num_signed(); } if let Some(y) = parts.get(4) { self.y = y.to_num_signed(); } if let Some(w) = parts.get(5) { self.w = w.to_num(); } if let Some(h) = parts.get(6) { self.h = h.to_num(); } } }
conditional_block
window.rs
use std::fs::File; use std::io::*; use std::mem; use std::slice; use std::thread; use std::to_num::ToNum; use super::Event; use super::Color; /// A window pub struct Window { /// The x coordinate of the window x: i32, /// The y coordinate of the window y: i32, /// The width of the window w: u32, /// The height of the window h: u32, /// The title of the window t: String, /// The input scheme file: File, /// Font file font: Vec<u8>, /// Window data data: Vec<u32>, } impl Window { /// Create a new window pub fn new(x: i32, y: i32, w: u32, h: u32, title: &str) -> Option<Box<Self>> { let mut font = Vec::new(); if let Ok(mut font_file) = File::open("file:/ui/unifont.font") { font_file.read_to_end(&mut font); } match File::open(&format!("orbital:///{}/{}/{}/{}/{}", x, y, w, h, title)) { Ok(file) => { Some(box Window { x: x, y: y, w: w, h: h, t: title.to_string(), file: file, font: font, data: vec![0; (w * h * 4) as usize], }) } Err(_) => None, } } // TODO: Replace with smarter mechanism, maybe a move event? pub fn sync_path(&mut self) { if let Ok(path) = self.file.path() { // orbital://x/y/w/h/t if let Some(path_str) = path.to_str() { let parts: Vec<&str> = path_str.split('/').collect(); if let Some(x) = parts.get(3) { self.x = x.to_num_signed(); } if let Some(y) = parts.get(4) { self.y = y.to_num_signed(); } if let Some(w) = parts.get(5) { self.w = w.to_num(); } if let Some(h) = parts.get(6) { self.h = h.to_num(); } } } } /// Get x // TODO: Sync with window movements pub fn x(&self) -> i32 { self.x } /// Get y // TODO: Sync with window movements pub fn y(&self) -> i32 { self.y } /// Get width pub fn
(&self) -> u32 { self.w } /// Get height pub fn height(&self) -> u32 { self.h } /// Get title pub fn title(&self) -> String { self.t.clone() } /// Set title pub fn set_title(&mut self, _: &str) { // TODO } /// Draw a pixel pub fn pixel(&mut self, x: i32, y: i32, color: Color) { if x >= 0 && y >= 0 && x < self.w as i32 && y < self.h as i32 { let offset = y as u32 * self.w + x as u32; self.data[offset as usize] = color.data; } } /// Draw a character, using the loaded font pub fn char(&mut self, x: i32, y: i32, c: char, color: Color) { let mut offset = (c as usize) * 16; for row in 0..16 { let row_data; if offset < self.font.len() { row_data = self.font[offset]; } else { row_data = 0; } for col in 0..8 { let pixel = (row_data >> (7 - col)) & 1; if pixel > 0 { self.pixel(x + col as i32, y + row as i32, color); } } offset += 1; } } // TODO move, resize, set_title /// Set entire window to a color // TODO: Improve speed #[allow(unused_variables)] pub fn set(&mut self, color: Color) { let w = self.w; let h = self.h; self.rect(0, 0, w, h, color); } /// Draw rectangle // TODO: Improve speed #[allow(unused_variables)] pub fn rect(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, color: Color) { for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { self.pixel(x, y, color); } } } /// Display an image // TODO: Improve speed pub fn image(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, data: &[Color]) { let mut i = 0; for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { if i < data.len() { self.pixel(x, y, data[i]) } i += 1; } } } /// Poll for an event // TODO: clean this up pub fn poll(&mut self) -> Option<Event> { let mut event = Event::new(); let event_ptr: *mut Event = &mut event; loop { match self.file.read(&mut unsafe { slice::from_raw_parts_mut(event_ptr as *mut u8, mem::size_of::<Event>()) }) { Ok(0) => thread::yield_now(), Ok(_) => return Some(event), Err(_) => return None, } } } /// Flip the window buffer pub fn sync(&mut self) -> bool { self.file.seek(SeekFrom::Start(0)); self.file.write(&unsafe { slice::from_raw_parts(self.data.as_ptr() as *const u8, self.data.len() * mem::size_of::<u32>()) }); return self.file.sync_all().is_ok(); } /// Return a iterator over events pub fn event_iter<'a>(&'a mut self) -> EventIter<'a> { EventIter { window: self } } } /// Event iterator pub struct EventIter<'a> { window: &'a mut Window, } impl<'a> Iterator for EventIter<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { self.window.poll() } }
width
identifier_name
window.rs
use std::fs::File; use std::io::*; use std::mem; use std::slice; use std::thread; use std::to_num::ToNum; use super::Event; use super::Color; /// A window pub struct Window { /// The x coordinate of the window x: i32, /// The y coordinate of the window y: i32, /// The width of the window w: u32, /// The height of the window h: u32, /// The title of the window t: String, /// The input scheme file: File, /// Font file font: Vec<u8>, /// Window data data: Vec<u32>, } impl Window { /// Create a new window pub fn new(x: i32, y: i32, w: u32, h: u32, title: &str) -> Option<Box<Self>> { let mut font = Vec::new(); if let Ok(mut font_file) = File::open("file:/ui/unifont.font") { font_file.read_to_end(&mut font); } match File::open(&format!("orbital:///{}/{}/{}/{}/{}", x, y, w, h, title)) { Ok(file) => { Some(box Window { x: x, y: y, w: w, h: h, t: title.to_string(), file: file, font: font, data: vec![0; (w * h * 4) as usize], }) } Err(_) => None, } } // TODO: Replace with smarter mechanism, maybe a move event? pub fn sync_path(&mut self) { if let Ok(path) = self.file.path() { // orbital://x/y/w/h/t if let Some(path_str) = path.to_str() { let parts: Vec<&str> = path_str.split('/').collect(); if let Some(x) = parts.get(3) { self.x = x.to_num_signed(); } if let Some(y) = parts.get(4) { self.y = y.to_num_signed(); } if let Some(w) = parts.get(5) { self.w = w.to_num(); } if let Some(h) = parts.get(6) { self.h = h.to_num(); } } } } /// Get x // TODO: Sync with window movements pub fn x(&self) -> i32 { self.x } /// Get y // TODO: Sync with window movements pub fn y(&self) -> i32 { self.y } /// Get width pub fn width(&self) -> u32 { self.w } /// Get height pub fn height(&self) -> u32 { self.h }
/// Set title pub fn set_title(&mut self, _: &str) { // TODO } /// Draw a pixel pub fn pixel(&mut self, x: i32, y: i32, color: Color) { if x >= 0 && y >= 0 && x < self.w as i32 && y < self.h as i32 { let offset = y as u32 * self.w + x as u32; self.data[offset as usize] = color.data; } } /// Draw a character, using the loaded font pub fn char(&mut self, x: i32, y: i32, c: char, color: Color) { let mut offset = (c as usize) * 16; for row in 0..16 { let row_data; if offset < self.font.len() { row_data = self.font[offset]; } else { row_data = 0; } for col in 0..8 { let pixel = (row_data >> (7 - col)) & 1; if pixel > 0 { self.pixel(x + col as i32, y + row as i32, color); } } offset += 1; } } // TODO move, resize, set_title /// Set entire window to a color // TODO: Improve speed #[allow(unused_variables)] pub fn set(&mut self, color: Color) { let w = self.w; let h = self.h; self.rect(0, 0, w, h, color); } /// Draw rectangle // TODO: Improve speed #[allow(unused_variables)] pub fn rect(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, color: Color) { for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { self.pixel(x, y, color); } } } /// Display an image // TODO: Improve speed pub fn image(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, data: &[Color]) { let mut i = 0; for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { if i < data.len() { self.pixel(x, y, data[i]) } i += 1; } } } /// Poll for an event // TODO: clean this up pub fn poll(&mut self) -> Option<Event> { let mut event = Event::new(); let event_ptr: *mut Event = &mut event; loop { match self.file.read(&mut unsafe { slice::from_raw_parts_mut(event_ptr as *mut u8, mem::size_of::<Event>()) }) { Ok(0) => thread::yield_now(), Ok(_) => return Some(event), Err(_) => return None, } } } /// Flip the window buffer pub fn sync(&mut self) -> bool { self.file.seek(SeekFrom::Start(0)); self.file.write(&unsafe { slice::from_raw_parts(self.data.as_ptr() as *const u8, self.data.len() * mem::size_of::<u32>()) }); return self.file.sync_all().is_ok(); } /// Return a iterator over events pub fn event_iter<'a>(&'a mut self) -> EventIter<'a> { EventIter { window: self } } } /// Event iterator pub struct EventIter<'a> { window: &'a mut Window, } impl<'a> Iterator for EventIter<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { self.window.poll() } }
/// Get title pub fn title(&self) -> String { self.t.clone() }
random_line_split
window.rs
use std::fs::File; use std::io::*; use std::mem; use std::slice; use std::thread; use std::to_num::ToNum; use super::Event; use super::Color; /// A window pub struct Window { /// The x coordinate of the window x: i32, /// The y coordinate of the window y: i32, /// The width of the window w: u32, /// The height of the window h: u32, /// The title of the window t: String, /// The input scheme file: File, /// Font file font: Vec<u8>, /// Window data data: Vec<u32>, } impl Window { /// Create a new window pub fn new(x: i32, y: i32, w: u32, h: u32, title: &str) -> Option<Box<Self>> { let mut font = Vec::new(); if let Ok(mut font_file) = File::open("file:/ui/unifont.font") { font_file.read_to_end(&mut font); } match File::open(&format!("orbital:///{}/{}/{}/{}/{}", x, y, w, h, title)) { Ok(file) => { Some(box Window { x: x, y: y, w: w, h: h, t: title.to_string(), file: file, font: font, data: vec![0; (w * h * 4) as usize], }) } Err(_) => None, } } // TODO: Replace with smarter mechanism, maybe a move event? pub fn sync_path(&mut self) { if let Ok(path) = self.file.path() { // orbital://x/y/w/h/t if let Some(path_str) = path.to_str() { let parts: Vec<&str> = path_str.split('/').collect(); if let Some(x) = parts.get(3) { self.x = x.to_num_signed(); } if let Some(y) = parts.get(4) { self.y = y.to_num_signed(); } if let Some(w) = parts.get(5) { self.w = w.to_num(); } if let Some(h) = parts.get(6) { self.h = h.to_num(); } } } } /// Get x // TODO: Sync with window movements pub fn x(&self) -> i32 { self.x } /// Get y // TODO: Sync with window movements pub fn y(&self) -> i32 { self.y } /// Get width pub fn width(&self) -> u32 { self.w } /// Get height pub fn height(&self) -> u32 { self.h } /// Get title pub fn title(&self) -> String { self.t.clone() } /// Set title pub fn set_title(&mut self, _: &str) { // TODO } /// Draw a pixel pub fn pixel(&mut self, x: i32, y: i32, color: Color) { if x >= 0 && y >= 0 && x < self.w as i32 && y < self.h as i32 { let offset = y as u32 * self.w + x as u32; self.data[offset as usize] = color.data; } } /// Draw a character, using the loaded font pub fn char(&mut self, x: i32, y: i32, c: char, color: Color) { let mut offset = (c as usize) * 16; for row in 0..16 { let row_data; if offset < self.font.len() { row_data = self.font[offset]; } else { row_data = 0; } for col in 0..8 { let pixel = (row_data >> (7 - col)) & 1; if pixel > 0 { self.pixel(x + col as i32, y + row as i32, color); } } offset += 1; } } // TODO move, resize, set_title /// Set entire window to a color // TODO: Improve speed #[allow(unused_variables)] pub fn set(&mut self, color: Color) { let w = self.w; let h = self.h; self.rect(0, 0, w, h, color); } /// Draw rectangle // TODO: Improve speed #[allow(unused_variables)] pub fn rect(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, color: Color)
/// Display an image // TODO: Improve speed pub fn image(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, data: &[Color]) { let mut i = 0; for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { if i < data.len() { self.pixel(x, y, data[i]) } i += 1; } } } /// Poll for an event // TODO: clean this up pub fn poll(&mut self) -> Option<Event> { let mut event = Event::new(); let event_ptr: *mut Event = &mut event; loop { match self.file.read(&mut unsafe { slice::from_raw_parts_mut(event_ptr as *mut u8, mem::size_of::<Event>()) }) { Ok(0) => thread::yield_now(), Ok(_) => return Some(event), Err(_) => return None, } } } /// Flip the window buffer pub fn sync(&mut self) -> bool { self.file.seek(SeekFrom::Start(0)); self.file.write(&unsafe { slice::from_raw_parts(self.data.as_ptr() as *const u8, self.data.len() * mem::size_of::<u32>()) }); return self.file.sync_all().is_ok(); } /// Return a iterator over events pub fn event_iter<'a>(&'a mut self) -> EventIter<'a> { EventIter { window: self } } } /// Event iterator pub struct EventIter<'a> { window: &'a mut Window, } impl<'a> Iterator for EventIter<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { self.window.poll() } }
{ for y in start_y..start_y + h as i32 { for x in start_x..start_x + w as i32 { self.pixel(x, y, color); } } }
identifier_body
issue-2735-3.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; use std::cell::Cell; // This test should behave exactly like issue-2735-2 struct defer { b: @Cell<bool>, } #[unsafe_destructor] impl Drop for defer { fn drop(&mut self) { self.b.set(true); } } fn defer(b: @Cell<bool>) -> defer { defer { b: b } } pub fn main() { let dtor_ran = @Cell::new(false); defer(dtor_ran); assert!(dtor_ran.get()); }
random_line_split
issue-2735-3.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; use std::cell::Cell; // This test should behave exactly like issue-2735-2 struct defer { b: @Cell<bool>, } #[unsafe_destructor] impl Drop for defer { fn drop(&mut self) { self.b.set(true); } } fn defer(b: @Cell<bool>) -> defer
pub fn main() { let dtor_ran = @Cell::new(false); defer(dtor_ran); assert!(dtor_ran.get()); }
{ defer { b: b } }
identifier_body
issue-2735-3.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; use std::cell::Cell; // This test should behave exactly like issue-2735-2 struct defer { b: @Cell<bool>, } #[unsafe_destructor] impl Drop for defer { fn
(&mut self) { self.b.set(true); } } fn defer(b: @Cell<bool>) -> defer { defer { b: b } } pub fn main() { let dtor_ran = @Cell::new(false); defer(dtor_ran); assert!(dtor_ran.get()); }
drop
identifier_name
packet.rs
use crate::options::*; use nom::bytes::complete::{tag, take}; use nom::multi::{many0, many_till}; use nom::number::complete::{be_u16, be_u32, be_u8}; use std::net::Ipv4Addr; pub enum Err<I> { NomError(nom::Err<(I, nom::error::ErrorKind)>), NonUtf8String, UnrecognizedMessageType, InvalidHlen, } impl<I> nom::error::ParseError<I> for Err<I> { fn from_error_kind(input: I, kind: nom::error::ErrorKind) -> Self { Err::NomError(nom::Err::Error((input, kind))) } fn append(_input: I, _kind: nom::error::ErrorKind, other: Self) -> Self { other } } type IResult<I, O> = nom::IResult<I, O, Err<I>>; /// DHCP Packet Structure pub struct Packet { pub reply: bool, // false = request, true = reply pub hops: u8, pub xid: u32, // Random identifier pub secs: u16, pub broadcast: bool, pub ciaddr: Ipv4Addr, pub yiaddr: Ipv4Addr, pub siaddr: Ipv4Addr, pub giaddr: Ipv4Addr, pub chaddr: [u8; 6], pub options: Vec<DhcpOption>, } fn decode_reply(input: &[u8]) -> IResult<&[u8], bool> { let (input, reply) = take(1u8)(input)?; Ok(( input, match reply[0] { BOOT_REPLY => true, BOOT_REQUEST => false, _ => { // @TODO: Throw an error false } },
fn decode_ipv4(p: &[u8]) -> IResult<&[u8], Ipv4Addr> { let (input, addr) = take(4u8)(p)?; Ok((input, Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3]))) } pub fn decode_option(input: &[u8]) -> IResult<&[u8], DhcpOption> { let (input, code) = be_u8(input)?; assert!(code!= END); let (input, len) = be_u8(input)?; let (input, data) = take(len)(input)?; let option = match code { DHCP_MESSAGE_TYPE => DhcpOption::DhcpMessageType(match MessageType::from(be_u8(data)?.1) { Ok(x) => x, Err(_) => return Err(nom::Err::Error(Err::UnrecognizedMessageType)), }), SERVER_IDENTIFIER => DhcpOption::ServerIdentifier(decode_ipv4(data)?.1), PARAMETER_REQUEST_LIST => DhcpOption::ParameterRequestList(data.to_vec()), REQUESTED_IP_ADDRESS => DhcpOption::RequestedIpAddress(decode_ipv4(data)?.1), HOST_NAME => DhcpOption::HostName(match std::str::from_utf8(data) { Ok(s) => s.to_string(), Err(_) => return Err(nom::Err::Error(Err::NonUtf8String)), }), ROUTER => DhcpOption::Router(many0(decode_ipv4)(data)?.1), DOMAIN_NAME_SERVER => DhcpOption::DomainNameServer(many0(decode_ipv4)(data)?.1), IP_ADDRESS_LEASE_TIME => DhcpOption::IpAddressLeaseTime(be_u32(data)?.1), MESSAGE => DhcpOption::Message(match std::str::from_utf8(data) { Ok(s) => s.to_string(), Err(_) => return Err(nom::Err::Error(Err::NonUtf8String)), }), _ => DhcpOption::Unrecognized(RawDhcpOption { code, data: data.to_vec(), }), }; Ok((input, option)) } /// Parses Packet from byte array fn decode(input: &[u8]) -> IResult<&[u8], Packet> { let (options_input, input) = take(236u32)(input)?; let (input, reply) = decode_reply(input)?; let (input, _htype) = take(1u8)(input)?; let (input, hlen) = be_u8(input)?; let (input, hops) = be_u8(input)?; let (input, xid) = be_u32(input)?; let (input, secs) = be_u16(input)?; let (input, flags) = be_u16(input)?; let (input, ciaddr) = decode_ipv4(input)?; let (input, yiaddr) = decode_ipv4(input)?; let (input, siaddr) = decode_ipv4(input)?; let (input, giaddr) = decode_ipv4(input)?; if hlen!= 6 { return Err(nom::Err::Error(Err::InvalidHlen)); } let (_, chaddr) = take(6u8)(input)?; let input = options_input; let (input, _) = tag(COOKIE)(input)?; let (input, (options, _)) = many_till(decode_option, tag(&[END]))(input)?; Ok(( input, Packet { reply, hops, secs, broadcast: flags & 128 == 128, ciaddr, yiaddr, siaddr, giaddr, options, chaddr: [ chaddr[0], chaddr[1], chaddr[2], chaddr[3], chaddr[4], chaddr[5], ], xid, }, )) } impl Packet { pub fn from(input: &[u8]) -> Result<Packet, nom::Err<Err<&[u8]>>> { Ok(decode(input)?.1) } /// Extracts requested option payload from packet if available pub fn option(&self, code: u8) -> Option<&DhcpOption> { for option in &self.options { if option.code() == code { return Some(&option); } } None } /// Convenience function for extracting a packet's message type. pub fn message_type(&self) -> Result<MessageType, String> { match self.option(DHCP_MESSAGE_TYPE) { Some(DhcpOption::DhcpMessageType(msgtype)) => Ok(*msgtype), Some(option) => Err(format![ "Got wrong enum code {} for DHCP_MESSAGE_TYPE", option.code() ]), None => Err("Packet does not have MessageType option".to_string()), } } /// Creates byte array DHCP packet pub fn encode<'c>(&'c self, p: &'c mut [u8]) -> &[u8] { p[..12].clone_from_slice(&[ (if self.reply { BOOT_REPLY } else { BOOT_REQUEST }), 1, 6, self.hops, ((self.xid >> 24) & 0xFF) as u8, ((self.xid >> 16) & 0xFF) as u8, ((self.xid >> 8) & 0xFF) as u8, (self.xid & 0xFF) as u8, (self.secs >> 8) as u8, (self.secs & 255) as u8, (if self.broadcast { 128 } else { 0 }), 0, ]); p[12..16].clone_from_slice(&self.ciaddr.octets()); p[16..20].clone_from_slice(&self.yiaddr.octets()); p[20..24].clone_from_slice(&self.siaddr.octets()); p[24..28].clone_from_slice(&self.giaddr.octets()); p[28..34].clone_from_slice(&self.chaddr); p[34..236].clone_from_slice(&[0; 202]); p[236..240].clone_from_slice(&COOKIE); let mut length: usize = 240; for option in &self.options { let option = option.to_raw(); p[length] = option.code; p[length + 1] = option.data.len() as u8; p[length + 2..length + 2 + option.data.len()].clone_from_slice(&option.data); length += 2 + option.data.len(); } p[length] = END; length += 1; if length < 272 { // Pad to min size p[length..272].clone_from_slice(&[PAD; 32][..272 - length]); length = 272 } &p[..length] } } const COOKIE: [u8; 4] = [99, 130, 83, 99]; const BOOT_REQUEST: u8 = 1; // From Client; const BOOT_REPLY: u8 = 2; // From Server; const END: u8 = 255; const PAD: u8 = 0;
)) }
random_line_split
packet.rs
use crate::options::*; use nom::bytes::complete::{tag, take}; use nom::multi::{many0, many_till}; use nom::number::complete::{be_u16, be_u32, be_u8}; use std::net::Ipv4Addr; pub enum Err<I> { NomError(nom::Err<(I, nom::error::ErrorKind)>), NonUtf8String, UnrecognizedMessageType, InvalidHlen, } impl<I> nom::error::ParseError<I> for Err<I> { fn from_error_kind(input: I, kind: nom::error::ErrorKind) -> Self { Err::NomError(nom::Err::Error((input, kind))) } fn append(_input: I, _kind: nom::error::ErrorKind, other: Self) -> Self { other } } type IResult<I, O> = nom::IResult<I, O, Err<I>>; /// DHCP Packet Structure pub struct Packet { pub reply: bool, // false = request, true = reply pub hops: u8, pub xid: u32, // Random identifier pub secs: u16, pub broadcast: bool, pub ciaddr: Ipv4Addr, pub yiaddr: Ipv4Addr, pub siaddr: Ipv4Addr, pub giaddr: Ipv4Addr, pub chaddr: [u8; 6], pub options: Vec<DhcpOption>, } fn decode_reply(input: &[u8]) -> IResult<&[u8], bool> { let (input, reply) = take(1u8)(input)?; Ok(( input, match reply[0] { BOOT_REPLY => true, BOOT_REQUEST => false, _ => { // @TODO: Throw an error false } }, )) } fn
(p: &[u8]) -> IResult<&[u8], Ipv4Addr> { let (input, addr) = take(4u8)(p)?; Ok((input, Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3]))) } pub fn decode_option(input: &[u8]) -> IResult<&[u8], DhcpOption> { let (input, code) = be_u8(input)?; assert!(code!= END); let (input, len) = be_u8(input)?; let (input, data) = take(len)(input)?; let option = match code { DHCP_MESSAGE_TYPE => DhcpOption::DhcpMessageType(match MessageType::from(be_u8(data)?.1) { Ok(x) => x, Err(_) => return Err(nom::Err::Error(Err::UnrecognizedMessageType)), }), SERVER_IDENTIFIER => DhcpOption::ServerIdentifier(decode_ipv4(data)?.1), PARAMETER_REQUEST_LIST => DhcpOption::ParameterRequestList(data.to_vec()), REQUESTED_IP_ADDRESS => DhcpOption::RequestedIpAddress(decode_ipv4(data)?.1), HOST_NAME => DhcpOption::HostName(match std::str::from_utf8(data) { Ok(s) => s.to_string(), Err(_) => return Err(nom::Err::Error(Err::NonUtf8String)), }), ROUTER => DhcpOption::Router(many0(decode_ipv4)(data)?.1), DOMAIN_NAME_SERVER => DhcpOption::DomainNameServer(many0(decode_ipv4)(data)?.1), IP_ADDRESS_LEASE_TIME => DhcpOption::IpAddressLeaseTime(be_u32(data)?.1), MESSAGE => DhcpOption::Message(match std::str::from_utf8(data) { Ok(s) => s.to_string(), Err(_) => return Err(nom::Err::Error(Err::NonUtf8String)), }), _ => DhcpOption::Unrecognized(RawDhcpOption { code, data: data.to_vec(), }), }; Ok((input, option)) } /// Parses Packet from byte array fn decode(input: &[u8]) -> IResult<&[u8], Packet> { let (options_input, input) = take(236u32)(input)?; let (input, reply) = decode_reply(input)?; let (input, _htype) = take(1u8)(input)?; let (input, hlen) = be_u8(input)?; let (input, hops) = be_u8(input)?; let (input, xid) = be_u32(input)?; let (input, secs) = be_u16(input)?; let (input, flags) = be_u16(input)?; let (input, ciaddr) = decode_ipv4(input)?; let (input, yiaddr) = decode_ipv4(input)?; let (input, siaddr) = decode_ipv4(input)?; let (input, giaddr) = decode_ipv4(input)?; if hlen!= 6 { return Err(nom::Err::Error(Err::InvalidHlen)); } let (_, chaddr) = take(6u8)(input)?; let input = options_input; let (input, _) = tag(COOKIE)(input)?; let (input, (options, _)) = many_till(decode_option, tag(&[END]))(input)?; Ok(( input, Packet { reply, hops, secs, broadcast: flags & 128 == 128, ciaddr, yiaddr, siaddr, giaddr, options, chaddr: [ chaddr[0], chaddr[1], chaddr[2], chaddr[3], chaddr[4], chaddr[5], ], xid, }, )) } impl Packet { pub fn from(input: &[u8]) -> Result<Packet, nom::Err<Err<&[u8]>>> { Ok(decode(input)?.1) } /// Extracts requested option payload from packet if available pub fn option(&self, code: u8) -> Option<&DhcpOption> { for option in &self.options { if option.code() == code { return Some(&option); } } None } /// Convenience function for extracting a packet's message type. pub fn message_type(&self) -> Result<MessageType, String> { match self.option(DHCP_MESSAGE_TYPE) { Some(DhcpOption::DhcpMessageType(msgtype)) => Ok(*msgtype), Some(option) => Err(format![ "Got wrong enum code {} for DHCP_MESSAGE_TYPE", option.code() ]), None => Err("Packet does not have MessageType option".to_string()), } } /// Creates byte array DHCP packet pub fn encode<'c>(&'c self, p: &'c mut [u8]) -> &[u8] { p[..12].clone_from_slice(&[ (if self.reply { BOOT_REPLY } else { BOOT_REQUEST }), 1, 6, self.hops, ((self.xid >> 24) & 0xFF) as u8, ((self.xid >> 16) & 0xFF) as u8, ((self.xid >> 8) & 0xFF) as u8, (self.xid & 0xFF) as u8, (self.secs >> 8) as u8, (self.secs & 255) as u8, (if self.broadcast { 128 } else { 0 }), 0, ]); p[12..16].clone_from_slice(&self.ciaddr.octets()); p[16..20].clone_from_slice(&self.yiaddr.octets()); p[20..24].clone_from_slice(&self.siaddr.octets()); p[24..28].clone_from_slice(&self.giaddr.octets()); p[28..34].clone_from_slice(&self.chaddr); p[34..236].clone_from_slice(&[0; 202]); p[236..240].clone_from_slice(&COOKIE); let mut length: usize = 240; for option in &self.options { let option = option.to_raw(); p[length] = option.code; p[length + 1] = option.data.len() as u8; p[length + 2..length + 2 + option.data.len()].clone_from_slice(&option.data); length += 2 + option.data.len(); } p[length] = END; length += 1; if length < 272 { // Pad to min size p[length..272].clone_from_slice(&[PAD; 32][..272 - length]); length = 272 } &p[..length] } } const COOKIE: [u8; 4] = [99, 130, 83, 99]; const BOOT_REQUEST: u8 = 1; // From Client; const BOOT_REPLY: u8 = 2; // From Server; const END: u8 = 255; const PAD: u8 = 0;
decode_ipv4
identifier_name
client.rs
// Rust JSON-RPC Library // Written in 2015 by // Andrew Poelstra <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Client support //! //! Support for connecting to JSONRPC servers over HTTP, sending requests, //! and parsing responses //! use hyper::client::Client as HyperClient; use hyper::header::{Headers, Authorization, Basic}; use json; use json::value::Value as JsonValue; use super::{Request, Response}; use error::Error; /// A handle to a remote JSONRPC server #[derive(Clone, PartialEq, Eq, Debug)] pub struct Client { url: String, user: Option<String>, pass: Option<String>, nonce: u64 } impl Client { /// Creates a new client pub fn new(url: String, user: Option<String>, pass: Option<String>) -> Client { // Check that if we have a password, we have a username; other way around is ok debug_assert!(pass.is_none() || user.is_some()); Client { url: url, user: user, pass: pass, nonce: 0 } } /// Sends a request to a client pub fn send_request(&self, request: &Request) -> Result<Response, Error> { // Build request let request = json::to_string(&request).unwrap(); // Setup connection let mut headers = Headers::new(); if let Some(ref user) = self.user
// Send request let client = HyperClient::new(); let request = client.post(&self.url).headers(headers).body(&request); let stream = try!(request.send().map_err(Error::Hyper)); json::de::from_reader(stream).map_err(Error::Json) // TODO check nonces match } /// Builds a request pub fn build_request(&mut self, name: String, params: Vec<JsonValue>) -> Request { self.nonce += 1; Request { method: name, params: params, id: JsonValue::U64(self.nonce) } } } #[cfg(test)] mod tests { use super::Client; #[test] fn sanity() { let mut client = Client::new("localhost".to_owned(), None, None); let req1 = client.build_request("test".to_owned(), vec![]); let req2 = client.build_request("test".to_owned(), vec![]); assert!(req1!= req2); } }
{ headers.set(Authorization(Basic { username: user.clone(), password: self.pass.clone() })); }
conditional_block
client.rs
// Rust JSON-RPC Library // Written in 2015 by // Andrew Poelstra <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Client support //! //! Support for connecting to JSONRPC servers over HTTP, sending requests, //! and parsing responses //! use hyper::client::Client as HyperClient; use hyper::header::{Headers, Authorization, Basic}; use json; use json::value::Value as JsonValue; use super::{Request, Response}; use error::Error; /// A handle to a remote JSONRPC server #[derive(Clone, PartialEq, Eq, Debug)] pub struct Client { url: String, user: Option<String>, pass: Option<String>, nonce: u64 } impl Client { /// Creates a new client pub fn
(url: String, user: Option<String>, pass: Option<String>) -> Client { // Check that if we have a password, we have a username; other way around is ok debug_assert!(pass.is_none() || user.is_some()); Client { url: url, user: user, pass: pass, nonce: 0 } } /// Sends a request to a client pub fn send_request(&self, request: &Request) -> Result<Response, Error> { // Build request let request = json::to_string(&request).unwrap(); // Setup connection let mut headers = Headers::new(); if let Some(ref user) = self.user { headers.set(Authorization(Basic { username: user.clone(), password: self.pass.clone() })); } // Send request let client = HyperClient::new(); let request = client.post(&self.url).headers(headers).body(&request); let stream = try!(request.send().map_err(Error::Hyper)); json::de::from_reader(stream).map_err(Error::Json) // TODO check nonces match } /// Builds a request pub fn build_request(&mut self, name: String, params: Vec<JsonValue>) -> Request { self.nonce += 1; Request { method: name, params: params, id: JsonValue::U64(self.nonce) } } } #[cfg(test)] mod tests { use super::Client; #[test] fn sanity() { let mut client = Client::new("localhost".to_owned(), None, None); let req1 = client.build_request("test".to_owned(), vec![]); let req2 = client.build_request("test".to_owned(), vec![]); assert!(req1!= req2); } }
new
identifier_name
client.rs
// Rust JSON-RPC Library // Written in 2015 by // Andrew Poelstra <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Client support //! //! Support for connecting to JSONRPC servers over HTTP, sending requests, //! and parsing responses //! use hyper::client::Client as HyperClient; use hyper::header::{Headers, Authorization, Basic}; use json; use json::value::Value as JsonValue; use super::{Request, Response}; use error::Error; /// A handle to a remote JSONRPC server #[derive(Clone, PartialEq, Eq, Debug)] pub struct Client { url: String, user: Option<String>, pass: Option<String>, nonce: u64 } impl Client { /// Creates a new client pub fn new(url: String, user: Option<String>, pass: Option<String>) -> Client { // Check that if we have a password, we have a username; other way around is ok debug_assert!(pass.is_none() || user.is_some()); Client { url: url, user: user,
pass: pass, nonce: 0 } } /// Sends a request to a client pub fn send_request(&self, request: &Request) -> Result<Response, Error> { // Build request let request = json::to_string(&request).unwrap(); // Setup connection let mut headers = Headers::new(); if let Some(ref user) = self.user { headers.set(Authorization(Basic { username: user.clone(), password: self.pass.clone() })); } // Send request let client = HyperClient::new(); let request = client.post(&self.url).headers(headers).body(&request); let stream = try!(request.send().map_err(Error::Hyper)); json::de::from_reader(stream).map_err(Error::Json) // TODO check nonces match } /// Builds a request pub fn build_request(&mut self, name: String, params: Vec<JsonValue>) -> Request { self.nonce += 1; Request { method: name, params: params, id: JsonValue::U64(self.nonce) } } } #[cfg(test)] mod tests { use super::Client; #[test] fn sanity() { let mut client = Client::new("localhost".to_owned(), None, None); let req1 = client.build_request("test".to_owned(), vec![]); let req2 = client.build_request("test".to_owned(), vec![]); assert!(req1!= req2); } }
random_line_split
noise.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Multi-language Perlin noise benchmark. // See https://github.com/nsf/pnoise for timings and alternative implementations. // ignore-lexer-test FIXME #15679 #![feature(rand, core)] use std::f32::consts::PI; use std::num::Float; use std::rand::{Rng, StdRng}; #[derive(Copy, Clone)] struct Vec2 { x: f32, y: f32, } fn lerp(a: f32, b: f32, v: f32) -> f32 { a * (1.0 - v) + b * v } fn smooth(v: f32) -> f32 { v * v * (3.0 - 2.0 * v) } fn random_gradient<R: Rng>(r: &mut R) -> Vec2 { let v = PI * 2.0 * r.gen::<f32>(); Vec2 { x: v.cos(), y: v.sin() } } fn gradient(orig: Vec2, grad: Vec2, p: Vec2) -> f32 { (p.x - orig.x) * grad.x + (p.y - orig.y) * grad.y } struct Noise2DContext { rgradients: [Vec2; 256], permutations: [i32; 256], } impl Noise2DContext { fn new() -> Noise2DContext { let mut rng = StdRng::new().unwrap(); let mut rgradients = [Vec2 { x: 0.0, y: 0.0 }; 256]; for x in &mut rgradients[..] { *x = random_gradient(&mut rng); } let mut permutations = [0; 256]; for (i, x) in permutations.iter_mut().enumerate() { *x = i as i32; } rng.shuffle(&mut permutations); Noise2DContext { rgradients: rgradients, permutations: permutations } } fn
(&self, x: i32, y: i32) -> Vec2 { let idx = self.permutations[(x & 255) as usize] + self.permutations[(y & 255) as usize]; self.rgradients[(idx & 255) as usize] } fn get_gradients(&self, x: f32, y: f32) -> ([Vec2; 4], [Vec2; 4]) { let x0f = x.floor(); let y0f = y.floor(); let x1f = x0f + 1.0; let y1f = y0f + 1.0; let x0 = x0f as i32; let y0 = y0f as i32; let x1 = x0 + 1; let y1 = y0 + 1; ([self.get_gradient(x0, y0), self.get_gradient(x1, y0), self.get_gradient(x0, y1), self.get_gradient(x1, y1)], [Vec2 { x: x0f, y: y0f }, Vec2 { x: x1f, y: y0f }, Vec2 { x: x0f, y: y1f }, Vec2 { x: x1f, y: y1f }]) } fn get(&self, x: f32, y: f32) -> f32 { let p = Vec2 {x: x, y: y}; let (gradients, origins) = self.get_gradients(x, y); let v0 = gradient(origins[0], gradients[0], p); let v1 = gradient(origins[1], gradients[1], p); let v2 = gradient(origins[2], gradients[2], p); let v3 = gradient(origins[3], gradients[3], p); let fx = smooth(x - origins[0].x); let vx0 = lerp(v0, v1, fx); let vx1 = lerp(v2, v3, fx); let fy = smooth(y - origins[0].y); lerp(vx0, vx1, fy) } } fn main() { let symbols = [' ', '░', '▒', '▓', '█', '█']; let mut pixels = [0f32; 256*256]; let n2d = Noise2DContext::new(); for _ in 0..100 { for y in 0..256 { for x in 0..256 { let v = n2d.get(x as f32 * 0.1, y as f32 * 0.1); pixels[y*256+x] = v * 0.5 + 0.5; } } } for y in 0..256 { for x in 0..256 { let idx = (pixels[y*256+x] / 0.2) as usize; print!("{}", symbols[idx]); } print!("\n"); } }
get_gradient
identifier_name
noise.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Multi-language Perlin noise benchmark. // See https://github.com/nsf/pnoise for timings and alternative implementations. // ignore-lexer-test FIXME #15679 #![feature(rand, core)] use std::f32::consts::PI; use std::num::Float; use std::rand::{Rng, StdRng}; #[derive(Copy, Clone)] struct Vec2 { x: f32, y: f32, } fn lerp(a: f32, b: f32, v: f32) -> f32 { a * (1.0 - v) + b * v } fn smooth(v: f32) -> f32 { v * v * (3.0 - 2.0 * v) } fn random_gradient<R: Rng>(r: &mut R) -> Vec2 { let v = PI * 2.0 * r.gen::<f32>(); Vec2 { x: v.cos(), y: v.sin() } } fn gradient(orig: Vec2, grad: Vec2, p: Vec2) -> f32 { (p.x - orig.x) * grad.x + (p.y - orig.y) * grad.y } struct Noise2DContext { rgradients: [Vec2; 256], permutations: [i32; 256], } impl Noise2DContext { fn new() -> Noise2DContext { let mut rng = StdRng::new().unwrap(); let mut rgradients = [Vec2 { x: 0.0, y: 0.0 }; 256]; for x in &mut rgradients[..] { *x = random_gradient(&mut rng); } let mut permutations = [0; 256]; for (i, x) in permutations.iter_mut().enumerate() { *x = i as i32; } rng.shuffle(&mut permutations); Noise2DContext { rgradients: rgradients, permutations: permutations } } fn get_gradient(&self, x: i32, y: i32) -> Vec2 { let idx = self.permutations[(x & 255) as usize] + self.permutations[(y & 255) as usize]; self.rgradients[(idx & 255) as usize] } fn get_gradients(&self, x: f32, y: f32) -> ([Vec2; 4], [Vec2; 4]) { let x0f = x.floor(); let y0f = y.floor(); let x1f = x0f + 1.0; let y1f = y0f + 1.0; let x0 = x0f as i32; let y0 = y0f as i32; let x1 = x0 + 1; let y1 = y0 + 1; ([self.get_gradient(x0, y0), self.get_gradient(x1, y0), self.get_gradient(x0, y1), self.get_gradient(x1, y1)], [Vec2 { x: x0f, y: y0f }, Vec2 { x: x1f, y: y0f }, Vec2 { x: x0f, y: y1f }, Vec2 { x: x1f, y: y1f }]) } fn get(&self, x: f32, y: f32) -> f32 { let p = Vec2 {x: x, y: y}; let (gradients, origins) = self.get_gradients(x, y); let v0 = gradient(origins[0], gradients[0], p); let v1 = gradient(origins[1], gradients[1], p); let v2 = gradient(origins[2], gradients[2], p); let v3 = gradient(origins[3], gradients[3], p); let fx = smooth(x - origins[0].x); let vx0 = lerp(v0, v1, fx); let vx1 = lerp(v2, v3, fx); let fy = smooth(y - origins[0].y); lerp(vx0, vx1, fy) } } fn main() { let symbols = [' ', '░', '▒', '▓', '█', '█']; let mut pixels = [0f32; 256*256]; let n2d = Noise2DContext::new(); for _ in 0..100 { for y in 0..256 { for x in 0..256 { let v = n2d.get(x as f32 * 0.1, y as f32 * 0.1); pixels[y*256+x] = v * 0.5 + 0.5; } }
for x in 0..256 { let idx = (pixels[y*256+x] / 0.2) as usize; print!("{}", symbols[idx]); } print!("\n"); } }
} for y in 0..256 {
random_line_split
chunk.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::{bail, Error, Result}; use bytes_old::{BufMut, Bytes, BytesMut}; use tokio_codec::{Decoder, Encoder}; use crate::errors::ErrorKind; use crate::utils::BytesExt; /// A bundle2 chunk. /// /// Chunks underlie the bundle2 protocol. A chunk is a series of bytes and is /// encoded as: /// /// i32 chunk_size /// [u8] data (chunk_size bytes) /// /// Normally chunk_size > 0. /// /// There are two special kinds of chunks: /// /// 1. An "empty chunk", which is simply a chunk of size 0. This is represented /// as a Normal chunk below with an empty Bytes. /// 2. An "error chunk", which is a chunk with size -1 and no data. Error chunks /// interrupt a chunk stream and are followed by a new part. #[derive(Clone, Debug, PartialEq)] pub struct Chunk(ChunkInner); // This is separate to prevent constructing chunks with unexpected Bytes objects. #[derive(Clone, Debug, PartialEq)] enum ChunkInner { Normal(Bytes), Error, } impl Chunk { pub fn new<T: Into<Bytes>>(val: T) -> Result<Self> { let bytes: Bytes = val.into(); if bytes.len() > i32::max_value() as usize { bail!(ErrorKind::Bundle2Chunk(format!( "chunk of length {} exceeds maximum {}", bytes.len(), i32::max_value() ))); } Ok(Chunk(ChunkInner::Normal(bytes))) } pub fn empty() -> Self { Chunk(ChunkInner::Normal(Bytes::new())) } pub fn error() -> Self { Chunk(ChunkInner::Error) } pub fn is_normal(&self) -> bool { match self.0 { ChunkInner::Normal(_) => true, ChunkInner::Error => false, } } pub fn is_empty(&self) -> bool { match self.0 { ChunkInner::Normal(ref bytes) => bytes.is_empty(), ChunkInner::Error => false, } } pub fn is_error(&self) -> bool { match self.0 { ChunkInner::Normal(_) => false, ChunkInner::Error => true, } } /// Convert a chunk into its inner bytes. /// /// Returns an error if this chunk was an error chunk, since those do not /// have any bytes associated with them. pub fn into_bytes(self) -> Result<Bytes> { match self.0 { ChunkInner::Normal(bytes) => Ok(bytes), ChunkInner::Error => bail!("error chunk, no associated bytes"), } } } /// Encode a bundle2 chunk into a bytestream. #[derive(Debug)] pub struct ChunkEncoder; impl Encoder for ChunkEncoder { type Item = Chunk; type Error = Error; fn encode(&mut self, item: Chunk, dst: &mut BytesMut) -> Result<()> { match item.0 { ChunkInner::Normal(bytes) => { dst.reserve(4 + bytes.len()); dst.put_i32_be(bytes.len() as i32); dst.put_slice(&bytes); } ChunkInner::Error => { dst.reserve(4); dst.put_i32_be(-1); } } Ok(()) } } /// Decode a bytestream into bundle2 chunks. #[allow(dead_code)] pub struct ChunkDecoder; impl Decoder for ChunkDecoder { type Item = Chunk; type Error = Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Chunk>> { if src.len() < 4 { return Ok(None); } let len = src.peek_i32(); if len == -1 { src.drain_i32(); return Ok(Some(Chunk::error())); } if len < 0 { bail!(ErrorKind::Bundle2Chunk(format!( "chunk length must be >= -1, found {}", len ),)); } let len = len as usize; if src.len() < 4 + len { return Ok(None); } src.drain_i32(); let chunk = Chunk::new(src.split_to(len))?; Ok(Some(chunk)) } } #[cfg(test)] mod test { use std::io::Cursor; use assert_matches::assert_matches; use futures::compat::Future01CompatExt; use futures_old::{stream, Future, Sink, Stream}; use quickcheck::{quickcheck, TestResult}; use tokio_codec::{FramedRead, FramedWrite}; use super::*; #[test] fn test_empty_chunk() { let mut buf = BytesMut::with_capacity(4); buf.put_i32_be(0); let mut decoder = ChunkDecoder; let chunk = decoder.decode(&mut buf).unwrap().unwrap(); assert_eq!(chunk, Chunk::empty()); assert!(chunk.is_normal()); assert!(chunk.is_empty()); assert!(!chunk.is_error()); } #[test] fn
() { let mut buf = BytesMut::with_capacity(4); buf.put_i32_be(-1); let mut decoder = ChunkDecoder; let chunk = decoder.decode(&mut buf).unwrap().unwrap(); assert_eq!(chunk, Chunk::error()); assert!(!chunk.is_normal()); assert!(!chunk.is_empty()); assert!(chunk.is_error()); } #[test] fn test_invalid_chunk() { let mut buf = BytesMut::with_capacity(4); buf.put_i32_be(-2); let mut decoder = ChunkDecoder; let chunk_err = decoder.decode(&mut buf); let err = chunk_err.unwrap_err(); assert_matches!( err.downcast::<ErrorKind>().unwrap(), ErrorKind::Bundle2Chunk(_) ); } #[test] fn test_roundtrip() { // Avoid using the quickcheck! macro because it eats up line numbers in // stack traces. quickcheck(roundtrip as fn(Vec<Option<Vec<u8>>>) -> TestResult); } fn roundtrip(data: Vec<Option<Vec<u8>>>) -> TestResult { let count = data.len(); // Treat Some(bytes) as a normal chunk, None as an error chunk. let chunks: Vec<Chunk> = data .into_iter() .map(|x| match x { Some(b) => Chunk::new(b).unwrap(), None => Chunk::error(), }) .collect(); // Make a clone so we can use chunks later. let chunks_res: Vec<Result<Chunk>> = chunks.clone().into_iter().map(|x| Ok(x)).collect(); let cursor = Cursor::new(Vec::with_capacity(32 * 1024)); let sink = FramedWrite::new(cursor, ChunkEncoder); let encode_fut = sink .send_all(stream::iter_ok(chunks_res).and_then(|x| x)) .map_err(|err| panic!("{:#?}", err)) .and_then(move |(sink, _)| { let mut cursor = sink.into_inner(); cursor.set_position(0); // cursor will now have the encoded byte stream. Run it through the decoder. let stream = FramedRead::new(cursor, ChunkDecoder); let collector: Vec<Chunk> = Vec::with_capacity(count); collector.send_all(stream.map_err(|err| { panic!("Unexpected error: {}", err); })) }) .map(move |(collector, _)| { assert_eq!(collector, chunks); }) .map_err(|err| panic!("{:#?}", err)); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(encode_fut.compat()).unwrap(); TestResult::passed() } }
test_error_chunk
identifier_name
chunk.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::{bail, Error, Result}; use bytes_old::{BufMut, Bytes, BytesMut}; use tokio_codec::{Decoder, Encoder}; use crate::errors::ErrorKind; use crate::utils::BytesExt; /// A bundle2 chunk. /// /// Chunks underlie the bundle2 protocol. A chunk is a series of bytes and is /// encoded as: /// /// i32 chunk_size /// [u8] data (chunk_size bytes) /// /// Normally chunk_size > 0. /// /// There are two special kinds of chunks: /// /// 1. An "empty chunk", which is simply a chunk of size 0. This is represented /// as a Normal chunk below with an empty Bytes. /// 2. An "error chunk", which is a chunk with size -1 and no data. Error chunks /// interrupt a chunk stream and are followed by a new part. #[derive(Clone, Debug, PartialEq)] pub struct Chunk(ChunkInner); // This is separate to prevent constructing chunks with unexpected Bytes objects. #[derive(Clone, Debug, PartialEq)] enum ChunkInner { Normal(Bytes), Error, } impl Chunk { pub fn new<T: Into<Bytes>>(val: T) -> Result<Self> { let bytes: Bytes = val.into(); if bytes.len() > i32::max_value() as usize { bail!(ErrorKind::Bundle2Chunk(format!( "chunk of length {} exceeds maximum {}", bytes.len(), i32::max_value() ))); } Ok(Chunk(ChunkInner::Normal(bytes))) } pub fn empty() -> Self { Chunk(ChunkInner::Normal(Bytes::new())) } pub fn error() -> Self { Chunk(ChunkInner::Error) } pub fn is_normal(&self) -> bool { match self.0 { ChunkInner::Normal(_) => true, ChunkInner::Error => false, } } pub fn is_empty(&self) -> bool { match self.0 { ChunkInner::Normal(ref bytes) => bytes.is_empty(), ChunkInner::Error => false, } } pub fn is_error(&self) -> bool { match self.0 { ChunkInner::Normal(_) => false, ChunkInner::Error => true, } } /// Convert a chunk into its inner bytes. /// /// Returns an error if this chunk was an error chunk, since those do not /// have any bytes associated with them. pub fn into_bytes(self) -> Result<Bytes> { match self.0 { ChunkInner::Normal(bytes) => Ok(bytes), ChunkInner::Error => bail!("error chunk, no associated bytes"), } } } /// Encode a bundle2 chunk into a bytestream. #[derive(Debug)] pub struct ChunkEncoder; impl Encoder for ChunkEncoder { type Item = Chunk; type Error = Error; fn encode(&mut self, item: Chunk, dst: &mut BytesMut) -> Result<()> { match item.0 { ChunkInner::Normal(bytes) => { dst.reserve(4 + bytes.len()); dst.put_i32_be(bytes.len() as i32); dst.put_slice(&bytes); } ChunkInner::Error => { dst.reserve(4); dst.put_i32_be(-1); } } Ok(()) } } /// Decode a bytestream into bundle2 chunks. #[allow(dead_code)] pub struct ChunkDecoder; impl Decoder for ChunkDecoder { type Item = Chunk; type Error = Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Chunk>> { if src.len() < 4 { return Ok(None); } let len = src.peek_i32(); if len == -1 { src.drain_i32(); return Ok(Some(Chunk::error())); } if len < 0 { bail!(ErrorKind::Bundle2Chunk(format!( "chunk length must be >= -1, found {}", len ),)); } let len = len as usize; if src.len() < 4 + len { return Ok(None); } src.drain_i32(); let chunk = Chunk::new(src.split_to(len))?; Ok(Some(chunk)) } }
use assert_matches::assert_matches; use futures::compat::Future01CompatExt; use futures_old::{stream, Future, Sink, Stream}; use quickcheck::{quickcheck, TestResult}; use tokio_codec::{FramedRead, FramedWrite}; use super::*; #[test] fn test_empty_chunk() { let mut buf = BytesMut::with_capacity(4); buf.put_i32_be(0); let mut decoder = ChunkDecoder; let chunk = decoder.decode(&mut buf).unwrap().unwrap(); assert_eq!(chunk, Chunk::empty()); assert!(chunk.is_normal()); assert!(chunk.is_empty()); assert!(!chunk.is_error()); } #[test] fn test_error_chunk() { let mut buf = BytesMut::with_capacity(4); buf.put_i32_be(-1); let mut decoder = ChunkDecoder; let chunk = decoder.decode(&mut buf).unwrap().unwrap(); assert_eq!(chunk, Chunk::error()); assert!(!chunk.is_normal()); assert!(!chunk.is_empty()); assert!(chunk.is_error()); } #[test] fn test_invalid_chunk() { let mut buf = BytesMut::with_capacity(4); buf.put_i32_be(-2); let mut decoder = ChunkDecoder; let chunk_err = decoder.decode(&mut buf); let err = chunk_err.unwrap_err(); assert_matches!( err.downcast::<ErrorKind>().unwrap(), ErrorKind::Bundle2Chunk(_) ); } #[test] fn test_roundtrip() { // Avoid using the quickcheck! macro because it eats up line numbers in // stack traces. quickcheck(roundtrip as fn(Vec<Option<Vec<u8>>>) -> TestResult); } fn roundtrip(data: Vec<Option<Vec<u8>>>) -> TestResult { let count = data.len(); // Treat Some(bytes) as a normal chunk, None as an error chunk. let chunks: Vec<Chunk> = data .into_iter() .map(|x| match x { Some(b) => Chunk::new(b).unwrap(), None => Chunk::error(), }) .collect(); // Make a clone so we can use chunks later. let chunks_res: Vec<Result<Chunk>> = chunks.clone().into_iter().map(|x| Ok(x)).collect(); let cursor = Cursor::new(Vec::with_capacity(32 * 1024)); let sink = FramedWrite::new(cursor, ChunkEncoder); let encode_fut = sink .send_all(stream::iter_ok(chunks_res).and_then(|x| x)) .map_err(|err| panic!("{:#?}", err)) .and_then(move |(sink, _)| { let mut cursor = sink.into_inner(); cursor.set_position(0); // cursor will now have the encoded byte stream. Run it through the decoder. let stream = FramedRead::new(cursor, ChunkDecoder); let collector: Vec<Chunk> = Vec::with_capacity(count); collector.send_all(stream.map_err(|err| { panic!("Unexpected error: {}", err); })) }) .map(move |(collector, _)| { assert_eq!(collector, chunks); }) .map_err(|err| panic!("{:#?}", err)); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(encode_fut.compat()).unwrap(); TestResult::passed() } }
#[cfg(test)] mod test { use std::io::Cursor;
random_line_split
mod.rs
use std::fmt; use std::iter; pub mod persistence; pub mod editor; pub mod util; #[derive(Debug)] pub struct Note { pub id: Option<isize>, pub name: String, pub content: String }
impl fmt::Display for Note { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let _ = match self.id { Some(id) => write!(f, "{}. ", id), None => write!(f, "[unsaved] "), }; write!(f, "{}\n{}", self.name, self.content) } } impl Note { pub fn new(id: Option<isize>, name: &str, content: &str) -> Note { Note { id: id, name: name.to_string(), content: content.to_string() } } pub fn as_markdown(&self) -> String { let mut ret = String::new(); ret.push_str(&self.name); ret.push_str("\n"); let underline: String = iter::repeat("=").take(self.name.len()).collect(); ret.push_str(&underline); ret.push_str("\n"); ret.push_str(&self.content); ret.push_str("\n"); ret } }
random_line_split
mod.rs
use std::fmt; use std::iter; pub mod persistence; pub mod editor; pub mod util; #[derive(Debug)] pub struct
{ pub id: Option<isize>, pub name: String, pub content: String } impl fmt::Display for Note { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let _ = match self.id { Some(id) => write!(f, "{}. ", id), None => write!(f, "[unsaved] "), }; write!(f, "{}\n{}", self.name, self.content) } } impl Note { pub fn new(id: Option<isize>, name: &str, content: &str) -> Note { Note { id: id, name: name.to_string(), content: content.to_string() } } pub fn as_markdown(&self) -> String { let mut ret = String::new(); ret.push_str(&self.name); ret.push_str("\n"); let underline: String = iter::repeat("=").take(self.name.len()).collect(); ret.push_str(&underline); ret.push_str("\n"); ret.push_str(&self.content); ret.push_str("\n"); ret } }
Note
identifier_name
mod.rs
use std::fmt; use std::iter; pub mod persistence; pub mod editor; pub mod util; #[derive(Debug)] pub struct Note { pub id: Option<isize>, pub name: String, pub content: String } impl fmt::Display for Note { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let _ = match self.id { Some(id) => write!(f, "{}. ", id), None => write!(f, "[unsaved] "), }; write!(f, "{}\n{}", self.name, self.content) } } impl Note { pub fn new(id: Option<isize>, name: &str, content: &str) -> Note
pub fn as_markdown(&self) -> String { let mut ret = String::new(); ret.push_str(&self.name); ret.push_str("\n"); let underline: String = iter::repeat("=").take(self.name.len()).collect(); ret.push_str(&underline); ret.push_str("\n"); ret.push_str(&self.content); ret.push_str("\n"); ret } }
{ Note { id: id, name: name.to_string(), content: content.to_string() } }
identifier_body
sha2.rs
// Copyright (c) 2018-2019, The Tor Project, Inc. // Copyright (c) 2018, isis agora lovecruft // See LICENSE for licensing information //! Hash Digests and eXtendible Output Functions (XOFs) pub use digest::Digest; use digest::generic_array::typenum::U32; use digest::generic_array::typenum::U64; use digest::generic_array::GenericArray; use digest::BlockInput; use digest::FixedOutput; use digest::Input; use external::crypto_digest::get_256_bit_digest; use external::crypto_digest::get_512_bit_digest; use external::crypto_digest::CryptoDigest; use external::crypto_digest::DigestAlgorithm; pub use external::crypto_digest::DIGEST256_LEN; pub use external::crypto_digest::DIGEST512_LEN; /// The block size for both SHA-256 and SHA-512 digests is 512 bits/64 bytes. /// /// Unfortunately, we have to use the generic_array crate currently to express /// this at compile time. Later, in the future, when Rust implements const /// generics, we'll be able to remove this dependency (actually, it will get /// removed from the digest crate, which is currently `pub use`ing it). type BlockSize = U64; /// A SHA2-256 digest. /// /// # C_RUST_COUPLED /// /// * `crypto_digest_dup` #[derive(Clone)] pub struct Sha256 { engine: CryptoDigest, } /// Construct a new, default instance of a `Sha256` hash digest function. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha256, Digest}; /// /// let mut hasher: Sha256 = Sha256::default(); /// ``` /// /// # Returns /// /// A new `Sha256` digest. impl Default for Sha256 { fn default() -> Sha256 { Sha256 { engine: CryptoDigest::new(Some(DigestAlgorithm::SHA2_256)), } } } impl BlockInput for Sha256 { type BlockSize = BlockSize; } /// Input `msg` into the digest. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha256, Digest}; /// /// let mut hasher: Sha256 = Sha256::default(); /// /// hasher.input(b"foo"); /// hasher.input(b"bar"); /// ``` impl Input for Sha256 { fn process(&mut self, msg: &[u8]) { self.engine.add_bytes(&msg); } } /// Retrieve the output hash from everything which has been fed into this /// `Sha256` digest thus far. /// // // FIXME: Once const generics land in Rust, we should genericise calling // crypto_digest_get_digest in external::crypto_digest. impl FixedOutput for Sha256 { type OutputSize = U32; fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> { let buffer: [u8; DIGEST256_LEN] = get_256_bit_digest(self.engine); GenericArray::from(buffer) } } /// A SHA2-512 digest.
/// /// # C_RUST_COUPLED /// /// * `crypto_digest_dup` #[derive(Clone)] pub struct Sha512 { engine: CryptoDigest, } /// Construct a new, default instance of a `Sha512` hash digest function. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha512, Digest}; /// /// let mut hasher: Sha512 = Sha512::default(); /// ``` /// /// # Returns /// /// A new `Sha512` digest. impl Default for Sha512 { fn default() -> Sha512 { Sha512 { engine: CryptoDigest::new(Some(DigestAlgorithm::SHA2_512)), } } } impl BlockInput for Sha512 { type BlockSize = BlockSize; } /// Input `msg` into the digest. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha512, Digest}; /// /// let mut hasher: Sha512 = Sha512::default(); /// /// hasher.input(b"foo"); /// hasher.input(b"bar"); /// ``` impl Input for Sha512 { fn process(&mut self, msg: &[u8]) { self.engine.add_bytes(&msg); } } /// Retrieve the output hash from everything which has been fed into this /// `Sha512` digest thus far. /// // // FIXME: Once const generics land in Rust, we should genericise calling // crypto_digest_get_digest in external::crypto_digest. impl FixedOutput for Sha512 { type OutputSize = U64; fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> { let buffer: [u8; DIGEST512_LEN] = get_512_bit_digest(self.engine); GenericArray::clone_from_slice(&buffer) } } #[cfg(test)] mod test { #[cfg(feature = "test-c-from-rust")] use digest::Digest; #[cfg(feature = "test-c-from-rust")] use super::*; #[cfg(feature = "test-c-from-rust")] #[test] fn sha256_default() { let _: Sha256 = Sha256::default(); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha256_digest() { let mut h: Sha256 = Sha256::new(); let mut result: [u8; DIGEST256_LEN] = [0u8; DIGEST256_LEN]; let expected = [ 151, 223, 53, 136, 181, 163, 242, 75, 171, 195, 133, 27, 55, 47, 11, 167, 26, 157, 205, 222, 212, 59, 20, 185, 208, 105, 97, 191, 193, 112, 125, 157, ]; h.input(b"foo"); h.input(b"bar"); h.input(b"baz"); result.copy_from_slice(h.fixed_result().as_slice()); println!("{:?}", &result[..]); assert_eq!(result, expected); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha512_default() { let _: Sha512 = Sha512::default(); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha512_digest() { let mut h: Sha512 = Sha512::new(); let mut result: [u8; DIGEST512_LEN] = [0u8; DIGEST512_LEN]; let expected = [ 203, 55, 124, 16, 176, 245, 166, 44, 128, 54, 37, 167, 153, 217, 233, 8, 190, 69, 231, 103, 245, 209, 71, 212, 116, 73, 7, 203, 5, 89, 122, 164, 237, 211, 41, 160, 175, 20, 122, 221, 12, 244, 24, 30, 211, 40, 250, 30, 121, 148, 38, 88, 38, 179, 237, 61, 126, 246, 240, 103, 202, 153, 24, 90, ]; h.input(b"foo"); h.input(b"bar"); h.input(b"baz"); result.copy_from_slice(h.fixed_result().as_slice()); println!("{:?}", &result[..]); assert_eq!(&result[..], &expected[..]); } }
random_line_split
sha2.rs
// Copyright (c) 2018-2019, The Tor Project, Inc. // Copyright (c) 2018, isis agora lovecruft // See LICENSE for licensing information //! Hash Digests and eXtendible Output Functions (XOFs) pub use digest::Digest; use digest::generic_array::typenum::U32; use digest::generic_array::typenum::U64; use digest::generic_array::GenericArray; use digest::BlockInput; use digest::FixedOutput; use digest::Input; use external::crypto_digest::get_256_bit_digest; use external::crypto_digest::get_512_bit_digest; use external::crypto_digest::CryptoDigest; use external::crypto_digest::DigestAlgorithm; pub use external::crypto_digest::DIGEST256_LEN; pub use external::crypto_digest::DIGEST512_LEN; /// The block size for both SHA-256 and SHA-512 digests is 512 bits/64 bytes. /// /// Unfortunately, we have to use the generic_array crate currently to express /// this at compile time. Later, in the future, when Rust implements const /// generics, we'll be able to remove this dependency (actually, it will get /// removed from the digest crate, which is currently `pub use`ing it). type BlockSize = U64; /// A SHA2-256 digest. /// /// # C_RUST_COUPLED /// /// * `crypto_digest_dup` #[derive(Clone)] pub struct Sha256 { engine: CryptoDigest, } /// Construct a new, default instance of a `Sha256` hash digest function. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha256, Digest}; /// /// let mut hasher: Sha256 = Sha256::default(); /// ``` /// /// # Returns /// /// A new `Sha256` digest. impl Default for Sha256 { fn default() -> Sha256 { Sha256 { engine: CryptoDigest::new(Some(DigestAlgorithm::SHA2_256)), } } } impl BlockInput for Sha256 { type BlockSize = BlockSize; } /// Input `msg` into the digest. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha256, Digest}; /// /// let mut hasher: Sha256 = Sha256::default(); /// /// hasher.input(b"foo"); /// hasher.input(b"bar"); /// ``` impl Input for Sha256 { fn process(&mut self, msg: &[u8]) { self.engine.add_bytes(&msg); } } /// Retrieve the output hash from everything which has been fed into this /// `Sha256` digest thus far. /// // // FIXME: Once const generics land in Rust, we should genericise calling // crypto_digest_get_digest in external::crypto_digest. impl FixedOutput for Sha256 { type OutputSize = U32; fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> { let buffer: [u8; DIGEST256_LEN] = get_256_bit_digest(self.engine); GenericArray::from(buffer) } } /// A SHA2-512 digest. /// /// # C_RUST_COUPLED /// /// * `crypto_digest_dup` #[derive(Clone)] pub struct Sha512 { engine: CryptoDigest, } /// Construct a new, default instance of a `Sha512` hash digest function. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha512, Digest}; /// /// let mut hasher: Sha512 = Sha512::default(); /// ``` /// /// # Returns /// /// A new `Sha512` digest. impl Default for Sha512 { fn default() -> Sha512
} impl BlockInput for Sha512 { type BlockSize = BlockSize; } /// Input `msg` into the digest. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha512, Digest}; /// /// let mut hasher: Sha512 = Sha512::default(); /// /// hasher.input(b"foo"); /// hasher.input(b"bar"); /// ``` impl Input for Sha512 { fn process(&mut self, msg: &[u8]) { self.engine.add_bytes(&msg); } } /// Retrieve the output hash from everything which has been fed into this /// `Sha512` digest thus far. /// // // FIXME: Once const generics land in Rust, we should genericise calling // crypto_digest_get_digest in external::crypto_digest. impl FixedOutput for Sha512 { type OutputSize = U64; fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> { let buffer: [u8; DIGEST512_LEN] = get_512_bit_digest(self.engine); GenericArray::clone_from_slice(&buffer) } } #[cfg(test)] mod test { #[cfg(feature = "test-c-from-rust")] use digest::Digest; #[cfg(feature = "test-c-from-rust")] use super::*; #[cfg(feature = "test-c-from-rust")] #[test] fn sha256_default() { let _: Sha256 = Sha256::default(); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha256_digest() { let mut h: Sha256 = Sha256::new(); let mut result: [u8; DIGEST256_LEN] = [0u8; DIGEST256_LEN]; let expected = [ 151, 223, 53, 136, 181, 163, 242, 75, 171, 195, 133, 27, 55, 47, 11, 167, 26, 157, 205, 222, 212, 59, 20, 185, 208, 105, 97, 191, 193, 112, 125, 157, ]; h.input(b"foo"); h.input(b"bar"); h.input(b"baz"); result.copy_from_slice(h.fixed_result().as_slice()); println!("{:?}", &result[..]); assert_eq!(result, expected); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha512_default() { let _: Sha512 = Sha512::default(); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha512_digest() { let mut h: Sha512 = Sha512::new(); let mut result: [u8; DIGEST512_LEN] = [0u8; DIGEST512_LEN]; let expected = [ 203, 55, 124, 16, 176, 245, 166, 44, 128, 54, 37, 167, 153, 217, 233, 8, 190, 69, 231, 103, 245, 209, 71, 212, 116, 73, 7, 203, 5, 89, 122, 164, 237, 211, 41, 160, 175, 20, 122, 221, 12, 244, 24, 30, 211, 40, 250, 30, 121, 148, 38, 88, 38, 179, 237, 61, 126, 246, 240, 103, 202, 153, 24, 90, ]; h.input(b"foo"); h.input(b"bar"); h.input(b"baz"); result.copy_from_slice(h.fixed_result().as_slice()); println!("{:?}", &result[..]); assert_eq!(&result[..], &expected[..]); } }
{ Sha512 { engine: CryptoDigest::new(Some(DigestAlgorithm::SHA2_512)), } }
identifier_body
sha2.rs
// Copyright (c) 2018-2019, The Tor Project, Inc. // Copyright (c) 2018, isis agora lovecruft // See LICENSE for licensing information //! Hash Digests and eXtendible Output Functions (XOFs) pub use digest::Digest; use digest::generic_array::typenum::U32; use digest::generic_array::typenum::U64; use digest::generic_array::GenericArray; use digest::BlockInput; use digest::FixedOutput; use digest::Input; use external::crypto_digest::get_256_bit_digest; use external::crypto_digest::get_512_bit_digest; use external::crypto_digest::CryptoDigest; use external::crypto_digest::DigestAlgorithm; pub use external::crypto_digest::DIGEST256_LEN; pub use external::crypto_digest::DIGEST512_LEN; /// The block size for both SHA-256 and SHA-512 digests is 512 bits/64 bytes. /// /// Unfortunately, we have to use the generic_array crate currently to express /// this at compile time. Later, in the future, when Rust implements const /// generics, we'll be able to remove this dependency (actually, it will get /// removed from the digest crate, which is currently `pub use`ing it). type BlockSize = U64; /// A SHA2-256 digest. /// /// # C_RUST_COUPLED /// /// * `crypto_digest_dup` #[derive(Clone)] pub struct Sha256 { engine: CryptoDigest, } /// Construct a new, default instance of a `Sha256` hash digest function. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha256, Digest}; /// /// let mut hasher: Sha256 = Sha256::default(); /// ``` /// /// # Returns /// /// A new `Sha256` digest. impl Default for Sha256 { fn
() -> Sha256 { Sha256 { engine: CryptoDigest::new(Some(DigestAlgorithm::SHA2_256)), } } } impl BlockInput for Sha256 { type BlockSize = BlockSize; } /// Input `msg` into the digest. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha256, Digest}; /// /// let mut hasher: Sha256 = Sha256::default(); /// /// hasher.input(b"foo"); /// hasher.input(b"bar"); /// ``` impl Input for Sha256 { fn process(&mut self, msg: &[u8]) { self.engine.add_bytes(&msg); } } /// Retrieve the output hash from everything which has been fed into this /// `Sha256` digest thus far. /// // // FIXME: Once const generics land in Rust, we should genericise calling // crypto_digest_get_digest in external::crypto_digest. impl FixedOutput for Sha256 { type OutputSize = U32; fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> { let buffer: [u8; DIGEST256_LEN] = get_256_bit_digest(self.engine); GenericArray::from(buffer) } } /// A SHA2-512 digest. /// /// # C_RUST_COUPLED /// /// * `crypto_digest_dup` #[derive(Clone)] pub struct Sha512 { engine: CryptoDigest, } /// Construct a new, default instance of a `Sha512` hash digest function. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha512, Digest}; /// /// let mut hasher: Sha512 = Sha512::default(); /// ``` /// /// # Returns /// /// A new `Sha512` digest. impl Default for Sha512 { fn default() -> Sha512 { Sha512 { engine: CryptoDigest::new(Some(DigestAlgorithm::SHA2_512)), } } } impl BlockInput for Sha512 { type BlockSize = BlockSize; } /// Input `msg` into the digest. /// /// # Examples /// /// ```rust,no_run /// use crypto::digests::sha2::{Sha512, Digest}; /// /// let mut hasher: Sha512 = Sha512::default(); /// /// hasher.input(b"foo"); /// hasher.input(b"bar"); /// ``` impl Input for Sha512 { fn process(&mut self, msg: &[u8]) { self.engine.add_bytes(&msg); } } /// Retrieve the output hash from everything which has been fed into this /// `Sha512` digest thus far. /// // // FIXME: Once const generics land in Rust, we should genericise calling // crypto_digest_get_digest in external::crypto_digest. impl FixedOutput for Sha512 { type OutputSize = U64; fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> { let buffer: [u8; DIGEST512_LEN] = get_512_bit_digest(self.engine); GenericArray::clone_from_slice(&buffer) } } #[cfg(test)] mod test { #[cfg(feature = "test-c-from-rust")] use digest::Digest; #[cfg(feature = "test-c-from-rust")] use super::*; #[cfg(feature = "test-c-from-rust")] #[test] fn sha256_default() { let _: Sha256 = Sha256::default(); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha256_digest() { let mut h: Sha256 = Sha256::new(); let mut result: [u8; DIGEST256_LEN] = [0u8; DIGEST256_LEN]; let expected = [ 151, 223, 53, 136, 181, 163, 242, 75, 171, 195, 133, 27, 55, 47, 11, 167, 26, 157, 205, 222, 212, 59, 20, 185, 208, 105, 97, 191, 193, 112, 125, 157, ]; h.input(b"foo"); h.input(b"bar"); h.input(b"baz"); result.copy_from_slice(h.fixed_result().as_slice()); println!("{:?}", &result[..]); assert_eq!(result, expected); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha512_default() { let _: Sha512 = Sha512::default(); } #[cfg(feature = "test-c-from-rust")] #[test] fn sha512_digest() { let mut h: Sha512 = Sha512::new(); let mut result: [u8; DIGEST512_LEN] = [0u8; DIGEST512_LEN]; let expected = [ 203, 55, 124, 16, 176, 245, 166, 44, 128, 54, 37, 167, 153, 217, 233, 8, 190, 69, 231, 103, 245, 209, 71, 212, 116, 73, 7, 203, 5, 89, 122, 164, 237, 211, 41, 160, 175, 20, 122, 221, 12, 244, 24, 30, 211, 40, 250, 30, 121, 148, 38, 88, 38, 179, 237, 61, 126, 246, 240, 103, 202, 153, 24, 90, ]; h.input(b"foo"); h.input(b"bar"); h.input(b"baz"); result.copy_from_slice(h.fixed_result().as_slice()); println!("{:?}", &result[..]); assert_eq!(&result[..], &expected[..]); } }
default
identifier_name
value.rs
use serde::Serialize; use serde_json::value::{to_value, Value as Json}; pub(crate) static DEFAULT_VALUE: Json = Json::Null; /// A JSON wrapper designed for handlebars internal use case /// /// * Constant: the JSON value hardcoded into template /// * Context: the JSON value referenced in your provided data context /// * Derived: the owned JSON value computed during rendering process /// #[derive(Debug)] pub enum ScopedJson<'reg: 'rc, 'rc> { Constant(&'reg Json), Derived(Json), // represents a json reference to context value, its full path Context(&'rc Json, Vec<String>), Missing, } impl<'reg: 'rc, 'rc> ScopedJson<'reg, 'rc> { /// get the JSON reference pub fn as_json(&self) -> &Json { match self { ScopedJson::Constant(j) => j, ScopedJson::Derived(ref j) => j, ScopedJson::Context(j, _) => j, _ => &DEFAULT_VALUE, } } pub fn render(&self) -> String { self.as_json().render() } pub fn is_missing(&self) -> bool { matches!(self, ScopedJson::Missing) } pub fn into_derived(self) -> ScopedJson<'reg, 'rc> { let v = self.as_json(); ScopedJson::Derived(v.clone()) } pub fn context_path(&self) -> Option<&Vec<String>> { match self { ScopedJson::Context(_, ref p) => Some(p), _ => None, } } } impl<'reg: 'rc, 'rc> From<Json> for ScopedJson<'reg, 'rc> { fn from(v: Json) -> ScopedJson<'reg, 'rc> { ScopedJson::Derived(v) } } /// Json wrapper that holds the Json value and reference path information /// #[derive(Debug)] pub struct PathAndJson<'reg, 'rc> { relative_path: Option<String>, value: ScopedJson<'reg, 'rc>, } impl<'reg: 'rc, 'rc> PathAndJson<'reg, 'rc> { pub fn new( relative_path: Option<String>, value: ScopedJson<'reg, 'rc>, ) -> PathAndJson<'reg, 'rc> { PathAndJson { relative_path, value, } } /// Returns relative path when the value is referenced /// If the value is from a literal, the path is `None` pub fn relative_path(&self) -> Option<&String> { self.relative_path.as_ref() } /// Returns full path to this value if any pub fn context_path(&self) -> Option<&Vec<String>> { self.value.context_path() } /// Returns the value pub fn value(&self) -> &Json { self.value.as_json() } /// Test if value is missing pub fn is_value_missing(&self) -> bool { self.value.is_missing() } pub fn render(&self) -> String
} /// Render Json data with default format pub trait JsonRender { fn render(&self) -> String; } pub trait JsonTruthy { fn is_truthy(&self, include_zero: bool) -> bool; } impl JsonRender for Json { fn render(&self) -> String { match *self { Json::String(ref s) => s.to_string(), Json::Bool(i) => i.to_string(), Json::Number(ref n) => n.to_string(), Json::Null => "".to_owned(), Json::Array(ref a) => { let mut buf = String::new(); buf.push('['); for i in a.iter() { buf.push_str(i.render().as_ref()); buf.push_str(", "); } buf.push(']'); buf } Json::Object(_) => "[object]".to_owned(), } } } /// Convert any serializable data into Serde Json type pub fn to_json<T>(src: T) -> Json where T: Serialize, { to_value(src).unwrap_or_default() } pub fn as_string(src: &Json) -> Option<&str> { src.as_str() } impl JsonTruthy for Json { fn is_truthy(&self, include_zero: bool) -> bool { match *self { Json::Bool(ref i) => *i, Json::Number(ref n) => { if include_zero { n.as_f64().map(|f|!f.is_nan()).unwrap_or(false) } else { // there is no inifity in json/serde_json n.as_f64().map(|f| f.is_normal()).unwrap_or(false) } } Json::Null => false, Json::String(ref i) =>!i.is_empty(), Json::Array(ref i) =>!i.is_empty(), Json::Object(ref i) =>!i.is_empty(), } } } #[test] fn test_json_render() { let raw = "<p>Hello world</p>\n<p thing=\"hello\"</p>"; let thing = Json::String(raw.to_string()); assert_eq!(raw, thing.render()); } #[test] fn test_json_number_truthy() { use std::f64; assert!(json!(16i16).is_truthy(false)); assert!(json!(16i16).is_truthy(true)); assert!(json!(0i16).is_truthy(true)); assert!(!json!(0i16).is_truthy(false)); assert!(json!(1.0f64).is_truthy(false)); assert!(json!(1.0f64).is_truthy(true)); assert!(json!(Some(16i16)).is_truthy(false)); assert!(json!(Some(16i16)).is_truthy(true)); assert!(!json!(None as Option<i16>).is_truthy(false)); assert!(!json!(None as Option<i16>).is_truthy(true)); assert!(!json!(f64::NAN).is_truthy(false)); assert!(!json!(f64::NAN).is_truthy(true)); // there is no infinity in json/serde_json // assert!(json!(f64::INFINITY).is_truthy(false)); // assert!(json!(f64::INFINITY).is_truthy(true)); // assert!(json!(f64::NEG_INFINITY).is_truthy(false)); // assert!(json!(f64::NEG_INFINITY).is_truthy(true)); }
{ self.value.render() }
identifier_body
value.rs
use serde::Serialize; use serde_json::value::{to_value, Value as Json}; pub(crate) static DEFAULT_VALUE: Json = Json::Null; /// A JSON wrapper designed for handlebars internal use case /// /// * Constant: the JSON value hardcoded into template /// * Context: the JSON value referenced in your provided data context /// * Derived: the owned JSON value computed during rendering process /// #[derive(Debug)] pub enum ScopedJson<'reg: 'rc, 'rc> { Constant(&'reg Json), Derived(Json), // represents a json reference to context value, its full path Context(&'rc Json, Vec<String>), Missing, } impl<'reg: 'rc, 'rc> ScopedJson<'reg, 'rc> { /// get the JSON reference pub fn as_json(&self) -> &Json { match self { ScopedJson::Constant(j) => j, ScopedJson::Derived(ref j) => j, ScopedJson::Context(j, _) => j, _ => &DEFAULT_VALUE, } } pub fn render(&self) -> String { self.as_json().render() } pub fn is_missing(&self) -> bool { matches!(self, ScopedJson::Missing) } pub fn into_derived(self) -> ScopedJson<'reg, 'rc> { let v = self.as_json(); ScopedJson::Derived(v.clone()) } pub fn context_path(&self) -> Option<&Vec<String>> { match self { ScopedJson::Context(_, ref p) => Some(p), _ => None, } } } impl<'reg: 'rc, 'rc> From<Json> for ScopedJson<'reg, 'rc> { fn from(v: Json) -> ScopedJson<'reg, 'rc> { ScopedJson::Derived(v) } } /// Json wrapper that holds the Json value and reference path information /// #[derive(Debug)] pub struct PathAndJson<'reg, 'rc> { relative_path: Option<String>, value: ScopedJson<'reg, 'rc>, } impl<'reg: 'rc, 'rc> PathAndJson<'reg, 'rc> { pub fn new( relative_path: Option<String>, value: ScopedJson<'reg, 'rc>, ) -> PathAndJson<'reg, 'rc> { PathAndJson { relative_path, value, } } /// Returns relative path when the value is referenced /// If the value is from a literal, the path is `None` pub fn relative_path(&self) -> Option<&String> { self.relative_path.as_ref() } /// Returns full path to this value if any pub fn context_path(&self) -> Option<&Vec<String>> { self.value.context_path() } /// Returns the value pub fn value(&self) -> &Json { self.value.as_json() } /// Test if value is missing pub fn is_value_missing(&self) -> bool { self.value.is_missing() } pub fn render(&self) -> String {
} /// Render Json data with default format pub trait JsonRender { fn render(&self) -> String; } pub trait JsonTruthy { fn is_truthy(&self, include_zero: bool) -> bool; } impl JsonRender for Json { fn render(&self) -> String { match *self { Json::String(ref s) => s.to_string(), Json::Bool(i) => i.to_string(), Json::Number(ref n) => n.to_string(), Json::Null => "".to_owned(), Json::Array(ref a) => { let mut buf = String::new(); buf.push('['); for i in a.iter() { buf.push_str(i.render().as_ref()); buf.push_str(", "); } buf.push(']'); buf } Json::Object(_) => "[object]".to_owned(), } } } /// Convert any serializable data into Serde Json type pub fn to_json<T>(src: T) -> Json where T: Serialize, { to_value(src).unwrap_or_default() } pub fn as_string(src: &Json) -> Option<&str> { src.as_str() } impl JsonTruthy for Json { fn is_truthy(&self, include_zero: bool) -> bool { match *self { Json::Bool(ref i) => *i, Json::Number(ref n) => { if include_zero { n.as_f64().map(|f|!f.is_nan()).unwrap_or(false) } else { // there is no inifity in json/serde_json n.as_f64().map(|f| f.is_normal()).unwrap_or(false) } } Json::Null => false, Json::String(ref i) =>!i.is_empty(), Json::Array(ref i) =>!i.is_empty(), Json::Object(ref i) =>!i.is_empty(), } } } #[test] fn test_json_render() { let raw = "<p>Hello world</p>\n<p thing=\"hello\"</p>"; let thing = Json::String(raw.to_string()); assert_eq!(raw, thing.render()); } #[test] fn test_json_number_truthy() { use std::f64; assert!(json!(16i16).is_truthy(false)); assert!(json!(16i16).is_truthy(true)); assert!(json!(0i16).is_truthy(true)); assert!(!json!(0i16).is_truthy(false)); assert!(json!(1.0f64).is_truthy(false)); assert!(json!(1.0f64).is_truthy(true)); assert!(json!(Some(16i16)).is_truthy(false)); assert!(json!(Some(16i16)).is_truthy(true)); assert!(!json!(None as Option<i16>).is_truthy(false)); assert!(!json!(None as Option<i16>).is_truthy(true)); assert!(!json!(f64::NAN).is_truthy(false)); assert!(!json!(f64::NAN).is_truthy(true)); // there is no infinity in json/serde_json // assert!(json!(f64::INFINITY).is_truthy(false)); // assert!(json!(f64::INFINITY).is_truthy(true)); // assert!(json!(f64::NEG_INFINITY).is_truthy(false)); // assert!(json!(f64::NEG_INFINITY).is_truthy(true)); }
self.value.render() }
random_line_split
value.rs
use serde::Serialize; use serde_json::value::{to_value, Value as Json}; pub(crate) static DEFAULT_VALUE: Json = Json::Null; /// A JSON wrapper designed for handlebars internal use case /// /// * Constant: the JSON value hardcoded into template /// * Context: the JSON value referenced in your provided data context /// * Derived: the owned JSON value computed during rendering process /// #[derive(Debug)] pub enum ScopedJson<'reg: 'rc, 'rc> { Constant(&'reg Json), Derived(Json), // represents a json reference to context value, its full path Context(&'rc Json, Vec<String>), Missing, } impl<'reg: 'rc, 'rc> ScopedJson<'reg, 'rc> { /// get the JSON reference pub fn as_json(&self) -> &Json { match self { ScopedJson::Constant(j) => j, ScopedJson::Derived(ref j) => j, ScopedJson::Context(j, _) => j, _ => &DEFAULT_VALUE, } } pub fn render(&self) -> String { self.as_json().render() } pub fn
(&self) -> bool { matches!(self, ScopedJson::Missing) } pub fn into_derived(self) -> ScopedJson<'reg, 'rc> { let v = self.as_json(); ScopedJson::Derived(v.clone()) } pub fn context_path(&self) -> Option<&Vec<String>> { match self { ScopedJson::Context(_, ref p) => Some(p), _ => None, } } } impl<'reg: 'rc, 'rc> From<Json> for ScopedJson<'reg, 'rc> { fn from(v: Json) -> ScopedJson<'reg, 'rc> { ScopedJson::Derived(v) } } /// Json wrapper that holds the Json value and reference path information /// #[derive(Debug)] pub struct PathAndJson<'reg, 'rc> { relative_path: Option<String>, value: ScopedJson<'reg, 'rc>, } impl<'reg: 'rc, 'rc> PathAndJson<'reg, 'rc> { pub fn new( relative_path: Option<String>, value: ScopedJson<'reg, 'rc>, ) -> PathAndJson<'reg, 'rc> { PathAndJson { relative_path, value, } } /// Returns relative path when the value is referenced /// If the value is from a literal, the path is `None` pub fn relative_path(&self) -> Option<&String> { self.relative_path.as_ref() } /// Returns full path to this value if any pub fn context_path(&self) -> Option<&Vec<String>> { self.value.context_path() } /// Returns the value pub fn value(&self) -> &Json { self.value.as_json() } /// Test if value is missing pub fn is_value_missing(&self) -> bool { self.value.is_missing() } pub fn render(&self) -> String { self.value.render() } } /// Render Json data with default format pub trait JsonRender { fn render(&self) -> String; } pub trait JsonTruthy { fn is_truthy(&self, include_zero: bool) -> bool; } impl JsonRender for Json { fn render(&self) -> String { match *self { Json::String(ref s) => s.to_string(), Json::Bool(i) => i.to_string(), Json::Number(ref n) => n.to_string(), Json::Null => "".to_owned(), Json::Array(ref a) => { let mut buf = String::new(); buf.push('['); for i in a.iter() { buf.push_str(i.render().as_ref()); buf.push_str(", "); } buf.push(']'); buf } Json::Object(_) => "[object]".to_owned(), } } } /// Convert any serializable data into Serde Json type pub fn to_json<T>(src: T) -> Json where T: Serialize, { to_value(src).unwrap_or_default() } pub fn as_string(src: &Json) -> Option<&str> { src.as_str() } impl JsonTruthy for Json { fn is_truthy(&self, include_zero: bool) -> bool { match *self { Json::Bool(ref i) => *i, Json::Number(ref n) => { if include_zero { n.as_f64().map(|f|!f.is_nan()).unwrap_or(false) } else { // there is no inifity in json/serde_json n.as_f64().map(|f| f.is_normal()).unwrap_or(false) } } Json::Null => false, Json::String(ref i) =>!i.is_empty(), Json::Array(ref i) =>!i.is_empty(), Json::Object(ref i) =>!i.is_empty(), } } } #[test] fn test_json_render() { let raw = "<p>Hello world</p>\n<p thing=\"hello\"</p>"; let thing = Json::String(raw.to_string()); assert_eq!(raw, thing.render()); } #[test] fn test_json_number_truthy() { use std::f64; assert!(json!(16i16).is_truthy(false)); assert!(json!(16i16).is_truthy(true)); assert!(json!(0i16).is_truthy(true)); assert!(!json!(0i16).is_truthy(false)); assert!(json!(1.0f64).is_truthy(false)); assert!(json!(1.0f64).is_truthy(true)); assert!(json!(Some(16i16)).is_truthy(false)); assert!(json!(Some(16i16)).is_truthy(true)); assert!(!json!(None as Option<i16>).is_truthy(false)); assert!(!json!(None as Option<i16>).is_truthy(true)); assert!(!json!(f64::NAN).is_truthy(false)); assert!(!json!(f64::NAN).is_truthy(true)); // there is no infinity in json/serde_json // assert!(json!(f64::INFINITY).is_truthy(false)); // assert!(json!(f64::INFINITY).is_truthy(true)); // assert!(json!(f64::NEG_INFINITY).is_truthy(false)); // assert!(json!(f64::NEG_INFINITY).is_truthy(true)); }
is_missing
identifier_name
arc_types.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This file lists all arc FFI types and defines corresponding addref //! and release functions. This list corresponds to ServoArcTypeList.h //! file in Gecko. #![allow(non_snake_case, missing_docs)] use gecko_bindings::bindings::RawServoCounterStyleRule; use gecko_bindings::bindings::RawServoFontFeatureValuesRule; use gecko_bindings::bindings::RawServoImportRule; use gecko_bindings::bindings::RawServoKeyframe; use gecko_bindings::bindings::RawServoKeyframesRule; use gecko_bindings::bindings::RawServoMediaRule; use gecko_bindings::bindings::RawServoMozDocumentRule; use gecko_bindings::bindings::RawServoNamespaceRule; use gecko_bindings::bindings::RawServoPageRule; use gecko_bindings::bindings::RawServoRuleNode; use gecko_bindings::bindings::RawServoRuleNodeStrong; use gecko_bindings::bindings::RawServoSupportsRule; use gecko_bindings::bindings::ServoCssRules; use gecko_bindings::structs::RawServoAnimationValue; use gecko_bindings::structs::RawServoDeclarationBlock; use gecko_bindings::structs::RawServoFontFaceRule; use gecko_bindings::structs::RawServoMediaList; use gecko_bindings::structs::RawServoStyleRule; use gecko_bindings::structs::RawServoStyleSheetContents; use gecko_bindings::sugar::ownership::{HasArcFFI, HasFFI, Strong}; use media_queries::MediaList; use properties::{ComputedValues, PropertyDeclarationBlock}; use properties::animated_properties::AnimationValue; use rule_tree::StrongRuleNode; use servo_arc::{Arc, ArcBorrow}; use shared_lock::Locked; use std::{mem, ptr}; use stylesheets::{CounterStyleRule, CssRules, FontFaceRule, FontFeatureValuesRule}; use stylesheets::{DocumentRule, ImportRule, KeyframesRule, MediaRule, NamespaceRule, PageRule}; use stylesheets::{StyleRule, StylesheetContents, SupportsRule}; use stylesheets::keyframes_rule::Keyframe; macro_rules! impl_arc_ffi { ($servo_type:ty => $gecko_type:ty[$addref:ident, $release:ident]) => { unsafe impl HasFFI for $servo_type { type FFIType = $gecko_type; } unsafe impl HasArcFFI for $servo_type {} #[no_mangle] pub unsafe extern "C" fn $addref(obj: &$gecko_type) { <$servo_type>::addref(obj); } #[no_mangle] pub unsafe extern "C" fn $release(obj: &$gecko_type) { <$servo_type>::release(obj); } }; } impl_arc_ffi!(Locked<CssRules> => ServoCssRules [Servo_CssRules_AddRef, Servo_CssRules_Release]); impl_arc_ffi!(StylesheetContents => RawServoStyleSheetContents [Servo_StyleSheetContents_AddRef, Servo_StyleSheetContents_Release]); impl_arc_ffi!(Locked<PropertyDeclarationBlock> => RawServoDeclarationBlock [Servo_DeclarationBlock_AddRef, Servo_DeclarationBlock_Release]); impl_arc_ffi!(Locked<StyleRule> => RawServoStyleRule [Servo_StyleRule_AddRef, Servo_StyleRule_Release]); impl_arc_ffi!(Locked<ImportRule> => RawServoImportRule [Servo_ImportRule_AddRef, Servo_ImportRule_Release]); impl_arc_ffi!(AnimationValue => RawServoAnimationValue [Servo_AnimationValue_AddRef, Servo_AnimationValue_Release]); impl_arc_ffi!(Locked<Keyframe> => RawServoKeyframe [Servo_Keyframe_AddRef, Servo_Keyframe_Release]); impl_arc_ffi!(Locked<KeyframesRule> => RawServoKeyframesRule [Servo_KeyframesRule_AddRef, Servo_KeyframesRule_Release]); impl_arc_ffi!(Locked<MediaList> => RawServoMediaList [Servo_MediaList_AddRef, Servo_MediaList_Release]); impl_arc_ffi!(Locked<MediaRule> => RawServoMediaRule [Servo_MediaRule_AddRef, Servo_MediaRule_Release]); impl_arc_ffi!(Locked<NamespaceRule> => RawServoNamespaceRule [Servo_NamespaceRule_AddRef, Servo_NamespaceRule_Release]); impl_arc_ffi!(Locked<PageRule> => RawServoPageRule [Servo_PageRule_AddRef, Servo_PageRule_Release]); impl_arc_ffi!(Locked<SupportsRule> => RawServoSupportsRule [Servo_SupportsRule_AddRef, Servo_SupportsRule_Release]); impl_arc_ffi!(Locked<DocumentRule> => RawServoMozDocumentRule [Servo_DocumentRule_AddRef, Servo_DocumentRule_Release]); impl_arc_ffi!(Locked<FontFeatureValuesRule> => RawServoFontFeatureValuesRule [Servo_FontFeatureValuesRule_AddRef, Servo_FontFeatureValuesRule_Release]); impl_arc_ffi!(Locked<FontFaceRule> => RawServoFontFaceRule [Servo_FontFaceRule_AddRef, Servo_FontFaceRule_Release]);
impl_arc_ffi!(Locked<CounterStyleRule> => RawServoCounterStyleRule [Servo_CounterStyleRule_AddRef, Servo_CounterStyleRule_Release]); // RuleNode is a Arc-like type but it does not use Arc. impl StrongRuleNode { pub fn into_strong(self) -> RawServoRuleNodeStrong { let ptr = self.ptr(); mem::forget(self); unsafe { mem::transmute(ptr) } } pub fn from_ffi<'a>(ffi: &'a &RawServoRuleNode) -> &'a Self { unsafe { &*(ffi as *const &RawServoRuleNode as *const StrongRuleNode) } } } #[no_mangle] pub unsafe extern "C" fn Servo_RuleNode_AddRef(obj: &RawServoRuleNode) { mem::forget(StrongRuleNode::from_ffi(&obj).clone()); } #[no_mangle] pub unsafe extern "C" fn Servo_RuleNode_Release(obj: &RawServoRuleNode) { let ptr = StrongRuleNode::from_ffi(&obj); ptr::read(ptr as *const StrongRuleNode); } // ComputedStyle is not an opaque type on any side of FFI. // This means that doing the HasArcFFI type trick is actually unsound, // since it gives us a way to construct an Arc<ComputedStyle> from // an &ComputedStyle, which in general is not allowed. So we // implement the restricted set of arc type functionality we need. #[no_mangle] pub unsafe extern "C" fn Servo_ComputedStyle_AddRef(obj: &ComputedValues) { mem::forget(ArcBorrow::from_ref(obj).clone_arc()); } #[no_mangle] pub unsafe extern "C" fn Servo_ComputedStyle_Release(obj: &ComputedValues) { ArcBorrow::from_ref(obj).with_arc(|a: &Arc<ComputedValues>| { let _: Arc<ComputedValues> = ptr::read(a); }); } impl From<Arc<ComputedValues>> for Strong<ComputedValues> { fn from(arc: Arc<ComputedValues>) -> Self { unsafe { mem::transmute(Arc::into_raw_offset(arc)) } } }
random_line_split
arc_types.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This file lists all arc FFI types and defines corresponding addref //! and release functions. This list corresponds to ServoArcTypeList.h //! file in Gecko. #![allow(non_snake_case, missing_docs)] use gecko_bindings::bindings::RawServoCounterStyleRule; use gecko_bindings::bindings::RawServoFontFeatureValuesRule; use gecko_bindings::bindings::RawServoImportRule; use gecko_bindings::bindings::RawServoKeyframe; use gecko_bindings::bindings::RawServoKeyframesRule; use gecko_bindings::bindings::RawServoMediaRule; use gecko_bindings::bindings::RawServoMozDocumentRule; use gecko_bindings::bindings::RawServoNamespaceRule; use gecko_bindings::bindings::RawServoPageRule; use gecko_bindings::bindings::RawServoRuleNode; use gecko_bindings::bindings::RawServoRuleNodeStrong; use gecko_bindings::bindings::RawServoSupportsRule; use gecko_bindings::bindings::ServoCssRules; use gecko_bindings::structs::RawServoAnimationValue; use gecko_bindings::structs::RawServoDeclarationBlock; use gecko_bindings::structs::RawServoFontFaceRule; use gecko_bindings::structs::RawServoMediaList; use gecko_bindings::structs::RawServoStyleRule; use gecko_bindings::structs::RawServoStyleSheetContents; use gecko_bindings::sugar::ownership::{HasArcFFI, HasFFI, Strong}; use media_queries::MediaList; use properties::{ComputedValues, PropertyDeclarationBlock}; use properties::animated_properties::AnimationValue; use rule_tree::StrongRuleNode; use servo_arc::{Arc, ArcBorrow}; use shared_lock::Locked; use std::{mem, ptr}; use stylesheets::{CounterStyleRule, CssRules, FontFaceRule, FontFeatureValuesRule}; use stylesheets::{DocumentRule, ImportRule, KeyframesRule, MediaRule, NamespaceRule, PageRule}; use stylesheets::{StyleRule, StylesheetContents, SupportsRule}; use stylesheets::keyframes_rule::Keyframe; macro_rules! impl_arc_ffi { ($servo_type:ty => $gecko_type:ty[$addref:ident, $release:ident]) => { unsafe impl HasFFI for $servo_type { type FFIType = $gecko_type; } unsafe impl HasArcFFI for $servo_type {} #[no_mangle] pub unsafe extern "C" fn $addref(obj: &$gecko_type) { <$servo_type>::addref(obj); } #[no_mangle] pub unsafe extern "C" fn $release(obj: &$gecko_type) { <$servo_type>::release(obj); } }; } impl_arc_ffi!(Locked<CssRules> => ServoCssRules [Servo_CssRules_AddRef, Servo_CssRules_Release]); impl_arc_ffi!(StylesheetContents => RawServoStyleSheetContents [Servo_StyleSheetContents_AddRef, Servo_StyleSheetContents_Release]); impl_arc_ffi!(Locked<PropertyDeclarationBlock> => RawServoDeclarationBlock [Servo_DeclarationBlock_AddRef, Servo_DeclarationBlock_Release]); impl_arc_ffi!(Locked<StyleRule> => RawServoStyleRule [Servo_StyleRule_AddRef, Servo_StyleRule_Release]); impl_arc_ffi!(Locked<ImportRule> => RawServoImportRule [Servo_ImportRule_AddRef, Servo_ImportRule_Release]); impl_arc_ffi!(AnimationValue => RawServoAnimationValue [Servo_AnimationValue_AddRef, Servo_AnimationValue_Release]); impl_arc_ffi!(Locked<Keyframe> => RawServoKeyframe [Servo_Keyframe_AddRef, Servo_Keyframe_Release]); impl_arc_ffi!(Locked<KeyframesRule> => RawServoKeyframesRule [Servo_KeyframesRule_AddRef, Servo_KeyframesRule_Release]); impl_arc_ffi!(Locked<MediaList> => RawServoMediaList [Servo_MediaList_AddRef, Servo_MediaList_Release]); impl_arc_ffi!(Locked<MediaRule> => RawServoMediaRule [Servo_MediaRule_AddRef, Servo_MediaRule_Release]); impl_arc_ffi!(Locked<NamespaceRule> => RawServoNamespaceRule [Servo_NamespaceRule_AddRef, Servo_NamespaceRule_Release]); impl_arc_ffi!(Locked<PageRule> => RawServoPageRule [Servo_PageRule_AddRef, Servo_PageRule_Release]); impl_arc_ffi!(Locked<SupportsRule> => RawServoSupportsRule [Servo_SupportsRule_AddRef, Servo_SupportsRule_Release]); impl_arc_ffi!(Locked<DocumentRule> => RawServoMozDocumentRule [Servo_DocumentRule_AddRef, Servo_DocumentRule_Release]); impl_arc_ffi!(Locked<FontFeatureValuesRule> => RawServoFontFeatureValuesRule [Servo_FontFeatureValuesRule_AddRef, Servo_FontFeatureValuesRule_Release]); impl_arc_ffi!(Locked<FontFaceRule> => RawServoFontFaceRule [Servo_FontFaceRule_AddRef, Servo_FontFaceRule_Release]); impl_arc_ffi!(Locked<CounterStyleRule> => RawServoCounterStyleRule [Servo_CounterStyleRule_AddRef, Servo_CounterStyleRule_Release]); // RuleNode is a Arc-like type but it does not use Arc. impl StrongRuleNode { pub fn into_strong(self) -> RawServoRuleNodeStrong
pub fn from_ffi<'a>(ffi: &'a &RawServoRuleNode) -> &'a Self { unsafe { &*(ffi as *const &RawServoRuleNode as *const StrongRuleNode) } } } #[no_mangle] pub unsafe extern "C" fn Servo_RuleNode_AddRef(obj: &RawServoRuleNode) { mem::forget(StrongRuleNode::from_ffi(&obj).clone()); } #[no_mangle] pub unsafe extern "C" fn Servo_RuleNode_Release(obj: &RawServoRuleNode) { let ptr = StrongRuleNode::from_ffi(&obj); ptr::read(ptr as *const StrongRuleNode); } // ComputedStyle is not an opaque type on any side of FFI. // This means that doing the HasArcFFI type trick is actually unsound, // since it gives us a way to construct an Arc<ComputedStyle> from // an &ComputedStyle, which in general is not allowed. So we // implement the restricted set of arc type functionality we need. #[no_mangle] pub unsafe extern "C" fn Servo_ComputedStyle_AddRef(obj: &ComputedValues) { mem::forget(ArcBorrow::from_ref(obj).clone_arc()); } #[no_mangle] pub unsafe extern "C" fn Servo_ComputedStyle_Release(obj: &ComputedValues) { ArcBorrow::from_ref(obj).with_arc(|a: &Arc<ComputedValues>| { let _: Arc<ComputedValues> = ptr::read(a); }); } impl From<Arc<ComputedValues>> for Strong<ComputedValues> { fn from(arc: Arc<ComputedValues>) -> Self { unsafe { mem::transmute(Arc::into_raw_offset(arc)) } } }
{ let ptr = self.ptr(); mem::forget(self); unsafe { mem::transmute(ptr) } }
identifier_body
arc_types.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This file lists all arc FFI types and defines corresponding addref //! and release functions. This list corresponds to ServoArcTypeList.h //! file in Gecko. #![allow(non_snake_case, missing_docs)] use gecko_bindings::bindings::RawServoCounterStyleRule; use gecko_bindings::bindings::RawServoFontFeatureValuesRule; use gecko_bindings::bindings::RawServoImportRule; use gecko_bindings::bindings::RawServoKeyframe; use gecko_bindings::bindings::RawServoKeyframesRule; use gecko_bindings::bindings::RawServoMediaRule; use gecko_bindings::bindings::RawServoMozDocumentRule; use gecko_bindings::bindings::RawServoNamespaceRule; use gecko_bindings::bindings::RawServoPageRule; use gecko_bindings::bindings::RawServoRuleNode; use gecko_bindings::bindings::RawServoRuleNodeStrong; use gecko_bindings::bindings::RawServoSupportsRule; use gecko_bindings::bindings::ServoCssRules; use gecko_bindings::structs::RawServoAnimationValue; use gecko_bindings::structs::RawServoDeclarationBlock; use gecko_bindings::structs::RawServoFontFaceRule; use gecko_bindings::structs::RawServoMediaList; use gecko_bindings::structs::RawServoStyleRule; use gecko_bindings::structs::RawServoStyleSheetContents; use gecko_bindings::sugar::ownership::{HasArcFFI, HasFFI, Strong}; use media_queries::MediaList; use properties::{ComputedValues, PropertyDeclarationBlock}; use properties::animated_properties::AnimationValue; use rule_tree::StrongRuleNode; use servo_arc::{Arc, ArcBorrow}; use shared_lock::Locked; use std::{mem, ptr}; use stylesheets::{CounterStyleRule, CssRules, FontFaceRule, FontFeatureValuesRule}; use stylesheets::{DocumentRule, ImportRule, KeyframesRule, MediaRule, NamespaceRule, PageRule}; use stylesheets::{StyleRule, StylesheetContents, SupportsRule}; use stylesheets::keyframes_rule::Keyframe; macro_rules! impl_arc_ffi { ($servo_type:ty => $gecko_type:ty[$addref:ident, $release:ident]) => { unsafe impl HasFFI for $servo_type { type FFIType = $gecko_type; } unsafe impl HasArcFFI for $servo_type {} #[no_mangle] pub unsafe extern "C" fn $addref(obj: &$gecko_type) { <$servo_type>::addref(obj); } #[no_mangle] pub unsafe extern "C" fn $release(obj: &$gecko_type) { <$servo_type>::release(obj); } }; } impl_arc_ffi!(Locked<CssRules> => ServoCssRules [Servo_CssRules_AddRef, Servo_CssRules_Release]); impl_arc_ffi!(StylesheetContents => RawServoStyleSheetContents [Servo_StyleSheetContents_AddRef, Servo_StyleSheetContents_Release]); impl_arc_ffi!(Locked<PropertyDeclarationBlock> => RawServoDeclarationBlock [Servo_DeclarationBlock_AddRef, Servo_DeclarationBlock_Release]); impl_arc_ffi!(Locked<StyleRule> => RawServoStyleRule [Servo_StyleRule_AddRef, Servo_StyleRule_Release]); impl_arc_ffi!(Locked<ImportRule> => RawServoImportRule [Servo_ImportRule_AddRef, Servo_ImportRule_Release]); impl_arc_ffi!(AnimationValue => RawServoAnimationValue [Servo_AnimationValue_AddRef, Servo_AnimationValue_Release]); impl_arc_ffi!(Locked<Keyframe> => RawServoKeyframe [Servo_Keyframe_AddRef, Servo_Keyframe_Release]); impl_arc_ffi!(Locked<KeyframesRule> => RawServoKeyframesRule [Servo_KeyframesRule_AddRef, Servo_KeyframesRule_Release]); impl_arc_ffi!(Locked<MediaList> => RawServoMediaList [Servo_MediaList_AddRef, Servo_MediaList_Release]); impl_arc_ffi!(Locked<MediaRule> => RawServoMediaRule [Servo_MediaRule_AddRef, Servo_MediaRule_Release]); impl_arc_ffi!(Locked<NamespaceRule> => RawServoNamespaceRule [Servo_NamespaceRule_AddRef, Servo_NamespaceRule_Release]); impl_arc_ffi!(Locked<PageRule> => RawServoPageRule [Servo_PageRule_AddRef, Servo_PageRule_Release]); impl_arc_ffi!(Locked<SupportsRule> => RawServoSupportsRule [Servo_SupportsRule_AddRef, Servo_SupportsRule_Release]); impl_arc_ffi!(Locked<DocumentRule> => RawServoMozDocumentRule [Servo_DocumentRule_AddRef, Servo_DocumentRule_Release]); impl_arc_ffi!(Locked<FontFeatureValuesRule> => RawServoFontFeatureValuesRule [Servo_FontFeatureValuesRule_AddRef, Servo_FontFeatureValuesRule_Release]); impl_arc_ffi!(Locked<FontFaceRule> => RawServoFontFaceRule [Servo_FontFaceRule_AddRef, Servo_FontFaceRule_Release]); impl_arc_ffi!(Locked<CounterStyleRule> => RawServoCounterStyleRule [Servo_CounterStyleRule_AddRef, Servo_CounterStyleRule_Release]); // RuleNode is a Arc-like type but it does not use Arc. impl StrongRuleNode { pub fn into_strong(self) -> RawServoRuleNodeStrong { let ptr = self.ptr(); mem::forget(self); unsafe { mem::transmute(ptr) } } pub fn from_ffi<'a>(ffi: &'a &RawServoRuleNode) -> &'a Self { unsafe { &*(ffi as *const &RawServoRuleNode as *const StrongRuleNode) } } } #[no_mangle] pub unsafe extern "C" fn Servo_RuleNode_AddRef(obj: &RawServoRuleNode) { mem::forget(StrongRuleNode::from_ffi(&obj).clone()); } #[no_mangle] pub unsafe extern "C" fn Servo_RuleNode_Release(obj: &RawServoRuleNode) { let ptr = StrongRuleNode::from_ffi(&obj); ptr::read(ptr as *const StrongRuleNode); } // ComputedStyle is not an opaque type on any side of FFI. // This means that doing the HasArcFFI type trick is actually unsound, // since it gives us a way to construct an Arc<ComputedStyle> from // an &ComputedStyle, which in general is not allowed. So we // implement the restricted set of arc type functionality we need. #[no_mangle] pub unsafe extern "C" fn Servo_ComputedStyle_AddRef(obj: &ComputedValues) { mem::forget(ArcBorrow::from_ref(obj).clone_arc()); } #[no_mangle] pub unsafe extern "C" fn
(obj: &ComputedValues) { ArcBorrow::from_ref(obj).with_arc(|a: &Arc<ComputedValues>| { let _: Arc<ComputedValues> = ptr::read(a); }); } impl From<Arc<ComputedValues>> for Strong<ComputedValues> { fn from(arc: Arc<ComputedValues>) -> Self { unsafe { mem::transmute(Arc::into_raw_offset(arc)) } } }
Servo_ComputedStyle_Release
identifier_name
child_process.rs
// Copyright 2020 The Evcxr Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::errors::{bail, Error}; use crate::runtime; use std::io::BufReader; use std::process; use std::sync::mpsc; use std::sync::{Arc, Mutex}; pub(crate) struct ChildProcess { process: std::process::Child, stdout: std::io::Lines<BufReader<std::process::ChildStdout>>, // Only none while in drop. stdin: Option<std::process::ChildStdin>, command: Arc<Mutex<process::Command>>, stderr_sender: Arc<Mutex<mpsc::Sender<String>>>, } impl ChildProcess { pub(crate) fn new( mut command: std::process::Command, stderr_sender: mpsc::Sender<String>, ) -> Result<ChildProcess, Error>
fn new_internal( command: Arc<Mutex<std::process::Command>>, stderr_sender: Arc<Mutex<mpsc::Sender<String>>>, ) -> Result<ChildProcess, Error> { let process = command.lock().unwrap().spawn(); let mut process = match process { Ok(c) => c, Err(error) => bail!("Failed to run '{:?}': {:?}", command, error), }; let stdout = std::io::BufRead::lines(BufReader::new(process.stdout.take().unwrap())); // Handle stderr by patching it through to a channel in our output struct. let mut child_stderr = std::io::BufRead::lines(BufReader::new(process.stderr.take().unwrap())); std::thread::spawn({ let stderr_sender = Arc::clone(&stderr_sender); move || { let stderr_sender = stderr_sender.lock().unwrap(); while let Some(Ok(line)) = child_stderr.next() { // Ignore errors, since it just means that the user of the library has dropped the receive end. let _ = stderr_sender.send(line); } } }); let stdin = process.stdin.take(); Ok(ChildProcess { process, stdout, stdin, command, stderr_sender, }) } /// Terminates this process if it hasn't already, then restarts pub(crate) fn restart(&mut self) -> Result<ChildProcess, Error> { // If the process hasn't already terminated for some reason, kill it. if let Ok(None) = self.process.try_wait() { let _ = self.process.kill(); let _ = self.process.wait(); } ChildProcess::new_internal(Arc::clone(&self.command), Arc::clone(&self.stderr_sender)) } pub(crate) fn send(&mut self, command: &str) -> Result<(), Error> { use std::io::Write; writeln!(self.stdin.as_mut().unwrap(), "{}", command) .map_err(|_| self.get_termination_error())?; self.stdin.as_mut().unwrap().flush()?; Ok(()) } pub(crate) fn recv_line(&mut self) -> Result<String, Error> { Ok(self .stdout .next() .ok_or_else(|| self.get_termination_error())??) } fn get_termination_error(&mut self) -> Error { // Wait until the stderr handling thread has released its lock on stderr_sender, which it // will do when there's nothing more to read from stderr. We don't need to keep the lock, // just wait until we can aquire it, then drop it straight away. std::mem::drop(self.stderr_sender.lock().unwrap()); let mut content = String::new(); while let Some(Ok(line)) = self.stdout.next() { content.push_str(&line); content.push('\n'); } Error::SubprocessTerminated(match self.process.wait() { Ok(exit_status) => { #[cfg(target_os = "macos")] { use std::os::unix::process::ExitStatusExt; if Some(9) == exit_status.signal() { return Error::SubprocessTerminated( "Subprocess terminated with signal 9. This is known \ to happen when evcxr is installed via a Homebrew shell \ under emulation. Try installing rustup and evcxr without \ using Homebrew and see if that helps." .to_owned(), ); } } format!( "{}Subprocess terminated with status: {}", content, exit_status ) } Err(wait_error) => format!("Subprocess didn't start: {}", wait_error), }) } } impl Drop for ChildProcess { fn drop(&mut self) { // Drop child_stdin before we wait. Our subprocess uses stdin being // closed to know that it's time to terminate. self.stdin.take(); // Wait for our subprocess to terminate. Otherwise we'll be left with // zombie processes. let _ = self.process.wait(); } }
{ // Avoid a fork bomb. We could call runtime_hook here but then all the work that we did up // to this point would be wasted. Also, it's possible that we could already have started // threads, which could get messy. if std::env::var(runtime::EVCXR_IS_RUNTIME_VAR).is_ok() { bail!("Our current binary doesn't call runtime_hook()"); } command .env(runtime::EVCXR_IS_RUNTIME_VAR, "1") .env("RUST_BACKTRACE", "1") .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); ChildProcess::new_internal( Arc::new(Mutex::new(command)), Arc::new(Mutex::new(stderr_sender)), ) }
identifier_body
child_process.rs
// Copyright 2020 The Evcxr Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::errors::{bail, Error}; use crate::runtime; use std::io::BufReader; use std::process; use std::sync::mpsc; use std::sync::{Arc, Mutex}; pub(crate) struct ChildProcess { process: std::process::Child, stdout: std::io::Lines<BufReader<std::process::ChildStdout>>, // Only none while in drop. stdin: Option<std::process::ChildStdin>, command: Arc<Mutex<process::Command>>, stderr_sender: Arc<Mutex<mpsc::Sender<String>>>, } impl ChildProcess { pub(crate) fn new( mut command: std::process::Command, stderr_sender: mpsc::Sender<String>, ) -> Result<ChildProcess, Error> { // Avoid a fork bomb. We could call runtime_hook here but then all the work that we did up // to this point would be wasted. Also, it's possible that we could already have started // threads, which could get messy. if std::env::var(runtime::EVCXR_IS_RUNTIME_VAR).is_ok() { bail!("Our current binary doesn't call runtime_hook()"); } command .env(runtime::EVCXR_IS_RUNTIME_VAR, "1") .env("RUST_BACKTRACE", "1") .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); ChildProcess::new_internal( Arc::new(Mutex::new(command)), Arc::new(Mutex::new(stderr_sender)), ) } fn new_internal( command: Arc<Mutex<std::process::Command>>, stderr_sender: Arc<Mutex<mpsc::Sender<String>>>, ) -> Result<ChildProcess, Error> { let process = command.lock().unwrap().spawn(); let mut process = match process { Ok(c) => c, Err(error) => bail!("Failed to run '{:?}': {:?}", command, error), }; let stdout = std::io::BufRead::lines(BufReader::new(process.stdout.take().unwrap())); // Handle stderr by patching it through to a channel in our output struct. let mut child_stderr = std::io::BufRead::lines(BufReader::new(process.stderr.take().unwrap())); std::thread::spawn({ let stderr_sender = Arc::clone(&stderr_sender); move || { let stderr_sender = stderr_sender.lock().unwrap(); while let Some(Ok(line)) = child_stderr.next() { // Ignore errors, since it just means that the user of the library has dropped the receive end. let _ = stderr_sender.send(line); }
} }); let stdin = process.stdin.take(); Ok(ChildProcess { process, stdout, stdin, command, stderr_sender, }) } /// Terminates this process if it hasn't already, then restarts pub(crate) fn restart(&mut self) -> Result<ChildProcess, Error> { // If the process hasn't already terminated for some reason, kill it. if let Ok(None) = self.process.try_wait() { let _ = self.process.kill(); let _ = self.process.wait(); } ChildProcess::new_internal(Arc::clone(&self.command), Arc::clone(&self.stderr_sender)) } pub(crate) fn send(&mut self, command: &str) -> Result<(), Error> { use std::io::Write; writeln!(self.stdin.as_mut().unwrap(), "{}", command) .map_err(|_| self.get_termination_error())?; self.stdin.as_mut().unwrap().flush()?; Ok(()) } pub(crate) fn recv_line(&mut self) -> Result<String, Error> { Ok(self .stdout .next() .ok_or_else(|| self.get_termination_error())??) } fn get_termination_error(&mut self) -> Error { // Wait until the stderr handling thread has released its lock on stderr_sender, which it // will do when there's nothing more to read from stderr. We don't need to keep the lock, // just wait until we can aquire it, then drop it straight away. std::mem::drop(self.stderr_sender.lock().unwrap()); let mut content = String::new(); while let Some(Ok(line)) = self.stdout.next() { content.push_str(&line); content.push('\n'); } Error::SubprocessTerminated(match self.process.wait() { Ok(exit_status) => { #[cfg(target_os = "macos")] { use std::os::unix::process::ExitStatusExt; if Some(9) == exit_status.signal() { return Error::SubprocessTerminated( "Subprocess terminated with signal 9. This is known \ to happen when evcxr is installed via a Homebrew shell \ under emulation. Try installing rustup and evcxr without \ using Homebrew and see if that helps." .to_owned(), ); } } format!( "{}Subprocess terminated with status: {}", content, exit_status ) } Err(wait_error) => format!("Subprocess didn't start: {}", wait_error), }) } } impl Drop for ChildProcess { fn drop(&mut self) { // Drop child_stdin before we wait. Our subprocess uses stdin being // closed to know that it's time to terminate. self.stdin.take(); // Wait for our subprocess to terminate. Otherwise we'll be left with // zombie processes. let _ = self.process.wait(); } }
random_line_split
child_process.rs
// Copyright 2020 The Evcxr Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::errors::{bail, Error}; use crate::runtime; use std::io::BufReader; use std::process; use std::sync::mpsc; use std::sync::{Arc, Mutex}; pub(crate) struct ChildProcess { process: std::process::Child, stdout: std::io::Lines<BufReader<std::process::ChildStdout>>, // Only none while in drop. stdin: Option<std::process::ChildStdin>, command: Arc<Mutex<process::Command>>, stderr_sender: Arc<Mutex<mpsc::Sender<String>>>, } impl ChildProcess { pub(crate) fn new( mut command: std::process::Command, stderr_sender: mpsc::Sender<String>, ) -> Result<ChildProcess, Error> { // Avoid a fork bomb. We could call runtime_hook here but then all the work that we did up // to this point would be wasted. Also, it's possible that we could already have started // threads, which could get messy. if std::env::var(runtime::EVCXR_IS_RUNTIME_VAR).is_ok() { bail!("Our current binary doesn't call runtime_hook()"); } command .env(runtime::EVCXR_IS_RUNTIME_VAR, "1") .env("RUST_BACKTRACE", "1") .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); ChildProcess::new_internal( Arc::new(Mutex::new(command)), Arc::new(Mutex::new(stderr_sender)), ) } fn new_internal( command: Arc<Mutex<std::process::Command>>, stderr_sender: Arc<Mutex<mpsc::Sender<String>>>, ) -> Result<ChildProcess, Error> { let process = command.lock().unwrap().spawn(); let mut process = match process { Ok(c) => c, Err(error) => bail!("Failed to run '{:?}': {:?}", command, error), }; let stdout = std::io::BufRead::lines(BufReader::new(process.stdout.take().unwrap())); // Handle stderr by patching it through to a channel in our output struct. let mut child_stderr = std::io::BufRead::lines(BufReader::new(process.stderr.take().unwrap())); std::thread::spawn({ let stderr_sender = Arc::clone(&stderr_sender); move || { let stderr_sender = stderr_sender.lock().unwrap(); while let Some(Ok(line)) = child_stderr.next() { // Ignore errors, since it just means that the user of the library has dropped the receive end. let _ = stderr_sender.send(line); } } }); let stdin = process.stdin.take(); Ok(ChildProcess { process, stdout, stdin, command, stderr_sender, }) } /// Terminates this process if it hasn't already, then restarts pub(crate) fn restart(&mut self) -> Result<ChildProcess, Error> { // If the process hasn't already terminated for some reason, kill it. if let Ok(None) = self.process.try_wait() { let _ = self.process.kill(); let _ = self.process.wait(); } ChildProcess::new_internal(Arc::clone(&self.command), Arc::clone(&self.stderr_sender)) } pub(crate) fn send(&mut self, command: &str) -> Result<(), Error> { use std::io::Write; writeln!(self.stdin.as_mut().unwrap(), "{}", command) .map_err(|_| self.get_termination_error())?; self.stdin.as_mut().unwrap().flush()?; Ok(()) } pub(crate) fn
(&mut self) -> Result<String, Error> { Ok(self .stdout .next() .ok_or_else(|| self.get_termination_error())??) } fn get_termination_error(&mut self) -> Error { // Wait until the stderr handling thread has released its lock on stderr_sender, which it // will do when there's nothing more to read from stderr. We don't need to keep the lock, // just wait until we can aquire it, then drop it straight away. std::mem::drop(self.stderr_sender.lock().unwrap()); let mut content = String::new(); while let Some(Ok(line)) = self.stdout.next() { content.push_str(&line); content.push('\n'); } Error::SubprocessTerminated(match self.process.wait() { Ok(exit_status) => { #[cfg(target_os = "macos")] { use std::os::unix::process::ExitStatusExt; if Some(9) == exit_status.signal() { return Error::SubprocessTerminated( "Subprocess terminated with signal 9. This is known \ to happen when evcxr is installed via a Homebrew shell \ under emulation. Try installing rustup and evcxr without \ using Homebrew and see if that helps." .to_owned(), ); } } format!( "{}Subprocess terminated with status: {}", content, exit_status ) } Err(wait_error) => format!("Subprocess didn't start: {}", wait_error), }) } } impl Drop for ChildProcess { fn drop(&mut self) { // Drop child_stdin before we wait. Our subprocess uses stdin being // closed to know that it's time to terminate. self.stdin.take(); // Wait for our subprocess to terminate. Otherwise we'll be left with // zombie processes. let _ = self.process.wait(); } }
recv_line
identifier_name
aarch64.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use cty::{c_int}; use {VarArg}; use core::{mem, ptr}; use core::intrinsics::{type_id}; #[repr(C)] pub struct VarArgs { __stack: *mut u8, __gr_top: *mut u8, __vr_top: *mut u8, __gr_offs: c_int, __vr_offs: c_int, } impl VarArgs { pub unsafe fn get<T: VarArg>(&mut self) -> T { if fp::<T>() { let mut offs = self.__vr_offs as isize; if offs <= -16 { self.__vr_offs += 16; if cfg!(target_endian = "big") { offs += 16 - mem::size_of::<T>() as isize; } return ptr::read(self.__vr_top.offset(offs) as *mut T); } } else { let mut offs = self.__gr_offs as isize; if offs <= -8 { self.__gr_offs += 8;
} } let mut ptr = self.__stack; self.__stack = ptr.add(8); if cfg!(target_endian = "big") { ptr = ptr.add(8 - mem::size_of::<T>()); } ptr::read(ptr as *mut T) } } unsafe fn fp<T>() -> bool { let id = type_id::<T>(); id == type_id::<f32>() || id == type_id::<f64>() }
if cfg!(target_endian = "big") { offs += 8 - mem::size_of::<T>() as isize } return ptr::read(self.__gr_top.offset(offs) as *mut T);
random_line_split
aarch64.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use cty::{c_int}; use {VarArg}; use core::{mem, ptr}; use core::intrinsics::{type_id}; #[repr(C)] pub struct VarArgs { __stack: *mut u8, __gr_top: *mut u8, __vr_top: *mut u8, __gr_offs: c_int, __vr_offs: c_int, } impl VarArgs { pub unsafe fn get<T: VarArg>(&mut self) -> T { if fp::<T>() { let mut offs = self.__vr_offs as isize; if offs <= -16 { self.__vr_offs += 16; if cfg!(target_endian = "big") { offs += 16 - mem::size_of::<T>() as isize; } return ptr::read(self.__vr_top.offset(offs) as *mut T); } } else
let mut ptr = self.__stack; self.__stack = ptr.add(8); if cfg!(target_endian = "big") { ptr = ptr.add(8 - mem::size_of::<T>()); } ptr::read(ptr as *mut T) } } unsafe fn fp<T>() -> bool { let id = type_id::<T>(); id == type_id::<f32>() || id == type_id::<f64>() }
{ let mut offs = self.__gr_offs as isize; if offs <= -8 { self.__gr_offs += 8; if cfg!(target_endian = "big") { offs += 8 - mem::size_of::<T>() as isize } return ptr::read(self.__gr_top.offset(offs) as *mut T); } }
conditional_block
aarch64.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use cty::{c_int}; use {VarArg}; use core::{mem, ptr}; use core::intrinsics::{type_id}; #[repr(C)] pub struct VarArgs { __stack: *mut u8, __gr_top: *mut u8, __vr_top: *mut u8, __gr_offs: c_int, __vr_offs: c_int, } impl VarArgs { pub unsafe fn get<T: VarArg>(&mut self) -> T { if fp::<T>() { let mut offs = self.__vr_offs as isize; if offs <= -16 { self.__vr_offs += 16; if cfg!(target_endian = "big") { offs += 16 - mem::size_of::<T>() as isize; } return ptr::read(self.__vr_top.offset(offs) as *mut T); } } else { let mut offs = self.__gr_offs as isize; if offs <= -8 { self.__gr_offs += 8; if cfg!(target_endian = "big") { offs += 8 - mem::size_of::<T>() as isize } return ptr::read(self.__gr_top.offset(offs) as *mut T); } } let mut ptr = self.__stack; self.__stack = ptr.add(8); if cfg!(target_endian = "big") { ptr = ptr.add(8 - mem::size_of::<T>()); } ptr::read(ptr as *mut T) } } unsafe fn
<T>() -> bool { let id = type_id::<T>(); id == type_id::<f32>() || id == type_id::<f64>() }
fp
identifier_name
aarch64.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use cty::{c_int}; use {VarArg}; use core::{mem, ptr}; use core::intrinsics::{type_id}; #[repr(C)] pub struct VarArgs { __stack: *mut u8, __gr_top: *mut u8, __vr_top: *mut u8, __gr_offs: c_int, __vr_offs: c_int, } impl VarArgs { pub unsafe fn get<T: VarArg>(&mut self) -> T
let mut ptr = self.__stack; self.__stack = ptr.add(8); if cfg!(target_endian = "big") { ptr = ptr.add(8 - mem::size_of::<T>()); } ptr::read(ptr as *mut T) } } unsafe fn fp<T>() -> bool { let id = type_id::<T>(); id == type_id::<f32>() || id == type_id::<f64>() }
{ if fp::<T>() { let mut offs = self.__vr_offs as isize; if offs <= -16 { self.__vr_offs += 16; if cfg!(target_endian = "big") { offs += 16 - mem::size_of::<T>() as isize; } return ptr::read(self.__vr_top.offset(offs) as *mut T); } } else { let mut offs = self.__gr_offs as isize; if offs <= -8 { self.__gr_offs += 8; if cfg!(target_endian = "big") { offs += 8 - mem::size_of::<T>() as isize } return ptr::read(self.__gr_top.offset(offs) as *mut T); } }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of in script so that the devtools crate can be //! modified independently of the rest of Servo. #![crate_name = "devtools_traits"] #![crate_type = "rlib"] #![allow(non_snake_case)] #![feature(custom_derive, plugin)] #![plugin(serde_macros)] #[macro_use] extern crate bitflags; extern crate ipc_channel; extern crate msg; extern crate rustc_serialize; extern crate serde; extern crate url; extern crate hyper; extern crate util; extern crate time; use rustc_serialize::{Decodable, Decoder}; use msg::constellation_msg::{PipelineId, WorkerId}; use util::str::DOMString; use url::Url; use hyper::header::Headers; use hyper::http::RawStatus; use hyper::method::Method; use ipc_channel::ipc::IpcSender; use time::Duration; use std::net::TcpStream; // Information would be attached to NewGlobal to be received and show in devtools. // Extend these fields if we need more information. #[derive(Deserialize, Serialize)] pub struct DevtoolsPageInfo { pub title: DOMString, pub url: Url } /// Messages to the instruct the devtools server to update its known actors/state /// according to changes in the browser. pub enum DevtoolsControlMsg { FromChrome(ChromeToDevtoolsControlMsg), FromScript(ScriptToDevtoolsControlMsg), } pub enum ChromeToDevtoolsControlMsg { AddClient(TcpStream), FramerateTick(String, f64), ServerExitMsg, NetworkEventMessage(String, NetworkEvent), } #[derive(Deserialize, Serialize)] pub enum ScriptToDevtoolsControlMsg { NewGlobal((PipelineId, Option<WorkerId>), IpcSender<DevtoolScriptControlMsg>, DevtoolsPageInfo), SendConsoleMessage(PipelineId, ConsoleMessage, Option<WorkerId>), } /// Serialized JS return values /// TODO: generalize this beyond the EvaluateJS message? #[derive(Deserialize, Serialize)] pub enum EvaluateJSReply { VoidValue, NullValue, BooleanValue(bool), NumberValue(f64), StringValue(String), ActorValue { class: String, uuid: String }, } #[derive(Deserialize, Serialize)] pub struct AttrInfo { pub namespace: String, pub name: String, pub value: String, } #[derive(Deserialize, Serialize)] pub struct NodeInfo { pub uniqueId: String, pub baseURI: String, pub parent: String, pub nodeType: u16, pub namespaceURI: String, pub nodeName: String, pub numChildren: usize, pub name: String, pub publicId: String, pub systemId: String, pub attrs: Vec<AttrInfo>, pub isDocumentElement: bool, pub shortValue: String, pub incompleteValue: bool, } #[derive(PartialEq, Eq, Deserialize, Serialize)] pub enum TracingMetadata { Default, IntervalStart, IntervalEnd, Event, EventBacktrace, } #[derive(Deserialize, Serialize)] pub struct TimelineMarker { pub name: String, pub metadata: TracingMetadata, pub time: PreciseTime,
Reflow, DOMEvent, } /// Messages to process in a particular script task, as instructed by a devtools client. #[derive(Deserialize, Serialize)] pub enum DevtoolScriptControlMsg { EvaluateJS(PipelineId, String, IpcSender<EvaluateJSReply>), GetRootNode(PipelineId, IpcSender<NodeInfo>), GetDocumentElement(PipelineId, IpcSender<NodeInfo>), GetChildren(PipelineId, String, IpcSender<Vec<NodeInfo>>), GetLayout(PipelineId, String, IpcSender<(f32, f32)>), GetCachedMessages(PipelineId, CachedConsoleMessageTypes, IpcSender<Vec<CachedConsoleMessage>>), ModifyAttribute(PipelineId, String, Vec<Modification>), WantsLiveNotifications(PipelineId, bool), SetTimelineMarkers(PipelineId, Vec<TimelineMarkerType>, IpcSender<TimelineMarker>), DropTimelineMarkers(PipelineId, Vec<TimelineMarkerType>), RequestAnimationFrame(PipelineId, IpcSender<f64>), } #[derive(RustcEncodable, Deserialize, Serialize)] pub struct Modification { pub attributeName: String, pub newValue: Option<String>, } impl Decodable for Modification { fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> { d.read_struct("Modification", 2, |d| Ok(Modification { attributeName: try!(d.read_struct_field("attributeName", 0, |d| Decodable::decode(d))), newValue: match d.read_struct_field("newValue", 1, |d| Decodable::decode(d)) { Ok(opt) => opt, Err(_) => None } }) ) } } #[derive(Clone, Deserialize, Serialize)] pub enum LogLevel { Log, Debug, Info, Warn, Error, } #[derive(Clone, Deserialize, Serialize)] pub struct ConsoleMessage { pub message: String, pub logLevel: LogLevel, pub filename: String, pub lineNumber: u32, pub columnNumber: u32, } bitflags! { #[derive(Deserialize, Serialize)] flags CachedConsoleMessageTypes: u8 { const PAGE_ERROR = 1 << 0, const CONSOLE_API = 1 << 1, } } #[derive(RustcEncodable, Deserialize, Serialize)] pub struct PageError { pub _type: String, pub errorMessage: String, pub sourceName: String, pub lineText: String, pub lineNumber: u32, pub columnNumber: u32, pub category: String, pub timeStamp: u64, pub error: bool, pub warning: bool, pub exception: bool, pub strict: bool, pub private: bool, } #[derive(RustcEncodable, Deserialize, Serialize)] pub struct ConsoleAPI { pub _type: String, pub level: String, pub filename: String, pub lineNumber: u32, pub functionName: String, pub timeStamp: u64, pub private: bool, pub arguments: Vec<String>, } #[derive(Deserialize, Serialize)] pub enum CachedConsoleMessage { PageError(PageError), ConsoleAPI(ConsoleAPI), } #[derive(Clone)] pub enum NetworkEvent { HttpRequest(Url, Method, Headers, Option<Vec<u8>>), HttpResponse(Option<Headers>, Option<RawStatus>, Option<Vec<u8>>) } impl TimelineMarker { pub fn new(name: String, metadata: TracingMetadata) -> TimelineMarker { TimelineMarker { name: name, metadata: metadata, time: PreciseTime::now(), stack: None, } } } /// A replacement for `time::PreciseTime` that isn't opaque, so we can serialize it. /// /// The reason why this doesn't go upstream is that `time` is slated to be part of Rust's standard /// library, which definitely can't have any dependencies on `serde`. But `serde` can't implement /// `Deserialize` and `Serialize` itself, because `time::PreciseTime` is opaque! A Catch-22. So I'm /// duplicating the definition here. #[derive(Copy, Clone, Deserialize, Serialize)] pub struct PreciseTime(u64); impl PreciseTime { pub fn now() -> PreciseTime { PreciseTime(time::precise_time_ns()) } pub fn to(&self, later: PreciseTime) -> Duration { Duration::nanoseconds((later.0 - self.0) as i64) } }
pub stack: Option<Vec<()>>, } #[derive(PartialEq, Eq, Hash, Clone, Deserialize, Serialize)] pub enum TimelineMarkerType {
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of in script so that the devtools crate can be //! modified independently of the rest of Servo. #![crate_name = "devtools_traits"] #![crate_type = "rlib"] #![allow(non_snake_case)] #![feature(custom_derive, plugin)] #![plugin(serde_macros)] #[macro_use] extern crate bitflags; extern crate ipc_channel; extern crate msg; extern crate rustc_serialize; extern crate serde; extern crate url; extern crate hyper; extern crate util; extern crate time; use rustc_serialize::{Decodable, Decoder}; use msg::constellation_msg::{PipelineId, WorkerId}; use util::str::DOMString; use url::Url; use hyper::header::Headers; use hyper::http::RawStatus; use hyper::method::Method; use ipc_channel::ipc::IpcSender; use time::Duration; use std::net::TcpStream; // Information would be attached to NewGlobal to be received and show in devtools. // Extend these fields if we need more information. #[derive(Deserialize, Serialize)] pub struct DevtoolsPageInfo { pub title: DOMString, pub url: Url } /// Messages to the instruct the devtools server to update its known actors/state /// according to changes in the browser. pub enum DevtoolsControlMsg { FromChrome(ChromeToDevtoolsControlMsg), FromScript(ScriptToDevtoolsControlMsg), } pub enum ChromeToDevtoolsControlMsg { AddClient(TcpStream), FramerateTick(String, f64), ServerExitMsg, NetworkEventMessage(String, NetworkEvent), } #[derive(Deserialize, Serialize)] pub enum ScriptToDevtoolsControlMsg { NewGlobal((PipelineId, Option<WorkerId>), IpcSender<DevtoolScriptControlMsg>, DevtoolsPageInfo), SendConsoleMessage(PipelineId, ConsoleMessage, Option<WorkerId>), } /// Serialized JS return values /// TODO: generalize this beyond the EvaluateJS message? #[derive(Deserialize, Serialize)] pub enum EvaluateJSReply { VoidValue, NullValue, BooleanValue(bool), NumberValue(f64), StringValue(String), ActorValue { class: String, uuid: String }, } #[derive(Deserialize, Serialize)] pub struct AttrInfo { pub namespace: String, pub name: String, pub value: String, } #[derive(Deserialize, Serialize)] pub struct NodeInfo { pub uniqueId: String, pub baseURI: String, pub parent: String, pub nodeType: u16, pub namespaceURI: String, pub nodeName: String, pub numChildren: usize, pub name: String, pub publicId: String, pub systemId: String, pub attrs: Vec<AttrInfo>, pub isDocumentElement: bool, pub shortValue: String, pub incompleteValue: bool, } #[derive(PartialEq, Eq, Deserialize, Serialize)] pub enum TracingMetadata { Default, IntervalStart, IntervalEnd, Event, EventBacktrace, } #[derive(Deserialize, Serialize)] pub struct TimelineMarker { pub name: String, pub metadata: TracingMetadata, pub time: PreciseTime, pub stack: Option<Vec<()>>, } #[derive(PartialEq, Eq, Hash, Clone, Deserialize, Serialize)] pub enum TimelineMarkerType { Reflow, DOMEvent, } /// Messages to process in a particular script task, as instructed by a devtools client. #[derive(Deserialize, Serialize)] pub enum DevtoolScriptControlMsg { EvaluateJS(PipelineId, String, IpcSender<EvaluateJSReply>), GetRootNode(PipelineId, IpcSender<NodeInfo>), GetDocumentElement(PipelineId, IpcSender<NodeInfo>), GetChildren(PipelineId, String, IpcSender<Vec<NodeInfo>>), GetLayout(PipelineId, String, IpcSender<(f32, f32)>), GetCachedMessages(PipelineId, CachedConsoleMessageTypes, IpcSender<Vec<CachedConsoleMessage>>), ModifyAttribute(PipelineId, String, Vec<Modification>), WantsLiveNotifications(PipelineId, bool), SetTimelineMarkers(PipelineId, Vec<TimelineMarkerType>, IpcSender<TimelineMarker>), DropTimelineMarkers(PipelineId, Vec<TimelineMarkerType>), RequestAnimationFrame(PipelineId, IpcSender<f64>), } #[derive(RustcEncodable, Deserialize, Serialize)] pub struct Modification { pub attributeName: String, pub newValue: Option<String>, } impl Decodable for Modification { fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> { d.read_struct("Modification", 2, |d| Ok(Modification { attributeName: try!(d.read_struct_field("attributeName", 0, |d| Decodable::decode(d))), newValue: match d.read_struct_field("newValue", 1, |d| Decodable::decode(d)) { Ok(opt) => opt, Err(_) => None } }) ) } } #[derive(Clone, Deserialize, Serialize)] pub enum LogLevel { Log, Debug, Info, Warn, Error, } #[derive(Clone, Deserialize, Serialize)] pub struct ConsoleMessage { pub message: String, pub logLevel: LogLevel, pub filename: String, pub lineNumber: u32, pub columnNumber: u32, } bitflags! { #[derive(Deserialize, Serialize)] flags CachedConsoleMessageTypes: u8 { const PAGE_ERROR = 1 << 0, const CONSOLE_API = 1 << 1, } } #[derive(RustcEncodable, Deserialize, Serialize)] pub struct PageError { pub _type: String, pub errorMessage: String, pub sourceName: String, pub lineText: String, pub lineNumber: u32, pub columnNumber: u32, pub category: String, pub timeStamp: u64, pub error: bool, pub warning: bool, pub exception: bool, pub strict: bool, pub private: bool, } #[derive(RustcEncodable, Deserialize, Serialize)] pub struct ConsoleAPI { pub _type: String, pub level: String, pub filename: String, pub lineNumber: u32, pub functionName: String, pub timeStamp: u64, pub private: bool, pub arguments: Vec<String>, } #[derive(Deserialize, Serialize)] pub enum CachedConsoleMessage { PageError(PageError), ConsoleAPI(ConsoleAPI), } #[derive(Clone)] pub enum NetworkEvent { HttpRequest(Url, Method, Headers, Option<Vec<u8>>), HttpResponse(Option<Headers>, Option<RawStatus>, Option<Vec<u8>>) } impl TimelineMarker { pub fn new(name: String, metadata: TracingMetadata) -> TimelineMarker { TimelineMarker { name: name, metadata: metadata, time: PreciseTime::now(), stack: None, } } } /// A replacement for `time::PreciseTime` that isn't opaque, so we can serialize it. /// /// The reason why this doesn't go upstream is that `time` is slated to be part of Rust's standard /// library, which definitely can't have any dependencies on `serde`. But `serde` can't implement /// `Deserialize` and `Serialize` itself, because `time::PreciseTime` is opaque! A Catch-22. So I'm /// duplicating the definition here. #[derive(Copy, Clone, Deserialize, Serialize)] pub struct PreciseTime(u64); impl PreciseTime { pub fn
() -> PreciseTime { PreciseTime(time::precise_time_ns()) } pub fn to(&self, later: PreciseTime) -> Duration { Duration::nanoseconds((later.0 - self.0) as i64) } }
now
identifier_name
texture_animator.rs
use resources::AnimatedTexture; use rand::{Rng, thread_rng};
randomize: (bool, bool), tex_width: u32, current: u32, delay: f32, timer: f32, rect: IntRect, } impl TextureAnimator { pub fn new(anim_tex: &AnimatedTexture) -> TextureAnimator { let size = anim_tex.tex.size(); let mut t = TextureAnimator { n_frames: anim_tex.n_frames, step: (size.y / anim_tex.n_frames) as i32, randomize: anim_tex.randomize, tex_width: size.x, current: 0, delay: anim_tex.delay, timer: 0., rect: IntRect::new(0, 0, 1, 1), }; t.gen_rect(); t } pub fn update(&mut self, delta: f32) { self.timer += delta; if self.timer > self.delay { self.timer = 0.; self.gen_rect(); self.current += 1; if self.current > self.n_frames - 1 { self.current = 0; } } } pub fn texture_rect(&self) -> IntRect { self.rect } fn gen_rect(&mut self) { let (left, width) = if self.randomize.0 && thread_rng().gen_weighted_bool(2) { (self.tex_width as i32, -(self.tex_width as i32)) } else { (0, self.tex_width as i32) }; let (top, height) = if self.randomize.1 && thread_rng().gen_weighted_bool(2) { ((self.current as i32 + 1) * self.step, -self.step) } else { (self.current as i32 * self.step, self.step) }; self.rect = IntRect::new(left, top, width, height); } /* pub fn n_frames(&self) -> u32 { self.n_frames } pub fn current(&self) -> u32 { self.current } */ }
use sfml::graphics::IntRect; pub struct TextureAnimator { n_frames: u32, step: i32,
random_line_split
texture_animator.rs
use resources::AnimatedTexture; use rand::{Rng, thread_rng}; use sfml::graphics::IntRect; pub struct TextureAnimator { n_frames: u32, step: i32, randomize: (bool, bool), tex_width: u32, current: u32, delay: f32, timer: f32, rect: IntRect, } impl TextureAnimator { pub fn new(anim_tex: &AnimatedTexture) -> TextureAnimator { let size = anim_tex.tex.size(); let mut t = TextureAnimator { n_frames: anim_tex.n_frames, step: (size.y / anim_tex.n_frames) as i32, randomize: anim_tex.randomize, tex_width: size.x, current: 0, delay: anim_tex.delay, timer: 0., rect: IntRect::new(0, 0, 1, 1), }; t.gen_rect(); t } pub fn update(&mut self, delta: f32) { self.timer += delta; if self.timer > self.delay { self.timer = 0.; self.gen_rect(); self.current += 1; if self.current > self.n_frames - 1 { self.current = 0; } } } pub fn texture_rect(&self) -> IntRect { self.rect } fn gen_rect(&mut self) { let (left, width) = if self.randomize.0 && thread_rng().gen_weighted_bool(2) { (self.tex_width as i32, -(self.tex_width as i32)) } else { (0, self.tex_width as i32) }; let (top, height) = if self.randomize.1 && thread_rng().gen_weighted_bool(2)
else { (self.current as i32 * self.step, self.step) }; self.rect = IntRect::new(left, top, width, height); } /* pub fn n_frames(&self) -> u32 { self.n_frames } pub fn current(&self) -> u32 { self.current } */ }
{ ((self.current as i32 + 1) * self.step, -self.step) }
conditional_block