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 |
|---|---|---|---|---|
build.rs | #[cfg(target_os="macos")]
fn build_flags(){
println!("cargo:rustc-flags= -L framework=/Library/Frameworks");
}
#[cfg(target_os="linux")]
fn build_flags(){
}
#[cfg(target_os="windows")]
extern crate libc;
#[cfg(target_os="windows")]
use std::env;
#[cfg(target_os="windows")]
use std::mem;
#[cfg(target_os="windows")]... |
}
fn main(){
build_flags();
}
| {
println!("error: GSTREAMER_1_0_ROOT_X86 var not present, probably gstreamer is not installed");
} | conditional_block |
build.rs | #[cfg(target_os="macos")]
fn build_flags(){
println!("cargo:rustc-flags= -L framework=/Library/Frameworks");
}
#[cfg(target_os="linux")]
fn build_flags() |
#[cfg(target_os="windows")]
extern crate libc;
#[cfg(target_os="windows")]
use std::env;
#[cfg(target_os="windows")]
use std::mem;
#[cfg(target_os="windows")]
fn build_flags(){
let key = if cfg!(target_pointer_width = "32") {
"GSTREAMER_1_0_ROOT_X86"
}else{
"GSTREAMER_1_0_ROOT_X86_64"
};
if let Ok(gst_root) ... | {
} | identifier_body |
print_cfg.rs | //! The `print-cfg` sub-command.
//!
//! Read a series of Cranelift IR files and print their control flow graphs
//! in graphviz format.
use crate::utils::read_to_string;
use crate::CommandResult;
use cranelift_codegen::cfg_printer::CFGPrinter;
use cranelift_reader::parse_functions;
pub fn run(files: &[String]) -> Co... |
print!("{}", CFGPrinter::new(&func));
}
Ok(())
}
| {
println!();
} | conditional_block |
print_cfg.rs | //! The `print-cfg` sub-command.
//!
//! Read a series of Cranelift IR files and print their control flow graphs
//! in graphviz format.
use crate::utils::read_to_string;
use crate::CommandResult;
use cranelift_codegen::cfg_printer::CFGPrinter;
use cranelift_reader::parse_functions;
pub fn run(files: &[String]) -> Co... | (filename: &str) -> CommandResult {
let buffer = read_to_string(filename).map_err(|e| format!("{}: {}", filename, e))?;
let items = parse_functions(&buffer).map_err(|e| format!("{}: {}", filename, e))?;
for (idx, func) in items.into_iter().enumerate() {
if idx!= 0 {
println!();
... | print_cfg | identifier_name |
print_cfg.rs | //! The `print-cfg` sub-command.
//!
//! Read a series of Cranelift IR files and print their control flow graphs
//! in graphviz format.
use crate::utils::read_to_string;
use crate::CommandResult;
use cranelift_codegen::cfg_printer::CFGPrinter;
use cranelift_reader::parse_functions;
pub fn run(files: &[String]) -> Co... |
fn print_cfg(filename: &str) -> CommandResult {
let buffer = read_to_string(filename).map_err(|e| format!("{}: {}", filename, e))?;
let items = parse_functions(&buffer).map_err(|e| format!("{}: {}", filename, e))?;
for (idx, func) in items.into_iter().enumerate() {
if idx!= 0 {
printl... | {
for (i, f) in files.into_iter().enumerate() {
if i != 0 {
println!();
}
print_cfg(f)?
}
Ok(())
} | identifier_body |
print_cfg.rs | //! The `print-cfg` sub-command.
//!
//! Read a series of Cranelift IR files and print their control flow graphs
//! in graphviz format.
use crate::utils::read_to_string;
use crate::CommandResult;
use cranelift_codegen::cfg_printer::CFGPrinter;
use cranelift_reader::parse_functions;
| }
print_cfg(f)?
}
Ok(())
}
fn print_cfg(filename: &str) -> CommandResult {
let buffer = read_to_string(filename).map_err(|e| format!("{}: {}", filename, e))?;
let items = parse_functions(&buffer).map_err(|e| format!("{}: {}", filename, e))?;
for (idx, func) in items.into_iter().enu... | pub fn run(files: &[String]) -> CommandResult {
for (i, f) in files.into_iter().enumerate() {
if i != 0 {
println!(); | random_line_split |
lib.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | pub mod set;
pub mod string;
pub mod url;
#[cfg(test)]
pub mod test {
#[test]
fn test_stuff() {
use base::TCFType;
use boolean::CFBoolean;
use number::number;
use dictionary::CFDictionary;
use string::CFString;
/*let n = CFNumber::new_number(42 as i32);
... | pub mod number; | random_line_split |
lib.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | (baz.as_CFType(), tru.as_CFType()),
(foo.as_CFType(), n42.as_CFType()),
]);
}
}
| {
use base::TCFType;
use boolean::CFBoolean;
use number::number;
use dictionary::CFDictionary;
use string::CFString;
/*let n = CFNumber::new_number(42 as i32);
io::println(format!("%d", (&n).retain_count() as int));
(&n).show();*/
let bar = CFStr... | identifier_body |
lib.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | () {
use base::TCFType;
use boolean::CFBoolean;
use number::number;
use dictionary::CFDictionary;
use string::CFString;
/*let n = CFNumber::new_number(42 as i32);
io::println(format!("%d", (&n).retain_count() as int));
(&n).show();*/
let bar = CF... | test_stuff | identifier_name |
goaway_frame.rs | use std::io::Cursor;
use byteorder::{WriteBytesExt, ReadBytesExt, BigEndian};
use error::Result;
#[derive(Debug, PartialEq)]
pub struct GoAwayFrame {
pub largest_client_stream_id: u32,
pub largest_server_stream_id: u32,
}
impl GoAwayFrame {
pub fn as_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::... |
assert_eq!(frame, parsed_frame);
}
} | random_line_split | |
goaway_frame.rs | use std::io::Cursor;
use byteorder::{WriteBytesExt, ReadBytesExt, BigEndian};
use error::Result;
#[derive(Debug, PartialEq)]
pub struct GoAwayFrame {
pub largest_client_stream_id: u32,
pub largest_server_stream_id: u32,
}
impl GoAwayFrame {
pub fn as_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::... | () {
let frame = GoAwayFrame {
largest_client_stream_id: 634632634,
largest_server_stream_id: 235962,
};
let frame_bytes = frame.as_bytes();
let parsed_frame = GoAwayFrame::from_bytes(&frame_bytes).unwrap();
assert_eq!(frame, parsed_frame);
}
} | serialize | identifier_name |
goaway_frame.rs | use std::io::Cursor;
use byteorder::{WriteBytesExt, ReadBytesExt, BigEndian};
use error::Result;
#[derive(Debug, PartialEq)]
pub struct GoAwayFrame {
pub largest_client_stream_id: u32,
pub largest_server_stream_id: u32,
}
impl GoAwayFrame {
pub fn as_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::... |
pub fn frame_len() -> Result<usize> {
Ok(9)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialize() {
let frame = GoAwayFrame {
largest_client_stream_id: 634632634,
largest_server_stream_id: 235962,
};
let frame_bytes = frame.as_... | {
let mut reader = Cursor::new(buf);
let _ = reader.read_u8()?;
let largest_client_stream_id = reader.read_u32::<BigEndian>()?;
let largest_server_stream_id = reader.read_u32::<BigEndian>()?;
Ok(GoAwayFrame {
largest_client_stream_id: largest_client_stream_id,
... | identifier_body |
xml.rs | //! Interface to libxml2.
use remacs_macros::lisp_fn;
use crate::{lisp::LispObject, remacs_sys::Qnil};
#[cfg(feature = "use-xml2")]
use crate::remacs_sys::{init_libxml2_functions, parse_region};
#[cfg(feature = "use-xml2")]
fn libxml_parse_region(
start: LispObject,
end: LispObject,
base_url: LispObject... |
include!(concat!(env!("OUT_DIR"), "/xml_exports.rs")); | random_line_split | |
xml.rs | //! Interface to libxml2.
use remacs_macros::lisp_fn;
use crate::{lisp::LispObject, remacs_sys::Qnil};
#[cfg(feature = "use-xml2")]
use crate::remacs_sys::{init_libxml2_functions, parse_region};
#[cfg(feature = "use-xml2")]
fn libxml_parse_region(
start: LispObject,
end: LispObject,
base_url: LispObject... |
/// Parse the region as an XML document and return the parse tree.
/// If BASE-URL is non-nil, it is used to expand relative URLs.
/// If DISCARD-COMMENTS is non-nil, all HTML comments are discarded.
#[lisp_fn(min = "2")]
pub fn libxml_parse_xml_region(
start: LispObject,
end: LispObject,
base_url: LispOb... | {
libxml_parse_region(start, end, base_url, discard_comments, true)
} | identifier_body |
xml.rs | //! Interface to libxml2.
use remacs_macros::lisp_fn;
use crate::{lisp::LispObject, remacs_sys::Qnil};
#[cfg(feature = "use-xml2")]
use crate::remacs_sys::{init_libxml2_functions, parse_region};
#[cfg(feature = "use-xml2")]
fn libxml_parse_region(
start: LispObject,
end: LispObject,
base_url: LispObject... | else {
Qnil
}
}
}
#[cfg(not(feature = "use-xml2"))]
fn libxml_parse_region(
_start: LispObject,
_end: LispObject,
_base_url: LispObject,
_discard_comments: LispObject,
_htmlp: bool,
) -> LispObject {
Qnil
}
/// Parse the region as an HTML document and return the parse ... | {
parse_region(start, end, base_url, discard_comments, htmlp)
} | conditional_block |
xml.rs | //! Interface to libxml2.
use remacs_macros::lisp_fn;
use crate::{lisp::LispObject, remacs_sys::Qnil};
#[cfg(feature = "use-xml2")]
use crate::remacs_sys::{init_libxml2_functions, parse_region};
#[cfg(feature = "use-xml2")]
fn | (
start: LispObject,
end: LispObject,
base_url: LispObject,
discard_comments: LispObject,
htmlp: bool,
) -> LispObject {
unsafe {
if init_libxml2_functions() {
parse_region(start, end, base_url, discard_comments, htmlp)
} else {
Qnil
}
}
}
#[c... | libxml_parse_region | identifier_name |
unique_items.rs | use serde_json::Value;
use super::super::schema;
use super::super::validators;
#[allow(missing_copy_implementations)]
pub struct UniqueItems;
impl super::Keyword for UniqueItems {
fn | (&self, def: &Value, ctx: &schema::WalkContext<'_>) -> super::KeywordResult {
let uniq = keyword_key_exists!(def, "uniqueItems");
if uniq.is_boolean() {
if uniq.as_bool().unwrap() {
Ok(Some(Box::new(validators::UniqueItems)))
} else {
Ok(None)
... | compile | identifier_name |
unique_items.rs | use serde_json::Value;
use super::super::schema;
use super::super::validators;
#[allow(missing_copy_implementations)]
pub struct UniqueItems;
impl super::Keyword for UniqueItems {
fn compile(&self, def: &Value, ctx: &schema::WalkContext<'_>) -> super::KeywordResult {
let uniq = keyword_key_exists!(def, "u... |
}
}
#[cfg(test)]
use super::super::builder;
#[cfg(test)]
use super::super::scope;
#[cfg(test)]
use serde_json::to_value;
#[test]
fn validate_unique_items() {
let mut scope = scope::Scope::new();
let schema = scope
.compile_and_return(builder::schema(|s| s.unique_items(true)).into_json(), true)
... | {
Err(schema::SchemaError::Malformed {
path: ctx.fragment.join("/"),
detail: "The value of pattern MUST be boolean".to_string(),
})
} | conditional_block |
unique_items.rs | use serde_json::Value;
use super::super::schema;
use super::super::validators;
#[allow(missing_copy_implementations)]
pub struct UniqueItems;
impl super::Keyword for UniqueItems {
fn compile(&self, def: &Value, ctx: &schema::WalkContext<'_>) -> super::KeywordResult {
let uniq = keyword_key_exists!(def, "u... |
assert_eq!(
schema
.validate(&to_value(&[1, 2, 3, 4]).unwrap())
.is_valid(),
true
);
assert_eq!(
schema
.validate(&to_value(&[1, 1, 3, 4]).unwrap())
.is_valid(),
false
);
} | let mut scope = scope::Scope::new();
let schema = scope
.compile_and_return(builder::schema(|s| s.unique_items(true)).into_json(), true)
.ok()
.unwrap(); | random_line_split |
stratum.rs | // Copyright 2015-2017 Parity Technologies (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 lat... | use nanoipc;
use std::thread;
use ethcore::miner::stratum::{STRATUM_SOCKET_NAME, JOB_DISPATCHER_SOCKET_NAME};
pub const MODULE_ID: IpcModuleId = 8000;
#[derive(Default)]
struct StratumControlService {
pub stop: Arc<AtomicBool>,
}
impl ControlService for StratumControlService {
fn shutdown(&self) -> bool {
trace!... | use std::str::FromStr; | random_line_split |
stratum.rs | // Copyright 2015-2017 Parity Technologies (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 lat... | () {
boot::setup_cli_logger("stratum");
let service_config: ServiceConfiguration = boot::payload()
.unwrap_or_else(|e| {
println!("Fatal: error reading boot arguments ({:?})", e);
std::process::exit(1)
});
let job_dispatcher = dependency!(
RemoteJobDispatcher,
&service_urls::with_base(&service_config... | main | identifier_name |
ops.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) {
b.iter(|| {
HasDtor { _x : 10 };
})
}
// Test the Range structs without the syntactic sugar.
#[test]
fn test_range() {
let r = Range { start: 2, end: 10 };
let mut count = 0;
for (i, ri) in r.enumerate() {
assert!(ri == i + 2);
assert!(ri >= 2 && ri < 10... | alloc_obj_with_dtor | identifier_name |
ops.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 ... |
#[test]
fn test_range_from() {
let r = RangeFrom { start: 2 };
let mut count = 0;
for (i, ri) in r.take(10).enumerate() {
assert!(ri == i + 2);
assert!(ri >= 2 && ri < 12);
count += 1;
}
assert!(count == 10);
}
#[test]
fn test_range_to() {
// Not much to test.
let ... | {
let r = Range { start: 2, end: 10 };
let mut count = 0;
for (i, ri) in r.enumerate() {
assert!(ri == i + 2);
assert!(ri >= 2 && ri < 10);
count += 1;
}
assert!(count == 8);
} | identifier_body |
ops.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 ... | count += 1;
}
assert!(count == 10);
}
#[test]
fn test_range_to() {
// Not much to test.
let _ = RangeTo { end: 42 };
}
#[test]
fn test_full_range() {
// Not much to test.
let _ = RangeFull;
} | assert!(ri >= 2 && ri < 12); | random_line_split |
borrowck-struct-update-with-dtor.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
// Issue 4691: Ensure that functional-struct-update can only copy, not
// move, when the struct implements Drop.
struct B;
struct S { a: isize, b: B }
impl ... | // 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 | random_line_split |
borrowck-struct-update-with-dtor.rs | // Copyright 2012-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-MI... | }
fn f(s0:S) {
let _s2 = S{a: 2,..s0};
//[ast]~^ error: cannot move out of type `S`, which implements the `Drop` trait
//[mir]~^^ ERROR [E0509]
}
fn g(s0:T) {
let _s2 = T{a: 2,..s0};
//[ast]~^ error: cannot move out of type `T`, which implements the `Drop` trait
//[mir]~^^ ERROR [E0509]
}
fn... | { } | identifier_body |
borrowck-struct-update-with-dtor.rs | // Copyright 2012-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-MI... | (&mut self) { } }
struct T { a: isize, mv: Box<isize> }
impl Drop for T { fn drop(&mut self) { } }
fn f(s0:S) {
let _s2 = S{a: 2,..s0};
//[ast]~^ error: cannot move out of type `S`, which implements the `Drop` trait
//[mir]~^^ ERROR [E0509]
}
fn g(s0:T) {
let _s2 = T{a: 2,..s0};
//[ast]~^ error: ... | drop | identifier_name |
lib.rs | //! IPv4 and IPv6 network structs.
//!
//! ## Optional features
//!
//! When using this crate, you can choose to compile with these features:
//!
//! * `serde` – for serialization and deserialization by [Serde framework](https://serde.rs).
//! * `diesel` – support for [PostgreSQL CIDR type] with [Diesel ORM](https://di... | , fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
IpNetworkParseError::InvalidNetmaskFormat => write!(fmt, "invalid netmask format"),
IpNetworkParseError::InvalidFormatError => write!(fmt, "invalid format"),
IpNetworkParseError::AddrParseError => write!(fmt, "invalid... | elf | identifier_name |
lib.rs | //! IPv4 and IPv6 network structs.
//!
//! ## Optional features
//!
//! When using this crate, you can choose to compile with these features:
//!
//! * `serde` – for serialization and deserialization by [Serde framework](https://serde.rs).
//! * `diesel` – support for [PostgreSQL CIDR type] with [Diesel ORM](https://di... | }
impl fmt::Display for IpNetworkParseError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
IpNetworkParseError::InvalidNetmaskFormat => write!(fmt, "invalid netmask format"),
IpNetworkParseError::InvalidFormatError => write!(fmt, "invalid format"),
... | _ => None,
}
} | random_line_split |
mod.rs | //! Contains traits with platform-specific methods in them.
//!
//! Contains the following modules:
//!
//! - `android`
//! - `ios`
//! - `macos`
//! - `unix`
//! - `windows`
//!
/// Platform-specific methods for android.
pub mod android;
/// Platform-specific methods for iOS.
pub mod ios;
/// Platform-specific m... | } | random_line_split | |
parser-bench.rs | #![cfg(test)]
extern crate esprit;
extern crate estree;
extern crate joker;
extern crate serde_json;
// From 'rustc-test' crate.
// Mirrors Rust's internal 'libtest'.
// https://doc.rust-lang.org/1.1.0/test/index.html
extern crate test;
extern crate unjson;
use esprit::script;
use estree::IntoScript;
use joker::tra... | () {
let args: Vec<_> = env::args().collect();
let bench = args.contains(&"--bench".to_string());
let ignore_integration_tests =!bench && env::var_os("ESTREE_INTEGRATION_TESTS") == None;
if ignore_integration_tests {
println!("note: Run with `ESTREE_INTEGRATION_TESTS=1` to run with integration t... | main | identifier_name |
parser-bench.rs | #![cfg(test)]
extern crate esprit;
extern crate estree;
extern crate joker;
extern crate serde_json;
// From 'rustc-test' crate.
// Mirrors Rust's internal 'libtest'.
// https://doc.rust-lang.org/1.1.0/test/index.html
extern crate test;
extern crate unjson;
use esprit::script;
use estree::IntoScript;
use joker::tra... |
fn integration_tests(target: &mut Vec<TestDescAndFn>, ignore: bool) {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let fixtures = {
let mut fixtures = root.to_path_buf();
fixtures.push("tests");
fixtures.push("esprima");
fixtures.push("test");
fixtures.push("3rdpa... | {
tests.push(TestDescAndFn {
desc: TestDesc {
name: TestName::DynTestName(name),
ignore: ignore,
should_panic: No
},
testfn: TestFn::DynBenchFn(Box::new(DynBenchFn { run: f }))
});
} | identifier_body |
parser-bench.rs | #![cfg(test)]
extern crate esprit;
extern crate estree;
extern crate joker;
extern crate serde_json;
// From 'rustc-test' crate.
// Mirrors Rust's internal 'libtest'.
// https://doc.rust-lang.org/1.1.0/test/index.html
extern crate test;
extern crate unjson;
use esprit::script;
use estree::IntoScript;
use joker::tra... | })
// First collect to evaluate iterator and spawn threads
.collect::<Vec<_>>()
.into_iter()
.map(|(name, thread)| {
let (source, expected_ast) = thread.join().unwrap();
(name, source, expected_ast)
})
// Then collect results from threads so ... | random_line_split | |
generate.rs | extern crate sodiumoxide;
| pub upper: bool,
pub digit: bool,
pub sym: bool,
}
fn get_chars(opts: &PasswCharset) -> Result<Vec<char>, String> {
let mut chars = Vec::new();
if opts.lower {
chars.extend("abcdefghijklmnopqrstuvwxyz".chars());
};
if opts.upper {
chars.extend("ABCDEFGHIJKLMNOPQRSTUVWXYZ".ch... | use crypto;
pub struct PasswCharset {
pub lower: bool, | random_line_split |
generate.rs | extern crate sodiumoxide;
use crypto;
pub struct PasswCharset {
pub lower: bool,
pub upper: bool,
pub digit: bool,
pub sym: bool,
}
fn get_chars(opts: &PasswCharset) -> Result<Vec<char>, String> {
let mut chars = Vec::new();
if opts.lower {
chars.extend("abcdefghijklmnopqrstuvwxyz".ch... | (len: usize, numchars: usize) -> i64 {
let perchar = (numchars as f64).log2();
let total = (len as f64) * perchar;
total as i64
}
pub fn generate(len: usize, opts: &PasswCharset) -> Result<(String, i64), String> {
let chars = get_chars(opts)?;
let mut pw = String::new();
pw.reserve(len);
... | get_entropy | identifier_name |
generate.rs | extern crate sodiumoxide;
use crypto;
pub struct PasswCharset {
pub lower: bool,
pub upper: bool,
pub digit: bool,
pub sym: bool,
}
fn get_chars(opts: &PasswCharset) -> Result<Vec<char>, String> {
let mut chars = Vec::new();
if opts.lower {
chars.extend("abcdefghijklmnopqrstuvwxyz".ch... | else {
Ok(chars)
}
}
fn get_entropy(len: usize, numchars: usize) -> i64 {
let perchar = (numchars as f64).log2();
let total = (len as f64) * perchar;
total as i64
}
pub fn generate(len: usize, opts: &PasswCharset) -> Result<(String, i64), String> {
let chars = get_chars(opts)?;
let m... | {
Err("No characters enabled for password generation".into())
} | conditional_block |
josephus_problem.rs | // http://rosettacode.org/wiki/Josephus_problem
// implementation based on observation:
// `josephus(n, k) == if n < 2 { 0 } else { (josephus(n - 1, k) + k) % n }`
fn josephus(n: u32, k: u32) -> u32 {
let mut result = 0u32;
for i in 2..(n+1) {
result = (result + k) % i;
};
result
}
#[cfg(not(... | () {
assert!(josephus(5, 2) == 2);
assert!(josephus(41, 3) == 30);
}
}
| test | identifier_name |
josephus_problem.rs | // http://rosettacode.org/wiki/Josephus_problem
// implementation based on observation: | result = (result + k) % i;
};
result
}
#[cfg(not(test))]
fn main() {
let n = 5;
let k = 2;
println!("n: {} k: {} survivor: {}", n, k, josephus(n, k));
}
#[cfg(test)]
mod test {
use super::josephus;
#[test]
fn test() {
assert!(josephus(5, 2) == 2);
assert!(josep... | // `josephus(n, k) == if n < 2 { 0 } else { (josephus(n - 1, k) + k) % n }`
fn josephus(n: u32, k: u32) -> u32 {
let mut result = 0u32;
for i in 2..(n+1) { | random_line_split |
josephus_problem.rs | // http://rosettacode.org/wiki/Josephus_problem
// implementation based on observation:
// `josephus(n, k) == if n < 2 { 0 } else { (josephus(n - 1, k) + k) % n }`
fn josephus(n: u32, k: u32) -> u32 {
let mut result = 0u32;
for i in 2..(n+1) {
result = (result + k) % i;
};
result
}
#[cfg(not(... |
}
| {
assert!(josephus(5, 2) == 2);
assert!(josephus(41, 3) == 30);
} | identifier_body |
clean.rs | use std::env;
use cargo::core::Workspace;
use cargo::ops;
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
#[derive(Deserialize)]
pub struct | {
flag_package: Vec<String>,
flag_target: Option<String>,
flag_manifest_path: Option<String>,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
flag_release: bool,
flag_frozen: bool,
flag_locked: bool,
#[serde(rename = "flag_Z")]
flag_z: Vec<String>,
}... | Options | identifier_name |
clean.rs | use std::env;
use cargo::core::Workspace;
use cargo::ops;
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
#[derive(Deserialize)]
pub struct Options {
flag_package: Vec<String>,
flag_target: Option<String>,
flag_manifest_path: Option<String>,
flag_ve... | flag_z: Vec<String>,
}
pub const USAGE: &'static str = "
Remove artifacts that cargo has generated in the past
Usage:
cargo clean [options]
Options:
-h, --help Print this message
-p SPEC, --package SPEC... Package to clean artifacts for
--manifest-path PATH Path to the ... | #[serde(rename = "flag_Z")] | random_line_split |
clean.rs | use std::env;
use cargo::core::Workspace;
use cargo::ops;
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
#[derive(Deserialize)]
pub struct Options {
flag_package: Vec<String>,
flag_target: Option<String>,
flag_manifest_path: Option<String>,
flag_ve... | {
debug!("executing; cmd=cargo-clean; args={:?}", env::args().collect::<Vec<_>>());
config.configure(options.flag_verbose,
options.flag_quiet,
&options.flag_color,
options.flag_frozen,
options.flag_locked,
&... | identifier_body | |
fms.rs | #![cfg(feature = "fms")]
extern crate rusoto_core;
extern crate rusoto_fms;
use rusoto_fms::{Fms, FmsClient, ListPoliciesRequest, ListPoliciesError};
use rusoto_core::Region;
use std::str;
#[test]
fn | () {
let client = FmsClient::new(Region::UsEast1);
let request = ListPoliciesRequest::default();
// If our account doesn't have access, assume everything is fine:
match client.list_policies(request).sync() {
Err(e) => {
match e {
ListPoliciesError::Unknown(ref e) => ... | should_list_policies | identifier_name |
fms.rs | #![cfg(feature = "fms")]
extern crate rusoto_core;
extern crate rusoto_fms;
use rusoto_fms::{Fms, FmsClient, ListPoliciesRequest, ListPoliciesError};
use rusoto_core::Region;
use std::str;
#[test]
fn should_list_policies() {
let client = FmsClient::new(Region::UsEast1);
let request = ListPoliciesRequest::de... | } | random_line_split | |
fms.rs | #![cfg(feature = "fms")]
extern crate rusoto_core;
extern crate rusoto_fms;
use rusoto_fms::{Fms, FmsClient, ListPoliciesRequest, ListPoliciesError};
use rusoto_core::Region;
use std::str;
#[test]
fn should_list_policies() | {
let client = FmsClient::new(Region::UsEast1);
let request = ListPoliciesRequest::default();
// If our account doesn't have access, assume everything is fine:
match client.list_policies(request).sync() {
Err(e) => {
match e {
ListPoliciesError::Unknown(ref e) => ass... | identifier_body | |
get_unwrap.rs | use super::utils::derefs_to_slice;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::get_parent_expr;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::Lat... | needs_ref = false;
span = parent.span;
}
}
let mut_str = if is_mut { "_mut" } else { "" };
let borrow_str = if!needs_ref {
""
} else if is_mut {
"&mut "
} else {
"&"
};
span_lint_and_sugg(
cx,
GET_UNWRAP,
span,... | random_line_split | |
get_unwrap.rs | use super::utils::derefs_to_slice;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::get_parent_expr;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::Lat... | <'tcx>(
cx: &LateContext<'tcx>,
expr: &hir::Expr<'_>,
recv: &'tcx hir::Expr<'tcx>,
get_arg: &'tcx hir::Expr<'_>,
is_mut: bool,
) {
// Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
// because they do not implement `IndexMut`
let mut applicability = Applicabil... | check | identifier_name |
get_unwrap.rs | use super::utils::derefs_to_slice;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::get_parent_expr;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::Lat... | needs_ref = true;
"BTreeMap"
} else {
return; // caller is not a type that we want to lint
};
let mut span = expr.span;
// Handle the case where the result is immediately dereferenced
// by not requiring ref and pulling the dereference into the
// suggestion.
if_cha... | {
// Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
// because they do not implement `IndexMut`
let mut applicability = Applicability::MachineApplicable;
let expr_ty = cx.typeck_results().expr_ty(recv);
let get_args_str = snippet_with_applicability(cx, get_arg.span, ".."... | identifier_body |
get_unwrap.rs | use super::utils::derefs_to_slice;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::get_parent_expr;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::Lat... | ;
span_lint_and_sugg(
cx,
GET_UNWRAP,
span,
&format!(
"called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
mut_str, caller_type
),
"try this",
format!(
"{}{}[{}]",
borrow_str,
... | {
"&"
} | conditional_block |
counting_sort.rs | /// 计数排序
/// 时间复杂度:O(n), 稳定排序
// 计数排序
pub fn counting_sort(mut nums: Vec<i32>) -> | if nums.len() <= 1 { return nums; }
let nums_len = nums.len();
// 获取最大数
let mut max = nums[0];
let mut tmp = vec![0; nums_len];
for i in 1..nums_len {
if max < nums[i] { max = nums[i]; }
}
// 申请一个长度为 max + 1 的新数组
let mut bucket = vec![0; (max+1) as usize];
for i in... | Vec<i32> {
| identifier_name |
counting_sort.rs | /// 计数排序
/// 时间复杂度:O(n), 稳定排序
// 计数排序
pub fn counting_sort(mut nums: Vec<i32>) -> Vec<i32> {
if nums.len() <= 1 { return nums; }
let nums_len = nums.len();
// 获取最大数
let mut max = nums[0];
let mut tmp = vec![0; nums_len];
for i in 1..nums_len {
if max < nums[i] { max = nums[i]; }
... | // 对 bucket 中元素进行累加,针对 nums 数组中每个元素,小于等于这个元素的个数
// 如,nums 数组中元素 3,小于等于 3 的个数为 7 个
for i in 1..bucket.len() {
bucket[i] += bucket[i-1];
}
// 排序
// 1. 申请一个与 nums 等长的数组,用于存储排序后的内容;
// 2. 对数组 nums 从后向前迭代
// 1). 从 bucket 数组中取出下标为 nums 数组中当前元素的值,如 nums 中当前元素为3,则从 bucket
// 中取出下标... | random_line_split | |
counting_sort.rs | /// 计数排序
/// 时间复杂度:O(n), 稳定排序
// 计数排序
pub fn counting_sort(mut nums: Vec<i32>) -> Vec<i32> {
if nums.len() <= 1 { return nums; }
let nums_len = nums.len();
// 获取最大数
let mut max = nums[0];
let mut tmp = vec![0; nums_len];
for i in 1..nums_len {
if max < nums[i] { max = nums[i]; }
... | bucket = vec![0; (max+1) as usize];
for i in 0..nums_len {
bucket[nums[i] as usize] += 1;
}
// 对 bucket 中元素进行累加,针对 nums 数组中每个元素,小于等于这个元素的个数
// 如,nums 数组中元素 3,小于等于 3 的个数为 7 个
for i in 1..bucket.len() {
bucket[i] += bucket[i-1];
}
// 排序
// 1. 申请一个与 nums 等长的数组,用于存储排序后的内容... | 1 的新数组
let mut | conditional_block |
counting_sort.rs | /// 计数排序
/// 时间复杂度:O(n), 稳定排序
// 计数排序
pub fn counting_sort(mut nums: Vec<i32>) -> Vec<i32> {
if nums.len() <= 1 { return nums; }
let nums_len = nums.len();
// 获取最大数
let mut max = nums[0];
let mut tmp = vec![0; nums_len];
for i in 1..nums_len {
if max < nums[i] { max = nums[i]; }
... | identifier_body | ||
client.rs | //! Common client functionality.
//!
//! In librdkafka parlance, a client is either a consumer or a producer. This
//! module's [`Client`] type provides the functionality that is common to both
//! consumers and producers.
//!
//! Typically you will not want to construct a client directly. Construct one of
//! the cons... | }
}
/// Receives the decoded statistics of the librdkafka client. To enable, the
/// `statistics.interval.ms` configuration parameter must be specified.
///
/// The default implementation logs the statistics at the `info` log level.
fn stats(&self, statistics: Statistics) {
inf... | {
match level {
RDKafkaLogLevel::Emerg
| RDKafkaLogLevel::Alert
| RDKafkaLogLevel::Critical
| RDKafkaLogLevel::Error => {
error!(target: "librdkafka", "librdkafka: {} {}", fac, log_message)
}
RDKafkaLogLevel::Warning => {
... | identifier_body |
client.rs | //! Common client functionality.
//!
//! In librdkafka parlance, a client is either a consumer or a producer. This
//! module's [`Client`] type provides the functionality that is common to both
//! consumers and producers.
//!
//! Typically you will not want to construct a client directly. Construct one of
//! the cons... | ;
let mut group_list_ptr: *const RDKafkaGroupList = ptr::null_mut();
trace!("Starting group list fetch");
let ret = unsafe {
rdsys::rd_kafka_list_groups(
self.native_ptr(),
group_c_ptr,
&mut group_list_ptr as *mut *const RDKafkaGroupLis... | {
ptr::null_mut()
} | conditional_block |
client.rs | //! Common client functionality.
//!
//! In librdkafka parlance, a client is either a consumer or a producer. This
//! module's [`Client`] type provides the functionality that is common to both
//! consumers and producers.
//!
//! Typically you will not want to construct a client directly. Construct one of
//! the cons... | opaque: *mut c_void,
) -> i32 {
let context = &mut *(opaque as *mut C);
context.stats_raw(slice::from_raw_parts(json as *mut u8, json_len));
0 // librdkafka will free the json buffer
}
pub(crate) unsafe extern "C" fn native_error_cb<C: ClientContext>(
_client: *mut RDKafka,
err: i32,
reason... | pub(crate) unsafe extern "C" fn native_stats_cb<C: ClientContext>(
_conf: *mut RDKafka,
json: *mut c_char,
json_len: usize, | random_line_split |
client.rs | //! Common client functionality.
//!
//! In librdkafka parlance, a client is either a consumer or a producer. This
//! module's [`Client`] type provides the functionality that is common to both
//! consumers and producers.
//!
//! Typically you will not want to construct a client directly. Construct one of
//! the cons... | <T: Into<Timeout>>(&self, t: T) -> *mut RDKafkaEvent {
unsafe { rdsys::rd_kafka_queue_poll(self.ptr(), t.into().as_millis()) }
}
}
pub(crate) unsafe extern "C" fn native_log_cb<C: ClientContext>(
client: *const RDKafka,
level: i32,
fac: *const c_char,
buf: *const c_char,
) {
let fac = C... | poll | identifier_name |
vr.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRBinding;
use dom::bindings::codegen::... | use dom::vrdisplayevent::VRDisplayEvent;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use ipc_channel::ipc::IpcSender;
use script_traits::WebVREventMsg;
use std::rc::Rc;
use webvr_traits::WebVRMsg;
use webvr_traits::webvr;
#[dom_struct]
pub struct VR {
eventtarget: EventTarget,
displays: DOMRefCell<Vec<JS... | use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::promise::Promise;
use dom::vrdisplay::VRDisplay; | random_line_split |
vr.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRBinding;
use dom::bindings::codegen::... | (&self, event: WebVREventMsg) {
let WebVREventMsg::DisplayEvent(event) = event;
match &event {
&webvr::VRDisplayEvent::Connect(ref display) => {
let display = self.sync_display(&display);
display.handle_webvr_event(&event);
self.notify_event(&d... | handle_webvr_event | identifier_name |
vr.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRBinding;
use dom::bindings::codegen::... |
}
} else {
// WebVR spec: The Promise MUST be rejected if WebVR is not enabled/supported.
promise.reject_error(promise.global().get_cx(), Error::Security);
return promise;
}
// convert from JS to Root
let displays: Vec<Root<VRDisplay>> = ... | {
promise.reject_native(promise.global().get_cx(), &e);
return promise;
} | conditional_block |
cache.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 std::collections::hashmap::HashMap;
use rand::Rng;
use std::hash::{Hash, sip};
use std::rand::task_rng;
use st... |
self.entries.push((key, val));
}
fn find(&mut self, key: &K) -> Option<V> {
match self.entries.iter().position(|&(ref k, _)| *k == *key) {
Some(pos) => Some(self.touch(pos)),
None => None,
}
}
fn find_or_create(&mut self, key: &K, blk: |&K| -> V) -... | {
self.entries.remove(0);
} | conditional_block |
cache.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 std::collections::hashmap::HashMap;
use rand::Rng;
use std::hash::{Hash, sip};
use std::rand::task_rng;
use st... |
fn evict_all(&mut self) {
self.entries.clear();
}
}
impl<K,V> HashCache<K,V> where K: Clone + PartialEq + Eq + Hash, V: Clone {
pub fn find_equiv<'a,Q>(&'a self, key: &Q) -> Option<&'a V> where Q: Hash + Equiv<K> {
self.entries.find_equiv(key)
}
}
#[test]
fn test_hashcache() {
l... | {
self.entries.find_or_insert_with(key.clone(), blk).clone()
} | identifier_body |
cache.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 std::collections::hashmap::HashMap;
use rand::Rng;
use std::hash::{Hash, sip};
use std::rand::task_rng;
use st... | cache.find_or_create(&2, |_v| { two });
assert!(cache.find(&1).is_some());
assert!(cache.find(&2).is_some());
}
pub struct LRUCache<K, V> {
entries: Vec<(K, V)>,
cache_size: uint,
}
impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> {
pub fn new(size: uint) -> LRUCache<K, V> {
LRUCache... | cache.insert(1, one);
assert!(cache.find(&1).is_some());
assert!(cache.find(&2).is_none());
| random_line_split |
cache.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 std::collections::hashmap::HashMap;
use rand::Rng;
use std::hash::{Hash, sip};
use std::rand::task_rng;
use st... | (&self, h: uint) -> uint {
h % self.entries.len()
}
#[inline]
fn bucket_for_key<Q:Hash>(&self, key: &Q) -> uint {
self.to_bucket(sip::hash_with_keys(self.k0, self.k1, key) as uint)
}
#[inline]
pub fn find_equiv<'a,Q:Hash+Equiv<K>>(&'a self, key: &Q) -> Option<&'a V> {
l... | to_bucket | identifier_name |
albino-build.rs | #![crate_name="albino-build"]
#![crate_type="bin"]
#![feature(phase)]
#![unstable]
#[phase(plugin, link)] extern crate log;
extern crate getopts;
extern crate whitebase;
extern crate albino;
use getopts::Matches;
use std::os;
use std::io::IoError;
use whitebase::syntax::{Compiler, Assembly, Brainfuck, DT, Ook, White... |
fn exec<B: Buffer, W: Writer>(&self, _: &Matches, buffer: &mut B, writer: &mut W, target: Option<Target>) {
match target {
Some(util::Assembly) => build(buffer, writer, Assembly::new()),
Some(util::Brainfuck) => build(buffer, writer, Brainfuck::new()),
Some(util::DT)... | {
println!("{}", e);
os::set_exit_status(1);
} | identifier_body |
albino-build.rs | #![crate_name="albino-build"]
#![crate_type="bin"]
#![feature(phase)]
#![unstable]
#[phase(plugin, link)] extern crate log;
extern crate getopts;
extern crate whitebase;
extern crate albino;
use getopts::Matches;
use std::os;
use std::io::IoError;
use whitebase::syntax::{Compiler, Assembly, Brainfuck, DT, Ook, White... | os::set_exit_status(1);
}
_ => (),
}
}
struct CommandBody;
impl BuildExecutable for CommandBody {
fn handle_error(&self, e: IoError) {
println!("{}", e);
os::set_exit_status(1);
}
fn exec<B: Buffer, W: Writer>(&self, _: &Matches, buffer: &mut B, writer: &mu... |
fn build<B: Buffer, W: Writer, C: Compiler>(input: &mut B, output: &mut W, syntax: C) {
match syntax.compile(input, output) {
Err(e) => {
println!("{}", e); | random_line_split |
albino-build.rs | #![crate_name="albino-build"]
#![crate_type="bin"]
#![feature(phase)]
#![unstable]
#[phase(plugin, link)] extern crate log;
extern crate getopts;
extern crate whitebase;
extern crate albino;
use getopts::Matches;
use std::os;
use std::io::IoError;
use whitebase::syntax::{Compiler, Assembly, Brainfuck, DT, Ook, White... | (&self, e: IoError) {
println!("{}", e);
os::set_exit_status(1);
}
fn exec<B: Buffer, W: Writer>(&self, _: &Matches, buffer: &mut B, writer: &mut W, target: Option<Target>) {
match target {
Some(util::Assembly) => build(buffer, writer, Assembly::new()),
Some(ut... | handle_error | identifier_name |
character.rs | use datatypes::{Coords, Region};
use terminal::{CharData, CellData, UseStyles};
use terminal::interfaces::{WriteableGrid, WriteableCell};
impl CharData for char {
fn write<T>(&self, coords: Coords, styles: UseStyles, grid: &mut T) -> Coords
where T: WriteableGrid, T::Cell: WriteableCell {
if let Some(c... | if let Some(cell) = grid.writeable(extension_coords) {
cell.write(CellData::Extension(coords), styles)
}
}
Coords { x: coords.x + self.1 - 1, y: coords.y }
}
#[cfg(any(debug_assertions, test))]
fn repr(&self) -> String {
self.0.to_string()
... | random_line_split | |
character.rs | use datatypes::{Coords, Region};
use terminal::{CharData, CellData, UseStyles};
use terminal::interfaces::{WriteableGrid, WriteableCell};
impl CharData for char {
fn write<T>(&self, coords: Coords, styles: UseStyles, grid: &mut T) -> Coords
where T: WriteableGrid, T::Cell: WriteableCell {
if let Some(c... |
for extension_coords in (1..self.1).map(|i| Coords { x: coords.x + i,..coords }) {
if let Some(cell) = grid.writeable(extension_coords) {
cell.write(CellData::Extension(coords), styles)
}
}
Coords { x: coords.x + self.1 - 1, y: coords.y }
}
#[cfg... | {
cell.write(CellData::Char(self.0), styles);
} | conditional_block |
character.rs | use datatypes::{Coords, Region};
use terminal::{CharData, CellData, UseStyles};
use terminal::interfaces::{WriteableGrid, WriteableCell};
impl CharData for char {
fn write<T>(&self, coords: Coords, styles: UseStyles, grid: &mut T) -> Coords
where T: WriteableGrid, T::Cell: WriteableCell {
if let Some(c... |
}
pub struct WideChar(pub char, pub u32);
impl WideChar {
pub fn new(ch: char, width: u32) -> WideChar {
WideChar(ch, width)
}
}
impl CharData for WideChar {
fn write<T>(&self, coords: Coords, styles: UseStyles, grid: &mut T) -> Coords
where T: WriteableGrid, T::Cell: WriteableCell {
... | {
self.to_string()
} | identifier_body |
character.rs | use datatypes::{Coords, Region};
use terminal::{CharData, CellData, UseStyles};
use terminal::interfaces::{WriteableGrid, WriteableCell};
impl CharData for char {
fn write<T>(&self, coords: Coords, styles: UseStyles, grid: &mut T) -> Coords
where T: WriteableGrid, T::Cell: WriteableCell {
if let Some(c... | (&self) -> String {
self.0.to_string()
}
}
pub struct CharExtender(pub char);
impl CharExtender {
pub fn new(ch: char) -> CharExtender {
CharExtender(ch)
}
}
impl CharData for CharExtender {
fn write<T>(&self, coords: Coords, styles: UseStyles, grid: &mut T) -> Coords
where T: Wri... | repr | identifier_name |
typeid-intrinsic.rs | // Copyright 2013-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-MI... | ;
struct Test;
pub fn main() {
unsafe {
assert_eq!(TypeId::of::<other1::A>(), other1::id_A());
assert_eq!(TypeId::of::<other1::B>(), other1::id_B());
assert_eq!(TypeId::of::<other1::C>(), other1::id_C());
assert_eq!(TypeId::of::<other1::D>(), other1::id_D());
assert_eq!(Type... | A | identifier_name |
typeid-intrinsic.rs | // Copyright 2013-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-MI... | assert_eq!(TypeId::of::<isize>(), other2::foo::<isize>());
assert_eq!(TypeId::of::<isize>(), other1::foo::<isize>());
assert_eq!(other2::foo::<isize>(), other1::foo::<isize>());
assert_eq!(TypeId::of::<A>(), other2::foo::<A>());
assert_eq!(TypeId::of::<A>(), other1::foo::<A>());
... | assert_eq!(other1::id_G(), other2::id_G());
assert_eq!(other1::id_H(), other2::id_H());
| random_line_split |
re.rs | allow(visible_private_types)]
pub struct Regex {
/// The representation of `Regex` is exported to support the `regex!`
/// syntax extension. Do not rely on it.
///
/// See the comments for the `program` module in `lib.rs` for a more
/// detailed explanation for what `regex!` requires.
#[doc(hidd... |
/// Returns an iterator of substrings of `text` delimited by a match
/// of the regular expression.
/// Namely, each element of the iterator corresponds to text that *isn't*
/// matched by the regular expression.
///
/// This method will *not* copy the text given.
///
/// # Example
... | {
FindCaptures {
re: self,
search: text,
last_match: None,
last_end: 0,
}
} | identifier_body |
re.rs | if you want to discover the position
/// of the match. Testing the existence of a match is faster if you use
/// `is_match`.
///
/// # Example
///
/// Find the start and end location of every word with exactly 13
/// characters:
///
/// ```rust
/// # #![feature(phase)]
/// #... | SubCapturesPos | identifier_name | |
re.rs | (phase)]
/// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
/// # fn main() {
/// let text = "I categorically deny having triskaidekaphobia.";
/// let matched = regex!(r"\b\w{13}\b").is_match(text);
/// assert!(matched);
/// # }
/// ```
pub fn is_match(&self, text: &st... | idx: uint,
caps: &'t Captures<'t>, | random_line_split | |
mandelview.rs | extern crate num;
extern crate num_cpus;
use self::num::complex::{Complex64};
use leelib::vector2::Vector2f;
use leelib::matrix::Matrix;
use leelib::animator::{Animator, Anim};
use leelib::dirtychecker::DirtyChecker;
use fract::constants;
use fract::fractalcalc::{FractalSpecs, FractalType};
use fract::Asciifier;
use ... | (&self) -> &Asciifier {
&self.asciifier
}
fn asciifier_m(&mut self) -> &mut Asciifier {
&mut self.asciifier
}
fn set_matrix_size(&mut self, matrix_w: usize, matrix_h: usize) {
self.fractal_matrix = Matrix::new(matrix_w, matrix_h);
self.index_matrix = Matrix::new(matrix_w, matrix_h);
self.di... | asciifier | identifier_name |
mandelview.rs | extern crate num;
extern crate num_cpus;
use self::num::complex::{Complex64};
use leelib::vector2::Vector2f;
use leelib::matrix::Matrix;
use leelib::animator::{Animator, Anim};
use leelib::dirtychecker::DirtyChecker;
use fract::constants;
use fract::fractalcalc::{FractalSpecs, FractalType};
use fract::Asciifier;
use ... | else {
match self.specs.fractal_type {
FractalType::Mandelbrot => {
if index >= self.mandel_coordlist.len() {
false
} else {
self.start_mandel_coord_anim(index);
true
}
},
_ => { false }
}
}
}
fn do_dirty_fractal_check(&mut self) -> bool {
let v = vec![self.po... | {
false
} | conditional_block |
mandelview.rs | extern crate num;
extern crate num_cpus;
use self::num::complex::{Complex64};
use leelib::vector2::Vector2f;
use leelib::matrix::Matrix;
use leelib::animator::{Animator, Anim};
use leelib::dirtychecker::DirtyChecker;
use fract::constants;
use fract::fractalcalc::{FractalSpecs, FractalType};
use fract::Asciifier;
use ... | width_animator: Animator::<f64>::new(specs.default_width, Anim::None),
rotation_animator: Animator::<f64>::new(0.0, Anim::None),
exposure_floor_animator: Animator::<f64>::new( 0.0, Anim::Target { target: 0.0, coefficient: 0.1, epsilon: Some(0.01) } ),
exposure_ceil_animator: Animator::<f64>::new( specs.max... | asciifier: Asciifier::new(0.0, specs.max_val as f64),
fractal_matrix: Matrix::new(matrix_w, matrix_h),
index_matrix: Matrix::new(matrix_w, matrix_h),
position_animator: Animator::<Vector2f>::new(Vector2f::new(0.0, 0.0), Anim::None), | random_line_split |
mandelview.rs | extern crate num;
extern crate num_cpus;
use self::num::complex::{Complex64};
use leelib::vector2::Vector2f;
use leelib::matrix::Matrix;
use leelib::animator::{Animator, Anim};
use leelib::dirtychecker::DirtyChecker;
use fract::constants;
use fract::fractalcalc::{FractalSpecs, FractalType};
use fract::Asciifier;
use ... |
debug: "".to_string(),
dirty_fractal_checker: DirtyChecker::new(4),
mandel_coordlist: CoordList::<Three64>::new(constants::MANDELBROT_POI_TEXT),
}
}
/**
* Zooms out to home position, and then tweens to specific coordlist + width,
* using the animators for position and width
*/
fn start_mand... | {
MandelView {
specs: specs,
asciifier: Asciifier::new(0.0, specs.max_val as f64),
fractal_matrix: Matrix::new(matrix_w, matrix_h),
index_matrix: Matrix::new(matrix_w, matrix_h),
position_animator: Animator::<Vector2f>::new(Vector2f::new(0.0, 0.0), Anim::None),
width_animator: Animator::... | identifier_body |
server.rs | // Legato - Statsd Server in Rust
//
// Copyright 2016 TSH Labs
//
// 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 d... | <T>(mut handler: T, event_capacity: usize) -> MetricResult<()>
where T: EventHandler
{
let mut events = Events::with_capacity(event_capacity);
let poll = try!(Poll::new());
try!(handler.initialize(&poll));
loop {
try!(poll.poll(&mut events, None));
f... | run_event_handler | identifier_name |
server.rs | // Legato - Statsd Server in Rust
//
// Copyright 2016 TSH Labs
//
// 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 d... |
Self::log_diagnostics(&self.config);
backend_thread.join().expect("Backend error");
metric_thread.join().expect("Frontend error");
}
/// Create an MIO `Poll` instance, initialize the event handler, and run the
/// handler forever, accepting events from the `Poll` instance. This me... | {
debug!("Starting server with config: {:?}", self.config);
let backend_handler = self.backend_handler;
let metric_handler = self.metric_handler;
debug!("Starting backend thread...");
let backend_thread = thread::spawn(move || {
match Self::run_event_handler(backend_... | identifier_body |
server.rs | // Legato - Statsd Server in Rust
//
// Copyright 2016 TSH Labs
//
// 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 d... | info!(
"Metrics will be flush to Graphite ({}) every {} ms",
config.graphite_addr, config.flush_period_ms
);
} else {
info!("Metrics will NOT be flushed to Graphite");
}
}
} | info!("Metrics will NOT be flushed to console");
}
if config.enable_graphite { | random_line_split |
quaternion.rs | // Convector -- An interactive CPU path tracer
// Copyright 2016 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! Implements quaternion ... | #[test]
fn interpolate() {
use vector3::SVector3;
let half_sqrt_2 = 0.5 * 2.0_f32.sqrt();
let identity = MQuaternion::broadcast(SQuaternion::new(1.0, 0.0, 0.0, 0.0));
let rotate_z_delta = MQuaternion::broadcast(SQuaternion::new(half_sqrt_2 - 1.0, 0.0, 0.0, half_sqrt_2));
let rotation = identity.inte... | random_line_split | |
quaternion.rs | // Convector -- An interactive CPU path tracer
// Copyright 2016 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! Implements quaternion ... | (&self, delta: &MQuaternion, t: Mf32) -> MQuaternion {
// The hypersphere of unit quaternions forms a double cover of SO3(R).
// Every rotation is represented by two antipodal points on the
// hypersphere. If we naively run over the arc subtended by the two
// quaternions, then we could ... | interpolate | identifier_name |
explicit_into_iter_loop.rs | use super::EXPLICIT_INTO_ITER_LOOP;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet_with_applicability;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::TyS;
use rustc_span::symbol::sym;
pub(... | span_lint_and_sugg(
cx,
EXPLICIT_INTO_ITER_LOOP,
call_expr.span,
"it is more concise to loop over containers instead of using explicit \
iteration methods",
"to write this more concisely, try",
object.to_string(),
applicability,
);
} | return;
}
let mut applicability = Applicability::MachineApplicable;
let object = snippet_with_applicability(cx, self_arg.span, "_", &mut applicability); | random_line_split |
explicit_into_iter_loop.rs | use super::EXPLICIT_INTO_ITER_LOOP;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet_with_applicability;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::TyS;
use rustc_span::symbol::sym;
pub(... | (cx: &LateContext<'_>, self_arg: &'hir Expr<'hir>, call_expr: &Expr<'_>) {
let self_ty = cx.typeck_results().expr_ty(self_arg);
let self_ty_adjusted = cx.typeck_results().expr_ty_adjusted(self_arg);
if!(TyS::same_type(self_ty, self_ty_adjusted) && is_trait_method(cx, call_expr, sym::IntoIterator)) {
... | check | identifier_name |
explicit_into_iter_loop.rs | use super::EXPLICIT_INTO_ITER_LOOP;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet_with_applicability;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::TyS;
use rustc_span::symbol::sym;
pub(... | {
let self_ty = cx.typeck_results().expr_ty(self_arg);
let self_ty_adjusted = cx.typeck_results().expr_ty_adjusted(self_arg);
if !(TyS::same_type(self_ty, self_ty_adjusted) && is_trait_method(cx, call_expr, sym::IntoIterator)) {
return;
}
let mut applicability = Applicability::MachineApplic... | identifier_body | |
explicit_into_iter_loop.rs | use super::EXPLICIT_INTO_ITER_LOOP;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet_with_applicability;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::TyS;
use rustc_span::symbol::sym;
pub(... |
let mut applicability = Applicability::MachineApplicable;
let object = snippet_with_applicability(cx, self_arg.span, "_", &mut applicability);
span_lint_and_sugg(
cx,
EXPLICIT_INTO_ITER_LOOP,
call_expr.span,
"it is more concise to loop over containers instead of using expli... | {
return;
} | conditional_block |
logs.rs | use mockito::mock;
use support::ProjectBuilder;
#[test]
fn | () {
let stubbed_repsonse = json!([
{
"id": 1,
"name": "staging1",
}
]);
let trekker = "login";
let url = format!("/stages?trekker_name={}", trekker);
let _mock = mock("GET", &url[..])
.with_status(200)
.with_header("Content-Type", "accept/json... | test_logs | identifier_name |
logs.rs | use mockito::mock;
use support::ProjectBuilder;
#[test]
fn test_logs() | let stage = "staging1";
let result = project
.sherpa_command(&format!("-c {} --sherpa-stage test logs --trekker {} {}", project.config_path(), trekker, stage))
.run();
assert!(result.is_success(), result.failure_message("command to succeed"));
}
| {
let stubbed_repsonse = json!([
{
"id": 1,
"name": "staging1",
}
]);
let trekker = "login";
let url = format!("/stages?trekker_name={}", trekker);
let _mock = mock("GET", &url[..])
.with_status(200)
.with_header("Content-Type", "accept/json"... | identifier_body |
logs.rs | use mockito::mock;
use support::ProjectBuilder;
| fn test_logs() {
let stubbed_repsonse = json!([
{
"id": 1,
"name": "staging1",
}
]);
let trekker = "login";
let url = format!("/stages?trekker_name={}", trekker);
let _mock = mock("GET", &url[..])
.with_status(200)
.with_header("Content-Type", ... | #[test] | random_line_split |
main.rs | use std::str::FromStr;
use std::collections::HashSet;
use std::io::BufRead;
#[derive(Debug, Clone, Copy)]
enum Axis {
X,
Y
}
static HEIGHT: u8 = 6;
static WIDTH: u8 = 50;
#[derive(Debug)]
enum Instruction {
Rectangle(u8, u8),
Rotate(Axis, u8, u8)
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struc... | else {Axis::X};
let coord = words.next().unwrap();
let (_, c) = coord.split_at(coord.find('=').unwrap() + 1);
words.next();
let dist = words.next().unwrap();
return Instruction::Rotate(
axis,
u8::from_str(c).unwrap(),
u8::from_str(dist).unwrap... | {Axis::Y} | conditional_block |
main.rs | use std::str::FromStr;
use std::collections::HashSet;
use std::io::BufRead;
#[derive(Debug, Clone, Copy)]
enum Axis {
X,
Y
}
static HEIGHT: u8 = 6;
static WIDTH: u8 = 50;
#[derive(Debug)]
enum Instruction {
Rectangle(u8, u8),
Rotate(Axis, u8, u8)
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struc... | (&self, idx: Axis, dist: u8) -> Coord {
let mut x = self.0;
let mut y = self.1;
match idx {
Axis::X => y = (y + dist + HEIGHT) % HEIGHT,
Axis::Y => x = (x + dist + WIDTH) % WIDTH,
}
Coord(x,y)
}
}
fn parse(s: &str) -> Instruction {
let mut words =... | rotate | identifier_name |
main.rs | use std::str::FromStr;
use std::collections::HashSet;
use std::io::BufRead;
#[derive(Debug, Clone, Copy)]
enum Axis {
X,
Y
}
static HEIGHT: u8 = 6;
static WIDTH: u8 = 50;
#[derive(Debug)]
enum Instruction {
Rectangle(u8, u8),
Rotate(Axis, u8, u8)
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struc... |
}
fn parse(s: &str) -> Instruction {
let mut words = s.split_whitespace();
let action = words.next().expect("No actions in instruction");
if action == "rect" {
let rest = words.next().unwrap();
let mut splitted = rest.split('x');
return Instruction::Rectangle(
u8::from_... | {
let mut x = self.0;
let mut y = self.1;
match idx {
Axis::X => y = (y + dist + HEIGHT) % HEIGHT,
Axis::Y => x = (x + dist + WIDTH) % WIDTH,
}
Coord(x,y)
} | identifier_body |
main.rs | use std::str::FromStr;
use std::collections::HashSet;
use std::io::BufRead;
#[derive(Debug, Clone, Copy)]
enum Axis {
X,
Y
}
static HEIGHT: u8 = 6;
static WIDTH: u8 = 50;
#[derive(Debug)]
enum Instruction {
Rectangle(u8, u8),
Rotate(Axis, u8, u8)
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struc... | return Instruction::Rotate(
axis,
u8::from_str(c).unwrap(),
u8::from_str(dist).unwrap()
);
}
}
fn process(inst: &Instruction, lights: &mut HashSet<Coord>) {
match *inst {
Instruction::Rectangle(w, h) => {
for x in 0..w {
fo... | let coord = words.next().unwrap();
let (_, c) = coord.split_at(coord.find('=').unwrap() + 1);
words.next();
let dist = words.next().unwrap(); | random_line_split |
custom_derive_partial_eq.rs | // Copyright 2016 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 ... | cx,
span,
substr)
}
let inline = cx.meta_word(span, Symbol::intern("inline"));
let attrs = vec![cx.attribute(span, inline)];
let methods = vec![MethodDef {
name: "eq",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_expl... | },
cx.expr_bool(span, true),
Box::new(|cx, span, _, _| cx.expr_bool(span, false)), | random_line_split |
custom_derive_partial_eq.rs | // Copyright 2016 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 expand_deriving_partial_eq(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable,
push: &mut FnMut(Annotatable)) {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn cs_eq(cx:... | {
reg.register_syntax_extension(Symbol::intern("derive_CustomPartialEq"),
MultiDecorator(Box::new(expand_deriving_partial_eq)));
} | identifier_body |
custom_derive_partial_eq.rs | // Copyright 2016 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 ... | (cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
cs_fold(true,
|cx, span, subexpr, self_f, other_fs| {
let other_f = (other_fs.len(), other_fs.get(0)).1.unwrap();
let eq = cx.expr_binary(span, BinOpKind::Eq, self_f, other_f.clone());
... | cs_eq | identifier_name |
mod.rs | //public mods
pub mod address_mode;
pub mod opcode_class;
//private mods
use std::clone::Clone;
// hoisted interfaces
#[derive(Default)]
pub struct OpcodeDebugInfo {
pub opcode: u8,
pub name: String,
pub address_mode_name: String,
pub notes: String,
}
#[derive(Default)]
pub struct OpcodeExecInfo {
... | (&self) -> OpcodeExecInfo {
OpcodeExecInfo {
opcode :self.opcode,
opcode_class : self.opcode_class.clone(),
address_mode : self.address_mode.clone(),
len : self.len,
cycles : self.cycles,
page_cycles : self.page_cycles,
}
}
}
| clone | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.