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 |
|---|---|---|---|---|
diy_hints.rs | use std::collections::HashSet;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::{Editor, Result};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
// It's simple example of rustyline, for more effi... | }
impl Hinter for DIYHinter {
type Hint = CommandHint;
fn hint(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<CommandHint> {
if line.is_empty() || pos < line.len() {
return None;
}
self.hints
.iter()
.filter_map(|hint| {
... | display: self.display[strip_chars..].to_owned(),
complete_up_to: self.complete_up_to.saturating_sub(strip_chars),
}
} | random_line_split |
diy_hints.rs | use std::collections::HashSet;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::{Editor, Result};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
// It's simple example of rustyline, for more effi... | (&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<CommandHint> {
if line.is_empty() || pos < line.len() {
return None;
}
self.hints
.iter()
.filter_map(|hint| {
// expect hint after word complete, like redis cli, add condition:
... | hint | identifier_name |
diy_hints.rs | use std::collections::HashSet;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::{Editor, Result};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
// It's simple example of rustyline, for more effi... |
fn main() -> Result<()> {
println!("This is a DIY hint hack of rustyline");
let h = DIYHinter { hints: diy_hints() };
let mut rl: Editor<DIYHinter> = Editor::new();
rl.set_helper(Some(h));
loop {
let input = rl.readline("> ")?;
println!("input: {}", input);
}
}
| {
let mut set = HashSet::new();
set.insert(CommandHint::new("help", "help"));
set.insert(CommandHint::new("get key", "get "));
set.insert(CommandHint::new("set key value", "set "));
set.insert(CommandHint::new("hget key field", "hget "));
set.insert(CommandHint::new("hset key field value", "hset... | identifier_body |
diy_hints.rs | use std::collections::HashSet;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::{Editor, Result};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
// It's simple example of rustyline, for more effi... |
})
.next()
}
}
fn diy_hints() -> HashSet<CommandHint> {
let mut set = HashSet::new();
set.insert(CommandHint::new("help", "help"));
set.insert(CommandHint::new("get key", "get "));
set.insert(CommandHint::new("set key value", "set "));
set.insert(CommandHint::new("hget k... | {
None
} | conditional_block |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct | {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Photo{
fn from_dao(dao: &Dao) -> Self {
Photo {
photo_id: dao.get("photo_id"),
url: dao.get_opt("url"),
}
}
fn to_dao(&self) -> Dao {
let mut dao = Dao::new();
dao.set("photo_id... | Photo | identifier_name |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<S... |
fn to_dao(&self) -> Dao {
let mut dao = Dao::new();
dao.set("photo_id", &self.photo_id);
match self.url {
Some(ref _value) => dao.set("url", _value),
None => dao.set_null("url"),
}
dao
}
}
fn main() {
let url = "postgres://postgres:p0stgr3s@... | {
Photo {
photo_id: dao.get("photo_id"),
url: dao.get_opt("url"),
}
} | identifier_body |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono; |
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Photo{
fn from_dao(dao: &Dao) -> Self {
Photo {
... | extern crate rustc_serialize; | random_line_split |
extern-pass-TwoU32s.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 ... | () {
unsafe {
let x = TwoU32s {one: 22, two: 23};
let y = rust_dbg_extern_identity_TwoU32s(x);
assert_eq!(x, y);
}
}
| main | identifier_name |
extern-pass-TwoU32s.rs | // Copyright 2012 The Rust Project Developers. See the 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 a foreign f... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
extern-pass-TwoU32s.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 ... | {
unsafe {
let x = TwoU32s {one: 22, two: 23};
let y = rust_dbg_extern_identity_TwoU32s(x);
assert_eq!(x, y);
}
} | identifier_body | |
lex_rule_loader.rs | use common::lexer::{Ruleset, LexRule};
use walkdir::{WalkDir, DirEntry};
use std::io::prelude::*;
use std::io;
use std::fs;
pub fn ruleset_from_dir (dir_path: String) -> io::Result<Ruleset> {
ruleset_from_dir_v(dir_path, false)
}
pub fn | (dir_path: String, verbose: bool) -> io::Result<Ruleset> {
let mut lex_list:Vec<DirEntry> = Vec::new();
for entry in WalkDir::new(dir_path) {
let entry = entry.unwrap();
let ent_path = &entry.path();
match ent_path.extension() {
Some(ext) => {
if ext == "lex"... | ruleset_from_dir_v | identifier_name |
lex_rule_loader.rs | use common::lexer::{Ruleset, LexRule};
use walkdir::{WalkDir, DirEntry};
use std::io::prelude::*;
use std::io;
use std::fs;
pub fn ruleset_from_dir (dir_path: String) -> io::Result<Ruleset> {
ruleset_from_dir_v(dir_path, false)
}
pub fn ruleset_from_dir_v (dir_path: String, verbose: bool) -> io::Result<Ruleset> | }
let mut file = fs::File::open(entry.path())?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
for line in contents.lines() {
if! ((line.trim() == "") || (line.starts_with("#"))) {
rules.add(LexRule::from_string(String::from(li... | {
let mut lex_list:Vec<DirEntry> = Vec::new();
for entry in WalkDir::new(dir_path) {
let entry = entry.unwrap();
let ent_path = &entry.path();
match ent_path.extension() {
Some(ext) => {
if ext == "lex" {
lex_list.push(entry.clone());
... | identifier_body |
lex_rule_loader.rs | use common::lexer::{Ruleset, LexRule};
use walkdir::{WalkDir, DirEntry};
use std::io::prelude::*;
use std::io;
use std::fs;
pub fn ruleset_from_dir (dir_path: String) -> io::Result<Ruleset> {
ruleset_from_dir_v(dir_path, false)
}
pub fn ruleset_from_dir_v (dir_path: String, verbose: bool) -> io::Result<Ruleset> {... | lex_list.push(entry.clone());
}
},
None => ()
}
}
let mut rules = Ruleset::new();
for entry in lex_list {
if verbose {
println!("Loading rules from file [{}]", &entry.path().display());
}
let mut file =... | Some(ext) => {
if ext == "lex" { | random_line_split |
lib.rs | //! (Hopefully) Safe fork-join parallelism abstractions
//!
//! Implements the [`divide`](fn.divide.html) and
//! [`execute!`](../parallel_macros/macro.execute!.html) functions proposed in Niko's
//! [blog](http://smallcultfollowing.com/babysteps/blog/2013/06/11/data-parallelism-in-rust/).
//!
//! # Cargo
//!
//! ``` t... |
#![allow(unused_features)]
#![cfg_attr(test, plugin(quickcheck_macros))]
#![deny(warnings)]
#![feature(core)]
#![feature(os)]
#![feature(plugin)]
#![feature(std_misc)]
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
extern crate rand;
pub use divide::divide;
pub use apply::apply;
mod divide;
mod apply; | //! [dependencies.parallel_macros]
//! git = "https://github.com/japaric/parallel.rs"
//! ``` | random_line_split |
data.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>,... | fn contains_pfx(haystack: &[&str], needle: &str) -> bool {
haystack.iter().any(|&x| needle.starts_with(x))
}
// Quirks-mode matches are case-insensitive.
let public = opt_to_ascii_lower(public);
let system = opt_to_ascii_lower(system);
let quirk = match (opt_as_slice(&public), opt_as_s... | // FIXME: We could do something asymptotically faster here.
// But there aren't many strings, and this happens at most once per parse. | random_line_split |
data.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>,... | (x: Option<&str>) -> Option<String> {
x.map(|y| y.to_ascii_lower())
}
let name = opt_as_slice(&doctype.name);
let public = opt_as_slice(&doctype.public_id);
let system = opt_as_slice(&doctype.system_id);
let err = match (name, public, system) {
(Some("html"), None, None)
... | opt_to_ascii_lower | identifier_name |
data.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>,... |
// Quirks-mode matches are case-insensitive.
let public = opt_to_ascii_lower(public);
let system = opt_to_ascii_lower(system);
let quirk = match (opt_as_slice(&public), opt_as_slice(&system)) {
_ if doctype.force_quirks => Quirks,
_ if name!= Some("html") => Quirks,
_ if ifra... | {
haystack.iter().any(|&x| needle.starts_with(x))
} | identifier_body |
raw_block.rs | use Renderable;
use context::Context;
use LiquidOptions;
use token::Token;
use lexer::Element::{self, Expression, Tag, Raw};
use error::Result;
struct RawT {
content: String,
}
impl Renderable for RawT {
fn | (&self, _context: &mut Context) -> Result<Option<String>> {
Ok(Some(self.content.to_owned()))
}
}
pub fn raw_block(_tag_name: &str,
_arguments: &[Token],
tokens: &[Element],
_options: &LiquidOptions)
-> Result<Box<Renderable>> {
let co... | render | identifier_name |
raw_block.rs | use Renderable;
use context::Context;
use LiquidOptions;
use token::Token;
use lexer::Element::{self, Expression, Tag, Raw};
use error::Result;
struct RawT {
content: String,
}
impl Renderable for RawT {
fn render(&self, _context: &mut Context) -> Result<Option<String>> |
}
pub fn raw_block(_tag_name: &str,
_arguments: &[Token],
tokens: &[Element],
_options: &LiquidOptions)
-> Result<Box<Renderable>> {
let content = tokens.iter().fold("".to_owned(), |a, b| {
match *b {
Expression(_, ref text) |... | {
Ok(Some(self.content.to_owned()))
} | identifier_body |
raw_block.rs | use Renderable;
use context::Context;
use LiquidOptions;
use token::Token;
use lexer::Element::{self, Expression, Tag, Raw};
use error::Result;
struct RawT {
content: String, | impl Renderable for RawT {
fn render(&self, _context: &mut Context) -> Result<Option<String>> {
Ok(Some(self.content.to_owned()))
}
}
pub fn raw_block(_tag_name: &str,
_arguments: &[Token],
tokens: &[Element],
_options: &LiquidOptions)
... | }
| random_line_split |
local-generic.rs | // We specify -C incremental here because we want to test the partitioning for
// incremental compilation
// compile-flags:-Zprint-mono-items=eager -Cincremental=tmp/partitioning-tests/local-generic
#![allow(dead_code)]
#![crate_type="lib"]
//~ MONO_ITEM fn generic::<u32> @@ local_generic.volatile[External]
//~ MONO_... | () {
let _ = generic("abc");
}
}
| user | identifier_name |
local-generic.rs | // We specify -C incremental here because we want to test the partitioning for
// incremental compilation
// compile-flags:-Zprint-mono-items=eager -Cincremental=tmp/partitioning-tests/local-generic
#![allow(dead_code)]
#![crate_type="lib"]
//~ MONO_ITEM fn generic::<u32> @@ local_generic.volatile[External]
//~ MONO_... |
mod mod1 {
pub use super::generic;
//~ MONO_ITEM fn mod1::user @@ local_generic-mod1[Internal]
fn user() {
let _ = generic(0u64);
}
mod mod1 {
use super::generic;
//~ MONO_ITEM fn mod1::mod1::user @@ local_generic-mod1-mod1[Internal]
fn user() {
let _... | {
let _ = generic(0u32);
} | identifier_body |
local-generic.rs | // We specify -C incremental here because we want to test the partitioning for
// incremental compilation
// compile-flags:-Zprint-mono-items=eager -Cincremental=tmp/partitioning-tests/local-generic
#![allow(dead_code)]
#![crate_type="lib"]
//~ MONO_ITEM fn generic::<u32> @@ local_generic.volatile[External]
//~ MONO_... | fn user() {
let _ = generic(0u32);
}
mod mod1 {
pub use super::generic;
//~ MONO_ITEM fn mod1::user @@ local_generic-mod1[Internal]
fn user() {
let _ = generic(0u64);
}
mod mod1 {
use super::generic;
//~ MONO_ITEM fn mod1::mod1::user @@ local_generic-mod1-mod1[Interna... | //~ MONO_ITEM fn generic::<char> @@ local_generic.volatile[External]
//~ MONO_ITEM fn generic::<&str> @@ local_generic.volatile[External]
pub fn generic<T>(x: T) -> T { x }
//~ MONO_ITEM fn user @@ local_generic[Internal] | random_line_split |
error.rs | use std::error;
use std::fmt;
use std::io::{self, Error};
#[derive(Debug)]
pub struct TarError {
desc: String,
io: io::Error,
}
impl TarError {
pub fn new(desc: &str, err: Error) -> TarError {
TarError {
desc: desc.to_string(),
io: err,
}
}
}
impl error::Error ... | } | random_line_split | |
error.rs | use std::error;
use std::fmt;
use std::io::{self, Error};
#[derive(Debug)]
pub struct TarError {
desc: String,
io: io::Error,
}
impl TarError {
pub fn new(desc: &str, err: Error) -> TarError {
TarError {
desc: desc.to_string(),
io: err,
}
}
}
impl error::Error ... |
}
impl fmt::Display for TarError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.desc.fmt(f)
}
}
impl From<TarError> for Error {
fn from(t: TarError) -> Error {
Error::new(t.io.kind(), t)
}
}
| {
Some(&self.io)
} | identifier_body |
error.rs | use std::error;
use std::fmt;
use std::io::{self, Error};
#[derive(Debug)]
pub struct | {
desc: String,
io: io::Error,
}
impl TarError {
pub fn new(desc: &str, err: Error) -> TarError {
TarError {
desc: desc.to_string(),
io: err,
}
}
}
impl error::Error for TarError {
fn description(&self) -> &str {
&self.desc
}
fn cause(&self... | TarError | identifier_name |
htmltableheadercellelement.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::HTMLTableHeaderCellElementBinding;
use dom::bindings::codegen::InheritTypes:... | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableHeaderCellElement> {
let element = HTMLTableHeaderCellElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTableHeaderCellElementBinding::Wr... | new | identifier_name |
htmltableheadercellelement.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::HTMLTableHeaderCellElementBinding;
use dom::bindings::codegen::InheritTypes:... | use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::HTMLElementTypeId;
use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLTableHeaderCellElement {
htmltablecellelement... | random_line_split | |
composite_shape_against_any.rs | use std::marker::PhantomData;
use na::{Identity, Translate, Translation};
use na;
use entities::bounding_volume::{HasAABB, AABB};
use entities::partitioning::BVTCostFn;
use entities::shape::CompositeShape;
use entities::inspection::Repr;
use point::PointQuery;
use geometry::distance_internal;
use math::{Scalar, Point, ... | (&mut self, bv: &AABB<P>) -> Option<<P::Vect as Vect>::Scalar> {
// Compute the minkowski sum of the two AABBs.
let msum = AABB::new(*bv.mins() + self.msum_shift + (-self.msum_margin),
*bv.maxs() + self.msum_shift + self.msum_margin);
// Compute the distance to the ... | compute_bv_cost | identifier_name |
composite_shape_against_any.rs | use std::marker::PhantomData;
use na::{Identity, Translate, Translation};
use na;
use entities::bounding_volume::{HasAABB, AABB};
use entities::partitioning::BVTCostFn;
use entities::shape::CompositeShape;
use entities::inspection::Repr;
use point::PointQuery;
use geometry::distance_internal;
use math::{Scalar, Point, ... |
}
impl<'a, P, M, G1:?Sized, G2:?Sized>
BVTCostFn<<P::Vect as Vect>::Scalar, usize, AABB<P>, <P::Vect as Vect>::Scalar>
for CompositeShapeAgainstAnyDistCostFn<'a, P, M, G1, G2>
where P: Point,
P::Vect: Translate<P>,
M: Isometry<P, P::Vect> + Translation<P::Vect>,
G1: CompositeShape<... | {
let ls_m2 = na::inv(m1).expect("The transformation `m1` must be inversible.") * *m2;
let ls_aabb2 = g2.aabb(&ls_m2);
CompositeShapeAgainstAnyDistCostFn {
msum_shift: -ls_aabb2.center().to_vec(),
msum_margin: ls_aabb2.half_extents(),
m1: m1,
... | identifier_body |
composite_shape_against_any.rs | use std::marker::PhantomData;
use na::{Identity, Translate, Translation};
use na;
use entities::bounding_volume::{HasAABB, AABB};
use entities::partitioning::BVTCostFn;
use entities::shape::CompositeShape;
use entities::inspection::Repr;
use point::PointQuery;
use geometry::distance_internal;
use math::{Scalar, Point, ... | g1.bvt().best_first_search(&mut cost_fn).map(|(_, res)| res).expect("The composite shape must not be empty.")
}
/// Smallest distance between a shape and a composite shape.
pub fn any_against_composite_shape<P, M, G1:?Sized, G2:?Sized>(m1: &M, g1: &G1, m2: &M, g2: &G2) -> <P::Vect as Vect>::Scalar
where P: Po... | random_line_split | |
issue-5100.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.
// |
enum A { B, C }
fn main() {
match (true, false) {
B => (), //~ ERROR expected `(bool,bool)` but found an enum or structure pattern
_ => ()
}
match (true, false) {
(true, false, false) => () //~ ERROR mismatched types: expected `(bool,bool)` but found tuple (expected a tuple with 2... | // 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. | random_line_split |
issue-5100.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 ... | () {
match (true, false) {
B => (), //~ ERROR expected `(bool,bool)` but found an enum or structure pattern
_ => ()
}
match (true, false) {
(true, false, false) => () //~ ERROR mismatched types: expected `(bool,bool)` but found tuple (expected a tuple with 2 elements but found one w... | main | identifier_name |
domexception.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::DOMExceptionBinding;
use dom::bindings::codegen::Bindings::DOMExceptionBindi... | format!("{:?}", self.code)
}
// https://heycam.github.io/webidl/#error-names
fn Message(self) -> DOMString {
let message = match self.code {
DOMErrorName::IndexSizeError => "The index is not in the allowed range.",
DOMErrorName::HierarchyRequestError => "The operatio... | random_line_split | |
domexception.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::DOMExceptionBinding;
use dom::bindings::codegen::Bindings::DOMExceptionBindi... | (self) -> DOMString {
format!("{:?}", self.code)
}
// https://heycam.github.io/webidl/#error-names
fn Message(self) -> DOMString {
let message = match self.code {
DOMErrorName::IndexSizeError => "The index is not in the allowed range.",
DOMErrorName::HierarchyRequest... | Name | identifier_name |
domexception.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::DOMExceptionBinding;
use dom::bindings::codegen::Bindings::DOMExceptionBindi... |
// https://heycam.github.io/webidl/#error-names
fn Message(self) -> DOMString {
let message = match self.code {
DOMErrorName::IndexSizeError => "The index is not in the allowed range.",
DOMErrorName::HierarchyRequestError => "The operation would yield an incorrect node tree.",
... | {
format!("{:?}", self.code)
} | identifier_body |
unix.rs | #![cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
use crate::platform::ContextTraitExt;
pub use crate::platform_impl::{HeadlessContextExt, RawContextExt, RawHandle};
use crate::{Context, ContextCurrentState};
pub use gl... |
#[inline]
unsafe fn get_egl_display(&self) -> Option<*const raw::c_void> {
self.context.get_egl_display()
}
}
| {
self.context.raw_handle()
} | identifier_body |
unix.rs | #![cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
use crate::platform::ContextTraitExt;
pub use crate::platform_impl::{HeadlessContextExt, RawContextExt, RawHandle};
use crate::{Context, ContextCurrentState};
pub use gl... | (&self) -> Option<*const raw::c_void> {
self.context.get_egl_display()
}
}
| get_egl_display | identifier_name |
unix.rs | #![cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
use crate::platform::ContextTraitExt;
pub use crate::platform_impl::{HeadlessContextExt, RawContextExt, RawHandle};
use crate::{Context, ContextCurrentState};
pub use gl... | self.context.get_egl_display()
}
} | #[inline]
unsafe fn get_egl_display(&self) -> Option<*const raw::c_void> { | random_line_split |
macro-interpolation.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!(overly_complicated!(f, x, Option<uint>, { return Some(x); },
Some(8u), Some(y), y) == 8u)
} | identifier_body | |
macro-interpolation.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 $fnname($arg: $ty) -> Option<$ty> $body
match $fnname($val) {
Some($pat) => {
$res
}
_ => { fail2!(); }
}
})
)
pub fn main() {
assert!(overly_complicated!(f, x, Option<uint>, { return Some(x); },
Some(8u), Some(... | random_line_split | |
macro-interpolation.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!(overly_complicated!(f, x, Option<uint>, { return Some(x); },
Some(8u), Some(y), y) == 8u)
}
| main | identifier_name |
root.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/. */
/// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d... | stream: &mut TcpStream) -> Result<bool, ()> {
Ok(match msg_type {
"listAddons" => {
let actor = ErrorReply {
from: "root".to_string(),
error: "noAddons".to_string(),
message: "This root actor has no bro... |
fn handle_message(&self,
registry: &ActorRegistry,
msg_type: &str,
_msg: &json::Object, | random_line_split |
root.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/. */
/// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d... | };
stream.write_json_packet(&actor);
true
}
_ => false
})
}
}
impl RootActor {
pub fn encodable(&self) -> RootActorMsg {
RootActorMsg {
from: "root".to_string(),
applicationType: "browser".to_strin... | {
Ok(match msg_type {
"listAddons" => {
let actor = ErrorReply {
from: "root".to_string(),
error: "noAddons".to_string(),
message: "This root actor has no browser addons.".to_string(),
};
stre... | identifier_body |
root.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/. */
/// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d... |
_ => false
})
}
}
impl RootActor {
pub fn encodable(&self) -> RootActorMsg {
RootActorMsg {
from: "root".to_string(),
applicationType: "browser".to_string(),
traits: ActorTraits {
sources: true,
highlightable: tru... | {
let actor = ListTabsReply {
from: "root".to_string(),
selected: 0,
tabs: self.tabs.iter().map(|tab| {
registry.find::<TabActor>(tab).encodable()
}).collect()
};
strea... | conditional_block |
root.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/. */
/// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d... | (&self) -> String {
"root".to_string()
}
fn handle_message(&self,
registry: &ActorRegistry,
msg_type: &str,
_msg: &json::Object,
stream: &mut TcpStream) -> Result<bool, ()> {
Ok(match msg_type {
... | name | identifier_name |
no_0037_sudoku_solver.rs | struct | ;
impl Solution {
pub fn solve_sudoku(board: &mut Vec<Vec<char>>) {
// 9 行,每个 u16 表示一行上的数据,u16 表示对应索引的数字在这一行上已经有了。
let mut line = vec![0_u16; 9];
// 9 列
let mut column = vec![0_u16; 9];
// 3 x 3 的块
let mut block = vec![vec![0_u16; 3]; 3];
// 如果不是空格,就将对应的位置设置成... | Solution | identifier_name |
no_0037_sudoku_solver.rs | struct Solution;
impl Solution {
pub fn solve_sudoku(board: &mut Vec<Vec<char>>) {
// 9 行,每个 u16 表示一行上的数据,u16 表示对应索引的数字在这一行上已经有了。
let mut line = vec![0_u16; 9];
// 9 列
let mut column = vec![0_u16; 9];
// 3 x 3 的块
let mut block = vec![vec![0_u16; 3]; 3];
// 如果... | line[i] ^= 1 << digit;
column[j] ^= 1 << digit;
block[i / 3][j / 3] ^= 1 << digit;
}
fn dfs(
spaces: &Vec<(usize, usize)>,
pos: usize,
line: &mut Vec<u16>,
column: &mut Vec<u16>,
block: &mut Vec<Vec<u16>>,
board: &mut Vec<Vec<char>>,
)... | i: usize,
j: usize,
digit: u8,
) {
| conditional_block |
no_0037_sudoku_solver.rs | struct Solution;
impl Solution {
pub fn solve_sudoku(board: &mut Vec<Vec<char>>) {
// 9 行,每个 u16 表示一行上的数据,u16 表示对应索引的数字在这一行上已经有了。
let mut line = vec![0_u16; 9];
// 9 列
let mut column = vec![0_u16; 9];
// 3 x 3 的块
let mut block = vec![vec![0_u16; 3]; 3];
// 如果... | }
| '.', '3', '.', '.', '1'],
vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'],
vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'],
vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'],
vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'],
];
Solution::solve_sudoku... | identifier_body |
no_0037_sudoku_solver.rs | struct Solution;
impl Solution {
pub fn solve_sudoku(board: &mut Vec<Vec<char>>) {
// 9 行,每个 u16 表示一行上的数据,u16 表示对应索引的数字在这一行上已经有了。
let mut line = vec![0_u16; 9];
// 9 列
let mut column = vec![0_u16; 9];
// 3 x 3 的块
let mut block = vec![vec![0_u16; 3]; 3];
// 如果... | vec!['3', '4', '5', '2', '8', '6', '1', '7', '9'],
];
assert_eq!(board, want);
}
} | vec!['9', '6', '1', '5', '3', '7', '2', '8', '4'],
vec!['2', '8', '7', '4', '1', '9', '6', '3', '5'], | random_line_split |
lib.rs | #[derive(Debug, PartialEq)]
pub enum Comparison {
Equal,
Sublist,
Superlist,
Unequal,
}
pub fn sublist<T: PartialEq>(list1: &[T], list2: &[T]) -> Comparison {
if list1.len() == list2.len() {
if list1 == list2 {
return Comparison::Equal;
} else {
return Compar... | } | random_line_split | |
lib.rs | #[derive(Debug, PartialEq)]
pub enum Comparison {
Equal,
Sublist,
Superlist,
Unequal,
}
pub fn sublist<T: PartialEq>(list1: &[T], list2: &[T]) -> Comparison {
if list1.len() == list2.len() {
if list1 == list2 {
return Comparison::Equal;
} else {
return Compar... |
Comparison::Unequal;
}
| {
let mut slice = &list1[..];
while slice.len() >= list2.len() {
if list2 == &slice[..list2.len()] {
return Comparison::Superlist;
}
slice = &slice[1..];
}
} | conditional_block |
lib.rs | #[derive(Debug, PartialEq)]
pub enum | {
Equal,
Sublist,
Superlist,
Unequal,
}
pub fn sublist<T: PartialEq>(list1: &[T], list2: &[T]) -> Comparison {
if list1.len() == list2.len() {
if list1 == list2 {
return Comparison::Equal;
} else {
return Comparison::Unequal;
}
} else if list1.le... | Comparison | identifier_name |
server.rs | extern crate serde_json;
use std::net::TcpListener;
use std::io::{BufReader, BufRead};
use std::thread;
use chat::ChatMessage;
use chat::ReplyMessage;
use std::sync::mpsc::Sender;
pub fn listen(sender: Sender<ReplyMessage>) {
let listener = TcpListener::bind("127.0.0.1:2933").expect("Failed to bind port");
for... |
Err(e) => {
println!("{:?}", e);
}
}
}
} | {
let sender = sender.clone();
thread::spawn(move || {
let reader = BufReader::new(stream);
for line in reader.lines() {
let message: Result<ChatMessage, _> = serde_json::from_str(line.unwrap().as_str());
... | conditional_block |
server.rs | extern crate serde_json;
use std::net::TcpListener;
use std::io::{BufReader, BufRead};
use std::thread;
use chat::ChatMessage;
use chat::ReplyMessage;
use std::sync::mpsc::Sender;
| pub fn listen(sender: Sender<ReplyMessage>) {
let listener = TcpListener::bind("127.0.0.1:2933").expect("Failed to bind port");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let sender = sender.clone();
thread::spawn(move || {
... | random_line_split | |
server.rs | extern crate serde_json;
use std::net::TcpListener;
use std::io::{BufReader, BufRead};
use std::thread;
use chat::ChatMessage;
use chat::ReplyMessage;
use std::sync::mpsc::Sender;
pub fn | (sender: Sender<ReplyMessage>) {
let listener = TcpListener::bind("127.0.0.1:2933").expect("Failed to bind port");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let sender = sender.clone();
thread::spawn(move || {
let r... | listen | identifier_name |
server.rs | extern crate serde_json;
use std::net::TcpListener;
use std::io::{BufReader, BufRead};
use std::thread;
use chat::ChatMessage;
use chat::ReplyMessage;
use std::sync::mpsc::Sender;
pub fn listen(sender: Sender<ReplyMessage>) | Err(e) => {
println!("{:?}", e);
}
}
}
} | {
let listener = TcpListener::bind("127.0.0.1:2933").expect("Failed to bind port");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let sender = sender.clone();
thread::spawn(move || {
let reader = BufReader::new(stream);... | identifier_body |
packet.rs | //! SIMD intersection result
use crate::geometry::{f32xN, m32xN, V3DxN};
use crate::intersection::Isect;
/// Intersection result
#[derive(Copy, Clone, Debug)]
pub struct IsectxN {
pub t: f32xN,
pub p: V3DxN,
pub n: V3DxN,
pub hit: m32xN,
}
impl Default for IsectxN {
#[inline]
fn | () -> Self {
Self {
t: f32xN::splat(1e17),
hit: m32xN::splat(false),
p: V3DxN::default(),
n: V3DxN::default(),
}
}
}
impl IsectxN {
pub fn get(&self, idx: usize) -> Isect {
Isect {
t: self.t.extract(idx),
p: self.p.... | default | identifier_name |
packet.rs | //! SIMD intersection result
use crate::geometry::{f32xN, m32xN, V3DxN};
use crate::intersection::Isect;
/// Intersection result
#[derive(Copy, Clone, Debug)]
pub struct IsectxN {
pub t: f32xN,
pub p: V3DxN,
pub n: V3DxN,
pub hit: m32xN,
} |
impl Default for IsectxN {
#[inline]
fn default() -> Self {
Self {
t: f32xN::splat(1e17),
hit: m32xN::splat(false),
p: V3DxN::default(),
n: V3DxN::default(),
}
}
}
impl IsectxN {
pub fn get(&self, idx: usize) -> Isect {
Isect {
... | random_line_split | |
packet.rs | //! SIMD intersection result
use crate::geometry::{f32xN, m32xN, V3DxN};
use crate::intersection::Isect;
/// Intersection result
#[derive(Copy, Clone, Debug)]
pub struct IsectxN {
pub t: f32xN,
pub p: V3DxN,
pub n: V3DxN,
pub hit: m32xN,
}
impl Default for IsectxN {
#[inline]
fn default() -> ... |
}
impl IsectxN {
pub fn get(&self, idx: usize) -> Isect {
Isect {
t: self.t.extract(idx),
p: self.p.get(idx),
n: self.n.get(idx),
hit: self.hit.extract(idx),
}
}
}
| {
Self {
t: f32xN::splat(1e17),
hit: m32xN::splat(false),
p: V3DxN::default(),
n: V3DxN::default(),
}
} | identifier_body |
stats.rs | // Copyright (c) 2014 Richard Diamond & contributors.
//
// This file is part of Rust Rocket.
//
// Rust Rocket is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (... | use std::collections::HashMap;
use address::Address;
enum Message {
}
#[deriving(Clone, Encodable, Decodable)]
pub struct Router {
/// Every train yard has its own entry here:
time: Vec<u64>,
}
#[deriving(Encodable, Decodable)]
struct Session {
times: HashMap<Address, u64>,
}
#[deriving(Clone)]
pub... |
use std::comm::Sender; | random_line_split |
stats.rs | // Copyright (c) 2014 Richard Diamond & contributors.
//
// This file is part of Rust Rocket.
//
// Rust Rocket is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (... | {
times: HashMap<Address, u64>,
}
#[deriving(Clone)]
pub struct SessionIf {
chan: Sender<Message>,
}
| Session | identifier_name |
bounds.rs | // 这个 trait 实现了打印标记:`{:?}`。
use std::fmt::Debug;
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Rectangle {
fn area(&self) -> f64 { self.length * self.height }
}
#[derive(Debug)]
struct Rectangle { length: f64, height: f64 }
#[allow(dead_code)]
struct Triangle { length: f64, height: f64 }
// 泛型 ... | t: 4.0 };
print_debug(&rectangle);
println!("Area: {}", area(&rectangle));
//print_debug(&_triangle);
//println!("Area: {}", area(&_triangle));
// ^ 试一试:将上述语句的注释去掉。
// | 报错:未实现 `Debug` 或 `HasArea`。
}
| identifier_body | |
bounds.rs | // 这个 trait 实现了打印标记:`{:?}`。
use std::fmt::Debug;
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Rectangle {
fn area(&self) -> f64 { self.length * self.height }
}
#[derive(Debug)]
struct Rectangle { length: f64, height: f64 }
#[allow(dead_code)]
struct Triangle { length: f6 | t: f64 }
// 泛型 `T` 必须实现 `Debug`。不管什么类型,都可以正常工作。
fn print_debug<T: Debug>(t: &T) {
println!("{:?}", t);
}
// `T` 必须实现 `HasArea`。任意符合限定的函数都可以访问
// `HasArea` 的 `area` 函数。
fn area<T: HasArea>(t: &T) -> f64 { t.area() }
fn main() {
let rectangle = Rectangle { length: 3.0, height: 4.0 };
let _triangle = Triang... | 4, heigh | identifier_name |
bounds.rs | // 这个 trait 实现了打印标记:`{:?}`。
use std::fmt::Debug;
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Rectangle {
fn area(&self) -> f64 { self.length * self.height }
}
#[derive(Debug)]
struct Rectangle { length: f64, height: f64 }
#[allow(dead_code)] | // 泛型 `T` 必须实现 `Debug`。不管什么类型,都可以正常工作。
fn print_debug<T: Debug>(t: &T) {
println!("{:?}", t);
}
// `T` 必须实现 `HasArea`。任意符合限定的函数都可以访问
// `HasArea` 的 `area` 函数。
fn area<T: HasArea>(t: &T) -> f64 { t.area() }
fn main() {
let rectangle = Rectangle { length: 3.0, height: 4.0 };
let _triangle = Triangle { leng... | struct Triangle { length: f64, height: f64 }
| random_line_split |
is_ascii.rs | use super::{LONG, MEDIUM, SHORT};
use test::black_box;
use test::Bencher;
macro_rules! benches {
($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => {
benches!(mod short SHORT[..] $($name $arg $body)+);
benches!(mod medium MEDIUM[..] $($name $arg $body)+);
benches!(mod long LONG[..]... | return bytes.iter().all(|b| b.is_ascii());
}
// SAFETY: transmuting a sequence of `u8` to `usize` is always fine
let (head, body, tail) = unsafe { bytes.align_to::<usize>() };
head.iter().all(|b| b.is_ascii())
&& body.iter().all(|w|!contains_nonascii(*w))
&& tail.iter().all(|b| b... | // These are separate since it's easier to debug errors if they don't go through
// macro expansion first.
fn is_ascii_align_to(bytes: &[u8]) -> bool {
if bytes.len() < core::mem::size_of::<usize>() { | random_line_split |
is_ascii.rs | use super::{LONG, MEDIUM, SHORT};
use test::black_box;
use test::Bencher;
macro_rules! benches {
($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => {
benches!(mod short SHORT[..] $($name $arg $body)+);
benches!(mod medium MEDIUM[..] $($name $arg $body)+);
benches!(mod long LONG[..]... |
// SAFETY: transmuting a sequence of `u8` to `usize` is always fine
let (head, body, tail) = unsafe { bytes.align_to::<usize>() };
head.iter().all(|b| b.is_ascii())
&& body.iter().all(|w|!contains_nonascii(*w))
&& tail.iter().all(|b| b.is_ascii())
}
fn is_ascii_align_to_unrolled(bytes: &[u... | {
return bytes.iter().all(|b| b.is_ascii());
} | conditional_block |
is_ascii.rs | use super::{LONG, MEDIUM, SHORT};
use test::black_box;
use test::Bencher;
macro_rules! benches {
($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => {
benches!(mod short SHORT[..] $($name $arg $body)+);
benches!(mod medium MEDIUM[..] $($name $arg $body)+);
benches!(mod long LONG[..]... | (bytes: &[u8]) -> bool {
if bytes.len() < core::mem::size_of::<usize>() {
return bytes.iter().all(|b| b.is_ascii());
}
// SAFETY: transmuting a sequence of `u8` to `usize` is always fine
let (head, body, tail) = unsafe { bytes.align_to::<usize>() };
head.iter().all(|b| b.is_ascii())
... | is_ascii_align_to | identifier_name |
is_ascii.rs | use super::{LONG, MEDIUM, SHORT};
use test::black_box;
use test::Bencher;
macro_rules! benches {
($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => {
benches!(mod short SHORT[..] $($name $arg $body)+);
benches!(mod medium MEDIUM[..] $($name $arg $body)+);
benches!(mod long LONG[..]... |
fn is_ascii_align_to_unrolled(bytes: &[u8]) -> bool {
if bytes.len() < core::mem::size_of::<usize>() {
return bytes.iter().all(|b| b.is_ascii());
}
// SAFETY: transmuting a sequence of `u8` to `[usize; 2]` is always fine
let (head, body, tail) = unsafe { bytes.align_to::<[usize; 2]>() };
h... | {
if bytes.len() < core::mem::size_of::<usize>() {
return bytes.iter().all(|b| b.is_ascii());
}
// SAFETY: transmuting a sequence of `u8` to `usize` is always fine
let (head, body, tail) = unsafe { bytes.align_to::<usize>() };
head.iter().all(|b| b.is_ascii())
&& body.iter().all(|w| ... | identifier_body |
game_state.rs | // See LICENSE file for copyright and license details.
use crate::core::core::{Event, ObjectTypes, Unit};
use crate::core::types::{MapPos, PlayerId, UnitId};
use std::collections::HashMap;
pub struct GameState {
pub units: HashMap<UnitId, Unit>,
}
impl<'a> GameState {
pub fn new() -> GameState {
Game... | unit.pos = pos;
assert!(unit.move_points > 0);
unit.move_points = 0;
}
Event::EventEndTurn(_, new_player_id) => {
self.refresh_units(object_types, new_player_id.clone());
}
Event::EventCreateUnit(id, pos, typ... | let unit = self.units.get_mut(&id).unwrap(); | random_line_split |
game_state.rs | // See LICENSE file for copyright and license details.
use crate::core::core::{Event, ObjectTypes, Unit};
use crate::core::types::{MapPos, PlayerId, UnitId};
use std::collections::HashMap;
pub struct GameState {
pub units: HashMap<UnitId, Unit>,
}
impl<'a> GameState {
pub fn new() -> GameState {
Game... | (&mut self, object_types: &ObjectTypes, player_id: PlayerId) {
for (_, unit) in self.units.iter_mut() {
if unit.player_id == player_id {
unit.move_points = object_types.get_unit_type(unit.type_id).move_points;
unit.attacked = false;
}
}
}
... | refresh_units | identifier_name |
game_state.rs | // See LICENSE file for copyright and license details.
use crate::core::core::{Event, ObjectTypes, Unit};
use crate::core::types::{MapPos, PlayerId, UnitId};
use std::collections::HashMap;
pub struct GameState {
pub units: HashMap<UnitId, Unit>,
}
impl<'a> GameState {
pub fn new() -> GameState {
Game... |
}
}
pub fn apply_event(&mut self, object_types: &ObjectTypes, event: &Event) {
match event {
Event::EventMove(id, ref path) => {
let pos = *path.last().unwrap();
let unit = self.units.get_mut(&id).unwrap();
unit.pos = pos;
... | {
unit.move_points = object_types.get_unit_type(unit.type_id).move_points;
unit.attacked = false;
} | conditional_block |
game_state.rs | // See LICENSE file for copyright and license details.
use crate::core::core::{Event, ObjectTypes, Unit};
use crate::core::types::{MapPos, PlayerId, UnitId};
use std::collections::HashMap;
pub struct GameState {
pub units: HashMap<UnitId, Unit>,
}
impl<'a> GameState {
pub fn new() -> GameState {
Game... |
fn refresh_units(&mut self, object_types: &ObjectTypes, player_id: PlayerId) {
for (_, unit) in self.units.iter_mut() {
if unit.player_id == player_id {
unit.move_points = object_types.get_unit_type(unit.type_id).move_points;
unit.attacked = false;
}... | {
let mut units = Vec::new();
for (_, unit) in self.units.iter() {
if unit.pos == pos {
units.push(unit);
}
}
units
} | identifier_body |
syntax_definition.rs | //! Data structures for representing syntax definitions
//!
//! Everything here is public becaues I want this library to be useful in super integrated cases
//! like text editors and I have no idea what kind of monkeying you might want to do with the data.
//! Perhaps parsing your own syntax format into this data struc... | {
pub meta_scope: Vec<Scope>,
pub meta_content_scope: Vec<Scope>,
/// This being set false in the syntax file implies this field being set false,
/// but it can also be set falso for contexts that don't include the prototype for other reasons
pub meta_include_prototype: bool,
pub clear_scopes: ... | Context | identifier_name |
syntax_definition.rs | //! Data structures for representing syntax definitions
//!
//! Everything here is public becaues I want this library to be useful in super integrated cases
//! like text editors and I have no idea what kind of monkeying you might want to do with the data.
//! Perhaps parsing your own syntax format into this data struc... | Pattern::Match(ref match_pat) => match_pat,
_ => panic!("bad index to match_at"),
}
}
}
impl ContextReference {
/// find the pointed to context, panics if ref is not linked
pub fn resolve<'a>(&self, syntax_set: &'a SyntaxSet) -> &'a Context {
match *self {
... | random_line_split | |
roerrorapi.rs | // Copyright © 2017 winapi-rs developers | // 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.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | random_line_split | |
xmldocument.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 document_loader::DocumentLoader;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use d... | }
doc
}
}
impl XMLDocumentMethods for XMLDocument {
// https://html.spec.whatwg.org/multipage/#dom-document-location
fn GetLocation(&self) -> Option<DomRoot<Location>> {
self.upcast::<Document>().GetLocation()
}
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors... | {
let doc = reflect_dom_object(
Box::new(XMLDocument::new_inherited(
window,
has_browsing_context,
url,
origin,
doctype,
content_type,
last_modified,
activity,
... | identifier_body |
xmldocument.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 document_loader::DocumentLoader;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use d... | (window: &Window,
has_browsing_context: HasBrowsingContext,
url: Option<ServoUrl>,
origin: MutableOrigin,
is_html_document: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option... | new_inherited | identifier_name |
xmldocument.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 document_loader::DocumentLoader;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use d... | // https://html.spec.whatwg.org/multipage/#dom-document-location
fn GetLocation(&self) -> Option<DomRoot<Location>> {
self.upcast::<Document>().GetLocation()
}
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names
fn SupportedPropertyNames(&self) -> Vec<DOMS... | impl XMLDocumentMethods for XMLDocument { | random_line_split |
wrap_unhygienic_example.rs | // Copyright 2017 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 ... | // (c)
::unhygienic_example::unhygienic_macro!();
// ^ Even though we invoke an unhygienic macro, `hygienic_macro` remains hygienic.
// In the above expansion:
// (1) `my_crate` always resolves to (b) regardless of invocation site.
// (2) The defined function `f` is only usable inside this macro de... | {} | identifier_body |
wrap_unhygienic_example.rs | // Copyright 2017 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 ... |
#[allow(unused)]
fn test_hygienic_macro() {
hygienic_macro!();
fn f() {} // (d) no conflict
f(); // resolves to (d)
}
fn main() {} |
f();
} | random_line_split |
wrap_unhygienic_example.rs | // Copyright 2017 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 ... | () {}
| main | identifier_name |
texture.rs | use glium::{self, backend::Facade, texture::Texture2d};
use crate::backend::{Direction, Position, ASSETS};
pub struct Textures {
pub crate_: Texture2d,
pub floor: Texture2d,
pub goal: Texture2d,
pub wall: Texture2d,
pub worker: Texture2d,
}
impl Textures {
/// Load all textures.
pub fn ne... | (display: &dyn Facade, name: &str) -> Texture2d {
let mut path = ASSETS.join("images");
path.push(name);
path.set_extension("png");
let image = image::open(path).unwrap().to_rgba();
let image_dimensions = image.dimensions();
let image =
glium::texture::RawImage2d::from_raw_rgba_reversed(... | load | identifier_name |
texture.rs | use glium::{self, backend::Facade, texture::Texture2d};
use crate::backend::{Direction, Position, ASSETS};
pub struct Textures {
pub crate_: Texture2d,
pub floor: Texture2d,
pub goal: Texture2d,
pub wall: Texture2d,
pub worker: Texture2d,
}
impl Textures {
/// Load all textures.
pub fn ne... | }
/// Create a rectangle covering the entire viewport.
pub fn full_screen() -> Vec<Vertex> {
lrtb_to_vertices(-1.0, 1.0, -1.0, 1.0, Direction::Left)
} | random_line_split | |
texture.rs | use glium::{self, backend::Facade, texture::Texture2d};
use crate::backend::{Direction, Position, ASSETS};
pub struct Textures {
pub crate_: Texture2d,
pub floor: Texture2d,
pub goal: Texture2d,
pub wall: Texture2d,
pub worker: Texture2d,
}
impl Textures {
/// Load all textures.
pub fn ne... |
/// Create a rectangle covering the entire viewport.
pub fn full_screen() -> Vec<Vertex> {
lrtb_to_vertices(-1.0, 1.0, -1.0, 1.0, Direction::Left)
}
| {
let left = 2.0 * pos.x as f32 / columns as f32 - 1.0;
let right = left + 2.0 / columns as f32;
let bottom = -2.0 * pos.y as f32 / rows as f32 + 1.0;
let top = bottom - 2.0 / rows as f32;
lrtb_to_vertices(left, right, top, bottom, Direction::Left)
} | identifier_body |
bench.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 ... | roughput!(easy0_32, easy0(), 32);
throughput!(easy0_1K, easy0(), 1<<10);
throughput!(easy0_32K, easy0(), 32<<10);
throughput!(easy0_1MB, easy0(), 1<<20);
throughput!(easy1_32, easy1(), 32);
throughput!(easy1_1K, easy1(), 1<<10);
throughput!(easy1_32K, easy1(), 32<<10);
throughput!(easy1_1MB, easy1(), 1<<20);
throughp... | let mut rng = thread_rng();
let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n)
.collect::<Vec<u8>>();
for (i, b) in bytes.iter_mut().enumerate() {
if i % 20 == 0 {
*b = b'\n'
}
}
String::from_utf8(bytes).unwrap()
}
th | identifier_body |
bench.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 ... | }
#[bench]
fn anchored_literal_short_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text: String = repeat("abcdefghijklmnopq... | fn anchored_literal_long_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text: String = repeat("abcdefghijklmnopqrstuvwxyz").take(15).collect();
b.iter(|| re.is_match(&text)); | random_line_split |
bench.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 ... | (b: &mut Bencher, re: Regex, text: &str) {
b.iter(|| if!re.is_match(text) { panic!("no match") });
}
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let regex_string = format!(
"{}{}",
repeat("a?").take(n).collect::<String>(),
repeat("a").take(n).collect::<String>());
... | bench_assert_match | identifier_name |
bench.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 ... | );
}
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let regex_string = format!(
"{}{}",
repeat("a?").take(n).collect::<String>(),
repeat("a").take(n).collect::<String>());
let re = Regex::new(®ex_string).unwrap();
let text: String = repeat("a").take(n).collect();
... | { panic!("no match") } | conditional_block |
mutex.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 ... | // dropped, that's not our job)
unsafe { self.inner.lock.destroy() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + fmt::Debug +'static> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.try_lock() {
Ok(guard) => w... | #[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Drop for Mutex<T> {
fn drop(&mut self) {
// This is actually safe b/c we know that there is no further usage of
// this mutex (it's up to the user to arrange for a mutex to get | random_line_split |
mutex.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 ... | {
i: Arc<Mutex<i32>>,
}
impl Drop for Unwinder {
fn drop(&mut self) {
*self.i.lock().unwrap() += 1;
}
}
let _u = Unwinder { i: arc2 };
panic!();
}).join();
let lock = arc.lock... | Unwinder | identifier_name |
cgs.rs | use super::*;
pub fn new() -> System {
System {
name: "CGS",
module: "cgs",
doc_prelude: "The Gaussian CGS unit system
Note: this system is incomplete. More derived units and constants are coming.
",
base: base_units!(
SQRTCM: SqrtCentimeter, sqrtcm;
SQRTG:... |
S2: Second2 = Second * Second;
S3: Second3 = Second2 * Second;
S4: Second4 = Second3 * Second;
CMPS: CentimeterPerSecond = Centimeter / Second, Velocity;
CMPS3: CentimeterPerSecond3 = Centimeter / Second3, Jerk;
CMPS4: CentimeterPerSecond4 = Cent... | CM: Centimeter = SqrtCentimeter * SqrtCentimeter, Length;
G: Gram = SqrtGram * SqrtGram, Mass;
CM2: Centimeter2 = Centimeter * Centimeter, Area;
CM3: Centimeter3 = Centimeter2 * Centimeter, Volume; | random_line_split |
cgs.rs | use super::*;
pub fn new() -> System |
S2: Second2 = Second * Second;
S3: Second3 = Second2 * Second;
S4: Second4 = Second3 * Second;
CMPS: CentimeterPerSecond = Centimeter / Second, Velocity;
CMPS3: CentimeterPerSecond3 = Centimeter / Second3, Jerk;
CMPS4: CentimeterPerSecond4 = Cent... | {
System {
name: "CGS",
module: "cgs",
doc_prelude: "The Gaussian CGS unit system
Note: this system is incomplete. More derived units and constants are coming.
",
base: base_units!(
SQRTCM: SqrtCentimeter, sqrtcm;
SQRTG: SqrtGram, sqrtg;
S: Secon... | identifier_body |
cgs.rs | use super::*;
pub fn | () -> System {
System {
name: "CGS",
module: "cgs",
doc_prelude: "The Gaussian CGS unit system
Note: this system is incomplete. More derived units and constants are coming.
",
base: base_units!(
SQRTCM: SqrtCentimeter, sqrtcm;
SQRTG: SqrtGram, sqrtg;
... | new | identifier_name |
no_0491_increasing_subsequences.rs | struct Solution;
impl Solution {
pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> |
fn dfs(cur: usize, last: i32, nums: &Vec<i32>, temp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if cur == nums.len() {
if temp.len() >= 2 {
ans.push(temp.clone());
}
return;
}
let cur_val = nums[cur];
if cur_val >= last {
... | {
let mut temp = Vec::new();
let mut ans = Vec::new();
Self::dfs(0, std::i32::MIN, &nums, &mut temp, &mut ans);
ans
} | identifier_body |
no_0491_increasing_subsequences.rs | struct Solution;
impl Solution {
pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut temp = Vec::new();
let mut ans = Vec::new();
Self::dfs(0, std::i32::MIN, &nums, &mut temp, &mut ans);
ans
}
fn dfs(cur: usize, last: i32, nums: &Vec<i32>, temp: &mut Vec<i32>... |
return;
}
let cur_val = nums[cur];
if cur_val >= last {
temp.push(cur_val);
Self::dfs(cur + 1, cur_val, nums, temp, ans);
temp.pop();
}
if cur_val!= last {
Self::dfs(cur + 1, last, nums, temp, ans);
}
}
}
#... | {
ans.push(temp.clone());
} | conditional_block |
no_0491_increasing_subsequences.rs | struct Solution;
impl Solution {
pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut temp = Vec::new();
let mut ans = Vec::new();
Self::dfs(0, std::i32::MIN, &nums, &mut temp, &mut ans);
ans
}
fn | (cur: usize, last: i32, nums: &Vec<i32>, temp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if cur == nums.len() {
if temp.len() >= 2 {
ans.push(temp.clone());
}
return;
}
let cur_val = nums[cur];
if cur_val >= last {
temp.push... | dfs | identifier_name |
no_0491_increasing_subsequences.rs | struct Solution;
impl Solution {
pub fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut temp = Vec::new();
let mut ans = Vec::new();
Self::dfs(0, std::i32::MIN, &nums, &mut temp, &mut ans);
ans
}
fn dfs(cur: usize, last: i32, nums: &Vec<i32>, temp: &mut Vec<i32>... | }
} | random_line_split | |
index.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | <E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
#[test]
fn block_number_deserialization() {
let s = r#"["0xa", "10"]"#;
let deserialized: Vec<Index> = serde_json::from_str(s).unwrap();
asser... | visit_string | identifier_name |
index.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
| {
let s = r#"["0xa", "10"]"#;
let deserialized: Vec<Index> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![Index(10), Index(10)]);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.