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 |
|---|---|---|---|---|
main.rs | use rand::{thread_rng, seq::SliceRandom};
use mcc4::*;
fn | () {
env_logger::init();
let game = ConnectFour::<BitState>::new(7, 6).unwrap();
let human_player = HumanPlayer::new();
let ai_player = TreeSearchPlayer::new(&game);
let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_player), Box::new(ai_player)];
players.shuffle(&mut thread_rn... | main | identifier_name |
main.rs | use rand::{thread_rng, seq::SliceRandom};
use mcc4::*;
fn main() | }
| {
env_logger::init();
let game = ConnectFour::<BitState>::new(7, 6).unwrap();
let human_player = HumanPlayer::new();
let ai_player = TreeSearchPlayer::new(&game);
let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_player), Box::new(ai_player)];
players.shuffle(&mut thread_rng()... | identifier_body |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... |
/// True if we should show borders on all layers and tiles for
/// debugging purposes (`--show-debug-borders`).
pub show_debug_borders: bool,
/// True if we should show borders on all fragments for debugging purposes
/// (`--show-debug-fragment-borders`).
pub show_debug_fragment_borders: bool,... | /// browser engines.
pub bubble_inline_sizes_separately: bool, | random_line_split |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... |
pub fn experimental_enabled() -> bool {
EXPERIMENTAL_ENABLED.load(Ordering::SeqCst)
}
// Make Opts available globally. This saves having to clone and pass
// opts everywhere it is used, which gets particularly cumbersome
// when passing through the DOM structures.
static mut OPTIONS: *mut Opts = 0 as *mut Opts;
... | {
EXPERIMENTAL_ENABLED.store(new_value, Ordering::SeqCst);
} | identifier_body |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | <'a>() -> &'a Opts {
unsafe {
// If code attempts to retrieve the options and they haven't
// been set by the platform init code, just return a default
// set of options. This is mostly useful for unit tests that
// run through a code path which queries the cmd line options.
... | get | identifier_name |
server.rs | //! Shadowsocks Local Tunnel Server
use std::{io, sync::Arc, time::Duration};
use futures::{future, FutureExt};
use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr};
use crate::local::{context::ServiceContext, loadbalancing::PingBalancer};
use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel};
... | impl Tunnel {
/// Create a new Tunnel server forwarding to `forward_addr`
pub fn new(forward_addr: Address) -> Tunnel {
let context = ServiceContext::new();
Tunnel::with_context(Arc::new(context), forward_addr)
}
/// Create a new Tunnel server with context
pub fn with_context(contex... | mode: Mode,
udp_expiry_duration: Option<Duration>,
udp_capacity: Option<usize>,
}
| random_line_split |
server.rs | //! Shadowsocks Local Tunnel Server
use std::{io, sync::Arc, time::Duration};
use futures::{future, FutureExt};
use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr};
use crate::local::{context::ServiceContext, loadbalancing::PingBalancer};
use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel};
... | (forward_addr: Address) -> Tunnel {
let context = ServiceContext::new();
Tunnel::with_context(Arc::new(context), forward_addr)
}
/// Create a new Tunnel server with context
pub fn with_context(context: Arc<ServiceContext>, forward_addr: Address) -> Tunnel {
Tunnel {
cont... | new | identifier_name |
server.rs | //! Shadowsocks Local Tunnel Server
use std::{io, sync::Arc, time::Duration};
use futures::{future, FutureExt};
use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr};
use crate::local::{context::ServiceContext, loadbalancing::PingBalancer};
use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel};
... |
if self.mode.enable_udp() {
vfut.push(self.run_udp_tunnel(udp_addr, balancer).boxed());
}
let (res,..) = future::select_all(vfut).await;
res
}
async fn run_tcp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> {
run_tcp_tu... | {
vfut.push(self.run_tcp_tunnel(tcp_addr, balancer.clone()).boxed());
} | conditional_block |
server.rs | //! Shadowsocks Local Tunnel Server
use std::{io, sync::Arc, time::Duration};
use futures::{future, FutureExt};
use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr};
use crate::local::{context::ServiceContext, loadbalancing::PingBalancer};
use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel};
... |
/// Set server mode
pub fn set_mode(&mut self, mode: Mode) {
self.mode = mode;
}
/// Start serving
pub async fn run(self, tcp_addr: &ServerAddr, udp_addr: &ServerAddr, balancer: PingBalancer) -> io::Result<()> {
let mut vfut = Vec::new();
if self.mode.enable_tcp() {
... | {
self.udp_capacity = Some(c);
} | identifier_body |
design_pattern-chain_of_command.rs | #![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/m... |
}
struct UserCommand;
impl UserCommand {
fn new() -> UserCommand {
UserCommand
}
}
impl Command for UserCommand {
fn on_command(&self, name: &str, args: &[&str]) {
if name == "addUser" {
println!("UserCommand handling '{}' with args {:?}.", name, args);
}
}
}
struct MailCommand;
impl MailCommand {
fn n... | {
for command in self.commands.iter() {
command.on_command(name, args);
}
} | identifier_body |
design_pattern-chain_of_command.rs | #![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/m... | () -> CommandChain<'a> {
CommandChain{commands: Vec::new()}
}
fn add_command(&mut self, command: Box<dyn Command + 'a>) {
self.commands.push(command);
}
fn run_command(&self, name: &str, args: &[&str]) {
for command in self.commands.iter() {
command.on_command(name, args);
}
}
}
struct UserCommand;
imp... | new | identifier_name |
design_pattern-chain_of_command.rs | #![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/m... | else if name == "mail" {
println!("MailCommand handling '{}' with args {:?}.", name, args);
}
}
}
fn main() {
let mut cc = CommandChain::new();
cc.add_command(Box::new(UserCommand::new()));
cc.add_command(Box::new(MailCommand::new()));
cc.run_command("addUser", &["Toto", "users"]);
cc.run_command("mail", &[... | {
println!("MailCommand handling '{}' with args {:?}.", name, args);
} | conditional_block |
design_pattern-chain_of_command.rs | #![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/m... | }
}
struct MailCommand;
impl MailCommand {
fn new() -> MailCommand {
MailCommand
}
}
impl Command for MailCommand {
fn on_command(&self, name: &str, args: &[&str]) {
if name == "addUser" {
println!("MailCommand handling '{}' with args {:?}.", name, args);
} else if name == "mail" {
println!("MailComman... | random_line_split | |
mode.rs | //! TODO Documentation
| use crate::output::Output;
#[derive(Debug, Eq, PartialEq)]
pub struct Mode<'output> {
output_mode: *mut wlr_output_mode,
phantom: PhantomData<&'output Output>
}
impl<'output> Mode<'output> {
/// NOTE This is a lifetime defined by the user of this function, but it
/// must not outlive the `Output` that... | use std::marker::PhantomData;
use wlroots_sys::wlr_output_mode;
| random_line_split |
mode.rs | //! TODO Documentation
use std::marker::PhantomData;
use wlroots_sys::wlr_output_mode;
use crate::output::Output;
#[derive(Debug, Eq, PartialEq)]
pub struct Mode<'output> {
output_mode: *mut wlr_output_mode,
phantom: PhantomData<&'output Output>
}
impl<'output> Mode<'output> {
/// NOTE This is a lifeti... | (&self) -> i32 {
unsafe { (*self.output_mode).refresh }
}
}
| refresh | identifier_name |
x86_64_rumprun_netbsd.rs | // Copyright 2014-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-MI... | () -> TargetResult {
let mut base = super::netbsd_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.linker = Some("x86_64-rumprun-netbsd-gcc".to_string());
base.max_atomic_width = Some(64);
base.dynamic_linking ... | target | identifier_name |
x86_64_rumprun_netbsd.rs | // Copyright 2014-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-MI... | })
} | random_line_split | |
x86_64_rumprun_netbsd.rs | // Copyright 2014-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-MI... | target_os: "netbsd".to_string(),
target_env: String::new(),
target_vendor: "rumprun".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
}
| {
let mut base = super::netbsd_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.linker = Some("x86_64-rumprun-netbsd-gcc".to_string());
base.max_atomic_width = Some(64);
base.dynamic_linking = false;
base.h... | identifier_body |
path.rs | use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoResult, internal, internal_error, human, Ch... | (path: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
trace!("new; id={}", id);
PathSource {
id: id.clone(),
path: path.to_path_buf(),
updated: false,
packages: Vec::new(),
config: config,
}
}
... | new | identifier_name |
path.rs | use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoResult, internal, internal_error, human, Ch... |
fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> {
trace!("getting packages; ids={:?}", ids);
Ok(self.packages.iter()
.filter(|pkg| ids.iter().any(|id| pkg.package_id() == id))
.map(|pkg| pkg.clone())
.collect())
}
fn fingerprint(&self, pkg: &Pa... | {
// TODO: assert! that the PackageId is contained by the source
Ok(())
} | identifier_body |
path.rs | use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoResult, internal, internal_error, human, Ch... | //.gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|e... | random_line_split | |
privacy2.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | //~^ ERROR: there is no
//~^^ ERROR: failed to resolve
}
#[start] fn main(_: int, _: **u8) -> int { 3 } | random_line_split | |
privacy2.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { 3 } | identifier_body | |
privacy2.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (_: int, _: **u8) -> int { 3 }
| main | identifier_name |
visibility.rs | // A module named `my`
mod my {
// Items in modules default to private visibility.
fn private_function() {
println!("called `my::private_function()`");
}
// Use the `pub` modifier to override default visibility.
pub fn function() {
println!("called `my::function()`");
}
... | // Modules allow disambiguation between items that have the same name.
function();
my::function();
// Public items, including those inside nested modules, can be
// accessed from outside the parent module.
my::indirect_access();
my::nested::function();
// Private items of a module ... | fn main() { | random_line_split |
visibility.rs | // A module named `my`
mod my {
// Items in modules default to private visibility.
fn private_function() {
println!("called `my::private_function()`");
}
// Use the `pub` modifier to override default visibility.
pub fn function() {
println!("called `my::function()`");
}
... |
// Error! `private_nested` is a private module
//my::private_nested::function();
// TODO ^ Try uncommenting this line
} | {
// Modules allow disambiguation between items that have the same name.
function();
my::function();
// Public items, including those inside nested modules, can be
// accessed from outside the parent module.
my::indirect_access();
my::nested::function();
// Private items of a modul... | identifier_body |
visibility.rs | // A module named `my`
mod my {
// Items in modules default to private visibility.
fn | () {
println!("called `my::private_function()`");
}
// Use the `pub` modifier to override default visibility.
pub fn function() {
println!("called `my::function()`");
}
// Items can access other items in the same module,
// even when private.
pub fn indirect_access(... | private_function | identifier_name |
if-check.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (x: uint) -> bool {
if x < 2u {
return false;
} else if x == 2u { return true; } else { return even(x - 2u); }
}
fn foo(x: uint) {
if even(x) {
println!("{}", x);
} else {
panic!();
}
}
pub fn main() { foo(2u); }
| even | identifier_name |
if-check.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 ... | panic!();
}
}
pub fn main() { foo(2u); } | random_line_split | |
if-check.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 ... | else {
panic!();
}
}
pub fn main() { foo(2u); }
| {
println!("{}", x);
} | conditional_block |
if-check.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn foo(x: uint) {
if even(x) {
println!("{}", x);
} else {
panic!();
}
}
pub fn main() { foo(2u); }
| {
if x < 2u {
return false;
} else if x == 2u { return true; } else { return even(x - 2u); }
} | identifier_body |
type_names.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 ... |
}
| {
if substs.types.is_empty() {
return;
}
output.push('<');
for &type_parameter in &substs.types {
push_debuginfo_type_name(cx, type_parameter, true, output);
output.push_str(", ");
}
output.pop();
output.pop();
outpu... | identifier_body |
type_names.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, 'tcx>(cx: &CrateContext<'a, 'tcx>,
t: Ty<'tcx>,
qualified: bool)
-> String {
let mut result = String::with_capacity(64);
push_debuginfo_type_name(cx, t, qualified, &mut res... | compute_debuginfo_type_name | identifier_name |
type_names.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 ... | output.push_str(",...");
} else {
output.push_str("...");
}
}
output.push(')');
match sig.output {
ty::FnConverging(result_type) if result_type.is_nil() => {}
ty::FnConverging(re... |
if sig.variadic {
if !sig.inputs.is_empty() { | random_line_split |
text.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/. */
//! Text layout.
use layout::box_::{Box, ScannedTextBox, ScannedTextBoxInfo, UnscannedTextBox};
use layout::flow:... | // handle remaining clumps
if self.clump.length() > 0 {
self.flush_clump_to_list(font_context, flow, last_whitespace, &mut out_boxes);
}
debug!("TextRunScanner: swapping out boxes.");
// Swap out the old and new box list of the flow.
flow.as_inline().boxes =... | {
{
let inline = flow.as_immutable_inline();
debug!("TextRunScanner: scanning {:u} boxes for text runs...", inline.boxes.len());
}
let mut last_whitespace = true;
let mut out_boxes = ~[];
for box_i in range(0, flow.as_immutable_inline().boxes.len()) {
... | identifier_body |
text.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/. */
//! Text layout.
use layout::box_::{Box, ScannedTextBox, ScannedTextBoxInfo, UnscannedTextBox};
use layout::flow:... | (boxes: &[Box], left_i: uint, right_i: uint) -> bool {
assert!(left_i < boxes.len());
assert!(right_i > 0 && right_i < boxes.len());
assert!(left_i!= right_i);
boxes[left_i].can_merge_with_box(&boxes[right_i])
}
}
/// A "clump" is a range of inline flow l... | can_coalesce_text_nodes | identifier_name |
text.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/. */
//! Text layout.
use layout::box_::{Box, ScannedTextBox, ScannedTextBoxInfo, UnscannedTextBox};
use layout::flow:... | struct NewLinePositions {
new_line_pos: ~[uint],
}
let mut new_line_positions: ~[NewLinePositions] = ~[];
// First, transform/compress text of all the nodes.
let mut last_whitespace_in_clump = new_whitespace;
... | random_line_split | |
ping.rs | extern crate mqttc;
extern crate netopt;
#[macro_use] extern crate log;
extern crate env_logger;
use std::env;
use std::process::exit;
use std::time::Duration;
use netopt::NetworkOptions;
use mqttc::{Client, ClientOptions, ReconnectMethod};
fn main() | Some(message) => println!("{:?}", message),
None => {
println!(".");
}
}
}
}
| {
env_logger::init();
let mut args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run --example ping -- 127.0.0.1:1883");
exit(0);
}
let ref address = args[1];
info!("Display logs");
println!("Establish connection to {}", address);
// Connect... | identifier_body |
ping.rs | extern crate mqttc;
extern crate netopt; | extern crate env_logger;
use std::env;
use std::process::exit;
use std::time::Duration;
use netopt::NetworkOptions;
use mqttc::{Client, ClientOptions, ReconnectMethod};
fn main() {
env_logger::init();
let mut args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run --ex... | #[macro_use] extern crate log; | random_line_split |
ping.rs | extern crate mqttc;
extern crate netopt;
#[macro_use] extern crate log;
extern crate env_logger;
use std::env;
use std::process::exit;
use std::time::Duration;
use netopt::NetworkOptions;
use mqttc::{Client, ClientOptions, ReconnectMethod};
fn | () {
env_logger::init();
let mut args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run --example ping -- 127.0.0.1:1883");
exit(0);
}
let ref address = args[1];
info!("Display logs");
println!("Establish connection to {}", address);
// Conn... | main | identifier_name |
http_utils.rs | use url::Url;
use hyper::Client;
use hyper::header::{ContentType};
use hyper::status::StatusCode;
use hyper::error::Error;
use std::io::Read;
pub struct HttpResponse {
pub status: StatusCode,
pub body: String
}
pub fn | (url: &Url) -> Result<HttpResponse, Error> {
let mut client = Client::new();
let result_response = client.get(&url.to_string()).send();
//TODO: use try! macro here
match result_response {
Ok(mut res) => {
let mut body = String::new();
let result = res.read_to_string(&mut ... | get | identifier_name |
http_utils.rs | use url::Url;
use hyper::Client;
use hyper::header::{ContentType};
use hyper::status::StatusCode;
use hyper::error::Error;
use std::io::Read;
pub struct HttpResponse {
pub status: StatusCode,
pub body: String
}
pub fn get(url: &Url) -> Result<HttpResponse, Error> | }
pub fn post_json(url: &Url, body: &str) -> Result<HttpResponse, Error> {
let mut client = Client::new();
let result_response = client.post(&url.to_string())
.header(ContentType::json())
.body(body)
.send();
match result_response {
Ok(mut res) => {
let mut body =... | {
let mut client = Client::new();
let result_response = client.get(&url.to_string()).send();
//TODO: use try! macro here
match result_response {
Ok(mut res) => {
let mut body = String::new();
let result = res.read_to_string(&mut body);
match result {
... | identifier_body |
http_utils.rs | use url::Url;
use hyper::Client;
use hyper::header::{ContentType};
use hyper::status::StatusCode;
use hyper::error::Error;
use std::io::Read;
pub struct HttpResponse {
pub status: StatusCode,
pub body: String
} |
pub fn get(url: &Url) -> Result<HttpResponse, Error> {
let mut client = Client::new();
let result_response = client.get(&url.to_string()).send();
//TODO: use try! macro here
match result_response {
Ok(mut res) => {
let mut body = String::new();
let result = res.read_to_s... | random_line_split | |
warn_corner_cases.rs | // run-pass
// This test is checking our logic for structural match checking by enumerating
// the different kinds of const expressions. This test is collecting cases where
// we have accepted the const expression as a pattern in the past but we want
// to begin warning the user that a future version of Rust may start... | () {
const INDEX: Option<NoDerive> = [None, Some(NoDerive(10))][0];
match None { Some(_) => panic!("whoops"), INDEX => dbg!(INDEX), };
//~^ WARN must be annotated with `#[derive(PartialEq, Eq)]`
//~| WARN this was previously accepted
const fn build() -> Option<NoDerive> { None }
const CALL: Opt... | main | identifier_name |
warn_corner_cases.rs | // run-pass
// This test is checking our logic for structural match checking by enumerating
// the different kinds of const expressions. This test is collecting cases where
// we have accepted the const expression as a pattern in the past but we want
// to begin warning the user that a future version of Rust may start... | } | match None { Some(_) => panic!("whoops"), METHOD_CALL => dbg!(METHOD_CALL), };
//~^ WARN must be annotated with `#[derive(PartialEq, Eq)]`
//~| WARN this was previously accepted | random_line_split |
issue-6128.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let g : Box<HashMap<int,int>> = box HashMap::new();
let _g2 : Box<Graph<int,int>> = g as Box<Graph<int,int>>;
} | identifier_body | |
issue-6128.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
extern crate collections;
use std::collections::HashMap;
trait Graph<Node, Edge> {
fn f(&self, Edge);
}
impl<E> Graph<int, E> for HashMap<int, int> {
fn f(&self, _e: E) {
panic!();
}
}
pub fn main() {
... | random_line_split | |
issue-6128.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let g : Box<HashMap<int,int>> = box HashMap::new();
let _g2 : Box<Graph<int,int>> = g as Box<Graph<int,int>>;
}
| main | identifier_name |
simple.rs | use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use lazy_static::lazy_static;
use reroute::{Captures, RouterBuilder};
lazy_static! {
static ref ROUTER: reroute::Router = {
let mut builder = RouterBuilder::new();
// Use... | (req: Request<Body>, _: Captures) -> Response<Body> {
Response::new(req.into_body())
}
// A custom 404 handler.
fn not_found(req: Request<Body>, _: Captures) -> Response<Body> {
let message = format!("why you calling {}?", req.uri());
Response::new(Body::from(message))
}
async fn handler(req: Request<Body... | body_handler | identifier_name |
simple.rs | use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use lazy_static::lazy_static;
use reroute::{Captures, RouterBuilder};
lazy_static! { | static ref ROUTER: reroute::Router = {
let mut builder = RouterBuilder::new();
// Use raw strings so you don't need to escape patterns.
builder.get(r"/(\d+)", digit_handler);
builder.post(r"/body", body_handler);
// Using a closure also works!
builder.delete(r"/clos... | random_line_split | |
simple.rs | use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use lazy_static::lazy_static;
use reroute::{Captures, RouterBuilder};
lazy_static! {
static ref ROUTER: reroute::Router = {
let mut builder = RouterBuilder::new();
// Use... |
async fn handler(req: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(ROUTER.handle(req))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let addr = ([127, 0, 0, 1], 3000).into();
let svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn... | {
let message = format!("why you calling {}?", req.uri());
Response::new(Body::from(message))
} | identifier_body |
simple.rs | use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use lazy_static::lazy_static;
use reroute::{Captures, RouterBuilder};
lazy_static! {
static ref ROUTER: reroute::Router = {
let mut builder = RouterBuilder::new();
// Use... | else {
Response::new(Body::from("not a big number"))
}
}
// You can ignore captures if you don't want to use them.
fn body_handler(req: Request<Body>, _: Captures) -> Response<Body> {
Response::new(req.into_body())
}
// A custom 404 handler.
fn not_found(req: Request<Body>, _: Captures) -> Response<B... | {
Response::new(Body::from("that's a big number!"))
} | conditional_block |
session.rs | // Copyright (C) 2015 Wire Swiss GmbH <support@wire.com>
// Based on libsignal-protocol-java by Open Whisper Systems
// https://github.com/WhisperSystems/libsignal-protocol-java.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as publish... | // GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pub use internal::session::Error;
pub use internal::session::PreKeyStore;
pub use internal::session::Session; | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | 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 http://mozilla.org/MPL/2.0/. */
#![cfg(test)]
extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate flate2;
extern crate h... | (request: &mut Request, cache: &mut CorsCache) -> Response {
let (sender, receiver) = channel();
let mut target = FetchResponseCollector {
sender: sender,
};
methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None));
receiver.recv().unwrap()
}
fn make_server<H:... | fetch_with_cors_cache | 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/. */
#![cfg(test)]
extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate flate2;
extern crate h... | extern crate servo_config;
extern crate servo_url;
extern crate time;
extern crate unicase;
extern crate url;
mod chrome_loader;
mod cookie;
mod cookie_http_state;
mod data_loader;
mod fetch;
mod file_loader;
mod filemanager_thread;
mod hsts;
mod http_loader;
mod mime_classifier;
mod resource_thread;
mod subresource_i... | extern crate profile_traits; | 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 http://mozilla.org/MPL/2.0/. */
#![cfg(test)]
extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate flate2;
extern crate h... |
fn process_response(&mut self, _: &Response) {}
fn process_response_chunk(&mut self, _: Vec<u8>) {}
/// Fired when the response is fully fetched
fn process_response_eof(&mut self, response: &Response) {
let _ = self.sender.send(response.clone());
}
}
fn fetch(request: &mut Request, dc: Opt... | {} | identifier_body |
utf8_idents.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... | 10;
let غداء = 10;
let լանչ = 10;
let обед = 10;
let абед = 10;
let μεσημεριανό = 10;
let hádegismatur = 10;
let ручек = 10;
let ăn_trưa = 10;
let อาหารกลางวัน = 10;
// Lunchy arithmetic, mm.
assert_eq!(hádegismatur * ручек * обед, 1000);
assert_eq!(10, ארוחת_צהריי);
... | nguages.
let ランチ = 10;
let 午餐 = 10;
let ארוחת_צהריי = | identifier_name |
utf8_idents.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... | t غداء = 10;
let լանչ = 10;
let обед = 10;
let абед = 10;
let μεσημεριανό = 10;
let hádegismatur = 10;
let ручек = 10;
let ăn_trưa = 10;
let อาหารกลางวัน = 10;
// Lunchy arithmetic, mm.
assert_eq!(hádegismatur * ручек * обед, 1000);
assert_eq!(10, ארוחת_צהריי);
assert_... | identifier_body | |
utf8_idents.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... | fn საჭმელად_გემრიელი_სადილი() -> int {
// Lunch in several languages.
let ランチ = 10;
let 午餐 = 10;
let ארוחת_צהריי = 10;
let غداء = 10;
let լանչ = 10;
let обед = 10;
let абед = 10;
let μεσημεριανό = 10;
let hádegismatur = 10;
let ручек = 10;
let ăn_trưa = 10;
let อา... | random_line_split | |
htmlfieldsetelement.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::HTMLFieldSetElementBinding;
use dom::bindings::codegen:... | (&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(&window, self.upcast())
}
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
... | Validity | identifier_name |
htmlfieldsetelement.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::HTMLFieldSetElementBinding;
use dom::bindings::codegen:... | } else if node.is::<HTMLLegendElement>() {
found_legend = true;
false
} else {
true
}
});
let fields = children.flat_map(|child| {
child... | {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("disabled") => {
let disabled_state = match mutation {
AttributeMutation::Set(None) => true,
AttributeMutation::Set(Some(_)) => {
... | identifier_body |
htmlfieldsetelement.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::HTMLFieldSetElementBinding;
use dom::bindings::codegen:... | Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("disabled") => {
let disabled_... | fn super_type(&self) -> Option<&VirtualMethods> { | random_line_split |
editor.rs | use rand;
use rand::Rng;
use std::process::Command;
use std::io::prelude::*;
use std::fs::File;
const TEMP_FILE_LENGTH: usize = 16;
pub fn text_from_editor() -> String | Err(_) => String::new()
}
}
/// TODO Return proper editor from env / config
fn editor() -> String {
return "vim".to_string();
}
/// TODO Ensure real unique names
fn temp_file() -> String {
let result = String::from("/tmp/");
let file = rand::thread_rng()
.gen_ascii_chars()
... | {
let temp_file = temp_file();
let status = Command::new(editor())
.arg(temp_file.clone())
.status();
match status {
Ok(status) => {
if !status.success() {
return String::new();
}
let mut file = ... | identifier_body |
editor.rs | use rand;
use rand::Rng;
use std::process::Command;
use std::io::prelude::*;
use std::fs::File;
const TEMP_FILE_LENGTH: usize = 16;
pub fn text_from_editor() -> String {
let temp_file = temp_file();
let status = Command::new(editor())
.arg(temp_file.clone())
.s... | () -> String {
return "vim".to_string();
}
/// TODO Ensure real unique names
fn temp_file() -> String {
let result = String::from("/tmp/");
let file = rand::thread_rng()
.gen_ascii_chars()
.take(TEMP_FILE_LENGTH)
.collect::<String>();
result + &... | editor | identifier_name |
editor.rs | use rand;
use rand::Rng;
use std::process::Command;
use std::io::prelude::*;
use std::fs::File;
const TEMP_FILE_LENGTH: usize = 16;
pub fn text_from_editor() -> String {
let temp_file = temp_file();
let status = Command::new(editor())
.arg(temp_file.clone())
.s... | fn editor() -> String {
return "vim".to_string();
}
/// TODO Ensure real unique names
fn temp_file() -> String {
let result = String::from("/tmp/");
let file = rand::thread_rng()
.gen_ascii_chars()
.take(TEMP_FILE_LENGTH)
.collect::<String>();
r... | /// TODO Return proper editor from env / config | random_line_split |
mod.rs | /// The spend tree stores the location of transactions in the block-tree
///
/// It is tracks the tree of blocks and is used to verify whether a block can be inserted at a
/// certain location in the tree
///
/// A block consists of the chain of records:
///
/// [start-of-block] <- [transaction] <- [spend-output] <- [s... |
impl BlockPtr {
pub fn to_guard(self) -> BlockPtr {
BlockPtr {
start: self.start,
length: self.length,
is_guard: true
}
}
pub fn to_non_guard(self) -> BlockPtr {
BlockPtr {
start: self.start,
length: self.length,... |
impl HashIndexGuard for BlockPtr {
fn is_guard(self) -> bool { self.is_guard }
} | random_line_split |
mod.rs |
/// The spend tree stores the location of transactions in the block-tree
///
/// It is tracks the tree of blocks and is used to verify whether a block can be inserted at a
/// certain location in the tree
///
/// A block consists of the chain of records:
///
/// [start-of-block] <- [transaction] <- [spend-output] <- ... | {
pub blocks: i64,
pub inputs: i64,
pub seeks: i64,
pub total_move: i64,
pub total_diff: i64,
pub jumps: i64,
}
// Make stats additive
impl ::std::ops::Add for SpendTreeStats {
type Output = SpendTreeStats;
fn add(self, other: SpendTreeStats) -> SpendTreeStats {
... | SpendTreeStats | identifier_name |
mod.rs |
/// The spend tree stores the location of transactions in the block-tree
///
/// It is tracks the tree of blocks and is used to verify whether a block can be inserted at a
/// certain location in the tree
///
/// A block consists of the chain of records:
///
/// [start-of-block] <- [transaction] <- [spend-output] <- ... |
}
| {
// care must be taken that when a block is added to the spend-tree before one of its
// predecessors, it may not be complete.
// This because in the spend tree, the inputs are stored as the outputs they reference,
// but these inputs may not have been available.
// The resolve... | identifier_body |
options.rs | //! This module contains the configuration of the application.
//!
//! All options are passed individually to each function and are not bundled
//! together.
//!
//! # Examples
//!
//! ```no_run
//! # use doh::Options;
//! let options = Options::parse();
//! println!("Showing {}", options.remote_dir);
//! ```
use cla... | () -> Options {
let matches = app_from_crate!("\n")
.setting(AppSettings::ColoredHelp)
.arg(Arg::from_usage("<URL> 'Remote directory to browse'").validator(Options::url_validator))
.get_matches();
let u = matches.value_of("URL").unwrap();
Options {
r... | parse | identifier_name |
options.rs | //! This module contains the configuration of the application.
//!
//! All options are passed individually to each function and are not bundled
//! together.
//!
//! # Examples
//!
//! ```no_run
//! # use doh::Options;
//! let options = Options::parse();
//! println!("Showing {}", options.remote_dir);
//! ```
use cla... | #[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Options {
/// Remote directory to start on.
pub remote_dir: Url,
}
impl Options {
/// Parse `env`-wide command-line arguments into an `Options` instance
pub fn parse() -> Options {
let matches = app_from_crate!("\n")
.setting(Ap... | use reqwest::Url;
/// Representation of the application's all configurable values. | random_line_split |
options.rs | //! This module contains the configuration of the application.
//!
//! All options are passed individually to each function and are not bundled
//! together.
//!
//! # Examples
//!
//! ```no_run
//! # use doh::Options;
//! let options = Options::parse();
//! println!("Showing {}", options.remote_dir);
//! ```
use cla... |
}
| {
Url::parse(&s)
.or_else(|_| Url::parse(&format!("http://{}", s)))
.map(|_| ())
.map_err(|e| e.to_string())
} | identifier_body |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name... | (cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32);
}
/// Throw a `RangeError` with the given message.
pub fn throw_range_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32);
}
| throw_type_error | identifier_name |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name... | }
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("\"this\" object does not implement interface {}.",
... | let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error); | random_line_split |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name... |
/// Format string used to throw javascript errors.
static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [
'{' as libc::c_char,
'0' as libc::c_char,
'}' as libc::c_char,
0 as libc::c_char,
];
/// Format string struct used to throw `TypeError`s.
static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatStrin... | {
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
} | identifier_body |
bigint.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
|
// Parity 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along ... | // 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. | random_line_split |
bigint.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.... | (b: &mut Bencher) {
b.iter(|| {
let n = black_box(10000);
(0..n).fold(U128([12345u64, 0u64]), |old, new| { old.overflowing_mul(U128::from(new)).0 })
});
}
| u128_mul | identifier_name |
bigint.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.... |
#[bench]
fn u256_mul(b: &mut Bencher) {
b.iter(|| {
let n = black_box(10000);
(0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_mul(U256::from(new)).0 })
});
}
#[bench]
fn u256_full_mul(b: &mut Bencher) {
b.iter(|| {
... | {
b.iter(|| {
let n = black_box(10000);
(0..n).fold(U512([0, 0, 0, 0, 0, 0, 0, 0]),
|old, new| { old.overflowing_add(U512([new, new, new, new, new, new, new, new])).0 })
});
} | identifier_body |
basket.rs | use rocket_contrib::Template;
use rocket::State;
use model::{AuthUser, Basket};
use context::Context;
use db::Db;
#[get("/<username>/<basket>", rank = 10)]
pub fn index(
username: &str,
basket: &str,
auth_user: Option<AuthUser>,
db: State<Db>,
) -> Option<Template> {
handler(username, basket, aut... | name,
).unwrap();
}
s
}
| {
use std::fmt::Write;
let mut s = String::new();
let facades = [
("foo", "Foo", ""),
("bar", "Bar", ""),
("baz", "Baz", ""),
("settings", "Settings", "float-right"),
];
for &(id, name, classes) in &facades {
write!(
s,
r#"<li class=... | identifier_body |
basket.rs | use rocket_contrib::Template;
use rocket::State;
use model::{AuthUser, Basket};
use context::Context;
use db::Db;
#[get("/<username>/<basket>", rank = 10)]
pub fn index(
username: &str,
basket: &str,
auth_user: Option<AuthUser>,
db: State<Db>,
) -> Option<Template> {
handler(username, basket, aut... | (
username: &str,
basket: &str,
auth_user: Option<AuthUser>,
db: State<Db>,
facade: Option<&str>,
) -> Option<Template> {
Basket::load(basket, username, auth_user.as_ref(), &db)
.map(|basket| {
// TODO: load facade
let active_facade = facade.unwrap_or("settings");... | handler | identifier_name |
basket.rs | use rocket_contrib::Template;
use rocket::State;
use model::{AuthUser, Basket};
use context::Context; | use db::Db;
#[get("/<username>/<basket>", rank = 10)]
pub fn index(
username: &str,
basket: &str,
auth_user: Option<AuthUser>,
db: State<Db>,
) -> Option<Template> {
handler(username, basket, auth_user, db, None)
}
#[get("/<username>/<basket>/<facade>", rank = 10)]
pub fn facade(
username: &s... | random_line_split | |
clock.rs | // Copyright 2021 Google LLC
//
// 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 agreed to in ... | } | random_line_split | |
clock.rs | // Copyright 2021 Google LLC
//
// 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 agreed to in ... | () {}
#[no_mangle]
pub extern "C" fn proxy_on_memory_allocate(_: usize) -> *mut u8 {
std::ptr::null_mut()
}
#[no_mangle]
pub extern "C" fn run() {
println!("monotonic: {:?}", Instant::now());
println!("realtime: {:?}", SystemTime::now());
}
| proxy_abi_version_0_2_0 | identifier_name |
clock.rs | // Copyright 2021 Google LLC
//
// 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 agreed to in ... | {
println!("monotonic: {:?}", Instant::now());
println!("realtime: {:?}", SystemTime::now());
} | identifier_body | |
crate_map.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let root_crate = CrateMapT2 {
version: 1, annihilate_fn: ptr::null(),
entries: vec::raw::to_ptr([
ModEntry { name: "t::f1".to_c_str().with_ref(|buf| buf), log_level: &mut 0},
ModEntry { name: ptr::null(), log_level: ptr::mut_null()}
]),
... | let child_crate1_ptr: *CrateMap = transmute(&child_crate1); | random_line_split |
crate_map.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (crate_map: *CrateMap) -> *ModEntry {
match version(crate_map) {
0 => {
let v0 = crate_map as (*CrateMapV0);
return (*v0).entries;
}
1 => return (*crate_map).entries,
_ => fail!("Unknown crate map version!")
}
}
unsafe fn iterator(crate_map: *CrateMap) ->... | entries | identifier_name |
simdint.rs | // Copyright 2015 blake2-rfc Developers
// | // http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
#![allow(dead_code)]
#[cfg(feature = "simd")]
extern "platform-intrinsic" {
pub fn simd_add<T>(x: T, y: T) -> T;
pub fn simd_shl<T>(x: T, y: T) -> T;
pub fn sim... | // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or | random_line_split |
tag-align-dyn-variants.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... | tB: a_tag<A,B>
}
fn mk_rec<A,B>(a: A, b: B) -> t_rec<A,B> {
return t_rec{ chA:0u8, tA:varA(a), chB:1u8, tB:varB(b) };
}
fn is_aligned<A>(amnt: uint, u: &A) -> bool {
let p = ptr::to_unsafe_ptr(u) as uint;
return (p & (amnt-1u)) == 0u;
}
fn variant_data_is_aligned<A,B>(amnt: uint, u: &a_tag<A,B>) -> b... | chB: u8, | random_line_split |
tag-align-dyn-variants.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... | <A,B> {
varA(A),
varB(B)
}
struct t_rec<A,B> {
chA: u8,
tA: a_tag<A,B>,
chB: u8,
tB: a_tag<A,B>
}
fn mk_rec<A,B>(a: A, b: B) -> t_rec<A,B> {
return t_rec{ chA:0u8, tA:varA(a), chB:1u8, tB:varB(b) };
}
fn is_aligned<A>(amnt: uint, u: &A) -> bool {
let p = ptr::to_unsafe_ptr(u) as uint;... | a_tag | identifier_name |
tag-align-dyn-variants.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... |
pub fn main() {
let x = mk_rec(22u64, 23u64);
assert!(is_aligned(8u, &x.tA));
assert!(variant_data_is_aligned(8u, &x.tA));
assert!(is_aligned(8u, &x.tB));
assert!(variant_data_is_aligned(8u, &x.tB));
let x = mk_rec(22u64, 23u32);
assert!(is_aligned(8u, &x.tA));
assert!(variant_data_is... | {
match u {
&varA(ref a) => is_aligned(amnt, a),
&varB(ref b) => is_aligned(amnt, b)
}
} | identifier_body |
memory.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#[cfg(not(feature = "std"))]
use alloc::prelude::*;
use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Share... |
}
#[cfg(test)]
mod tests {
/* FIXME nostd: enable test
use super::*;
use zinc64_core::{new_shared, Addressable, Ram, Rom};
impl Addressable for Ram {
fn read(&self, address: u16) -> u8 {
self.read(address)
}
fn write(&mut self, address: u16, value: u8) {
... | {
let bank = self.mmu.borrow().map(address);
match bank {
Bank::Ram => self.ram.borrow_mut().write(address, value),
Bank::Basic => self.ram.borrow_mut().write(address, value),
Bank::Charset => self.ram.borrow_mut().write(address, value),
Bank::Kernal => se... | identifier_body |
memory.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#[cfg(not(feature = "std"))]
use alloc::prelude::*;
use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Share... | (&self, address: u16) -> u8 {
let bank = self.mmu.borrow().map(address);
match bank {
Bank::Ram => self.ram.borrow().read(address),
Bank::Basic => self.basic.borrow().read(address),
Bank::Charset => self
.charset
.borrow()
... | read | identifier_name |
memory.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#[cfg(not(feature = "std"))]
use alloc::prelude::*;
use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Share... | }
fn write(&mut self, address: u16, value: u8) {
self.write(address, value);
}
}
fn setup_memory() -> Memory {
let basic = new_shared(Rom::new(0x1000, BaseAddr::Basic.addr(), 0x10));
let charset = new_shared(Rom::new(0x1000, 0x0000, 0x11));
let kerna... |
impl Addressable for Ram {
fn read(&self, address: u16) -> u8 {
self.read(address) | random_line_split |
arithmetic.rs | #[macro_use]
extern crate nom;
use nom::{IResult,digit, multispace};
use std::str;
use std::str::FromStr;
named!(parens<i64>, delimited!(
delimited!(opt!(multispace), tag!("("), opt!(multispace)),
expr,
delimited!(opt!(multispace), tag!(")"), opt!(multispace))
)
);
named!(factor<i64>,
alt!(
map_... | () {
assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&b""[..], 3));
assert_eq!(expr(&b" 12 + 6 - 4+ 3"[..]), IResult::Done(&b""[..], 17));
assert_eq!(expr(&b" 1 + 2*3 + 4"[..]), IResult::Done(&b""[..], 11));
}
#[test]
fn parens_test() {
assert_eq!(expr(&b" ( 2 )"[..]), IResult::Done(&b""[..], 2));
assert_... | expr_test | identifier_name |
arithmetic.rs | #[macro_use]
extern crate nom;
use nom::{IResult,digit, multispace};
use std::str;
use std::str::FromStr;
named!(parens<i64>, delimited!(
delimited!(opt!(multispace), tag!("("), opt!(multispace)),
expr,
delimited!(opt!(multispace), tag!(")"), opt!(multispace))
)
);
named!(factor<i64>,
alt!(
map_... |
#[test]
fn term_test() {
assert_eq!(term(&b" 12 *2 / 3"[..]), IResult::Done(&b""[..], 8));
assert_eq!(term(&b" 2* 3 *2 *2 / 3"[..]), IResult::Done(&b""[..], 8));
assert_eq!(term(&b" 48 / 3/2"[..]), IResult::Done(&b""[..], 8));
}
#[test]
fn expr_test() {
assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&... | {
assert_eq!(factor(&b"3"[..]), IResult::Done(&b""[..], 3));
assert_eq!(factor(&b" 12"[..]), IResult::Done(&b""[..], 12));
assert_eq!(factor(&b"537 "[..]), IResult::Done(&b""[..], 537));
assert_eq!(factor(&b" 24 "[..]), IResult::Done(&b""[..], 24));
} | identifier_body |
arithmetic.rs | #[macro_use]
extern crate nom;
use nom::{IResult,digit, multispace};
use std::str;
use std::str::FromStr;
named!(parens<i64>, delimited!(
delimited!(opt!(multispace), tag!("("), opt!(multispace)),
expr,
delimited!(opt!(multispace), tag!(")"), opt!(multispace))
)
);
named!(factor<i64>,
alt!(
map_... | )
| parens
)
);
named!(term <i64>,
chain!(
mut acc: factor ~
many0!(
alt!(
tap!(mul: preceded!(tag!("*"), factor) => acc = acc * mul) |
tap!(div: preceded!(tag!("/"), factor) => acc = acc / div)
)
),
|| { retur... | random_line_split | |
inner-attrs-on-impl.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #[cfg(cfg_that_surely_doesnt_exist)];
fn method(&self) -> bool { false }
}
impl Foo {
#[cfg(not(cfg_that_surely_doesnt_exist))];
// check that we don't eat attributes too eagerly.
#[cfg(cfg_that_surely_doesnt_exist)]
fn method(&self) -> bool { false }
fn method(&self) -> bool { true }
}
... | struct Foo;
impl Foo { | random_line_split |
inner-attrs-on-impl.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
pub fn main() {
assert!(Foo.method());
}
| { true } | identifier_body |
inner-attrs-on-impl.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> bool { true }
}
pub fn main() {
assert!(Foo.method());
}
| method | identifier_name |
memory.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
fn size(&self) -> usize {
self.len()
}
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
let off = init_off_u.low_u64() as usize;
let size = init_size_u.low_u64() as usize;
if!is_valid_range(off, size) {
&self[0..0]
} else {
&self[off..off+size]
}
}
fn read(&self, offset: U... | {
println!("MemoryDump:");
for i in self.iter() {
println!("{:02x} ", i);
}
println!("");
} | identifier_body |
memory.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | else {
&self[off..off+size]
}
}
fn read(&self, offset: U256) -> U256 {
let off = offset.low_u64() as usize;
U256::from(&self[off..off+32])
}
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] {
let off = offset.low_u64() as usize;
let s = size.low_u64() as usize;
if!is_valid_rang... | {
&self[0..0]
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.