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
shutdown.rs
extern crate arg_parser; extern crate extra; extern crate syscall; use std::env; use std::io::{stderr, stdout, Error, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; use syscall::flag::{SIGTERM, SIGKILL}; const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#" NAME ...
.add_flag(&["r", "reboot"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } if parser.found("reboot") { syscall::kill(1, SIGTERM).map_err(|err| Error::from_raw_o...
random_line_split
shutdown.rs
extern crate arg_parser; extern crate extra; extern crate syscall; use std::env; use std::io::{stderr, stdout, Error, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; use syscall::flag::{SIGTERM, SIGKILL}; const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#" NAME ...
() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]) .add_flag(&["r", "reboot"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut ...
main
identifier_name
shutdown.rs
extern crate arg_parser; extern crate extra; extern crate syscall; use std::env; use std::io::{stderr, stdout, Error, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; use syscall::flag::{SIGTERM, SIGKILL}; const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#" NAME ...
}
{ let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]) .add_flag(&["r", "reboot"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut s...
identifier_body
main.rs
extern crate dotenv; extern crate rand; extern crate serenity; use std::env; use std::sync::Arc; use dotenv::dotenv; use rand::Rng; use serenity::framework::standard::*; use serenity::framework::StandardFramework; use serenity::model::prelude::*; use serenity::prelude::*; struct Handler; impl EventHandler for Handle...
let result = rand::thread_rng().gen_range(0, up) + 1; msg.reply(&format!("{}", result)).unwrap(); }) } }
random_line_split
main.rs
extern crate dotenv; extern crate rand; extern crate serenity; use std::env; use std::sync::Arc; use dotenv::dotenv; use rand::Rng; use serenity::framework::standard::*; use serenity::framework::StandardFramework; use serenity::model::prelude::*; use serenity::prelude::*; struct Handler; impl EventHandler for Handle...
(_: &mut Context, msg: &Message, cmd: &str) { msg.reply(&format!("{} is not a command.", cmd)).unwrap(); } struct Flip; impl Command for Flip { fn options(&self) -> Arc<CommandOptions> { let mut options = CommandOptions::default(); options.desc = Some("Flips a coin.".to_owned()); option...
unrecognised_command_handler
identifier_name
main.rs
extern crate dotenv; extern crate rand; extern crate serenity; use std::env; use std::sync::Arc; use dotenv::dotenv; use rand::Rng; use serenity::framework::standard::*; use serenity::framework::StandardFramework; use serenity::model::prelude::*; use serenity::prelude::*; struct Handler; impl EventHandler for Handle...
}
{ let upper_bound = match args.single() { Ok(num) => Ok(num), Err(ArgError::Eos) => Ok(6), Err(ArgError::Parse(err)) => Err(CommandError(format!("{}", err))), }; upper_bound.map(|up| { let result = rand::thread_rng().gen_range(0, up) + 1; ...
identifier_body
write_tuple.rs
use std::io::Write; use crate::pg::Pg; use crate::serialize::{self, Output}; /// Helper trait for writing tuples as named composite types /// /// This trait is essentially `ToSql<Record<ST>>` for tuples. /// While we can provide a valid body of `to_sql`, /// PostgreSQL doesn't allow the use of bind parameters for unn...
/// See trait documentation. fn write_tuple<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result; }
/// ``` pub trait WriteTuple<ST> {
random_line_split
lower_array_len.rs
// compile-flags: -Z mir-opt-level=4 // EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound.InstCombine.diff pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 { if index < slice.len() {...
() { let _ = array_bound(3, &[0, 1, 2, 3]); let mut tmp = [0, 1, 2, 3, 4]; let _ = array_bound_mut(3, &mut [0, 1, 2, 3]); let _ = array_len(&[0]); let _ = array_len_by_value([0, 2]); }
main
identifier_name
lower_array_len.rs
// compile-flags: -Z mir-opt-level=4 // EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound.InstCombine.diff pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 { if index < slice.len() {...
{ let _ = array_bound(3, &[0, 1, 2, 3]); let mut tmp = [0, 1, 2, 3, 4]; let _ = array_bound_mut(3, &mut [0, 1, 2, 3]); let _ = array_len(&[0]); let _ = array_len_by_value([0, 2]); }
identifier_body
lower_array_len.rs
// compile-flags: -Z mir-opt-level=4 // EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound.InstCombine.diff pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 { if index < slice.len() {...
} // EMIT_MIR lower_array_len.array_bound_mut.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound_mut.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound_mut.InstCombine.diff pub fn array_bound_mut<const N: usize>(index: usize, slice: &mut [u8; N]) -> u8 { if index < slice.len() { slice...
{ 42 }
conditional_block
lower_array_len.rs
// compile-flags: -Z mir-opt-level=4 // EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound.InstCombine.diff pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 { if index < slice.len() {...
// EMIT_MIR lower_array_len.array_len_by_value.InstCombine.diff pub fn array_len_by_value<const N: usize>(arr: [u8; N]) -> usize { arr.len() } fn main() { let _ = array_bound(3, &[0, 1, 2, 3]); let mut tmp = [0, 1, 2, 3, 4]; let _ = array_bound_mut(3, &mut [0, 1, 2, 3]); let _ = array_len(&[0]); ...
// EMIT_MIR lower_array_len.array_len_by_value.SimplifyLocals.diff
random_line_split
inherited_box.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, ge...
impl ToCss for SpecifiedValue { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { Ok(()) // Internal property } } #[inline] pub fn derive_from_display(context: &mut Context) { use super::display::computed_value::T as Display; if context.st...
pub fn get_initial_value() -> computed_value::T { SpecifiedValue(false) }
random_line_split
inherited_box.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, ge...
(context: &mut Context) { use super::display::computed_value::T as Display; if context.style().get_box().clone_display() == Display::none { context.mutate_style().mutate_inheritedbox() .set__servo_under_display_none(SpecifiedValue(true)); } } </%...
derive_from_display
identifier_name
inherited_box.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, ge...
} #[inline] pub fn derive_from_display(context: &mut Context) { use super::display::computed_value::T as Display; if context.style().get_box().clone_display() == Display::none { context.mutate_style().mutate_inheritedbox() .set__servo_under_dis...
{ Ok(()) // Internal property }
identifier_body
inherited_box.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, ge...
} </%helpers:longhand>
{ context.mutate_style().mutate_inheritedbox() .set__servo_under_display_none(SpecifiedValue(true)); }
conditional_block
unwrap_or_else_default.rs
//! Lint for `some_result_or_option.unwrap_or_else(Default::default)` use super::UNWRAP_OR_ELSE_DEFAULT; use clippy_utils::{ diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item, }; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::Lat...
<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, recv: &'tcx hir::Expr<'_>, u_arg: &'tcx hir::Expr<'_>, ) { // something.unwrap_or_else(Default::default) // ^^^^^^^^^- recv ^^^^^^^^^^^^^^^^- u_arg // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr let recv_ty = cx.typ...
check
identifier_name
unwrap_or_else_default.rs
//! Lint for `some_result_or_option.unwrap_or_else(Default::default)` use super::UNWRAP_OR_ELSE_DEFAULT; use clippy_utils::{ diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item, }; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::Lat...
expr.span, "use of `.unwrap_or_else(..)` to construct default value", "try", format!( "{}.unwrap_or_default()", snippet_with_applicability(cx, recv.span, "..", &mut applicability) ), a...
UNWRAP_OR_ELSE_DEFAULT,
random_line_split
unwrap_or_else_default.rs
//! Lint for `some_result_or_option.unwrap_or_else(Default::default)` use super::UNWRAP_OR_ELSE_DEFAULT; use clippy_utils::{ diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item, }; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::Lat...
format!( "{}.unwrap_or_default()", snippet_with_applicability(cx, recv.span, "..", &mut applicability) ), applicability, ); } } }
{ // something.unwrap_or_else(Default::default) // ^^^^^^^^^- recv ^^^^^^^^^^^^^^^^- u_arg // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr let recv_ty = cx.typeck_results().expr_ty(recv); let is_option = is_type_diagnostic_item(cx, recv_ty, sym::Option); let is_result = is_type_diag...
identifier_body
result.rs
mod checked { // For.ln() and.sqrt() use std::num::Float; // Mathematical "errors" we want to catch #[deriving(Show)] pub enum MathError { DivisionByZero, NegativeLogarithm, NegativeSquareRoot, } pub type MathResult = Result<f64, MathError>; pub fn div(x: f64, y...
}
random_line_split
result.rs
mod checked { // For.ln() and.sqrt() use std::num::Float; // Mathematical "errors" we want to catch #[deriving(Show)] pub enum MathError { DivisionByZero, NegativeLogarithm, NegativeSquareRoot, } pub type MathResult = Result<f64, MathError>; pub fn div(x: f64, y...
else { Ok(x.ln()) } } } // `op(x, y)` === `sqrt(ln(x / y))` fn op(x: f64, y: f64) -> f64 { // This is a three level match pyramid! match checked::div(x, y) { Err(why) => panic!("{}", why), Ok(ratio) => match checked::ln(ratio) { Err(why) => panic!("{}", why)...
{ Err(MathError::NegativeLogarithm) }
conditional_block
result.rs
mod checked { // For.ln() and.sqrt() use std::num::Float; // Mathematical "errors" we want to catch #[deriving(Show)] pub enum MathError { DivisionByZero, NegativeLogarithm, NegativeSquareRoot, } pub type MathResult = Result<f64, MathError>; pub fn div(x: f64, y...
{ // Will this fail? println!("{}", op(1.0, 10.0)); }
identifier_body
result.rs
mod checked { // For.ln() and.sqrt() use std::num::Float; // Mathematical "errors" we want to catch #[deriving(Show)] pub enum MathError { DivisionByZero, NegativeLogarithm, NegativeSquareRoot, } pub type MathResult = Result<f64, MathError>; pub fn div(x: f64, y...
(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeSquareRoot) } else { Ok(x.sqrt()) } } pub fn ln(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeLogarithm) } else { Ok(x.ln()) } } } // `...
sqrt
identifier_name
primitives.rs
extern crate libc; extern crate cpython; extern crate rustypy; use cpython::Python; #[test] fn primitives()
let arg = true; let answ = basics.rust_bind_bool_func(arg); assert_eq!(false, answ); let arg1 = String::from("String from Rust, "); let arg2 = 10; let answ = basics.other_prefix_tuple1((arg1, arg2)); assert_eq!((String::from("String from Rust, added this in Python!"), 20), a...
{ use test_package::rustypy_pybind::PyModules; let gil = Python::acquire_gil(); let py = gil.python(); let module: PyModules = PyModules::new(&py); let basics = module.basics.primitives; let arg = 1; let answ = basics.rust_bind_int_func(arg); assert_eq!(2, answ); let arg = 0.5; ...
identifier_body
primitives.rs
extern crate libc; extern crate cpython; extern crate rustypy; use cpython::Python; #[test] fn
() { use test_package::rustypy_pybind::PyModules; let gil = Python::acquire_gil(); let py = gil.python(); let module: PyModules = PyModules::new(&py); let basics = module.basics.primitives; let arg = 1; let answ = basics.rust_bind_int_func(arg); assert_eq!(2, answ); let arg = 0.5;...
primitives
identifier_name
primitives.rs
extern crate libc; extern crate cpython; extern crate rustypy; use cpython::Python; #[test] fn primitives() { use test_package::rustypy_pybind::PyModules; let gil = Python::acquire_gil(); let py = gil.python(); let module: PyModules = PyModules::new(&py); let basics = module.basics.primitives; ...
answ); let arg = true; let answ = basics.rust_bind_bool_func(arg); assert_eq!(false, answ); let arg1 = String::from("String from Rust, "); let arg2 = 10; let answ = basics.other_prefix_tuple1((arg1, arg2)); assert_eq!((String::from("String from Rust, added this in Python!"),...
let arg = String::from("String from Rust, "); let answ = basics.rust_bind_str_func(arg); assert_eq!(String::from("String from Rust, added this in Python!"),
random_line_split
unique-pat-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 ...
}
random_line_split
unique-pat-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 ...
{ assert!(match bar::u(box Foo{a: 10, b: 40}) { bar::u(box Foo{a: a, b: b}) => { a + (b as isize) } _ => { 66 } } == 50); }
identifier_body
unique-pat-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 ...
{ u(Box<Foo>), w(isize), } pub fn main() { assert!(match bar::u(box Foo{a: 10, b: 40}) { bar::u(box Foo{a: a, b: b}) => { a + (b as isize) } _ => { 66 } } == 50); }
bar
identifier_name
board.rs
#[derive(Debug, Copy, Clone, PartialEq)] pub enum PieceColor { White, Black, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GamePiece { pub color: PieceColor, pub crowned: bool, } impl GamePiece { pub fn new(color: PieceColor) -> GamePiece { GamePiece { color, ...
jumps.into_iter() } pub fn move_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut moves = Vec::new(); let Coordinate(x, y) = *self; if x >= 1 { moves.push(Coordinate(x - 1, y + 1)); } moves.push(Coordinate(x + 1, y + 1)); if y...
{ jumps.push(Coordinate(x - 2, y + 2)); }
conditional_block
board.rs
#[derive(Debug, Copy, Clone, PartialEq)] pub enum PieceColor { White, Black, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GamePiece { pub color: PieceColor, pub crowned: bool, } impl GamePiece { pub fn new(color: PieceColor) -> GamePiece { GamePiece { color, ...
(from: (usize, usize), to: (usize, usize)) -> Move { Move { from: Coordinate(from.0, from.1), to: Coordinate(to.0, to.1), } } }
new
identifier_name
board.rs
#[derive(Debug, Copy, Clone, PartialEq)] pub enum PieceColor { White, Black, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GamePiece { pub color: PieceColor, pub crowned: bool, } impl GamePiece { pub fn new(color: PieceColor) -> GamePiece { GamePiece { color, ...
}
{ Move { from: Coordinate(from.0, from.1), to: Coordinate(to.0, to.1), } }
identifier_body
board.rs
#[derive(Debug, Copy, Clone, PartialEq)] pub enum PieceColor { White, Black, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GamePiece { pub color: PieceColor, pub crowned: bool, } impl GamePiece { pub fn new(color: PieceColor) -> GamePiece { GamePiece { color, ...
#[derive(Debug, Clone, PartialEq, Copy)] pub struct Coordinate(pub usize, pub usize); impl Coordinate { pub fn on_board(self) -> bool { let Coordinate(x, y) = self; x <= 7 && y <= 7 } pub fn jump_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut jumps = Vec::new(); ...
} } }
random_line_split
bytecode.rs
use std::io::{Error, LineWriter, Write}; type Offset = usize; /// Subset of values that can be initialised when a chunk is created. /// They will be turned into proper values when the VM accesses them. #[derive(Debug)] pub enum Constant { Number(f64), Bool(bool), Nil, String(String), } type Line = usiz...
} else { line = chunk.lines[i]; try!(write!(out, "{:4}", line)); } try!(write!(out, " ")); try!{disassemble_instruction(instruction, chunk, out)}; } Ok(()) }
// Using the OpCode enum all the opcodes have the same size. // It is not space-efficient, but for now it's fine try!(write!(out, "{:04}", i)); if line == chunk.lines[i] { try!(write!(out, " |"));
random_line_split
bytecode.rs
use std::io::{Error, LineWriter, Write}; type Offset = usize; /// Subset of values that can be initialised when a chunk is created. /// They will be turned into proper values when the VM accesses them. #[derive(Debug)] pub enum Constant { Number(f64), Bool(bool), Nil, String(String), } type Line = usiz...
{ instructions: Vec<OpCode>, values: Vec<Constant>, lines: Vec<Line>, } impl Chunk { pub fn get(&self, index: usize) -> OpCode { self.instructions[index] } pub fn get_value(&self, index: usize) -> &Constant { &self.values[index] } /// Adds a new instruction to the chu...
Chunk
identifier_name
letter_frequency.rs
// Implements http://rosettacode.org/wiki/Letter_frequency #[cfg(not(test))] use std::io::fs::File; #[cfg(not(test))] use std::io::BufferedReader; use std::collections::HashMap; fn count_chars<T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> { let mut map: HashMap<char, uint> = HashMap::new(); for lett...
#[test] fn test_empty() { let map = count_chars("".chars()); assert!(map.len() == 0); } #[test] fn test_basic() { let map = count_chars("aaaabbbbc".chars()); assert!(map.len() == 3); assert!(*map.get(&'a') == 4); assert!(*map.get(&'b') == 4); assert!(*map.get(&'c') == 1); }
{ let file = File::open(&Path::new("resources/unixdict.txt")); let mut reader = BufferedReader::new(file); println!("{}", count_chars(reader.chars().map(|c| c.unwrap()))); }
identifier_body
letter_frequency.rs
// Implements http://rosettacode.org/wiki/Letter_frequency #[cfg(not(test))] use std::io::fs::File; #[cfg(not(test))] use std::io::BufferedReader; use std::collections::HashMap; fn
<T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> { let mut map: HashMap<char, uint> = HashMap::new(); for letter in chars { map.insert_or_update_with(letter, 1, |_, count| *count += 1); } map } #[cfg(not(test))] fn main() { let file = File::open(&Path::new("resources/unixdict.txt"))...
count_chars
identifier_name
letter_frequency.rs
// Implements http://rosettacode.org/wiki/Letter_frequency #[cfg(not(test))] use std::io::fs::File; #[cfg(not(test))] use std::io::BufferedReader; use std::collections::HashMap; fn count_chars<T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> { let mut map: HashMap<char, uint> = HashMap::new(); for lett...
let file = File::open(&Path::new("resources/unixdict.txt")); let mut reader = BufferedReader::new(file); println!("{}", count_chars(reader.chars().map(|c| c.unwrap()))); } #[test] fn test_empty() { let map = count_chars("".chars()); assert!(map.len() == 0); } #[test] fn test_basic() { let map...
} #[cfg(not(test))] fn main() {
random_line_split
htmllinkelement.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 crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Binding...
(&self, _rel: &str, href: &str, _sizes: &Option<String>) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let window = document.window(); if window.is_top_level() { let msg = EmbedderMsg::NewFav...
handle_favicon_url
identifier_name
htmllinkelement.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 crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Binding...
}, Err(e) => debug!("Parsing url {} failed: {}", href, e), } } } impl StylesheetOwner for HTMLLinkElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool>...
{ let msg = EmbedderMsg::NewFavicon(url.clone()); window.send_to_embedder(msg); }
conditional_block
htmllinkelement.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 crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Binding...
// https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn SetCrossOrigin(&self, value: Option<DOMString>) { set_cross_origin_attribute(self.upcast::<Element>(), value); } // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> {...
{ reflect_cross_origin_attribute(self.upcast::<Element>()) }
identifier_body
htmllinkelement.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 crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Binding...
use crate::stylesheet_loader::{StylesheetContextSource, StylesheetLoader, StylesheetOwner}; use cssparser::{Parser as CssParser, ParserInput}; use dom_struct::dom_struct; use embedder_traits::EmbedderMsg; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::borrow::ToOwned; u...
random_line_split
default_draw_state.rs
use draw_state::state::*; use DrawState; static DEFAULT_DRAW_STATE: &'static DrawState = &DrawState { primitive: Primitive { front_face: FrontFace::CounterClockwise, method: RasterMethod::Fill( CullFace::Nothing ), offset: None, }, ...
() -> &'static DrawState { DEFAULT_DRAW_STATE }
default_draw_state
identifier_name
default_draw_state.rs
use draw_state::state::*; use DrawState; static DEFAULT_DRAW_STATE: &'static DrawState = &DrawState { primitive: Primitive { front_face: FrontFace::CounterClockwise, method: RasterMethod::Fill( CullFace::Nothing ), offset: None, }, ...
{ DEFAULT_DRAW_STATE }
identifier_body
default_draw_state.rs
use draw_state::state::*; use DrawState; static DEFAULT_DRAW_STATE: &'static DrawState = &DrawState { primitive: Primitive { front_face: FrontFace::CounterClockwise, method: RasterMethod::Fill( CullFace::Nothing ), offset: None, }, ...
}
random_line_split
lib.rs
//! A library for using the Branch by Abstraction pattern to test for performance and correctness. //! //! # Examples //! ``` //! use dexter::*; //! struct ExamplePublisher; //! //! impl Publisher<Vec<char>, String, String> for ExamplePublisher { //! fn publish(&mut self, result: ExperimentResult<String, String>) {...
/// /// Returns the result of the current subject closure. pub fn carry_out<Pub: Publisher<P, Cr, Nr>>(mut self, mut param: P, publisher: &mut Pub) -> Cr { if!publisher.enabled() { return (self.current)(&param); } if let Some(mut setup) = self.setup { param = ...
self.ignore_if = Some(Box::new(ignore_if)); self } /// Carry out the experiment given a parameter and a publisher.
random_line_split
lib.rs
//! A library for using the Branch by Abstraction pattern to test for performance and correctness. //! //! # Examples //! ``` //! use dexter::*; //! struct ExamplePublisher; //! //! impl Publisher<Vec<char>, String, String> for ExamplePublisher { //! fn publish(&mut self, result: ExperimentResult<String, String>) {...
; let comparison = publisher.compare(&current_val.as_ref().unwrap(), &new_val.as_ref().unwrap()); publisher.publish(ExperimentResult::new( self.name, SubjectResult::new(current_duration as f64 * 1e-9, &current_val.as_ref().unwrap()), SubjectResult::new(new_duration ...
{ false }
conditional_block
lib.rs
//! A library for using the Branch by Abstraction pattern to test for performance and correctness. //! //! # Examples //! ``` //! use dexter::*; //! struct ExamplePublisher; //! //! impl Publisher<Vec<char>, String, String> for ExamplePublisher { //! fn publish(&mut self, result: ExperimentResult<String, String>) {...
<S>(mut self, setup: S) -> Self where S: FnMut(P) -> P + 'a { self.setup = Some(Box::new(setup)); self } /// Adds a check step that will disable the experiment in certain cases. /// /// If the passed closure returns false when passed the experiment's parameter, then the ...
setup
identifier_name
workqueue.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/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
} } // At this point, we have some work. Perform it. let mut proxy = WorkerProxy { worker: &mut deque, ref_count: ref_count, queue_data: queue_data, worker_index: self.in...
{ break }
conditional_block
workqueue.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/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
_ => {} } } unsafe { usleep(back_off_sleep as u32); } back_off_sleep += BACKOFF...
break } Ok(WorkerMsg::Exit) => return, Ok(_) => panic!("unexpected message"),
random_line_split
workqueue.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/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
(&self) -> u8 { self.worker_index } } /// A work queue on which units of work can be submitted. pub struct WorkQueue<QueueData:'static, WorkData:'static> { /// Information about each of the workers. workers: Vec<WorkerInfo<QueueData, WorkData>>, /// A port on which deques can be received from t...
worker_index
identifier_name
compare-generic-enums.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 ...
(x: Option<an_int>, y: Option<isize>) -> bool { x == y } pub fn main() { assert!(!cmp(Some(3), None)); assert!(!cmp(Some(3), Some(4))); assert!(cmp(Some(3), Some(3))); assert!(cmp(None, None)); }
cmp
identifier_name
compare-generic-enums.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 ...
// run-pass #![allow(non_camel_case_types)] type an_int = isize; fn cmp(x: Option<an_int>, y: Option<isize>) -> bool { x == y } pub fn main() { assert!(!cmp(Some(3), None)); assert!(!cmp(Some(3), Some(4))); assert!(cmp(Some(3), Some(3))); assert!(cmp(None, None)); }
random_line_split
compare-generic-enums.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 ...
{ assert!(!cmp(Some(3), None)); assert!(!cmp(Some(3), Some(4))); assert!(cmp(Some(3), Some(3))); assert!(cmp(None, None)); }
identifier_body
kinds.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 ...
#[lang="owned"] pub trait Send { // empty. } #[cfg(not(stage0))] #[lang="send"] pub trait Send { // empty. } #[cfg(stage0)] #[lang="const"] pub trait Freeze { // empty. } #[cfg(not(stage0))] #[lang="freeze"] pub trait Freeze { // empty. } #[lang="sized"] pub trait Sized { // Empty. }
// Empty. } #[cfg(stage0)]
random_line_split
applicationsettings.rs
//! Stores all settings related to the application from a user perspective use app_dirs::*; use clap::ArgMatches; use crate::io::constants::{APP_INFO, SCALE};
use log4rs::config::{Appender, Config, Root}; use log4rs::encode::pattern::PatternEncoder; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct ApplicationSettings { pub rom_file_name: String, pub debug_mode: bool, pub trace_mode: bool, pub memvis_mode: bool, pub debugger_on: bool, pub vu...
use std::path::PathBuf; use log::LevelFilter; use log4rs; use log4rs::append::console::ConsoleAppender;
random_line_split
applicationsettings.rs
//! Stores all settings related to the application from a user perspective use app_dirs::*; use clap::ArgMatches; use crate::io::constants::{APP_INFO, SCALE}; use std::path::PathBuf; use log::LevelFilter; use log4rs; use log4rs::append::console::ConsoleAppender; use log4rs::config::{Appender, Config, Root}; use log4r...
(arguments: &ArgMatches) -> Result<ApplicationSettings, String> { // Attempt to read ROM first let rom_file_name = arguments .value_of("game") .expect("Could not open specified rom") .to_string(); let debug_mode = arguments.is_present("debug"); let trace_...
new
identifier_name
ffi.rs
use std::io::Write; use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr}; use std::sync::mpsc::channel; use std::slice::from_raw_parts; use rotor_redis::conversion::ToRedisCommand; use rotor_stream::Buf; use inner::{MANAGER, Command, SockId, Socket}; #[repr(C)] pub struct Arg { data: *const u8, len: usiz...
impl ToRedisCommand for ArgSet { fn write_into(self, buf: &mut Buf) { unsafe { let items = from_raw_parts(self.items, self.num); let n = items.len(); write!(buf, "*{}\r\n", n).expect("buffer write"); for item in items { let slc = from_raw_par...
{ MANAGER.with_socket(sock as SockId, |s| { match s { &mut Socket::Redis(ref red) => { let mut lock = red.0.lock().expect("lock redis connection"); ArgSet { items: args, num: num }.write_into( lock.transport().expect("valid redis transport").ou...
identifier_body
ffi.rs
use std::io::Write; use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr}; use std::sync::mpsc::channel; use std::slice::from_raw_parts; use rotor_redis::conversion::ToRedisCommand; use rotor_stream::Buf; use inner::{MANAGER, Command, SockId, Socket}; #[repr(C)] pub struct Arg { data: *const u8, len: usiz...
{ items: *const Arg, num: usize, } #[no_mangle] pub extern fn stator_redis_connect_ipv4(ip: u32, port: u16, db: u32) -> u64 { let (tx, rx) = channel(); MANAGER.post_message( Command::NewRedis(( SocketAddr::V4(V4::new(Ipv4Addr::from(ip), port)), db, tx, ...
ArgSet
identifier_name
ffi.rs
use std::io::Write; use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr}; use std::sync::mpsc::channel;
use rotor_stream::Buf; use inner::{MANAGER, Command, SockId, Socket}; #[repr(C)] pub struct Arg { data: *const u8, len: usize, } pub struct ArgSet { items: *const Arg, num: usize, } #[no_mangle] pub extern fn stator_redis_connect_ipv4(ip: u32, port: u16, db: u32) -> u64 { let (tx, rx) = channel(...
use std::slice::from_raw_parts; use rotor_redis::conversion::ToRedisCommand;
random_line_split
ffi.rs
use std::io::Write; use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr}; use std::sync::mpsc::channel; use std::slice::from_raw_parts; use rotor_redis::conversion::ToRedisCommand; use rotor_stream::Buf; use inner::{MANAGER, Command, SockId, Socket}; #[repr(C)] pub struct Arg { data: *const u8, len: usiz...
_ => { error!("Socket {} is a redis", sock); return 0; } } }).unwrap_or(0) as u64 } impl ToRedisCommand for ArgSet { fn write_into(self, buf: &mut Buf) { unsafe { let items = from_raw_parts(self.items, self.num); l...
{ let mut lock = red.0.lock().expect("lock redis connection"); ArgSet { items: args, num: num }.write_into( lock.transport().expect("valid redis transport").output()); let id = lock.protocol().expect("valid redis proto") .receiver.n...
conditional_block
datagram.rs
use super::{socket_addr, SocketAddr}; use crate::sys::unix::net::new_socket; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net; use std::path::Path; pub(crate) fn bind(path: &Path) -> io::Result<net::UnixDatagram> { let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?; // Ensur...
pub(crate) fn local_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> { super::local_addr(socket.as_raw_fd()) } pub(crate) fn peer_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> { super::peer_addr(socket.as_raw_fd()) } pub(crate) fn recv_from( socket: &net::UnixDatagram, dst: &mut...
pub(crate) fn pair() -> io::Result<(net::UnixDatagram, net::UnixDatagram)> { super::pair(libc::SOCK_DGRAM) }
random_line_split
datagram.rs
use super::{socket_addr, SocketAddr}; use crate::sys::unix::net::new_socket; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net; use std::path::Path; pub(crate) fn bind(path: &Path) -> io::Result<net::UnixDatagram> { let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?; // Ensur...
pub(crate) fn peer_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> { super::peer_addr(socket.as_raw_fd()) } pub(crate) fn recv_from( socket: &net::UnixDatagram, dst: &mut [u8], ) -> io::Result<(usize, SocketAddr)> { let mut count = 0; let socketaddr = SocketAddr::new(|sockaddr, socklen...
{ super::local_addr(socket.as_raw_fd()) }
identifier_body
datagram.rs
use super::{socket_addr, SocketAddr}; use crate::sys::unix::net::new_socket; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net; use std::path::Path; pub(crate) fn
(path: &Path) -> io::Result<net::UnixDatagram> { let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?; // Ensure the fd is closed. let socket = unsafe { net::UnixDatagram::from_raw_fd(fd) }; let (sockaddr, socklen) = socket_addr(path)?; let sockaddr = &sockaddr as *const libc::sockaddr_un as *const...
bind
identifier_name
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser...
() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(easy::Stream(State::new(IteratorStream::new(&mut iter))), 1); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(s...
shared_stream_insufficent_backtrack
identifier_name
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser...
else { c } }); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int: &mut Parser<Input = _, Output = _, PartialState = _> = &mut many(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = sep_by(int, char(',')).parse(buffer).map(|t|...
{ (c as u8 + 1) as char }
conditional_block
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser...
#[test] fn shared_stream_backtrack() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(State::new(IteratorStream::new(&mut iter)), 2); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut ...
{ // Iterator that can't be cloned let text = "10,222,3,44".chars().map(|c| { if c.is_digit(10) { (c as u8 + 1) as char } else { c } }); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int: &mut Parser<Input = _, Output ...
identifier_body
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser...
let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result: Result<Vec<&str>, _> = parser.parse(stream).map(|t| t.0); assert!(re...
let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(easy::Stream(State::new(IteratorStream::new(&mut iter))), 1);
random_line_split
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path; pub fn check(path: &Path, bad: &mut bool)
// and these long messages often have error codes themselves inside // them, but we don't want to report duplicates in these cases. This // variable keeps track of whether we're currently inside one of these // long diagnostic messages. let mut inside_long_dia...
{ let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().unwrap().to_string_lossy(); if ...
identifier_body
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path;
pub fn check(path: &Path, bad: &mut bool) { let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().u...
random_line_split
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path; pub fn
(path: &Path, bad: &mut bool) { let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().unwrap().to_s...
check
identifier_name
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd...
{ EpollCtlAdd = 1, EpollCtlDel = 2, EpollCtlMod = 3 } #[cfg(not(target_arch = "x86_64"))] #[derive(Clone, Copy)] #[repr(C)] pub struct EpollEvent { pub events: EpollEventKind, pub data: u64 } #[cfg(target_arch = "x86_64")] #[derive(Clone, Copy)] #[repr(C, packed)] pub struct EpollEvent { pub ...
EpollOp
identifier_name
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd...
const EPOLLOUT = 0x004, const EPOLLRDNORM = 0x040, const EPOLLRDBAND = 0x080, const EPOLLWRNORM = 0x100, const EPOLLWRBAND = 0x200, const EPOLLMSG = 0x400, const EPOLLERR = 0x008, const EPOLLHUP = 0x010, const EPOLLRDHUP = 0x2000, const EPO...
const EPOLLIN = 0x001, const EPOLLPRI = 0x002,
random_line_split
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd...
#[inline] pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> { let res = unsafe { ffi::epoll_wait(epfd, events.as_mut_ptr(), events.len() as c_int, timeout_ms as c_int) }; Errno::result(res).map(|r| r as usize) }
{ let res = unsafe { ffi::epoll_ctl(epfd, op as c_int, fd, event as *const EpollEvent) }; Errno::result(res).map(drop) }
identifier_body
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono;
if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/questions/43753491/include-git-commit-h...
fn main() { use std::process::Command;
random_line_split
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn main()
println!("cargo:rustc-env=RUSTCVER={}", rustc_version::version().unwrap()); println!("cargo:rustc-env=RUSTCDATE={}", rustc_version::version_meta().unwrap().commit_date.unwrap()); }
{ use std::process::Command; if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/questio...
identifier_body
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn
() { use std::process::Command; if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/ques...
main
identifier_name
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn main() { use std::process::Command; if cfg!(target_os = "windows")
// https://stackoverflow.com/questions/43753491/include-git-commit-hash-as-string-into-rust-program let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap(); let git_hash = String::from_utf8(output.stdout).unwrap(); println!("cargo:rustc-env=GIT_HASH={}", git_hash); // build timestam...
{ let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); }
conditional_block
macros.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 accordin...
random_line_split
issue-4366-2.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 ...
() { foo(); //~ ERROR: unresolved name }
main
identifier_name
issue-4366-2.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 ...
mod foo { pub fn foo() {} } mod a { pub mod b { use foo::foo; type bar = isize; } pub mod sub { use a::b::*; fn sub() -> bar { 1 } //~^ ERROR: undeclared type name } } mod m1 { fn foo() {} } fn main() { foo(); //~ ERROR: unresolved name }
random_line_split
issue-4366-2.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 ...
//~^ ERROR: undeclared type name } } mod m1 { fn foo() {} } fn main() { foo(); //~ ERROR: unresolved name }
{ 1 }
identifier_body
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop { let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity)...
return mass * acceleration; }
println!("Enter the mass of the ball"); let input_m = io::stdin().read_line().ok().expect("Failed to read line"); let input_num_m: Option<f32> = input_m.trim().parse(); let mass = match input_num_m { Some(mass) => mass, None => 0.0 }; println!("Enter the length of the pipe"); ...
identifier_body
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop { let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity)...
time: f32) -> Velocity { println!("Enter the range of the appeture"); let input = io::stdin().read_line().ok().expect("Failed to read line"); let input_num: Option<f32> = input.trim().parse(); let range = match input_num { Some(range) => range, None => 0.0 }; let velocity_x: f3...
alculate_velocity(
identifier_name
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop {
println!("The time it'll take the ball to travel is {}s", time); println!("The velocity of the ball will be {} m/s", velocity.v); println!("The angle of the launcher should be {}º", angle); println!("The force exerted by the launcher on the ball should be {} N", force); } } fn calcu...
let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity); let force: f32 = calculate_force(&velocity);
random_line_split
type-ascription.rs
// run-pass #![allow(dead_code)] #![allow(unused_variables)] // Type ascription doesn't lead to unsoundness #![feature(type_ascription)] use std::mem; const C1: u8 = 10: u8; const C2: [u8; 1: usize] = [1]; struct S { a: u8 } fn main() { assert_eq!(C1.into(): i32, 10); assert_eq!(C2[0], 1);
let s = S { a: 10: u8 }; let arr = &[1u8, 2, 3]; let mut v = arr.iter().cloned().collect(): Vec<_>; v.push(4); assert_eq!(v, [1, 2, 3, 4]); let a = 1: u8; let b = a.into(): u16; assert_eq!(v[a.into(): usize], 2); assert_eq!(mem::size_of_val(&a), 1); assert_eq!(mem::size_of_val...
random_line_split
type-ascription.rs
// run-pass #![allow(dead_code)] #![allow(unused_variables)] // Type ascription doesn't lead to unsoundness #![feature(type_ascription)] use std::mem; const C1: u8 = 10: u8; const C2: [u8; 1: usize] = [1]; struct
{ a: u8 } fn main() { assert_eq!(C1.into(): i32, 10); assert_eq!(C2[0], 1); let s = S { a: 10: u8 }; let arr = &[1u8, 2, 3]; let mut v = arr.iter().cloned().collect(): Vec<_>; v.push(4); assert_eq!(v, [1, 2, 3, 4]); let a = 1: u8; let b = a.into(): u16; assert_eq!(v[a.in...
S
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pu...
(bytes: &[u8]) -> DiagnosticsResult<FlatBufferSchema<'_>> { Ok(FlatBufferSchema::build(bytes)) } pub fn builtins() -> DiagnosticsResult<SchemaDocument> { graphql_syntax::parse_schema_document(BUILTINS, SourceLocationKey::generated()) }
build_schema_from_flat_buffer
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pu...
pub fn builtins() -> DiagnosticsResult<SchemaDocument> { graphql_syntax::parse_schema_document(BUILTINS, SourceLocationKey::generated()) }
{ Ok(FlatBufferSchema::build(bytes)) }
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pu...
client_schema_documents.push(graphql_syntax::parse_schema_document( extension_sdl.as_ref(), *location_key, )?); } SDLSchema::build(&server_documents, &client_schema_documents) } pub fn build_schema_with_flat_buffer(bytes: Vec<u8>) -> SDLSchema { SDLSchema::FlatBuffe...
SourceLocationKey::generated(), )?); let mut client_schema_documents = Vec::new(); for (extension_sdl, location_key) in extension_sdls {
random_line_split
player.rs
/* Controls the Player Behaviour */ use polar_game::object::{Part,Object,}; use polar_game::object::{Point}; use polar_game::GameSetup; use rand; use rand::distributions::IndependentSample; use rand::distributions::range::Range; use std::f64::consts::PI; pub struct Player{ pub position: Point, parts: Vec<Part...
(&self) -> Point{ self.position } fn get_render_parts(&self) -> Vec<Part>{ let mut part_vec: Vec<Part> = Vec::new(); if!self.destroyed{ for p in self.parts.iter(){ let p_shift = Part{ radial: p.radial + Point{x: self.position.x, y: self.po...
get_position
identifier_name
player.rs
/* Controls the Player Behaviour */ use polar_game::object::{Part,Object,}; use polar_game::object::{Point}; use polar_game::GameSetup; use rand; use rand::distributions::IndependentSample; use rand::distributions::range::Range; use std::f64::consts::PI; pub struct Player{ pub position: Point, parts: Vec<Part...
else{ time_passed = time_passed /5.0; for i in 0..100{ let radial_shift = Point{x: self.destruct_dirs[i].x, y: self.destruct_dirs[i].x}; let angle_shift = Point{x: self.destruct_dirs[i].y, y: self.destruct_dirs[i].y}; self.destruct_parts...
{ self.position = self.position + shift.mult(time_passed); self.position.x = self.position.x.min(game_setup.radial_max - game_setup.player_width.x).max(0.0); }
conditional_block
player.rs
/* Controls the Player Behaviour */ use polar_game::object::{Part,Object,}; use polar_game::object::{Point}; use polar_game::GameSetup; use rand; use rand::distributions::IndependentSample; use rand::distributions::range::Range; use std::f64::consts::PI; pub struct Player{ pub position: Point, parts: Vec<Part...
destroyed: false,} } pub fn update_position(&mut self, shift: Point, mut time_passed: f64, game_setup: GameSetup){ if!self.destroyed{ self.position = self.position + shift.mult(time_passed); self.position.x = self.position.x.min(game_setup.radial_max - game_setup....
color: [1.0, 1.0, 1.0, 1.0]}]; Player{position: Point{x: start.x, y: start.y}, parts: prts, destruct_parts: Vec::new(), destruct_dirs: Vec::new(),
random_line_split
player.rs
/* Controls the Player Behaviour */ use polar_game::object::{Part,Object,}; use polar_game::object::{Point}; use polar_game::GameSetup; use rand; use rand::distributions::IndependentSample; use rand::distributions::range::Range; use std::f64::consts::PI; pub struct Player{ pub position: Point, parts: Vec<Part...
fn get_collision_parts(&self) -> Vec<Part>{ let mut parts: Vec<Part> = Vec::new(); if!self.destroyed{ parts = self.get_render_parts(); } parts } } impl Player{ pub fn new(start: Point, width: Point) -> Player{ let prts = vec![Part{radial: Point{x: 0.0, ...
{ let mut part_vec: Vec<Part> = Vec::new(); if !self.destroyed{ for p in self.parts.iter(){ let p_shift = Part{ radial: p.radial + Point{x: self.position.x, y: self.position.x}, angle: p.angle + Point{x: self.position.y, y: self.positio...
identifier_body
resource-assign-is-not-copy.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 ...
}
random_line_split
resource-assign-is-not-copy.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 ...
() { let i = @mut 0; // Even though these look like copies, they are guaranteed not to be { let a = r(i); let b = (a, 10); let (c, _d) = b; info!(c); } assert_eq!(*i, 1); }
main
identifier_name
borrowck-lend-flow-loop.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 ...
// Here we check that when you break out of an inner loop, the // borrows that go out of scope as you exit the inner loop are // removed from the bitset. while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); ...
} } fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
random_line_split
borrowck-lend-flow-loop.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 ...
() { // In this instance, the borrow encompasses the entire loop. let mut v = ~3; let mut x = &mut v; **x += 1; loop { borrow(v); //~ ERROR cannot borrow } } fn block_overarching_alias_mut() { // In this instance, the borrow encompasses the entire closure call. let mut v = ~3;...
loop_overarching_alias_mut
identifier_name
borrowck-lend-flow-loop.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 ...
fn borrow_mut(_v: &mut int) {} fn cond() -> bool { fail2!() } fn produce<T>() -> T { fail2!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn loop_overarching_alias_mut() { // In this instance, the borrow encompasses the entire loop. let mut v = ~3; let mut x = &mut v; **x += 1; loop { ...
{}
identifier_body
borrowck-lend-flow-loop.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 ...
} } fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { // Here we check that when you break out of an inner loop, the // borrows that go out of scope as you exit the inner loop are // removed from the bitset. while cond() { while cond() { // this...
{ x = &mut v; //~ ERROR cannot borrow }
conditional_block
solver060.rs
// COPYRIGHT (C) 2017 barreiro. All Rights Reserved. // Rust solvers for Project Euler problems use std::collections::HashMap; use euler::algorithm::long::{concatenation, pow_10, square}; use euler::algorithm::prime::{generator_wheel, miller_rabin, prime_sieve}; use euler::Solver; // The primes 3, 7, 109, and 673, a...
if set.len() >= size || add_prime_to_set(set, size, primes, cache) { true } else { set.pop(); false } }) }
{ let last_prime = *primes.last().unwrap(); let is_prime = |c| if c < last_prime { primes.binary_search(&c).is_ok() } else if c < square(last_prime) { prime_sieve(c, primes) } else { miller_rabin(c) }; let concatenation_list = |p| primes.iter().filter(|&&prime| prime > p ...
identifier_body