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
pluginarray.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::Bindings::PluginArrayBinding; use dom::bindings::codegen::Bindings::PluginArrayBinding::PluginArrayMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::globalscope::GlobalScope; use dom::plugin::Plugin; use dom_struct::dom_struct; #[dom_struct] pub struct PluginArray { reflector_: Reflector, } impl PluginArray { pub fn new_inherited() -> PluginArray { PluginArray { reflector_: Reflector::new() } }
PluginArrayBinding::Wrap) } } impl PluginArrayMethods for PluginArray { // https://html.spec.whatwg.org/multipage/#dom-pluginarray-refresh fn Refresh(&self, _reload: bool) { } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-length fn Length(&self) -> u32 { 0 } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-item fn Item(&self, _index: u32) -> Option<DomRoot<Plugin>> { None } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-nameditem fn NamedItem(&self, _name: DOMString) -> Option<DomRoot<Plugin>> { None } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-item fn IndexedGetter(&self, _index: u32) -> Option<DomRoot<Plugin>> { None } // check-tidy: no specs after this line fn NamedGetter(&self, _name: DOMString) -> Option<DomRoot<Plugin>> { None } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { vec![] } }
pub fn new(global: &GlobalScope) -> DomRoot<PluginArray> { reflect_dom_object(box PluginArray::new_inherited(), global,
random_line_split
pluginarray.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::Bindings::PluginArrayBinding; use dom::bindings::codegen::Bindings::PluginArrayBinding::PluginArrayMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::globalscope::GlobalScope; use dom::plugin::Plugin; use dom_struct::dom_struct; #[dom_struct] pub struct PluginArray { reflector_: Reflector, } impl PluginArray { pub fn new_inherited() -> PluginArray { PluginArray { reflector_: Reflector::new() } } pub fn new(global: &GlobalScope) -> DomRoot<PluginArray> { reflect_dom_object(box PluginArray::new_inherited(), global, PluginArrayBinding::Wrap) } } impl PluginArrayMethods for PluginArray { // https://html.spec.whatwg.org/multipage/#dom-pluginarray-refresh fn Refresh(&self, _reload: bool) { } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-length fn Length(&self) -> u32 { 0 } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-item fn Item(&self, _index: u32) -> Option<DomRoot<Plugin>> { None } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-nameditem fn NamedItem(&self, _name: DOMString) -> Option<DomRoot<Plugin>> { None } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-item fn IndexedGetter(&self, _index: u32) -> Option<DomRoot<Plugin>> { None } // check-tidy: no specs after this line fn NamedGetter(&self, _name: DOMString) -> Option<DomRoot<Plugin>> { None } // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString>
}
{ vec![] }
identifier_body
pluginarray.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::Bindings::PluginArrayBinding; use dom::bindings::codegen::Bindings::PluginArrayBinding::PluginArrayMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::globalscope::GlobalScope; use dom::plugin::Plugin; use dom_struct::dom_struct; #[dom_struct] pub struct PluginArray { reflector_: Reflector, } impl PluginArray { pub fn new_inherited() -> PluginArray { PluginArray { reflector_: Reflector::new() } } pub fn new(global: &GlobalScope) -> DomRoot<PluginArray> { reflect_dom_object(box PluginArray::new_inherited(), global, PluginArrayBinding::Wrap) } } impl PluginArrayMethods for PluginArray { // https://html.spec.whatwg.org/multipage/#dom-pluginarray-refresh fn Refresh(&self, _reload: bool) { } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-length fn Length(&self) -> u32 { 0 } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-item fn Item(&self, _index: u32) -> Option<DomRoot<Plugin>> { None } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-nameditem fn NamedItem(&self, _name: DOMString) -> Option<DomRoot<Plugin>> { None } // https://html.spec.whatwg.org/multipage/#dom-pluginarray-item fn IndexedGetter(&self, _index: u32) -> Option<DomRoot<Plugin>> { None } // check-tidy: no specs after this line fn NamedGetter(&self, _name: DOMString) -> Option<DomRoot<Plugin>> { None } // https://heycam.github.io/webidl/#dfn-supported-property-names fn
(&self) -> Vec<DOMString> { vec![] } }
SupportedPropertyNames
identifier_name
graph.rs
// Copyright (c) 2016 Patrick Burroughs <celti@celti.name>. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0>, or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed except // according to those terms. extern crate unicode_graph; use std::{env, num, process}; use unicode_graph::{graph, braille}; #[derive(Debug)] enum CommandError { UnknownError, ParseArgs(String), ParseGraph(unicode_graph::ParseGraphError), ParseInt(num::ParseIntError), } impl From<num::ParseIntError> for CommandError { fn from(e: num::ParseIntError) -> CommandError { CommandError::ParseInt(e) } } impl From<unicode_graph::ParseGraphError> for CommandError { fn from(e: unicode_graph::ParseGraphError) -> CommandError { CommandError::ParseGraph(e) } } const VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn usage(argc: String) { print!("graph (from unicode_graph) v{}\n\ Copyright © 2016 Patrick Burroughs <celti@celti.name>\n\ \n\ Prints a graph made of Unicode glyphs (at current only Braille patterns). \n\ Usage: {} [h|v][r] <index> [<index>...]\n\ \x20\x20‘h’ and ‘v’ request a horizontal or vertical graph (horizontal if omitted).\n\ \x20\x20`r` reverses the usual direction of the graph (i.e., from the top or left).\n\ \x20\x20The remaining integer arguments indicate the size of the bar at that index.\n", VERSION, argc) } fn _main(mut argv: Vec<String>) -> Result<bool, CommandError> { let arg1 = match argv.get(0) { Some(x) => { x.clone() } None => { return Ok(false) } }; let (call, reverse) = match arg1.as_ref() { "v" => { argv.remove(0); ("vertical", false) } "h" => { argv.remove(0); ("horizontal", false) } "vr" => { argv.remove(0); ("vertical", true) } "hr" => { argv.remove(0); ("horizontal", true) } "r" => { ("horizontal", true) } num if num.parse::<usize>().is_ok() => { ("horizontal", false) } err => { return Err(CommandError::ParseArgs(err.to_owned())) } }; let arg2 = match argv.get(0) { Some(x) => { x.clone() } None => { return Err(CommandError::ParseArgs("no input specified".to_owned())) } }; let reverse = match arg2.as_ref() { "r" => { argv.remove(0); true } num if num.parse::<usize>().is_ok() => { reverse } err => { return Err(CommandError::ParseArgs(err.to_owned())) } }; let input: Vec<usize> = try!(argv.into_iter().map(|i| i.trim().parse()).collect()); let graph = match call { "horizontal" => { try!(braille::horizontal_graph(reverse, input)) } "vertical" => { try!(braille::vertical_graph(reverse, input)) } _ => { return Err(CommandError::UnknownError) } }; for line in try!(graph::graph_to_strings(graph)) { println!("{}", line) }; Ok(true) } fn main() { let mut argv: Vec<String> = env::args().collect(); let argc: String = argv.remove(0); match _main(argv) { Ok(false) => { usage(a
Err(CommandError::ParseArgs(e)) => { println!("Invalid argument: {}", e); usage(argc); process::exit(64) } Err(CommandError::ParseInt(_)) => { println!("An error occurred parsing the input."); usage(argc); process::exit(65) } Err(CommandError::ParseGraph(_)) => { println!("An error occurred parsing the graph."); process::exit(65) } Err(CommandError::UnknownError) => { println!("An unknown error occurred. Please report this."); process::exit(-1) } Ok(true) => { process::exit(0) } } }
rgc); process::exit(0) }
conditional_block
graph.rs
// Copyright (c) 2016 Patrick Burroughs <celti@celti.name>. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0>, or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed except // according to those terms. extern crate unicode_graph; use std::{env, num, process}; use unicode_graph::{graph, braille}; #[derive(Debug)] enum CommandError { UnknownError, ParseArgs(String), ParseGraph(unicode_graph::ParseGraphError), ParseInt(num::ParseIntError), } impl From<num::ParseIntError> for CommandError { fn from(e: num::ParseIntError) -> CommandError { CommandError::ParseInt(e) } } impl From<unicode_graph::ParseGraphError> for CommandError { fn from(e: unicode_graph::ParseGraphError) -> CommandError { CommandError::ParseGraph(e) } } const VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn usage(argc: String) { print!("graph (from unicode_graph) v{}\n\ Copyright © 2016 Patrick Burroughs <celti@celti.name>\n\ \n\ Prints a graph made of Unicode glyphs (at current only Braille patterns). \n\ Usage: {} [h|v][r] <index> [<index>...]\n\ \x20\x20‘h’ and ‘v’ request a horizontal or vertical graph (horizontal if omitted).\n\ \x20\x20`r` reverses the usual direction of the graph (i.e., from the top or left).\n\ \x20\x20The remaining integer arguments indicate the size of the bar at that index.\n", VERSION, argc) } fn _main(mut
: Vec<String>) -> Result<bool, CommandError> { let arg1 = match argv.get(0) { Some(x) => { x.clone() } None => { return Ok(false) } }; let (call, reverse) = match arg1.as_ref() { "v" => { argv.remove(0); ("vertical", false) } "h" => { argv.remove(0); ("horizontal", false) } "vr" => { argv.remove(0); ("vertical", true) } "hr" => { argv.remove(0); ("horizontal", true) } "r" => { ("horizontal", true) } num if num.parse::<usize>().is_ok() => { ("horizontal", false) } err => { return Err(CommandError::ParseArgs(err.to_owned())) } }; let arg2 = match argv.get(0) { Some(x) => { x.clone() } None => { return Err(CommandError::ParseArgs("no input specified".to_owned())) } }; let reverse = match arg2.as_ref() { "r" => { argv.remove(0); true } num if num.parse::<usize>().is_ok() => { reverse } err => { return Err(CommandError::ParseArgs(err.to_owned())) } }; let input: Vec<usize> = try!(argv.into_iter().map(|i| i.trim().parse()).collect()); let graph = match call { "horizontal" => { try!(braille::horizontal_graph(reverse, input)) } "vertical" => { try!(braille::vertical_graph(reverse, input)) } _ => { return Err(CommandError::UnknownError) } }; for line in try!(graph::graph_to_strings(graph)) { println!("{}", line) }; Ok(true) } fn main() { let mut argv: Vec<String> = env::args().collect(); let argc: String = argv.remove(0); match _main(argv) { Ok(false) => { usage(argc); process::exit(0) } Err(CommandError::ParseArgs(e)) => { println!("Invalid argument: {}", e); usage(argc); process::exit(64) } Err(CommandError::ParseInt(_)) => { println!("An error occurred parsing the input."); usage(argc); process::exit(65) } Err(CommandError::ParseGraph(_)) => { println!("An error occurred parsing the graph."); process::exit(65) } Err(CommandError::UnknownError) => { println!("An unknown error occurred. Please report this."); process::exit(-1) } Ok(true) => { process::exit(0) } } }
argv
identifier_name
graph.rs
// Copyright (c) 2016 Patrick Burroughs <celti@celti.name>. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0>, or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed except // according to those terms. extern crate unicode_graph; use std::{env, num, process}; use unicode_graph::{graph, braille}; #[derive(Debug)] enum CommandError { UnknownError, ParseArgs(String), ParseGraph(unicode_graph::ParseGraphError), ParseInt(num::ParseIntError), } impl From<num::ParseIntError> for CommandError { fn from(e: num::ParseIntError) -> CommandError { CommandError::ParseInt(e) } } impl From<unicode_graph::ParseGraphError> for CommandError { fn from(e: unicode_graph::ParseGraphError) -> CommandError { CommandError::ParseGraph(e) } } const VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn usage(argc: String) { print!("graph (from unicode_graph) v{}\n\ Copyright © 2016 Patrick Burroughs <celti@celti.name>\n\ \n\ Prints a graph made of Unicode glyphs (at current only Braille patterns). \n\ Usage: {} [h|v][r] <index> [<index>...]\n\ \x20\x20‘h’ and ‘v’ request a horizontal or vertical graph (horizontal if omitted).\n\ \x20\x20`r` reverses the usual direction of the graph (i.e., from the top or left).\n\ \x20\x20The remaining integer arguments indicate the size of the bar at that index.\n", VERSION, argc) } fn _main(mut argv: Vec<String>) -> Result<bool, CommandError> { let arg1 = match argv.get(0) { Some(x) => { x.clone() } None => { return Ok(false) } }; let (call, reverse) = match arg1.as_ref() { "v" => { argv.remove(0); ("vertical", false) } "h" => { argv.remove(0); ("horizontal", false) } "vr" => { argv.remove(0); ("vertical", true) } "hr" => { argv.remove(0); ("horizontal", true) } "r" => { ("horizontal", true) } num if num.parse::<usize>().is_ok() => { ("horizontal", false) } err => { return Err(CommandError::ParseArgs(err.to_owned())) } }; let arg2 = match argv.get(0) { Some(x) => { x.clone() } None => { return Err(CommandError::ParseArgs("no input specified".to_owned())) } }; let reverse = match arg2.as_ref() { "r" => { argv.remove(0); true } num if num.parse::<usize>().is_ok() => { reverse } err => { return Err(CommandError::ParseArgs(err.to_owned())) } }; let input: Vec<usize> = try!(argv.into_iter().map(|i| i.trim().parse()).collect()); let graph = match call { "horizontal" => { try!(braille::horizontal_graph(reverse, input)) } "vertical" => { try!(braille::vertical_graph(reverse, input)) } _ => { return Err(CommandError::UnknownError) } }; for line in try!(graph::graph_to_strings(graph)) { println!("{}", line) }; Ok(true) } fn main() { let
mut argv: Vec<String> = env::args().collect(); let argc: String = argv.remove(0); match _main(argv) { Ok(false) => { usage(argc); process::exit(0) } Err(CommandError::ParseArgs(e)) => { println!("Invalid argument: {}", e); usage(argc); process::exit(64) } Err(CommandError::ParseInt(_)) => { println!("An error occurred parsing the input."); usage(argc); process::exit(65) } Err(CommandError::ParseGraph(_)) => { println!("An error occurred parsing the graph."); process::exit(65) } Err(CommandError::UnknownError) => { println!("An unknown error occurred. Please report this."); process::exit(-1) } Ok(true) => { process::exit(0) } } }
identifier_body
graph.rs
// Copyright (c) 2016 Patrick Burroughs <celti@celti.name>. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0>, or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed except
extern crate unicode_graph; use std::{env, num, process}; use unicode_graph::{graph, braille}; #[derive(Debug)] enum CommandError { UnknownError, ParseArgs(String), ParseGraph(unicode_graph::ParseGraphError), ParseInt(num::ParseIntError), } impl From<num::ParseIntError> for CommandError { fn from(e: num::ParseIntError) -> CommandError { CommandError::ParseInt(e) } } impl From<unicode_graph::ParseGraphError> for CommandError { fn from(e: unicode_graph::ParseGraphError) -> CommandError { CommandError::ParseGraph(e) } } const VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn usage(argc: String) { print!("graph (from unicode_graph) v{}\n\ Copyright © 2016 Patrick Burroughs <celti@celti.name>\n\ \n\ Prints a graph made of Unicode glyphs (at current only Braille patterns). \n\ Usage: {} [h|v][r] <index> [<index>...]\n\ \x20\x20‘h’ and ‘v’ request a horizontal or vertical graph (horizontal if omitted).\n\ \x20\x20`r` reverses the usual direction of the graph (i.e., from the top or left).\n\ \x20\x20The remaining integer arguments indicate the size of the bar at that index.\n", VERSION, argc) } fn _main(mut argv: Vec<String>) -> Result<bool, CommandError> { let arg1 = match argv.get(0) { Some(x) => { x.clone() } None => { return Ok(false) } }; let (call, reverse) = match arg1.as_ref() { "v" => { argv.remove(0); ("vertical", false) } "h" => { argv.remove(0); ("horizontal", false) } "vr" => { argv.remove(0); ("vertical", true) } "hr" => { argv.remove(0); ("horizontal", true) } "r" => { ("horizontal", true) } num if num.parse::<usize>().is_ok() => { ("horizontal", false) } err => { return Err(CommandError::ParseArgs(err.to_owned())) } }; let arg2 = match argv.get(0) { Some(x) => { x.clone() } None => { return Err(CommandError::ParseArgs("no input specified".to_owned())) } }; let reverse = match arg2.as_ref() { "r" => { argv.remove(0); true } num if num.parse::<usize>().is_ok() => { reverse } err => { return Err(CommandError::ParseArgs(err.to_owned())) } }; let input: Vec<usize> = try!(argv.into_iter().map(|i| i.trim().parse()).collect()); let graph = match call { "horizontal" => { try!(braille::horizontal_graph(reverse, input)) } "vertical" => { try!(braille::vertical_graph(reverse, input)) } _ => { return Err(CommandError::UnknownError) } }; for line in try!(graph::graph_to_strings(graph)) { println!("{}", line) }; Ok(true) } fn main() { let mut argv: Vec<String> = env::args().collect(); let argc: String = argv.remove(0); match _main(argv) { Ok(false) => { usage(argc); process::exit(0) } Err(CommandError::ParseArgs(e)) => { println!("Invalid argument: {}", e); usage(argc); process::exit(64) } Err(CommandError::ParseInt(_)) => { println!("An error occurred parsing the input."); usage(argc); process::exit(65) } Err(CommandError::ParseGraph(_)) => { println!("An error occurred parsing the graph."); process::exit(65) } Err(CommandError::UnknownError) => { println!("An unknown error occurred. Please report this."); process::exit(-1) } Ok(true) => { process::exit(0) } } }
// according to those terms.
random_line_split
method-two-trait-defer-resolution-2.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. // Test that when we write `x.foo()`, we do nothave to know the // complete type of `x` in order to type-check the method call. In // this case, we know that `x: Vec<_1>`, but we don't know what type // `_1` is (because the call to `push` comes later). To pick between // the impls, we would have to know `_1`, since we have to know // whether `_1: MyCopy` or `_1 == Box<i32>`. However (and this is the // point of the test), we don't have to pick between the two impls -- // it is enough to know that `foo` comes from the `Foo` trait. We can // translate the call as `Foo::foo(&x)` and let the specific impl get // chosen later. #![allow(unknown_features)] #![feature(box_syntax)] trait Foo { fn foo(&self) -> isize; } trait MyCopy { fn foo(&self) { } } impl MyCopy for i32 { } impl<T:MyCopy> Foo for Vec<T> { fn foo(&self) -> isize {1} } impl Foo for Vec<Box<i32>> { fn foo(&self) -> isize {2} } fn call_foo_copy() -> isize { let mut x = Vec::new(); let y = x.foo(); x.push(0_i32); y } fn call_foo_other() -> isize { let mut x: Vec<_> = Vec::new(); let y = x.foo(); let z: Box<i32> = box 0; x.push(z); y } fn
() { assert_eq!(call_foo_copy(), 1); assert_eq!(call_foo_other(), 2); }
main
identifier_name
method-two-trait-defer-resolution-2.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. // Test that when we write `x.foo()`, we do nothave to know the // complete type of `x` in order to type-check the method call. In // this case, we know that `x: Vec<_1>`, but we don't know what type // `_1` is (because the call to `push` comes later). To pick between // the impls, we would have to know `_1`, since we have to know // whether `_1: MyCopy` or `_1 == Box<i32>`. However (and this is the // point of the test), we don't have to pick between the two impls -- // it is enough to know that `foo` comes from the `Foo` trait. We can // translate the call as `Foo::foo(&x)` and let the specific impl get // chosen later. #![allow(unknown_features)] #![feature(box_syntax)] trait Foo { fn foo(&self) -> isize; } trait MyCopy { fn foo(&self) { } } impl MyCopy for i32 { } impl<T:MyCopy> Foo for Vec<T> { fn foo(&self) -> isize {1} } impl Foo for Vec<Box<i32>> { fn foo(&self) -> isize {2} } fn call_foo_copy() -> isize
fn call_foo_other() -> isize { let mut x: Vec<_> = Vec::new(); let y = x.foo(); let z: Box<i32> = box 0; x.push(z); y } fn main() { assert_eq!(call_foo_copy(), 1); assert_eq!(call_foo_other(), 2); }
{ let mut x = Vec::new(); let y = x.foo(); x.push(0_i32); y }
identifier_body
method-two-trait-defer-resolution-2.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. // Test that when we write `x.foo()`, we do nothave to know the // complete type of `x` in order to type-check the method call. In // this case, we know that `x: Vec<_1>`, but we don't know what type // `_1` is (because the call to `push` comes later). To pick between // the impls, we would have to know `_1`, since we have to know // whether `_1: MyCopy` or `_1 == Box<i32>`. However (and this is the // point of the test), we don't have to pick between the two impls -- // it is enough to know that `foo` comes from the `Foo` trait. We can // translate the call as `Foo::foo(&x)` and let the specific impl get // chosen later. #![allow(unknown_features)] #![feature(box_syntax)] trait Foo { fn foo(&self) -> isize; } trait MyCopy { fn foo(&self) { } } impl MyCopy for i32 { } impl<T:MyCopy> Foo for Vec<T> { fn foo(&self) -> isize {1} } impl Foo for Vec<Box<i32>> { fn foo(&self) -> isize {2} } fn call_foo_copy() -> isize { let mut x = Vec::new(); let y = x.foo();
fn call_foo_other() -> isize { let mut x: Vec<_> = Vec::new(); let y = x.foo(); let z: Box<i32> = box 0; x.push(z); y } fn main() { assert_eq!(call_foo_copy(), 1); assert_eq!(call_foo_other(), 2); }
x.push(0_i32); y }
random_line_split
timer.rs
// Copyright 2014 The sdl2-rs Developers. //
// you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://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 ffi::stdinc::{SDL_bool, Uint32, Uint64}; use libc::{c_int, c_void}; // SDL_timer.h pub type SDL_TimerCallback = extern "C" fn(interval: Uint32, param: *c_void) -> Uint32; pub type SDL_TimerID = c_int; extern "C" { pub fn SDL_GetTicks() -> Uint32; pub fn SDL_GetPerformanceCounter() -> Uint64; pub fn SDL_GetPerformanceFrequency() -> Uint64; pub fn SDL_Delay(ms: Uint32); pub fn SDL_AddTimer(interval: Uint32, callback: SDL_TimerCallback, param: *c_void) -> SDL_TimerID; pub fn SDL_RemoveTimer(id: SDL_TimerID) -> SDL_bool; }
// Licensed under the Apache License, Version 2.0 (the "License");
random_line_split
tokenizer.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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. #![allow(non_camel_case_types)] use core::prelude::*; use for_c::common::{LifetimeBuf, AsLifetimeBuf, h5e_buf, c_bool}; use tokenizer::{TokenSink, Token, Doctype, Tag, ParseError, DoctypeToken}; use tokenizer::{CommentToken, CharacterTokens, NullCharacterToken}; use tokenizer::{TagToken, StartTag, EndTag, EOFToken, Tokenizer}; use core::mem; use core::default::Default; use alloc::boxed::Box; use collections::String; use libc::{c_void, c_int, size_t}; #[repr(C)] pub struct h5e_token_ops { do_doctype: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, public: h5e_buf, system: h5e_buf, force_quirks: c_int)>, do_start_tag: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, self_closing: c_int, num_attrs: size_t)>, do_tag_attr: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, value: h5e_buf)>, do_end_tag: Option<extern "C" fn(user: *mut c_void, name: h5e_buf)>, do_comment: Option<extern "C" fn(user: *mut c_void, text: h5e_buf)>, do_chars: Option<extern "C" fn(user: *mut c_void, text: h5e_buf)>, do_null_char: Option<extern "C" fn(user: *mut c_void)>, do_eof: Option<extern "C" fn(user: *mut c_void)>, do_error: Option<extern "C" fn(user: *mut c_void, message: h5e_buf)>, } impl Copy for h5e_token_ops { } #[repr(C)] pub struct h5e_token_sink { ops: *const h5e_token_ops, user: *mut c_void, } impl Copy for h5e_token_sink { } impl TokenSink for *mut h5e_token_sink { fn process_token(&mut self, token: Token) { macro_rules! call { ($name:ident, $($arg:expr),*) => ( unsafe { match (*(**self).ops).$name { None => (), Some(f) => f((**self).user $(, $arg)*), } } ); ($name:ident) => (call!($name,)); // bleh } fn opt_str_to_buf<'a>(s: &'a Option<String>) -> LifetimeBuf<'a>
match token { DoctypeToken(Doctype { name, public_id, system_id, force_quirks }) => { let name = opt_str_to_buf(&name); let public_id = opt_str_to_buf(&public_id); let system_id = opt_str_to_buf(&system_id); call!(do_doctype, name.get(), public_id.get(), system_id.get(), c_bool(force_quirks)); } TagToken(Tag { kind, name, self_closing, attrs }) => { let name = name.as_lifetime_buf(); match kind { StartTag => { call!(do_start_tag, name.get(), c_bool(self_closing), attrs.len() as size_t); for attr in attrs.into_iter() { // All attribute names from the tokenizer are local. assert!(attr.name.ns == ns!("")); let name = attr.name.local.as_lifetime_buf(); let value = attr.value.as_lifetime_buf(); call!(do_tag_attr, name.get(), value.get()); } } EndTag => call!(do_end_tag, name.get()), } } CommentToken(text) => { let text = text.as_lifetime_buf(); call!(do_comment, text.get()); } CharacterTokens(text) => { let text = text.as_lifetime_buf(); call!(do_chars, text.get()); } NullCharacterToken => call!(do_null_char), EOFToken => call!(do_eof), ParseError(msg) => { let msg = msg.as_lifetime_buf(); call!(do_error, msg.get()); } } } } pub type h5e_tokenizer_ptr = *const (); #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_new(sink: *mut h5e_token_sink) -> h5e_tokenizer_ptr { let tok: Box<Tokenizer<*mut h5e_token_sink>> = box Tokenizer::new(sink, Default::default()); mem::transmute(tok) } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_free(tok: h5e_tokenizer_ptr) { let _: Box<Tokenizer<*mut h5e_token_sink>> = mem::transmute(tok); } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_feed(tok: h5e_tokenizer_ptr, buf: h5e_buf) { let tok: &mut Tokenizer<*mut h5e_token_sink> = mem::transmute(tok); tok.feed(String::from_str(buf.as_slice())); } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_end(tok: h5e_tokenizer_ptr) { let tok: &mut Tokenizer<*mut h5e_token_sink> = mem::transmute(tok); tok.end(); }
{ match *s { None => LifetimeBuf::null(), Some(ref s) => s.as_lifetime_buf(), } }
identifier_body
tokenizer.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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. #![allow(non_camel_case_types)] use core::prelude::*; use for_c::common::{LifetimeBuf, AsLifetimeBuf, h5e_buf, c_bool}; use tokenizer::{TokenSink, Token, Doctype, Tag, ParseError, DoctypeToken};
use core::default::Default; use alloc::boxed::Box; use collections::String; use libc::{c_void, c_int, size_t}; #[repr(C)] pub struct h5e_token_ops { do_doctype: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, public: h5e_buf, system: h5e_buf, force_quirks: c_int)>, do_start_tag: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, self_closing: c_int, num_attrs: size_t)>, do_tag_attr: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, value: h5e_buf)>, do_end_tag: Option<extern "C" fn(user: *mut c_void, name: h5e_buf)>, do_comment: Option<extern "C" fn(user: *mut c_void, text: h5e_buf)>, do_chars: Option<extern "C" fn(user: *mut c_void, text: h5e_buf)>, do_null_char: Option<extern "C" fn(user: *mut c_void)>, do_eof: Option<extern "C" fn(user: *mut c_void)>, do_error: Option<extern "C" fn(user: *mut c_void, message: h5e_buf)>, } impl Copy for h5e_token_ops { } #[repr(C)] pub struct h5e_token_sink { ops: *const h5e_token_ops, user: *mut c_void, } impl Copy for h5e_token_sink { } impl TokenSink for *mut h5e_token_sink { fn process_token(&mut self, token: Token) { macro_rules! call { ($name:ident, $($arg:expr),*) => ( unsafe { match (*(**self).ops).$name { None => (), Some(f) => f((**self).user $(, $arg)*), } } ); ($name:ident) => (call!($name,)); // bleh } fn opt_str_to_buf<'a>(s: &'a Option<String>) -> LifetimeBuf<'a> { match *s { None => LifetimeBuf::null(), Some(ref s) => s.as_lifetime_buf(), } } match token { DoctypeToken(Doctype { name, public_id, system_id, force_quirks }) => { let name = opt_str_to_buf(&name); let public_id = opt_str_to_buf(&public_id); let system_id = opt_str_to_buf(&system_id); call!(do_doctype, name.get(), public_id.get(), system_id.get(), c_bool(force_quirks)); } TagToken(Tag { kind, name, self_closing, attrs }) => { let name = name.as_lifetime_buf(); match kind { StartTag => { call!(do_start_tag, name.get(), c_bool(self_closing), attrs.len() as size_t); for attr in attrs.into_iter() { // All attribute names from the tokenizer are local. assert!(attr.name.ns == ns!("")); let name = attr.name.local.as_lifetime_buf(); let value = attr.value.as_lifetime_buf(); call!(do_tag_attr, name.get(), value.get()); } } EndTag => call!(do_end_tag, name.get()), } } CommentToken(text) => { let text = text.as_lifetime_buf(); call!(do_comment, text.get()); } CharacterTokens(text) => { let text = text.as_lifetime_buf(); call!(do_chars, text.get()); } NullCharacterToken => call!(do_null_char), EOFToken => call!(do_eof), ParseError(msg) => { let msg = msg.as_lifetime_buf(); call!(do_error, msg.get()); } } } } pub type h5e_tokenizer_ptr = *const (); #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_new(sink: *mut h5e_token_sink) -> h5e_tokenizer_ptr { let tok: Box<Tokenizer<*mut h5e_token_sink>> = box Tokenizer::new(sink, Default::default()); mem::transmute(tok) } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_free(tok: h5e_tokenizer_ptr) { let _: Box<Tokenizer<*mut h5e_token_sink>> = mem::transmute(tok); } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_feed(tok: h5e_tokenizer_ptr, buf: h5e_buf) { let tok: &mut Tokenizer<*mut h5e_token_sink> = mem::transmute(tok); tok.feed(String::from_str(buf.as_slice())); } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_end(tok: h5e_tokenizer_ptr) { let tok: &mut Tokenizer<*mut h5e_token_sink> = mem::transmute(tok); tok.end(); }
use tokenizer::{CommentToken, CharacterTokens, NullCharacterToken}; use tokenizer::{TagToken, StartTag, EndTag, EOFToken, Tokenizer}; use core::mem;
random_line_split
tokenizer.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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. #![allow(non_camel_case_types)] use core::prelude::*; use for_c::common::{LifetimeBuf, AsLifetimeBuf, h5e_buf, c_bool}; use tokenizer::{TokenSink, Token, Doctype, Tag, ParseError, DoctypeToken}; use tokenizer::{CommentToken, CharacterTokens, NullCharacterToken}; use tokenizer::{TagToken, StartTag, EndTag, EOFToken, Tokenizer}; use core::mem; use core::default::Default; use alloc::boxed::Box; use collections::String; use libc::{c_void, c_int, size_t}; #[repr(C)] pub struct h5e_token_ops { do_doctype: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, public: h5e_buf, system: h5e_buf, force_quirks: c_int)>, do_start_tag: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, self_closing: c_int, num_attrs: size_t)>, do_tag_attr: Option<extern "C" fn(user: *mut c_void, name: h5e_buf, value: h5e_buf)>, do_end_tag: Option<extern "C" fn(user: *mut c_void, name: h5e_buf)>, do_comment: Option<extern "C" fn(user: *mut c_void, text: h5e_buf)>, do_chars: Option<extern "C" fn(user: *mut c_void, text: h5e_buf)>, do_null_char: Option<extern "C" fn(user: *mut c_void)>, do_eof: Option<extern "C" fn(user: *mut c_void)>, do_error: Option<extern "C" fn(user: *mut c_void, message: h5e_buf)>, } impl Copy for h5e_token_ops { } #[repr(C)] pub struct h5e_token_sink { ops: *const h5e_token_ops, user: *mut c_void, } impl Copy for h5e_token_sink { } impl TokenSink for *mut h5e_token_sink { fn process_token(&mut self, token: Token) { macro_rules! call { ($name:ident, $($arg:expr),*) => ( unsafe { match (*(**self).ops).$name { None => (), Some(f) => f((**self).user $(, $arg)*), } } ); ($name:ident) => (call!($name,)); // bleh } fn opt_str_to_buf<'a>(s: &'a Option<String>) -> LifetimeBuf<'a> { match *s { None => LifetimeBuf::null(), Some(ref s) => s.as_lifetime_buf(), } } match token { DoctypeToken(Doctype { name, public_id, system_id, force_quirks }) => { let name = opt_str_to_buf(&name); let public_id = opt_str_to_buf(&public_id); let system_id = opt_str_to_buf(&system_id); call!(do_doctype, name.get(), public_id.get(), system_id.get(), c_bool(force_quirks)); } TagToken(Tag { kind, name, self_closing, attrs }) => { let name = name.as_lifetime_buf(); match kind { StartTag => { call!(do_start_tag, name.get(), c_bool(self_closing), attrs.len() as size_t); for attr in attrs.into_iter() { // All attribute names from the tokenizer are local. assert!(attr.name.ns == ns!("")); let name = attr.name.local.as_lifetime_buf(); let value = attr.value.as_lifetime_buf(); call!(do_tag_attr, name.get(), value.get()); } } EndTag => call!(do_end_tag, name.get()), } } CommentToken(text) => { let text = text.as_lifetime_buf(); call!(do_comment, text.get()); } CharacterTokens(text) => { let text = text.as_lifetime_buf(); call!(do_chars, text.get()); } NullCharacterToken => call!(do_null_char), EOFToken => call!(do_eof), ParseError(msg) => { let msg = msg.as_lifetime_buf(); call!(do_error, msg.get()); } } } } pub type h5e_tokenizer_ptr = *const (); #[no_mangle] pub unsafe extern "C" fn
(sink: *mut h5e_token_sink) -> h5e_tokenizer_ptr { let tok: Box<Tokenizer<*mut h5e_token_sink>> = box Tokenizer::new(sink, Default::default()); mem::transmute(tok) } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_free(tok: h5e_tokenizer_ptr) { let _: Box<Tokenizer<*mut h5e_token_sink>> = mem::transmute(tok); } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_feed(tok: h5e_tokenizer_ptr, buf: h5e_buf) { let tok: &mut Tokenizer<*mut h5e_token_sink> = mem::transmute(tok); tok.feed(String::from_str(buf.as_slice())); } #[no_mangle] pub unsafe extern "C" fn h5e_tokenizer_end(tok: h5e_tokenizer_ptr) { let tok: &mut Tokenizer<*mut h5e_token_sink> = mem::transmute(tok); tok.end(); }
h5e_tokenizer_new
identifier_name
p091.rs
//! [Problem 91](https://projecteuler.net/problem=91) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_integer::Integer; use std::cmp; fn count_right_at_o(x_max: u32, y_max: u32) -> u32 { x_max * y_max } fn count_right_at_p(x_max: u32, y_max: u32) -> u32 { let mut cnt = x_max * y_max; // p: (0, y0) q: (xi, y0) => xi: [1, x_max], y0: [0, y_max] for x in 1..(x_max + 1) { for y in 1..(y_max + 1) { let d = x.gcd(&y); let (dx, neg_dy) = (y / d, x / d); cnt += cmp::min(y / neg_dy, (x_max - x) / dx); } } cnt } fn
(x_max: u32, y_max: u32) -> u32 { count_right_at_o(x_max, y_max) + count_right_at_p(x_max, y_max) * 2 } fn solve() -> String { compute(50, 50).to_string() } common::problem!("14234", solve); #[cfg(test)] mod tests { #[test] fn two() { assert_eq!(4, super::count_right_at_o(2, 2)); assert_eq!(5, super::count_right_at_p(2, 2)); assert_eq!(14, super::compute(2, 2)); } }
compute
identifier_name
p091.rs
//! [Problem 91](https://projecteuler.net/problem=91) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use num_integer::Integer; use std::cmp; fn count_right_at_o(x_max: u32, y_max: u32) -> u32 { x_max * y_max } fn count_right_at_p(x_max: u32, y_max: u32) -> u32 { let mut cnt = x_max * y_max; // p: (0, y0) q: (xi, y0) => xi: [1, x_max], y0: [0, y_max] for x in 1..(x_max + 1) { for y in 1..(y_max + 1) { let d = x.gcd(&y); let (dx, neg_dy) = (y / d, x / d); cnt += cmp::min(y / neg_dy, (x_max - x) / dx); } } cnt } fn compute(x_max: u32, y_max: u32) -> u32 { count_right_at_o(x_max, y_max) + count_right_at_p(x_max, y_max) * 2 } fn solve() -> String { compute(50, 50).to_string() } common::problem!("14234", solve); #[cfg(test)] mod tests { #[test] fn two()
}
{ assert_eq!(4, super::count_right_at_o(2, 2)); assert_eq!(5, super::count_right_at_p(2, 2)); assert_eq!(14, super::compute(2, 2)); }
identifier_body
p091.rs
//! [Problem 91](https://projecteuler.net/problem=91) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications,
unused_results )] use num_integer::Integer; use std::cmp; fn count_right_at_o(x_max: u32, y_max: u32) -> u32 { x_max * y_max } fn count_right_at_p(x_max: u32, y_max: u32) -> u32 { let mut cnt = x_max * y_max; // p: (0, y0) q: (xi, y0) => xi: [1, x_max], y0: [0, y_max] for x in 1..(x_max + 1) { for y in 1..(y_max + 1) { let d = x.gcd(&y); let (dx, neg_dy) = (y / d, x / d); cnt += cmp::min(y / neg_dy, (x_max - x) / dx); } } cnt } fn compute(x_max: u32, y_max: u32) -> u32 { count_right_at_o(x_max, y_max) + count_right_at_p(x_max, y_max) * 2 } fn solve() -> String { compute(50, 50).to_string() } common::problem!("14234", solve); #[cfg(test)] mod tests { #[test] fn two() { assert_eq!(4, super::count_right_at_o(2, 2)); assert_eq!(5, super::count_right_at_p(2, 2)); assert_eq!(14, super::compute(2, 2)); } }
random_line_split
benches.rs
#![feature(plugin,test)] #![plugin(power_assert)] extern crate ip2location; extern crate test;
#[bench] fn ip2country (bencher: &mut Bencher) { let ip2location = Ip2Location::open ("/usr/share/ip2location/IP2LOCATION-LITE-DB1.BIN").expect ("!open"); bencher.iter (|| { assert_eq! (ip2location.ip2country ("8.8.8.8").expect ("!ip2country"), Some (*b"US"));})} #[bench] fn location (bencher: &mut Bencher) { let ip2location = Ip2Location::open ("/usr/share/ip2location/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-SAMPLE.BIN").expect ("!open"); bencher.iter (|| { let location = ip2location.location ("8.8.8.8").expect ("!location").expect ("!8.8.8.8"); power_assert! (location.longitude.round() == -122.0);})}
use ip2location::Ip2Location; use test::Bencher;
random_line_split
benches.rs
#![feature(plugin,test)] #![plugin(power_assert)] extern crate ip2location; extern crate test; use ip2location::Ip2Location; use test::Bencher; #[bench] fn ip2country (bencher: &mut Bencher) { let ip2location = Ip2Location::open ("/usr/share/ip2location/IP2LOCATION-LITE-DB1.BIN").expect ("!open"); bencher.iter (|| { assert_eq! (ip2location.ip2country ("8.8.8.8").expect ("!ip2country"), Some (*b"US"));})} #[bench] fn location (bencher: &mut Bencher)
{ let ip2location = Ip2Location::open ("/usr/share/ip2location/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-SAMPLE.BIN") .expect ("!open"); bencher.iter (|| { let location = ip2location.location ("8.8.8.8") .expect ("!location") .expect ("!8.8.8.8"); power_assert! (location.longitude.round() == -122.0);})}
identifier_body
benches.rs
#![feature(plugin,test)] #![plugin(power_assert)] extern crate ip2location; extern crate test; use ip2location::Ip2Location; use test::Bencher; #[bench] fn
(bencher: &mut Bencher) { let ip2location = Ip2Location::open ("/usr/share/ip2location/IP2LOCATION-LITE-DB1.BIN").expect ("!open"); bencher.iter (|| { assert_eq! (ip2location.ip2country ("8.8.8.8").expect ("!ip2country"), Some (*b"US"));})} #[bench] fn location (bencher: &mut Bencher) { let ip2location = Ip2Location::open ("/usr/share/ip2location/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-SAMPLE.BIN").expect ("!open"); bencher.iter (|| { let location = ip2location.location ("8.8.8.8").expect ("!location").expect ("!8.8.8.8"); power_assert! (location.longitude.round() == -122.0);})}
ip2country
identifier_name
karma.rs
use rusqlite as rs; use slack_api as slack; use chrono::prelude::{Utc, DateTime}; use std::result::Result; use tokio::sync::mpsc; use crate::bot::parser::karma::KST; use crate::bot::parser::karma; use crate::bot::query::KarmaName; use crate::bot::query::normalize; use crate::bot::query::santizer; use crate::core::cache; use crate::core::database::Query; use crate::core::database::send_query; pub async fn add_karma<R>( sql_tx: &mut mpsc::Sender<Query>, cache: &cache::Cache<R>, input: &str, user_id: String, channel_id: String, ) where R: slack::requests::SlackWebRequestSender + std::clone::Clone { let santized_text = santizer(&input, &cache).await; let res = karma::parse(&santized_text); match res { Ok(mut karma) if!karma.is_empty() => { println!("INFO [User Event]: Parsed Karma: {:?}", karma); let username = cache.get_username(&user_id).await; let user_real_name = cache.get_user_real_name(&user_id).await; // Filter karma of any entity that is same as // username, and check if any got filtered, if // so, log. let before = karma.len(); match username { None => (), Some(ref ud) => karma.retain(|&karma::KST(ref t, _)| { KarmaName::new(t)!= KarmaName::new(ud) }), } let after = karma.len(); if before!= after { println!("INFO [User Event]: User self-voted: {:?}", username); } if!karma.is_empty() { match (username, user_real_name) { (Some(ud), Some(rn)) => { let _ = add_karma_query( sql_tx, Utc::now(), user_id, KarmaName::new(&ud), KarmaName::new(&rn), Some(channel_id), karma ).await; }, _ => eprintln!("ERROR: [User Event] Wasn't able to get a username/real_name from slack"), } } }, Ok(_) => (), Err(e) => { // The parse should return empty if its valid, something // broke, should log it here eprintln!("ERROR [User Event]: Failed to parse karma: {:?}", e); }, } } async fn add_karma_query( sql_tx: &mut mpsc::Sender<Query>, timestamp: DateTime<Utc>, user_id: String, username: KarmaName, real_name: KarmaName, channel_id: Option<String>, karma: Vec<KST>, ) -> Result<Option<i64>, &'static str>
let mut stmt = conn.prepare("SELECT id FROM chan_metadata WHERE channel =?").unwrap(); let mut rows = stmt.query(rs::params![cid]).unwrap(); if let Ok(Some(row)) = rows.next() { row.get(0).ok() } else { let mut stmt = conn.prepare("INSERT INTO chan_metadata (channel) VALUES (?)").unwrap(); stmt.insert(rs::params![cid]).ok() } } else { None }; // Shove the karma into the db now let txn = conn.transaction().expect("txn error"); { let mut stmt = txn.prepare( "INSERT INTO votes (voted_at, by_whom_name, for_what_name, amount, nick_id, chan_id) VALUES (?,?,?,?,?,?)" ).unwrap(); for KST(karma_text, amount) in karma.iter() { let ts = timestamp.to_rfc3339(); let ts = ts.trim_end_matches("+00:00"); let karma_text = normalize(karma_text); // TODO: better handle failure of username, maybe we should make username // mandatory before inserting? match channel_id { Some(cid) => stmt.insert( rs::params![ts, username, karma_text, amount, nick_id, cid] ).unwrap(), None => stmt.insert( rs::params![ts, username, karma_text, amount, nick_id, &rs::types::Null] ).unwrap(), }; } } let _ = txn.commit(); Ok(None) }) ).await }
{ send_query( sql_tx, Box::new(move |conn: &mut rs::Connection| { let nick_id: i64 = { let mut stmt = conn.prepare("SELECT id FROM nick_metadata WHERE username = ?").unwrap(); let mut rows = stmt.query(rs::params![user_id]).unwrap(); if let Ok(Some(row)) = rows.next() { row.get(0).unwrap() } else { let mut stmt = conn.prepare( "INSERT INTO nick_metadata (cleaned_nick, full_name, username, hostmask) VALUES (?, ?, ?, ?)" ).unwrap(); stmt.insert(rs::params![username, real_name, user_id, "SlackServer"]).unwrap() } }; let channel_id: Option<i64> = if let Some(cid) = channel_id {
identifier_body
karma.rs
use rusqlite as rs; use slack_api as slack; use chrono::prelude::{Utc, DateTime}; use std::result::Result; use tokio::sync::mpsc; use crate::bot::parser::karma::KST; use crate::bot::parser::karma; use crate::bot::query::KarmaName; use crate::bot::query::normalize; use crate::bot::query::santizer; use crate::core::cache; use crate::core::database::Query; use crate::core::database::send_query; pub async fn add_karma<R>( sql_tx: &mut mpsc::Sender<Query>, cache: &cache::Cache<R>, input: &str, user_id: String, channel_id: String, ) where R: slack::requests::SlackWebRequestSender + std::clone::Clone { let santized_text = santizer(&input, &cache).await; let res = karma::parse(&santized_text); match res { Ok(mut karma) if!karma.is_empty() => { println!("INFO [User Event]: Parsed Karma: {:?}", karma); let username = cache.get_username(&user_id).await; let user_real_name = cache.get_user_real_name(&user_id).await; // Filter karma of any entity that is same as // username, and check if any got filtered, if // so, log. let before = karma.len(); match username { None => (), Some(ref ud) => karma.retain(|&karma::KST(ref t, _)| { KarmaName::new(t)!= KarmaName::new(ud) }), } let after = karma.len(); if before!= after { println!("INFO [User Event]: User self-voted: {:?}", username); } if!karma.is_empty() {
match (username, user_real_name) { (Some(ud), Some(rn)) => { let _ = add_karma_query( sql_tx, Utc::now(), user_id, KarmaName::new(&ud), KarmaName::new(&rn), Some(channel_id), karma ).await; }, _ => eprintln!("ERROR: [User Event] Wasn't able to get a username/real_name from slack"), } } }, Ok(_) => (), Err(e) => { // The parse should return empty if its valid, something // broke, should log it here eprintln!("ERROR [User Event]: Failed to parse karma: {:?}", e); }, } } async fn add_karma_query( sql_tx: &mut mpsc::Sender<Query>, timestamp: DateTime<Utc>, user_id: String, username: KarmaName, real_name: KarmaName, channel_id: Option<String>, karma: Vec<KST>, ) -> Result<Option<i64>, &'static str> { send_query( sql_tx, Box::new(move |conn: &mut rs::Connection| { let nick_id: i64 = { let mut stmt = conn.prepare("SELECT id FROM nick_metadata WHERE username =?").unwrap(); let mut rows = stmt.query(rs::params![user_id]).unwrap(); if let Ok(Some(row)) = rows.next() { row.get(0).unwrap() } else { let mut stmt = conn.prepare( "INSERT INTO nick_metadata (cleaned_nick, full_name, username, hostmask) VALUES (?,?,?,?)" ).unwrap(); stmt.insert(rs::params![username, real_name, user_id, "SlackServer"]).unwrap() } }; let channel_id: Option<i64> = if let Some(cid) = channel_id { let mut stmt = conn.prepare("SELECT id FROM chan_metadata WHERE channel =?").unwrap(); let mut rows = stmt.query(rs::params![cid]).unwrap(); if let Ok(Some(row)) = rows.next() { row.get(0).ok() } else { let mut stmt = conn.prepare("INSERT INTO chan_metadata (channel) VALUES (?)").unwrap(); stmt.insert(rs::params![cid]).ok() } } else { None }; // Shove the karma into the db now let txn = conn.transaction().expect("txn error"); { let mut stmt = txn.prepare( "INSERT INTO votes (voted_at, by_whom_name, for_what_name, amount, nick_id, chan_id) VALUES (?,?,?,?,?,?)" ).unwrap(); for KST(karma_text, amount) in karma.iter() { let ts = timestamp.to_rfc3339(); let ts = ts.trim_end_matches("+00:00"); let karma_text = normalize(karma_text); // TODO: better handle failure of username, maybe we should make username // mandatory before inserting? match channel_id { Some(cid) => stmt.insert( rs::params![ts, username, karma_text, amount, nick_id, cid] ).unwrap(), None => stmt.insert( rs::params![ts, username, karma_text, amount, nick_id, &rs::types::Null] ).unwrap(), }; } } let _ = txn.commit(); Ok(None) }) ).await }
random_line_split
karma.rs
use rusqlite as rs; use slack_api as slack; use chrono::prelude::{Utc, DateTime}; use std::result::Result; use tokio::sync::mpsc; use crate::bot::parser::karma::KST; use crate::bot::parser::karma; use crate::bot::query::KarmaName; use crate::bot::query::normalize; use crate::bot::query::santizer; use crate::core::cache; use crate::core::database::Query; use crate::core::database::send_query; pub async fn add_karma<R>( sql_tx: &mut mpsc::Sender<Query>, cache: &cache::Cache<R>, input: &str, user_id: String, channel_id: String, ) where R: slack::requests::SlackWebRequestSender + std::clone::Clone { let santized_text = santizer(&input, &cache).await; let res = karma::parse(&santized_text); match res { Ok(mut karma) if!karma.is_empty() => { println!("INFO [User Event]: Parsed Karma: {:?}", karma); let username = cache.get_username(&user_id).await; let user_real_name = cache.get_user_real_name(&user_id).await; // Filter karma of any entity that is same as // username, and check if any got filtered, if // so, log. let before = karma.len(); match username { None => (), Some(ref ud) => karma.retain(|&karma::KST(ref t, _)| { KarmaName::new(t)!= KarmaName::new(ud) }), } let after = karma.len(); if before!= after { println!("INFO [User Event]: User self-voted: {:?}", username); } if!karma.is_empty() { match (username, user_real_name) { (Some(ud), Some(rn)) => { let _ = add_karma_query( sql_tx, Utc::now(), user_id, KarmaName::new(&ud), KarmaName::new(&rn), Some(channel_id), karma ).await; }, _ => eprintln!("ERROR: [User Event] Wasn't able to get a username/real_name from slack"), } } }, Ok(_) => (), Err(e) => { // The parse should return empty if its valid, something // broke, should log it here eprintln!("ERROR [User Event]: Failed to parse karma: {:?}", e); }, } } async fn
( sql_tx: &mut mpsc::Sender<Query>, timestamp: DateTime<Utc>, user_id: String, username: KarmaName, real_name: KarmaName, channel_id: Option<String>, karma: Vec<KST>, ) -> Result<Option<i64>, &'static str> { send_query( sql_tx, Box::new(move |conn: &mut rs::Connection| { let nick_id: i64 = { let mut stmt = conn.prepare("SELECT id FROM nick_metadata WHERE username =?").unwrap(); let mut rows = stmt.query(rs::params![user_id]).unwrap(); if let Ok(Some(row)) = rows.next() { row.get(0).unwrap() } else { let mut stmt = conn.prepare( "INSERT INTO nick_metadata (cleaned_nick, full_name, username, hostmask) VALUES (?,?,?,?)" ).unwrap(); stmt.insert(rs::params![username, real_name, user_id, "SlackServer"]).unwrap() } }; let channel_id: Option<i64> = if let Some(cid) = channel_id { let mut stmt = conn.prepare("SELECT id FROM chan_metadata WHERE channel =?").unwrap(); let mut rows = stmt.query(rs::params![cid]).unwrap(); if let Ok(Some(row)) = rows.next() { row.get(0).ok() } else { let mut stmt = conn.prepare("INSERT INTO chan_metadata (channel) VALUES (?)").unwrap(); stmt.insert(rs::params![cid]).ok() } } else { None }; // Shove the karma into the db now let txn = conn.transaction().expect("txn error"); { let mut stmt = txn.prepare( "INSERT INTO votes (voted_at, by_whom_name, for_what_name, amount, nick_id, chan_id) VALUES (?,?,?,?,?,?)" ).unwrap(); for KST(karma_text, amount) in karma.iter() { let ts = timestamp.to_rfc3339(); let ts = ts.trim_end_matches("+00:00"); let karma_text = normalize(karma_text); // TODO: better handle failure of username, maybe we should make username // mandatory before inserting? match channel_id { Some(cid) => stmt.insert( rs::params![ts, username, karma_text, amount, nick_id, cid] ).unwrap(), None => stmt.insert( rs::params![ts, username, karma_text, amount, nick_id, &rs::types::Null] ).unwrap(), }; } } let _ = txn.commit(); Ok(None) }) ).await }
add_karma_query
identifier_name
client.rs
use BindClient; use streaming::{Body, Message}; use super::{StreamingPipeline, Frame, Transport}; use super::advanced::{Pipeline, PipelineMessage}; use util::client_proxy::{self, ClientProxy, Receiver}; use futures::{Future, IntoFuture, Poll, Async, Stream}; use futures::sync::oneshot; use tokio_core::reactor::Handle; use std::collections::VecDeque; use std::io; /// A streaming, pipelined client protocol. /// /// The `T` parameter is used for the I/O object used to communicate, which is /// supplied in `bind_transport`. /// /// For simple protocols, the `Self` type is often a unit struct. In more /// advanced cases, `Self` may contain configuration information that is used /// for setting up the transport in `bind_transport`. pub trait ClientProto<T:'static>:'static { /// The type of request headers. type Request:'static; /// The type of request body chunks. type RequestBody:'static; /// The type of response headers. type Response:'static; /// The type of response body chunks. type ResponseBody:'static; /// The type of error frames. type Error: From<io::Error> +'static; /// The frame transport, which usually take `T` as a parameter. type Transport: Transport<Item = Frame<Self::Response, Self::ResponseBody, Self::Error>, SinkItem = Frame<Self::Request, Self::RequestBody, Self::Error>>; /// A future for initializing a transport from an I/O object. /// /// In simple cases, `Result<Self::Transport, Self::Error>` often suffices. type BindTransport: IntoFuture<Item = Self::Transport, Error = io::Error>; /// Build a transport from the given I/O object, using `self` for any /// configuration. fn bind_transport(&self, io: T) -> Self::BindTransport; } impl<P, T, B> BindClient<StreamingPipeline<B>, T> for P where P: ClientProto<T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { type ServiceRequest = Message<P::Request, B>; type ServiceResponse = Message<P::Response, Body<P::ResponseBody, P::Error>>; type ServiceError = P::Error; type BindClient = ClientProxy<Self::ServiceRequest, Self::ServiceResponse, Self::ServiceError>; fn bind_client(&self, handle: &Handle, io: T) -> Self::BindClient { let (client, rx) = client_proxy::pair(); let task = self.bind_transport(io).into_future().and_then(|transport| { let dispatch: Dispatch<P, T, B> = Dispatch { transport: transport, requests: rx, in_flight: VecDeque::with_capacity(32), }; Pipeline::new(dispatch) }).map_err(|e| { // TODO: where to punt this error to? error!("pipeline error: {}", e); }); // Spawn the task handle.spawn(task); // Return the client client } } struct Dispatch<P, T, B> where P: ClientProto<T> + BindClient<StreamingPipeline<B>, T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { transport: P::Transport, requests: Receiver<P::ServiceRequest, P::ServiceResponse, P::Error>, in_flight: VecDeque<oneshot::Sender<Result<P::ServiceResponse, P::Error>>>, } impl<P, T, B> super::advanced::Dispatch for Dispatch<P, T, B> where P: ClientProto<T>, B: Stream<Item = P::RequestBody, Error = P::Error>, { type Io = T; type In = P::Request; type BodyIn = P::RequestBody; type Out = P::Response; type BodyOut = P::ResponseBody; type Error = P::Error; type Stream = B; type Transport = P::Transport; fn transport(&mut self) -> &mut Self::Transport { &mut self.transport } fn
(&mut self, response: PipelineMessage<Self::Out, Body<Self::BodyOut, Self::Error>, Self::Error>) -> io::Result<()> { if let Some(complete) = self.in_flight.pop_front() { drop(complete.send(response)); } else { return Err(io::Error::new(io::ErrorKind::Other, "request / response mismatch")); } Ok(()) } fn poll(&mut self) -> Poll<Option<PipelineMessage<Self::In, Self::Stream, Self::Error>>, io::Error> { trace!("Dispatch::poll"); // Try to get a new request frame match self.requests.poll() { Ok(Async::Ready(Some(Ok((request, complete))))) => { trace!(" --> received request"); // Track complete handle self.in_flight.push_back(complete); Ok(Async::Ready(Some(Ok(request)))) } Ok(Async::Ready(None)) => { trace!(" --> client dropped"); Ok(Async::Ready(None)) } Ok(Async::Ready(Some(Err(e)))) => { trace!(" --> error"); // An error on receive can only happen when the other half // disconnected. In this case, the client needs to be // shutdown panic!("unimplemented error handling: {:?}", e); } Ok(Async::NotReady) => { trace!(" --> not ready"); Ok(Async::NotReady) } Err(()) => panic!(), } } fn has_in_flight(&self) -> bool { !self.in_flight.is_empty() } } impl<P, T, B> Drop for Dispatch<P, T, B> where P: ClientProto<T> + BindClient<StreamingPipeline<B>, T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { fn drop(&mut self) { // Complete any pending requests with an error while let Some(complete) = self.in_flight.pop_front() { drop(complete.send(Err(broken_pipe().into()))); } } } fn broken_pipe() -> io::Error { io::Error::new(io::ErrorKind::BrokenPipe, "broken pipe") }
dispatch
identifier_name
client.rs
use BindClient; use streaming::{Body, Message}; use super::{StreamingPipeline, Frame, Transport}; use super::advanced::{Pipeline, PipelineMessage}; use util::client_proxy::{self, ClientProxy, Receiver}; use futures::{Future, IntoFuture, Poll, Async, Stream}; use futures::sync::oneshot; use tokio_core::reactor::Handle; use std::collections::VecDeque; use std::io; /// A streaming, pipelined client protocol. /// /// The `T` parameter is used for the I/O object used to communicate, which is /// supplied in `bind_transport`. /// /// For simple protocols, the `Self` type is often a unit struct. In more /// advanced cases, `Self` may contain configuration information that is used /// for setting up the transport in `bind_transport`. pub trait ClientProto<T:'static>:'static { /// The type of request headers. type Request:'static; /// The type of request body chunks. type RequestBody:'static; /// The type of response headers. type Response:'static; /// The type of response body chunks. type ResponseBody:'static; /// The type of error frames. type Error: From<io::Error> +'static; /// The frame transport, which usually take `T` as a parameter. type Transport: Transport<Item = Frame<Self::Response, Self::ResponseBody, Self::Error>, SinkItem = Frame<Self::Request, Self::RequestBody, Self::Error>>; /// A future for initializing a transport from an I/O object. /// /// In simple cases, `Result<Self::Transport, Self::Error>` often suffices. type BindTransport: IntoFuture<Item = Self::Transport, Error = io::Error>; /// Build a transport from the given I/O object, using `self` for any /// configuration. fn bind_transport(&self, io: T) -> Self::BindTransport; } impl<P, T, B> BindClient<StreamingPipeline<B>, T> for P where P: ClientProto<T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { type ServiceRequest = Message<P::Request, B>; type ServiceResponse = Message<P::Response, Body<P::ResponseBody, P::Error>>; type ServiceError = P::Error; type BindClient = ClientProxy<Self::ServiceRequest, Self::ServiceResponse, Self::ServiceError>; fn bind_client(&self, handle: &Handle, io: T) -> Self::BindClient { let (client, rx) = client_proxy::pair(); let task = self.bind_transport(io).into_future().and_then(|transport| { let dispatch: Dispatch<P, T, B> = Dispatch { transport: transport, requests: rx, in_flight: VecDeque::with_capacity(32), }; Pipeline::new(dispatch) }).map_err(|e| { // TODO: where to punt this error to? error!("pipeline error: {}", e); }); // Spawn the task handle.spawn(task); // Return the client client } } struct Dispatch<P, T, B> where P: ClientProto<T> + BindClient<StreamingPipeline<B>, T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { transport: P::Transport, requests: Receiver<P::ServiceRequest, P::ServiceResponse, P::Error>, in_flight: VecDeque<oneshot::Sender<Result<P::ServiceResponse, P::Error>>>, } impl<P, T, B> super::advanced::Dispatch for Dispatch<P, T, B> where P: ClientProto<T>, B: Stream<Item = P::RequestBody, Error = P::Error>, { type Io = T; type In = P::Request; type BodyIn = P::RequestBody; type Out = P::Response; type BodyOut = P::ResponseBody; type Error = P::Error; type Stream = B; type Transport = P::Transport; fn transport(&mut self) -> &mut Self::Transport { &mut self.transport } fn dispatch(&mut self, response: PipelineMessage<Self::Out, Body<Self::BodyOut, Self::Error>, Self::Error>) -> io::Result<()> {
Ok(()) } fn poll(&mut self) -> Poll<Option<PipelineMessage<Self::In, Self::Stream, Self::Error>>, io::Error> { trace!("Dispatch::poll"); // Try to get a new request frame match self.requests.poll() { Ok(Async::Ready(Some(Ok((request, complete))))) => { trace!(" --> received request"); // Track complete handle self.in_flight.push_back(complete); Ok(Async::Ready(Some(Ok(request)))) } Ok(Async::Ready(None)) => { trace!(" --> client dropped"); Ok(Async::Ready(None)) } Ok(Async::Ready(Some(Err(e)))) => { trace!(" --> error"); // An error on receive can only happen when the other half // disconnected. In this case, the client needs to be // shutdown panic!("unimplemented error handling: {:?}", e); } Ok(Async::NotReady) => { trace!(" --> not ready"); Ok(Async::NotReady) } Err(()) => panic!(), } } fn has_in_flight(&self) -> bool { !self.in_flight.is_empty() } } impl<P, T, B> Drop for Dispatch<P, T, B> where P: ClientProto<T> + BindClient<StreamingPipeline<B>, T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { fn drop(&mut self) { // Complete any pending requests with an error while let Some(complete) = self.in_flight.pop_front() { drop(complete.send(Err(broken_pipe().into()))); } } } fn broken_pipe() -> io::Error { io::Error::new(io::ErrorKind::BrokenPipe, "broken pipe") }
if let Some(complete) = self.in_flight.pop_front() { drop(complete.send(response)); } else { return Err(io::Error::new(io::ErrorKind::Other, "request / response mismatch")); }
random_line_split
client.rs
use BindClient; use streaming::{Body, Message}; use super::{StreamingPipeline, Frame, Transport}; use super::advanced::{Pipeline, PipelineMessage}; use util::client_proxy::{self, ClientProxy, Receiver}; use futures::{Future, IntoFuture, Poll, Async, Stream}; use futures::sync::oneshot; use tokio_core::reactor::Handle; use std::collections::VecDeque; use std::io; /// A streaming, pipelined client protocol. /// /// The `T` parameter is used for the I/O object used to communicate, which is /// supplied in `bind_transport`. /// /// For simple protocols, the `Self` type is often a unit struct. In more /// advanced cases, `Self` may contain configuration information that is used /// for setting up the transport in `bind_transport`. pub trait ClientProto<T:'static>:'static { /// The type of request headers. type Request:'static; /// The type of request body chunks. type RequestBody:'static; /// The type of response headers. type Response:'static; /// The type of response body chunks. type ResponseBody:'static; /// The type of error frames. type Error: From<io::Error> +'static; /// The frame transport, which usually take `T` as a parameter. type Transport: Transport<Item = Frame<Self::Response, Self::ResponseBody, Self::Error>, SinkItem = Frame<Self::Request, Self::RequestBody, Self::Error>>; /// A future for initializing a transport from an I/O object. /// /// In simple cases, `Result<Self::Transport, Self::Error>` often suffices. type BindTransport: IntoFuture<Item = Self::Transport, Error = io::Error>; /// Build a transport from the given I/O object, using `self` for any /// configuration. fn bind_transport(&self, io: T) -> Self::BindTransport; } impl<P, T, B> BindClient<StreamingPipeline<B>, T> for P where P: ClientProto<T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { type ServiceRequest = Message<P::Request, B>; type ServiceResponse = Message<P::Response, Body<P::ResponseBody, P::Error>>; type ServiceError = P::Error; type BindClient = ClientProxy<Self::ServiceRequest, Self::ServiceResponse, Self::ServiceError>; fn bind_client(&self, handle: &Handle, io: T) -> Self::BindClient { let (client, rx) = client_proxy::pair(); let task = self.bind_transport(io).into_future().and_then(|transport| { let dispatch: Dispatch<P, T, B> = Dispatch { transport: transport, requests: rx, in_flight: VecDeque::with_capacity(32), }; Pipeline::new(dispatch) }).map_err(|e| { // TODO: where to punt this error to? error!("pipeline error: {}", e); }); // Spawn the task handle.spawn(task); // Return the client client } } struct Dispatch<P, T, B> where P: ClientProto<T> + BindClient<StreamingPipeline<B>, T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { transport: P::Transport, requests: Receiver<P::ServiceRequest, P::ServiceResponse, P::Error>, in_flight: VecDeque<oneshot::Sender<Result<P::ServiceResponse, P::Error>>>, } impl<P, T, B> super::advanced::Dispatch for Dispatch<P, T, B> where P: ClientProto<T>, B: Stream<Item = P::RequestBody, Error = P::Error>, { type Io = T; type In = P::Request; type BodyIn = P::RequestBody; type Out = P::Response; type BodyOut = P::ResponseBody; type Error = P::Error; type Stream = B; type Transport = P::Transport; fn transport(&mut self) -> &mut Self::Transport { &mut self.transport } fn dispatch(&mut self, response: PipelineMessage<Self::Out, Body<Self::BodyOut, Self::Error>, Self::Error>) -> io::Result<()> { if let Some(complete) = self.in_flight.pop_front() { drop(complete.send(response)); } else
Ok(()) } fn poll(&mut self) -> Poll<Option<PipelineMessage<Self::In, Self::Stream, Self::Error>>, io::Error> { trace!("Dispatch::poll"); // Try to get a new request frame match self.requests.poll() { Ok(Async::Ready(Some(Ok((request, complete))))) => { trace!(" --> received request"); // Track complete handle self.in_flight.push_back(complete); Ok(Async::Ready(Some(Ok(request)))) } Ok(Async::Ready(None)) => { trace!(" --> client dropped"); Ok(Async::Ready(None)) } Ok(Async::Ready(Some(Err(e)))) => { trace!(" --> error"); // An error on receive can only happen when the other half // disconnected. In this case, the client needs to be // shutdown panic!("unimplemented error handling: {:?}", e); } Ok(Async::NotReady) => { trace!(" --> not ready"); Ok(Async::NotReady) } Err(()) => panic!(), } } fn has_in_flight(&self) -> bool { !self.in_flight.is_empty() } } impl<P, T, B> Drop for Dispatch<P, T, B> where P: ClientProto<T> + BindClient<StreamingPipeline<B>, T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { fn drop(&mut self) { // Complete any pending requests with an error while let Some(complete) = self.in_flight.pop_front() { drop(complete.send(Err(broken_pipe().into()))); } } } fn broken_pipe() -> io::Error { io::Error::new(io::ErrorKind::BrokenPipe, "broken pipe") }
{ return Err(io::Error::new(io::ErrorKind::Other, "request / response mismatch")); }
conditional_block
client.rs
use BindClient; use streaming::{Body, Message}; use super::{StreamingPipeline, Frame, Transport}; use super::advanced::{Pipeline, PipelineMessage}; use util::client_proxy::{self, ClientProxy, Receiver}; use futures::{Future, IntoFuture, Poll, Async, Stream}; use futures::sync::oneshot; use tokio_core::reactor::Handle; use std::collections::VecDeque; use std::io; /// A streaming, pipelined client protocol. /// /// The `T` parameter is used for the I/O object used to communicate, which is /// supplied in `bind_transport`. /// /// For simple protocols, the `Self` type is often a unit struct. In more /// advanced cases, `Self` may contain configuration information that is used /// for setting up the transport in `bind_transport`. pub trait ClientProto<T:'static>:'static { /// The type of request headers. type Request:'static; /// The type of request body chunks. type RequestBody:'static; /// The type of response headers. type Response:'static; /// The type of response body chunks. type ResponseBody:'static; /// The type of error frames. type Error: From<io::Error> +'static; /// The frame transport, which usually take `T` as a parameter. type Transport: Transport<Item = Frame<Self::Response, Self::ResponseBody, Self::Error>, SinkItem = Frame<Self::Request, Self::RequestBody, Self::Error>>; /// A future for initializing a transport from an I/O object. /// /// In simple cases, `Result<Self::Transport, Self::Error>` often suffices. type BindTransport: IntoFuture<Item = Self::Transport, Error = io::Error>; /// Build a transport from the given I/O object, using `self` for any /// configuration. fn bind_transport(&self, io: T) -> Self::BindTransport; } impl<P, T, B> BindClient<StreamingPipeline<B>, T> for P where P: ClientProto<T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { type ServiceRequest = Message<P::Request, B>; type ServiceResponse = Message<P::Response, Body<P::ResponseBody, P::Error>>; type ServiceError = P::Error; type BindClient = ClientProxy<Self::ServiceRequest, Self::ServiceResponse, Self::ServiceError>; fn bind_client(&self, handle: &Handle, io: T) -> Self::BindClient { let (client, rx) = client_proxy::pair(); let task = self.bind_transport(io).into_future().and_then(|transport| { let dispatch: Dispatch<P, T, B> = Dispatch { transport: transport, requests: rx, in_flight: VecDeque::with_capacity(32), }; Pipeline::new(dispatch) }).map_err(|e| { // TODO: where to punt this error to? error!("pipeline error: {}", e); }); // Spawn the task handle.spawn(task); // Return the client client } } struct Dispatch<P, T, B> where P: ClientProto<T> + BindClient<StreamingPipeline<B>, T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { transport: P::Transport, requests: Receiver<P::ServiceRequest, P::ServiceResponse, P::Error>, in_flight: VecDeque<oneshot::Sender<Result<P::ServiceResponse, P::Error>>>, } impl<P, T, B> super::advanced::Dispatch for Dispatch<P, T, B> where P: ClientProto<T>, B: Stream<Item = P::RequestBody, Error = P::Error>, { type Io = T; type In = P::Request; type BodyIn = P::RequestBody; type Out = P::Response; type BodyOut = P::ResponseBody; type Error = P::Error; type Stream = B; type Transport = P::Transport; fn transport(&mut self) -> &mut Self::Transport { &mut self.transport } fn dispatch(&mut self, response: PipelineMessage<Self::Out, Body<Self::BodyOut, Self::Error>, Self::Error>) -> io::Result<()>
fn poll(&mut self) -> Poll<Option<PipelineMessage<Self::In, Self::Stream, Self::Error>>, io::Error> { trace!("Dispatch::poll"); // Try to get a new request frame match self.requests.poll() { Ok(Async::Ready(Some(Ok((request, complete))))) => { trace!(" --> received request"); // Track complete handle self.in_flight.push_back(complete); Ok(Async::Ready(Some(Ok(request)))) } Ok(Async::Ready(None)) => { trace!(" --> client dropped"); Ok(Async::Ready(None)) } Ok(Async::Ready(Some(Err(e)))) => { trace!(" --> error"); // An error on receive can only happen when the other half // disconnected. In this case, the client needs to be // shutdown panic!("unimplemented error handling: {:?}", e); } Ok(Async::NotReady) => { trace!(" --> not ready"); Ok(Async::NotReady) } Err(()) => panic!(), } } fn has_in_flight(&self) -> bool { !self.in_flight.is_empty() } } impl<P, T, B> Drop for Dispatch<P, T, B> where P: ClientProto<T> + BindClient<StreamingPipeline<B>, T>, T:'static, B: Stream<Item = P::RequestBody, Error = P::Error> +'static, { fn drop(&mut self) { // Complete any pending requests with an error while let Some(complete) = self.in_flight.pop_front() { drop(complete.send(Err(broken_pipe().into()))); } } } fn broken_pipe() -> io::Error { io::Error::new(io::ErrorKind::BrokenPipe, "broken pipe") }
{ if let Some(complete) = self.in_flight.pop_front() { drop(complete.send(response)); } else { return Err(io::Error::new(io::ErrorKind::Other, "request / response mismatch")); } Ok(()) }
identifier_body
quicksort.rs
// use rand::{thread_rng, Rng}; use std::mem; use super::insertion_sort; /// quicksort partitioning fn partition<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) -> usize { let mut i = lo; let mut j = hi + 1; loop { loop { i += 1; if a[i] < a[lo] { if i == hi { break } } else { break } } loop { j -= 1; if a[lo] < a[j] { if j == lo { break } } else { break } } if i >= j { break; } a.swap(i, j); } a.swap(lo, j); j } /// find median of 3, index #[allow(dead_code)] #[inline] fn median_of_3<T: PartialOrd>(a: &[T], i: usize, j: usize, k: usize) -> usize
} } } // Cutoff to insertion sort for ≈ 10 items. const CUTOFF: usize = 10; /// quicksort optimised fn sort<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) { // # small subarrays improve: if hi <= lo + CUTOFF - 1 { insertion_sort(&mut a[lo.. hi+1]); return ; } // # awaste of time under big arrays: // let m = median_of_3(a, lo, lo + (hi - lo)/2, hi); // a.swap(lo, m); let j = partition(a, lo, hi); // BUG FIXED: (in original code) if j == 0, j - 1 overflows if j > 1 { sort(a, lo, j-1); } sort(a, j+1, hi); } /// quicksort optimised pub fn quick_sort<T: PartialOrd>(a: &mut [T]) { let n = a.len(); // # time waste // let mut rng = thread_rng(); // rng.shuffle(a); if n > 1 { sort(a, 0, n-1) } } /// quick-select pub fn quick_select<T: PartialOrd>(a: &mut [T], k: usize) -> T { // skip StdRandom.shuffle(a); let mut lo = 0; let mut hi = a.len() - 1; while hi > lo { let j = partition(a, lo, hi); if j < k { lo = j + 1; } else if j > k { hi = j - 1; } else { break; } } // take the value out // FIXME: better to return a &T? mem::replace(&mut a[k], unsafe { mem::zeroed() }) } // for original quick sort fn sort_orig<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) { if hi <= lo { return } let j = partition(a, lo, hi); if j >= 1 { sort_orig(a, lo, j-1); } sort_orig(a, j+1, hi); } /// original quick sort pub fn quick_sort_orig<T: PartialOrd>(a: &mut [T]) { let n = a.len(); if n > 1 { sort_orig(a, 0, n-1) } } fn sort_3way<T: PartialOrd + Copy>(a: &mut [T], lo: usize, hi: usize) { if hi <= lo { return; } let mut lt = lo; let mut gt = hi; let mut i = lo; // FIXME: this needs Copy let v = a[lo]; while i <= gt { if a[i] < v { a.swap(lt, i); lt += 1; i += 1; } else if a[i] > v { a.swap(i, gt); gt -= 1; } else { i += 1; } } if lt >= 1 { sort_3way(a, lo, lt - 1); } sort_3way(a, gt + 1, hi); } /// 3-way quicksort pub fn quick_sort_3way<T: PartialOrd + Copy>(a: &mut [T]) { let n = a.len(); if n > 1 { sort_3way(a, 0, n-1) } } #[test] fn test_median_of_3() { use rand::{thread_rng, Rng}; let array = thread_rng().gen_iter().take(3).collect::<Vec<f64>>(); let m = median_of_3(&array, 0, 1, 2); assert!(array[0].min(array[1]).min(array[2]) <= array[m]); assert!(array[m] <= array[0].max(array[1]).max(array[2])); }
{ if a[i] >= a[j] { if a[j] >= a[k] { j } else { if a[i] >= a[k] { k } else { i } } } else { if a[j] >= a[k] { if a[i] >= a[k] { i } else { k } } else { j
identifier_body
quicksort.rs
// use rand::{thread_rng, Rng}; use std::mem; use super::insertion_sort; /// quicksort partitioning fn partition<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) -> usize { let mut i = lo; let mut j = hi + 1; loop { loop { i += 1; if a[i] < a[lo] { if i == hi { break } } else { break } } loop { j -= 1; if a[lo] < a[j] { if j == lo { break } } else { break } } if i >= j { break; } a.swap(i, j); } a.swap(lo, j); j } /// find median of 3, index #[allow(dead_code)] #[inline] fn median_of_3<T: PartialOrd>(a: &[T], i: usize, j: usize, k: usize) -> usize { if a[i] >= a[j] { if a[j] >= a[k] { j } else { if a[i] >= a[k] { k } else { i } } } else { if a[j] >= a[k] { if a[i] >= a[k] { i } else { k } } else { j } } } // Cutoff to insertion sort for ≈ 10 items. const CUTOFF: usize = 10; /// quicksort optimised fn sort<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) { // # small subarrays improve: if hi <= lo + CUTOFF - 1 { insertion_sort(&mut a[lo.. hi+1]); return ; } // # awaste of time under big arrays: // let m = median_of_3(a, lo, lo + (hi - lo)/2, hi); // a.swap(lo, m); let j = partition(a, lo, hi); // BUG FIXED: (in original code) if j == 0, j - 1 overflows if j > 1 { sort(a, lo, j-1); } sort(a, j+1, hi); } /// quicksort optimised pub fn quick_sort<T: PartialOrd>(a: &mut [T]) { let n = a.len(); // # time waste // let mut rng = thread_rng(); // rng.shuffle(a); if n > 1 { sort(a, 0, n-1) } } /// quick-select pub fn quick_select<T: PartialOrd>(a: &mut [T], k: usize) -> T { // skip StdRandom.shuffle(a); let mut lo = 0; let mut hi = a.len() - 1; while hi > lo { let j = partition(a, lo, hi); if j < k { lo = j + 1; } else if j > k { hi = j - 1; } else { break; } } // take the value out // FIXME: better to return a &T? mem::replace(&mut a[k], unsafe { mem::zeroed() }) } // for original quick sort fn sort_orig<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) { if hi <= lo { return } let j = partition(a, lo, hi); if j >= 1 { sort_orig(a, lo, j-1); } sort_orig(a, j+1, hi); } /// original quick sort pub fn qu
: PartialOrd>(a: &mut [T]) { let n = a.len(); if n > 1 { sort_orig(a, 0, n-1) } } fn sort_3way<T: PartialOrd + Copy>(a: &mut [T], lo: usize, hi: usize) { if hi <= lo { return; } let mut lt = lo; let mut gt = hi; let mut i = lo; // FIXME: this needs Copy let v = a[lo]; while i <= gt { if a[i] < v { a.swap(lt, i); lt += 1; i += 1; } else if a[i] > v { a.swap(i, gt); gt -= 1; } else { i += 1; } } if lt >= 1 { sort_3way(a, lo, lt - 1); } sort_3way(a, gt + 1, hi); } /// 3-way quicksort pub fn quick_sort_3way<T: PartialOrd + Copy>(a: &mut [T]) { let n = a.len(); if n > 1 { sort_3way(a, 0, n-1) } } #[test] fn test_median_of_3() { use rand::{thread_rng, Rng}; let array = thread_rng().gen_iter().take(3).collect::<Vec<f64>>(); let m = median_of_3(&array, 0, 1, 2); assert!(array[0].min(array[1]).min(array[2]) <= array[m]); assert!(array[m] <= array[0].max(array[1]).max(array[2])); }
ick_sort_orig<T
identifier_name
quicksort.rs
// use rand::{thread_rng, Rng}; use std::mem; use super::insertion_sort; /// quicksort partitioning fn partition<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) -> usize { let mut i = lo; let mut j = hi + 1; loop { loop { i += 1; if a[i] < a[lo] { if i == hi
} else { break } } loop { j -= 1; if a[lo] < a[j] { if j == lo { break } } else { break } } if i >= j { break; } a.swap(i, j); } a.swap(lo, j); j } /// find median of 3, index #[allow(dead_code)] #[inline] fn median_of_3<T: PartialOrd>(a: &[T], i: usize, j: usize, k: usize) -> usize { if a[i] >= a[j] { if a[j] >= a[k] { j } else { if a[i] >= a[k] { k } else { i } } } else { if a[j] >= a[k] { if a[i] >= a[k] { i } else { k } } else { j } } } // Cutoff to insertion sort for ≈ 10 items. const CUTOFF: usize = 10; /// quicksort optimised fn sort<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) { // # small subarrays improve: if hi <= lo + CUTOFF - 1 { insertion_sort(&mut a[lo.. hi+1]); return ; } // # awaste of time under big arrays: // let m = median_of_3(a, lo, lo + (hi - lo)/2, hi); // a.swap(lo, m); let j = partition(a, lo, hi); // BUG FIXED: (in original code) if j == 0, j - 1 overflows if j > 1 { sort(a, lo, j-1); } sort(a, j+1, hi); } /// quicksort optimised pub fn quick_sort<T: PartialOrd>(a: &mut [T]) { let n = a.len(); // # time waste // let mut rng = thread_rng(); // rng.shuffle(a); if n > 1 { sort(a, 0, n-1) } } /// quick-select pub fn quick_select<T: PartialOrd>(a: &mut [T], k: usize) -> T { // skip StdRandom.shuffle(a); let mut lo = 0; let mut hi = a.len() - 1; while hi > lo { let j = partition(a, lo, hi); if j < k { lo = j + 1; } else if j > k { hi = j - 1; } else { break; } } // take the value out // FIXME: better to return a &T? mem::replace(&mut a[k], unsafe { mem::zeroed() }) } // for original quick sort fn sort_orig<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) { if hi <= lo { return } let j = partition(a, lo, hi); if j >= 1 { sort_orig(a, lo, j-1); } sort_orig(a, j+1, hi); } /// original quick sort pub fn quick_sort_orig<T: PartialOrd>(a: &mut [T]) { let n = a.len(); if n > 1 { sort_orig(a, 0, n-1) } } fn sort_3way<T: PartialOrd + Copy>(a: &mut [T], lo: usize, hi: usize) { if hi <= lo { return; } let mut lt = lo; let mut gt = hi; let mut i = lo; // FIXME: this needs Copy let v = a[lo]; while i <= gt { if a[i] < v { a.swap(lt, i); lt += 1; i += 1; } else if a[i] > v { a.swap(i, gt); gt -= 1; } else { i += 1; } } if lt >= 1 { sort_3way(a, lo, lt - 1); } sort_3way(a, gt + 1, hi); } /// 3-way quicksort pub fn quick_sort_3way<T: PartialOrd + Copy>(a: &mut [T]) { let n = a.len(); if n > 1 { sort_3way(a, 0, n-1) } } #[test] fn test_median_of_3() { use rand::{thread_rng, Rng}; let array = thread_rng().gen_iter().take(3).collect::<Vec<f64>>(); let m = median_of_3(&array, 0, 1, 2); assert!(array[0].min(array[1]).min(array[2]) <= array[m]); assert!(array[m] <= array[0].max(array[1]).max(array[2])); }
{ break }
conditional_block
quicksort.rs
// use rand::{thread_rng, Rng}; use std::mem; use super::insertion_sort; /// quicksort partitioning fn partition<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) -> usize { let mut i = lo; let mut j = hi + 1; loop { loop { i += 1; if a[i] < a[lo] { if i == hi { break } } else { break } } loop { j -= 1; if a[lo] < a[j] { if j == lo { break } } else { break } } if i >= j { break; } a.swap(i, j); } a.swap(lo, j); j } /// find median of 3, index #[allow(dead_code)] #[inline] fn median_of_3<T: PartialOrd>(a: &[T], i: usize, j: usize, k: usize) -> usize { if a[i] >= a[j] { if a[j] >= a[k] { j } else { if a[i] >= a[k] { k } else { i } } } else { if a[j] >= a[k] { if a[i] >= a[k] { i } else { k } } else { j } } } // Cutoff to insertion sort for ≈ 10 items. const CUTOFF: usize = 10; /// quicksort optimised fn sort<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) { // # small subarrays improve: if hi <= lo + CUTOFF - 1 { insertion_sort(&mut a[lo.. hi+1]); return ; } // # awaste of time under big arrays: // let m = median_of_3(a, lo, lo + (hi - lo)/2, hi); // a.swap(lo, m); let j = partition(a, lo, hi); // BUG FIXED: (in original code) if j == 0, j - 1 overflows if j > 1 { sort(a, lo, j-1); } sort(a, j+1, hi); } /// quicksort optimised pub fn quick_sort<T: PartialOrd>(a: &mut [T]) { let n = a.len(); // # time waste // let mut rng = thread_rng(); // rng.shuffle(a); if n > 1 { sort(a, 0, n-1) } } /// quick-select pub fn quick_select<T: PartialOrd>(a: &mut [T], k: usize) -> T { // skip StdRandom.shuffle(a); let mut lo = 0; let mut hi = a.len() - 1; while hi > lo { let j = partition(a, lo, hi); if j < k { lo = j + 1; } else if j > k { hi = j - 1; } else { break; } } // take the value out // FIXME: better to return a &T? mem::replace(&mut a[k], unsafe { mem::zeroed() }) } // for original quick sort fn sort_orig<T: PartialOrd>(a: &mut [T], lo: usize, hi: usize) { if hi <= lo { return } let j = partition(a, lo, hi); if j >= 1 { sort_orig(a, lo, j-1); } sort_orig(a, j+1, hi); } /// original quick sort pub fn quick_sort_orig<T: PartialOrd>(a: &mut [T]) { let n = a.len(); if n > 1 { sort_orig(a, 0, n-1) } } fn sort_3way<T: PartialOrd + Copy>(a: &mut [T], lo: usize, hi: usize) {
} let mut lt = lo; let mut gt = hi; let mut i = lo; // FIXME: this needs Copy let v = a[lo]; while i <= gt { if a[i] < v { a.swap(lt, i); lt += 1; i += 1; } else if a[i] > v { a.swap(i, gt); gt -= 1; } else { i += 1; } } if lt >= 1 { sort_3way(a, lo, lt - 1); } sort_3way(a, gt + 1, hi); } /// 3-way quicksort pub fn quick_sort_3way<T: PartialOrd + Copy>(a: &mut [T]) { let n = a.len(); if n > 1 { sort_3way(a, 0, n-1) } } #[test] fn test_median_of_3() { use rand::{thread_rng, Rng}; let array = thread_rng().gen_iter().take(3).collect::<Vec<f64>>(); let m = median_of_3(&array, 0, 1, 2); assert!(array[0].min(array[1]).min(array[2]) <= array[m]); assert!(array[m] <= array[0].max(array[1]).max(array[2])); }
if hi <= lo { return;
random_line_split
webglshader.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLMsgSender, WebGLParameter, WebGLResult, WebGLShaderId}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::webgl_extensions::WebGLExtensions; use dom::webgl_extensions::ext::oesstandardderivatives::OESStandardDerivatives; use dom::webglobject::WebGLObject; use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use std::sync::{ONCE_INIT, Once}; #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)] pub enum ShaderCompilationStatus { NotCompiled, Succeeded, Failed, } #[dom_struct] pub struct WebGLShader { webgl_object: WebGLObject, id: WebGLShaderId, gl_type: u32, source: DomRefCell<Option<DOMString>>, info_log: DomRefCell<Option<String>>, is_deleted: Cell<bool>, attached_counter: Cell<u32>, compilation_status: Cell<ShaderCompilationStatus>, #[ignore_malloc_size_of = "Defined in ipc-channel"] renderer: WebGLMsgSender, } #[cfg(not(target_os = "android"))] const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; #[cfg(target_os = "android")] const SHADER_OUTPUT_FORMAT: Output = Output::Essl; static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { fn new_inherited(renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> WebGLShader { GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: DomRefCell::new(None), info_log: DomRefCell::new(None), is_deleted: Cell::new(false), attached_counter: Cell::new(0), compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } pub fn maybe_new(window: &Window, renderer: WebGLMsgSender, shader_type: u32) -> Option<DomRoot<WebGLShader>> { let (sender, receiver) = webgl_channel().unwrap(); renderer.send(WebGLCommand::CreateShader(shader_type, sender)).unwrap(); let result = receiver.recv().unwrap(); result.map(|shader_id| WebGLShader::new(window, renderer, shader_id, shader_type)) } pub fn new(window: &Window, renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> DomRoot<WebGLShader> { reflect_dom_object(Box::new(WebGLShader::new_inherited(renderer, id, shader_type)), window, WebGLShaderBinding::Wrap) } } impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id } pub fn gl_type(&self) -> u32 { self.gl_type } /// glCompileShader pub fn compile(&self, ext: &WebGLExtensions) { if self.compilation_status.get()!= ShaderCompilationStatus::NotCompiled { debug!("Compiling already compiled shader {}", self.id); } if let Some(ref source) = *self.source.borrow() { let mut params = BuiltInResources::default(); params.FragmentPrecisionHigh = 1; params.OES_standard_derivatives = ext.is_enabled::<OESStandardDerivatives>() as i32; let validator = ShaderValidator::for_webgl(self.gl_type, SHADER_OUTPUT_FORMAT, &params).unwrap(); match validator.compile_and_translate(&[source]) { Ok(translated_source) =>
, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); debug!("Shader {} compilation failed: {}", self.id, error); }, } *self.info_log.borrow_mut() = Some(validator.info_log()); // TODO(emilio): More data (like uniform data) should be collected // here to properly validate uniforms. // // This requires a more complex interface with ANGLE, using C++ // bindings and being extremely cautious about destructing things. } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. /// Currently does not check if shader is attached pub fn delete(&self) { if!self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(WebGLCommand::DeleteShader(self.id)); } } pub fn is_deleted(&self) -> bool { self.is_deleted.get() } pub fn is_attached(&self) -> bool { self.attached_counter.get() > 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set(self.attached_counter.get() + 1); } pub fn decrement_attached_counter(&self) { assert!(self.attached_counter.get() > 0); self.attached_counter.set(self.attached_counter.get() - 1); } /// glGetShaderInfoLog pub fn info_log(&self) -> Option<String> { self.info_log.borrow().clone() } /// glGetParameter pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter> { let (sender, receiver) = webgl_channel().unwrap(); self.renderer.send(WebGLCommand::GetShaderParameter(self.id, param_id, sender)).unwrap(); receiver.recv().unwrap() } /// Get the shader source pub fn source(&self) -> Option<DOMString> { self.source.borrow().clone() } /// glShaderSource pub fn set_source(&self, source: DOMString) { *self.source.borrow_mut() = Some(source); } pub fn successfully_compiled(&self) -> bool { self.compilation_status.get() == ShaderCompilationStatus::Succeeded } } impl Drop for WebGLShader { fn drop(&mut self) { assert!(self.attached_counter.get() == 0); self.delete(); } }
{ debug!("Shader translated: {}", translated_source); // NOTE: At this point we should be pretty sure that the compilation in the paint thread // will succeed. // It could be interesting to retrieve the info log from the paint thread though let msg = WebGLCommand::CompileShader(self.id, translated_source); self.renderer.send(msg).unwrap(); self.compilation_status.set(ShaderCompilationStatus::Succeeded); }
conditional_block
webglshader.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLMsgSender, WebGLParameter, WebGLResult, WebGLShaderId}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::webgl_extensions::WebGLExtensions; use dom::webgl_extensions::ext::oesstandardderivatives::OESStandardDerivatives; use dom::webglobject::WebGLObject; use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use std::sync::{ONCE_INIT, Once}; #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)] pub enum ShaderCompilationStatus { NotCompiled, Succeeded, Failed, } #[dom_struct] pub struct WebGLShader { webgl_object: WebGLObject, id: WebGLShaderId, gl_type: u32, source: DomRefCell<Option<DOMString>>, info_log: DomRefCell<Option<String>>, is_deleted: Cell<bool>, attached_counter: Cell<u32>, compilation_status: Cell<ShaderCompilationStatus>, #[ignore_malloc_size_of = "Defined in ipc-channel"] renderer: WebGLMsgSender, } #[cfg(not(target_os = "android"))] const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; #[cfg(target_os = "android")] const SHADER_OUTPUT_FORMAT: Output = Output::Essl; static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { fn new_inherited(renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> WebGLShader { GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: DomRefCell::new(None), info_log: DomRefCell::new(None), is_deleted: Cell::new(false), attached_counter: Cell::new(0), compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } pub fn maybe_new(window: &Window, renderer: WebGLMsgSender, shader_type: u32) -> Option<DomRoot<WebGLShader>> { let (sender, receiver) = webgl_channel().unwrap(); renderer.send(WebGLCommand::CreateShader(shader_type, sender)).unwrap(); let result = receiver.recv().unwrap(); result.map(|shader_id| WebGLShader::new(window, renderer, shader_id, shader_type)) } pub fn new(window: &Window, renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> DomRoot<WebGLShader> { reflect_dom_object(Box::new(WebGLShader::new_inherited(renderer, id, shader_type)), window, WebGLShaderBinding::Wrap) } } impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id } pub fn gl_type(&self) -> u32 { self.gl_type } /// glCompileShader pub fn compile(&self, ext: &WebGLExtensions) { if self.compilation_status.get()!= ShaderCompilationStatus::NotCompiled { debug!("Compiling already compiled shader {}", self.id); } if let Some(ref source) = *self.source.borrow() { let mut params = BuiltInResources::default(); params.FragmentPrecisionHigh = 1; params.OES_standard_derivatives = ext.is_enabled::<OESStandardDerivatives>() as i32; let validator = ShaderValidator::for_webgl(self.gl_type, SHADER_OUTPUT_FORMAT, &params).unwrap(); match validator.compile_and_translate(&[source]) { Ok(translated_source) => { debug!("Shader translated: {}", translated_source); // NOTE: At this point we should be pretty sure that the compilation in the paint thread // will succeed. // It could be interesting to retrieve the info log from the paint thread though let msg = WebGLCommand::CompileShader(self.id, translated_source); self.renderer.send(msg).unwrap(); self.compilation_status.set(ShaderCompilationStatus::Succeeded); }, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); debug!("Shader {} compilation failed: {}", self.id, error); }, } *self.info_log.borrow_mut() = Some(validator.info_log()); // TODO(emilio): More data (like uniform data) should be collected // here to properly validate uniforms. // // This requires a more complex interface with ANGLE, using C++ // bindings and being extremely cautious about destructing things. } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. /// Currently does not check if shader is attached pub fn delete(&self) { if!self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(WebGLCommand::DeleteShader(self.id)); } } pub fn is_deleted(&self) -> bool { self.is_deleted.get() } pub fn is_attached(&self) -> bool { self.attached_counter.get() > 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set(self.attached_counter.get() + 1); } pub fn decrement_attached_counter(&self) { assert!(self.attached_counter.get() > 0); self.attached_counter.set(self.attached_counter.get() - 1); } /// glGetShaderInfoLog pub fn info_log(&self) -> Option<String> { self.info_log.borrow().clone() } /// glGetParameter pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter> { let (sender, receiver) = webgl_channel().unwrap(); self.renderer.send(WebGLCommand::GetShaderParameter(self.id, param_id, sender)).unwrap(); receiver.recv().unwrap() } /// Get the shader source pub fn source(&self) -> Option<DOMString> { self.source.borrow().clone() } /// glShaderSource pub fn
(&self, source: DOMString) { *self.source.borrow_mut() = Some(source); } pub fn successfully_compiled(&self) -> bool { self.compilation_status.get() == ShaderCompilationStatus::Succeeded } } impl Drop for WebGLShader { fn drop(&mut self) { assert!(self.attached_counter.get() == 0); self.delete(); } }
set_source
identifier_name
webglshader.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLMsgSender, WebGLParameter, WebGLResult, WebGLShaderId}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::webgl_extensions::WebGLExtensions; use dom::webgl_extensions::ext::oesstandardderivatives::OESStandardDerivatives; use dom::webglobject::WebGLObject; use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use std::sync::{ONCE_INIT, Once}; #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)] pub enum ShaderCompilationStatus { NotCompiled, Succeeded, Failed, } #[dom_struct] pub struct WebGLShader { webgl_object: WebGLObject, id: WebGLShaderId, gl_type: u32, source: DomRefCell<Option<DOMString>>, info_log: DomRefCell<Option<String>>, is_deleted: Cell<bool>, attached_counter: Cell<u32>, compilation_status: Cell<ShaderCompilationStatus>, #[ignore_malloc_size_of = "Defined in ipc-channel"] renderer: WebGLMsgSender, } #[cfg(not(target_os = "android"))] const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; #[cfg(target_os = "android")] const SHADER_OUTPUT_FORMAT: Output = Output::Essl; static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { fn new_inherited(renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> WebGLShader { GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: DomRefCell::new(None), info_log: DomRefCell::new(None), is_deleted: Cell::new(false), attached_counter: Cell::new(0), compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } pub fn maybe_new(window: &Window, renderer: WebGLMsgSender, shader_type: u32) -> Option<DomRoot<WebGLShader>> { let (sender, receiver) = webgl_channel().unwrap(); renderer.send(WebGLCommand::CreateShader(shader_type, sender)).unwrap(); let result = receiver.recv().unwrap(); result.map(|shader_id| WebGLShader::new(window, renderer, shader_id, shader_type)) } pub fn new(window: &Window, renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> DomRoot<WebGLShader> { reflect_dom_object(Box::new(WebGLShader::new_inherited(renderer, id, shader_type)), window, WebGLShaderBinding::Wrap) } } impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id } pub fn gl_type(&self) -> u32 { self.gl_type } /// glCompileShader pub fn compile(&self, ext: &WebGLExtensions) { if self.compilation_status.get()!= ShaderCompilationStatus::NotCompiled { debug!("Compiling already compiled shader {}", self.id); } if let Some(ref source) = *self.source.borrow() { let mut params = BuiltInResources::default(); params.FragmentPrecisionHigh = 1; params.OES_standard_derivatives = ext.is_enabled::<OESStandardDerivatives>() as i32; let validator = ShaderValidator::for_webgl(self.gl_type, SHADER_OUTPUT_FORMAT, &params).unwrap(); match validator.compile_and_translate(&[source]) { Ok(translated_source) => { debug!("Shader translated: {}", translated_source); // NOTE: At this point we should be pretty sure that the compilation in the paint thread // will succeed. // It could be interesting to retrieve the info log from the paint thread though let msg = WebGLCommand::CompileShader(self.id, translated_source); self.renderer.send(msg).unwrap(); self.compilation_status.set(ShaderCompilationStatus::Succeeded); }, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); debug!("Shader {} compilation failed: {}", self.id, error); }, } *self.info_log.borrow_mut() = Some(validator.info_log()); // TODO(emilio): More data (like uniform data) should be collected // here to properly validate uniforms. // // This requires a more complex interface with ANGLE, using C++ // bindings and being extremely cautious about destructing things. } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. /// Currently does not check if shader is attached pub fn delete(&self) { if!self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(WebGLCommand::DeleteShader(self.id)); } }
self.attached_counter.get() > 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set(self.attached_counter.get() + 1); } pub fn decrement_attached_counter(&self) { assert!(self.attached_counter.get() > 0); self.attached_counter.set(self.attached_counter.get() - 1); } /// glGetShaderInfoLog pub fn info_log(&self) -> Option<String> { self.info_log.borrow().clone() } /// glGetParameter pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter> { let (sender, receiver) = webgl_channel().unwrap(); self.renderer.send(WebGLCommand::GetShaderParameter(self.id, param_id, sender)).unwrap(); receiver.recv().unwrap() } /// Get the shader source pub fn source(&self) -> Option<DOMString> { self.source.borrow().clone() } /// glShaderSource pub fn set_source(&self, source: DOMString) { *self.source.borrow_mut() = Some(source); } pub fn successfully_compiled(&self) -> bool { self.compilation_status.get() == ShaderCompilationStatus::Succeeded } } impl Drop for WebGLShader { fn drop(&mut self) { assert!(self.attached_counter.get() == 0); self.delete(); } }
pub fn is_deleted(&self) -> bool { self.is_deleted.get() } pub fn is_attached(&self) -> bool {
random_line_split
webglshader.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::webgl::{webgl_channel, WebGLCommand, WebGLMsgSender, WebGLParameter, WebGLResult, WebGLShaderId}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::webgl_extensions::WebGLExtensions; use dom::webgl_extensions::ext::oesstandardderivatives::OESStandardDerivatives; use dom::webglobject::WebGLObject; use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use std::sync::{ONCE_INIT, Once}; #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)] pub enum ShaderCompilationStatus { NotCompiled, Succeeded, Failed, } #[dom_struct] pub struct WebGLShader { webgl_object: WebGLObject, id: WebGLShaderId, gl_type: u32, source: DomRefCell<Option<DOMString>>, info_log: DomRefCell<Option<String>>, is_deleted: Cell<bool>, attached_counter: Cell<u32>, compilation_status: Cell<ShaderCompilationStatus>, #[ignore_malloc_size_of = "Defined in ipc-channel"] renderer: WebGLMsgSender, } #[cfg(not(target_os = "android"))] const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; #[cfg(target_os = "android")] const SHADER_OUTPUT_FORMAT: Output = Output::Essl; static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { fn new_inherited(renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> WebGLShader { GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: DomRefCell::new(None), info_log: DomRefCell::new(None), is_deleted: Cell::new(false), attached_counter: Cell::new(0), compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } pub fn maybe_new(window: &Window, renderer: WebGLMsgSender, shader_type: u32) -> Option<DomRoot<WebGLShader>> { let (sender, receiver) = webgl_channel().unwrap(); renderer.send(WebGLCommand::CreateShader(shader_type, sender)).unwrap(); let result = receiver.recv().unwrap(); result.map(|shader_id| WebGLShader::new(window, renderer, shader_id, shader_type)) } pub fn new(window: &Window, renderer: WebGLMsgSender, id: WebGLShaderId, shader_type: u32) -> DomRoot<WebGLShader> { reflect_dom_object(Box::new(WebGLShader::new_inherited(renderer, id, shader_type)), window, WebGLShaderBinding::Wrap) } } impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id } pub fn gl_type(&self) -> u32 { self.gl_type } /// glCompileShader pub fn compile(&self, ext: &WebGLExtensions) { if self.compilation_status.get()!= ShaderCompilationStatus::NotCompiled { debug!("Compiling already compiled shader {}", self.id); } if let Some(ref source) = *self.source.borrow() { let mut params = BuiltInResources::default(); params.FragmentPrecisionHigh = 1; params.OES_standard_derivatives = ext.is_enabled::<OESStandardDerivatives>() as i32; let validator = ShaderValidator::for_webgl(self.gl_type, SHADER_OUTPUT_FORMAT, &params).unwrap(); match validator.compile_and_translate(&[source]) { Ok(translated_source) => { debug!("Shader translated: {}", translated_source); // NOTE: At this point we should be pretty sure that the compilation in the paint thread // will succeed. // It could be interesting to retrieve the info log from the paint thread though let msg = WebGLCommand::CompileShader(self.id, translated_source); self.renderer.send(msg).unwrap(); self.compilation_status.set(ShaderCompilationStatus::Succeeded); }, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); debug!("Shader {} compilation failed: {}", self.id, error); }, } *self.info_log.borrow_mut() = Some(validator.info_log()); // TODO(emilio): More data (like uniform data) should be collected // here to properly validate uniforms. // // This requires a more complex interface with ANGLE, using C++ // bindings and being extremely cautious about destructing things. } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. /// Currently does not check if shader is attached pub fn delete(&self) { if!self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(WebGLCommand::DeleteShader(self.id)); } } pub fn is_deleted(&self) -> bool { self.is_deleted.get() } pub fn is_attached(&self) -> bool { self.attached_counter.get() > 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set(self.attached_counter.get() + 1); } pub fn decrement_attached_counter(&self) { assert!(self.attached_counter.get() > 0); self.attached_counter.set(self.attached_counter.get() - 1); } /// glGetShaderInfoLog pub fn info_log(&self) -> Option<String> { self.info_log.borrow().clone() } /// glGetParameter pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter>
/// Get the shader source pub fn source(&self) -> Option<DOMString> { self.source.borrow().clone() } /// glShaderSource pub fn set_source(&self, source: DOMString) { *self.source.borrow_mut() = Some(source); } pub fn successfully_compiled(&self) -> bool { self.compilation_status.get() == ShaderCompilationStatus::Succeeded } } impl Drop for WebGLShader { fn drop(&mut self) { assert!(self.attached_counter.get() == 0); self.delete(); } }
{ let (sender, receiver) = webgl_channel().unwrap(); self.renderer.send(WebGLCommand::GetShaderParameter(self.id, param_id, sender)).unwrap(); receiver.recv().unwrap() }
identifier_body
issue-19452.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. // aux-build:issue_19452_aux.rs extern crate issue_19452_aux; enum
{ Madoka { age: u32 } } fn main() { let homura = Homura::Madoka; //~^ ERROR expected value, found struct variant `Homura::Madoka` let homura = issue_19452_aux::Homura::Madoka; //~^ ERROR expected value, found struct variant `issue_19452_aux::Homura::Madoka` }
Homura
identifier_name
issue-19452.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. // aux-build:issue_19452_aux.rs extern crate issue_19452_aux; enum Homura { Madoka { age: u32 } } fn main()
{ let homura = Homura::Madoka; //~^ ERROR expected value, found struct variant `Homura::Madoka` let homura = issue_19452_aux::Homura::Madoka; //~^ ERROR expected value, found struct variant `issue_19452_aux::Homura::Madoka` }
identifier_body
issue-19452.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
// aux-build:issue_19452_aux.rs extern crate issue_19452_aux; enum Homura { Madoka { age: u32 } } fn main() { let homura = Homura::Madoka; //~^ ERROR expected value, found struct variant `Homura::Madoka` let homura = issue_19452_aux::Homura::Madoka; //~^ ERROR expected value, found struct variant `issue_19452_aux::Homura::Madoka` }
// except according to those terms.
random_line_split
sine.rs
#![allow(non_snake_case)] #![allow(trivial_numeric_casts)] // FIXME: rust-lang/rfcs#1020 #[macro_use] extern crate lua; extern crate libc; use std::io; use std::io::prelude::*; pub fn repl(L: &mut lua::State) { let mut stdin = io::stdin(); let mut stdout = io::stdout(); let mut stderr = io::stderr(); let mut line = String::new(); loop { L.settop(0); // clear the stack let _ = write!(&mut stdout, "> "); let _ = stdout.flush(); line.clear(); if let Err(_) = stdin.read_line(&mut line) { break } if line.starts_with("=") { line = format!("return {}", &line[1..]); } match L.loadbuffer(&line, "=stdin") { Ok(_) => (), Err(err) => { let _ = writeln!(&mut stderr, "{:?}", err); continue; } } match L.pcall(0, lua::MULTRET, 0) { Ok(_) => (), Err(_) => { match L.tostring(-1) { Some(msg) => { let _ = writeln!(&mut stderr, "{}", msg); } None => { let _ = writeln!(&mut stderr, "(error object is not a string)"); } } } } if L.gettop() > 0 { L.getglobal("print"); L.insert(1); let nargs = L.gettop()-1; match L.pcall(nargs, 0, 0) { Ok(_) => (), Err(_) =>
} } } } fn main() { let mut L = lua::State::new(); L.openlibs(); L.register("sin", my_sin); L.register("cos", my_cos); L.register("tan", my_tan); repl(&mut L); } lua_extern! { unsafe fn my_sin(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.sin(); L.pushnumber(output); 1 } unsafe fn my_cos(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.cos(); L.pushnumber(output); 1 } } lua_extern_pub! { // this function is marked public unsafe fn my_tan(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.tan(); L.pushnumber(output); 1 } }
{ let _ = writeln!(&mut stderr, "error calling 'print' ({})", L.describe(-1)); continue; }
conditional_block
sine.rs
#![allow(non_snake_case)] #![allow(trivial_numeric_casts)] // FIXME: rust-lang/rfcs#1020 #[macro_use] extern crate lua; extern crate libc; use std::io; use std::io::prelude::*; pub fn repl(L: &mut lua::State)
match L.pcall(0, lua::MULTRET, 0) { Ok(_) => (), Err(_) => { match L.tostring(-1) { Some(msg) => { let _ = writeln!(&mut stderr, "{}", msg); } None => { let _ = writeln!(&mut stderr, "(error object is not a string)"); } } } } if L.gettop() > 0 { L.getglobal("print"); L.insert(1); let nargs = L.gettop()-1; match L.pcall(nargs, 0, 0) { Ok(_) => (), Err(_) => { let _ = writeln!(&mut stderr, "error calling 'print' ({})", L.describe(-1)); continue; } } } } } fn main() { let mut L = lua::State::new(); L.openlibs(); L.register("sin", my_sin); L.register("cos", my_cos); L.register("tan", my_tan); repl(&mut L); } lua_extern! { unsafe fn my_sin(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.sin(); L.pushnumber(output); 1 } unsafe fn my_cos(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.cos(); L.pushnumber(output); 1 } } lua_extern_pub! { // this function is marked public unsafe fn my_tan(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.tan(); L.pushnumber(output); 1 } }
{ let mut stdin = io::stdin(); let mut stdout = io::stdout(); let mut stderr = io::stderr(); let mut line = String::new(); loop { L.settop(0); // clear the stack let _ = write!(&mut stdout, "> "); let _ = stdout.flush(); line.clear(); if let Err(_) = stdin.read_line(&mut line) { break } if line.starts_with("=") { line = format!("return {}", &line[1..]); } match L.loadbuffer(&line, "=stdin") { Ok(_) => (), Err(err) => { let _ = writeln!(&mut stderr, "{:?}", err); continue; } }
identifier_body
sine.rs
#![allow(non_snake_case)] #![allow(trivial_numeric_casts)] // FIXME: rust-lang/rfcs#1020 #[macro_use] extern crate lua; extern crate libc; use std::io; use std::io::prelude::*; pub fn
(L: &mut lua::State) { let mut stdin = io::stdin(); let mut stdout = io::stdout(); let mut stderr = io::stderr(); let mut line = String::new(); loop { L.settop(0); // clear the stack let _ = write!(&mut stdout, "> "); let _ = stdout.flush(); line.clear(); if let Err(_) = stdin.read_line(&mut line) { break } if line.starts_with("=") { line = format!("return {}", &line[1..]); } match L.loadbuffer(&line, "=stdin") { Ok(_) => (), Err(err) => { let _ = writeln!(&mut stderr, "{:?}", err); continue; } } match L.pcall(0, lua::MULTRET, 0) { Ok(_) => (), Err(_) => { match L.tostring(-1) { Some(msg) => { let _ = writeln!(&mut stderr, "{}", msg); } None => { let _ = writeln!(&mut stderr, "(error object is not a string)"); } } } } if L.gettop() > 0 { L.getglobal("print"); L.insert(1); let nargs = L.gettop()-1; match L.pcall(nargs, 0, 0) { Ok(_) => (), Err(_) => { let _ = writeln!(&mut stderr, "error calling 'print' ({})", L.describe(-1)); continue; } } } } } fn main() { let mut L = lua::State::new(); L.openlibs(); L.register("sin", my_sin); L.register("cos", my_cos); L.register("tan", my_tan); repl(&mut L); } lua_extern! { unsafe fn my_sin(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.sin(); L.pushnumber(output); 1 } unsafe fn my_cos(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.cos(); L.pushnumber(output); 1 } } lua_extern_pub! { // this function is marked public unsafe fn my_tan(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.tan(); L.pushnumber(output); 1 } }
repl
identifier_name
sine.rs
#![allow(non_snake_case)] #![allow(trivial_numeric_casts)] // FIXME: rust-lang/rfcs#1020 #[macro_use] extern crate lua; extern crate libc; use std::io; use std::io::prelude::*; pub fn repl(L: &mut lua::State) { let mut stdin = io::stdin(); let mut stdout = io::stdout(); let mut stderr = io::stderr(); let mut line = String::new(); loop { L.settop(0); // clear the stack let _ = write!(&mut stdout, "> "); let _ = stdout.flush(); line.clear(); if let Err(_) = stdin.read_line(&mut line) { break } if line.starts_with("=") { line = format!("return {}", &line[1..]); } match L.loadbuffer(&line, "=stdin") { Ok(_) => (), Err(err) => { let _ = writeln!(&mut stderr, "{:?}", err); continue; } } match L.pcall(0, lua::MULTRET, 0) { Ok(_) => (), Err(_) => { match L.tostring(-1) { Some(msg) => { let _ = writeln!(&mut stderr, "{}", msg); } None => { let _ = writeln!(&mut stderr, "(error object is not a string)"); } }
} if L.gettop() > 0 { L.getglobal("print"); L.insert(1); let nargs = L.gettop()-1; match L.pcall(nargs, 0, 0) { Ok(_) => (), Err(_) => { let _ = writeln!(&mut stderr, "error calling 'print' ({})", L.describe(-1)); continue; } } } } } fn main() { let mut L = lua::State::new(); L.openlibs(); L.register("sin", my_sin); L.register("cos", my_cos); L.register("tan", my_tan); repl(&mut L); } lua_extern! { unsafe fn my_sin(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.sin(); L.pushnumber(output); 1 } unsafe fn my_cos(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.cos(); L.pushnumber(output); 1 } } lua_extern_pub! { // this function is marked public unsafe fn my_tan(L: &mut lua::ExternState) -> i32 { let input = L.checknumber(1); let output = input.tan(); L.pushnumber(output); 1 } }
}
random_line_split
unit-like-struct-drop-run.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. // Make sure the destructor is run for unit-like structs. use std::any::AnyOwnExt; use std::task; struct Foo; impl Drop for Foo { fn drop(&mut self) { fail!("This failure should happen."); } } pub fn main() { let x = task::try(proc() { let _b = Foo; });
}
let s = x.unwrap_err().move::<&'static str>().unwrap(); assert_eq!(s.as_slice(), "This failure should happen.");
random_line_split
unit-like-struct-drop-run.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. // Make sure the destructor is run for unit-like structs. use std::any::AnyOwnExt; use std::task; struct
; impl Drop for Foo { fn drop(&mut self) { fail!("This failure should happen."); } } pub fn main() { let x = task::try(proc() { let _b = Foo; }); let s = x.unwrap_err().move::<&'static str>().unwrap(); assert_eq!(s.as_slice(), "This failure should happen."); }
Foo
identifier_name
unit-like-struct-drop-run.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. // Make sure the destructor is run for unit-like structs. use std::any::AnyOwnExt; use std::task; struct Foo; impl Drop for Foo { fn drop(&mut self) { fail!("This failure should happen."); } } pub fn main()
{ let x = task::try(proc() { let _b = Foo; }); let s = x.unwrap_err().move::<&'static str>().unwrap(); assert_eq!(s.as_slice(), "This failure should happen."); }
identifier_body
happy_numbers.rs
// Implements http://rosettacode.org/wiki/Happy_numbers use std::collections::treemap::TreeSet; #[cfg(not(test))] use std::iter::count; fn digits(mut n: uint) -> Vec<uint> { let mut ds = vec![]; if n == 0 { return vec![0]; } while n > 0 { ds.push(n % 10); n /= 10; } ds.reverse(); ds } fn is_happy(mut x: uint) -> bool { let mut past = TreeSet::new(); while x!= 1 { // Take the sum of the squares of the digits of x x = digits(x).iter().fold(0, |a, &b| a + b * b); // The number is not happy if there is an endless loop if past.contains(&x) { return false } past.insert(x); } true } #[cfg(not(test))] fn main() { // Print the first 8 happy numbers let v: Vec<uint> = count(1u, 1) .filter(|x| is_happy(*x)) .take(8) .collect(); println!("{}", v) } #[test] fn test_digits()
#[test] fn test_is_happy() { let happys = [1u, 7, 10, 13, 19, 23, 28, 31, 1607, 1663]; let unhappys = [0u, 2, 3, 4, 5, 6, 8, 9, 29, 1662]; assert!(happys.iter().all(|&n| is_happy(n))); assert!(unhappys.iter().all(|&n|!is_happy(n))); }
{ assert_eq!(digits(0), vec![0]); assert_eq!(digits(1), vec![1]); assert_eq!(digits(2), vec![2]); assert_eq!(digits(10), vec![1, 0]); assert_eq!(digits(11), vec![1, 1]); assert_eq!(digits(101), vec![1, 0, 1]); assert_eq!(digits(1000), vec![1, 0, 0, 0]); }
identifier_body
happy_numbers.rs
// Implements http://rosettacode.org/wiki/Happy_numbers use std::collections::treemap::TreeSet; #[cfg(not(test))] use std::iter::count; fn digits(mut n: uint) -> Vec<uint> { let mut ds = vec![]; if n == 0 { return vec![0]; } while n > 0 { ds.push(n % 10); n /= 10; } ds.reverse(); ds } fn is_happy(mut x: uint) -> bool { let mut past = TreeSet::new(); while x!= 1 { // Take the sum of the squares of the digits of x x = digits(x).iter().fold(0, |a, &b| a + b * b); // The number is not happy if there is an endless loop if past.contains(&x) { return false } past.insert(x); } true } #[cfg(not(test))] fn main() { // Print the first 8 happy numbers let v: Vec<uint> = count(1u, 1) .filter(|x| is_happy(*x)) .take(8) .collect(); println!("{}", v) } #[test] fn test_digits() { assert_eq!(digits(0), vec![0]); assert_eq!(digits(1), vec![1]); assert_eq!(digits(2), vec![2]); assert_eq!(digits(10), vec![1, 0]); assert_eq!(digits(11), vec![1, 1]); assert_eq!(digits(101), vec![1, 0, 1]); assert_eq!(digits(1000), vec![1, 0, 0, 0]); } #[test] fn
() { let happys = [1u, 7, 10, 13, 19, 23, 28, 31, 1607, 1663]; let unhappys = [0u, 2, 3, 4, 5, 6, 8, 9, 29, 1662]; assert!(happys.iter().all(|&n| is_happy(n))); assert!(unhappys.iter().all(|&n|!is_happy(n))); }
test_is_happy
identifier_name
happy_numbers.rs
// Implements http://rosettacode.org/wiki/Happy_numbers use std::collections::treemap::TreeSet; #[cfg(not(test))] use std::iter::count; fn digits(mut n: uint) -> Vec<uint> { let mut ds = vec![]; if n == 0
while n > 0 { ds.push(n % 10); n /= 10; } ds.reverse(); ds } fn is_happy(mut x: uint) -> bool { let mut past = TreeSet::new(); while x!= 1 { // Take the sum of the squares of the digits of x x = digits(x).iter().fold(0, |a, &b| a + b * b); // The number is not happy if there is an endless loop if past.contains(&x) { return false } past.insert(x); } true } #[cfg(not(test))] fn main() { // Print the first 8 happy numbers let v: Vec<uint> = count(1u, 1) .filter(|x| is_happy(*x)) .take(8) .collect(); println!("{}", v) } #[test] fn test_digits() { assert_eq!(digits(0), vec![0]); assert_eq!(digits(1), vec![1]); assert_eq!(digits(2), vec![2]); assert_eq!(digits(10), vec![1, 0]); assert_eq!(digits(11), vec![1, 1]); assert_eq!(digits(101), vec![1, 0, 1]); assert_eq!(digits(1000), vec![1, 0, 0, 0]); } #[test] fn test_is_happy() { let happys = [1u, 7, 10, 13, 19, 23, 28, 31, 1607, 1663]; let unhappys = [0u, 2, 3, 4, 5, 6, 8, 9, 29, 1662]; assert!(happys.iter().all(|&n| is_happy(n))); assert!(unhappys.iter().all(|&n|!is_happy(n))); }
{ return vec![0]; }
conditional_block
happy_numbers.rs
// Implements http://rosettacode.org/wiki/Happy_numbers use std::collections::treemap::TreeSet; #[cfg(not(test))] use std::iter::count; fn digits(mut n: uint) -> Vec<uint> { let mut ds = vec![]; if n == 0 { return vec![0]; } while n > 0 { ds.push(n % 10); n /= 10; } ds.reverse(); ds } fn is_happy(mut x: uint) -> bool { let mut past = TreeSet::new(); while x!= 1 { // Take the sum of the squares of the digits of x x = digits(x).iter().fold(0, |a, &b| a + b * b);
// The number is not happy if there is an endless loop if past.contains(&x) { return false } past.insert(x); } true } #[cfg(not(test))] fn main() { // Print the first 8 happy numbers let v: Vec<uint> = count(1u, 1) .filter(|x| is_happy(*x)) .take(8) .collect(); println!("{}", v) } #[test] fn test_digits() { assert_eq!(digits(0), vec![0]); assert_eq!(digits(1), vec![1]); assert_eq!(digits(2), vec![2]); assert_eq!(digits(10), vec![1, 0]); assert_eq!(digits(11), vec![1, 1]); assert_eq!(digits(101), vec![1, 0, 1]); assert_eq!(digits(1000), vec![1, 0, 0, 0]); } #[test] fn test_is_happy() { let happys = [1u, 7, 10, 13, 19, 23, 28, 31, 1607, 1663]; let unhappys = [0u, 2, 3, 4, 5, 6, 8, 9, 29, 1662]; assert!(happys.iter().all(|&n| is_happy(n))); assert!(unhappys.iter().all(|&n|!is_happy(n))); }
random_line_split
astconv_util.rs
// Copyright 2012-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. /*! * This module contains a simple utility routine * used by both `typeck` and `const_eval`. * Almost certainly this could (and should) be refactored out of existence. */ use middle::def; use middle::ty::{self, Ty}; use syntax::ast; use util::ppaux::Repr; pub const NO_REGIONS: uint = 1; pub const NO_TPS: uint = 2; pub fn check_path_args(tcx: &ty::ctxt, segments: &[ast::PathSegment], flags: uint) { for segment in segments { if (flags & NO_TPS)!= 0 { for typ in segment.parameters.types() { span_err!(tcx.sess, typ.span, E0109, "type parameters are not allowed on this type"); break; } } if (flags & NO_REGIONS)!= 0 { for lifetime in segment.parameters.lifetimes() { span_err!(tcx.sess, lifetime.span, E0110, "lifetime parameters are not allowed on this type"); break; } } } } pub fn prim_ty_to_ty<'tcx>(tcx: &ty::ctxt<'tcx>, segments: &[ast::PathSegment], nty: ast::PrimTy) -> Ty<'tcx> { check_path_args(tcx, segments, NO_TPS | NO_REGIONS); match nty { ast::TyBool => tcx.types.bool, ast::TyChar => tcx.types.char, ast::TyInt(it) => ty::mk_mach_int(tcx, it), ast::TyUint(uit) => ty::mk_mach_uint(tcx, uit), ast::TyFloat(ft) => ty::mk_mach_float(tcx, ft), ast::TyStr => ty::mk_str(tcx) } } pub fn ast_ty_to_prim_ty<'tcx>(tcx: &ty::ctxt<'tcx>, ast_ty: &ast::Ty) -> Option<Ty<'tcx>>
{ if let ast::TyPath(None, ref path) = ast_ty.node { let def = match tcx.def_map.borrow().get(&ast_ty.id) { None => { tcx.sess.span_bug(ast_ty.span, &format!("unbound path {}", path.repr(tcx))) } Some(d) => d.full_def() }; if let def::DefPrimTy(nty) = def { Some(prim_ty_to_ty(tcx, &path.segments, nty)) } else { None } } else { None } }
identifier_body
astconv_util.rs
// Copyright 2012-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. /*! * This module contains a simple utility routine * used by both `typeck` and `const_eval`. * Almost certainly this could (and should) be refactored out of existence. */ use middle::def; use middle::ty::{self, Ty}; use syntax::ast; use util::ppaux::Repr; pub const NO_REGIONS: uint = 1; pub const NO_TPS: uint = 2; pub fn check_path_args(tcx: &ty::ctxt, segments: &[ast::PathSegment], flags: uint) { for segment in segments { if (flags & NO_TPS)!= 0 { for typ in segment.parameters.types() { span_err!(tcx.sess, typ.span, E0109, "type parameters are not allowed on this type"); break; } } if (flags & NO_REGIONS)!= 0 { for lifetime in segment.parameters.lifetimes() { span_err!(tcx.sess, lifetime.span, E0110, "lifetime parameters are not allowed on this type"); break; } } } } pub fn prim_ty_to_ty<'tcx>(tcx: &ty::ctxt<'tcx>, segments: &[ast::PathSegment], nty: ast::PrimTy) -> Ty<'tcx> { check_path_args(tcx, segments, NO_TPS | NO_REGIONS); match nty { ast::TyBool => tcx.types.bool, ast::TyChar => tcx.types.char, ast::TyInt(it) => ty::mk_mach_int(tcx, it), ast::TyUint(uit) => ty::mk_mach_uint(tcx, uit), ast::TyFloat(ft) => ty::mk_mach_float(tcx, ft), ast::TyStr => ty::mk_str(tcx) } } pub fn ast_ty_to_prim_ty<'tcx>(tcx: &ty::ctxt<'tcx>, ast_ty: &ast::Ty) -> Option<Ty<'tcx>> { if let ast::TyPath(None, ref path) = ast_ty.node { let def = match tcx.def_map.borrow().get(&ast_ty.id) { None =>
Some(d) => d.full_def() }; if let def::DefPrimTy(nty) = def { Some(prim_ty_to_ty(tcx, &path.segments, nty)) } else { None } } else { None } }
{ tcx.sess.span_bug(ast_ty.span, &format!("unbound path {}", path.repr(tcx))) }
conditional_block
astconv_util.rs
// Copyright 2012-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. /*! * This module contains a simple utility routine * used by both `typeck` and `const_eval`. * Almost certainly this could (and should) be refactored out of existence. */ use middle::def; use middle::ty::{self, Ty}; use syntax::ast; use util::ppaux::Repr; pub const NO_REGIONS: uint = 1; pub const NO_TPS: uint = 2; pub fn check_path_args(tcx: &ty::ctxt, segments: &[ast::PathSegment], flags: uint) { for segment in segments { if (flags & NO_TPS)!= 0 { for typ in segment.parameters.types() { span_err!(tcx.sess, typ.span, E0109, "type parameters are not allowed on this type"); break; } } if (flags & NO_REGIONS)!= 0 { for lifetime in segment.parameters.lifetimes() { span_err!(tcx.sess, lifetime.span, E0110, "lifetime parameters are not allowed on this type"); break; } } } } pub fn
<'tcx>(tcx: &ty::ctxt<'tcx>, segments: &[ast::PathSegment], nty: ast::PrimTy) -> Ty<'tcx> { check_path_args(tcx, segments, NO_TPS | NO_REGIONS); match nty { ast::TyBool => tcx.types.bool, ast::TyChar => tcx.types.char, ast::TyInt(it) => ty::mk_mach_int(tcx, it), ast::TyUint(uit) => ty::mk_mach_uint(tcx, uit), ast::TyFloat(ft) => ty::mk_mach_float(tcx, ft), ast::TyStr => ty::mk_str(tcx) } } pub fn ast_ty_to_prim_ty<'tcx>(tcx: &ty::ctxt<'tcx>, ast_ty: &ast::Ty) -> Option<Ty<'tcx>> { if let ast::TyPath(None, ref path) = ast_ty.node { let def = match tcx.def_map.borrow().get(&ast_ty.id) { None => { tcx.sess.span_bug(ast_ty.span, &format!("unbound path {}", path.repr(tcx))) } Some(d) => d.full_def() }; if let def::DefPrimTy(nty) = def { Some(prim_ty_to_ty(tcx, &path.segments, nty)) } else { None } } else { None } }
prim_ty_to_ty
identifier_name
issue-17718.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. // aux-build:issue-17718.rs #![feature(core)] extern crate issue_17718 as other; use std::sync::atomic::{AtomicUsize, Ordering}; const C1: usize = 1; const C2: AtomicUsize = AtomicUsize::new(0); const C3: fn() = foo; const C4: usize = C1 * C1 + C1 / C1; const C5: &'static usize = &C4; const C6: usize = { const C: usize = 3; C }; static S1: usize = 3; static S2: AtomicUsize = AtomicUsize::new(0); mod test { static A: usize = 4; static B: &'static usize = &A; static C: &'static usize = &(A); } fn foo() {} fn
() { assert_eq!(C1, 1); assert_eq!(C3(), ()); assert_eq!(C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(C4, 2); assert_eq!(*C5, 2); assert_eq!(C6, 3); assert_eq!(S1, 3); assert_eq!(S2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(S2.fetch_add(1, Ordering::SeqCst), 1); match 1 { C1 => {} _ => unreachable!(), } let _a = C1; let _a = C2; let _a = C3; let _a = C4; let _a = C5; let _a = C6; let _a = S1; assert_eq!(other::C1, 1); assert_eq!(other::C3(), ()); assert_eq!(other::C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::C4, 2); assert_eq!(*other::C5, 2); assert_eq!(other::S1, 3); assert_eq!(other::S2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::S2.fetch_add(1, Ordering::SeqCst), 1); let _a = other::C1; let _a = other::C2; let _a = other::C3; let _a = other::C4; let _a = other::C5; match 1 { other::C1 => {} _ => unreachable!(), } }
main
identifier_name
issue-17718.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. // aux-build:issue-17718.rs #![feature(core)] extern crate issue_17718 as other; use std::sync::atomic::{AtomicUsize, Ordering}; const C1: usize = 1; const C2: AtomicUsize = AtomicUsize::new(0); const C3: fn() = foo; const C4: usize = C1 * C1 + C1 / C1; const C5: &'static usize = &C4; const C6: usize = { const C: usize = 3; C }; static S1: usize = 3; static S2: AtomicUsize = AtomicUsize::new(0); mod test { static A: usize = 4; static B: &'static usize = &A; static C: &'static usize = &(A); } fn foo()
fn main() { assert_eq!(C1, 1); assert_eq!(C3(), ()); assert_eq!(C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(C4, 2); assert_eq!(*C5, 2); assert_eq!(C6, 3); assert_eq!(S1, 3); assert_eq!(S2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(S2.fetch_add(1, Ordering::SeqCst), 1); match 1 { C1 => {} _ => unreachable!(), } let _a = C1; let _a = C2; let _a = C3; let _a = C4; let _a = C5; let _a = C6; let _a = S1; assert_eq!(other::C1, 1); assert_eq!(other::C3(), ()); assert_eq!(other::C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::C4, 2); assert_eq!(*other::C5, 2); assert_eq!(other::S1, 3); assert_eq!(other::S2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::S2.fetch_add(1, Ordering::SeqCst), 1); let _a = other::C1; let _a = other::C2; let _a = other::C3; let _a = other::C4; let _a = other::C5; match 1 { other::C1 => {} _ => unreachable!(), } }
{}
identifier_body
issue-17718.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. // aux-build:issue-17718.rs #![feature(core)] extern crate issue_17718 as other; use std::sync::atomic::{AtomicUsize, Ordering}; const C1: usize = 1; const C2: AtomicUsize = AtomicUsize::new(0); const C3: fn() = foo; const C4: usize = C1 * C1 + C1 / C1; const C5: &'static usize = &C4; const C6: usize = { const C: usize = 3; C }; static S1: usize = 3; static S2: AtomicUsize = AtomicUsize::new(0); mod test { static A: usize = 4; static B: &'static usize = &A; static C: &'static usize = &(A); } fn foo() {} fn main() { assert_eq!(C1, 1); assert_eq!(C3(), ()); assert_eq!(C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(C4, 2); assert_eq!(*C5, 2); assert_eq!(C6, 3); assert_eq!(S1, 3); assert_eq!(S2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(S2.fetch_add(1, Ordering::SeqCst), 1); match 1 { C1 => {} _ => unreachable!(), } let _a = C1; let _a = C2; let _a = C3; let _a = C4; let _a = C5; let _a = C6; let _a = S1; assert_eq!(other::C1, 1); assert_eq!(other::C3(), ()); assert_eq!(other::C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::C2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::C4, 2); assert_eq!(*other::C5, 2); assert_eq!(other::S1, 3); assert_eq!(other::S2.fetch_add(1, Ordering::SeqCst), 0); assert_eq!(other::S2.fetch_add(1, Ordering::SeqCst), 1); let _a = other::C1; let _a = other::C2;
let _a = other::C3; let _a = other::C4; let _a = other::C5; match 1 { other::C1 => {} _ => unreachable!(), } }
random_line_split
overload-index-operator.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. // Test overloading of the `[]` operator. In particular test that it // takes its argument *by reference*. use std::ops::Index; struct AssociationList<K,V> { pairs: ~[AssociationPair<K,V>] } struct AssociationPair<K,V> { key: K, value: V } impl<K,V> AssociationList<K,V> { fn push(&mut self, key: K, value: V) { self.pairs.push(AssociationPair {key: key, value: value}); } } impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> { fn index(&self, index: &K) -> V
} pub fn main() { let foo = ~"foo"; let bar = ~"bar"; let mut list = AssociationList {pairs: ~[]}; list.push(copy foo, 22); list.push(copy bar, 44); assert!(list[foo] == 22) assert!(list[bar] == 44) assert!(list[foo] == 22) assert!(list[bar] == 44) }
{ for self.pairs.iter().advance |pair| { if pair.key == *index { return copy pair.value; } } fail!("No value found for key: %?", index); }
identifier_body
overload-index-operator.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. // Test overloading of the `[]` operator. In particular test that it // takes its argument *by reference*. use std::ops::Index; struct AssociationList<K,V> { pairs: ~[AssociationPair<K,V>] } struct AssociationPair<K,V> { key: K, value: V } impl<K,V> AssociationList<K,V> { fn push(&mut self, key: K, value: V) { self.pairs.push(AssociationPair {key: key, value: value}); } } impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> { fn index(&self, index: &K) -> V { for self.pairs.iter().advance |pair| { if pair.key == *index
} fail!("No value found for key: %?", index); } } pub fn main() { let foo = ~"foo"; let bar = ~"bar"; let mut list = AssociationList {pairs: ~[]}; list.push(copy foo, 22); list.push(copy bar, 44); assert!(list[foo] == 22) assert!(list[bar] == 44) assert!(list[foo] == 22) assert!(list[bar] == 44) }
{ return copy pair.value; }
conditional_block
overload-index-operator.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. // Test overloading of the `[]` operator. In particular test that it // takes its argument *by reference*. use std::ops::Index; struct AssociationList<K,V> { pairs: ~[AssociationPair<K,V>] } struct AssociationPair<K,V> { key: K, value: V } impl<K,V> AssociationList<K,V> { fn
(&mut self, key: K, value: V) { self.pairs.push(AssociationPair {key: key, value: value}); } } impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> { fn index(&self, index: &K) -> V { for self.pairs.iter().advance |pair| { if pair.key == *index { return copy pair.value; } } fail!("No value found for key: %?", index); } } pub fn main() { let foo = ~"foo"; let bar = ~"bar"; let mut list = AssociationList {pairs: ~[]}; list.push(copy foo, 22); list.push(copy bar, 44); assert!(list[foo] == 22) assert!(list[bar] == 44) assert!(list[foo] == 22) assert!(list[bar] == 44) }
push
identifier_name
overload-index-operator.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. // Test overloading of the `[]` operator. In particular test that it // takes its argument *by reference*. use std::ops::Index; struct AssociationList<K,V> { pairs: ~[AssociationPair<K,V>] } struct AssociationPair<K,V> { key: K, value: V } impl<K,V> AssociationList<K,V> { fn push(&mut self, key: K, value: V) { self.pairs.push(AssociationPair {key: key, value: value});
} impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> { fn index(&self, index: &K) -> V { for self.pairs.iter().advance |pair| { if pair.key == *index { return copy pair.value; } } fail!("No value found for key: %?", index); } } pub fn main() { let foo = ~"foo"; let bar = ~"bar"; let mut list = AssociationList {pairs: ~[]}; list.push(copy foo, 22); list.push(copy bar, 44); assert!(list[foo] == 22) assert!(list[bar] == 44) assert!(list[foo] == 22) assert!(list[bar] == 44) }
}
random_line_split
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataDerived, ElementCast}; use dom::bindings::codegen::InheritTypes::NodeCast; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Fallible, ErrorResult}; use dom::bindings::error::Error::IndexSize; use dom::bindings::js::{JSRef, LayoutJS, Temporary}; use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::node::{Node, NodeHelpers, NodeTypeId}; use util::str::DOMString; use std::borrow::ToOwned; use std::cell::Ref; use std::cmp; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterDataDerived for EventTarget { fn is_characterdata(&self) -> bool { match *self.type_id() { EventTargetTypeId::Node(NodeTypeId::CharacterData(_)) => true, _ => false } } } impl CharacterData { pub fn new_inherited(id: CharacterDataTypeId, data: DOMString, document: JSRef<Document>) -> CharacterData { CharacterData { node: Node::new_inherited(NodeTypeId::CharacterData(id), document), data: DOMRefCell::new(data), } } } impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(self) -> DOMString { // FIXME(https://github.com/rust-lang/rust/issues/23338) let data = self.data.borrow(); data.clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(self, data: DOMString) { *self.data.borrow_mut() = data; } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(self) -> u32 { // FIXME(https://github.com/rust-lang/rust/issues/23338) let data = self.data.borrow(); data.chars().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let len = data.chars().count(); if offset as usize > len { // Step 2. return Err(IndexSize); } // Step 3. let end = cmp::min((offset + count) as usize, len); // Step 4. Ok(data.slice_chars(offset as usize, end).to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddata fn AppendData(self, data: DOMString) { self.data.borrow_mut().push_str(&data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdata fn InsertData(self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedata fn DeleteData(self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, "".to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let length = self.data.borrow().chars().count() as u32; if offset > length { return Err(IndexSize); } let count = if offset + count > length { length - offset } else { count }; let mut data = self.data.borrow().slice_chars(0, offset as usize).to_owned(); data.push_str(&arg); data.push_str(&self.data.borrow().slice_chars((offset + count) as usize, length as usize)); *self.data.borrow_mut() = data; // FIXME: Once we have `Range`, we should implement step7 to step11 Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(self) { let node: JSRef<Node> = NodeCast::from_ref(self); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(self) -> Option<Temporary<Element>> { NodeCast::from_ref(self).preceding_siblings() .filter_map(ElementCast::to_temporary).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(self) -> Option<Temporary<Element>> { NodeCast::from_ref(self).following_siblings() .filter_map(ElementCast::to_temporary).next() } } /// The different types of CharacterData. #[derive(Copy, Clone, PartialEq, Debug)] #[jstraceable] pub enum
{ Comment, Text, ProcessingInstruction, } pub trait CharacterDataHelpers<'a> { fn data(self) -> Ref<'a, DOMString>; } impl<'a> CharacterDataHelpers<'a> for JSRef<'a, CharacterData> { #[inline] fn data(self) -> Ref<'a, DOMString> { self.extended_deref().data.borrow() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout<'a>(&'a self) -> &'a str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout<'a>(&'a self) -> &'a str { &(*self.unsafe_get()).data.borrow_for_layout() } }
CharacterDataTypeId
identifier_name
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataDerived, ElementCast}; use dom::bindings::codegen::InheritTypes::NodeCast; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Fallible, ErrorResult}; use dom::bindings::error::Error::IndexSize; use dom::bindings::js::{JSRef, LayoutJS, Temporary}; use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::node::{Node, NodeHelpers, NodeTypeId}; use util::str::DOMString; use std::borrow::ToOwned; use std::cell::Ref; use std::cmp; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterDataDerived for EventTarget { fn is_characterdata(&self) -> bool { match *self.type_id() { EventTargetTypeId::Node(NodeTypeId::CharacterData(_)) => true, _ => false } } } impl CharacterData { pub fn new_inherited(id: CharacterDataTypeId, data: DOMString, document: JSRef<Document>) -> CharacterData { CharacterData { node: Node::new_inherited(NodeTypeId::CharacterData(id), document), data: DOMRefCell::new(data), } } } impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(self) -> DOMString { // FIXME(https://github.com/rust-lang/rust/issues/23338) let data = self.data.borrow(); data.clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(self, data: DOMString) { *self.data.borrow_mut() = data; } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(self) -> u32 { // FIXME(https://github.com/rust-lang/rust/issues/23338) let data = self.data.borrow(); data.chars().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let len = data.chars().count(); if offset as usize > len { // Step 2. return Err(IndexSize); } // Step 3. let end = cmp::min((offset + count) as usize, len); // Step 4. Ok(data.slice_chars(offset as usize, end).to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddata fn AppendData(self, data: DOMString) { self.data.borrow_mut().push_str(&data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdata fn InsertData(self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedata fn DeleteData(self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, "".to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(self, offset: u32, count: u32, arg: DOMString) -> ErrorResult
// https://dom.spec.whatwg.org/#dom-childnode-before fn Before(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(self) { let node: JSRef<Node> = NodeCast::from_ref(self); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(self) -> Option<Temporary<Element>> { NodeCast::from_ref(self).preceding_siblings() .filter_map(ElementCast::to_temporary).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(self) -> Option<Temporary<Element>> { NodeCast::from_ref(self).following_siblings() .filter_map(ElementCast::to_temporary).next() } } /// The different types of CharacterData. #[derive(Copy, Clone, PartialEq, Debug)] #[jstraceable] pub enum CharacterDataTypeId { Comment, Text, ProcessingInstruction, } pub trait CharacterDataHelpers<'a> { fn data(self) -> Ref<'a, DOMString>; } impl<'a> CharacterDataHelpers<'a> for JSRef<'a, CharacterData> { #[inline] fn data(self) -> Ref<'a, DOMString> { self.extended_deref().data.borrow() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout<'a>(&'a self) -> &'a str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout<'a>(&'a self) -> &'a str { &(*self.unsafe_get()).data.borrow_for_layout() } }
{ let length = self.data.borrow().chars().count() as u32; if offset > length { return Err(IndexSize); } let count = if offset + count > length { length - offset } else { count }; let mut data = self.data.borrow().slice_chars(0, offset as usize).to_owned(); data.push_str(&arg); data.push_str(&self.data.borrow().slice_chars((offset + count) as usize, length as usize)); *self.data.borrow_mut() = data; // FIXME: Once we have `Range`, we should implement step7 to step11 Ok(()) }
identifier_body
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataDerived, ElementCast}; use dom::bindings::codegen::InheritTypes::NodeCast; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Fallible, ErrorResult}; use dom::bindings::error::Error::IndexSize; use dom::bindings::js::{JSRef, LayoutJS, Temporary}; use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::node::{Node, NodeHelpers, NodeTypeId}; use util::str::DOMString; use std::borrow::ToOwned; use std::cell::Ref; use std::cmp; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterDataDerived for EventTarget { fn is_characterdata(&self) -> bool { match *self.type_id() { EventTargetTypeId::Node(NodeTypeId::CharacterData(_)) => true, _ => false } } } impl CharacterData { pub fn new_inherited(id: CharacterDataTypeId, data: DOMString, document: JSRef<Document>) -> CharacterData { CharacterData { node: Node::new_inherited(NodeTypeId::CharacterData(id), document), data: DOMRefCell::new(data), } } } impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(self) -> DOMString { // FIXME(https://github.com/rust-lang/rust/issues/23338) let data = self.data.borrow(); data.clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(self, data: DOMString) { *self.data.borrow_mut() = data; } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(self) -> u32 { // FIXME(https://github.com/rust-lang/rust/issues/23338) let data = self.data.borrow(); data.chars().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let len = data.chars().count(); if offset as usize > len { // Step 2. return Err(IndexSize); } // Step 3. let end = cmp::min((offset + count) as usize, len); // Step 4. Ok(data.slice_chars(offset as usize, end).to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddata fn AppendData(self, data: DOMString) { self.data.borrow_mut().push_str(&data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdata fn InsertData(self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedata fn DeleteData(self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, "".to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let length = self.data.borrow().chars().count() as u32; if offset > length { return Err(IndexSize); } let count = if offset + count > length { length - offset } else
; let mut data = self.data.borrow().slice_chars(0, offset as usize).to_owned(); data.push_str(&arg); data.push_str(&self.data.borrow().slice_chars((offset + count) as usize, length as usize)); *self.data.borrow_mut() = data; // FIXME: Once we have `Range`, we should implement step7 to step11 Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(self) { let node: JSRef<Node> = NodeCast::from_ref(self); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(self) -> Option<Temporary<Element>> { NodeCast::from_ref(self).preceding_siblings() .filter_map(ElementCast::to_temporary).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(self) -> Option<Temporary<Element>> { NodeCast::from_ref(self).following_siblings() .filter_map(ElementCast::to_temporary).next() } } /// The different types of CharacterData. #[derive(Copy, Clone, PartialEq, Debug)] #[jstraceable] pub enum CharacterDataTypeId { Comment, Text, ProcessingInstruction, } pub trait CharacterDataHelpers<'a> { fn data(self) -> Ref<'a, DOMString>; } impl<'a> CharacterDataHelpers<'a> for JSRef<'a, CharacterData> { #[inline] fn data(self) -> Ref<'a, DOMString> { self.extended_deref().data.borrow() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout<'a>(&'a self) -> &'a str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout<'a>(&'a self) -> &'a str { &(*self.unsafe_get()).data.borrow_for_layout() } }
{ count }
conditional_block
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataDerived, ElementCast}; use dom::bindings::codegen::InheritTypes::NodeCast; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Fallible, ErrorResult}; use dom::bindings::error::Error::IndexSize; use dom::bindings::js::{JSRef, LayoutJS, Temporary}; use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::node::{Node, NodeHelpers, NodeTypeId}; use util::str::DOMString; use std::borrow::ToOwned; use std::cell::Ref; use std::cmp; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterDataDerived for EventTarget { fn is_characterdata(&self) -> bool { match *self.type_id() { EventTargetTypeId::Node(NodeTypeId::CharacterData(_)) => true, _ => false } } }
pub fn new_inherited(id: CharacterDataTypeId, data: DOMString, document: JSRef<Document>) -> CharacterData { CharacterData { node: Node::new_inherited(NodeTypeId::CharacterData(id), document), data: DOMRefCell::new(data), } } } impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(self) -> DOMString { // FIXME(https://github.com/rust-lang/rust/issues/23338) let data = self.data.borrow(); data.clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(self, data: DOMString) { *self.data.borrow_mut() = data; } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(self) -> u32 { // FIXME(https://github.com/rust-lang/rust/issues/23338) let data = self.data.borrow(); data.chars().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let len = data.chars().count(); if offset as usize > len { // Step 2. return Err(IndexSize); } // Step 3. let end = cmp::min((offset + count) as usize, len); // Step 4. Ok(data.slice_chars(offset as usize, end).to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddata fn AppendData(self, data: DOMString) { self.data.borrow_mut().push_str(&data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdata fn InsertData(self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedata fn DeleteData(self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, "".to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let length = self.data.borrow().chars().count() as u32; if offset > length { return Err(IndexSize); } let count = if offset + count > length { length - offset } else { count }; let mut data = self.data.borrow().slice_chars(0, offset as usize).to_owned(); data.push_str(&arg); data.push_str(&self.data.borrow().slice_chars((offset + count) as usize, length as usize)); *self.data.borrow_mut() = data; // FIXME: Once we have `Range`, we should implement step7 to step11 Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(self, nodes: Vec<NodeOrString>) -> ErrorResult { NodeCast::from_ref(self).replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(self) { let node: JSRef<Node> = NodeCast::from_ref(self); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(self) -> Option<Temporary<Element>> { NodeCast::from_ref(self).preceding_siblings() .filter_map(ElementCast::to_temporary).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(self) -> Option<Temporary<Element>> { NodeCast::from_ref(self).following_siblings() .filter_map(ElementCast::to_temporary).next() } } /// The different types of CharacterData. #[derive(Copy, Clone, PartialEq, Debug)] #[jstraceable] pub enum CharacterDataTypeId { Comment, Text, ProcessingInstruction, } pub trait CharacterDataHelpers<'a> { fn data(self) -> Ref<'a, DOMString>; } impl<'a> CharacterDataHelpers<'a> for JSRef<'a, CharacterData> { #[inline] fn data(self) -> Ref<'a, DOMString> { self.extended_deref().data.borrow() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout<'a>(&'a self) -> &'a str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout<'a>(&'a self) -> &'a str { &(*self.unsafe_get()).data.borrow_for_layout() } }
impl CharacterData {
random_line_split
text_attributes.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use ffi; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::mem; use std::ptr; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TextAttributes(Shared<ffi::GtkTextAttributes>); match fn { ref => |ptr| ffi::gtk_text_attributes_ref(ptr), unref => |ptr| ffi::gtk_text_attributes_unref(ptr), get_type => || ffi::gtk_text_attributes_get_type(), } } impl TextAttributes { pub fn new() -> TextAttributes { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_text_attributes_new()) } } pub fn copy(&self) -> Option<TextAttributes> { unsafe { from_glib_full(ffi::gtk_text_attributes_copy(self.to_glib_none().0)) } } pub fn
(&self, dest: &TextAttributes) { unsafe { ffi::gtk_text_attributes_copy_values(self.to_glib_none().0, dest.to_glib_none().0); } } } impl Default for TextAttributes { fn default() -> Self { Self::new() } }
copy_values
identifier_name
text_attributes.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use ffi; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::mem; use std::ptr; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TextAttributes(Shared<ffi::GtkTextAttributes>); match fn { ref => |ptr| ffi::gtk_text_attributes_ref(ptr), unref => |ptr| ffi::gtk_text_attributes_unref(ptr), get_type => || ffi::gtk_text_attributes_get_type(), } } impl TextAttributes { pub fn new() -> TextAttributes { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_text_attributes_new()) } } pub fn copy(&self) -> Option<TextAttributes> { unsafe { from_glib_full(ffi::gtk_text_attributes_copy(self.to_glib_none().0)) } } pub fn copy_values(&self, dest: &TextAttributes)
} impl Default for TextAttributes { fn default() -> Self { Self::new() } }
{ unsafe { ffi::gtk_text_attributes_copy_values(self.to_glib_none().0, dest.to_glib_none().0); } }
identifier_body
text_attributes.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use ffi; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::mem; use std::ptr; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TextAttributes(Shared<ffi::GtkTextAttributes>); match fn { ref => |ptr| ffi::gtk_text_attributes_ref(ptr), unref => |ptr| ffi::gtk_text_attributes_unref(ptr), get_type => || ffi::gtk_text_attributes_get_type(), } }
pub fn new() -> TextAttributes { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_text_attributes_new()) } } pub fn copy(&self) -> Option<TextAttributes> { unsafe { from_glib_full(ffi::gtk_text_attributes_copy(self.to_glib_none().0)) } } pub fn copy_values(&self, dest: &TextAttributes) { unsafe { ffi::gtk_text_attributes_copy_values(self.to_glib_none().0, dest.to_glib_none().0); } } } impl Default for TextAttributes { fn default() -> Self { Self::new() } }
impl TextAttributes {
random_line_split
main.rs
//! goto :: Flexible Working Directory Shortcuts //! //! Copyright (c) 2016-2019 by William R. Fraser #[macro_use] extern crate serde_derive; use std::collections::btree_map::*; use std::env; use std::fs::File; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use docopt::Docopt; const CONFIG_FILENAME: &str = ".goto.toml"; const DEFAULT_SHELLCMD: &str = "pushd"; // 79 columns: // ---------------------------------------------------------------------------- const USAGE: &str = r#" Usage: goto [options] [<name> [<extra>]] goto --list goto (--help | --version) Options: -c <command>, --cmd=<command> # defaults to 'pushd' Configuration is stored in ~/.goto.toml, with the following format: name = "/some/path" # 'goto name' takes you here othername = "~/some/other/path" # $HOME expansion will happen ["/somewhere/specific"] # Only in effect when in this location: "*" = "default/under/specific" # With no arguments, this is used. "name" = "somewhere/else" # Overshadows the one above. Relative paths under a context header are resolved relative to the path in that header. In the above example, when your current directory is under /somewhere/specific, running 'goto name' takes you to /somewhere/specific/somewhere/else. Configuration files can also be placed in any directory and will affect any invocations of goto from that directory or below it. In the case of conflicts, configurations from farther down the tree take precedence, and the one in your home directory takes precedence over all others. If <extra> is provided as an extra argument, it is appended to the computed path. goto is meant to be used as the argument to your shell's 'eval' builtin, like: function goto() { eval $(/usr/local/bin/goto $*) # or wherever the 'goto' binary is } "#; #[derive(Debug, Deserialize)] struct Args { arg_name: Option<String>, arg_extra: Option<String>, flag_cmd: Option<String>, flag_list: bool, } fn read_config_toml(config_path: &Path) -> io::Result<toml::value::Table> { let mut config_text = String::new(); let mut file = File::open(config_path)?; file.read_to_string(&mut config_text)?; match toml::from_str(&config_text) { Ok(config) => Ok(config), Err(e) => { Err(io::Error::new(io::ErrorKind::Other, format!("failed to parse TOML: {}", e))) } } } type PathMapping = BTreeMap<String, PathMappingEntry>; #[derive(Debug, Clone)] struct PathMappingEntry { dest: PathBuf, source_file: PathBuf, } #[derive(Debug)] struct Configuration { global: PathMapping, contexts: BTreeMap<PathBuf, PathMapping>, } impl Default for Configuration { fn default() -> Self { Configuration { global: PathMapping::new(), contexts: BTreeMap::new(), } } } /// Make the given TOML value into an absolute path. It should be a string, otherwise an error is /// returned. If the path is relative, it is made absolute by interpreting it relative to the given /// path, or to the user's home directory if it starts with "~/". fn parse_toml_as_path(t: &toml::Value, relative_to: &Path) -> Result<PathBuf, String> { if let toml::Value::String(ref s) = *t { let path: PathBuf = if s.starts_with("~/") || s.starts_with("~\\") { dirs::home_dir().unwrap().join(&Path::new(&s[2..])) } else { // note: this handles absolute paths correctly, by not using `relative_to` at all // (except for Windows, where the drive letter of `relative_to` may be considered). relative_to.join(Path::new(&s)) }; Ok(path) } else { Err(format!("type error: expected a string, not {}", t.type_str())) } } /// Process the parsed configuration TOML into goto's configuration struct. /// All relative paths will be interpreted relative to `relative_to`. fn process_config(config_file_path: &Path, config_toml: toml::value::Table, relative_to: &Path) -> Result<Configuration, String> { let mut config = Configuration::default(); for (k, v) in config_toml { if let toml::Value::Table(t) = v { // A path context. let context_path = match parse_toml_as_path(&toml::Value::String(k), relative_to) { Ok(path) => path, Err(msg) => { return Err(format!("error: {}", msg)); } }; let mut context_map = PathMapping::new(); for (name, path) in t { let mapped_path: PathBuf = match parse_toml_as_path(&path, &context_path) { Ok(path) => path, Err(msg) => { return Err(format!("error at {:?}.{}: {}", context_path, name, msg)); } }; context_map.insert(name, PathMappingEntry { source_file: config_file_path.to_owned(), dest: mapped_path, }); } config.contexts.insert(context_path, context_map); } else { // A top-level entry. Attempt to parse as a path and insert into the global table. let mapped_path: PathBuf = match parse_toml_as_path(&v, relative_to) { Ok(path) => path, Err(msg) => { return Err(format!( "error at {}: expected a table or a path string, not {} ({})", k, v.type_str(), msg)); }, }; config.global.insert(k, PathMappingEntry { source_file: config_file_path.to_owned(), dest: mapped_path, }); } } Ok(config) } /// Combine two configurations. The entries in `overlay` take precedence. fn combine_configs(combined: &mut Configuration, mut overlay: Configuration) { combined.global.append(&mut overlay.global); for (context_path, mut context) in overlay.contexts { match combined.contexts.entry(context_path) { Entry::Occupied(mut combined_context) => { combined_context.get_mut().append(&mut context); }, Entry::Vacant(entry) => { entry.insert(context); } } } } /// Read the configuration file at the given path. /// If the file does not exist, returns Ok(None), otherwise if the file cannot be read or processed /// for any reason, returns a message explaining the error. fn read_config(config_path: &Path) -> Result<Option<Configuration>, String> { let config_toml = match read_config_toml(config_path) { Ok(toml) => toml, Err(ref e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(format!("failed to read configuration {:?}: {}", config_path, e)), }; process_config(config_path, config_toml, config_path.parent().unwrap()) .map_err(|msg| { format!("invalid configuration in {:?}: {}", config_path, msg) }) .map(Some) } /// Read and combine all configuration files for a given path, by walking up the directory stack /// from the root to `cwd`, and finally the user's home configuration. If reading any of them /// fails (other than because the file does not exist), returns an appropriate error message. fn read_combine_configs(home_config_path: &Path, cwd: &Path) -> Result<Configuration, String> { assert!(cwd.is_absolute()); let mut combined = Configuration::default(); // Accumulate paths by stripping off components until we hit the root. let mut search_paths = Vec::<&Path>::new(); let mut maybe_path = Some(cwd); while let Some(path) = maybe_path { search_paths.push(path); maybe_path = path.parent(); } // Walk from the root up to `cwd`, reading and combining configs if they exist. for path in search_paths.iter().rev() { let toml_path = path.join(CONFIG_FILENAME); if let Some(config) = read_config(&toml_path)? { combine_configs(&mut combined, config); } } if let Some(config) = read_config(home_config_path)? { combine_configs(&mut combined, config); } Ok(combined) } fn exit(msg: &str, fatal: bool) ->! { io::stderr().write_all(msg.as_bytes()).unwrap(); if!msg.ends_with('\n') { io::stderr().write_all(b"\n").unwrap(); } let exit_code = if fatal { 1 } else { 0 }; ::std::process::exit(exit_code); } fn print_path(path: &Path, shellcmd: &str, extra: &str) { if!shellcmd.is_empty() { print!("{} ", shellcmd); } // Because the path is potentially combined with the current working directory, which is // untrusted data, and the path is going to be evaluated by the shell, the path needs to be // single-quote escaped to prevent any expansion, for security. // (Otherwise a folder named '$(:(){:|:&};:)' would make for a bad day.) println!("'{}'", path.join(extra).to_str().unwrap().replace("'", "'\\''")); } fn
() { let args: Args = Docopt::new(USAGE) .and_then(|d| { d.version(Some(format!("goto {}", env!("CARGO_PKG_VERSION")))) .deserialize() }) .unwrap_or_else(|e| { exit(&format!("{}", e), e.fatal()); }); let shellcmd = args.flag_cmd.as_ref().map(|s| s.as_str()).unwrap_or(DEFAULT_SHELLCMD); let name = args.arg_name.as_ref().map(|s| s.as_str()).unwrap_or("*"); let extra = args.arg_extra.as_ref().map(|s| s.as_str()).unwrap_or(""); let home = dirs::home_dir().unwrap_or_else(|| { exit("unable to determine home directory", true); }); let config_path = home.join(Path::new(CONFIG_FILENAME)); let cwd = env::current_dir().unwrap_or_else(|e| { exit(&format!("unable to get current working directory: {}", e), true); }); let config = read_combine_configs(&config_path, &cwd).unwrap_or_else(|msg| { exit(&msg, true); }); // only used for the --list mode let mut effective_map = PathMapping::new(); // Contexts can have keys that overlap with other contexts. The rule is that the longest // context path that matches the CWD takes precedence. let mut done = false; let mut context_paths_by_len: Vec<&PathBuf> = config.contexts.keys().collect(); context_paths_by_len.sort_by_key(|p| p.as_os_str().len()); for context_path in context_paths_by_len.iter().rev() { if cwd.starts_with(context_path) { let map = &config.contexts[*context_path]; if args.flag_list { for (k, v) in map { if let Entry::Vacant(entry) = effective_map.entry(k.clone()) { entry.insert(v.clone()); } } } else if let Some(ref entry) = map.get(&*name) { print_path(&entry.dest, shellcmd, extra); done = true; break; } } } if args.flag_list { for (k, v) in config.global { if let Entry::Vacant(entry) = effective_map.entry(k) { entry.insert(v); } } for (k, v) in effective_map { eprintln!("{} → {:?} (from {:?})", k, v.dest, v.source_file); } done = true; } else if!done { if let Some(ref entry) = config.global.get(&*name) { print_path(&entry.dest, shellcmd, extra); done = true; } } if!done { exit("not sure where to go", false); } }
main
identifier_name
main.rs
//! goto :: Flexible Working Directory Shortcuts //! //! Copyright (c) 2016-2019 by William R. Fraser #[macro_use] extern crate serde_derive; use std::collections::btree_map::*; use std::env; use std::fs::File; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use docopt::Docopt; const CONFIG_FILENAME: &str = ".goto.toml"; const DEFAULT_SHELLCMD: &str = "pushd"; // 79 columns: // ---------------------------------------------------------------------------- const USAGE: &str = r#" Usage: goto [options] [<name> [<extra>]] goto --list goto (--help | --version) Options: -c <command>, --cmd=<command> # defaults to 'pushd' Configuration is stored in ~/.goto.toml, with the following format: name = "/some/path" # 'goto name' takes you here othername = "~/some/other/path" # $HOME expansion will happen ["/somewhere/specific"] # Only in effect when in this location: "*" = "default/under/specific" # With no arguments, this is used. "name" = "somewhere/else" # Overshadows the one above. Relative paths under a context header are resolved relative to the path in that header. In the above example, when your current directory is under /somewhere/specific, running 'goto name' takes you to /somewhere/specific/somewhere/else. Configuration files can also be placed in any directory and will affect any invocations of goto from that directory or below it. In the case of conflicts, configurations from farther down the tree take precedence, and the one in your home directory takes precedence over all others. If <extra> is provided as an extra argument, it is appended to the computed path. goto is meant to be used as the argument to your shell's 'eval' builtin, like: function goto() { eval $(/usr/local/bin/goto $*) # or wherever the 'goto' binary is } "#; #[derive(Debug, Deserialize)] struct Args { arg_name: Option<String>, arg_extra: Option<String>, flag_cmd: Option<String>, flag_list: bool, } fn read_config_toml(config_path: &Path) -> io::Result<toml::value::Table> { let mut config_text = String::new(); let mut file = File::open(config_path)?; file.read_to_string(&mut config_text)?; match toml::from_str(&config_text) { Ok(config) => Ok(config), Err(e) => { Err(io::Error::new(io::ErrorKind::Other, format!("failed to parse TOML: {}", e))) } } } type PathMapping = BTreeMap<String, PathMappingEntry>; #[derive(Debug, Clone)] struct PathMappingEntry { dest: PathBuf, source_file: PathBuf, } #[derive(Debug)] struct Configuration { global: PathMapping, contexts: BTreeMap<PathBuf, PathMapping>, } impl Default for Configuration { fn default() -> Self { Configuration { global: PathMapping::new(), contexts: BTreeMap::new(), } } } /// Make the given TOML value into an absolute path. It should be a string, otherwise an error is /// returned. If the path is relative, it is made absolute by interpreting it relative to the given /// path, or to the user's home directory if it starts with "~/". fn parse_toml_as_path(t: &toml::Value, relative_to: &Path) -> Result<PathBuf, String> { if let toml::Value::String(ref s) = *t { let path: PathBuf = if s.starts_with("~/") || s.starts_with("~\\") { dirs::home_dir().unwrap().join(&Path::new(&s[2..])) } else { // note: this handles absolute paths correctly, by not using `relative_to` at all // (except for Windows, where the drive letter of `relative_to` may be considered). relative_to.join(Path::new(&s)) }; Ok(path) } else { Err(format!("type error: expected a string, not {}", t.type_str())) } } /// Process the parsed configuration TOML into goto's configuration struct. /// All relative paths will be interpreted relative to `relative_to`. fn process_config(config_file_path: &Path, config_toml: toml::value::Table, relative_to: &Path) -> Result<Configuration, String> { let mut config = Configuration::default(); for (k, v) in config_toml { if let toml::Value::Table(t) = v { // A path context. let context_path = match parse_toml_as_path(&toml::Value::String(k), relative_to) { Ok(path) => path, Err(msg) => { return Err(format!("error: {}", msg)); } }; let mut context_map = PathMapping::new(); for (name, path) in t { let mapped_path: PathBuf = match parse_toml_as_path(&path, &context_path) { Ok(path) => path, Err(msg) => { return Err(format!("error at {:?}.{}: {}", context_path, name, msg)); } }; context_map.insert(name, PathMappingEntry { source_file: config_file_path.to_owned(), dest: mapped_path, }); } config.contexts.insert(context_path, context_map); } else { // A top-level entry. Attempt to parse as a path and insert into the global table. let mapped_path: PathBuf = match parse_toml_as_path(&v, relative_to) { Ok(path) => path, Err(msg) => { return Err(format!( "error at {}: expected a table or a path string, not {} ({})", k, v.type_str(), msg)); }, }; config.global.insert(k, PathMappingEntry { source_file: config_file_path.to_owned(), dest: mapped_path, }); } } Ok(config) } /// Combine two configurations. The entries in `overlay` take precedence. fn combine_configs(combined: &mut Configuration, mut overlay: Configuration) { combined.global.append(&mut overlay.global); for (context_path, mut context) in overlay.contexts { match combined.contexts.entry(context_path) { Entry::Occupied(mut combined_context) => { combined_context.get_mut().append(&mut context); }, Entry::Vacant(entry) => { entry.insert(context); } } } } /// Read the configuration file at the given path. /// If the file does not exist, returns Ok(None), otherwise if the file cannot be read or processed /// for any reason, returns a message explaining the error. fn read_config(config_path: &Path) -> Result<Option<Configuration>, String> { let config_toml = match read_config_toml(config_path) { Ok(toml) => toml, Err(ref e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(format!("failed to read configuration {:?}: {}", config_path, e)), }; process_config(config_path, config_toml, config_path.parent().unwrap()) .map_err(|msg| { format!("invalid configuration in {:?}: {}", config_path, msg) }) .map(Some) } /// Read and combine all configuration files for a given path, by walking up the directory stack /// from the root to `cwd`, and finally the user's home configuration. If reading any of them /// fails (other than because the file does not exist), returns an appropriate error message. fn read_combine_configs(home_config_path: &Path, cwd: &Path) -> Result<Configuration, String>
if let Some(config) = read_config(home_config_path)? { combine_configs(&mut combined, config); } Ok(combined) } fn exit(msg: &str, fatal: bool) ->! { io::stderr().write_all(msg.as_bytes()).unwrap(); if!msg.ends_with('\n') { io::stderr().write_all(b"\n").unwrap(); } let exit_code = if fatal { 1 } else { 0 }; ::std::process::exit(exit_code); } fn print_path(path: &Path, shellcmd: &str, extra: &str) { if!shellcmd.is_empty() { print!("{} ", shellcmd); } // Because the path is potentially combined with the current working directory, which is // untrusted data, and the path is going to be evaluated by the shell, the path needs to be // single-quote escaped to prevent any expansion, for security. // (Otherwise a folder named '$(:(){:|:&};:)' would make for a bad day.) println!("'{}'", path.join(extra).to_str().unwrap().replace("'", "'\\''")); } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| { d.version(Some(format!("goto {}", env!("CARGO_PKG_VERSION")))) .deserialize() }) .unwrap_or_else(|e| { exit(&format!("{}", e), e.fatal()); }); let shellcmd = args.flag_cmd.as_ref().map(|s| s.as_str()).unwrap_or(DEFAULT_SHELLCMD); let name = args.arg_name.as_ref().map(|s| s.as_str()).unwrap_or("*"); let extra = args.arg_extra.as_ref().map(|s| s.as_str()).unwrap_or(""); let home = dirs::home_dir().unwrap_or_else(|| { exit("unable to determine home directory", true); }); let config_path = home.join(Path::new(CONFIG_FILENAME)); let cwd = env::current_dir().unwrap_or_else(|e| { exit(&format!("unable to get current working directory: {}", e), true); }); let config = read_combine_configs(&config_path, &cwd).unwrap_or_else(|msg| { exit(&msg, true); }); // only used for the --list mode let mut effective_map = PathMapping::new(); // Contexts can have keys that overlap with other contexts. The rule is that the longest // context path that matches the CWD takes precedence. let mut done = false; let mut context_paths_by_len: Vec<&PathBuf> = config.contexts.keys().collect(); context_paths_by_len.sort_by_key(|p| p.as_os_str().len()); for context_path in context_paths_by_len.iter().rev() { if cwd.starts_with(context_path) { let map = &config.contexts[*context_path]; if args.flag_list { for (k, v) in map { if let Entry::Vacant(entry) = effective_map.entry(k.clone()) { entry.insert(v.clone()); } } } else if let Some(ref entry) = map.get(&*name) { print_path(&entry.dest, shellcmd, extra); done = true; break; } } } if args.flag_list { for (k, v) in config.global { if let Entry::Vacant(entry) = effective_map.entry(k) { entry.insert(v); } } for (k, v) in effective_map { eprintln!("{} → {:?} (from {:?})", k, v.dest, v.source_file); } done = true; } else if!done { if let Some(ref entry) = config.global.get(&*name) { print_path(&entry.dest, shellcmd, extra); done = true; } } if!done { exit("not sure where to go", false); } }
{ assert!(cwd.is_absolute()); let mut combined = Configuration::default(); // Accumulate paths by stripping off components until we hit the root. let mut search_paths = Vec::<&Path>::new(); let mut maybe_path = Some(cwd); while let Some(path) = maybe_path { search_paths.push(path); maybe_path = path.parent(); } // Walk from the root up to `cwd`, reading and combining configs if they exist. for path in search_paths.iter().rev() { let toml_path = path.join(CONFIG_FILENAME); if let Some(config) = read_config(&toml_path)? { combine_configs(&mut combined, config); } }
identifier_body
main.rs
//! goto :: Flexible Working Directory Shortcuts //! //! Copyright (c) 2016-2019 by William R. Fraser #[macro_use] extern crate serde_derive; use std::collections::btree_map::*; use std::env; use std::fs::File; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use docopt::Docopt; const CONFIG_FILENAME: &str = ".goto.toml"; const DEFAULT_SHELLCMD: &str = "pushd"; // 79 columns: // ---------------------------------------------------------------------------- const USAGE: &str = r#" Usage: goto [options] [<name> [<extra>]] goto --list goto (--help | --version) Options: -c <command>, --cmd=<command> # defaults to 'pushd' Configuration is stored in ~/.goto.toml, with the following format: name = "/some/path" # 'goto name' takes you here othername = "~/some/other/path" # $HOME expansion will happen ["/somewhere/specific"] # Only in effect when in this location: "*" = "default/under/specific" # With no arguments, this is used. "name" = "somewhere/else" # Overshadows the one above. Relative paths under a context header are resolved relative to the path in that header. In the above example, when your current directory is under /somewhere/specific, running 'goto name' takes you to /somewhere/specific/somewhere/else. Configuration files can also be placed in any directory and will affect any invocations of goto from that directory or below it. In the case of conflicts, configurations from farther down the tree take precedence, and the one in your home directory takes precedence over all others. If <extra> is provided as an extra argument, it is appended to the computed path. goto is meant to be used as the argument to your shell's 'eval' builtin, like: function goto() { eval $(/usr/local/bin/goto $*) # or wherever the 'goto' binary is } "#; #[derive(Debug, Deserialize)] struct Args { arg_name: Option<String>, arg_extra: Option<String>, flag_cmd: Option<String>, flag_list: bool, } fn read_config_toml(config_path: &Path) -> io::Result<toml::value::Table> { let mut config_text = String::new(); let mut file = File::open(config_path)?; file.read_to_string(&mut config_text)?; match toml::from_str(&config_text) { Ok(config) => Ok(config), Err(e) => { Err(io::Error::new(io::ErrorKind::Other, format!("failed to parse TOML: {}", e))) } } } type PathMapping = BTreeMap<String, PathMappingEntry>; #[derive(Debug, Clone)] struct PathMappingEntry { dest: PathBuf, source_file: PathBuf, } #[derive(Debug)] struct Configuration { global: PathMapping, contexts: BTreeMap<PathBuf, PathMapping>, } impl Default for Configuration { fn default() -> Self { Configuration { global: PathMapping::new(), contexts: BTreeMap::new(), } } } /// Make the given TOML value into an absolute path. It should be a string, otherwise an error is /// returned. If the path is relative, it is made absolute by interpreting it relative to the given /// path, or to the user's home directory if it starts with "~/". fn parse_toml_as_path(t: &toml::Value, relative_to: &Path) -> Result<PathBuf, String> { if let toml::Value::String(ref s) = *t { let path: PathBuf = if s.starts_with("~/") || s.starts_with("~\\") { dirs::home_dir().unwrap().join(&Path::new(&s[2..])) } else { // note: this handles absolute paths correctly, by not using `relative_to` at all // (except for Windows, where the drive letter of `relative_to` may be considered). relative_to.join(Path::new(&s)) }; Ok(path) } else { Err(format!("type error: expected a string, not {}", t.type_str())) } } /// Process the parsed configuration TOML into goto's configuration struct. /// All relative paths will be interpreted relative to `relative_to`. fn process_config(config_file_path: &Path, config_toml: toml::value::Table, relative_to: &Path) -> Result<Configuration, String> { let mut config = Configuration::default(); for (k, v) in config_toml { if let toml::Value::Table(t) = v { // A path context. let context_path = match parse_toml_as_path(&toml::Value::String(k), relative_to) { Ok(path) => path, Err(msg) => { return Err(format!("error: {}", msg)); } }; let mut context_map = PathMapping::new(); for (name, path) in t { let mapped_path: PathBuf = match parse_toml_as_path(&path, &context_path) { Ok(path) => path, Err(msg) => { return Err(format!("error at {:?}.{}: {}", context_path, name, msg)); } }; context_map.insert(name, PathMappingEntry { source_file: config_file_path.to_owned(), dest: mapped_path, }); } config.contexts.insert(context_path, context_map); } else { // A top-level entry. Attempt to parse as a path and insert into the global table. let mapped_path: PathBuf = match parse_toml_as_path(&v, relative_to) { Ok(path) => path, Err(msg) => { return Err(format!( "error at {}: expected a table or a path string, not {} ({})", k, v.type_str(), msg)); }, }; config.global.insert(k, PathMappingEntry { source_file: config_file_path.to_owned(), dest: mapped_path, }); } } Ok(config) } /// Combine two configurations. The entries in `overlay` take precedence. fn combine_configs(combined: &mut Configuration, mut overlay: Configuration) { combined.global.append(&mut overlay.global); for (context_path, mut context) in overlay.contexts { match combined.contexts.entry(context_path) {
} } } } /// Read the configuration file at the given path. /// If the file does not exist, returns Ok(None), otherwise if the file cannot be read or processed /// for any reason, returns a message explaining the error. fn read_config(config_path: &Path) -> Result<Option<Configuration>, String> { let config_toml = match read_config_toml(config_path) { Ok(toml) => toml, Err(ref e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(format!("failed to read configuration {:?}: {}", config_path, e)), }; process_config(config_path, config_toml, config_path.parent().unwrap()) .map_err(|msg| { format!("invalid configuration in {:?}: {}", config_path, msg) }) .map(Some) } /// Read and combine all configuration files for a given path, by walking up the directory stack /// from the root to `cwd`, and finally the user's home configuration. If reading any of them /// fails (other than because the file does not exist), returns an appropriate error message. fn read_combine_configs(home_config_path: &Path, cwd: &Path) -> Result<Configuration, String> { assert!(cwd.is_absolute()); let mut combined = Configuration::default(); // Accumulate paths by stripping off components until we hit the root. let mut search_paths = Vec::<&Path>::new(); let mut maybe_path = Some(cwd); while let Some(path) = maybe_path { search_paths.push(path); maybe_path = path.parent(); } // Walk from the root up to `cwd`, reading and combining configs if they exist. for path in search_paths.iter().rev() { let toml_path = path.join(CONFIG_FILENAME); if let Some(config) = read_config(&toml_path)? { combine_configs(&mut combined, config); } } if let Some(config) = read_config(home_config_path)? { combine_configs(&mut combined, config); } Ok(combined) } fn exit(msg: &str, fatal: bool) ->! { io::stderr().write_all(msg.as_bytes()).unwrap(); if!msg.ends_with('\n') { io::stderr().write_all(b"\n").unwrap(); } let exit_code = if fatal { 1 } else { 0 }; ::std::process::exit(exit_code); } fn print_path(path: &Path, shellcmd: &str, extra: &str) { if!shellcmd.is_empty() { print!("{} ", shellcmd); } // Because the path is potentially combined with the current working directory, which is // untrusted data, and the path is going to be evaluated by the shell, the path needs to be // single-quote escaped to prevent any expansion, for security. // (Otherwise a folder named '$(:(){:|:&};:)' would make for a bad day.) println!("'{}'", path.join(extra).to_str().unwrap().replace("'", "'\\''")); } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| { d.version(Some(format!("goto {}", env!("CARGO_PKG_VERSION")))) .deserialize() }) .unwrap_or_else(|e| { exit(&format!("{}", e), e.fatal()); }); let shellcmd = args.flag_cmd.as_ref().map(|s| s.as_str()).unwrap_or(DEFAULT_SHELLCMD); let name = args.arg_name.as_ref().map(|s| s.as_str()).unwrap_or("*"); let extra = args.arg_extra.as_ref().map(|s| s.as_str()).unwrap_or(""); let home = dirs::home_dir().unwrap_or_else(|| { exit("unable to determine home directory", true); }); let config_path = home.join(Path::new(CONFIG_FILENAME)); let cwd = env::current_dir().unwrap_or_else(|e| { exit(&format!("unable to get current working directory: {}", e), true); }); let config = read_combine_configs(&config_path, &cwd).unwrap_or_else(|msg| { exit(&msg, true); }); // only used for the --list mode let mut effective_map = PathMapping::new(); // Contexts can have keys that overlap with other contexts. The rule is that the longest // context path that matches the CWD takes precedence. let mut done = false; let mut context_paths_by_len: Vec<&PathBuf> = config.contexts.keys().collect(); context_paths_by_len.sort_by_key(|p| p.as_os_str().len()); for context_path in context_paths_by_len.iter().rev() { if cwd.starts_with(context_path) { let map = &config.contexts[*context_path]; if args.flag_list { for (k, v) in map { if let Entry::Vacant(entry) = effective_map.entry(k.clone()) { entry.insert(v.clone()); } } } else if let Some(ref entry) = map.get(&*name) { print_path(&entry.dest, shellcmd, extra); done = true; break; } } } if args.flag_list { for (k, v) in config.global { if let Entry::Vacant(entry) = effective_map.entry(k) { entry.insert(v); } } for (k, v) in effective_map { eprintln!("{} → {:?} (from {:?})", k, v.dest, v.source_file); } done = true; } else if!done { if let Some(ref entry) = config.global.get(&*name) { print_path(&entry.dest, shellcmd, extra); done = true; } } if!done { exit("not sure where to go", false); } }
Entry::Occupied(mut combined_context) => { combined_context.get_mut().append(&mut context); }, Entry::Vacant(entry) => { entry.insert(context);
random_line_split
main.rs
//! goto :: Flexible Working Directory Shortcuts //! //! Copyright (c) 2016-2019 by William R. Fraser #[macro_use] extern crate serde_derive; use std::collections::btree_map::*; use std::env; use std::fs::File; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use docopt::Docopt; const CONFIG_FILENAME: &str = ".goto.toml"; const DEFAULT_SHELLCMD: &str = "pushd"; // 79 columns: // ---------------------------------------------------------------------------- const USAGE: &str = r#" Usage: goto [options] [<name> [<extra>]] goto --list goto (--help | --version) Options: -c <command>, --cmd=<command> # defaults to 'pushd' Configuration is stored in ~/.goto.toml, with the following format: name = "/some/path" # 'goto name' takes you here othername = "~/some/other/path" # $HOME expansion will happen ["/somewhere/specific"] # Only in effect when in this location: "*" = "default/under/specific" # With no arguments, this is used. "name" = "somewhere/else" # Overshadows the one above. Relative paths under a context header are resolved relative to the path in that header. In the above example, when your current directory is under /somewhere/specific, running 'goto name' takes you to /somewhere/specific/somewhere/else. Configuration files can also be placed in any directory and will affect any invocations of goto from that directory or below it. In the case of conflicts, configurations from farther down the tree take precedence, and the one in your home directory takes precedence over all others. If <extra> is provided as an extra argument, it is appended to the computed path. goto is meant to be used as the argument to your shell's 'eval' builtin, like: function goto() { eval $(/usr/local/bin/goto $*) # or wherever the 'goto' binary is } "#; #[derive(Debug, Deserialize)] struct Args { arg_name: Option<String>, arg_extra: Option<String>, flag_cmd: Option<String>, flag_list: bool, } fn read_config_toml(config_path: &Path) -> io::Result<toml::value::Table> { let mut config_text = String::new(); let mut file = File::open(config_path)?; file.read_to_string(&mut config_text)?; match toml::from_str(&config_text) { Ok(config) => Ok(config), Err(e) => { Err(io::Error::new(io::ErrorKind::Other, format!("failed to parse TOML: {}", e))) } } } type PathMapping = BTreeMap<String, PathMappingEntry>; #[derive(Debug, Clone)] struct PathMappingEntry { dest: PathBuf, source_file: PathBuf, } #[derive(Debug)] struct Configuration { global: PathMapping, contexts: BTreeMap<PathBuf, PathMapping>, } impl Default for Configuration { fn default() -> Self { Configuration { global: PathMapping::new(), contexts: BTreeMap::new(), } } } /// Make the given TOML value into an absolute path. It should be a string, otherwise an error is /// returned. If the path is relative, it is made absolute by interpreting it relative to the given /// path, or to the user's home directory if it starts with "~/". fn parse_toml_as_path(t: &toml::Value, relative_to: &Path) -> Result<PathBuf, String> { if let toml::Value::String(ref s) = *t { let path: PathBuf = if s.starts_with("~/") || s.starts_with("~\\") { dirs::home_dir().unwrap().join(&Path::new(&s[2..])) } else { // note: this handles absolute paths correctly, by not using `relative_to` at all // (except for Windows, where the drive letter of `relative_to` may be considered). relative_to.join(Path::new(&s)) }; Ok(path) } else { Err(format!("type error: expected a string, not {}", t.type_str())) } } /// Process the parsed configuration TOML into goto's configuration struct. /// All relative paths will be interpreted relative to `relative_to`. fn process_config(config_file_path: &Path, config_toml: toml::value::Table, relative_to: &Path) -> Result<Configuration, String> { let mut config = Configuration::default(); for (k, v) in config_toml { if let toml::Value::Table(t) = v { // A path context. let context_path = match parse_toml_as_path(&toml::Value::String(k), relative_to) { Ok(path) => path, Err(msg) => { return Err(format!("error: {}", msg)); } }; let mut context_map = PathMapping::new(); for (name, path) in t { let mapped_path: PathBuf = match parse_toml_as_path(&path, &context_path) { Ok(path) => path, Err(msg) => { return Err(format!("error at {:?}.{}: {}", context_path, name, msg)); } }; context_map.insert(name, PathMappingEntry { source_file: config_file_path.to_owned(), dest: mapped_path, }); } config.contexts.insert(context_path, context_map); } else
} Ok(config) } /// Combine two configurations. The entries in `overlay` take precedence. fn combine_configs(combined: &mut Configuration, mut overlay: Configuration) { combined.global.append(&mut overlay.global); for (context_path, mut context) in overlay.contexts { match combined.contexts.entry(context_path) { Entry::Occupied(mut combined_context) => { combined_context.get_mut().append(&mut context); }, Entry::Vacant(entry) => { entry.insert(context); } } } } /// Read the configuration file at the given path. /// If the file does not exist, returns Ok(None), otherwise if the file cannot be read or processed /// for any reason, returns a message explaining the error. fn read_config(config_path: &Path) -> Result<Option<Configuration>, String> { let config_toml = match read_config_toml(config_path) { Ok(toml) => toml, Err(ref e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(format!("failed to read configuration {:?}: {}", config_path, e)), }; process_config(config_path, config_toml, config_path.parent().unwrap()) .map_err(|msg| { format!("invalid configuration in {:?}: {}", config_path, msg) }) .map(Some) } /// Read and combine all configuration files for a given path, by walking up the directory stack /// from the root to `cwd`, and finally the user's home configuration. If reading any of them /// fails (other than because the file does not exist), returns an appropriate error message. fn read_combine_configs(home_config_path: &Path, cwd: &Path) -> Result<Configuration, String> { assert!(cwd.is_absolute()); let mut combined = Configuration::default(); // Accumulate paths by stripping off components until we hit the root. let mut search_paths = Vec::<&Path>::new(); let mut maybe_path = Some(cwd); while let Some(path) = maybe_path { search_paths.push(path); maybe_path = path.parent(); } // Walk from the root up to `cwd`, reading and combining configs if they exist. for path in search_paths.iter().rev() { let toml_path = path.join(CONFIG_FILENAME); if let Some(config) = read_config(&toml_path)? { combine_configs(&mut combined, config); } } if let Some(config) = read_config(home_config_path)? { combine_configs(&mut combined, config); } Ok(combined) } fn exit(msg: &str, fatal: bool) ->! { io::stderr().write_all(msg.as_bytes()).unwrap(); if!msg.ends_with('\n') { io::stderr().write_all(b"\n").unwrap(); } let exit_code = if fatal { 1 } else { 0 }; ::std::process::exit(exit_code); } fn print_path(path: &Path, shellcmd: &str, extra: &str) { if!shellcmd.is_empty() { print!("{} ", shellcmd); } // Because the path is potentially combined with the current working directory, which is // untrusted data, and the path is going to be evaluated by the shell, the path needs to be // single-quote escaped to prevent any expansion, for security. // (Otherwise a folder named '$(:(){:|:&};:)' would make for a bad day.) println!("'{}'", path.join(extra).to_str().unwrap().replace("'", "'\\''")); } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| { d.version(Some(format!("goto {}", env!("CARGO_PKG_VERSION")))) .deserialize() }) .unwrap_or_else(|e| { exit(&format!("{}", e), e.fatal()); }); let shellcmd = args.flag_cmd.as_ref().map(|s| s.as_str()).unwrap_or(DEFAULT_SHELLCMD); let name = args.arg_name.as_ref().map(|s| s.as_str()).unwrap_or("*"); let extra = args.arg_extra.as_ref().map(|s| s.as_str()).unwrap_or(""); let home = dirs::home_dir().unwrap_or_else(|| { exit("unable to determine home directory", true); }); let config_path = home.join(Path::new(CONFIG_FILENAME)); let cwd = env::current_dir().unwrap_or_else(|e| { exit(&format!("unable to get current working directory: {}", e), true); }); let config = read_combine_configs(&config_path, &cwd).unwrap_or_else(|msg| { exit(&msg, true); }); // only used for the --list mode let mut effective_map = PathMapping::new(); // Contexts can have keys that overlap with other contexts. The rule is that the longest // context path that matches the CWD takes precedence. let mut done = false; let mut context_paths_by_len: Vec<&PathBuf> = config.contexts.keys().collect(); context_paths_by_len.sort_by_key(|p| p.as_os_str().len()); for context_path in context_paths_by_len.iter().rev() { if cwd.starts_with(context_path) { let map = &config.contexts[*context_path]; if args.flag_list { for (k, v) in map { if let Entry::Vacant(entry) = effective_map.entry(k.clone()) { entry.insert(v.clone()); } } } else if let Some(ref entry) = map.get(&*name) { print_path(&entry.dest, shellcmd, extra); done = true; break; } } } if args.flag_list { for (k, v) in config.global { if let Entry::Vacant(entry) = effective_map.entry(k) { entry.insert(v); } } for (k, v) in effective_map { eprintln!("{} → {:?} (from {:?})", k, v.dest, v.source_file); } done = true; } else if!done { if let Some(ref entry) = config.global.get(&*name) { print_path(&entry.dest, shellcmd, extra); done = true; } } if!done { exit("not sure where to go", false); } }
{ // A top-level entry. Attempt to parse as a path and insert into the global table. let mapped_path: PathBuf = match parse_toml_as_path(&v, relative_to) { Ok(path) => path, Err(msg) => { return Err(format!( "error at {}: expected a table or a path string, not {} ({})", k, v.type_str(), msg)); }, }; config.global.insert(k, PathMappingEntry { source_file: config_file_path.to_owned(), dest: mapped_path, }); }
conditional_block
regions-bounded-by-send.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. // Test which of the builtin types are considered sendable. The tests // in this file all test region bound and lifetime violations that are // detected during type check. fn assert_send<T:Send>() { } trait Dummy { } // lifetime pointers with'static lifetime are ok fn static_lifime_ok<'a,T,U:Send>(_: &'a int) { assert_send::<&'static int>(); assert_send::<&'static str>(); assert_send::<&'static [int]>(); // whether or not they are mutable assert_send::<&'static mut int>(); } // otherwise lifetime pointers are not ok fn param_not_ok<'a>(x: &'a int) { assert_send::<&'a int>(); //~ ERROR does not fulfill } fn param_not_ok1<'a>(_: &'a int)
fn param_not_ok2<'a>(_: &'a int) { assert_send::<&'a [int]>(); //~ ERROR does not fulfill } // boxes are ok fn box_ok() { assert_send::<Box<int>>(); assert_send::<String>(); assert_send::<Vec<int>>(); } // but not if they own a bad thing fn box_with_region_not_ok<'a>() { assert_send::<Box<&'a int>>(); //~ ERROR does not fulfill } // objects with insufficient bounds no ok fn object_with_random_bound_not_ok<'a>() { assert_send::<&'a (Dummy+'a)>(); //~^ ERROR not implemented } fn object_with_send_bound_not_ok<'a>() { assert_send::<&'a (Dummy+Send)>(); //~^ ERROR does not fulfill } fn proc_with_lifetime_not_ok<'a>() { assert_send::<proc():'a>(); //~^ ERROR not implemented } fn closure_with_lifetime_not_ok<'a>() { assert_send::<||:'a>(); //~^ ERROR not implemented } // unsafe pointers are ok unless they point at unsendable things fn unsafe_ok1<'a>(_: &'a int) { assert_send::<*const int>(); assert_send::<*mut int>(); } fn unsafe_ok2<'a>(_: &'a int) { assert_send::<*const &'a int>(); //~ ERROR does not fulfill } fn unsafe_ok3<'a>(_: &'a int) { assert_send::<*mut &'a int>(); //~ ERROR does not fulfill } fn main() { }
{ assert_send::<&'a str>(); //~ ERROR does not fulfill }
identifier_body
regions-bounded-by-send.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. // Test which of the builtin types are considered sendable. The tests // in this file all test region bound and lifetime violations that are // detected during type check. fn assert_send<T:Send>() { } trait Dummy { } // lifetime pointers with'static lifetime are ok fn static_lifime_ok<'a,T,U:Send>(_: &'a int) { assert_send::<&'static int>(); assert_send::<&'static str>(); assert_send::<&'static [int]>(); // whether or not they are mutable assert_send::<&'static mut int>(); } // otherwise lifetime pointers are not ok fn param_not_ok<'a>(x: &'a int) { assert_send::<&'a int>(); //~ ERROR does not fulfill } fn param_not_ok1<'a>(_: &'a int) { assert_send::<&'a str>(); //~ ERROR does not fulfill } fn param_not_ok2<'a>(_: &'a int) { assert_send::<&'a [int]>(); //~ ERROR does not fulfill } // boxes are ok fn box_ok() { assert_send::<Box<int>>(); assert_send::<String>(); assert_send::<Vec<int>>(); } // but not if they own a bad thing
} // objects with insufficient bounds no ok fn object_with_random_bound_not_ok<'a>() { assert_send::<&'a (Dummy+'a)>(); //~^ ERROR not implemented } fn object_with_send_bound_not_ok<'a>() { assert_send::<&'a (Dummy+Send)>(); //~^ ERROR does not fulfill } fn proc_with_lifetime_not_ok<'a>() { assert_send::<proc():'a>(); //~^ ERROR not implemented } fn closure_with_lifetime_not_ok<'a>() { assert_send::<||:'a>(); //~^ ERROR not implemented } // unsafe pointers are ok unless they point at unsendable things fn unsafe_ok1<'a>(_: &'a int) { assert_send::<*const int>(); assert_send::<*mut int>(); } fn unsafe_ok2<'a>(_: &'a int) { assert_send::<*const &'a int>(); //~ ERROR does not fulfill } fn unsafe_ok3<'a>(_: &'a int) { assert_send::<*mut &'a int>(); //~ ERROR does not fulfill } fn main() { }
fn box_with_region_not_ok<'a>() { assert_send::<Box<&'a int>>(); //~ ERROR does not fulfill
random_line_split
regions-bounded-by-send.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. // Test which of the builtin types are considered sendable. The tests // in this file all test region bound and lifetime violations that are // detected during type check. fn assert_send<T:Send>() { } trait Dummy { } // lifetime pointers with'static lifetime are ok fn static_lifime_ok<'a,T,U:Send>(_: &'a int) { assert_send::<&'static int>(); assert_send::<&'static str>(); assert_send::<&'static [int]>(); // whether or not they are mutable assert_send::<&'static mut int>(); } // otherwise lifetime pointers are not ok fn param_not_ok<'a>(x: &'a int) { assert_send::<&'a int>(); //~ ERROR does not fulfill } fn param_not_ok1<'a>(_: &'a int) { assert_send::<&'a str>(); //~ ERROR does not fulfill } fn param_not_ok2<'a>(_: &'a int) { assert_send::<&'a [int]>(); //~ ERROR does not fulfill } // boxes are ok fn box_ok() { assert_send::<Box<int>>(); assert_send::<String>(); assert_send::<Vec<int>>(); } // but not if they own a bad thing fn box_with_region_not_ok<'a>() { assert_send::<Box<&'a int>>(); //~ ERROR does not fulfill } // objects with insufficient bounds no ok fn object_with_random_bound_not_ok<'a>() { assert_send::<&'a (Dummy+'a)>(); //~^ ERROR not implemented } fn object_with_send_bound_not_ok<'a>() { assert_send::<&'a (Dummy+Send)>(); //~^ ERROR does not fulfill } fn proc_with_lifetime_not_ok<'a>() { assert_send::<proc():'a>(); //~^ ERROR not implemented } fn
<'a>() { assert_send::<||:'a>(); //~^ ERROR not implemented } // unsafe pointers are ok unless they point at unsendable things fn unsafe_ok1<'a>(_: &'a int) { assert_send::<*const int>(); assert_send::<*mut int>(); } fn unsafe_ok2<'a>(_: &'a int) { assert_send::<*const &'a int>(); //~ ERROR does not fulfill } fn unsafe_ok3<'a>(_: &'a int) { assert_send::<*mut &'a int>(); //~ ERROR does not fulfill } fn main() { }
closure_with_lifetime_not_ok
identifier_name
packet.rs
use error::QuicError; use error::Result; use std::io::Cursor; use std::io::Read; use byteorder::{WriteBytesExt, ReadBytesExt, BigEndian}; use header::QuicHeader; use header::ShortHeader; use header::LongHeader; use frames::QuicFrame; bitflags! { pub flags ShortPacketType: u8 { const ONE_BYTE = 0x01, const TWO_BYTES = 0x02, const FOUR_BYTES = 0x03, } } bitflags! { pub flags PacketType: u8 { const VERSION_NEGOTIATION = 0x01, const CLIENT_CLEARTEXT = 0x02, const NON_FINAL_CLEARTEXT = 0x03, const FINAL_SERVER_CLEAR_TEXT = 0x04, const RTT0_ENCRYPTED = 0x05, const RTT1_ENCRYPTED_PHASE0 = 0x06, const RTT1_ENCRYPTED_PHASE1 = 0x07, const PUBLIC_RESET = 0x08, } } #[derive(Debug)] pub struct PublicResetPayload { } #[derive(Debug)] pub struct VersionNegotiationPayload { pub versions: Vec<u32>, } impl VersionNegotiationPayload { pub fn from_bytes(buf: &[u8]) -> Result<VersionNegotiationPayload> { let mut reader = Cursor::new(buf); let mut versions = Vec::with_capacity((buf.len() / 4) as usize); while let Ok(version) = reader.read_u32::<BigEndian>() { versions.push(version); } Ok(VersionNegotiationPayload { versions: versions, }) } pub fn as_bytes(&self) -> Vec<u8> { let mut bytes = Vec::with_capacity(self.versions.len()); self.versions.iter().map(|&version| bytes.write_u32::<BigEndian>(version)); bytes } } #[derive(Debug)] pub enum QuicPayload { Frames(Vec<QuicFrame>), PublicReset(PublicResetPayload), VersionNegotiation(VersionNegotiationPayload), } impl QuicPayload { pub fn as_bytes(&self) -> Vec<u8> { match *self { QuicPayload::Frames(ref frames) => { frames.iter().map(|frame| { frame.as_bytes() }) .collect::<Vec<_>>() .concat() }, QuicPayload::PublicReset(_) => vec![], QuicPayload::VersionNegotiation(ref version_payload) => version_payload.as_bytes(), } } } #[derive(Debug)] pub struct
{ pub header: QuicHeader, pub payload: QuicPayload, } impl QuicPacket { pub fn from_bytes(buf: &[u8]) -> Result<QuicPacket> { let mut reader = Cursor::new(buf); let first_byte = reader.read_uint::<BigEndian>(1)? as u8; if first_byte & 0x80!= 0 { // Long Header let mut header_bytes = [0u8; 17]; reader.read_exact(&mut header_bytes); let header = LongHeader::from_bytes(&header_bytes)?; let mut payload_bytes = Vec::new(); let _ = reader.read_to_end(&mut payload_bytes); let payload = match PacketType::from_bits(first_byte) { Some(CLIENT_CLEARTEXT) | Some(NON_FINAL_CLEARTEXT) | Some(FINAL_SERVER_CLEAR_TEXT) => QuicPayload::Frames(QuicPacket::parse_decrypted_payload(payload_bytes.as_slice())?), Some(VERSION_NEGOTIATION) => QuicPayload::VersionNegotiation(VersionNegotiationPayload::from_bytes(&payload_bytes)?), Some(_) | None => return Err(QuicError::ParseError), }; Ok(QuicPacket { header: QuicHeader::Long(header), payload: payload }) } else { // ShortHeader let packet_type = match ShortPacketType::from_bits(first_byte & 0x1f) { Some(pt) => pt, None => return Err(QuicError::ParseError) }; let mut header_len = 1; let conn_id_bit = first_byte & 0x40 > 0; if conn_id_bit { header_len += 8; } match packet_type { ONE_BYTE => header_len += 1, TWO_BYTES => header_len += 2, FOUR_BYTES => header_len += 4, _ => return Err(QuicError::ParseError) }; let mut header_bytes = vec![0u8; header_len]; reader.read_exact(&mut header_bytes); let header = ShortHeader::from_bytes(header_bytes.as_slice())?; // TODO: Decrypt frames and return the payloads. Ok(QuicPacket { header: QuicHeader::Short(header), payload: QuicPayload::Frames(vec![]) }) } } pub fn as_bytes(&self) -> Result<Vec<u8>> { let header_bytes = match self.header { QuicHeader::Short(ref header) => header.as_bytes(), QuicHeader::Long(ref header) => header.as_bytes(), }; let payload_bytes = self.payload.as_bytes(); let packet_bytes = [header_bytes, payload_bytes].concat(); if packet_bytes.len() > 1232 { return Err(QuicError::PacketTooLarge); } Ok(packet_bytes) } pub fn parse_decrypted_payload(buf: &[u8]) -> Result<Vec<QuicFrame>> { let mut frames: Vec<QuicFrame> = Vec::new(); let mut position = 0; loop { let frame_len = QuicFrame::frame_length(&buf[position..])?; let frame_end = position + frame_len; let frame = QuicFrame::from_bytes(&buf[position..frame_end])?; position += frame_len; frames.push(frame); if position == buf.len() { break; } } Ok(frames) } } #[cfg(test)] mod tests { use super::*; use frames; #[test] fn parse_decrypted_payload_1() { let reason = "Terrible connection!"; let frames = vec![ QuicFrame::ConnectionClose(frames::connection_close_frame::ConnectionCloseFrame { error_code: 29, reason_length: reason.len() as u16, reason_phrase: Some(reason.to_string()), }), QuicFrame::MaxStreamData(frames::max_stream_data_frame::MaxStreamDataFrame { stream_id: 20099 as u32, max_stream_data: 290 as u64, }), QuicFrame::MaxStreamData(frames::max_stream_data_frame::MaxStreamDataFrame { stream_id: 20099 as u32, max_stream_data: 290 as u64, }), QuicFrame::MaxStreamData(frames::max_stream_data_frame::MaxStreamDataFrame { stream_id: 20099 as u32, max_stream_data: 290 as u64, }), QuicFrame::MaxStreamData(frames::max_stream_data_frame::MaxStreamDataFrame { stream_id: 20099 as u32, max_stream_data: 290 as u64, }), ]; let mut bytes = Vec::new(); for frame in &frames { let frame_bytes = frame.as_bytes(); bytes.extend(frame_bytes); } let parsed_frames = QuicPacket::parse_decrypted_payload(&bytes).unwrap(); assert_eq!(&frames, &parsed_frames); } }
QuicPacket
identifier_name
packet.rs
use error::QuicError; use error::Result; use std::io::Cursor; use std::io::Read; use byteorder::{WriteBytesExt, ReadBytesExt, BigEndian}; use header::QuicHeader; use header::ShortHeader; use header::LongHeader; use frames::QuicFrame; bitflags! { pub flags ShortPacketType: u8 { const ONE_BYTE = 0x01, const TWO_BYTES = 0x02, const FOUR_BYTES = 0x03, } } bitflags! { pub flags PacketType: u8 { const VERSION_NEGOTIATION = 0x01, const CLIENT_CLEARTEXT = 0x02, const NON_FINAL_CLEARTEXT = 0x03, const FINAL_SERVER_CLEAR_TEXT = 0x04, const RTT0_ENCRYPTED = 0x05, const RTT1_ENCRYPTED_PHASE0 = 0x06, const RTT1_ENCRYPTED_PHASE1 = 0x07, const PUBLIC_RESET = 0x08, } } #[derive(Debug)] pub struct PublicResetPayload { } #[derive(Debug)] pub struct VersionNegotiationPayload { pub versions: Vec<u32>, } impl VersionNegotiationPayload { pub fn from_bytes(buf: &[u8]) -> Result<VersionNegotiationPayload> { let mut reader = Cursor::new(buf); let mut versions = Vec::with_capacity((buf.len() / 4) as usize); while let Ok(version) = reader.read_u32::<BigEndian>() { versions.push(version); } Ok(VersionNegotiationPayload { versions: versions, }) } pub fn as_bytes(&self) -> Vec<u8> { let mut bytes = Vec::with_capacity(self.versions.len()); self.versions.iter().map(|&version| bytes.write_u32::<BigEndian>(version)); bytes } } #[derive(Debug)] pub enum QuicPayload { Frames(Vec<QuicFrame>), PublicReset(PublicResetPayload), VersionNegotiation(VersionNegotiationPayload), } impl QuicPayload { pub fn as_bytes(&self) -> Vec<u8> { match *self { QuicPayload::Frames(ref frames) => { frames.iter().map(|frame| { frame.as_bytes() }) .collect::<Vec<_>>() .concat() }, QuicPayload::PublicReset(_) => vec![], QuicPayload::VersionNegotiation(ref version_payload) => version_payload.as_bytes(), } } } #[derive(Debug)] pub struct QuicPacket { pub header: QuicHeader, pub payload: QuicPayload, } impl QuicPacket { pub fn from_bytes(buf: &[u8]) -> Result<QuicPacket> { let mut reader = Cursor::new(buf); let first_byte = reader.read_uint::<BigEndian>(1)? as u8; if first_byte & 0x80!= 0 { // Long Header let mut header_bytes = [0u8; 17]; reader.read_exact(&mut header_bytes); let header = LongHeader::from_bytes(&header_bytes)?; let mut payload_bytes = Vec::new(); let _ = reader.read_to_end(&mut payload_bytes); let payload = match PacketType::from_bits(first_byte) { Some(CLIENT_CLEARTEXT) | Some(NON_FINAL_CLEARTEXT) | Some(FINAL_SERVER_CLEAR_TEXT) => QuicPayload::Frames(QuicPacket::parse_decrypted_payload(payload_bytes.as_slice())?), Some(VERSION_NEGOTIATION) => QuicPayload::VersionNegotiation(VersionNegotiationPayload::from_bytes(&payload_bytes)?), Some(_) | None => return Err(QuicError::ParseError), }; Ok(QuicPacket { header: QuicHeader::Long(header), payload: payload })
} else { // ShortHeader let packet_type = match ShortPacketType::from_bits(first_byte & 0x1f) { Some(pt) => pt, None => return Err(QuicError::ParseError) }; let mut header_len = 1; let conn_id_bit = first_byte & 0x40 > 0; if conn_id_bit { header_len += 8; } match packet_type { ONE_BYTE => header_len += 1, TWO_BYTES => header_len += 2, FOUR_BYTES => header_len += 4, _ => return Err(QuicError::ParseError) }; let mut header_bytes = vec![0u8; header_len]; reader.read_exact(&mut header_bytes); let header = ShortHeader::from_bytes(header_bytes.as_slice())?; // TODO: Decrypt frames and return the payloads. Ok(QuicPacket { header: QuicHeader::Short(header), payload: QuicPayload::Frames(vec![]) }) } } pub fn as_bytes(&self) -> Result<Vec<u8>> { let header_bytes = match self.header { QuicHeader::Short(ref header) => header.as_bytes(), QuicHeader::Long(ref header) => header.as_bytes(), }; let payload_bytes = self.payload.as_bytes(); let packet_bytes = [header_bytes, payload_bytes].concat(); if packet_bytes.len() > 1232 { return Err(QuicError::PacketTooLarge); } Ok(packet_bytes) } pub fn parse_decrypted_payload(buf: &[u8]) -> Result<Vec<QuicFrame>> { let mut frames: Vec<QuicFrame> = Vec::new(); let mut position = 0; loop { let frame_len = QuicFrame::frame_length(&buf[position..])?; let frame_end = position + frame_len; let frame = QuicFrame::from_bytes(&buf[position..frame_end])?; position += frame_len; frames.push(frame); if position == buf.len() { break; } } Ok(frames) } } #[cfg(test)] mod tests { use super::*; use frames; #[test] fn parse_decrypted_payload_1() { let reason = "Terrible connection!"; let frames = vec![ QuicFrame::ConnectionClose(frames::connection_close_frame::ConnectionCloseFrame { error_code: 29, reason_length: reason.len() as u16, reason_phrase: Some(reason.to_string()), }), QuicFrame::MaxStreamData(frames::max_stream_data_frame::MaxStreamDataFrame { stream_id: 20099 as u32, max_stream_data: 290 as u64, }), QuicFrame::MaxStreamData(frames::max_stream_data_frame::MaxStreamDataFrame { stream_id: 20099 as u32, max_stream_data: 290 as u64, }), QuicFrame::MaxStreamData(frames::max_stream_data_frame::MaxStreamDataFrame { stream_id: 20099 as u32, max_stream_data: 290 as u64, }), QuicFrame::MaxStreamData(frames::max_stream_data_frame::MaxStreamDataFrame { stream_id: 20099 as u32, max_stream_data: 290 as u64, }), ]; let mut bytes = Vec::new(); for frame in &frames { let frame_bytes = frame.as_bytes(); bytes.extend(frame_bytes); } let parsed_frames = QuicPacket::parse_decrypted_payload(&bytes).unwrap(); assert_eq!(&frames, &parsed_frames); } }
random_line_split
mod.rs
// Copyright 2015, Christopher Chambers // Distributed under the GNU GPL v3. See COPYING for details. use regex::Regex; use sbbm_asm::assembler::Assembler; use sbbm_asm::commands::{Command, Target, IntoTarget, players}; use sbbm_asm::fab; use sbbm_asm::hw::{Computer, MemoryRegion, MemoryStride}; use sbbm_asm::layout::{Layout, LinearMotion}; use sbbm_asm::lexer::Lexer; use sbbm_asm::nbt::Nbt; use sbbm_asm::parser::Parser; use sbbm_asm::types::{Extent, Vec3}; use std::env; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufRead, BufReader, Read, Write}; use std::mem; use std::path::PathBuf; use std::rt::at_exit; use std::sync::{MutexGuard, Once, StaticMutex, MUTEX_INIT, ONCE_INIT}; const ORIGIN: Vec3 = Vec3 { x: 0, y: 56, z: 0 }; static mut COMPUTER: *const Computer = 0 as *const Computer; static COMPUTER_INIT: Once = ONCE_INIT; static SERVER_MUTEX: StaticMutex = MUTEX_INIT; static SET_REGEX: Regex = regex!( r"Set score of (\w+) for player.+ to (-?\d+)"); fn server_path() -> PathBuf { let mut path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
path.push("server"); path } fn input_path() -> PathBuf { let mut p = server_path(); p.push("input"); p } fn output_path() -> PathBuf { let mut p = server_path(); p.push("output"); p } fn capture_path() -> PathBuf { let mut p = server_path(); p.push("capture"); p } pub struct Server { _guard: MutexGuard<'static, ()>, } impl Server { pub fn new() -> Server { let guard = SERVER_MUTEX.lock().unwrap(); COMPUTER_INIT.call_once(|| { init_computer(); at_exit(destroy_computer).unwrap(); }); let server = Server { _guard: guard, }; // Wait for any noise to die down. server.capture(|| {}); server } pub fn write(&self, cmd: &Command) -> io::Result<()> { let mut f = OpenOptions::new() .write(true) .append(true) .open(input_path()) .unwrap(); write!(f, "{}\n", cmd) } pub fn exec(&self, cmd: &Command) -> io::Result<String> { // FIXME: Eliminate all unwrap to prevent poisoning the mutex. let (_, output) = self.capture_until(|_| true, || { self.write(cmd).unwrap(); }); Ok(output) } pub fn get(&self, target: &Target, obj: &str) -> io::Result<i32> { let resp = try!(self.exec( &players::add(target.clone(), obj.to_string(), 0, None))); if let Some(cap) = SET_REGEX.captures(&resp[..]) { // TODO: Verify that the objectives match. // FIXME: Real error handling. Ok(cap.at(2).unwrap().parse().unwrap()) } else { panic!("ugh error handling is hard"); } } pub fn get_computer(&self, obj: &str) -> io::Result<i32> { self.get(&computer().selector().into_target(), obj) } pub fn capture_until<F, P, T>(&self, p: P, f: F) -> (T, String) where F : Fn() -> T, P : Fn(&str) -> bool { // FIXME: Eliminate all panics, return some kind of Result<> File::create(capture_path()).unwrap(); let res = f(); // FIXME: handle errors, good god man. let out = File::open(output_path()).unwrap(); let mut out = BufReader::new(out); // FIXME: eeeerrroors let mut captured = String::new(); loop { let start = captured.len(); out.read_line(&mut captured).unwrap(); if p(&captured[start..]) { break; } } fs::remove_file(capture_path()).unwrap(); (res, captured) } pub fn capture<F, T>(&self, f: F) -> (T, String) where F : Fn() -> T { let marker = "54799be5-7239-4e00-bd9f-095ae6ed58a3"; let (result, mut output) = self.capture_until(|s| s.contains(marker), || { let result = f(); self.write(&Command::Say(marker.to_string())).unwrap(); result }); // Remove the marker line from output. let mut count = 0; match output.rfind(|c| if c == '\n' { count += 1; count > 1 } else { false }) { Some(index) => output.truncate(index + 1), None => output.truncate(0), } (result, output) } pub fn run_asm(&self, input: &str) { // FIXME: Eliminate all unwrap to prevent poisoning the mutex. let marker = "6ee5dd4a-ea5c-476d-bcab-4c2a912ce2ed"; let (dirty_extent, _) = self.capture_until(|s| s.contains(marker), || { let mut marked = input.to_string(); marked.push_str("\n\traw say "); marked.push_str(marker); let mut parser = Parser::new(Lexer::mem(&marked[..])); let mut assembler = Assembler::new( computer(), parser.parse_program().into_iter()); assembler.set_track_output(true); let mem_controllers = { let mut c = vec!(); for region in computer().memory.iter() { c.extend(fab::make_mem_ctrl(region)); } c }; let motion = Box::new(LinearMotion::new(ORIGIN)); let mut layout = Layout::new(motion, assembler.chain(mem_controllers)); let mut dirty_extent = Extent::Empty; for (pos, block) in &mut layout { dirty_extent.add(pos); self.write(&Command::SetBlock( pos.as_abs(), block.id, None, None, Some(Nbt::Compound(block.nbt)))).unwrap(); } if let Some(Extent::MinMax(min, max)) = layout.get_power_extent("main") { dirty_extent.add(min); dirty_extent.add(max); self.write(&Command::Fill( min.as_abs(), max.as_abs(), "minecraft:redstone_block".to_string(), None, None, None)).unwrap(); } dirty_extent }); self.capture(|| { if let Extent::MinMax(min, max) = dirty_extent { self.write(&Command::Fill( min.as_abs(), max.as_abs(), "minecraft:air".to_string(), None, None, None)).unwrap(); } }); } } fn computer() -> &'static Computer { unsafe { mem::transmute(COMPUTER) } } fn init_computer() { unsafe { COMPUTER = mem::transmute(Box::new(Computer { name: "computer".to_string(), origin: ORIGIN, memory: vec![ MemoryRegion { start: 0x10, size: 0x100, origin: Vec3::new(ORIGIN.x - 1, ORIGIN.y, ORIGIN.z), growth: Vec3::new(-1, 1, 1), stride: MemoryStride::XY(8, 8), }] })) } let mut f = OpenOptions::new() .write(true) .append(true) .open(input_path()) .unwrap(); computer().write_init_script(&mut f).unwrap(); } fn destroy_computer() { let mut f = OpenOptions::new() .write(true) .append(true) .create(true) .open(input_path()) .unwrap(); computer().write_destroy_script(&mut f).unwrap(); }
path.push("..");
random_line_split
mod.rs
// Copyright 2015, Christopher Chambers // Distributed under the GNU GPL v3. See COPYING for details. use regex::Regex; use sbbm_asm::assembler::Assembler; use sbbm_asm::commands::{Command, Target, IntoTarget, players}; use sbbm_asm::fab; use sbbm_asm::hw::{Computer, MemoryRegion, MemoryStride}; use sbbm_asm::layout::{Layout, LinearMotion}; use sbbm_asm::lexer::Lexer; use sbbm_asm::nbt::Nbt; use sbbm_asm::parser::Parser; use sbbm_asm::types::{Extent, Vec3}; use std::env; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufRead, BufReader, Read, Write}; use std::mem; use std::path::PathBuf; use std::rt::at_exit; use std::sync::{MutexGuard, Once, StaticMutex, MUTEX_INIT, ONCE_INIT}; const ORIGIN: Vec3 = Vec3 { x: 0, y: 56, z: 0 }; static mut COMPUTER: *const Computer = 0 as *const Computer; static COMPUTER_INIT: Once = ONCE_INIT; static SERVER_MUTEX: StaticMutex = MUTEX_INIT; static SET_REGEX: Regex = regex!( r"Set score of (\w+) for player.+ to (-?\d+)"); fn server_path() -> PathBuf { let mut path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); path.push(".."); path.push("server"); path } fn input_path() -> PathBuf { let mut p = server_path(); p.push("input"); p } fn output_path() -> PathBuf { let mut p = server_path(); p.push("output"); p } fn capture_path() -> PathBuf { let mut p = server_path(); p.push("capture"); p } pub struct Server { _guard: MutexGuard<'static, ()>, } impl Server { pub fn new() -> Server { let guard = SERVER_MUTEX.lock().unwrap(); COMPUTER_INIT.call_once(|| { init_computer(); at_exit(destroy_computer).unwrap(); }); let server = Server { _guard: guard, }; // Wait for any noise to die down. server.capture(|| {}); server } pub fn write(&self, cmd: &Command) -> io::Result<()> { let mut f = OpenOptions::new() .write(true) .append(true) .open(input_path()) .unwrap(); write!(f, "{}\n", cmd) } pub fn exec(&self, cmd: &Command) -> io::Result<String> { // FIXME: Eliminate all unwrap to prevent poisoning the mutex. let (_, output) = self.capture_until(|_| true, || { self.write(cmd).unwrap(); }); Ok(output) } pub fn get(&self, target: &Target, obj: &str) -> io::Result<i32> { let resp = try!(self.exec( &players::add(target.clone(), obj.to_string(), 0, None))); if let Some(cap) = SET_REGEX.captures(&resp[..]) { // TODO: Verify that the objectives match. // FIXME: Real error handling. Ok(cap.at(2).unwrap().parse().unwrap()) } else { panic!("ugh error handling is hard"); } } pub fn get_computer(&self, obj: &str) -> io::Result<i32> { self.get(&computer().selector().into_target(), obj) } pub fn capture_until<F, P, T>(&self, p: P, f: F) -> (T, String) where F : Fn() -> T, P : Fn(&str) -> bool { // FIXME: Eliminate all panics, return some kind of Result<> File::create(capture_path()).unwrap(); let res = f(); // FIXME: handle errors, good god man. let out = File::open(output_path()).unwrap(); let mut out = BufReader::new(out); // FIXME: eeeerrroors let mut captured = String::new(); loop { let start = captured.len(); out.read_line(&mut captured).unwrap(); if p(&captured[start..])
} fs::remove_file(capture_path()).unwrap(); (res, captured) } pub fn capture<F, T>(&self, f: F) -> (T, String) where F : Fn() -> T { let marker = "54799be5-7239-4e00-bd9f-095ae6ed58a3"; let (result, mut output) = self.capture_until(|s| s.contains(marker), || { let result = f(); self.write(&Command::Say(marker.to_string())).unwrap(); result }); // Remove the marker line from output. let mut count = 0; match output.rfind(|c| if c == '\n' { count += 1; count > 1 } else { false }) { Some(index) => output.truncate(index + 1), None => output.truncate(0), } (result, output) } pub fn run_asm(&self, input: &str) { // FIXME: Eliminate all unwrap to prevent poisoning the mutex. let marker = "6ee5dd4a-ea5c-476d-bcab-4c2a912ce2ed"; let (dirty_extent, _) = self.capture_until(|s| s.contains(marker), || { let mut marked = input.to_string(); marked.push_str("\n\traw say "); marked.push_str(marker); let mut parser = Parser::new(Lexer::mem(&marked[..])); let mut assembler = Assembler::new( computer(), parser.parse_program().into_iter()); assembler.set_track_output(true); let mem_controllers = { let mut c = vec!(); for region in computer().memory.iter() { c.extend(fab::make_mem_ctrl(region)); } c }; let motion = Box::new(LinearMotion::new(ORIGIN)); let mut layout = Layout::new(motion, assembler.chain(mem_controllers)); let mut dirty_extent = Extent::Empty; for (pos, block) in &mut layout { dirty_extent.add(pos); self.write(&Command::SetBlock( pos.as_abs(), block.id, None, None, Some(Nbt::Compound(block.nbt)))).unwrap(); } if let Some(Extent::MinMax(min, max)) = layout.get_power_extent("main") { dirty_extent.add(min); dirty_extent.add(max); self.write(&Command::Fill( min.as_abs(), max.as_abs(), "minecraft:redstone_block".to_string(), None, None, None)).unwrap(); } dirty_extent }); self.capture(|| { if let Extent::MinMax(min, max) = dirty_extent { self.write(&Command::Fill( min.as_abs(), max.as_abs(), "minecraft:air".to_string(), None, None, None)).unwrap(); } }); } } fn computer() -> &'static Computer { unsafe { mem::transmute(COMPUTER) } } fn init_computer() { unsafe { COMPUTER = mem::transmute(Box::new(Computer { name: "computer".to_string(), origin: ORIGIN, memory: vec![ MemoryRegion { start: 0x10, size: 0x100, origin: Vec3::new(ORIGIN.x - 1, ORIGIN.y, ORIGIN.z), growth: Vec3::new(-1, 1, 1), stride: MemoryStride::XY(8, 8), }] })) } let mut f = OpenOptions::new() .write(true) .append(true) .open(input_path()) .unwrap(); computer().write_init_script(&mut f).unwrap(); } fn destroy_computer() { let mut f = OpenOptions::new() .write(true) .append(true) .create(true) .open(input_path()) .unwrap(); computer().write_destroy_script(&mut f).unwrap(); }
{ break; }
conditional_block
mod.rs
// Copyright 2015, Christopher Chambers // Distributed under the GNU GPL v3. See COPYING for details. use regex::Regex; use sbbm_asm::assembler::Assembler; use sbbm_asm::commands::{Command, Target, IntoTarget, players}; use sbbm_asm::fab; use sbbm_asm::hw::{Computer, MemoryRegion, MemoryStride}; use sbbm_asm::layout::{Layout, LinearMotion}; use sbbm_asm::lexer::Lexer; use sbbm_asm::nbt::Nbt; use sbbm_asm::parser::Parser; use sbbm_asm::types::{Extent, Vec3}; use std::env; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufRead, BufReader, Read, Write}; use std::mem; use std::path::PathBuf; use std::rt::at_exit; use std::sync::{MutexGuard, Once, StaticMutex, MUTEX_INIT, ONCE_INIT}; const ORIGIN: Vec3 = Vec3 { x: 0, y: 56, z: 0 }; static mut COMPUTER: *const Computer = 0 as *const Computer; static COMPUTER_INIT: Once = ONCE_INIT; static SERVER_MUTEX: StaticMutex = MUTEX_INIT; static SET_REGEX: Regex = regex!( r"Set score of (\w+) for player.+ to (-?\d+)"); fn server_path() -> PathBuf { let mut path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); path.push(".."); path.push("server"); path } fn input_path() -> PathBuf { let mut p = server_path(); p.push("input"); p } fn output_path() -> PathBuf { let mut p = server_path(); p.push("output"); p } fn capture_path() -> PathBuf { let mut p = server_path(); p.push("capture"); p } pub struct Server { _guard: MutexGuard<'static, ()>, } impl Server { pub fn new() -> Server { let guard = SERVER_MUTEX.lock().unwrap(); COMPUTER_INIT.call_once(|| { init_computer(); at_exit(destroy_computer).unwrap(); }); let server = Server { _guard: guard, }; // Wait for any noise to die down. server.capture(|| {}); server } pub fn write(&self, cmd: &Command) -> io::Result<()> { let mut f = OpenOptions::new() .write(true) .append(true) .open(input_path()) .unwrap(); write!(f, "{}\n", cmd) } pub fn exec(&self, cmd: &Command) -> io::Result<String> { // FIXME: Eliminate all unwrap to prevent poisoning the mutex. let (_, output) = self.capture_until(|_| true, || { self.write(cmd).unwrap(); }); Ok(output) } pub fn get(&self, target: &Target, obj: &str) -> io::Result<i32> { let resp = try!(self.exec( &players::add(target.clone(), obj.to_string(), 0, None))); if let Some(cap) = SET_REGEX.captures(&resp[..]) { // TODO: Verify that the objectives match. // FIXME: Real error handling. Ok(cap.at(2).unwrap().parse().unwrap()) } else { panic!("ugh error handling is hard"); } } pub fn get_computer(&self, obj: &str) -> io::Result<i32> { self.get(&computer().selector().into_target(), obj) } pub fn capture_until<F, P, T>(&self, p: P, f: F) -> (T, String) where F : Fn() -> T, P : Fn(&str) -> bool { // FIXME: Eliminate all panics, return some kind of Result<> File::create(capture_path()).unwrap(); let res = f(); // FIXME: handle errors, good god man. let out = File::open(output_path()).unwrap(); let mut out = BufReader::new(out); // FIXME: eeeerrroors let mut captured = String::new(); loop { let start = captured.len(); out.read_line(&mut captured).unwrap(); if p(&captured[start..]) { break; } } fs::remove_file(capture_path()).unwrap(); (res, captured) } pub fn capture<F, T>(&self, f: F) -> (T, String) where F : Fn() -> T { let marker = "54799be5-7239-4e00-bd9f-095ae6ed58a3"; let (result, mut output) = self.capture_until(|s| s.contains(marker), || { let result = f(); self.write(&Command::Say(marker.to_string())).unwrap(); result }); // Remove the marker line from output. let mut count = 0; match output.rfind(|c| if c == '\n' { count += 1; count > 1 } else { false }) { Some(index) => output.truncate(index + 1), None => output.truncate(0), } (result, output) } pub fn run_asm(&self, input: &str) { // FIXME: Eliminate all unwrap to prevent poisoning the mutex. let marker = "6ee5dd4a-ea5c-476d-bcab-4c2a912ce2ed"; let (dirty_extent, _) = self.capture_until(|s| s.contains(marker), || { let mut marked = input.to_string(); marked.push_str("\n\traw say "); marked.push_str(marker); let mut parser = Parser::new(Lexer::mem(&marked[..])); let mut assembler = Assembler::new( computer(), parser.parse_program().into_iter()); assembler.set_track_output(true); let mem_controllers = { let mut c = vec!(); for region in computer().memory.iter() { c.extend(fab::make_mem_ctrl(region)); } c }; let motion = Box::new(LinearMotion::new(ORIGIN)); let mut layout = Layout::new(motion, assembler.chain(mem_controllers)); let mut dirty_extent = Extent::Empty; for (pos, block) in &mut layout { dirty_extent.add(pos); self.write(&Command::SetBlock( pos.as_abs(), block.id, None, None, Some(Nbt::Compound(block.nbt)))).unwrap(); } if let Some(Extent::MinMax(min, max)) = layout.get_power_extent("main") { dirty_extent.add(min); dirty_extent.add(max); self.write(&Command::Fill( min.as_abs(), max.as_abs(), "minecraft:redstone_block".to_string(), None, None, None)).unwrap(); } dirty_extent }); self.capture(|| { if let Extent::MinMax(min, max) = dirty_extent { self.write(&Command::Fill( min.as_abs(), max.as_abs(), "minecraft:air".to_string(), None, None, None)).unwrap(); } }); } } fn computer() -> &'static Computer { unsafe { mem::transmute(COMPUTER) } } fn init_computer() { unsafe { COMPUTER = mem::transmute(Box::new(Computer { name: "computer".to_string(), origin: ORIGIN, memory: vec![ MemoryRegion { start: 0x10, size: 0x100, origin: Vec3::new(ORIGIN.x - 1, ORIGIN.y, ORIGIN.z), growth: Vec3::new(-1, 1, 1), stride: MemoryStride::XY(8, 8), }] })) } let mut f = OpenOptions::new() .write(true) .append(true) .open(input_path()) .unwrap(); computer().write_init_script(&mut f).unwrap(); } fn
() { let mut f = OpenOptions::new() .write(true) .append(true) .create(true) .open(input_path()) .unwrap(); computer().write_destroy_script(&mut f).unwrap(); }
destroy_computer
identifier_name
mod.rs
// Copyright 2015, Christopher Chambers // Distributed under the GNU GPL v3. See COPYING for details. use regex::Regex; use sbbm_asm::assembler::Assembler; use sbbm_asm::commands::{Command, Target, IntoTarget, players}; use sbbm_asm::fab; use sbbm_asm::hw::{Computer, MemoryRegion, MemoryStride}; use sbbm_asm::layout::{Layout, LinearMotion}; use sbbm_asm::lexer::Lexer; use sbbm_asm::nbt::Nbt; use sbbm_asm::parser::Parser; use sbbm_asm::types::{Extent, Vec3}; use std::env; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufRead, BufReader, Read, Write}; use std::mem; use std::path::PathBuf; use std::rt::at_exit; use std::sync::{MutexGuard, Once, StaticMutex, MUTEX_INIT, ONCE_INIT}; const ORIGIN: Vec3 = Vec3 { x: 0, y: 56, z: 0 }; static mut COMPUTER: *const Computer = 0 as *const Computer; static COMPUTER_INIT: Once = ONCE_INIT; static SERVER_MUTEX: StaticMutex = MUTEX_INIT; static SET_REGEX: Regex = regex!( r"Set score of (\w+) for player.+ to (-?\d+)"); fn server_path() -> PathBuf { let mut path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); path.push(".."); path.push("server"); path } fn input_path() -> PathBuf
fn output_path() -> PathBuf { let mut p = server_path(); p.push("output"); p } fn capture_path() -> PathBuf { let mut p = server_path(); p.push("capture"); p } pub struct Server { _guard: MutexGuard<'static, ()>, } impl Server { pub fn new() -> Server { let guard = SERVER_MUTEX.lock().unwrap(); COMPUTER_INIT.call_once(|| { init_computer(); at_exit(destroy_computer).unwrap(); }); let server = Server { _guard: guard, }; // Wait for any noise to die down. server.capture(|| {}); server } pub fn write(&self, cmd: &Command) -> io::Result<()> { let mut f = OpenOptions::new() .write(true) .append(true) .open(input_path()) .unwrap(); write!(f, "{}\n", cmd) } pub fn exec(&self, cmd: &Command) -> io::Result<String> { // FIXME: Eliminate all unwrap to prevent poisoning the mutex. let (_, output) = self.capture_until(|_| true, || { self.write(cmd).unwrap(); }); Ok(output) } pub fn get(&self, target: &Target, obj: &str) -> io::Result<i32> { let resp = try!(self.exec( &players::add(target.clone(), obj.to_string(), 0, None))); if let Some(cap) = SET_REGEX.captures(&resp[..]) { // TODO: Verify that the objectives match. // FIXME: Real error handling. Ok(cap.at(2).unwrap().parse().unwrap()) } else { panic!("ugh error handling is hard"); } } pub fn get_computer(&self, obj: &str) -> io::Result<i32> { self.get(&computer().selector().into_target(), obj) } pub fn capture_until<F, P, T>(&self, p: P, f: F) -> (T, String) where F : Fn() -> T, P : Fn(&str) -> bool { // FIXME: Eliminate all panics, return some kind of Result<> File::create(capture_path()).unwrap(); let res = f(); // FIXME: handle errors, good god man. let out = File::open(output_path()).unwrap(); let mut out = BufReader::new(out); // FIXME: eeeerrroors let mut captured = String::new(); loop { let start = captured.len(); out.read_line(&mut captured).unwrap(); if p(&captured[start..]) { break; } } fs::remove_file(capture_path()).unwrap(); (res, captured) } pub fn capture<F, T>(&self, f: F) -> (T, String) where F : Fn() -> T { let marker = "54799be5-7239-4e00-bd9f-095ae6ed58a3"; let (result, mut output) = self.capture_until(|s| s.contains(marker), || { let result = f(); self.write(&Command::Say(marker.to_string())).unwrap(); result }); // Remove the marker line from output. let mut count = 0; match output.rfind(|c| if c == '\n' { count += 1; count > 1 } else { false }) { Some(index) => output.truncate(index + 1), None => output.truncate(0), } (result, output) } pub fn run_asm(&self, input: &str) { // FIXME: Eliminate all unwrap to prevent poisoning the mutex. let marker = "6ee5dd4a-ea5c-476d-bcab-4c2a912ce2ed"; let (dirty_extent, _) = self.capture_until(|s| s.contains(marker), || { let mut marked = input.to_string(); marked.push_str("\n\traw say "); marked.push_str(marker); let mut parser = Parser::new(Lexer::mem(&marked[..])); let mut assembler = Assembler::new( computer(), parser.parse_program().into_iter()); assembler.set_track_output(true); let mem_controllers = { let mut c = vec!(); for region in computer().memory.iter() { c.extend(fab::make_mem_ctrl(region)); } c }; let motion = Box::new(LinearMotion::new(ORIGIN)); let mut layout = Layout::new(motion, assembler.chain(mem_controllers)); let mut dirty_extent = Extent::Empty; for (pos, block) in &mut layout { dirty_extent.add(pos); self.write(&Command::SetBlock( pos.as_abs(), block.id, None, None, Some(Nbt::Compound(block.nbt)))).unwrap(); } if let Some(Extent::MinMax(min, max)) = layout.get_power_extent("main") { dirty_extent.add(min); dirty_extent.add(max); self.write(&Command::Fill( min.as_abs(), max.as_abs(), "minecraft:redstone_block".to_string(), None, None, None)).unwrap(); } dirty_extent }); self.capture(|| { if let Extent::MinMax(min, max) = dirty_extent { self.write(&Command::Fill( min.as_abs(), max.as_abs(), "minecraft:air".to_string(), None, None, None)).unwrap(); } }); } } fn computer() -> &'static Computer { unsafe { mem::transmute(COMPUTER) } } fn init_computer() { unsafe { COMPUTER = mem::transmute(Box::new(Computer { name: "computer".to_string(), origin: ORIGIN, memory: vec![ MemoryRegion { start: 0x10, size: 0x100, origin: Vec3::new(ORIGIN.x - 1, ORIGIN.y, ORIGIN.z), growth: Vec3::new(-1, 1, 1), stride: MemoryStride::XY(8, 8), }] })) } let mut f = OpenOptions::new() .write(true) .append(true) .open(input_path()) .unwrap(); computer().write_init_script(&mut f).unwrap(); } fn destroy_computer() { let mut f = OpenOptions::new() .write(true) .append(true) .create(true) .open(input_path()) .unwrap(); computer().write_destroy_script(&mut f).unwrap(); }
{ let mut p = server_path(); p.push("input"); p }
identifier_body
percent_encoding.rs
// Copyright 2013-2014 Simon Sapin. // // 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. #[path = "encode_sets.rs"] mod encode_sets; /// Represents a set of characters / bytes that should be percent-encoded. /// /// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set). /// /// Different characters need to be encoded in different parts of an URL. /// For example, a literal `?` question mark in an URL’s path would indicate /// the start of the query string. /// A question mark meant to be part of the path therefore needs to be percent-encoded. /// In the query string however, a question mark does not have any special meaning /// and does not need to be percent-encoded. /// /// Since the implementation details of `EncodeSet` are private, /// the set of available encode sets is not extensible beyond the ones /// provided here. /// If you need a different encode set, /// please [file a bug](https://github.com/servo/rust-url/issues) /// explaining the use case. #[derive(Copy, Clone)] pub struct EncodeSet { map: &'static [&'static str; 256], } /// This encode set is used for fragment identifier and non-relative scheme data. pub static SIMPLE_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::SIMPLE }; /// This encode set is used in the URL parser for query strings. pub static QUERY_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::QUERY }; /// This encode set is used for path components. pub static DEFAULT_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::DEFAULT }; /// This encode set is used in the URL parser for usernames and passwords. pub static USERINFO_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERINFO }; /// This encode set should be used when setting the password field of a parsed URL. pub static PASSWORD_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::PASSWORD }; /// This encode set should be used when setting the username field of a parsed URL.
}; /// Percent-encode the given bytes, and push the result to `output`. /// /// The pushed strings are within the ASCII range. #[inline] pub fn percent_encode_to(input: &[u8], encode_set: EncodeSet, output: &mut String) { for &byte in input { output.push_str(encode_set.map[byte as usize]) } } /// Percent-encode the given bytes. /// /// The returned string is within the ASCII range. #[inline] pub fn percent_encode(input: &[u8], encode_set: EncodeSet) -> String { let mut output = String::new(); percent_encode_to(input, encode_set, &mut output); output } /// Percent-encode the UTF-8 encoding of the given string, and push the result to `output`. /// /// The pushed strings are within the ASCII range. #[inline] pub fn utf8_percent_encode_to(input: &str, encode_set: EncodeSet, output: &mut String) { percent_encode_to(input.as_bytes(), encode_set, output) } /// Percent-encode the UTF-8 encoding of the given string. /// /// The returned string is within the ASCII range. #[inline] pub fn utf8_percent_encode(input: &str, encode_set: EncodeSet) -> String { let mut output = String::new(); utf8_percent_encode_to(input, encode_set, &mut output); output } /// Percent-decode the given bytes, and push the result to `output`. pub fn percent_decode_to(input: &[u8], output: &mut Vec<u8>) { let mut i = 0; while i < input.len() { let c = input[i]; if c == b'%' && i + 2 < input.len() { if let (Some(h), Some(l)) = (from_hex(input[i + 1]), from_hex(input[i + 2])) { output.push(h * 0x10 + l); i += 3; continue } } output.push(c); i += 1; } } /// Percent-decode the given bytes. #[inline] pub fn percent_decode(input: &[u8]) -> Vec<u8> { let mut output = Vec::new(); percent_decode_to(input, &mut output); output } /// Percent-decode the given bytes, and decode the result as UTF-8. /// /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences /// will be replaced � U+FFFD, the replacement character. #[inline] pub fn lossy_utf8_percent_decode(input: &[u8]) -> String { String::from_utf8_lossy(&percent_decode(input)).to_string() } #[inline] pub fn from_hex(byte: u8) -> Option<u8> { match byte { b'0'... b'9' => Some(byte - b'0'), // 0..9 b'A'... b'F' => Some(byte + 10 - b'A'), // A..F b'a'... b'f' => Some(byte + 10 - b'a'), // a..f _ => None } }
pub static USERNAME_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERNAME }; /// This encode set is used in `application/x-www-form-urlencoded` serialization. pub static FORM_URLENCODED_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::FORM_URLENCODED,
random_line_split
percent_encoding.rs
// Copyright 2013-2014 Simon Sapin. // // 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. #[path = "encode_sets.rs"] mod encode_sets; /// Represents a set of characters / bytes that should be percent-encoded. /// /// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set). /// /// Different characters need to be encoded in different parts of an URL. /// For example, a literal `?` question mark in an URL’s path would indicate /// the start of the query string. /// A question mark meant to be part of the path therefore needs to be percent-encoded. /// In the query string however, a question mark does not have any special meaning /// and does not need to be percent-encoded. /// /// Since the implementation details of `EncodeSet` are private, /// the set of available encode sets is not extensible beyond the ones /// provided here. /// If you need a different encode set, /// please [file a bug](https://github.com/servo/rust-url/issues) /// explaining the use case. #[derive(Copy, Clone)] pub struct EncodeSet { map: &'static [&'static str; 256], } /// This encode set is used for fragment identifier and non-relative scheme data. pub static SIMPLE_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::SIMPLE }; /// This encode set is used in the URL parser for query strings. pub static QUERY_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::QUERY }; /// This encode set is used for path components. pub static DEFAULT_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::DEFAULT }; /// This encode set is used in the URL parser for usernames and passwords. pub static USERINFO_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERINFO }; /// This encode set should be used when setting the password field of a parsed URL. pub static PASSWORD_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::PASSWORD }; /// This encode set should be used when setting the username field of a parsed URL. pub static USERNAME_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERNAME }; /// This encode set is used in `application/x-www-form-urlencoded` serialization. pub static FORM_URLENCODED_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::FORM_URLENCODED, }; /// Percent-encode the given bytes, and push the result to `output`. /// /// The pushed strings are within the ASCII range. #[inline] pub fn percent_encode_to(input: &[u8], encode_set: EncodeSet, output: &mut String) { for &byte in input { output.push_str(encode_set.map[byte as usize]) } } /// Percent-encode the given bytes. /// /// The returned string is within the ASCII range. #[inline] pub fn percent_encode(input: &[u8], encode_set: EncodeSet) -> String { let mut output = String::new(); percent_encode_to(input, encode_set, &mut output); output } /// Percent-encode the UTF-8 encoding of the given string, and push the result to `output`. /// /// The pushed strings are within the ASCII range. #[inline] pub fn utf8_percent_encode_to(input: &str, encode_set: EncodeSet, output: &mut String) { percent_encode_to(input.as_bytes(), encode_set, output) } /// Percent-encode the UTF-8 encoding of the given string. /// /// The returned string is within the ASCII range. #[inline] pub fn utf8_percent_encode(input: &str, encode_set: EncodeSet) -> String { let mut output = String::new(); utf8_percent_encode_to(input, encode_set, &mut output); output } /// Percent-decode the given bytes, and push the result to `output`. pub fn percent_decode_to(input: &[u8], output: &mut Vec<u8>) { let mut i = 0; while i < input.len() { let c = input[i]; if c == b'%' && i + 2 < input.len() { if let (Some(h), Some(l)) = (from_hex(input[i + 1]), from_hex(input[i + 2])) { output.push(h * 0x10 + l); i += 3; continue } } output.push(c); i += 1; } } /// Percent-decode the given bytes. #[inline] pub fn percent_decode(input: &[u8]) -> Vec<u8> { let mut output = Vec::new(); percent_decode_to(input, &mut output); output } /// Percent-decode the given bytes, and decode the result as UTF-8. /// /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences /// will be replaced � U+FFFD, the replacement character. #[inline] pub fn lossy_utf8_percent_decode(input: &[u8]) -> String { String::from_utf8_lossy(&percent_decode(input)).to_string() } #[inline] pub fn from_hex(byte: u8) -> Option<u8> { ma
tch byte { b'0' ... b'9' => Some(byte - b'0'), // 0..9 b'A' ... b'F' => Some(byte + 10 - b'A'), // A..F b'a' ... b'f' => Some(byte + 10 - b'a'), // a..f _ => None } }
identifier_body
percent_encoding.rs
// Copyright 2013-2014 Simon Sapin. // // 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. #[path = "encode_sets.rs"] mod encode_sets; /// Represents a set of characters / bytes that should be percent-encoded. /// /// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set). /// /// Different characters need to be encoded in different parts of an URL. /// For example, a literal `?` question mark in an URL’s path would indicate /// the start of the query string. /// A question mark meant to be part of the path therefore needs to be percent-encoded. /// In the query string however, a question mark does not have any special meaning /// and does not need to be percent-encoded. /// /// Since the implementation details of `EncodeSet` are private, /// the set of available encode sets is not extensible beyond the ones /// provided here. /// If you need a different encode set, /// please [file a bug](https://github.com/servo/rust-url/issues) /// explaining the use case. #[derive(Copy, Clone)] pub struct En
map: &'static [&'static str; 256], } /// This encode set is used for fragment identifier and non-relative scheme data. pub static SIMPLE_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::SIMPLE }; /// This encode set is used in the URL parser for query strings. pub static QUERY_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::QUERY }; /// This encode set is used for path components. pub static DEFAULT_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::DEFAULT }; /// This encode set is used in the URL parser for usernames and passwords. pub static USERINFO_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERINFO }; /// This encode set should be used when setting the password field of a parsed URL. pub static PASSWORD_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::PASSWORD }; /// This encode set should be used when setting the username field of a parsed URL. pub static USERNAME_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::USERNAME }; /// This encode set is used in `application/x-www-form-urlencoded` serialization. pub static FORM_URLENCODED_ENCODE_SET: EncodeSet = EncodeSet { map: &encode_sets::FORM_URLENCODED, }; /// Percent-encode the given bytes, and push the result to `output`. /// /// The pushed strings are within the ASCII range. #[inline] pub fn percent_encode_to(input: &[u8], encode_set: EncodeSet, output: &mut String) { for &byte in input { output.push_str(encode_set.map[byte as usize]) } } /// Percent-encode the given bytes. /// /// The returned string is within the ASCII range. #[inline] pub fn percent_encode(input: &[u8], encode_set: EncodeSet) -> String { let mut output = String::new(); percent_encode_to(input, encode_set, &mut output); output } /// Percent-encode the UTF-8 encoding of the given string, and push the result to `output`. /// /// The pushed strings are within the ASCII range. #[inline] pub fn utf8_percent_encode_to(input: &str, encode_set: EncodeSet, output: &mut String) { percent_encode_to(input.as_bytes(), encode_set, output) } /// Percent-encode the UTF-8 encoding of the given string. /// /// The returned string is within the ASCII range. #[inline] pub fn utf8_percent_encode(input: &str, encode_set: EncodeSet) -> String { let mut output = String::new(); utf8_percent_encode_to(input, encode_set, &mut output); output } /// Percent-decode the given bytes, and push the result to `output`. pub fn percent_decode_to(input: &[u8], output: &mut Vec<u8>) { let mut i = 0; while i < input.len() { let c = input[i]; if c == b'%' && i + 2 < input.len() { if let (Some(h), Some(l)) = (from_hex(input[i + 1]), from_hex(input[i + 2])) { output.push(h * 0x10 + l); i += 3; continue } } output.push(c); i += 1; } } /// Percent-decode the given bytes. #[inline] pub fn percent_decode(input: &[u8]) -> Vec<u8> { let mut output = Vec::new(); percent_decode_to(input, &mut output); output } /// Percent-decode the given bytes, and decode the result as UTF-8. /// /// This is “lossy”: invalid UTF-8 percent-encoded byte sequences /// will be replaced � U+FFFD, the replacement character. #[inline] pub fn lossy_utf8_percent_decode(input: &[u8]) -> String { String::from_utf8_lossy(&percent_decode(input)).to_string() } #[inline] pub fn from_hex(byte: u8) -> Option<u8> { match byte { b'0'... b'9' => Some(byte - b'0'), // 0..9 b'A'... b'F' => Some(byte + 10 - b'A'), // A..F b'a'... b'f' => Some(byte + 10 - b'a'), // a..f _ => None } }
codeSet {
identifier_name
serviceworkercontainer.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::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{ServiceWorkerContainerMethods, Wrap}; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::str::USVString; use dom::eventtarget::EventTarget; use dom::serviceworker::ServiceWorker; use dom::serviceworkerregistration::ServiceWorkerRegistration; use script_thread::ScriptThread; use std::ascii::AsciiExt; use std::default::Default; #[dom_struct] pub struct ServiceWorkerContainer { eventtarget: EventTarget, controller: MutNullableHeap<JS<ServiceWorker>>, } impl ServiceWorkerContainer { fn new_inherited() -> ServiceWorkerContainer { ServiceWorkerContainer { eventtarget: EventTarget::new_inherited(), controller: Default::default(), } } pub fn new(global: GlobalRef) -> Root<ServiceWorkerContainer> { reflect_dom_object(box ServiceWorkerContainer::new_inherited(), global, Wrap) } } pub trait Controllable { fn set_controller(&self, active_worker: &ServiceWorker); } impl Controllable for ServiceWorkerContainer { fn set_controller(&self, active_worker: &ServiceWorker) { self.controller.set(Some(active_worker)); self.upcast::<EventTarget>().fire_simple_event("controllerchange"); } } impl ServiceWorkerContainerMethods for ServiceWorkerContainer { // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-container-controller-attribute fn GetController(&self) -> Option<Root<ServiceWorker>> { return self.controller.get() } // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-container-register-method fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Fallible<Root<ServiceWorkerRegistration>>
let &USVString(ref inner_scope) = scope; match self.global().r().api_base_url().join(inner_scope) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid scope URL".to_owned())) } }, None => script_url.join("./").unwrap() }; // Step 11 match scope.scheme() { "https" | "http" => {}, _ => return Err(Error::Type("Only secure origins are allowed".to_owned())) } // Step 12 if scope.path().to_ascii_lowercase().contains("%2f") || scope.path().to_ascii_lowercase().contains("%5c") { return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); } let scope_str = scope.as_str().to_owned(); let worker_registration = ServiceWorkerRegistration::new(self.global().r(), script_url, scope_str.clone(), self); ScriptThread::set_registration(scope, &*worker_registration, self.global().r().pipeline()); Ok(worker_registration) } }
{ let USVString(ref script_url) = script_url; // Step 3-4 let script_url = match self.global().r().api_base_url().join(script_url) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid script URL".to_owned())) }; // Step 5 match script_url.scheme() { "https" | "http" => {}, _ => return Err(Error::Type("Only secure origins are allowed".to_owned())) } // Step 6 if script_url.path().to_ascii_lowercase().contains("%2f") || script_url.path().to_ascii_lowercase().contains("%5c") { return Err(Error::Type("Script URL contains forbidden characters".to_owned())); } // Step 8-9 let scope = match options.scope { Some(ref scope) => {
identifier_body
serviceworkercontainer.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::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{ServiceWorkerContainerMethods, Wrap}; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::str::USVString; use dom::eventtarget::EventTarget; use dom::serviceworker::ServiceWorker; use dom::serviceworkerregistration::ServiceWorkerRegistration; use script_thread::ScriptThread; use std::ascii::AsciiExt; use std::default::Default; #[dom_struct] pub struct ServiceWorkerContainer { eventtarget: EventTarget, controller: MutNullableHeap<JS<ServiceWorker>>, } impl ServiceWorkerContainer { fn new_inherited() -> ServiceWorkerContainer { ServiceWorkerContainer { eventtarget: EventTarget::new_inherited(), controller: Default::default(), } } pub fn new(global: GlobalRef) -> Root<ServiceWorkerContainer> { reflect_dom_object(box ServiceWorkerContainer::new_inherited(), global, Wrap) } } pub trait Controllable { fn set_controller(&self, active_worker: &ServiceWorker); } impl Controllable for ServiceWorkerContainer { fn set_controller(&self, active_worker: &ServiceWorker) { self.controller.set(Some(active_worker)); self.upcast::<EventTarget>().fire_simple_event("controllerchange"); } } impl ServiceWorkerContainerMethods for ServiceWorkerContainer { // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-container-controller-attribute fn GetController(&self) -> Option<Root<ServiceWorker>> { return self.controller.get() } // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-container-register-method fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Fallible<Root<ServiceWorkerRegistration>> { let USVString(ref script_url) = script_url; // Step 3-4 let script_url = match self.global().r().api_base_url().join(script_url) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid script URL".to_owned())) }; // Step 5 match script_url.scheme() { "https" | "http" => {}, _ => return Err(Error::Type("Only secure origins are allowed".to_owned())) } // Step 6 if script_url.path().to_ascii_lowercase().contains("%2f") || script_url.path().to_ascii_lowercase().contains("%5c") { return Err(Error::Type("Script URL contains forbidden characters".to_owned())); } // Step 8-9 let scope = match options.scope { Some(ref scope) => { let &USVString(ref inner_scope) = scope; match self.global().r().api_base_url().join(inner_scope) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid scope URL".to_owned())) } }, None => script_url.join("./").unwrap() }; // Step 11 match scope.scheme() { "https" | "http" => {}, _ => return Err(Error::Type("Only secure origins are allowed".to_owned())) } // Step 12 if scope.path().to_ascii_lowercase().contains("%2f") || scope.path().to_ascii_lowercase().contains("%5c")
let scope_str = scope.as_str().to_owned(); let worker_registration = ServiceWorkerRegistration::new(self.global().r(), script_url, scope_str.clone(), self); ScriptThread::set_registration(scope, &*worker_registration, self.global().r().pipeline()); Ok(worker_registration) } }
{ return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); }
conditional_block
serviceworkercontainer.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::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{ServiceWorkerContainerMethods, Wrap}; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::str::USVString; use dom::eventtarget::EventTarget; use dom::serviceworker::ServiceWorker; use dom::serviceworkerregistration::ServiceWorkerRegistration; use script_thread::ScriptThread; use std::ascii::AsciiExt; use std::default::Default; #[dom_struct] pub struct ServiceWorkerContainer { eventtarget: EventTarget, controller: MutNullableHeap<JS<ServiceWorker>>, } impl ServiceWorkerContainer { fn
() -> ServiceWorkerContainer { ServiceWorkerContainer { eventtarget: EventTarget::new_inherited(), controller: Default::default(), } } pub fn new(global: GlobalRef) -> Root<ServiceWorkerContainer> { reflect_dom_object(box ServiceWorkerContainer::new_inherited(), global, Wrap) } } pub trait Controllable { fn set_controller(&self, active_worker: &ServiceWorker); } impl Controllable for ServiceWorkerContainer { fn set_controller(&self, active_worker: &ServiceWorker) { self.controller.set(Some(active_worker)); self.upcast::<EventTarget>().fire_simple_event("controllerchange"); } } impl ServiceWorkerContainerMethods for ServiceWorkerContainer { // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-container-controller-attribute fn GetController(&self) -> Option<Root<ServiceWorker>> { return self.controller.get() } // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-container-register-method fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Fallible<Root<ServiceWorkerRegistration>> { let USVString(ref script_url) = script_url; // Step 3-4 let script_url = match self.global().r().api_base_url().join(script_url) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid script URL".to_owned())) }; // Step 5 match script_url.scheme() { "https" | "http" => {}, _ => return Err(Error::Type("Only secure origins are allowed".to_owned())) } // Step 6 if script_url.path().to_ascii_lowercase().contains("%2f") || script_url.path().to_ascii_lowercase().contains("%5c") { return Err(Error::Type("Script URL contains forbidden characters".to_owned())); } // Step 8-9 let scope = match options.scope { Some(ref scope) => { let &USVString(ref inner_scope) = scope; match self.global().r().api_base_url().join(inner_scope) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid scope URL".to_owned())) } }, None => script_url.join("./").unwrap() }; // Step 11 match scope.scheme() { "https" | "http" => {}, _ => return Err(Error::Type("Only secure origins are allowed".to_owned())) } // Step 12 if scope.path().to_ascii_lowercase().contains("%2f") || scope.path().to_ascii_lowercase().contains("%5c") { return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); } let scope_str = scope.as_str().to_owned(); let worker_registration = ServiceWorkerRegistration::new(self.global().r(), script_url, scope_str.clone(), self); ScriptThread::set_registration(scope, &*worker_registration, self.global().r().pipeline()); Ok(worker_registration) } }
new_inherited
identifier_name
serviceworkercontainer.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::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{ServiceWorkerContainerMethods, Wrap}; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::eventtarget::EventTarget; use dom::serviceworker::ServiceWorker; use dom::serviceworkerregistration::ServiceWorkerRegistration; use script_thread::ScriptThread; use std::ascii::AsciiExt; use std::default::Default; #[dom_struct] pub struct ServiceWorkerContainer { eventtarget: EventTarget, controller: MutNullableHeap<JS<ServiceWorker>>, } impl ServiceWorkerContainer { fn new_inherited() -> ServiceWorkerContainer { ServiceWorkerContainer { eventtarget: EventTarget::new_inherited(), controller: Default::default(), } } pub fn new(global: GlobalRef) -> Root<ServiceWorkerContainer> { reflect_dom_object(box ServiceWorkerContainer::new_inherited(), global, Wrap) } } pub trait Controllable { fn set_controller(&self, active_worker: &ServiceWorker); } impl Controllable for ServiceWorkerContainer { fn set_controller(&self, active_worker: &ServiceWorker) { self.controller.set(Some(active_worker)); self.upcast::<EventTarget>().fire_simple_event("controllerchange"); } } impl ServiceWorkerContainerMethods for ServiceWorkerContainer { // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-container-controller-attribute fn GetController(&self) -> Option<Root<ServiceWorker>> { return self.controller.get() } // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-container-register-method fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Fallible<Root<ServiceWorkerRegistration>> { let USVString(ref script_url) = script_url; // Step 3-4 let script_url = match self.global().r().api_base_url().join(script_url) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid script URL".to_owned())) }; // Step 5 match script_url.scheme() { "https" | "http" => {}, _ => return Err(Error::Type("Only secure origins are allowed".to_owned())) } // Step 6 if script_url.path().to_ascii_lowercase().contains("%2f") || script_url.path().to_ascii_lowercase().contains("%5c") { return Err(Error::Type("Script URL contains forbidden characters".to_owned())); } // Step 8-9 let scope = match options.scope { Some(ref scope) => { let &USVString(ref inner_scope) = scope; match self.global().r().api_base_url().join(inner_scope) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid scope URL".to_owned())) } }, None => script_url.join("./").unwrap() }; // Step 11 match scope.scheme() { "https" | "http" => {}, _ => return Err(Error::Type("Only secure origins are allowed".to_owned())) } // Step 12 if scope.path().to_ascii_lowercase().contains("%2f") || scope.path().to_ascii_lowercase().contains("%5c") { return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); } let scope_str = scope.as_str().to_owned(); let worker_registration = ServiceWorkerRegistration::new(self.global().r(), script_url, scope_str.clone(), self); ScriptThread::set_registration(scope, &*worker_registration, self.global().r().pipeline()); Ok(worker_registration) } }
use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::str::USVString;
random_line_split
macro-stmt.rs
// Copyright 2012-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. // ignore-pretty - token trees can't pretty print macro_rules! myfn { ( $f:ident, ( $( $x:ident ),* ), $body:block ) => ( fn $f( $( $x : int),* ) -> int $body ) } myfn!(add, (a,b), { return a+b; } ); pub fn
() { macro_rules! mylet { ($x:ident, $val:expr) => ( let $x = $val; ) } mylet!(y, 8i*2); assert_eq!(y, 16i); myfn!(mult, (a,b), { a*b } ); assert_eq!(mult(2, add(4,4)), 16); macro_rules! actually_an_expr_macro { () => ( 16i ) } assert_eq!({ actually_an_expr_macro!() }, 16i); }
main
identifier_name
macro-stmt.rs
// Copyright 2012-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. // ignore-pretty - token trees can't pretty print macro_rules! myfn { ( $f:ident, ( $( $x:ident ),* ), $body:block ) => ( fn $f( $( $x : int),* ) -> int $body ) } myfn!(add, (a,b), { return a+b; } ); pub fn main()
}
{ macro_rules! mylet { ($x:ident, $val:expr) => ( let $x = $val; ) } mylet!(y, 8i*2); assert_eq!(y, 16i); myfn!(mult, (a,b), { a*b } ); assert_eq!(mult(2, add(4,4)), 16); macro_rules! actually_an_expr_macro { () => ( 16i ) } assert_eq!({ actually_an_expr_macro!() }, 16i);
identifier_body
macro-stmt.rs
// Copyright 2012-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. // ignore-pretty - token trees can't pretty print macro_rules! myfn { ( $f:ident, ( $( $x:ident ),* ), $body:block ) => ( fn $f( $( $x : int),* ) -> int $body ) } myfn!(add, (a,b), { return a+b; } ); pub fn main() { macro_rules! mylet { ($x:ident, $val:expr) => ( let $x = $val; ) } mylet!(y, 8i*2); assert_eq!(y, 16i); myfn!(mult, (a,b), { a*b } ); assert_eq!(mult(2, add(4,4)), 16); macro_rules! actually_an_expr_macro { () => ( 16i ) } assert_eq!({ actually_an_expr_macro!() }, 16i);
}
random_line_split
issue-52050.rs
// Copyright 2015 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(specialization)] // Regression test for #52050: when inserting the blanket impl `I` // into the tree, we had to replace the child node for `Foo`, which // led to the structure of the tree being messed up. use std::iter::Iterator; trait IntoPyDictPointer { } struct Foo { } impl Iterator for Foo { type Item = (); fn next(&mut self) -> Option<()> { None } } impl IntoPyDictPointer for Foo { } impl<I> IntoPyDictPointer for I where I: Iterator, { }
} fn main() { }
impl IntoPyDictPointer for () //~ ERROR conflicting implementations {
random_line_split
issue-52050.rs
// Copyright 2015 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(specialization)] // Regression test for #52050: when inserting the blanket impl `I` // into the tree, we had to replace the child node for `Foo`, which // led to the structure of the tree being messed up. use std::iter::Iterator; trait IntoPyDictPointer { } struct
{ } impl Iterator for Foo { type Item = (); fn next(&mut self) -> Option<()> { None } } impl IntoPyDictPointer for Foo { } impl<I> IntoPyDictPointer for I where I: Iterator, { } impl IntoPyDictPointer for () //~ ERROR conflicting implementations { } fn main() { }
Foo
identifier_name
camera.rs
use glutin::Window; use cgmath::{Point2, Vector2, EuclideanSpace}; #[derive(Debug, Clone)] pub struct Camera { pub position: Point2<f32>, pub size: Vector2<f32>, pub translate: Vector2<f32>, pub scale: Vector2<f32>, } impl Camera { pub fn new(position: Point2<f32>, size: Vector2<f32>, window: &Window) -> Self { let mut camera = Camera { position: position, size: size, translate: Vector2::new(0., 0.), scale: Vector2::new(1., 1.), }; camera.update_transform(window); camera } pub fn update_transform(&mut self, window: &Window) { let (w, h) = window.get_inner_size_pixels().unwrap(); let window_aspect_ratio = w as f32 / h as f32; let camera_aspect_ratio = self.size.x / self.size.y; let aspect_ratio = window_aspect_ratio / camera_aspect_ratio; let size = if aspect_ratio >= 1. { Vector2::new(self.size.x * aspect_ratio, self.size.y) } else { Vector2::new(self.size.x, self.size.y / aspect_ratio) }; self.translate = -self.position.to_vec(); self.scale = Vector2::new(2. / size.x, 2. / size.y); } pub fn window_point_to_gl(p: Point2<i32>, window: &Window) -> Point2<f32>
pub fn window_vector_to_gl(v: Vector2<i32>, window: &Window) -> Vector2<f32> { let (w, h) = window.get_inner_size_pixels().unwrap(); Vector2 { x: (v.x as f32 / w as f32), y: -(v.y as f32 / h as f32), } } pub fn window_point_to_world(&self, p: Point2<i32>, window: &Window) -> Point2<f32> { let gl = Self::window_point_to_gl(p, window); Point2 { x: gl.x / self.scale.x - self.translate.x, y: gl.y / self.scale.y - self.translate.y, } } pub fn window_vector_to_world(&self, v: Vector2<i32>, window: &Window) -> Vector2<f32> { let gl = Self::window_vector_to_gl(v, window); Vector2 { x: gl.x / self.scale.x, y: gl.y / self.scale.y, } } } gfx_defines! { constant Locals { translate: [f32; 2] = "u_Translate", scale: [f32; 2] = "u_Scale", } }
{ let (w, h) = window.get_inner_size_pixels().unwrap(); Point2 { x: (p.x as f32 / w as f32) * 2.0 - 1.0, y: 1.0 - (p.y as f32 / h as f32) * 2.0, } }
identifier_body
camera.rs
use glutin::Window; use cgmath::{Point2, Vector2, EuclideanSpace}; #[derive(Debug, Clone)] pub struct
{ pub position: Point2<f32>, pub size: Vector2<f32>, pub translate: Vector2<f32>, pub scale: Vector2<f32>, } impl Camera { pub fn new(position: Point2<f32>, size: Vector2<f32>, window: &Window) -> Self { let mut camera = Camera { position: position, size: size, translate: Vector2::new(0., 0.), scale: Vector2::new(1., 1.), }; camera.update_transform(window); camera } pub fn update_transform(&mut self, window: &Window) { let (w, h) = window.get_inner_size_pixels().unwrap(); let window_aspect_ratio = w as f32 / h as f32; let camera_aspect_ratio = self.size.x / self.size.y; let aspect_ratio = window_aspect_ratio / camera_aspect_ratio; let size = if aspect_ratio >= 1. { Vector2::new(self.size.x * aspect_ratio, self.size.y) } else { Vector2::new(self.size.x, self.size.y / aspect_ratio) }; self.translate = -self.position.to_vec(); self.scale = Vector2::new(2. / size.x, 2. / size.y); } pub fn window_point_to_gl(p: Point2<i32>, window: &Window) -> Point2<f32> { let (w, h) = window.get_inner_size_pixels().unwrap(); Point2 { x: (p.x as f32 / w as f32) * 2.0 - 1.0, y: 1.0 - (p.y as f32 / h as f32) * 2.0, } } pub fn window_vector_to_gl(v: Vector2<i32>, window: &Window) -> Vector2<f32> { let (w, h) = window.get_inner_size_pixels().unwrap(); Vector2 { x: (v.x as f32 / w as f32), y: -(v.y as f32 / h as f32), } } pub fn window_point_to_world(&self, p: Point2<i32>, window: &Window) -> Point2<f32> { let gl = Self::window_point_to_gl(p, window); Point2 { x: gl.x / self.scale.x - self.translate.x, y: gl.y / self.scale.y - self.translate.y, } } pub fn window_vector_to_world(&self, v: Vector2<i32>, window: &Window) -> Vector2<f32> { let gl = Self::window_vector_to_gl(v, window); Vector2 { x: gl.x / self.scale.x, y: gl.y / self.scale.y, } } } gfx_defines! { constant Locals { translate: [f32; 2] = "u_Translate", scale: [f32; 2] = "u_Scale", } }
Camera
identifier_name
camera.rs
use glutin::Window; use cgmath::{Point2, Vector2, EuclideanSpace}; #[derive(Debug, Clone)] pub struct Camera { pub position: Point2<f32>, pub size: Vector2<f32>, pub translate: Vector2<f32>, pub scale: Vector2<f32>, } impl Camera { pub fn new(position: Point2<f32>, size: Vector2<f32>, window: &Window) -> Self { let mut camera = Camera { position: position, size: size, translate: Vector2::new(0., 0.), scale: Vector2::new(1., 1.), }; camera.update_transform(window); camera } pub fn update_transform(&mut self, window: &Window) { let (w, h) = window.get_inner_size_pixels().unwrap(); let window_aspect_ratio = w as f32 / h as f32;
let camera_aspect_ratio = self.size.x / self.size.y; let aspect_ratio = window_aspect_ratio / camera_aspect_ratio; let size = if aspect_ratio >= 1. { Vector2::new(self.size.x * aspect_ratio, self.size.y) } else { Vector2::new(self.size.x, self.size.y / aspect_ratio) }; self.translate = -self.position.to_vec(); self.scale = Vector2::new(2. / size.x, 2. / size.y); } pub fn window_point_to_gl(p: Point2<i32>, window: &Window) -> Point2<f32> { let (w, h) = window.get_inner_size_pixels().unwrap(); Point2 { x: (p.x as f32 / w as f32) * 2.0 - 1.0, y: 1.0 - (p.y as f32 / h as f32) * 2.0, } } pub fn window_vector_to_gl(v: Vector2<i32>, window: &Window) -> Vector2<f32> { let (w, h) = window.get_inner_size_pixels().unwrap(); Vector2 { x: (v.x as f32 / w as f32), y: -(v.y as f32 / h as f32), } } pub fn window_point_to_world(&self, p: Point2<i32>, window: &Window) -> Point2<f32> { let gl = Self::window_point_to_gl(p, window); Point2 { x: gl.x / self.scale.x - self.translate.x, y: gl.y / self.scale.y - self.translate.y, } } pub fn window_vector_to_world(&self, v: Vector2<i32>, window: &Window) -> Vector2<f32> { let gl = Self::window_vector_to_gl(v, window); Vector2 { x: gl.x / self.scale.x, y: gl.y / self.scale.y, } } } gfx_defines! { constant Locals { translate: [f32; 2] = "u_Translate", scale: [f32; 2] = "u_Scale", } }
random_line_split
camera.rs
use glutin::Window; use cgmath::{Point2, Vector2, EuclideanSpace}; #[derive(Debug, Clone)] pub struct Camera { pub position: Point2<f32>, pub size: Vector2<f32>, pub translate: Vector2<f32>, pub scale: Vector2<f32>, } impl Camera { pub fn new(position: Point2<f32>, size: Vector2<f32>, window: &Window) -> Self { let mut camera = Camera { position: position, size: size, translate: Vector2::new(0., 0.), scale: Vector2::new(1., 1.), }; camera.update_transform(window); camera } pub fn update_transform(&mut self, window: &Window) { let (w, h) = window.get_inner_size_pixels().unwrap(); let window_aspect_ratio = w as f32 / h as f32; let camera_aspect_ratio = self.size.x / self.size.y; let aspect_ratio = window_aspect_ratio / camera_aspect_ratio; let size = if aspect_ratio >= 1.
else { Vector2::new(self.size.x, self.size.y / aspect_ratio) }; self.translate = -self.position.to_vec(); self.scale = Vector2::new(2. / size.x, 2. / size.y); } pub fn window_point_to_gl(p: Point2<i32>, window: &Window) -> Point2<f32> { let (w, h) = window.get_inner_size_pixels().unwrap(); Point2 { x: (p.x as f32 / w as f32) * 2.0 - 1.0, y: 1.0 - (p.y as f32 / h as f32) * 2.0, } } pub fn window_vector_to_gl(v: Vector2<i32>, window: &Window) -> Vector2<f32> { let (w, h) = window.get_inner_size_pixels().unwrap(); Vector2 { x: (v.x as f32 / w as f32), y: -(v.y as f32 / h as f32), } } pub fn window_point_to_world(&self, p: Point2<i32>, window: &Window) -> Point2<f32> { let gl = Self::window_point_to_gl(p, window); Point2 { x: gl.x / self.scale.x - self.translate.x, y: gl.y / self.scale.y - self.translate.y, } } pub fn window_vector_to_world(&self, v: Vector2<i32>, window: &Window) -> Vector2<f32> { let gl = Self::window_vector_to_gl(v, window); Vector2 { x: gl.x / self.scale.x, y: gl.y / self.scale.y, } } } gfx_defines! { constant Locals { translate: [f32; 2] = "u_Translate", scale: [f32; 2] = "u_Scale", } }
{ Vector2::new(self.size.x * aspect_ratio, self.size.y) }
conditional_block
expr-block-generic.rs
// Copyright 2012-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. fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool
fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool, _>(true, compare_bool); } #[derive(Clone)] struct Pair { a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair, _>(Pair {a: 1, b: 2}, compare_rec); } pub fn main() { test_bool(); test_rec(); }
{ let actual: T = { expected.clone() }; assert!(eq(expected, actual)); }
identifier_body
expr-block-generic.rs
// Copyright 2012-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. fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool { let actual: T = { expected.clone() }; assert!(eq(expected, actual)); } fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool, _>(true, compare_bool); } #[derive(Clone)] struct Pair { a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b
} pub fn main() { test_bool(); test_rec(); }
} test_generic::<Pair, _>(Pair {a: 1, b: 2}, compare_rec);
random_line_split
expr-block-generic.rs
// Copyright 2012-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. fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool { let actual: T = { expected.clone() }; assert!(eq(expected, actual)); } fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool, _>(true, compare_bool); } #[derive(Clone)] struct
{ a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair, _>(Pair {a: 1, b: 2}, compare_rec); } pub fn main() { test_bool(); test_rec(); }
Pair
identifier_name
polygon.rs
//! Draw polygon use types::Color; use {types, triangulation, Graphics, DrawState}; use math::{Matrix2d, Scalar}; /// A polygon #[derive(Copy, Clone)] pub struct Polygon { /// The color of the polygon pub color: Color, } impl Polygon { /// Creates new polygon pub fn new(color: Color) -> Polygon { Polygon { color: color } } /// Sets color. pub fn color(mut self, color: Color) -> Self { self.color = color; self } /// Draws polygon using the default method. #[inline(always)] pub fn draw<G>(&self, polygon: types::Polygon, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.polygon(self, polygon, draw_state, transform); } /// Draws polygon using triangulation. pub fn draw_tri<G>(&self, polygon: types::Polygon, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.tri_list(draw_state, &self.color, |f| { triangulation::with_polygon_tri_list(transform, polygon, |vertices| f(vertices)) }); } /// Draws tweened polygon with linear interpolation, using default method. #[inline(always)] pub fn draw_tween_lerp<G>(&self, polygons: types::Polygons, tween_factor: Scalar, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.polygon_tween_lerp(self, polygons, tween_factor, draw_state, transform); } /// Draws tweened polygon with linear interpolation, using triangulation. pub fn draw_tween_lerp_tri<G>(&self, polygons: types::Polygons, tween_factor: Scalar, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { if self.color[3] == 0.0
g.tri_list(draw_state, &self.color, |f| { triangulation::with_lerp_polygons_tri_list(transform, polygons, tween_factor, |vertices| f(vertices)) }); } } #[cfg(test)] mod test { use super::*; #[test] fn test_polygon() { let _polygon = Polygon::new([1.0; 4]).color([0.0; 4]); } }
{ return; }
conditional_block
polygon.rs
//! Draw polygon use types::Color; use {types, triangulation, Graphics, DrawState}; use math::{Matrix2d, Scalar}; /// A polygon #[derive(Copy, Clone)] pub struct Polygon { /// The color of the polygon pub color: Color, } impl Polygon { /// Creates new polygon pub fn new(color: Color) -> Polygon { Polygon { color: color } } /// Sets color. pub fn color(mut self, color: Color) -> Self { self.color = color; self } /// Draws polygon using the default method. #[inline(always)] pub fn draw<G>(&self, polygon: types::Polygon, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.polygon(self, polygon, draw_state, transform); } /// Draws polygon using triangulation. pub fn draw_tri<G>(&self, polygon: types::Polygon, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.tri_list(draw_state, &self.color, |f| { triangulation::with_polygon_tri_list(transform, polygon, |vertices| f(vertices)) }); } /// Draws tweened polygon with linear interpolation, using default method. #[inline(always)] pub fn draw_tween_lerp<G>(&self, polygons: types::Polygons, tween_factor: Scalar, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics { g.polygon_tween_lerp(self, polygons, tween_factor, draw_state, transform); } /// Draws tweened polygon with linear interpolation, using triangulation. pub fn draw_tween_lerp_tri<G>(&self, polygons: types::Polygons, tween_factor: Scalar, draw_state: &DrawState, transform: Matrix2d, g: &mut G) where G: Graphics
} #[cfg(test)] mod test { use super::*; #[test] fn test_polygon() { let _polygon = Polygon::new([1.0; 4]).color([0.0; 4]); } }
{ if self.color[3] == 0.0 { return; } g.tri_list(draw_state, &self.color, |f| { triangulation::with_lerp_polygons_tri_list(transform, polygons, tween_factor, |vertices| f(vertices)) }); }
identifier_body