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 |
|---|---|---|---|---|
alpine.rs | use std::io::Write;
use std::fs::File;
use std::path::Path;
use unshare::{Command, Stdio};
use rand::{thread_rng, Rng};
use super::super::super::file_util::create_dir;
use super::super::context::{Context};
use super::super::capsule;
use super::super::packages;
use process_util::capture_stdout;
use builder::distrib::{... |
return Ok(unsupp);
}
fn finish(&mut self, ctx: &mut Context) -> Result<(), String>
{
let pkgs = ctx.build_deps.clone().into_iter().collect();
try!(remove(ctx, &pkgs));
let mut cmd = Command::new("/vagga/bin/apk");
cmd
.stdin(Stdio::null())
.env_... | {
try!(capsule::apk_run(&[
"--root", "/vagga/root",
"add",
], &to_install[..]));
} | conditional_block |
alpine.rs | use std::io::Write;
use std::fs::File;
use std::path::Path;
use unshare::{Command, Stdio};
use rand::{thread_rng, Rng};
use super::super::super::file_util::create_dir;
use super::super::context::{Context};
use super::super::capsule;
use super::super::packages;
use process_util::capture_stdout;
use builder::distrib::{... | }
fn system_deps(pkg: packages::Package) -> Option<Vec<&'static str>> {
match pkg {
packages::BuildEssential => Some(vec!()),
packages::Https => Some(vec!()),
packages::Python2 => Some(vec!("python")),
packages::Python2Dev => Some(vec!()),
packages::Python3 => Some(vec!("pyt... | packages::NodeJsDev => Some(vec!("nodejs-dev")),
packages::Npm => Some(vec!()),
packages::Git => Some(vec!("git")),
packages::Mercurial => Some(vec!("hg")),
} | random_line_split |
package_id.rs | use std::cmp::Ordering;
use std::error::Error;
use std::fmt::{self, Formatter};
use std::hash::Hash;
use std::hash;
use std::sync::Arc;
use regex::Regex;
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
use semver;
use util::{CargoResult, CargoError, short_hash, ToSemver};
use core::source::SourceId;
/... |
PackageIdError::InvalidNamespace(ref ns) => {
write!(f, "invalid namespace: {}", *ns)
}
}
}
}
impl CargoError for PackageIdError {
fn is_human(&self) -> bool { true }
}
impl From<PackageIdError> for Box<CargoError> {
fn from(t: PackageIdError) -> Box<CargoE... | {
write!(f, "invalid version: {}", *v)
} | conditional_block |
package_id.rs | use std::cmp::Ordering;
use std::error::Error;
use std::fmt::{self, Formatter};
use std::hash::Hash;
use std::hash;
use std::sync::Arc;
use regex::Regex;
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
use semver;
use util::{CargoResult, CargoError, short_hash, ToSemver};
use core::source::SourceId;
/... |
}
#[derive(Clone, Debug, PartialEq)]
pub enum PackageIdError {
InvalidVersion(String),
InvalidNamespace(String)
}
impl Error for PackageIdError {
fn description(&self) -> &str { "failed to parse package id" }
}
impl fmt::Display for PackageIdError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Resu... | {
(*self.inner).cmp(&*other.inner)
} | identifier_body |
package_id.rs | use std::cmp::Ordering;
use std::error::Error;
use std::fmt::{self, Formatter};
use std::hash::Hash;
use std::hash;
use std::sync::Arc;
use regex::Regex;
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
use semver;
use util::{CargoResult, CargoError, short_hash, ToSemver};
use core::source::SourceId;
/... | (t: PackageIdError) -> Box<CargoError> { Box::new(t) }
}
#[derive(PartialEq, Eq, Hash, Clone, RustcEncodable, Debug)]
pub struct Metadata {
pub metadata: String,
pub extra_filename: String
}
impl PackageId {
pub fn new<T: ToSemver>(name: &str, version: T,
sid: &SourceId) -> Ca... | from | identifier_name |
package_id.rs | use std::cmp::Ordering;
use std::error::Error;
use std::fmt::{self, Formatter};
use std::hash::Hash;
use std::hash;
use std::sync::Arc;
use regex::Regex;
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
use semver;
use util::{CargoResult, CargoError, short_hash, ToSemver};
use core::source::SourceId;
/... | }
}
impl PartialOrd for PackageId {
fn partial_cmp(&self, other: &PackageId) -> Option<Ordering> {
(*self.inner).partial_cmp(&*other.inner)
}
}
impl Eq for PackageId {}
impl Ord for PackageId {
fn cmp(&self, other: &PackageId) -> Ordering {
(*self.inner).cmp(&*other.inner)
}
}
#[der... | random_line_split | |
is_prefix_of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::str::pattern::Pattern;
// pub trait Pattern<'a>: Sized {
// /// Associated searcher for this pattern
// type Searcher: Searcher<'a>;
//
// /// Constructs the associated searcher from
// /// `self` and t... | () {
let string: &str = "我能";
let haystack: &str = "我能吞下玻璃而不傷身體。";
let result: bool = string.is_prefix_of(haystack);
assert_eq!(result, true);
}
#[test]
fn is_prefix_of_test2() {
let string: &str = "玻璃";
let haystack: &str = "我能吞下玻璃而不傷身體。";
let result: bool = string.is_prefix_of(haystack);
assert... | is_prefix_of_test1 | identifier_name |
is_prefix_of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::str::pattern::Pattern;
// pub trait Pattern<'a>: Sized {
// /// Associated searcher for this pattern
// type Searcher: Searcher<'a>;
//
// /// Constructs the associated searcher from
// /// `self` and t... | ix_of_test2() {
let string: &str = "玻璃";
let haystack: &str = "我能吞下玻璃而不傷身體。";
let result: bool = string.is_prefix_of(haystack);
assert_eq!(result, false);
}
}
| {
let string: &str = "我能";
let haystack: &str = "我能吞下玻璃而不傷身體。";
let result: bool = string.is_prefix_of(haystack);
assert_eq!(result, true);
}
#[test]
fn is_pref | identifier_body |
is_prefix_of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::str::pattern::Pattern;
// pub trait Pattern<'a>: Sized {
// /// Associated searcher for this pattern
// type Searcher: Searcher<'a>;
//
// /// Constructs the associated searcher from
// /// `self` and t... |
// impl<'a, 'b> Pattern<'a> for &'b str {
// type Searcher = StrSearcher<'a, 'b>;
//
// #[inline]
// fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> {
// StrSearcher {
// haystack: haystack,
// needle: self,
// ... | // }
// }
// } | random_line_split |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... |
fn print_factors_str(num_str: &str) {
if let Err(e) = num_str.parse::<u64>().and_then(|x| Ok(print_factors(x))) {
show_warning!("{}: {}", num_str, e);
}
}
pub fn uumain(args: Vec<String>) -> i32 {
let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP)
.parse(args);
if matches.free.is... | {
print!("{}:", num);
let mut factors = Vec::new();
// we always start with table division, and go from there
table_division(num, &mut factors);
factors.sort();
for fac in &factors {
print!(" {}", fac);
}
println!("");
} | identifier_body |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... | let mut b = range.ind_sample(&mut rng);
loop {
x = rho_pollard_pseudorandom_function(x, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
let d = gcd(num, max(x, y) - min(x, y));
if d == num {
... | let mut x = range.ind_sample(&mut rng);
let mut y = x;
let mut a = range.ind_sample(&mut rng); | random_line_split |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... | (mut a: u64, mut b: u64) -> u64 {
while b > 0 {
a %= b;
swap(&mut a, &mut b);
}
a
}
fn rho_pollard_find_divisor(num: u64) -> u64 {
let range = Range::new(1, num);
let mut rng = rand::weak_rng();
let mut x = range.ind_sample(&mut rng);
let mut y = x;
let mut a = range.ind... | gcd | identifier_name |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... |
for &(prime, inv, ceil) in P_INVS_U64 {
if num == 1 {
break;
}
// inv = prime^-1 mod 2^64
// ceil = floor((2^64-1) / prime)
// if (num * inv) mod 2^64 <= ceil, then prime divides num
// See http://math.stackexchange.com/questions/1251327/
// for ... | {
factors.push(num);
return;
} | conditional_block |
err.rs | use std::error::Error;
use std::fmt;
pub type Result<T> = ::std::result::Result<T, DrawError>;
/// The enum `DrawError` defines the possible errors
/// from constructor Position.
#[derive(Clone, Debug)]
pub enum DrawError {
OutOfSize(String),
}
impl fmt::Display for DrawError {
/// The function `fmt` format... | match *self {
DrawError::OutOfSize(ref size) => size,
}
}
/// The function `cause` returns the lower-level cause of
/// this error if any.
fn cause(&self) -> Option<&Error> {
None
}
} | random_line_split | |
err.rs | use std::error::Error;
use std::fmt;
pub type Result<T> = ::std::result::Result<T, DrawError>;
/// The enum `DrawError` defines the possible errors
/// from constructor Position.
#[derive(Clone, Debug)]
pub enum DrawError {
OutOfSize(String),
}
impl fmt::Display for DrawError {
/// The function `fmt` format... |
/// The function `cause` returns the lower-level cause of
/// this error if any.
fn cause(&self) -> Option<&Error> {
None
}
}
| {
match *self {
DrawError::OutOfSize(ref size) => size,
}
} | identifier_body |
err.rs | use std::error::Error;
use std::fmt;
pub type Result<T> = ::std::result::Result<T, DrawError>;
/// The enum `DrawError` defines the possible errors
/// from constructor Position.
#[derive(Clone, Debug)]
pub enum DrawError {
OutOfSize(String),
}
impl fmt::Display for DrawError {
/// The function `fmt` format... | (&self) -> Option<&Error> {
None
}
}
| cause | 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/. */
extern crate ipc_channel;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate msg;
... |
pub fn recv_embedder_msg(&mut self) -> (Option<TopLevelBrowsingContextId>, EmbedderMsg) {
self.receiver.recv().unwrap()
}
}
#[derive(Deserialize, Serialize)]
pub enum EmbedderMsg {
/// A status message to be displayed by the browser chrome.
Status(Option<String>),
/// Alerts the embedder t... | {
self.receiver.try_recv()
} | 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 http://mozilla.org/MPL/2.0/. */
extern crate ipc_channel;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate msg;
... | (pub String);
| FilterPattern | 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/. */
extern crate ipc_channel;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate msg;
... | }
self.event_loop_waker.wake();
}
}
impl Clone for EmbedderProxy {
fn clone(&self) -> EmbedderProxy {
EmbedderProxy {
sender: self.sender.clone(),
event_loop_waker: self.event_loop_waker.clone(),
}
}
}
/// The port that the embedder receives messages... | random_line_split | |
executer.rs | use std::error;
use rusoto_core::Region;
use rusoto_ecs::EcsClient;
use crate::command::ecs::Executer as EcsExecuter;
use crate::command::error::CommandError;
use crate::config;
use crate::output;
pub struct ExecuterOptions {
pub no_wait: bool,
}
#[allow(dead_code)]
pub struct Executer<'c> {
ecs_client: Ecs... | (&self) -> &EcsClient {
&self.ecs_client
}
}
| ecs_client | identifier_name |
executer.rs | use std::error;
use rusoto_core::Region;
use rusoto_ecs::EcsClient;
use crate::command::ecs::Executer as EcsExecuter;
use crate::command::error::CommandError;
use crate::config;
use crate::output;
pub struct ExecuterOptions {
pub no_wait: bool,
}
#[allow(dead_code)]
pub struct Executer<'c> {
ecs_client: Ecs... |
let task_definition = maybe_task_definition.unwrap();
let zero_task_service = config::ecs::Service {
name: service_conf.name.to_owned(),
desired_count: Some(0),
deployment_configuration: service_conf.deployment_configuration.to_owned(),
load_balancers: s... | {
output::PrintLine::error("Could not find task_definition");
return Err(Box::new(CommandError::Unknown));
} | conditional_block |
executer.rs | use std::error;
use rusoto_core::Region;
use rusoto_ecs::EcsClient;
use crate::command::ecs::Executer as EcsExecuter;
use crate::command::error::CommandError;
use crate::config;
use crate::output;
pub struct ExecuterOptions {
pub no_wait: bool,
}
#[allow(dead_code)]
pub struct Executer<'c> {
ecs_client: Ecs... | return Ok(());
}
let maybe_task_definition = self
.describe_latest_task_definition(&service_conf.task_definition.family)
.await?;
if maybe_task_definition.is_none() {
output::PrintLine::error("Could not find task_definition");
return Err(... | if maybe_service.is_none() {
output::PrintLine::info("Service has not been exist."); | random_line_split |
executer.rs | use std::error;
use rusoto_core::Region;
use rusoto_ecs::EcsClient;
use crate::command::ecs::Executer as EcsExecuter;
use crate::command::error::CommandError;
use crate::config;
use crate::output;
pub struct ExecuterOptions {
pub no_wait: bool,
}
#[allow(dead_code)]
pub struct Executer<'c> {
ecs_client: Ecs... |
pub async fn run(&self) -> Result<(), Box<dyn error::Error>> {
trace!("command::service::stop::Executer::run");
let service_conf = &self.config.service;
let cluster = &self.config.cluster;
let maybe_service = self.describe_service(cluster, &service_conf).await?;
if maybe... | {
trace!("command::service::stop::Executer::from_config");
let client = EcsClient::new(Region::ApNortheast1);
Executer {
ecs_client: client,
config: config,
options: options,
}
} | identifier_body |
error.rs | use ::std::io;
use ::std::result;
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "Unable to find the path '{}'. Perhaps it does not exist or you do not have the required permissions.", path)]
PathNotFound {
path: String,
},
#[fail(display = "Unable to create an empty archive.")]
... |
pub type Result<T> = result::Result<T, Error>; | } | random_line_split |
error.rs | use ::std::io;
use ::std::result;
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "Unable to find the path '{}'. Perhaps it does not exist or you do not have the required permissions.", path)]
PathNotFound {
path: String,
},
#[fail(display = "Unable to create an empty archive.")]
... | (e: io::Error) -> Self {
Error::IO {
inner: e,
}
}
}
impl From<::walkdir::Error> for Error {
fn from(e: ::walkdir::Error) -> Self {
let path = e.path()
.map(|ref_path| ref_path.to_string_lossy().to_string())
.unwrap_or_else(|| String::from("<unknown pat... | from | identifier_name |
struct-style-enum.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.
// compile-flags:-Z extra-debug-info
// debugger:set print union on
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print case1
// check:$1 = {{Case1, a = 0, b = 31868, c = 31868, d = 31868, e = 31868}, {Case1, a = 0, b = 2088533116, c = 2088533116}, {Case1, a... | random_line_split | |
struct-style-enum.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 ... | () {()}
| zzz | identifier_name |
socket.rs | //! One-way socket wrapper data structures.
use nanomsg::{Endpoint, Socket, Protocol, Error};
use std;
use std::convert::AsRef;
use std::io::{Read, Write};
use std::time::Duration;
/// A send-only socket.
pub struct SendSocket {
socket: Socket,
endpoint: Endpoint,
}
fn as_millis(duration: Duration) -> isize {
... |
/// Terminate this connection.
pub fn close(self) {
// The `drop` takes care of everything.
}
}
impl Drop for ReceiveSocket {
fn drop(&mut self) {
self.endpoint.shutdown().unwrap_or(());
}
}
| {
let mut msg = Vec::new();
let result = self.socket.nb_read_to_end(&mut msg);
match result {
Ok(_) => Result::Success(msg),
Err(Error::TryAgain) => Result::Empty,
Err(Error::Terminating) => Result::Terminating,
Err(_) => {
result.unwrap();
unreachable!()
}
... | identifier_body |
socket.rs | //! One-way socket wrapper data structures.
use nanomsg::{Endpoint, Socket, Protocol, Error};
use std;
use std::convert::AsRef;
use std::io::{Read, Write};
use std::time::Duration;
/// A send-only socket.
pub struct SendSocket {
socket: Socket,
endpoint: Endpoint,
}
fn as_millis(duration: Duration) -> isize {
... |
}
}
/// Terminate this connection.
pub fn close(self) {
// The `drop` takes care of everything.
}
}
impl Drop for ReceiveSocket {
fn drop(&mut self) {
self.endpoint.shutdown().unwrap_or(());
}
}
| {
result.unwrap();
unreachable!()
} | conditional_block |
socket.rs | //! One-way socket wrapper data structures.
use nanomsg::{Endpoint, Socket, Protocol, Error};
use std;
use std::convert::AsRef;
use std::io::{Read, Write};
use std::time::Duration;
/// A send-only socket.
pub struct SendSocket {
socket: Socket,
endpoint: Endpoint,
}
fn as_millis(duration: Duration) -> isize {
... | (self) {
// The `drop` takes care of everything.
}
}
impl Drop for ReceiveSocket {
fn drop(&mut self) {
self.endpoint.shutdown().unwrap_or(());
}
}
| close | identifier_name |
socket.rs | //! One-way socket wrapper data structures.
use nanomsg::{Endpoint, Socket, Protocol, Error};
use std;
use std::convert::AsRef;
use std::io::{Read, Write};
use std::time::Duration;
/// A send-only socket.
pub struct SendSocket {
socket: Socket,
endpoint: Endpoint,
}
fn as_millis(duration: Duration) -> isize {
... | Empty,
Terminating,
}
/// A receive-only socket.
pub struct ReceiveSocket {
socket: Socket,
endpoint: Endpoint,
}
impl ReceiveSocket {
#[allow(missing_docs)]
pub fn new(url: &str, timeout: Option<Duration>) -> ReceiveSocket {
let mut socket = Socket::new(Protocol::Pull).unwrap();
timeout.map(|time... | random_line_split | |
issue-14254.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) {
self.baz();
self.x;
self.y;
BarTy::a();
Foo::bah(None::<&BarTy>);
self.b();
}
}
// If these fail, it's necessary to update rustc_resolve and the cfail tests.
impl<'a> Foo for &'a mut BarTy {
fn bar(&self) {
self.baz();
self.x;
se... | bar | identifier_name |
issue-14254.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | Foo::bah(None::<&mut BarTy>);
self.b();
}
}
// If these fail, it's necessary to update rustc_resolve and the cfail tests.
impl Foo for Box<BarTy> {
fn bar(&self) {
self.baz();
Foo::bah(None::<Box<BarTy>>);
}
}
// If these fail, it's necessary to update rustc_resolve and the... | random_line_split | |
issue-14254.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
// If these fail, it's necessary to update rustc_resolve and the cfail tests.
impl<'a> Foo for &'a isize {
fn bar(&self) {
self.baz();
Foo::bah(None::<&isize>);
}
}
// If these fail, it's necessary to update rustc_resolve and the cfail tests.
impl<'a> Foo for &'a mut isize {
fn bar(&sel... | {
self.baz();
Foo::bah(None::<*const isize>);
} | identifier_body |
testutils.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Macros and utilities for testing.
use std::borrow::ToOwned;
use types::{RawDecoder, RawEncoder};
pub struct TestResult<'a, Output: 'a +?Sized + ToOwned> {
pub expected_return: (usize,... |
fn process_finish_err<'a>(&mut self, backup: isize, output: &'a [u8]) -> TestResult<'a, [u8]> {
let mut buf = Vec::new();
let err = self.raw_finish(&mut buf);
TestResult {
expected_return: (0, Some(backup)),
expected_push: output,
actual_return: (0, err.... | {
let mut buf = Vec::new();
let err = self.raw_finish(&mut buf);
TestResult {
expected_return: (0, None),
expected_push: output,
actual_return: (0, err.map(|e| e.upto)),
actual_push: buf,
}
} | identifier_body |
testutils.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Macros and utilities for testing.
use std::borrow::ToOwned;
use types::{RawDecoder, RawEncoder};
pub struct TestResult<'a, Output: 'a +?Sized + ToOwned> {
pub expected_return: (usize,... | <'a>(&mut self, backup: isize, processed: &str, problem: &str,
remaining: &str, output: &'a [u8]) -> TestResult<'a, [u8]> {
let mut input = String::with_capacity(processed.len() + problem.len() + remaining.len());
input.push_str(processed);
input.push_str(problem);
... | process_feed_err | identifier_name |
testutils.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Macros and utilities for testing.
use std::borrow::ToOwned;
use types::{RawDecoder, RawEncoder};
pub struct TestResult<'a, Output: 'a +?Sized + ToOwned> {
pub expected_return: (usize,... | Err(..) => {
LONGER_TEXT.to_vec()
}
}
} | file.read_to_end(&mut ret).ok().expect("cannot read an external bench data");
ret
} | random_line_split |
lib.rs | #![deny(unused)]
#![feature(metadata_ext)]
#![cfg_attr(test, deny(warnings))]
#[cfg(test)] extern crate hamcrest;
#[macro_use] extern crate log;
extern crate curl;
extern crate docopt;
extern crate flate2;
extern crate git2;
extern crate glob;
extern crate libc;
extern crate num_cpus;
extern crate regex;
extern crate ... | <'a, T>(usage: &str, args: &[String],
options_first: bool) -> CliResult<T>
where T: Decodable
{
let docopt = Docopt::new(usage).unwrap()
.options_first(options_first)
.argv(args.iter().map(|s| &s[..]))
... | flags_from_args | identifier_name |
lib.rs | #![deny(unused)]
#![feature(metadata_ext)]
#![cfg_attr(test, deny(warnings))]
#[cfg(test)] extern crate hamcrest;
#[macro_use] extern crate log;
extern crate curl;
extern crate docopt;
extern crate flate2;
extern crate git2;
extern crate glob;
extern crate libc;
extern crate num_cpus;
extern crate regex;
extern crate ... | None => format!("{}.{}.{}{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH"),
option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""))
})
}
fn flags_from_args<'a, T>... | Some(s) => s.to_string(), | random_line_split |
lib.rs | #![deny(unused)]
#![feature(metadata_ext)]
#![cfg_attr(test, deny(warnings))]
#[cfg(test)] extern crate hamcrest;
#[macro_use] extern crate log;
extern crate curl;
extern crate docopt;
extern crate flate2;
extern crate git2;
extern crate glob;
extern crate libc;
extern crate num_cpus;
extern crate regex;
extern crate ... |
pub fn handle_error(err: CliError, shell: &mut MultiShell) {
debug!("handle_error; err={:?}", err);
let CliError { error, exit_code, unknown } = err;
let fatal = exit_code!= 0; // exit_code == 0 is non-fatal error
let hide = unknown &&!shell.get_verbose();
if hide {
let _ = shell.err().... | {
let std_shell = if fatal {shell.err()} else {shell.out()};
let color = if fatal {RED} else {BLACK};
let _ = std_shell.say(err, color);
} | identifier_body |
lib.rs | #![deny(unused)]
#![feature(metadata_ext)]
#![cfg_attr(test, deny(warnings))]
#[cfg(test)] extern crate hamcrest;
#[macro_use] extern crate log;
extern crate curl;
extern crate docopt;
extern crate flate2;
extern crate git2;
extern crate glob;
extern crate libc;
extern crate num_cpus;
extern crate regex;
extern crate ... | else {0};
CliError::from_error(human(e.to_string()), code)
})
}
fn json_from_stdin<T: Decodable>() -> CliResult<T> {
let mut reader = io::stdin();
let mut input = String::new();
try!(reader.read_to_string(&mut input).map_err(|_| {
CliError::new("Standard in did not exist or was not UTF... | {1} | conditional_block |
minwinbase.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! This module defines the 32-Bit Windows Base APIs
#[repr(C)] #[derive(Clone, Copy, Debug)]
pub struct SECURITY_ATTRIBUTES {
pub nLength: ::DWORD,
pub lpSecurityDescriptor: ::LPVOID,
pub bInheritHandle: ::BOOL,
}
pub type P... | &self) -> WIN32_FIND_DATAA { *self } }
pub type PWIN32_FIND_DATAA = *mut WIN32_FIND_DATAA;
pub type LPWIN32_FIND_DATAA = *mut WIN32_FIND_DATAA;
#[repr(C)] #[derive(Copy)]
pub struct WIN32_FIND_DATAW {
pub dwFileAttributes: ::DWORD,
pub ftCreationTime: ::FILETIME,
pub ftLastAccessTime: ::FILETIME,
pub ft... | lone( | identifier_name |
minwinbase.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! This module defines the 32-Bit Windows Base APIs
#[repr(C)] #[derive(Clone, Copy, Debug)]
pub struct SECURITY_ATTRIBUTES {
pub nLength: ::DWORD, | pub lpSecurityDescriptor: ::LPVOID,
pub bInheritHandle: ::BOOL,
}
pub type PSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES;
pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES;
#[repr(C)] #[derive(Clone, Copy, Debug)]
pub struct OVERLAPPED {
pub Internal: ::ULONG_PTR,
pub InternalHigh: ::ULONG_PTR... | random_line_split | |
metrics_test.rs | #![cfg(test)]
extern crate ferrous_threads;
use ferrous_threads::thread_pool::ThreadPool;
use std::sync::atomic::{Ordering, AtomicBool};
use std::sync::{Arc};
use std::process::{Stdio, Command};
use std::net::UdpSocket;
const ADDR: &'static str = "localhost:60000";
#[test]
fn main_metrics_test() | let res = socket.recv_from(&mut buf);
assert!(res.is_ok());
test_done.store(true, Ordering::SeqCst);
test_passed.store(true, Ordering::SeqCst);
})).unwrap_or_else(|e| panic!("{}", e));
let child = Command::new("cargo")
.arg("run")
.arg(ADDR)
.stderr(Stdio::... | {
let mut pool = ThreadPool::new(2, 2);
let test_thread = pool.thread().unwrap_or_else(|e| panic!("{}", e));
let timer_thread = pool.thread().unwrap_or_else(|e| panic!("{}", e));
let reg_interval = 10;
let done = Arc::new(AtomicBool::new(false));
let test_done = done.clone();
let timer_done... | identifier_body |
metrics_test.rs | #![cfg(test)]
extern crate ferrous_threads;
use ferrous_threads::thread_pool::ThreadPool;
use std::sync::atomic::{Ordering, AtomicBool};
use std::sync::{Arc};
use std::process::{Stdio, Command};
use std::net::UdpSocket;
const ADDR: &'static str = "localhost:60000";
#[test]
fn main_metrics_test() {
let mut pool... | assert!(passed.load(Ordering::SeqCst));
} | .output().unwrap_or_else(|e| panic!("{}", e)); | random_line_split |
metrics_test.rs | #![cfg(test)]
extern crate ferrous_threads;
use ferrous_threads::thread_pool::ThreadPool;
use std::sync::atomic::{Ordering, AtomicBool};
use std::sync::{Arc};
use std::process::{Stdio, Command};
use std::net::UdpSocket;
const ADDR: &'static str = "localhost:60000";
#[test]
fn | () {
let mut pool = ThreadPool::new(2, 2);
let test_thread = pool.thread().unwrap_or_else(|e| panic!("{}", e));
let timer_thread = pool.thread().unwrap_or_else(|e| panic!("{}", e));
let reg_interval = 10;
let done = Arc::new(AtomicBool::new(false));
let test_done = done.clone();
let timer_d... | main_metrics_test | identifier_name |
metrics_test.rs | #![cfg(test)]
extern crate ferrous_threads;
use ferrous_threads::thread_pool::ThreadPool;
use std::sync::atomic::{Ordering, AtomicBool};
use std::sync::{Arc};
use std::process::{Stdio, Command};
use std::net::UdpSocket;
const ADDR: &'static str = "localhost:60000";
#[test]
fn main_metrics_test() {
let mut pool... |
::std::thread::yield_now();
}
let pid = child.id();
let _output = Command::new("pkill")
.arg("-TERM")
.arg("-P")
.arg(format!("{}", pid))
.output().unwrap_or_else(|e| panic!("{}", e));
assert!(passed.load(Ordering::SeqCst));
}
| {
break
} | conditional_block |
settings.rs | use console;
use std::marker::PhantomData;
use sdl2::keyboard::Keycode;
// Might just rename this to settings.rs
pub const R_MAX_FPS: console::CVar<i64> = console::CVar {
ty: PhantomData,
name: "r_max_fps",
description: "fps_max caps the maximum FPS for the rendering engine",
mutable: true,
seriali... |
pub fn get_by_keycode(keycode: Keycode, console: &console::Console) -> Option<Stevenkey> {
for steven_key in Stevenkey::values() {
if keycode as i64 == *console.get(steven_key.get_cvar()) {
return Some(steven_key)
}
}
None
}
pub fn get_cvar(... | {
vec!(Stevenkey::Forward, Stevenkey::Backward, Stevenkey::Left,
Stevenkey::Right, Stevenkey::OpenInv, Stevenkey::Sneak,
Stevenkey::Sprint, Stevenkey::Jump)
} | identifier_body |
settings.rs | use console;
use std::marker::PhantomData;
use sdl2::keyboard::Keycode;
// Might just rename this to settings.rs
pub const R_MAX_FPS: console::CVar<i64> = console::CVar {
ty: PhantomData,
name: "r_max_fps",
description: "fps_max caps the maximum FPS for the rendering engine",
mutable: true,
seriali... | (keycode: Keycode, console: &console::Console) -> Option<Stevenkey> {
for steven_key in Stevenkey::values() {
if keycode as i64 == *console.get(steven_key.get_cvar()) {
return Some(steven_key)
}
}
None
}
pub fn get_cvar(&self) -> console::CVar<i64... | get_by_keycode | identifier_name |
settings.rs | use console;
use std::marker::PhantomData;
use sdl2::keyboard::Keycode;
// Might just rename this to settings.rs
pub const R_MAX_FPS: console::CVar<i64> = console::CVar {
ty: PhantomData,
name: "r_max_fps",
description: "fps_max caps the maximum FPS for the rendering engine",
mutable: true,
seriali... | ($keycode:ident, $name:expr, $description:expr) => (console::CVar {
ty: PhantomData,
name: $name,
description: $description,
mutable: true,
serializable: true,
default: &|| Keycode::$keycode as i64
})
}
pub const CL_KEYBIND_FORWARD: console::CVar<i64> = create_ke... | macro_rules! create_keybind { | random_line_split |
webglbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use crate::dom::bindings::codegen::Bindings:... |
pub fn is_attached(&self) -> bool {
self.attached_counter.get()!= 0
}
pub fn increment_attached_counter(&self) {
self.attached_counter.set(
self.attached_counter
.get()
.checked_add(1)
.expect("refcount overflowed"),
);
... | {
if self.target.get().map_or(false, |t| t != target) {
return Err(WebGLError::InvalidOperation);
}
self.target.set(Some(target));
Ok(())
} | identifier_body |
webglbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use crate::dom::bindings::codegen::Bindings:... |
pub fn decrement_attached_counter(&self) {
self.attached_counter.set(
self.attached_counter
.get()
.checked_sub(1)
.expect("refcount underflowed"),
);
if self.is_deleted() {
self.delete();
}
}
pub fn usage... | );
} | random_line_split |
webglbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use crate::dom::bindings::codegen::Bindings:... | (&self) -> bool {
self.attached_counter.get()!= 0
}
pub fn increment_attached_counter(&self) {
self.attached_counter.set(
self.attached_counter
.get()
.checked_add(1)
.expect("refcount overflowed"),
);
}
pub fn decrement_... | is_attached | identifier_name |
syntax-extension-with-dll-deps-2.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let answer = other::the_answer();
MacExpr::new(quote_expr!(cx, $answer))
} | identifier_body | |
syntax-extension-with-dll-deps-2.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #![feature(macro_registrar, quote, globs)]
extern crate other = "syntax-extension-with-dll-deps-1";
extern crate syntax;
use syntax::ast::{Name, TokenTree, Item, MetaItem};
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token;
#[macro_registrar]
pub fn macro_registrar(register: |Name, Syntax... |
#![crate_type = "dylib"] | random_line_split |
syntax-extension-with-dll-deps-2.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (register: |Name, SyntaxExtension|) {
register(token::intern("foo"),
NormalTT(box BasicMacroExpander {
expander: expand_foo,
span: None,
},
None));
}
fn expand_foo(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-> Box<MacResult> {
let answer = other... | macro_registrar | identifier_name |
sepcomp-unwind.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 ... |
// Test unwinding through multiple compilation units.
// According to acrichto, in the distant past `ld -r` (which is used during
// linking when codegen-units > 1) was known to produce object files with
// damaged unwinding tables. This may be related to GNU binutils bug #6893
// ("Partial linking results in corrup... | // ignore-emscripten no threads support | random_line_split |
sepcomp-unwind.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 ... | () -> usize { 0 }
mod a {
pub fn f() {
panic!();
}
}
mod b {
pub fn g() {
::a::f();
}
}
fn main() {
thread::spawn(move|| { ::b::g() }).join().unwrap_err();
}
| pad | identifier_name |
sepcomp-unwind.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 ... |
}
mod b {
pub fn g() {
::a::f();
}
}
fn main() {
thread::spawn(move|| { ::b::g() }).join().unwrap_err();
}
| {
panic!();
} | identifier_body |
main.rs | use std::env; // cool as shizzle
fn find(haystack: &str, needle: char) -> Option<usize> {
for (offset, c) in haystack.char_indices() {
if c == needle {
return Some(offset); // Some is a "value" constructor for Option type
}
}
None
}
/*
fn main() {
let mut argval = env::args... | {
let x = "6";
match add_one_to_number_str(x) {
Ok(j) => println!("Six plus one is: {}", j),
Err(err) => println!("Error: {}", err),
}
} | identifier_body | |
main.rs | use std::env; // cool as shizzle
fn find(haystack: &str, needle: char) -> Option<usize> {
for (offset, c) in haystack.char_indices() {
if c == needle {
return Some(offset); // Some is a "value" constructor for Option type
}
}
None
}
/*
fn main() {
let mut argval = env::args... | () {
let x = "6";
match add_one_to_number_str(x) {
Ok(j) => println!("Six plus one is: {}", j),
Err(err) => println!("Error: {}", err),
}
}
| main | identifier_name |
main.rs | use std::env; // cool as shizzle
fn find(haystack: &str, needle: char) -> Option<usize> {
for (offset, c) in haystack.char_indices() {
if c == needle {
return Some(offset); // Some is a "value" constructor for Option type
}
}
None
}
/*
fn main() {
let mut argval = env::args... | */ // Doesn't work for case analysis, map is always with some
/*
fn main() {
let file_name = "foobarbaz.rs";
match find (file_name, '.') {
None => println!("None"),
Some(i) => println!("File extension: {}", &file_name[i+1..]), // Once again the documentation shows indexing the string... strang... | fn extension(file_name: &str) -> Option<&str> {
find(file_name, '.').map(|i| &file_name[i+1]..)
} | random_line_split |
clean.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
#[derive(RustcDecodable)]
struct | {
flag_package: Option<String>,
flag_target: Option<String>,
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Remove artifacts that cargo has generated in the past
Usage:
cargo clean [options]
Option... | Options | identifier_name |
clean.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
#[derive(RustcDecodable)]
struct Options {
flag_package: Option<String>, | flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Remove artifacts that cargo has generated in the past
Usage:
cargo clean [options]
Options:
-h, --help Print this message
-p SPEC, --package SPEC Package to clean artifacts for
--manifest-path PATH Path to the mani... | flag_target: Option<String>,
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool, | random_line_split |
rect.rs | use std::ops::Add;
#[derive(Default, Copy, Clone, Debug)]
pub struct Point { | }
#[derive(Default, Debug, Copy, Clone)]
pub struct Rect {
pub x: i32,
pub y: i32,
pub w: u32,
pub h: u32,
}
impl Rect {
pub fn intersects(&self, other: &Rect) -> bool {
self.x < other.x + other.w as i32
&& self.x + self.w as i32 > other.x
&& self.y < other.y + othe... | pub x: i32,
pub y: i32, | random_line_split |
rect.rs | use std::ops::Add;
#[derive(Default, Copy, Clone, Debug)]
pub struct Point {
pub x: i32,
pub y: i32,
}
#[derive(Default, Debug, Copy, Clone)]
pub struct | {
pub x: i32,
pub y: i32,
pub w: u32,
pub h: u32,
}
impl Rect {
pub fn intersects(&self, other: &Rect) -> bool {
self.x < other.x + other.w as i32
&& self.x + self.w as i32 > other.x
&& self.y < other.y + other.h as i32
&& self.h as i32 + self.y > other.... | Rect | identifier_name |
mod.rs | use gl;
use gl::types::*;
use glutin;
use glutin::GlContext;
use game_state;
use game_state::state::SceneGraph;
use game_state::winit;
use game_state::Renderer;
use game_state::input;
use std::sync::{Arc, Mutex};
use game_state::thing::CameraFacet;
use game_state::Identity;
use std::collections::VecDeque;
pub st... | }
}
fn render(&mut self, camera: &CameraFacet) {
unsafe {
gl::Clear(gl::COLOR_BUFFER_BIT);
}
loop {
match self.render_layer_queue.pop_front() {
Some(layer) => {
//TODO : gather needed resources from the layer and ren... | {
let context = glutin::ContextBuilder::new();
let el = glutin::EventsLoop::new();
let gl_window = glutin::GlWindow::new(window.clone(), context, &el).unwrap();
unsafe {
gl_window.make_current().unwrap();
}
unsafe {
gl::load_with(|symbol| gl_win... | identifier_body |
mod.rs | use gl;
use gl::types::*;
use glutin;
use glutin::GlContext;
use game_state;
use game_state::state::SceneGraph;
use game_state::winit;
use game_state::Renderer;
use game_state::input;
use std::sync::{Arc, Mutex};
use game_state::thing::CameraFacet;
use game_state::Identity;
use std::collections::VecDeque;
pub st... | (
window: winit::WindowBuilder,
events_loop: Arc<Mutex<Option<winit::event::EventsLoop<()>>>>,
) -> Self {
let context = glutin::ContextBuilder::new();
let el = glutin::EventsLoop::new();
let gl_window = glutin::GlWindow::new(window.clone(), context, &el).unwrap();
... | new | identifier_name |
mod.rs | use gl;
use gl::types::*;
use glutin;
use glutin::GlContext;
use game_state;
use game_state::state::SceneGraph;
use game_state::winit;
use game_state::Renderer;
use game_state::input;
use std::sync::{Arc, Mutex};
use game_state::thing::CameraFacet;
use game_state::Identity;
use std::collections::VecDeque;
pub st... | }
OpenGLRenderer {
id: game_state::create_next_identity(),
gl_window: gl_window,
el,
render_layer_queue: VecDeque::new(),
}
}
fn render(&mut self, camera: &CameraFacet) {
unsafe {
gl::Clear(gl::COLOR_BUFFER_BIT);
... | random_line_split | |
root.rs | . If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of DOM objects whose lifetime is entirely controlled by
//! the whims of the SpiderMonkey garbage collector. The types in th... | None => {
let inner = cb();
self.set(Some(&inner));
inner
},
}
}
/// Retrieve a copy of the inner optional `Dom<T>` as `LayoutDom<T>`.
/// For use by layout, which can't use safe types like Temporary.
#[allow(unrooted_must_... | debug_assert!(thread_state::get().is_script());
match self.get() {
Some(inner) => inner, | random_line_split |
root.rs | If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of DOM objects whose lifetime is entirely controlled by
//! the whims of the SpiderMonkey garbage collector. The types in thi... |
}
impl<T: DomObject> Dom<T> {
/// Create a Dom<T> from a &T
#[allow(unrooted_must_root)]
pub fn from_ref(obj: &T) -> Dom<T> {
debug_assert!(thread_state::get().is_script());
Dom {
ptr: ptr::NonNull::from(obj),
}
}
}
impl<T: DomObject> Deref for Dom<T> {
type Ta... | {
debug_assert!(thread_state::get().is_layout());
LayoutDom {
ptr: self.ptr.clone(),
}
} | identifier_body |
root.rs | If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of DOM objects whose lifetime is entirely controlled by
//! the whims of the SpiderMonkey garbage collector. The types in thi... | (&mut self) {
unsafe {
(*self.root_list).unroot(self.value.stable_trace_object());
}
}
}
/// A rooted reference to a DOM object.
pub type DomRoot<T> = Root<Dom<T>>;
impl<T: Castable> DomRoot<T> {
/// Cast a DOM object root upwards to one of the interfaces it derives from.
pub f... | drop | identifier_name |
testcase_empty.rs | // https://rustbyexample.com/generics/bounds/testcase_empty.html
// http://rust-lang-ja.org/rust-by-example/generics/bounds/testcase_empty.html
struct Cardinal;
struct BlueJay;
struct Turkey;
trait Red {}
trait Blue {}
impl Red for Cardinal {}
impl Blue for BlueJay {}
// These functions are only valid for types whi... | <T: Red>(_: &T) -> &'static str { "red" }
fn blue<T: Blue>(_: &T) -> &'static str { "blue" }
fn main() {
let cardinal = Cardinal;
let blue_jay = BlueJay;
let _turkey = Turkey;
// `red()` won't work on a blue jay nor vice versa
// because of the bounds.
println!("A cardinal is {}", red(&card... | red | identifier_name |
testcase_empty.rs | // https://rustbyexample.com/generics/bounds/testcase_empty.html
// http://rust-lang-ja.org/rust-by-example/generics/bounds/testcase_empty.html
struct Cardinal;
struct BlueJay;
struct Turkey;
trait Red {}
trait Blue {}
impl Red for Cardinal {}
impl Blue for BlueJay {}
// These functions are only valid for types whi... | } | // error[E0277]: the trait bound `Turkey: Red` is not satisfied | random_line_split |
solver052.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::bit::BitSet;
use euler::algorithm::long::{digits_sum, from_digits, to_digits};
use euler::Solver;
// It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, bu... | (&self) -> isize {
// start on the number 123...n and do a preliminary filter based on the sum of the digits
(from_digits((1..=self.n).rev().collect())..).filter(|&candidate| {
let candidate_sum = digits_sum(candidate);
(2..=self.n).map(|m| m * candidate).all(|multiple| digits_su... | solve | identifier_name |
solver052.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::bit::BitSet;
use euler::algorithm::long::{digits_sum, from_digits, to_digits};
use euler::Solver;
// It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, bu... |
}
impl Solver for Solver052 {
fn solve(&self) -> isize {
// start on the number 123...n and do a preliminary filter based on the sum of the digits
(from_digits((1..=self.n).rev().collect())..).filter(|&candidate| {
let candidate_sum = digits_sum(candidate);
(2..=self.n).map... | {
Solver052 { n: 6 }
} | identifier_body |
solver052.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use euler::algorithm::bit::BitSet;
use euler::algorithm::long::{digits_sum, from_digits, to_digits};
use euler::Solver;
// It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, bu... | }
}
impl Solver for Solver052 {
fn solve(&self) -> isize {
// start on the number 123...n and do a preliminary filter based on the sum of the digits
(from_digits((1..=self.n).rev().collect())..).filter(|&candidate| {
let candidate_sum = digits_sum(candidate);
(2..=self.n... | Solver052 { n: 6 } | random_line_split |
edit_channel.rs | use internal::prelude::*;
/// A builder to edit a [`GuildChannel`] for use via [`GuildChannel::edit`]
///
/// Defaults are not directly provided by the builder itself.
///
/// # Examples
///
/// Edit a channel, providing a new name and topic:
///
/// ```rust,ignore
/// // assuming a channel has already been bound
/// ... |
/// The topic of the channel. Can be empty.
///
/// Must be between 0 and 1024 characters long.
///
/// This is for [text] channels only.
///
/// [text]:../model/enum.ChannelType.html#variant.Text
pub fn topic(mut self, topic: &str) -> Self {
self.0.insert(
"topic".... | {
self.0.insert(
"position".to_owned(),
Value::Number(Number::from(position)),
);
self
} | identifier_body |
edit_channel.rs | use internal::prelude::*;
/// A builder to edit a [`GuildChannel`] for use via [`GuildChannel::edit`]
///
/// Defaults are not directly provided by the builder itself.
///
/// # Examples
///
/// Edit a channel, providing a new name and topic:
///
/// ```rust,ignore
/// // assuming a channel has already been bound
/// ... | Value::Number(Number::from(position)),
);
self
}
/// The topic of the channel. Can be empty.
///
/// Must be between 0 and 1024 characters long.
///
/// This is for [text] channels only.
///
/// [text]:../model/enum.ChannelType.html#variant.Text
pub fn t... | random_line_split | |
edit_channel.rs | use internal::prelude::*;
/// A builder to edit a [`GuildChannel`] for use via [`GuildChannel::edit`]
///
/// Defaults are not directly provided by the builder itself.
///
/// # Examples
///
/// Edit a channel, providing a new name and topic:
///
/// ```rust,ignore
/// // assuming a channel has already been bound
/// ... | (mut self, user_limit: u64) -> Self {
self.0.insert(
"user_limit".to_owned(),
Value::Number(Number::from(user_limit)),
);
self
}
}
| user_limit | identifier_name |
matrix.rs | use std::ops::{Index, IndexMut};
/// A type shorthand for the lookup key we'll be using, a width/height tuple.
type Idx = (usize, usize);
/// A 2-dimensional matrix of f64 values.
#[derive(Clone, Debug)]
pub struct Matrix {
width: usize,
contents: Vec<f64>,
}
impl Matrix {
/// Creates a new Matrix with t... | let mut matrix = Matrix::new(1024, 768);
// Index<Idx>
assert_eq!(matrix[(1023, 767)], 0.0);
// IndexMut<Idx>
matrix[(12, 24)] = 123.456;
assert_eq!(matrix[(12, 24)], 123.456);
assert_eq!(matrix[(24, 12)], 0.0);
}
} | random_line_split | |
matrix.rs | use std::ops::{Index, IndexMut};
/// A type shorthand for the lookup key we'll be using, a width/height tuple.
type Idx = (usize, usize);
/// A 2-dimensional matrix of f64 values.
#[derive(Clone, Debug)]
pub struct Matrix {
width: usize,
contents: Vec<f64>,
}
impl Matrix {
/// Creates a new Matrix with t... | (&self, (width, height): Idx) -> &Self::Output {
&self.contents[height * self.width + width]
}
}
impl IndexMut<Idx> for Matrix {
fn index_mut(&mut self, (width, height): Idx) -> &mut Self::Output {
&mut self.contents[height * self.width + width]
}
}
#[cfg(test)]
mod test {
use super::*... | index | identifier_name |
matrix.rs | use std::ops::{Index, IndexMut};
/// A type shorthand for the lookup key we'll be using, a width/height tuple.
type Idx = (usize, usize);
/// A 2-dimensional matrix of f64 values.
#[derive(Clone, Debug)]
pub struct Matrix {
width: usize,
contents: Vec<f64>,
}
impl Matrix {
/// Creates a new Matrix with t... |
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_matrix() {
let mut matrix = Matrix::new(1024, 768);
// Index<Idx>
assert_eq!(matrix[(1023, 767)], 0.0);
// IndexMut<Idx>
matrix[(12, 24)] = 123.456;
assert_eq!(matrix[(12, 24)], 123.456);
ass... | {
&mut self.contents[height * self.width + width]
} | identifier_body |
video_mode.rs | //
// 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, copy, modify, merge, publish, distribute, sublicense, and/or sell... | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang | random_line_split | |
video_mode.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// 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, c... | () -> VideoMode {
VideoMode {
width: 640i32,
height: 480i32
}
}
} | new | identifier_name |
gnu_hash.rs | //! A Gnu Hash table as 4 sections:
//!
//! 1. Header
//! 2. Bloom Filter
//! 3. Hash Buckets
//! 4. Chains
//!
//! The header has is an array of four `u32`s:
//!
//! 1. nbuckets
//! 2. symndx
//! 3. maskwords
//! 4. shift2
//!
//! See more:
//! * http://www.linker-aliens.org/blogs/ali/entry/gnu_hash_elf_secti... | /// # Safety
///
/// This function creates a `GnuHash` directly from a raw pointer
pub unsafe fn from_raw_table(
hashtab: &'a [u8],
dynsyms: &'a [Sym],
) -> Result<Self, &'static str> {
if hashtab.as_ptr() as usi... | impl<'a> GnuHash<'a> {
/// Initialize a GnuHash from a pointer to `.hash` (or `.gnu.hash`) section
/// and total number of dynamic symbols. | random_line_split |
gnu_hash.rs | //! A Gnu Hash table as 4 sections:
//!
//! 1. Header
//! 2. Bloom Filter
//! 3. Hash Buckets
//! 4. Chains
//!
//! The header has is an array of four `u32`s:
//!
//! 1. nbuckets
//! 2. symndx
//! 3. maskwords
//! 4. shift2
//!
//! See more:
//! * http://www.linker-aliens.org/blogs/ali/entry/gnu_hash_elf_secti... | (symbol: &str) -> u32 {
const HASH_SEED: u32 = 5381;
symbol.bytes().fold(HASH_SEED, |hash, b| {
hash.wrapping_mul(33).wrapping_add(u32::from(b))
})
}
#[cfg(test)]
mod tests {
use super::hash;
#[test]
fn test_hash() {
assert_eq!(hash(""), 0x0000_1505);
assert_eq!(hash("pr... | hash | identifier_name |
gnu_hash.rs | //! A Gnu Hash table as 4 sections:
//!
//! 1. Header
//! 2. Bloom Filter
//! 3. Hash Buckets
//! 4. Chains
//!
//! The header has is an array of four `u32`s:
//!
//! 1. nbuckets
//! 2. symndx
//! 3. maskwords
//! 4. shift2
//!
//! See more:
//! * http://www.linker-aliens.org/blogs/ali/entry/gnu_hash_elf_secti... |
}
macro_rules! elf_gnu_hash_impl {
($IntTy:ty) => {
use crate::elf::sym::Sym;
use crate::strtab::Strtab;
use core::fmt;
use core::mem;
use core::slice;
const INT_SIZE: usize = mem::size_of::<$IntTy>();
const U32_SIZE: usize = mem::size_of::<u32>();
... | {
assert_eq!(hash(""), 0x0000_1505);
assert_eq!(hash("printf"), 0x156b_2bb8);
assert_eq!(hash("exit"), 0x7c96_7e3f);
assert_eq!(hash("syscall"), 0xbac2_12a0);
assert_eq!(hash("flapenguin.me"), 0x8ae9_f18e);
} | identifier_body |
intrinsic_inject.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 ... | (sess: Session, crate: @ast::crate) -> @ast::crate {
let intrinsic_module = @(include_str!("intrinsic.rs").to_owned());
let item = parse::parse_item_from_source_str(~"<intrinsic>",
intrinsic_module,
/*bad*/copy se... | inject_intrinsic | identifier_name |
intrinsic_inject.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 ... | } | },
.. /*bad*/copy crate.node
},
.. /*bad*/copy *crate
} | random_line_split |
intrinsic_inject.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
};
let items = vec::append(~[item], crate.node.module.items);
@spanned {
node: ast::crate_ {
module: ast::_mod {
items: items,
.. /*bad*/copy crate.node.module
},
.. /*bad*/copy crate.node
},
.. /*bad*/copy *crat... | {
let intrinsic_module = @(include_str!("intrinsic.rs").to_owned());
let item = parse::parse_item_from_source_str(~"<intrinsic>",
intrinsic_module,
/*bad*/copy sess.opts.cfg,
... | identifier_body |
eventdispatcher.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 devtools_traits::{StartedTimelineMarker, TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::Exc... | {
Canceled,
NotCanceled
}
// https://dom.spec.whatwg.org/#concept-event-dispatch
pub fn dispatch_event(target: &EventTarget,
target_override: Option<&EventTarget>,
event: &Event) -> EventStatus {
assert!(!event.dispatching());
assert!(event.initialized());
... | EventStatus | identifier_name |
eventdispatcher.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 devtools_traits::{StartedTimelineMarker, TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::Exc... | if!event.bubbles() {
return;
}
// Step 9.1.
event.set_phase(EventPhase::Bubbling);
// Step 9.2.
for object in event_path {
invoke(window.r(), object, event, Some(ListenerPhase::Bubbling));
if event.stop_propagation() {
return;
}
}
}
#[derive(Par... | assert!(!event.stop_propagation());
assert!(!event.stop_immediate());
| random_line_split |
eventdispatcher.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 devtools_traits::{StartedTimelineMarker, TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::Exc... |
// Step 9.1.
event.set_phase(EventPhase::Bubbling);
// Step 9.2.
for object in event_path {
invoke(window.r(), object, event, Some(ListenerPhase::Bubbling));
if event.stop_propagation() {
return;
}
}
}
#[derive(PartialEq)]
pub enum EventStatus {
Canceled,
... | {
return;
} | conditional_block |
example3.rs | // This file is released into Public Domain.
use crate::common::*;
use gnuplot::*;
use std::vec::Vec;
mod common;
| let h = 61;
let mut z1 = Vec::with_capacity((w * h) as usize);
for i in 0..h
{
for j in 0..w
{
let y = 8.0 * (i as f64) / h as f64 - 4.0;
let x = 8.0 * (j as f64) / w as f64 - 4.0;
z1.push(x.cos() * y.cos() / ((x * x + y * y).sqrt() + 1.0));
}
}
let mut fg = Figure::new();
fg.axes3d()
.set_tit... | fn example(c: Common)
{
let w = 61; | random_line_split |
example3.rs | // This file is released into Public Domain.
use crate::common::*;
use gnuplot::*;
use std::vec::Vec;
mod common;
fn example(c: Common)
| .set_y_label("Y", &[])
.set_z_label("Z", &[])
.set_z_range(Fix(-1.0), Fix(1.0))
.set_z_ticks(Some((Fix(1.0), 1)), &[Mirror(false)], &[])
.set_view(45.0, 45.0);
c.show(&mut fg, "example3_1");
let mut fg = Figure::new();
fg.axes3d()
.set_title("Map fg3.2", &[])
.surface(z1.iter(), w, h, None, &[])
.... | {
let w = 61;
let h = 61;
let mut z1 = Vec::with_capacity((w * h) as usize);
for i in 0..h
{
for j in 0..w
{
let y = 8.0 * (i as f64) / h as f64 - 4.0;
let x = 8.0 * (j as f64) / w as f64 - 4.0;
z1.push(x.cos() * y.cos() / ((x * x + y * y).sqrt() + 1.0));
}
}
let mut fg = Figure::new();
fg.axes... | identifier_body |
example3.rs | // This file is released into Public Domain.
use crate::common::*;
use gnuplot::*;
use std::vec::Vec;
mod common;
fn example(c: Common)
{
let w = 61;
let h = 61;
let mut z1 = Vec::with_capacity((w * h) as usize);
for i in 0..h
{
for j in 0..w
{
let y = 8.0 * (i as f64) / h as f64 - 4.0;
let x = 8.0 * ... | ()
{
Common::new().map(|c| example(c));
}
| main | identifier_name |
return_option.rs | use sys::*;
/// Holds result and indicates the overall success or failure of a function.
#[derive(Debug)]
#[must_use]
pub enum ReturnOption<T, E = ()> {
/// The function has been executed successfully. Holds result.
Success(T),
/// The function has been executed successfully. There have been warnings. Hold... | SQL_ERROR => ReturnOption::Error(()),
SQL_NO_DATA => ReturnOption::NoData(()),
other => panic!("Unexpected SQLRETURN value: {:?}", other),
}
}
} | match source {
SQL_SUCCESS => ReturnOption::Success(()),
SQL_SUCCESS_WITH_INFO => ReturnOption::Info(()), | random_line_split |
return_option.rs | use sys::*;
/// Holds result and indicates the overall success or failure of a function.
#[derive(Debug)]
#[must_use]
pub enum ReturnOption<T, E = ()> {
/// The function has been executed successfully. Holds result.
Success(T),
/// The function has been executed successfully. There have been warnings. Hold... | (source: SQLRETURN) -> ReturnOption<()> {
match source {
SQL_SUCCESS => ReturnOption::Success(()),
SQL_SUCCESS_WITH_INFO => ReturnOption::Info(()),
SQL_ERROR => ReturnOption::Error(()),
SQL_NO_DATA => ReturnOption::NoData(()),
other => panic!("Unexpect... | from | identifier_name |
prompt.rs | use super::super::{Capture, Function, Shell};
use parser::shell_expand::expand_string;
use std::io::Read;
use std::process;
use sys;
pub(crate) fn prompt(shell: &mut Shell) -> String {
if shell.flow_control.level == 0 {
let rprompt = match prompt_fn(shell) {
Some(prompt) => prompt,
... | Err(why) => {
eprintln!("ion: fork error: {}", why);
}
}
// Ensure that the parent retains ownership of the terminal before exiting.
let _ = sys::tcsetpgrp(sys::STDIN_FILENO, process::id());
output
}
| {
let function = match shell.functions.get("PROMPT") {
Some(func) => func as *const Function,
None => return None,
};
let mut output = None;
match shell.fork(Capture::Stdout, |child| unsafe {
let _ = function.read().execute(child, &["ion"]);
}) {
Ok(result) => {
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.