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 |
|---|---|---|---|---|
issue-41936-variance-coerce-unsized-cycle.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 ... | (){}
| main | identifier_name |
issue-41936-variance-coerce-unsized-cycle.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 ... |
// Change the array to a non-array, and error disappears
// Adding a new field to the end keeps the error
struct LogDataBuf([u8;8]);
struct Aref<T:?Sized>
{
// Inner structure triggers the error, removing the inner removes the message.
ptr: Box<ArefInner<T>>,
}
impl<T:?Sized + marker::Unsize<U>, U:?Sized> ops... | #![feature(unsize)]
#![feature(coerce_unsized)]
use std::{marker,ops}; | random_line_split |
lib.rs | //! Utitilty for writing nagios-style check scripts/plugins
//!
//! There are three things:
//!
//! * The `Status` enum for representing health status
//! * The `procfs` module, which contains rusty representations of some files
//! from /proc
//! * A few scripts in the bin directory, which contain actual
//! nagio... | /// Represent the nagios-ish error status of a script.
#[must_use]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Deserialize)]
pub enum Status {
/// Unexpected result
Unknown,
/// Everything is fine
Ok,
/// Something is weird, but don't necessary call anybody
Warning,
/// OMG ... | }
/// All results are TabinResults
pub type TabinResult<T> = Result<T, TabinError>;
| random_line_split |
lib.rs | //! Utitilty for writing nagios-style check scripts/plugins
//!
//! There are three things:
//!
//! * The `Status` enum for representing health status
//! * The `procfs` module, which contains rusty representations of some files
//! from /proc
//! * A few scripts in the bin directory, which contain actual
//! nagio... | () {
use crate::Status::*;
assert!(Ok < Critical);
assert!(Ok < Warning);
assert_eq!(std::cmp::max(Warning, Critical), Critical)
}
| comparison_is_as_expected | identifier_name |
lib.rs | //! Utitilty for writing nagios-style check scripts/plugins
//!
//! There are three things:
//!
//! * The `Status` enum for representing health status
//! * The `procfs` module, which contains rusty representations of some files
//! from /proc
//! * A few scripts in the bin directory, which contain actual
//! nagio... |
}
impl FromStr for Status {
type Err = TabinError;
/// Primarily useful to construct from argv
fn from_str(s: &str) -> TabinResult<Status> {
use crate::Status::{Critical, Unknown, Warning};
match s {
"ok" => Ok(Status::Ok),
"warning" => Ok(Warning),
"cr... | {
["ok", "warning", "critical", "unknown"]
} | identifier_body |
solution.rs | use std::collections::HashMap;
// #[derive(Debug)]
// struct Solution {}
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let mut sum: i32 = 0;
let table: HashMap<char, i32> = [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100)... | // println!("{}", Solution::roman_to_int(String::from("MCMXCIV")));
// println!("{}", Solution::roman_to_int(String::from("MCDLXXVI")));
// } | random_line_split | |
solution.rs | use std::collections::HashMap;
// #[derive(Debug)]
// struct Solution {}
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let mut sum: i32 = 0;
let table: HashMap<char, i32> = [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100)... |
// println!("{:?}", c);
}
return sum;
}
}
// fn main() {
// println!("{}", Solution::roman_to_int(String::from("IV")));
// println!("{}", Solution::roman_to_int(String::from("IX")));
// println!("{}", Solution::roman_to_int(String::from("VII")));
// println!("{}", Solu... | {
sum -= cv;
} | conditional_block |
solution.rs | use std::collections::HashMap;
// #[derive(Debug)]
// struct Solution {}
impl Solution {
pub fn roman_to_int(s: String) -> i32 | // println!("{:?}", c);
}
return sum;
}
}
// fn main() {
// println!("{}", Solution::roman_to_int(String::from("IV")));
// println!("{}", Solution::roman_to_int(String::from("IX")));
// println!("{}", Solution::roman_to_int(String::from("VII")));
// println!("{}", Solu... | {
let mut sum: i32 = 0;
let table: HashMap<char, i32> = [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100),
('D', 500),
('M', 1000),
(' ', 0)]
.iter().cloned().collect();
for (c, n) in... | identifier_body |
solution.rs | use std::collections::HashMap;
// #[derive(Debug)]
// struct Solution {}
impl Solution {
pub fn | (s: String) -> i32 {
let mut sum: i32 = 0;
let table: HashMap<char, i32> = [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100),
('D', 500),
('M', 1000),
(' ', 0)]
.iter().cloned().collect();
... | roman_to_int | identifier_name |
utils.rs | use std::borrow::Cow;
use std::process;
use shellexpand;
use errors::*;
pub fn run(args: &Vec<String>) -> Result<process::ExitStatus> { |
let exit_status = process::Command::new(&args[0]).args(&args[1..]).status()?;
if!exit_status.success() {
bail!("command ended with {}", exit_status);
}
Ok(exit_status)
}
pub fn expanded_vec(v: &Vec<String>) -> Result<Vec<Cow<str>>> {
v.iter().map(|x| expanded(x)).collect()
}
pub fn expa... | let args: Vec<String> = expanded_vec(args)?
.into_iter()
.map(|x| x.into_owned())
.collect(); | random_line_split |
utils.rs | use std::borrow::Cow;
use std::process;
use shellexpand;
use errors::*;
pub fn run(args: &Vec<String>) -> Result<process::ExitStatus> {
let args: Vec<String> = expanded_vec(args)?
.into_iter()
.map(|x| x.into_owned())
.collect();
let exit_status = process::Command::new(&args[0]).args(&a... |
Ok(exit_status)
}
pub fn expanded_vec(v: &Vec<String>) -> Result<Vec<Cow<str>>> {
v.iter().map(|x| expanded(x)).collect()
}
pub fn expanded<'a>(s: &'a str) -> Result<Cow<'a, str>> {
shellexpand::full(s).chain_err(|| {
format!("cannot perform tilde or envvar expansion on {}", s)
})
}
| {
bail!("command ended with {}", exit_status);
} | conditional_block |
utils.rs | use std::borrow::Cow;
use std::process;
use shellexpand;
use errors::*;
pub fn run(args: &Vec<String>) -> Result<process::ExitStatus> {
let args: Vec<String> = expanded_vec(args)?
.into_iter()
.map(|x| x.into_owned())
.collect();
let exit_status = process::Command::new(&args[0]).args(&a... | {
shellexpand::full(s).chain_err(|| {
format!("cannot perform tilde or envvar expansion on {}", s)
})
} | identifier_body | |
utils.rs | use std::borrow::Cow;
use std::process;
use shellexpand;
use errors::*;
pub fn | (args: &Vec<String>) -> Result<process::ExitStatus> {
let args: Vec<String> = expanded_vec(args)?
.into_iter()
.map(|x| x.into_owned())
.collect();
let exit_status = process::Command::new(&args[0]).args(&args[1..]).status()?;
if!exit_status.success() {
bail!("command ended wit... | run | identifier_name |
main.rs | #![feature(box_syntax)]
#![feature(asm)]
extern crate e2d2;
extern crate fnv;
extern crate time;
extern crate rand;
use e2d2::scheduler::*;
pub struct DepTask {
id: String,
deps: Vec<usize>,
}
impl Executable for DepTask {
fn execute(&mut self) {
println!("Task -- {}", self.id);
}
fn depen... | impl DepTask {
pub fn new(parent: usize, id: &str) -> DepTask {
DepTask {
id: String::from(id),
deps: vec![parent],
}
}
}
fn test_func(id: &str) {
println!("Base Task -- {}", id);
}
fn main() {
let mut sched = embedded_scheduler::EmbeddedScheduler::new();
le... | self.deps.clone()
}
} | random_line_split |
main.rs | #![feature(box_syntax)]
#![feature(asm)]
extern crate e2d2;
extern crate fnv;
extern crate time;
extern crate rand;
use e2d2::scheduler::*;
pub struct DepTask {
id: String,
deps: Vec<usize>,
}
impl Executable for DepTask {
fn execute(&mut self) {
println!("Task -- {}", self.id);
}
fn depen... | (id: &str) {
println!("Base Task -- {}", id);
}
fn main() {
let mut sched = embedded_scheduler::EmbeddedScheduler::new();
let handle0 = sched.add_task(|| test_func("task-0")).unwrap();
let other_handles = {
let mut prev_handle = handle0;
let mut nhandles: Vec<_> = (0..10).map(|_| 0).col... | test_func | identifier_name |
calculator.rs | pub fn num_words(words: &Vec<&str>) -> f32 {
let num_words;
num_words = words.len() as f32;
return num_words as f32;
}
pub fn word_mean(words: &Vec<&str>) -> f32 {
let word_mean: f32;
let mut word_length_total = 0;
let word_total = num_words(words) as f32;
for word in words {
word_length_tota... |
return (num_and, num_but, num_however, num_if, num_that, num_more, num_must, num_might, num_this, num_very);
} | } | random_line_split |
calculator.rs | pub fn num_words(words: &Vec<&str>) -> f32 {
let num_words;
num_words = words.len() as f32;
return num_words as f32;
}
pub fn word_mean(words: &Vec<&str>) -> f32 {
let word_mean: f32;
let mut word_length_total = 0;
let word_total = num_words(words) as f32;
for word in words {
word_length_tota... |
pub fn word_freq(words: &Vec<&str>) -> (i32, i32, i32, i32, i32, i32, i32, i32, i32, i32) {
let mut num_and = 0;
let mut num_but = 0;
let mut num_however = 0;
let mut num_if = 0;
let mut num_that = 0;
let mut num_more = 0;
let mut num_must = 0;
let mut num_might = 0;
let mut num_this = 0;
let mut num_very =... | {
let sent_mean: f32;
let sent_total;
sent_total = sentences.len() as f32;
let total_sent = sent_total as f32;
sent_mean = word_total / total_sent;
return sent_mean;
} | identifier_body |
calculator.rs | pub fn num_words(words: &Vec<&str>) -> f32 {
let num_words;
num_words = words.len() as f32;
return num_words as f32;
}
pub fn word_mean(words: &Vec<&str>) -> f32 {
let word_mean: f32;
let mut word_length_total = 0;
let word_total = num_words(words) as f32;
for word in words {
word_length_tota... | (word_total: &f32, sentences: &Vec<&str>) -> f32 {
let sent_mean: f32;
let sent_total;
sent_total = sentences.len() as f32;
let total_sent = sent_total as f32;
sent_mean = word_total / total_sent;
return sent_mean;
}
pub fn word_freq(words: &Vec<&str>) -> (i32, i32, i32, i32, i32, i32, i32, i32, i32, i32) {
... | sent_mean | identifier_name |
server.rs |
use common::err;
pub struct Server {
pub name: String,
cipher: Cipher,
suffix: Vec<u8>,
network: &Network
}
impl Server {
fn new(name: &str, cipher: &Cipher) -> Self {
Server {
name: name
}
}
fn set_suffix(&mut ... | (&self, method: &str, data: &Vec<u8>) -> Response {
match method {
"suffix" => self.suffix(&data),
"profile_for" => self.profile_for(&data),
_ => err
}
}
}
| receive | identifier_name |
server.rs |
use common::err;
pub struct Server {
pub name: String,
cipher: Cipher,
suffix: Vec<u8>,
network: &Network
}
impl Server {
fn new(name: &str, cipher: &Cipher) -> Self {
Server {
name: name
}
}
fn set_suffix(&mut ... |
fn suffix(&self, data: &Vec<u8>) -> Response {
let mut final_data = data.clone();
final_data.extend(&self.suffix);
let cipherdata = ertry!(self.cipher.encrypt(&final_data));
let conn = self.network.connect(&self.name, "server2");
conn.send(&cipherdata)
}
}
impl R... | {
let email_str = ertry!(ascii::raw_to_str(&email));
let user = User::new(&email, 10, "user");
let encoded = ertry!(user.encode());
let enc_raw = ertry!(ascii::str_to_raw(&encoded));
ertry!(self.cipher.encrypt(&enc_raw))
} | identifier_body |
server.rs | use common::err;
pub struct Server {
pub name: String,
cipher: Cipher,
suffix: Vec<u8>,
network: &Network
}
impl Server {
fn new(name: &str, cipher: &Cipher) -> Self {
Server {
name: name
} |
fn set_suffix(&mut self, data: &Vec<u8>) {
self.suffix = data.clone();
}
fn profile_for(&self, email: &Vec<u8>) -> Response {
let email_str = ertry!(ascii::raw_to_str(&email));
let user = User::new(&email, 10, "user");
let encoded = ertry!(user.encode());
let enc_r... | } | random_line_split |
lib.rs | #![forbid(missing_docs, warnings)]
#![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals,
plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features,
unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation,
unused_attributes,... | let max_len = params.max_msg_len();
let plain = ntru::rand::generate(max_len as u16, &rand_ctx).unwrap();
for plain_len in 0..max_len + 1 {
// Test single public key
let encrypted = ntru::encrypt(&plain[..plain_len as usize],
kp.get_public(),
... | {
let rng = RNG_DEFAULT;
let rand_ctx = ntru::rand::init(&rng).unwrap();
let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap();
// Randomly choose the number of public keys for testing ntru::generate_multiple_key_pairs and
// ntru::generate_public
let num_pub_keys: usize = rand::thread_r... | identifier_body |
lib.rs | #![forbid(missing_docs, warnings)]
#![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals,
plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features,
unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation,
unused_attributes,... |
}
d
}
fn gen_key_pair(seed: &str, params: &EncParams) -> KeyPair {
let seed_u8 = seed.as_bytes();
let rng = RNG_CTR_DRBG;
let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap();
ntru::generate_key_pair(params, &rand_ctx).unwrap()
}
fn sha1(input: &[u8]) -> [u8; 20] {
let mut hasher ... | {
d.set_coeff(i, -1)
} | conditional_block |
lib.rs | #![forbid(missing_docs, warnings)]
#![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals,
plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features,
unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation,
unused_attributes,... | params.get_n() / 3,
&rand_ctx)
.unwrap();
let m_int = m.to_int_poly();
let r = TernPoly::rand(params.get_n(),
params.get_n() / 3,
params.get_n() / 3,
... | // Encrypt a random message
let m = TernPoly::rand(params.get_n(),
params.get_n() / 3, | random_line_split |
lib.rs | #![forbid(missing_docs, warnings)]
#![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals,
plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features,
unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation,
unused_attributes,... | (seed: &str, params: &EncParams) -> KeyPair {
let seed_u8 = seed.as_bytes();
let rng = RNG_CTR_DRBG;
let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap();
ntru::generate_key_pair(params, &rand_ctx).unwrap()
}
fn sha1(input: &[u8]) -> [u8; 20] {
let mut hasher = Sha1::new();
hasher.input... | gen_key_pair | identifier_name |
static-method-on-struct-and-enum.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... | (arg1: int, arg2: int) -> int {
zzz();
arg1 + arg2
}
}
enum Enum {
Variant1 { x: int },
Variant2,
Variant3(f64, int, char),
}
impl Enum {
fn static_method(arg1: int, arg2: f64, arg3: uint) -> int {
zzz();
arg1
}
}
fn main() {
Struct::static_method(1, 2);
... | static_method | identifier_name |
static-method-on-struct-and-enum.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... | impl Enum {
fn static_method(arg1: int, arg2: f64, arg3: uint) -> int {
zzz();
arg1
}
}
fn main() {
Struct::static_method(1, 2);
Enum::static_method(-3, 4.5, 5);
}
fn zzz() {()} | Variant3(f64, int, char),
}
| random_line_split |
static-method-on-struct-and-enum.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... | {()} | identifier_body | |
protocol.rs | use std::task::TaskBuilder;
use std::io::{TcpListener, TcpStream, Acceptor, Listener};
use std::io::net::tcp::TcpAcceptor;
use std::collections::{HashSet, HashMap};
use uuid::Uuid;
use stream::{Stream, Response, SockAddr, Callback, BroadcastFrom};
use broadcast::Broadcast;
use result::{GossipResult, GossipError, NotLi... | {
Green,
Yellow,
Red
}
/// An iterator that receives new broadcasts and iterates over them.
pub struct Incoming {
node_tx: Sender<BroadcastFrom>,
tx: Sender<(Broadcast, Stream)>,
rx: Receiver<(Broadcast, Stream)>,
listening: bool
}
impl Incoming {
pub fn new(node_tx: Sender<BroadcastF... | Health | identifier_name |
protocol.rs | use std::task::TaskBuilder;
use std::io::{TcpListener, TcpStream, Acceptor, Listener};
use std::io::net::tcp::TcpAcceptor;
use std::collections::{HashSet, HashMap};
use uuid::Uuid;
use stream::{Stream, Response, SockAddr, Callback, BroadcastFrom};
use broadcast::Broadcast;
use result::{GossipResult, GossipError, NotLi... |
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn empty_member_set() {
let mut node = Node::new();
assert_eq!(node.members.len(), 0);
}
#[test]
fn bind_listening() {
let mut node = Node::new();
}
}
| {
let (tx, rx) = channel();
let incoming = Incoming::new(self.tx.clone(), tx);
self.incoming_tx = Some(rx.recv());
incoming
} | identifier_body |
protocol.rs | use std::task::TaskBuilder;
use std::io::{TcpListener, TcpStream, Acceptor, Listener};
use std::io::net::tcp::TcpAcceptor;
use std::collections::{HashSet, HashMap};
use uuid::Uuid;
use stream::{Stream, Response, SockAddr, Callback, BroadcastFrom};
use broadcast::Broadcast;
use result::{GossipResult, GossipError, NotLi... |
#[test]
fn bind_listening() {
let mut node = Node::new();
}
} | fn empty_member_set() {
let mut node = Node::new();
assert_eq!(node.members.len(), 0);
} | random_line_split |
protocol.rs | use std::task::TaskBuilder;
use std::io::{TcpListener, TcpStream, Acceptor, Listener};
use std::io::net::tcp::TcpAcceptor;
use std::collections::{HashSet, HashMap};
use uuid::Uuid;
use stream::{Stream, Response, SockAddr, Callback, BroadcastFrom};
use broadcast::Broadcast;
use result::{GossipResult, GossipError, NotLi... | ,
Err(e) => println!("Error: {}", e)
}
}
}
}
struct ServerTask {
streams: HashMap<Peer, TcpStream>,
acceptor_tx: Sender<Broadcast>,
tx: Sender<TaskMessage>,
rx: Receiver<TaskMessage>
}
impl ServerTask {
pub fn new(host: String, port: u16) -> ServerTask {
... | {
// Handle the joining here...
let stream_send = s.clone();
let server = self.server_tx.clone();
spawn(proc() {
let stream = Stream::new(stream_send);
server.send(StreamMsg(stream.clone()));
... | conditional_block |
subscriber_to_roscpp_publisher.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String);
}
#[test]
fn subscriber_to_roscpp_publisher() {
let _roscore = util::run_roscore_for(util::Language::Cpp, util::Feature::Subscriber);
let _publisher = util::ChildProcessTerminato... | })
.unwrap();
util::test_subscriber(rx, r"hello world (\d+)", true, 20);
assert_eq!(subscriber.publisher_count(), 1);
} | let (tx, rx) = unbounded();
rosrust::init("hello_world_listener");
let subscriber = rosrust::subscribe::<msg::std_msgs::String, _>("chatter", 100, move |data| {
tx.send(data.data).unwrap(); | random_line_split |
subscriber_to_roscpp_publisher.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String);
}
#[test]
fn | () {
let _roscore = util::run_roscore_for(util::Language::Cpp, util::Feature::Subscriber);
let _publisher = util::ChildProcessTerminator::spawn(
Command::new("rosrun").arg("roscpp_tutorials").arg("talker"),
);
let (tx, rx) = unbounded();
rosrust::init("hello_world_listener");
let subsc... | subscriber_to_roscpp_publisher | identifier_name |
subscriber_to_roscpp_publisher.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String);
}
#[test]
fn subscriber_to_roscpp_publisher() | {
let _roscore = util::run_roscore_for(util::Language::Cpp, util::Feature::Subscriber);
let _publisher = util::ChildProcessTerminator::spawn(
Command::new("rosrun").arg("roscpp_tutorials").arg("talker"),
);
let (tx, rx) = unbounded();
rosrust::init("hello_world_listener");
let subscrib... | identifier_body | |
simple.rs | use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').c... |
if parts[1].is_empty() {
return Err(AddrError { msg: "empty string is not valid for domain part".to_string() });
}
Ok(EmailAddress {
local: parts[1].to_string(),
domain: parts[0].to_string()
})
}
#[cfg(test)]
mod test {
use super::*;
use common::{EmailAddress};
#... | {
return Err(AddrError { msg: "empty string is not valid for local part".to_string() });
} | conditional_block |
simple.rs | use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').c... | if parts[1].is_empty() {
return Err(AddrError { msg: "empty string is not valid for domain part".to_string() });
}
Ok(EmailAddress {
local: parts[1].to_string(),
domain: parts[0].to_string()
})
}
#[cfg(test)]
mod test {
use super::*;
use common::{EmailAddress};
#[t... | return Err(AddrError { msg: "empty string is not valid for local part".to_string() });
}
| random_line_split |
simple.rs | use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> |
#[cfg(test)]
mod test {
use super::*;
use common::{EmailAddress};
#[test]
fn test_simple_parse() {
assert_eq!(
parse("someone@example.com").unwrap(),
EmailAddress {
local: "someone".to_string(),
domain: "example.com".to_s... | {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').collect();
if parts[0].is_empty() {
return Err(AddrError { msg: "empty string is not valid for local part".to_string() });
}
if parts[1... | identifier_body |
simple.rs | use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').c... | () {
assert_eq!(
parse("someone@example.com").unwrap(),
EmailAddress {
local: "someone".to_string(),
domain: "example.com".to_string()
}
);
}
}
| test_simple_parse | identifier_name |
lint-uppercase-variables.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
let Test: usize = 0; //~ ERROR variable `Test` should have a snake case name such as `test`
println!("{}", Test);
let mut f = File::open(&Path::new("something.txt"));
let mut buff = [0u8; 16];
match f.read(&mut buff) {
Ok(cnt) => println!("read this many bytes: {}", cnt),
Err(I... | main | identifier_name |
lint-uppercase-variables.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | }
test(1);
let _ = Something { X: 0 };
} | Err(IoError{ kind: EndOfFile, .. }) => println!("Got end of file: {:?}", EndOfFile),
//~^ ERROR variable `EndOfFile` should have a snake case name such as `end_of_file`
//~^^ WARN `EndOfFile` is named the same as one of the variants of the type `std::old_io::IoErrorKind` | random_line_split |
mod.rs | /// Shareable data structures.
pub mod directory;
pub use self::shared_vec::*;
mod shared_vec;
use libc::{self, c_void, close, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::ffi::CString;
use std::io::Error;
use std::ptr;
use utils::PAGE_SIZE;
struct SharedMemory<T> {
pub mem: *mut T,
name: CString,
... | let size = self.size;
let _ret = munmap(self.mem as *mut c_void, size); // Unmap pages.
// Record munmap failure.
let shm_ret = shm_unlink(self.name.as_ptr());
assert!(shm_ret == 0, "Could not unlink shared mem... | fn drop(&mut self) {
unsafe { | random_line_split |
mod.rs | /// Shareable data structures.
pub mod directory;
pub use self::shared_vec::*;
mod shared_vec;
use libc::{self, c_void, close, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::ffi::CString;
use std::io::Error;
use std::ptr;
use utils::PAGE_SIZE;
struct SharedMemory<T> {
pub mem: *mut T,
name: CString,
... |
close(fd);
SharedMemory {
mem: address as *mut T,
name: name,
size: size,
}
}
| {
let err_string = CString::new("mmap failed").unwrap();
libc::perror(err_string.as_ptr());
panic!("Could not mmap shared region");
} | conditional_block |
mod.rs | /// Shareable data structures.
pub mod directory;
pub use self::shared_vec::*;
mod shared_vec;
use libc::{self, c_void, close, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::ffi::CString;
use std::io::Error;
use std::ptr;
use utils::PAGE_SIZE;
struct | <T> {
pub mem: *mut T,
name: CString,
size: usize,
}
impl<T> Drop for SharedMemory<T> {
fn drop(&mut self) {
unsafe {
let size = self.size;
let _ret = munmap(self.mem as *mut c_void, size); // Unmap pages.
// ... | SharedMemory | identifier_name |
phrase_query.rs | use schema::Term;
use query::Query;
use core::searcher::Searcher;
use super::PhraseWeight;
use std::any::Any;
use query::Weight;
use Result;
/// `PhraseQuery` matches a specific sequence of word.
/// For instance the phrase query for `"part time"` will match
/// the sentence
///
/// **Alan just got a part time job.**... | (phrase_terms: Vec<Term>) -> PhraseQuery {
assert!(phrase_terms.len() > 1);
PhraseQuery { phrase_terms: phrase_terms }
}
}
| from | identifier_name |
phrase_query.rs | use schema::Term;
use query::Query;
use core::searcher::Searcher;
use super::PhraseWeight; | use query::Weight;
use Result;
/// `PhraseQuery` matches a specific sequence of word.
/// For instance the phrase query for `"part time"` will match
/// the sentence
///
/// **Alan just got a part time job.**
///
/// On the other hand it will not match the sentence.
///
/// **This is my favorite part of the job.**
//... | use std::any::Any; | random_line_split |
consts.rs | use crate::mir::interpret::ConstValue;
use crate::mir::interpret::{LitToConstInput, Scalar};
use crate::ty::{
self, InlineConstSubsts, InlineConstSubstsParts, InternalSubsts, ParamEnv, ParamEnvAnd, Ty,
TyCtxt, TypeFoldable,
};
use rustc_errors::ErrorReported;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId,... | let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
let parent_substs =
tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
let substs =
InlineConstSubsts::new(tcx, InlineConstSubstsParts ... | {
debug!("Const::from_inline_const(def_id={:?})", def_id);
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = match tcx.hir().get(hir_id) {
hir::Node::AnonConst(ac) => ac.body,
_ => span_bug!(
tcx.def_span(def_id.to_def_id()),
... | identifier_body |
consts.rs | use crate::mir::interpret::ConstValue;
use crate::mir::interpret::{LitToConstInput, Scalar};
use crate::ty::{
self, InlineConstSubsts, InlineConstSubstsParts, InternalSubsts, ParamEnv, ParamEnvAnd, Ty,
TyCtxt, TypeFoldable,
};
use rustc_errors::ErrorReported;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId,... | #[inline]
/// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
pub fn eval_bits(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
self.try_eval_bits(tcx, param_env, ty)
.unwrap_or_else(|| bug!("expected bits of {:#?},... | random_line_split | |
consts.rs | use crate::mir::interpret::ConstValue;
use crate::mir::interpret::{LitToConstInput, Scalar};
use crate::ty::{
self, InlineConstSubsts, InlineConstSubstsParts, InternalSubsts, ParamEnv, ParamEnvAnd, Ty,
TyCtxt, TypeFoldable,
};
use rustc_errors::ErrorReported;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId,... | (&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u64> {
self.val.eval(tcx, param_env).try_to_machine_usize(tcx)
}
#[inline]
/// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the
/// unevaluated constant.
pub fn eval(&self, tcx: TyCtxt<... | try_eval_usize | identifier_name |
cogroup.rs | //! Group records by a key, and apply a reduction function.
//!
//! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records
//! with the same key, and apply user supplied functions to the key and a list of values, which are
//! expected to populate a list of output values.
//!
//!... | // create an exchange channel based on the supplied Fn(&D1)->u64.
let exch1 = Exchange::new(move |&((ref k, _),_)| key_1(k).as_u64());
let exch2 = Exchange::new(move |&((ref k, _),_)| key_2(k).as_u64());
let mut sorter1 = LSBRadixSorter::new();
let mut sorter2 = LSBRadixSorter::... | {
let mut source1 = Trace::new(look(0));
let mut source2 = Trace::new(look(0));
let mut result = Trace::new(look(0));
// A map from times to received (key, val, wgt) triples.
let mut inputs1 = Vec::new();
let mut inputs2 = Vec::new();
// A map from times to a l... | identifier_body |
cogroup.rs | //! Group records by a key, and apply a reduction function.
//!
//! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records
//! with the same key, and apply user supplied functions to the key and a list of values, which are
//! expected to populate a list of output values.
//!
//!... |
}
}
}))
}
}
| {
// println!("group2");
result.set_difference(index.time(), accumulation);
} | conditional_block |
cogroup.rs | //! Group records by a key, and apply a reduction function.
//!
//! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records
//! with the same key, and apply user supplied functions to the key and a list of values, which are
//! expected to populate a list of output values.
//!
//!... | let mut sorted = sorter2.finish(&|x| key_h(&(x.0).0));
let result = Compact::from_radix(&mut sorted, &|k| key_h(k));
sorted.truncate(256);
sorter2.recycle(sorted);
result
}
... | } | random_line_split |
cogroup.rs | //! Group records by a key, and apply a reduction function.
//!
//! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records
//! with the same key, and apply user supplied functions to the key and a list of values, which are
//! expected to populate a list of output values.
//!
//!... | <
D: Data,
V2: Data+Default,
V3: Data+Default,
U: Unsigned+Default,
KH: Fn(&K)->U+'static,
Look: Lookup<K, Offset>+'static,
LookG: Fn(u64)->Look,
Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)... | cogroup_by_inner | identifier_name |
bind-by-move-no-guards.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 ... | Some(z) => { assert!(!z.recv().unwrap()); },
None => panic!()
}
} | random_line_split | |
bind-by-move-no-guards.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let (tx, rx) = channel();
let x = Some(rx);
tx.send(false);
match x {
Some(z) if z.recv().unwrap() => { panic!() },
//~^ ERROR cannot bind by-move into a pattern guard
Some(z) => { assert!(!z.recv().unwrap()); },
None => panic!()
}
}
| main | identifier_name |
bind-by-move-no-guards.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let (tx, rx) = channel();
let x = Some(rx);
tx.send(false);
match x {
Some(z) if z.recv().unwrap() => { panic!() },
//~^ ERROR cannot bind by-move into a pattern guard
Some(z) => { assert!(!z.recv().unwrap()); },
None => panic!()
}
} | identifier_body | |
bind-by-move-no-guards.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 ... | ,
//~^ ERROR cannot bind by-move into a pattern guard
Some(z) => { assert!(!z.recv().unwrap()); },
None => panic!()
}
}
| { panic!() } | conditional_block |
tempdir.rs | // Mainly taken from crate `tempdir`
extern crate rand;
use rand::{Rng, thread_rng};
use std::io::Result as IOResult;
use std::io::{Error, ErrorKind};
use std::path::Path;
// How many times should we (re)try finding an unused random name? It should be
// enough that an attacker will run out of luck before we run out... | pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str, rand: usize, suffix: &str) -> IOResult<String> {
let mut rng = thread_rng();
for _ in 0..NUM_RETRIES {
let rand_chars: String = rng.gen_ascii_chars().take(rand).collect();
let leaf = format!("{}{}{}", prefix, rand_chars, suffix);
le... | }
| random_line_split |
tempdir.rs | // Mainly taken from crate `tempdir`
extern crate rand;
use rand::{Rng, thread_rng};
use std::io::Result as IOResult;
use std::io::{Error, ErrorKind};
use std::path::Path;
// How many times should we (re)try finding an unused random name? It should be
// enough that an attacker will run out of luck before we run out... | <P: AsRef<Path>>(path: P) -> IOResult<()> {
use std::fs::DirBuilder;
use std::os::unix::fs::DirBuilderExt;
DirBuilder::new().mode(0o700).create(path)
}
#[cfg(windows)]
fn create_dir<P: AsRef<Path>>(path: P) -> IOResult<()> {
::std::fs::create_dir(path)
}
pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefi... | create_dir | identifier_name |
tempdir.rs | // Mainly taken from crate `tempdir`
extern crate rand;
use rand::{Rng, thread_rng};
use std::io::Result as IOResult;
use std::io::{Error, ErrorKind};
use std::path::Path;
// How many times should we (re)try finding an unused random name? It should be
// enough that an attacker will run out of luck before we run out... |
pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str, rand: usize, suffix: &str) -> IOResult<String> {
let mut rng = thread_rng();
for _ in 0..NUM_RETRIES {
let rand_chars: String = rng.gen_ascii_chars().take(rand).collect();
let leaf = format!("{}{}{}", prefix, rand_chars, suffix);
... | {
::std::fs::create_dir(path)
} | identifier_body |
mod.rs | use num::{One, Integer};
use num::bigint::{BigUint, RandBigInt};
use rand::Rng;
use utils::primes::tests::PrimeTest;
pub mod tests;
const PRIME_TEST_COUNT: usize = 20;
/// Generate new prime number with given bit size via given random number generator.
///
/// Currently this function give guarantee that it ever end... |
if tests::MillerRabin(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue }
return Some(int)
}
}
| { continue } | conditional_block |
mod.rs | use num::{One, Integer};
use num::bigint::{BigUint, RandBigInt};
use rand::Rng;
use utils::primes::tests::PrimeTest;
pub mod tests;
const PRIME_TEST_COUNT: usize = 20;
/// Generate new prime number with given bit size via given random number generator.
///
/// Currently this function give guarantee that it ever end... | {
loop {
let mut int = gen.gen_biguint(bits);
if int.is_even() { int = int + BigUint::one(); }
if tests::Fermat(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue }
if tests::MillerRabin(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue }
retur... | identifier_body | |
mod.rs | use num::{One, Integer};
use num::bigint::{BigUint, RandBigInt};
use rand::Rng;
use utils::primes::tests::PrimeTest;
pub mod tests;
const PRIME_TEST_COUNT: usize = 20;
/// Generate new prime number with given bit size via given random number generator.
///
/// Currently this function give guarantee that it ever end... | <T: Rng + RandBigInt>(gen: &mut T, bits: usize) -> Option<BigUint> {
loop {
let mut int = gen.gen_biguint(bits);
if int.is_even() { int = int + BigUint::one(); }
if tests::Fermat(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue }
if tests::MillerRabin(gen).test_loop... | generate_prime | identifier_name |
mod.rs | use num::{One, Integer};
use num::bigint::{BigUint, RandBigInt};
use rand::Rng;
use utils::primes::tests::PrimeTest;
pub mod tests;
const PRIME_TEST_COUNT: usize = 20;
/// Generate new prime number with given bit size via given random number generator.
///
/// Currently this function give guarantee that it ever end... | if tests::MillerRabin(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue }
return Some(int)
}
} | random_line_split | |
mut_reference.rs | use clippy_utils::diagnostics::span_lint;
use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::subst::Subst;
use rustc_middle::ty::{self, Ty};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use std::iter;
declare_clippy_lint! {
/// ... | <'tcx>(
cx: &LateContext<'tcx>,
arguments: &[Expr<'_>],
type_definition: Ty<'tcx>,
name: &str,
fn_kind: &str,
) {
match type_definition.kind() {
ty::FnDef(..) | ty::FnPtr(_) => {
let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
for (argument... | check_arguments | identifier_name |
mut_reference.rs | use clippy_utils::diagnostics::span_lint;
use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::subst::Subst;
use rustc_middle::ty::{self, Ty};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use std::iter;
declare_clippy_lint! {
/// ... | argument.span,
&format!("the {} `{}` doesn't need a mutable reference", fn_kind, name),
);
}
},
_ => (),
}
}
},
_ => (),... | }) => {
if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind {
span_lint(
cx,
UNNECESSARY_MUT_PASSED, | random_line_split |
mut_reference.rs | use clippy_utils::diagnostics::span_lint;
use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::subst::Subst;
use rustc_middle::ty::{self, Ty};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use std::iter;
declare_clippy_lint! {
/// ... | }
}
}
fn check_arguments<'tcx>(
cx: &LateContext<'tcx>,
arguments: &[Expr<'_>],
type_definition: Ty<'tcx>,
name: &str,
fn_kind: &str,
) {
match type_definition.kind() {
ty::FnDef(..) | ty::FnPtr(_) => {
let parameters = type_definition.fn_sig(cx.tcx).skip_binder... | {
match e.kind {
ExprKind::Call(fn_expr, arguments) => {
if let ExprKind::Path(ref path) = fn_expr.kind {
check_arguments(
cx,
arguments,
cx.typeck_results().expr_ty(fn_expr),
... | identifier_body |
add_retag.rs | //! This pass adds validation calls (AcquireValid, ReleaseValid) where appropriate.
//! It has to be run really early, before transformations like inlining, because
//! introducing these calls *adds* UB -- so, conceptually, this pass is actually part
//! of MIR building, and only after this pass we think of the program... | }
}
impl<'tcx> MirPass<'tcx> for AddRetag {
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
if!tcx.sess.opts.debugging_opts.mir_emit_retag {
return;
}
// We need an `AllCallEdges` pass before we can do any work.
super::add_call_guards::AllCallEdges.r... | {
match ty.kind() {
// Primitive types that are not references
ty::Bool
| ty::Char
| ty::Float(_)
| ty::Int(_)
| ty::Uint(_)
| ty::RawPtr(..)
| ty::FnPtr(..)
| ty::Str
| ty::FnDef(..)
| ty::Never => false,
// References
... | identifier_body |
add_retag.rs | //! This pass adds validation calls (AcquireValid, ReleaseValid) where appropriate.
//! It has to be run really early, before transformations like inlining, because
//! introducing these calls *adds* UB -- so, conceptually, this pass is actually part
//! of MIR building, and only after this pass we think of the program... | // FIXME: Consider using just the span covering the function
// argument declaration.
let source_info = SourceInfo::outermost(span);
// Gather all arguments, skip return value.
let places = local_decls
.iter_enumerated()
.skip(1)
... |
// PART 1
// Retag arguments at the beginning of the start block.
{ | random_line_split |
add_retag.rs | //! This pass adds validation calls (AcquireValid, ReleaseValid) where appropriate.
//! It has to be run really early, before transformations like inlining, because
//! introducing these calls *adds* UB -- so, conceptually, this pass is actually part
//! of MIR building, and only after this pass we think of the program... | (ty: Ty<'tcx>) -> bool {
match ty.kind() {
// Primitive types that are not references
ty::Bool
| ty::Char
| ty::Float(_)
| ty::Int(_)
| ty::Uint(_)
| ty::RawPtr(..)
| ty::FnPtr(..)
| ty::Str
| ty::FnDef(..)
| ty::Never => false,... | may_be_reference | identifier_name |
rename.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::borrow::Cow;
use std::str::FromStr;
/// The type of identifier to be renamed.
#[derive(Debug, Clone, Cop... |
/// Applies the rename rule to a string
pub fn apply<'a>(self, text: &'a str, context: IdentifierType) -> Cow<'a, str> {
use heck::*;
if text.is_empty() {
return Cow::Borrowed(text);
}
Cow::Owned(match self {
RenameRule::None => return Cow::Borrowed(te... | {
match self {
RenameRule::None => None,
other => Some(other),
}
} | identifier_body |
rename.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::borrow::Cow;
use std::str::FromStr;
/// The type of identifier to be renamed.
#[derive(Debug, Clone, Cop... | (s: &str) -> Result<RenameRule, Self::Err> {
match s {
"none" => Ok(RenameRule::None),
"None" => Ok(RenameRule::None),
"mGeckoCase" => Ok(RenameRule::GeckoCase),
"GeckoCase" => Ok(RenameRule::GeckoCase),
"gecko_case" => Ok(RenameRule::GeckoCase),
... | from_str | identifier_name |
rename.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::borrow::Cow;
use std::str::FromStr;
/// The type of identifier to be renamed.
#[derive(Debug, Clone, Cop... | pub(crate) fn not_none(self) -> Option<Self> {
match self {
RenameRule::None => None,
other => Some(other),
}
}
/// Applies the rename rule to a string
pub fn apply<'a>(self, text: &'a str, context: IdentifierType) -> Cow<'a, str> {
use heck::*;
... |
impl RenameRule { | random_line_split |
main.rs | fn can_spell(w: &str, blocks: &Vec<&str>) -> bool {
fn solve(chars: Vec<char>, avail_blocks: &Vec<&str>) -> bool {
if chars.is_empty() {
true
} else if avail_blocks.is_empty() {
false
} else {
let pos = avail_blocks.iter().position(|&b| b.chars().any(|c| c... | "TG", "QD", "FS", "JW", "HU", "VI", "AN",
"OB", "ER", "FS", "LY", "PC", "ZM"];
for w in words.iter() {
println!("Can I spell {}: {}", w, can_spell(w, &blocks));
}
} | random_line_split | |
main.rs | fn can_spell(w: &str, blocks: &Vec<&str>) -> bool | }
}
}
solve(w.chars().collect(), blocks)
}
fn main() {
let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"];
let blocks = vec!["BO", "XK", "DQ", "CP", "NA", "GT", "RE",
"TG", "QD", "FS", "JW", "HU", "VI", "AN",
"OB", ... | {
fn solve(chars: Vec<char>, avail_blocks: &Vec<&str>) -> bool {
if chars.is_empty() {
true
} else if avail_blocks.is_empty() {
false
} else {
let pos = avail_blocks.iter().position(|&b| b.chars().any(|c| c == chars[0]));
match pos {
... | identifier_body |
main.rs | fn can_spell(w: &str, blocks: &Vec<&str>) -> bool {
fn | (chars: Vec<char>, avail_blocks: &Vec<&str>) -> bool {
if chars.is_empty() {
true
} else if avail_blocks.is_empty() {
false
} else {
let pos = avail_blocks.iter().position(|&b| b.chars().any(|c| c == chars[0]));
match pos {
Some(n)... | solve | identifier_name |
union-fields-2.rs | // revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
union U {
a: u8,
b: u16,
}
fn main() {
let u = U {}; //~ ERROR union expressions should have exactly one field
let u = U { a: 0 }; // OK
let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly... | let U { a, b } = u; //~ ERROR union patterns should have exactly one field
let U { a, b, c } = u; //~ ERROR union patterns should have exactly one field
//~^ ERROR union `U` does not have a field named `c`
let U {.. } = u; //~ ERROR union patterns should have exactly one field
... | let u = U { ..u }; //~ ERROR union expressions should have exactly one field
//~^ ERROR functional record update syntax requires a struct
let U {} = u; //~ ERROR union patterns should have exactly one field
let U { a } = u; // OK | random_line_split |
union-fields-2.rs | // revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
union U {
a: u8,
b: u16,
}
fn main() | {
let u = U {}; //~ ERROR union expressions should have exactly one field
let u = U { a: 0 }; // OK
let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly one field
let u = U { a: 0, b: 1, c: 2 }; //~ ERROR union expressions should have exactly one field
... | identifier_body | |
union-fields-2.rs | // revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
union U {
a: u8,
b: u16,
}
fn | () {
let u = U {}; //~ ERROR union expressions should have exactly one field
let u = U { a: 0 }; // OK
let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly one field
let u = U { a: 0, b: 1, c: 2 }; //~ ERROR union expressions should have exactly one field
... | main | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | #![feature(io)]
#![feature(rustc_private)]
#![feature(std_misc)]
#![allow(missing_copy_implementations)]
#[macro_use]
extern crate log;
extern crate azure;
extern crate devtools_traits;
extern crate geom;
extern crate gfx;
extern crate layers;
extern crate layout_traits;
extern crate png;
extern crate script_traits;... |
#![feature(box_syntax)]
#![feature(core)]
#![feature(int_uint)] | random_line_split |
request.rs | use error;
use hyper;
use hyper_rustls;
use response;
use std;
use types;
use url;
#[derive(Debug, Clone)]
pub struct Request<'a> {
client: std::sync::Arc<hyper::Client>,
method: types::Method,
url: url::Url<'a>,
headers: hyper::header::Headers,
body: String,
}
impl<'a> Request<'a> {
pub fn new() -> Req... |
pub fn add_header<H>(&mut self, header: H) -> &mut Request<'a>
where H: hyper::header::Header + hyper::header::HeaderFormat
{
self.headers.set(header);
self
}
pub fn add_path<S>(&mut self, path: S) -> &mut Request<'a>
where S: Into<String>
{
self.url.add_path(path.into());
self
... | {
self.body = body.into();
self
} | identifier_body |
request.rs | use error;
use hyper;
use hyper_rustls;
use response;
use std;
use types;
use url;
#[derive(Debug, Clone)]
pub struct Request<'a> {
client: std::sync::Arc<hyper::Client>,
method: types::Method,
url: url::Url<'a>,
headers: hyper::header::Headers,
body: String,
}
impl<'a> Request<'a> {
pub fn new() -> Req... | <K, S>(&mut self, key: K, val: S) -> &mut Request<'a>
where K: Into<String>,
S: Into<std::borrow::Cow<'a, str>>
{
self.url.add_query_param(key, val);
self
}
pub fn basic_auth<U, P>(&mut self, u: U, p: Option<P>) -> &mut Request<'a>
where U: Into<String>,
P: Into<String>
{
... | add_query_param | identifier_name |
request.rs | use error;
use hyper;
use hyper_rustls;
use response;
use std;
use types;
use url;
#[derive(Debug, Clone)]
pub struct Request<'a> {
client: std::sync::Arc<hyper::Client>,
method: types::Method,
url: url::Url<'a>,
headers: hyper::header::Headers,
body: String,
}
impl<'a> Request<'a> {
pub fn new() -> Req... |
pub fn set_body<S>(&mut self, body: S) -> &mut Request<'a>
where S: Into<String>
{
self.body = body.into();
self
}
pub fn add_header<H>(&mut self, header: H) -> &mut Request<'a>
where H: hyper::header::Header + hyper::header::HeaderFormat
{
self.headers.set(header);
self
}
p... | self.headers = headers;
self
} | random_line_split |
mod.rs | //! Public-key authenticated encryption
//!
//! # Security model
//! The `seal()` function is designed to meet the standard notions of privacy and | //! encryption in the public-key setting: security notions and analyses,"
//! http://eprint.iacr.org/2001/079.
//!
//! Distinct messages between the same {sender, receiver} set are required
//! to have distinct nonces. For example, the lexicographically smaller
//! public key can use nonce 1 for its first message to th... | //! third-party unforgeability for a public-key authenticated-encryption scheme
//! using nonces. For formal definitions see, e.g., Jee Hea An, "Authenticated | random_line_split |
main.rs | //parser created by Ivan Temchenko <ivan.temchenko@yandex.ua>, 2015
extern crate csv;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
struct All {
y0: Vec<Vec<String>>,
y1: Vec<Vec<String>>,
y2: Vec<Vec<String>>,
y3: Vec<Vec<String>>,
y4: Ve... | uniq.p0 = find_uniq(all.y0);
println!("15% done..");
uniq.p1 = find_uniq(all.y1);
println!("30% done..");
uniq.p2 = find_uniq(all.y2);
println!("45% done..");
uniq.p3 = find_uniq(all.y3);
println!("60% done..");
uniq.p4 = find_uniq(all.y4);
println!("75% done..");
uniq.p5 = find_uniq(all.y5);
println!("90% ... | {
let mut all = All {y0: vec![], y1: vec![], y2: vec![], y3: vec![], y4: vec![], y5: vec![], y6: vec![], els: vec![]};
let mut uniq = Uniq {p0: vec![], p1: vec![], p2: vec![], p3: vec![], p4: vec![], p5: vec![], p6: vec![]};
let mut train = csv::Reader::from_file("./data/train.csv").unwrap();
for train_record in t... | identifier_body |
main.rs | //parser created by Ivan Temchenko <ivan.temchenko@yandex.ua>, 2015
extern crate csv;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
struct All {
y0: Vec<Vec<String>>,
y1: Vec<Vec<String>>,
y2: Vec<Vec<String>>,
y3: Vec<Vec<String>>,
y4: Ve... | (v: Vec<Vec<String>>) -> Vec<String> {
v.into_iter().flat_map(|v| v).collect::<HashSet<String>>().into_iter().collect()
}
fn write_to_file(s: String) {
let path = Path::new("./data/sol.csv");
let mut options = OpenOptions::new();
options.write(true).append(true);
let file = match options.open(&path) {
Ok(fil... | find_uniq | identifier_name |
main.rs | //parser created by Ivan Temchenko <ivan.temchenko@yandex.ua>, 2015
extern crate csv;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
struct All {
y0: Vec<Vec<String>>,
y1: Vec<Vec<String>>,
y2: Vec<Vec<String>>,
y3: Vec<Vec<String>>,
y4: Ve... | p5: Vec<String>,
p6: Vec<String>,
}
struct RCounter {
c0: i32,
c1: i32,
c2: i32,
c3: i32,
c4: i32,
c5: i32,
c6: i32,
}
fn main() {
let mut all = All {y0: vec![], y1: vec![], y2: vec![], y3: vec![], y4: vec![], y5: vec![], y6: vec![], els: vec![]};
let mut uniq = Uniq {p0: vec![], p1: vec![], p2: vec![], p3... | p2: Vec<String>,
p3: Vec<String>,
p4: Vec<String>, | random_line_split |
main.rs | //parser created by Ivan Temchenko <ivan.temchenko@yandex.ua>, 2015
extern crate csv;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
struct All {
y0: Vec<Vec<String>>,
y1: Vec<Vec<String>>,
y2: Vec<Vec<String>>,
y3: Vec<Vec<String>>,
y4: Ve... |
}
for u in &uniq.p4 {
if test_string == &u.to_string() {
rate.c4 += 1;
}
}
for u in &uniq.p5 {
if test_string == &u.to_string() {
rate.c5 += 1;
}
}
for u in &uniq.p6 {
if test_string == &u.to_string() {
rate.c6 += 1;
}
}
}
let mut decisi... | {
rate.c3 += 1;
} | conditional_block |
rwlock.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 ... | (&self) -> bool {
ffi::pthread_rwlock_trywrlock(self.inner.get()) == 0
}
#[inline]
pub unsafe fn read_unlock(&self) {
let r = ffi::pthread_rwlock_unlock(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn write_unlock(&self) { self.read_unlock() }
#[i... | try_write | identifier_name |
rwlock.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 ... |
#[inline]
pub unsafe fn destroy(&self) {
let r = ffi::pthread_rwlock_destroy(self.inner.get());
debug_assert_eq!(r, 0);
}
}
| { self.read_unlock() } | identifier_body |
rwlock.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 ... | pub unsafe fn read(&self) {
let r = ffi::pthread_rwlock_rdlock(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn try_read(&self) -> bool {
ffi::pthread_rwlock_tryrdlock(self.inner.get()) == 0
}
#[inline]
pub unsafe fn write(&self) {
let r = ... | // Might be moved and address is changing it is better to avoid
// initialization of potentially opaque OS data before it landed
RWLOCK_INIT
}
#[inline] | random_line_split |
viewport.rs | // This file is part of rgtk.
//
// rgtk 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
// (at your option) any later version.
//
// rgtk is distributed in the hop... | self) -> gtk::ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn set_shadow_type(&mut self, ty: gtk::ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
}
impl_drop!... | t_shadow_type(& | identifier_name |
viewport.rs | // This file is part of rgtk.
//
// rgtk 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
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser Gener... | random_line_split | |
viewport.rs | // This file is part of rgtk.
//
// rgtk 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
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
impl_drop!(Viewport);
impl_TraitWidget!(Viewport);
impl gtk::ContainerTrait for Viewport {}
impl gtk::BinTrait for Viewport {}
impl gtk::ScrollableTrait for Viewport {}
impl_widget_events!(Viewport);
| unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
} | identifier_body |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... | svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<SVGSVGElement> {
Node::ref... | prefix: Option<DOMString>,
document: &Document) -> SVGSVGElement {
SVGSVGElement { | random_line_split |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... | (local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> SVGSVGElement {
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
... | new_inherited | identifier_name |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... |
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type()... | {
self.super_type().unwrap().attribute_mutated(attr, mutation);
} | identifier_body |
trait-bounds-impl-comparison-1.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 ... |
fn test_error7_fn<T: A + Eq>(&self) {}
//~^ ERROR the requirement `T : core::cmp::Eq` appears on the impl
fn test_error8_fn<T: C>(&self) {}
//~^ ERROR the requirement `T : C` appears on the impl
}
trait Getter<T> { }
trait Trait {
fn method<G:Getter<isize>>();
}
impl Trait for usize {
fn ... | {} | identifier_body |
trait-bounds-impl-comparison-1.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 ... |
impl Foo for isize {
// invalid bound for T, was defined as Eq in trait
fn test_error1_fn<T: Ord>(&self) {}
//~^ ERROR the requirement `T : core::cmp::Ord` appears on the impl
// invalid bound for T, was defined as Eq + Ord in trait
fn test_error2_fn<T: Eq + B>(&self) {}
//~^ ERROR the require... | fn test_error8_fn<T: B>(&self);
} | random_line_split |
trait-bounds-impl-comparison-1.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 ... | <T: Ord + Eq>(&self) {}
// multiple bounds, different order as in trait
fn test4_fn<T: Eq + Ord>(&self) {}
// parameters in impls must be equal or more general than in the defining trait
fn test_error5_fn<T: B>(&self) {}
//~^ ERROR the requirement `T : B` appears on the impl
// bound `std::cm... | test3_fn | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.