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 |
|---|---|---|---|---|
msg_pong.rs | use std;
use ::serialize::{self, Serializable};
use super::PingMessage;
use super::BIP0031_VERSION;
#[derive(Debug,Default,Clone)]
pub struct |
{
pub nonce: u64,
}
impl PongMessage {
pub fn new(ping:&PingMessage) -> PongMessage {
PongMessage{ nonce: ping.nonce }
}
}
impl super::Message for PongMessage {
fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] {
super::message_header::COMMAND_PONG
}
}
impl std::fmt::Displa... | PongMessage | identifier_name |
msg_pong.rs | use std;
use ::serialize::{self, Serializable};
use super::PingMessage;
use super::BIP0031_VERSION;
#[derive(Debug,Default,Clone)]
pub struct PongMessage
{
pub nonce: u64,
}
impl PongMessage {
pub fn new(ping:&PingMessage) -> PongMessage {
PongMessage{ nonce: ping.nonce }
}
}
impl super::Message for Po... | else {
Ok(0usize)
}
}
}
| {
self.nonce.deserialize(io, ser)
} | conditional_block |
msg_pong.rs | use std;
use ::serialize::{self, Serializable};
use super::PingMessage;
use super::BIP0031_VERSION;
#[derive(Debug,Default,Clone)]
pub struct PongMessage
{
pub nonce: u64,
}
impl PongMessage {
pub fn new(ping:&PingMessage) -> PongMessage {
PongMessage{ nonce: ping.nonce }
}
}
impl super::Message for Po... | if BIP0031_VERSION < ser.version {
self.nonce.get_serialize_size(ser)
} else {
0usize
}
}
fn serialize(&self, io:&mut std::io::Write, ser:&serialize::SerializeParam) -> serialize::Result {
if BIP0031_VERSION < ser.version {
self.nonce.serialize(io, ser)
} e... | impl Serializable for PongMessage {
fn get_serialize_size(&self, ser:&serialize::SerializeParam) -> usize { | random_line_split |
benchmarks.rs | extern crate ostrov;
extern crate test;
use ostrov::runtime::Runtime;
use test::Bencher;
static NESTED_IFS: &'static str = "
(if
(if
(if
(if
(if
(if
(> 1 2 3 4 5 6 7 8 9 10)
(= ... | #f
)
(= 2 2 2 2 2 2 2 2 2 2)
#f
)
(= 2 2 2 2 2 2 2 2 2 2)
#f
)
(= 2 2 2 2 2 2 2 2 2 2)
#f
)
2
3
)
";
#[bench]
fn nested_eva... | #f
)
(= 2 2 2 2 2 2 2 2 2 2) | random_line_split |
benchmarks.rs | extern crate ostrov;
extern crate test;
use ostrov::runtime::Runtime;
use test::Bencher;
static NESTED_IFS: &'static str = "
(if
(if
(if
(if
(if
(if
(> 1 2 3 4 5 6 7 8 9 10)
(= ... | (b: &mut Bencher) {
let mut runtime = Runtime::new();
b.iter(|| {
assert_eq!(runtime.eval_str(NESTED_IFS), runtime.eval_str("3"));
})
}
#[bench]
fn nested_evaluation_bytecode(b: &mut Bencher) {
let mut runtime = Runtime::new();
b.iter(|| {
assert_eq!(runtime.eval_str(NESTED_IFS), ... | nested_evaluation | identifier_name |
benchmarks.rs | extern crate ostrov;
extern crate test;
use ostrov::runtime::Runtime;
use test::Bencher;
static NESTED_IFS: &'static str = "
(if
(if
(if
(if
(if
(if
(> 1 2 3 4 5 6 7 8 9 10)
(= ... |
#[bench]
fn nested_evaluation_bytecode(b: &mut Bencher) {
let mut runtime = Runtime::new();
b.iter(|| {
assert_eq!(runtime.eval_str(NESTED_IFS), runtime.eval_str("3"));
})
}
#[bench]
fn procedure_evaluation(b: &mut Bencher) {
let input = "
(define (fact n)
(if (= n 1)
... | {
let mut runtime = Runtime::new();
b.iter(|| {
assert_eq!(runtime.eval_str(NESTED_IFS), runtime.eval_str("3"));
})
} | identifier_body |
string_list.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 libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf16_alloc,cef_string_userfree_utf16_free,cef_s... |
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if lt.is_null() { return 0 as *mut cef_string_list_t; }
... | { return; } | conditional_block |
string_list.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 libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf16_alloc,cef_string_userfree_utf16_free,cef_s... | unsafe {
if lt.is_null() { return; }
let v = string_list_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len()!= 0 {
cs = (*v).pop();
cef_string_userfree_utf16_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_s... | random_line_split | |
string_list.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 libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf16_alloc,cef_string_userfree_utf16_free,cef_s... | (lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if lt.is_null() { return; }
let v = string_list_to_vec(lt);
let cs = cef_string_userfree_utf16_alloc();
cef_string_utf16_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no... | cef_string_list_append | identifier_name |
string_list.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 libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf16_alloc,cef_string_userfree_utf16_free,cef_s... |
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if lt.is_null() { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut ... | {
unsafe {
if lt.is_null() { return; }
let v = string_list_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len() != 0 {
cs = (*v).pop();
cef_string_userfree_utf16_free(cs.unwrap());
}
}
} | identifier_body |
deadlock.rs | // Zeming Lin
// For CS4414, probably generates a deadlock.
// Inspired by David Evans code from class 13 for CS4414, Fall '13
// This works on an AMD cpu running ubuntu LTS 12.04,
// but it fails on an Intel Atom netbook.
// Rust tasks also don't like to run concurrently on the same netbook
// so it probably isn't ... |
else { // Oops, another process grabbed the locks
grab_lock(id);
}
}
}
fn release_locks() {
unsafe {
lock1 = None;
lock2 = None
}
}
fn update_count(id: uint) {
unsafe {
grab_lock(id);
count += 1;
println(fmt!("Count updated by %?: %?", id, count));
release_locks();
}
}
fn main() {
... | {
lock2 = Some(id);
print(fmt!("Process %u grabbed lock2!\n", id));
while (lock1.is_some()) {
;
}
lock1 = Some(id);
print(fmt!("Process %u grabbed lock1!\n", id));
} | conditional_block |
deadlock.rs | // but it fails on an Intel Atom netbook.
// Rust tasks also don't like to run concurrently on the same netbook
// so it probably isn't the code's fault.
type Semaphore = Option<uint> ; // either None (available) or owner
static mut count: uint = 0; // protected by lock
static mut lock1: Semaphore = None;
static ... | // Zeming Lin
// For CS4414, probably generates a deadlock.
// Inspired by David Evans code from class 13 for CS4414, Fall '13
// This works on an AMD cpu running ubuntu LTS 12.04, | random_line_split | |
deadlock.rs | // Zeming Lin
// For CS4414, probably generates a deadlock.
// Inspired by David Evans code from class 13 for CS4414, Fall '13
// This works on an AMD cpu running ubuntu LTS 12.04,
// but it fails on an Intel Atom netbook.
// Rust tasks also don't like to run concurrently on the same netbook
// so it probably isn't ... |
fn main() {
for num in range(0u, 10) {
do spawn {
for _ in range(0u, 1000) {
update_count(num);
}
}
}
}
| {
unsafe {
grab_lock(id);
count += 1;
println(fmt!("Count updated by %?: %?", id, count));
release_locks();
}
} | identifier_body |
deadlock.rs | // Zeming Lin
// For CS4414, probably generates a deadlock.
// Inspired by David Evans code from class 13 for CS4414, Fall '13
// This works on an AMD cpu running ubuntu LTS 12.04,
// but it fails on an Intel Atom netbook.
// Rust tasks also don't like to run concurrently on the same netbook
// so it probably isn't ... | (id: uint) {
unsafe {
grab_lock(id);
count += 1;
println(fmt!("Count updated by %?: %?", id, count));
release_locks();
}
}
fn main() {
for num in range(0u, 10) {
do spawn {
for _ in range(0u, 1000) {
update_count(num);
}
}
}
}
| update_count | identifier_name |
env.rs | // except according to those terms.
use std::collections::hashmap::HashMap;
use expr::{Expr, ExprResult};
use result::SchemerResult;
pub type EnvResult = SchemerResult<Env>;
pub type EnvSetResult = SchemerResult<()>;
#[deriving(Clone)]
pub struct Env {
entries: HashMap<String, Expr>,
outer: Option<Box<Env>>
... | // Copyright 2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed | random_line_split | |
env.rs | // Copyright 2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::collections::hashmap::HashMap;
use expr::{Expr, ExprResult};
use result::SchemerRe... |
pub fn enclose(&mut self, base: Env) {
match self.outer {
Some(ref mut outer) => outer.enclose(base),
None => self.outer = Some(box base)
}
}
pub fn into_parent(self) -> Option<Env> {
self.outer.map(|x| *x)
}
}
| {
match self.entries.find(symbol) {
Some(v) => Ok(v.clone()),
None => {
match &self.outer {
&Some(ref outer_env) => outer_env.find(symbol),
&None => Err(format!("No variable named {} defined in the environment."
... | identifier_body |
env.rs | // Copyright 2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::collections::hashmap::HashMap;
use expr::{Expr, ExprResult};
use result::SchemerRe... | <'b>(&'b self, symbol: &String) -> ExprResult {
match self.entries.find(symbol) {
Some(v) => Ok(v.clone()),
None => {
match &self.outer {
&Some(ref outer_env) => outer_env.find(symbol),
&None => Err(format!("No variable named {} def... | find | identifier_name |
main.rs | extern crate osmpbfreader;
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use(bson, doc)] extern crate bson;
extern crate mongodb;
use std::collections::HashMap;
use std::env::args;
use mongodb::coll::options::WriteModel;
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
us... |
osmpbfreader::OsmObj::Way(w) => {
let mut path = Vec::new();
for node_id in &w.nodes {
match nodes.get(&node_id) {
Some(node) => path.push((node.0,node.1)),
None => { panic!(); }
}
... | {
nodes.insert( n.id, (n.lat(),n.lon()) );
} | conditional_block |
main.rs | extern crate osmpbfreader;
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use(bson, doc)] extern crate bson;
extern crate mongodb;
use std::collections::HashMap;
use std::env::args;
use mongodb::coll::options::WriteModel;
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
us... | if exception.message.len()>0 {
println!("ERROR(s): {}",exception.message);
}
}
None => ()
}
}
}
fn main() {
// Connect to MongoDB client and select collection
let client = Client::connect("localhost", 27017).ok().expect("F... | random_line_split | |
main.rs | extern crate osmpbfreader;
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use(bson, doc)] extern crate bson;
extern crate mongodb;
use std::collections::HashMap;
use std::env::args;
use mongodb::coll::options::WriteModel;
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
us... | () {
// Connect to MongoDB client and select collection
let client = Client::connect("localhost", 27017).ok().expect("Failed to initialize client.");
let rivers_coll = client.db("wwsupdb").collection("osm");
match rivers_coll.drop() {
Ok(_) => println!("Collection droped"),
Err(_) => pan... | main | identifier_name |
mod.rs | use anyhow::Result;
use pueue_lib::network::message::Message;
use pueue_lib::network::protocol::*;
use pueue_lib::state::State;
mod edit;
mod format_state;
mod local_follow;
mod restart;
mod wait;
pub use edit::edit;
pub use format_state::format_state;
pub use local_follow::local_follow;
pub use restart::restart;
pu... | {
// Create the message payload and send it to the daemon.
send_message(Message::Status, stream).await?;
// Check if we can receive the response from the daemon
let message = receive_message(stream).await?;
match message {
Message::StatusResponse(state) => Ok(*state),
_ => unreacha... | identifier_body | |
mod.rs | use pueue_lib::state::State;
mod edit;
mod format_state;
mod local_follow;
mod restart;
mod wait;
pub use edit::edit;
pub use format_state::format_state;
pub use local_follow::local_follow;
pub use restart::restart;
pub use wait::wait;
// This is a helper function for easy retrieval of the current daemon state.
// T... | use anyhow::Result;
use pueue_lib::network::message::Message;
use pueue_lib::network::protocol::*; | random_line_split | |
mod.rs | use anyhow::Result;
use pueue_lib::network::message::Message;
use pueue_lib::network::protocol::*;
use pueue_lib::state::State;
mod edit;
mod format_state;
mod local_follow;
mod restart;
mod wait;
pub use edit::edit;
pub use format_state::format_state;
pub use local_follow::local_follow;
pub use restart::restart;
pu... | (stream: &mut GenericStream) -> Result<State> {
// Create the message payload and send it to the daemon.
send_message(Message::Status, stream).await?;
// Check if we can receive the response from the daemon
let message = receive_message(stream).await?;
match message {
Message::StatusRespon... | get_state | identifier_name |
du.rs | #![crate_name = "du"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc, unicode)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed w... | my_stat.fstat.size += this_stat.fstat.size;
my_stat.fstat.unstable.blocks += this_stat.fstat.unstable.blocks;
if options.all {
stats.push(Arc::new(this_stat))
}
}
}
}
for future in futures.iter_mut() {
... | {
let mut stats = vec!();
let mut futures = vec!();
if my_stat.fstat.kind == FileType::Directory {
let read = match fs::readdir(path) {
Ok(read) => read,
Err(e) => {
safe_writeln!(&mut stderr(), "{}: cannot read directory ‘{}‘: {}",
... | identifier_body |
du.rs | #![crate_name = "du"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc, unicode)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed w... | let mut numbers = String::new();
let mut letters = String::new();
for c in s.as_slice().chars() {
if found_letter && c.is_digit(10) ||!found_number &&!c.is_digit(10) {
show_error!("invalid --block-size argument '{}'", s);
retu... | random_line_split | |
du.rs | #![crate_name = "du"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc, unicode)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed w... | }
}
}
}
for future in futures.iter_mut() {
for stat in future.get().into_iter().rev() {
if!options.separate_dirs && stat.path.dir_path() == my_stat.path {
my_stat.fstat.size += stat.fstat.size;
my_stat.fstat.unstable.block... | {
let read = match fs::readdir(path) {
Ok(read) => read,
Err(e) => {
safe_writeln!(&mut stderr(), "{}: cannot read directory ‘{}‘: {}",
options.program_name, path.display(), e);
return vec!(Arc::new(my_stat))
}
... | conditional_block |
du.rs | #![crate_name = "du"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc, unicode)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed w... | (path: &Path, mut my_stat: Stat,
options: Arc<Options>, depth: usize) -> Vec<Arc<Stat>> {
let mut stats = vec!();
let mut futures = vec!();
if my_stat.fstat.kind == FileType::Directory {
let read = match fs::readdir(path) {
Ok(read) => read,
Err(e) => {
... | du | identifier_name |
input.rs | use std::f64;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use glutin;
use glutin::{ElementState, EventsLoop, VirtualKeyCode};
use glutin::WindowEvent::*;
pub const INPUT_UP: usize = 0;
pub const INPUT_DOWN: usize = 1;
pub const INPUT_LEFT: usize = 2;
pub const INPUT_RIGHT: usize = 3;
enum MouseSt... |
fn get_binding(&self, key: &VirtualKeyCode) -> Option<usize> {
if let Some(action) = self.bindings.get(&key) {
Some(*action)
} else {
None
}
}
pub fn gather(&mut self, events_loop: &mut EventsLoop) -> bool {
self.delta_x = 0.0;
self.delta_y ... | {
self.bindings.insert(key, action);
} | identifier_body |
input.rs | use std::f64;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use glutin;
use glutin::{ElementState, EventsLoop, VirtualKeyCode};
use glutin::WindowEvent::*;
pub const INPUT_UP: usize = 0;
pub const INPUT_DOWN: usize = 1;
pub const INPUT_LEFT: usize = 2;
pub const INPUT_RIGHT: usize = 3;
enum MouseSt... | (&self, key: &VirtualKeyCode) -> Option<usize> {
if let Some(action) = self.bindings.get(&key) {
Some(*action)
} else {
None
}
}
pub fn gather(&mut self, events_loop: &mut EventsLoop) -> bool {
self.delta_x = 0.0;
self.delta_y = 0.0;
let m... | get_binding | identifier_name |
input.rs | use std::f64;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use glutin;
use glutin::{ElementState, EventsLoop, VirtualKeyCode};
use glutin::WindowEvent::*;
pub const INPUT_UP: usize = 0;
pub const INPUT_DOWN: usize = 1;
pub const INPUT_LEFT: usize = 2;
pub const INPUT_RIGHT: usize = 3;
enum MouseSt... | INPUT_RIGHT => &mut self.strafe_right,
_ => unimplemented!(),
}
}
} | fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut bool {
match index {
INPUT_UP => &mut self.move_forward,
INPUT_DOWN => &mut self.move_backward,
INPUT_LEFT => &mut self.strafe_left, | random_line_split |
input.rs | use std::f64;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use glutin;
use glutin::{ElementState, EventsLoop, VirtualKeyCode};
use glutin::WindowEvent::*;
pub const INPUT_UP: usize = 0;
pub const INPUT_DOWN: usize = 1;
pub const INPUT_LEFT: usize = 2;
pub const INPUT_RIGHT: usize = 3;
enum MouseSt... | ,
MouseMoved{ position: (x, y),.. } => self.set_mouse(x, y),
_ => {},
}
}
});
continue_game
}
}
impl Index<usize> for Input {
type Output = bool;
fn index<'a>(&'a self, index: usize) -> &'a bool {
match index {
... | {
self.mouse = MouseState::Released;
} | conditional_block |
checkboxes.rs | /*
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, ... |
},
PlusToggle => {
if self.widgets.plus_button.is_active() {
self.components.minus_button.emit(Uncheck);
}
else {
self.components.minus_button.emit(Check);
}
},
}
}
}
... | {
self.components.plus_button.emit(Check);
} | conditional_block |
checkboxes.rs | /*
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, ... | () {
let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let plus_button = &widgets.plus_button;
let minus_button = &widgets.minus_button;
assert!(!plus_button.is_active());
assert!(!minus_button.is_active());
click(plus_button);
... | check_uncheck | identifier_name |
checkboxes.rs | /*
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, ... | } |
click(minus_button);
assert!(!plus_button.is_active());
assert!(minus_button.is_active());
} | random_line_split |
checkboxes.rs | /*
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, ... | }
}
impl Widget for Win {
type Root = Window;
fn root(&self) -> Self::Root {
self.widgets.window.clone()
}
fn view(relm: &Relm<Self>, _model: Self::Model) -> Self {
let vbox = gtk::Box::new(Vertical, 0);
let plus_button = vbox.add_widget::<CheckButton>("+");
let ... | {
match event {
Quit => gtk::main_quit(),
MinusToggle => {
if self.widgets.minus_button.is_active() {
self.components.plus_button.emit(Uncheck);
}
else {
self.components.plus_button.emit(Check);
... | identifier_body |
cell.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... | (c: char, fg: Color, bg: Color) -> Cell {
Cell {
c: c.into(),
bg: bg,
fg: fg,
flags: Flags::empty(),
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.c =='' &&
self.bg == Color::Named(NamedColor::Background) &&
... | new | identifier_name |
cell.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... |
}
impl Cell {
pub fn bold(&self) -> bool {
self.flags.contains(BOLD)
}
pub fn new(c: char, fg: Color, bg: Color) -> Cell {
Cell {
c: c.into(),
bg: bg,
fg: fg,
flags: Flags::empty(),
}
}
#[inline]
pub fn is_empty(&self) -... | {
let mut length = Column(0);
if self[Column(self.len() - 1)].flags.contains(WRAPLINE) {
return Column(self.len());
}
for (index, cell) in self[..].iter().rev().enumerate() {
if cell.c != ' ' {
length = Column(self.len() - index);
... | identifier_body |
cell.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... |
}
length
}
}
impl Cell {
pub fn bold(&self) -> bool {
self.flags.contains(BOLD)
}
pub fn new(c: char, fg: Color, bg: Color) -> Cell {
Cell {
c: c.into(),
bg: bg,
fg: fg,
flags: Flags::empty(),
}
}
#[inli... | {
length = Column(self.len() - index);
break;
} | conditional_block |
cell.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... | Cell {
c: c.into(),
bg: bg,
fg: fg,
flags: Flags::empty(),
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.c =='' &&
self.bg == Color::Named(NamedColor::Background) &&
!self.flags.contains(INVERSE)
}
... | random_line_split | |
variance-regions-direct.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 ... | () {}
| main | identifier_name |
variance-regions-direct.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 ... | #[rustc_variance]
struct Test3<'a, 'b, 'c> { //~ ERROR regions=[[+, +, +];[];[];[]]
x: extern "Rust" fn(&'a int),
y: extern "Rust" fn(&'b [int]),
c: extern "Rust" fn(&'c str),
}
// Mutability induces invariance:
#[rustc_variance]
struct Test4<'a, 'b:'a> { //~ ERROR regions=[[-, o];[];[];[]]
x: &'a mut... | // Those same annotations in function arguments become covariant:
| random_line_split |
network_listener.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 bluetooth_traits::{BluetoothResponseListener, BluetoothResponseResult};
use net_traits::{Action, FetchResponse... |
impl<Listener: PreInvoke + Send +'static> NetworkListener<Listener> {
pub fn notify<A: Action<Listener> + Send +'static>(&self, action: A) {
let runnable = box ListenerRunnable {
context: self.context.clone(),
action: action,
};
let result = if let Some(ref wrapper) ... | } | random_line_split |
network_listener.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 bluetooth_traits::{BluetoothResponseListener, BluetoothResponseResult};
use net_traits::{Action, FetchResponse... | (&self) -> bool {
true
}
}
/// A runnable for moving the async network events between threads.
struct ListenerRunnable<A: Action<Listener> + Send +'static, Listener: PreInvoke + Send> {
context: Arc<Mutex<Listener>>,
action: A,
}
impl<A: Action<Listener> + Send +'static, Listener: PreInvoke + Send... | should_invoke | identifier_name |
network_listener.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 bluetooth_traits::{BluetoothResponseListener, BluetoothResponseResult};
use net_traits::{Action, FetchResponse... |
}
/// A gating mechanism that runs before invoking the runnable on the target thread.
/// If the `should_invoke` method returns false, the runnable is discarded without
/// being invoked.
pub trait PreInvoke {
fn should_invoke(&self) -> bool {
true
}
}
/// A runnable for moving the async network even... | {
self.notify(action);
} | identifier_body |
network_listener.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 bluetooth_traits::{BluetoothResponseListener, BluetoothResponseResult};
use net_traits::{Action, FetchResponse... | ;
if let Err(err) = result {
warn!("failed to deliver network data: {:?}", err);
}
}
}
// helps type inference
impl<Listener: FetchResponseListener + PreInvoke + Send +'static> NetworkListener<Listener> {
pub fn notify_fetch(&self, action: FetchResponseMsg) {
self.notify(act... | {
self.task_source.queue_wrapperless(runnable)
} | conditional_block |
tree_gravity.rs | //! Simple integration tests oriented towards gravity computations
extern crate acacia;
extern crate approx;
extern crate nalgebra;
extern crate quickcheck;
use acacia::partition::Ncube;
use acacia::{AssociatedData, DataQuery, Node, Positioned, Tree};
use approx::Relative;
use nalgebra::{distance, zero, Point2, Point... | })
.map(|&(com, m)| newton((m, com), test_point))
.fold(zero::<Vector3<f64>>(), |a, b| a + b);
// Now the tree gravity should approximate the exact one, within 10 %
TestResult::from_bool(
Relative::default()
.epsilon(0.1 * simple_gravity.norm... | let &(ref center_of_mass, _) = node.data();
let d = distance(&test_point, center_of_mass);
let delta = distance(&node.partition().center(), center_of_mass);
d < node.partition().width() / theta + delta | random_line_split |
tree_gravity.rs | //! Simple integration tests oriented towards gravity computations
extern crate acacia;
extern crate approx;
extern crate nalgebra;
extern crate quickcheck;
use acacia::partition::Ncube;
use acacia::{AssociatedData, DataQuery, Node, Positioned, Tree};
use approx::Relative;
use nalgebra::{distance, zero, Point2, Point... | return TestResult::discard();
}
}
}
// (T, T, T) -> Point3<T>
fn pnt<T: Debug + PartialEq + Copy +'static>(p: (T, T, T)) -> Point3<T> {
let (x, y, z) = p;
Point3::new(x, y, z)
}
let test_point = pnt(test_poin... | fn tree_gravity_approx(
starfield: Vec<(f64, (f64, f64, f64))>,
test_point: (f64, f64, f64),
) -> TestResult {
// We want to have at least one star
if starfield.is_empty() {
return TestResult::discard();
}
// Only test positive masses
if starfi... | identifier_body |
tree_gravity.rs | //! Simple integration tests oriented towards gravity computations
extern crate acacia;
extern crate approx;
extern crate nalgebra;
extern crate quickcheck;
use acacia::partition::Ncube;
use acacia::{AssociatedData, DataQuery, Node, Positioned, Tree};
use approx::Relative;
use nalgebra::{distance, zero, Point2, Point... | {
fn tree_gravity_approx(
starfield: Vec<(f64, (f64, f64, f64))>,
test_point: (f64, f64, f64),
) -> TestResult {
// We want to have at least one star
if starfield.is_empty() {
return TestResult::discard();
}
// Only test positive masses
if sta... | ee_gravity_approx() | identifier_name |
tree_gravity.rs | //! Simple integration tests oriented towards gravity computations
extern crate acacia;
extern crate approx;
extern crate nalgebra;
extern crate quickcheck;
use acacia::partition::Ncube;
use acacia::{AssociatedData, DataQuery, Node, Positioned, Tree};
use approx::Relative;
use nalgebra::{distance, zero, Point2, Point... | lse {
(orig, zero())
}
},
)
.expect("Couldn't construct tree");
let theta = 0.5; // A bit arbitrary but this appears to work
let tree_gravity = tree
.query_data(|node| {
let &(ref center_of_mass, _) = node.data();
... | (com1 + (com2 - com1) * (m2 / (m1 + m2)), m1 + m2)
} e | conditional_block |
derive_object.rs | use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn build_derive_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::R... | }
if!attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
ident.span()
});
}
if fields.is_empty() {
error.not_empty(ast_span);
}
// Early abort after GraphQL... |
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| field.name.as_str())
{
error.duplicate(duplicates.iter()); | random_line_split |
derive_object.rs | use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn build_derive_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::R... |
let field_name = &field.ident.unwrap();
let name = field_attrs
.name
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| {
attrs
.rename
.unwrap_or(RenameRule::... | {
return None;
} | conditional_block |
derive_object.rs | use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn | (ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ast_span = ast.span();
let struct_fields = match ast.data {
Data::Struct(data) => match data.fields {
Fields::Named(fields) => fields.named,
_ => return Err(error.custom_error(ast_span, "only named fie... | build_derive_object | identifier_name |
derive_object.rs | use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn build_derive_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::R... | let fields = struct_fields
.into_iter()
.filter_map(|field| {
let span = field.span();
let field_attrs = match util::FieldAttributes::from_attrs(
&field.attrs,
util::FieldAttributeParseMode::Object,
) {
Ok(attrs) => at... | {
let ast_span = ast.span();
let struct_fields = match ast.data {
Data::Struct(data) => match data.fields {
Fields::Named(fields) => fields.named,
_ => return Err(error.custom_error(ast_span, "only named fields are allowed")),
},
_ => return Err(error.custom_error... | identifier_body |
rscope.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 ... | _: Span,
count: uint)
-> Result<~[ty::Region], ()> {
let idx = *self.anon_bindings;
*self.anon_bindings += count;
Ok(vec::from_fn(count, |i| ty::ReLateBound(self.binder_id,
ty::BrAnon(i... | }
impl RegionScope for BindingRscope {
fn anon_regions(&self, | random_line_split |
rscope.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert!(defs.iter().all(|def| def.def_id.crate == ast::LOCAL_CRATE));
defs.iter().enumerate().map(
|(i, def)| ty::ReEarlyBound(def.def_id.node, i, def.ident)).collect()
} | identifier_body | |
rscope.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 ... | ;
impl RegionScope for ExplicitRscope {
fn anon_regions(&self,
_span: Span,
_count: uint)
-> Result<~[ty::Region], ()> {
Err(())
}
}
/// A scope in which we generate anonymous, late-bound regions for
/// omitted regions. This occurs in functi... | ExplicitRscope | identifier_name |
lib.rs | //! EPUB library
//! lib to read and navigate throught an epub file contents
//!
//! # Examples
//!
//! ## Opening
//!
//! ```
//! use epub::doc::EpubDoc;
//! let doc = EpubDoc::new("test.epub");
//! assert!(doc.is_ok());
//! let doc = doc.unwrap();
//!
//! ```
//!
//! ## Getting doc metatada
//!
//! Metadata is a Hash... | //! doc.go_next();
//! assert_eq!("001.xhtml", doc.get_current_id().unwrap());
//! doc.go_prev();
//! assert_eq!("000.xhtml", doc.get_current_id().unwrap());
//!
//! doc.set_current_page(2);
//! assert_eq!("001.xhtml", doc.get_current_id().unwrap());
//! assert_eq!(2, doc.get_current_page());
//! assert!(doc.set_curren... | //!
//! doc.go_next();
//! assert_eq!("000.xhtml", doc.get_current_id().unwrap()); | random_line_split |
replace_fallback.rs | use std::io;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ogg::{OggTrackBuf};
use super::super::{RequestType, Request};
use ::proto::{self, Deserialize, Serialize};
/// Skips to the end of the currently playing track
#[derive(Clone)]
pub struct ReplaceFallbackRequest {
pub track: OggTrackBuf,
... | let track = match track {
Some(track) => track,
None => return Err(io::Error::new(io::ErrorKind::Other, "missing field: track")),
};
let track = try!(OggTrackBuf::new(track)
.map_err(|_| io::Error::new(io::ErrorKind::Other, "invalid ogg")));
Ok(Replac... | {
try!(proto::expect_type(buf, proto::TYPE_STRUCT));
let field_count = try!(buf.read_u32::<BigEndian>());
let mut track: Option<Vec<u8>> = None;
let mut metadata: Option<Vec<(String, String)>> = None;
for _ in 0..field_count {
let field_name: String = try!(Deseriali... | identifier_body |
replace_fallback.rs | use std::io;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ogg::{OggTrackBuf};
use super::super::{RequestType, Request};
use ::proto::{self, Deserialize, Serialize};
/// Skips to the end of the currently playing track
#[derive(Clone)]
pub struct ReplaceFallbackRequest {
pub track: OggTrackBuf,
... | type Value = ();
type Error = ReplaceFallbackError;
fn req_type(&self) -> RequestType {
RequestType::ReplaceFallback
}
}
pub type ReplaceFallbackResult = Result<(), ReplaceFallbackError>;
#[derive(Debug, Clone)]
pub enum ReplaceFallbackError {
InvalidTrack = 1,
BadSampleRate = 2,
... | }
}
impl Request for ReplaceFallbackRequest { | random_line_split |
replace_fallback.rs | use std::io;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ogg::{OggTrackBuf};
use super::super::{RequestType, Request};
use ::proto::{self, Deserialize, Serialize};
/// Skips to the end of the currently playing track
#[derive(Clone)]
pub struct ReplaceFallbackRequest {
pub track: OggTrackBuf,
... | (&self, buf: &mut io::Cursor<Vec<u8>>) -> io::Result<()> {
try!(buf.write_u16::<BigEndian>(proto::TYPE_STRUCT));
let length = if self.metadata.is_some() { 2 } else { 1 };
try!(buf.write_u32::<BigEndian>(length));
try!(Serialize::write("track", buf));
try!(Serialize::write(self.... | write | identifier_name |
angle.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 https://mozilla.org/MPL/2.0/. */
//! Computed angles.
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::... | #[inline]
pub fn radians(&self) -> CSSFloat {
self.radians64().min(f32::MAX as f64).max(f32::MIN as f64) as f32
}
/// Returns the amount of radians this angle represents as a `f64`.
///
/// Gecko stores angles as singles, but does this computation using doubles.
///
/// This is ... | }
/// Returns the amount of radians this angle represents. | random_line_split |
angle.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 https://mozilla.org/MPL/2.0/. */
//! Computed angles.
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::... | (&self, other: &Self) -> Result<SquaredDistance, ()> {
// Use the formula for calculating the distance between angles defined in SVG:
// https://www.w3.org/TR/SVG/animate.html#complexDistances
self.radians64()
.compute_squared_distance(&other.radians64())
}
}
| compute_squared_distance | identifier_name |
angle.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 https://mozilla.org/MPL/2.0/. */
//! Computed angles.
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::... |
}
const RAD_PER_DEG: f64 = PI / 180.0;
impl Angle {
/// Creates a computed `Angle` value from a radian amount.
pub fn from_radians(radians: CSSFloat) -> Self {
Angle(radians / RAD_PER_DEG as f32)
}
/// Creates a computed `Angle` value from a degrees amount.
#[inline]
pub fn from_degr... | {
self.degrees().to_css(dest)?;
dest.write_str("deg")
} | identifier_body |
multilevel-path-1.rs | // edition:2021
#![feature(rustc_attrs)]
#![allow(unused)]
struct Point {
x: i32,
y: i32,
}
struct Wrapper {
p: Point,
}
fn main() {
let mut w = Wrapper { p: Point { x: 10, y: 10 } };
// Only paths that appears within the closure that directly start off
// a variable defined outside the clos... |
*py = 20
} | random_line_split | |
multilevel-path-1.rs | // edition:2021
#![feature(rustc_attrs)]
#![allow(unused)]
struct Point {
x: i32,
y: i32,
}
struct Wrapper {
p: Point,
}
fn | () {
let mut w = Wrapper { p: Point { x: 10, y: 10 } };
// Only paths that appears within the closure that directly start off
// a variable defined outside the closure are captured.
//
// Therefore `w.p` is captured
// Note that `wp.x` doesn't start off a variable defined outside the closure.
... | main | identifier_name |
set2.rs | extern crate openssl;
extern crate serialize;
use serialize::base64::{FromBase64};
use std::rand::{task_rng, Rng};
use std::io::BufferedReader;
use std::io::File;
use openssl::crypto::symm::{encrypt, decrypt, AES_128_ECB, AES_128_CBC};
fn xor(v1 : &[u8], v2 : &[u8]) -> Vec<u8> {
v1.iter().zip(v2.iter()).map(|(&b... |
fn ch9() {
println!("------- 9 ---------");
let mut data = Vec::from_slice("YELLOW SUBMARINE".as_bytes());
pkcs7_pad(&mut data, 20);
println!("Padded data: {}", data);
println!("Padded message: {}", bytes_to_string(data.clone()));
assert!("YELLOW SUBMARINE\x04\x04\x04\x04".as_bytes() == data.a... | {
let key = gen_key();
let iv = gen_key();
let prepend_bytes = gen_random_size_vec(5, 10);
let append_bytes = gen_random_size_vec(5, 10);
let data = prepend_bytes + input + append_bytes;
let choices = [AES_128_ECB, AES_128_CBC];
let t = task_rng().choose(choices).unwrap();
println!("Used... | identifier_body |
set2.rs | extern crate openssl;
extern crate serialize;
use serialize::base64::{FromBase64};
use std::rand::{task_rng, Rng};
use std::io::BufferedReader;
use std::io::File;
use openssl::crypto::symm::{encrypt, decrypt, AES_128_ECB, AES_128_CBC};
fn xor(v1 : &[u8], v2 : &[u8]) -> Vec<u8> {
v1.iter().zip(v2.iter()).map(|(&b... | fn ch9() {
println!("------- 9 ---------");
let mut data = Vec::from_slice("YELLOW SUBMARINE".as_bytes());
pkcs7_pad(&mut data, 20);
println!("Padded data: {}", data);
println!("Padded message: {}", bytes_to_string(data.clone()));
assert!("YELLOW SUBMARINE\x04\x04\x04\x04".as_bytes() == data.as_... | println!("Used {}", (match *t { AES_128_ECB => "ECB", AES_128_CBC => "CBC", _ => "Unknown" }));
encrypt(*t, key.as_slice(), iv, data.as_slice())
}
| random_line_split |
set2.rs | extern crate openssl;
extern crate serialize;
use serialize::base64::{FromBase64};
use std::rand::{task_rng, Rng};
use std::io::BufferedReader;
use std::io::File;
use openssl::crypto::symm::{encrypt, decrypt, AES_128_ECB, AES_128_CBC};
fn xor(v1 : &[u8], v2 : &[u8]) -> Vec<u8> {
v1.iter().zip(v2.iter()).map(|(&b... | () {
println!("------- 9 ---------");
let mut data = Vec::from_slice("YELLOW SUBMARINE".as_bytes());
pkcs7_pad(&mut data, 20);
println!("Padded data: {}", data);
println!("Padded message: {}", bytes_to_string(data.clone()));
assert!("YELLOW SUBMARINE\x04\x04\x04\x04".as_bytes() == data.as_slice(... | ch9 | identifier_name |
lexical-scope-with-macro.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... | () {
let a = trivial!(10);
let b = no_new_scope!(33);
zzz();
sentinel();
new_scope!();
zzz();
sentinel();
shadow_within_macro!(100);
zzz();
sentinel();
let c = dup_expr!(10 * 20);
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()}
| main | identifier_name |
lexical-scope-with-macro.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... |
fn sentinel() {()}
| {()} | identifier_body |
lexical-scope-with-macro.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... | zzz();
sentinel();
new_scope!();
zzz();
sentinel();
shadow_within_macro!(100);
zzz();
sentinel();
let c = dup_expr!(10 * 20);
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()} | random_line_split | |
std_dirs.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | create_dir(
client,
access_container,
btree_map![
authenticator_key => MDataSeqValue { version: 0, data: access_cont_value }
],
btree_map![],
)
.map_err(From::from)
.into_box()
}
/// Generates a list of `MDataInfo` for standard dirs.
/// Returns a colle... | None,
));
| random_line_split |
std_dirs.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | .into_iter()
.map(|(name, md_info)| (String::from(name), md_info))
.collect();
let std_dirs_fut = create_std_dirs(&c3, &access_cont_value);
let access_cont_fut =
create_access_container(&... | {
let c2 = client.clone();
let c3 = client.clone();
let c4 = client.clone();
// Initialise standard directories
let access_container = client.access_container();
let config_dir = client.config_root_dir();
// Try to get default dirs from the access container
let access_cont_fut = access... | identifier_body |
std_dirs.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | (client: &AuthClient) -> Box<AuthFuture<()>> {
let c2 = client.clone();
let c3 = client.clone();
let c4 = client.clone();
// Initialise standard directories
let access_container = client.access_container();
let config_dir = client.config_root_dir();
// Try to get default dirs from the acce... | create | identifier_name |
shared_cache.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | use bit_set::BitSet;
use super::super::instructions;
const INITIAL_CAPACITY: usize = 32;
const DEFAULT_CACHE_SIZE: usize = 4 * 1024 * 1024;
/// Global cache for EVM interpreter
pub struct SharedCache {
jump_destinations: Mutex<LruCache<H256, Arc<BitSet>>>,
max_size: usize,
cur_size: Mutex<usize>,
}
impl SharedCac... | random_line_split | |
shared_cache.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (max_size: usize) -> Self {
SharedCache {
jump_destinations: Mutex::new(LruCache::new(INITIAL_CAPACITY)),
max_size: max_size * 8, // dealing with bits here.
cur_size: Mutex::new(0),
}
}
/// Get jump destinations bitmap for a contract.
pub fn jump_destinations(&self, code_hash: &H256, code: &[u8]) -> Ar... | new | identifier_name |
shared_cache.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
/// Get jump destinations bitmap for a contract.
pub fn jump_destinations(&self, code_hash: &H256, code: &[u8]) -> Arc<BitSet> {
if code_hash == &SHA3_EMPTY {
return Self::find_jump_destinations(code);
}
if let Some(d) = self.jump_destinations.lock().get_mut(code_hash) {
return d.clone();
}
let d ... | {
SharedCache {
jump_destinations: Mutex::new(LruCache::new(INITIAL_CAPACITY)),
max_size: max_size * 8, // dealing with bits here.
cur_size: Mutex::new(0),
}
} | identifier_body |
shared_cache.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
if let Some(d) = self.jump_destinations.lock().get_mut(code_hash) {
return d.clone();
}
let d = Self::find_jump_destinations(code);
{
let mut cur_size = self.cur_size.lock();
*cur_size += d.capacity();
let mut jump_dests = self.jump_destinations.lock();
let cap = jump_dests.capacity();
/... | {
return Self::find_jump_destinations(code);
} | conditional_block |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use dependency_analyzer::{get_reachable_ast, ReachableAst};
use fixture_tests::Fixture; | pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> {
let parts: Vec<&str> = fixture.content.split("%definitions%").collect();
let source_location = SourceLocationKey::standalone(fixture.file_name);
let definitions = parse_executable(parts[0], source_location).unwrap();
let base_d... | use graphql_syntax::*;
| random_line_split |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use dependency_analyzer::{get_reachable_ast, ReachableAst};
use fixture_tests::Fixture;
use graphq... | (fixture: &Fixture<'_>) -> Result<String, String> {
let parts: Vec<&str> = fixture.content.split("%definitions%").collect();
let source_location = SourceLocationKey::standalone(fixture.file_name);
let definitions = parse_executable(parts[0], source_location).unwrap();
let base_definitions = parts
... | transform_fixture | identifier_name |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use dependency_analyzer::{get_reachable_ast, ReachableAst};
use fixture_tests::Fixture;
use graphq... | texts.push("========== Base definitions ==========".to_string());
let mut defs = base_fragment_names
.iter()
.map(|key| key.lookup())
.collect::<Vec<_>>();
defs.sort_unstable();
texts.push(defs.join(", "));
Ok(texts.join("\n"))
}
| {
let parts: Vec<&str> = fixture.content.split("%definitions%").collect();
let source_location = SourceLocationKey::standalone(fixture.file_name);
let definitions = parse_executable(parts[0], source_location).unwrap();
let base_definitions = parts
.iter()
.skip(1)
.flat_map(|par... | identifier_body |
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 https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of st... | (&self) -> bool {
<Self as num_traits::Zero>::is_zero(self)
}
}
| is_zero | 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 https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of st... | /// Returns whether this value is zero.
fn is_zero(&self) -> bool;
}
impl<T> Zero for T
where
T: num_traits::Zero,
{
fn zero() -> Self {
<Self as num_traits::Zero>::zero()
}
fn is_zero(&self) -> bool {
<Self as num_traits::Zero>::is_zero(self)
}
} | /// implementing `Add`.
pub trait Zero {
/// Returns the zero value.
fn zero() -> Self;
| random_line_split |
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 https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of st... |
}
/// A trait pretty much similar to num_traits::Zero, but without the need of
/// implementing `Add`.
pub trait Zero {
/// Returns the zero value.
fn zero() -> Self;
/// Returns whether this value is zero.
fn is_zero(&self) -> bool;
}
impl<T> Zero for T
where
T: num_traits::Zero,
{
fn zero(... | {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
} | identifier_body |
gated-quote.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let ecx = &ParseSess;
let x = quote_tokens!(ecx, 3); //~ ERROR macro undefined: 'quote_tokens!'
let x = quote_expr!(ecx, 3); //~ ERROR macro undefined: 'quote_expr!'
let x = quote_ty!(ecx, 3); //~ ERROR macro undefined: 'quote_ty!'
let x = quote_method!(ecx, 3); //~ ERROR macro undef... | identifier_body | |
gated-quote.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a>(&'a self) -> &'a parse::ParseSess { loop { } }
fn call_site(&self) -> Span { loop { } }
fn ident_of(&self, st: &str) -> ast::Ident { loop { } }
fn name_of(&self, st: &str) -> ast::Name { loop { } }
}
pub fn main() {
let ecx = &ParseSess;
let x = quote_tokens!(ecx, 3); //~ ERROR macro undefin... | parse_sess | identifier_name |
gated-quote.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use syntax::ast;
use syntax::codemap::Span;
use syntax::parse;
struct ParseSess;
impl ParseSess {
fn cfg(&self) -> ast::CrateConfig { loop { } }
fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { loop { } }
fn call_site(&self) -> Span { loop { } }
fn ident_of(&self, st: &str) -> ast::Ident { loop ... | #![allow(dead_code, unused_imports, unused_variables)]
#[macro_use]
extern crate syntax; | random_line_split |
lib.rs | // Copyright 2017 James Duley
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | without_name
}
fn extract_tied_operands(
pos_and_tts: (usize, Vec<TokenTree>),
) -> (Vec<TokenTree>, Option<Vec<TokenTree>>) {
{
let constraint = get_string_literal(pos_and_tts.1.first().expect("error: empty operand"));
if constraint.starts_with("+") {
let lvalue = pos_and_tts.... | {
let name_and_remaining = match *tts.first().expect("error: empty operand") {
TokenTree::Delimited(ref d) => {
assert!(d.delim == DelimToken::Bracket, "error: bad operand");
let name = if d.tts.len() == 1usize {
match d.tts[0] {
TokenTree::Token(T... | identifier_body |
lib.rs | // Copyright 2017 James Duley
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | use syn::{parse_token_trees, Token, TokenTree, Lit, DelimToken, StrStyle};
#[proc_macro]
pub fn gcc_asm(token_stream: TokenStream) -> TokenStream {
let tokens = token_stream.to_string();
let token_trees = parse_token_trees(&tokens).unwrap();
let mut parts = split_on_token(token_trees.as_slice(), &Token::Co... | #[macro_use]
extern crate quote;
use proc_macro::TokenStream;
use std::str::FromStr; | random_line_split |
lib.rs | // Copyright 2017 James Duley
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | (token_stream: TokenStream) -> TokenStream {
let tokens = token_stream.to_string();
let token_trees = parse_token_trees(&tokens).unwrap();
let mut parts = split_on_token(token_trees.as_slice(), &Token::Colon);
let template = parts
.next()
.expect("error: template missing")
.iter()
... | gcc_asm | identifier_name |
scan.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Scan;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item... |
None => { assert!(false); }
}
}
assert_eq!(scan.next(), None::<B>);
}
}
| { assert_eq!(v, n * (n + 1) / 2); } | conditional_block |
scan.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Scan;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item... | (&mut self, (st, item): Args) -> Self::Output {
*st += item;
Some::<B>(*st)
}
}
#[test]
fn scan_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let st: St = 0;
let f: F = F;
let mut scan: Scan<A<T>, B, F> = a.scan::<St, B, F>(st, f);
for n in 0..10 {
let x: Option<B> = scan.next();
... | call_mut | identifier_name |
scan.rs | #![feature(core, unboxed_closures)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Scan;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item... | Some::<B>(*st)
}
}
#[test]
fn scan_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let st: St = 0;
let f: F = F;
let mut scan: Scan<A<T>, B, F> = a.scan::<St, B, F>(st, f);
for n in 0..10 {
let x: Option<B> = scan.next();
match x {
Some(v) => { assert_eq!(v, n * (n + 1) / 2); }
... | random_line_split | |
acquire_pessimistic_lock.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::kvrpcpb::{ExtraOp, LockInfo};
use txn_types::{Key, OldValues, TimeStamp, TxnExtra};
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::{LockManager, WaitTimeout};
use crate::storage::mvcc::{
Error as MvccError, Error... |
}
context.statistics.add(&reader.take_statistics());
// no conflict
let (pr, to_be_write, rows, ctx, lock_info) = if res.is_ok() {
let pr = ProcessResult::PessimisticLockRes { res };
let extra = TxnExtra {
old_values: self.old_values,
... | {
txn.concurrency_manager.update_max_ts(self.for_update_ts);
} | conditional_block |
acquire_pessimistic_lock.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::kvrpcpb::{ExtraOp, LockInfo};
use txn_types::{Key, OldValues, TimeStamp, TxnExtra};
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::{LockManager, WaitTimeout};
use crate::storage::mvcc::{
Error as MvccError, Error... |
fn write_bytes(&self) -> usize {
self.keys
.iter()
.map(|(key, _)| key.as_encoded().len())
.sum()
}
gen_lock!(keys: multiple(|x| &x.0));
}
fn extract_lock_info_from_result<T>(res: &StorageResult<T>) -> &LockInfo {
match res {
Err(StorageError(box Stora... | command_method!(can_be_pipelined, bool, true); | random_line_split |
acquire_pessimistic_lock.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::kvrpcpb::{ExtraOp, LockInfo};
use txn_types::{Key, OldValues, TimeStamp, TxnExtra};
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::{LockManager, WaitTimeout};
use crate::storage::mvcc::{
Error as MvccError, Error... | (&self) -> usize {
self.keys
.iter()
.map(|(key, _)| key.as_encoded().len())
.sum()
}
gen_lock!(keys: multiple(|x| &x.0));
}
fn extract_lock_info_from_result<T>(res: &StorageResult<T>) -> &LockInfo {
match res {
Err(StorageError(box StorageErrorInner::Txn(E... | write_bytes | identifier_name |
acquire_pessimistic_lock.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::kvrpcpb::{ExtraOp, LockInfo};
use txn_types::{Key, OldValues, TimeStamp, TxnExtra};
use crate::storage::kv::WriteData;
use crate::storage::lock_manager::{LockManager, WaitTimeout};
use crate::storage::mvcc::{
Error as MvccError, Error... |
gen_lock!(keys: multiple(|x| &x.0));
}
fn extract_lock_info_from_result<T>(res: &StorageResult<T>) -> &LockInfo {
match res {
Err(StorageError(box StorageErrorInner::Txn(Error(box ErrorInner::Mvcc(MvccError(
box MvccErrorInner::KeyIsLocked(info),
)))))) => info,
_ => panic... | {
self.keys
.iter()
.map(|(key, _)| key.as_encoded().len())
.sum()
} | identifier_body |
lib.rs | //! pokereval-rs currently contains a single way of evaluating poker hands (5,6 or 7 cards)
//! to a HandRank, which is a number from 0 to 7461 inclusive, the higher the better the hand.
//! Inside the modules, there are more efficient methods that don't need to convert cards
//! to internal representations first.
ext... | (cards: &[&Card; 6]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let c6 = card_to_deck_number(cards[5]);
let converted_ca... | eval_6cards | identifier_name |
lib.rs | //! pokereval-rs currently contains a single way of evaluating poker hands (5,6 or 7 cards)
//! to a HandRank, which is a number from 0 to 7461 inclusive, the higher the better the hand.
//! Inside the modules, there are more efficient methods that don't need to convert cards
//! to internal representations first.
ext... | pub mod original;
//mod perfect;
pub mod utils;
use cards::card::{Card};
use holdem::{HandRank};
use utils::{card_to_deck_number};
/// Evalate a hand consisting of 5 cards. The cards are grouped in an array.
/// This is quite inefficient, due to the arrays that need to be created. But convenient.
pub fn eval_5cards(c... | random_line_split | |
lib.rs | //! pokereval-rs currently contains a single way of evaluating poker hands (5,6 or 7 cards)
//! to a HandRank, which is a number from 0 to 7461 inclusive, the higher the better the hand.
//! Inside the modules, there are more efficient methods that don't need to convert cards
//! to internal representations first.
ext... |
/// Evalate a hand consisting of 7 cards. The cards are grouped in an array.
/// This is quite inefficient, due to the arrays that need to be created. But convenient.
pub fn eval_7cards(cards: &[&Card; 7]) -> HandRank {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3... | {
let c1 = card_to_deck_number(cards[0]);
let c2 = card_to_deck_number(cards[1]);
let c3 = card_to_deck_number(cards[2]);
let c4 = card_to_deck_number(cards[3]);
let c5 = card_to_deck_number(cards[4]);
let c6 = card_to_deck_number(cards[5]);
let converted_cards = [&c1, &c2, &c3, &c4, &c5, &... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.