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 |
|---|---|---|---|---|
color.rs | use crate::rank::Rank;
use std::ops::Not;
/// Represent a color.
#[derive(PartialOrd, PartialEq, Eq, Copy, Clone, Debug, Hash)]
pub enum Color {
White,
Black,
}
/// How many colors are there?
pub const NUM_COLORS: usize = 2;
/// List all colors
pub const ALL_COLORS: [Color; NUM_COLORS] = [Color::White, Color:... | (self) -> Color {
if self == Color::White {
Color::Black
} else {
Color::White
}
}
}
| not | identifier_name |
cred_def.rs | use super::constants::{CRED_DEF, GET_CRED_DEF};
use super::response::{GetReplyResultV1, ReplyType};
use super::super::anoncreds::credential_definition::{CredentialDefinitionData, CredentialDefinitionV1, SignatureType, CredentialDefinitionId};
use super::super::anoncreds::schema::SchemaId;
use super::super::ledger::requ... | else { Some(data.tag.clone()) },
_type: CRED_DEF.to_string()
}
}
}
#[derive(Serialize, PartialEq, Debug)]
pub struct GetCredDefOperation {
#[serde(rename = "type")]
pub _type: String,
#[serde(rename = "ref")]
pub _ref: i32,
pub signature_type: String,
pub origin: ShortD... | { None } | conditional_block |
cred_def.rs | use super::constants::{CRED_DEF, GET_CRED_DEF};
use super::response::{GetReplyResultV1, ReplyType};
use super::super::anoncreds::credential_definition::{CredentialDefinitionData, CredentialDefinitionV1, SignatureType, CredentialDefinitionId};
use super::super::anoncreds::schema::SchemaId;
use super::super::ledger::requ... | (data: CredentialDefinitionV1) -> CredDefOperation {
CredDefOperation {
_ref: data.schema_id.0.parse::<i32>().unwrap_or(0),
signature_type: data.signature_type.to_str().to_string(),
data: data.value,
tag: if ProtocolVersion::is_node_1_3() { None } else { Some(data... | new | identifier_name |
cred_def.rs | use super::constants::{CRED_DEF, GET_CRED_DEF};
use super::response::{GetReplyResultV1, ReplyType}; | use super::super::crypto::did::ShortDidValue;
#[derive(Serialize, Debug)]
pub struct CredDefOperation {
#[serde(rename = "ref")]
pub _ref: i32,
pub data: CredentialDefinitionData,
#[serde(rename = "type")]
pub _type: String,
pub signature_type: String,
#[serde(skip_serializing_if = "Option:... | use super::super::anoncreds::credential_definition::{CredentialDefinitionData, CredentialDefinitionV1, SignatureType, CredentialDefinitionId};
use super::super::anoncreds::schema::SchemaId;
use super::super::ledger::request::ProtocolVersion; | random_line_split |
daytime4_a_synchronous_udp_daytime_client.rs | extern crate asyncio; | use std::process::exit;
use std::str;
use asyncio::*;
use asyncio::ip::*;
fn main() {
let host = args().nth(1).unwrap_or_else(|| {
println!("usage: client <host>");
exit(1);
});
let ctx = &IoContext::new().unwrap();
let ep = UdpResolver::new(ctx)
.resolve((Udp::v4(), host, "day... |
use std::env::args; | random_line_split |
daytime4_a_synchronous_udp_daytime_client.rs | extern crate asyncio;
use std::env::args;
use std::process::exit;
use std::str;
use asyncio::*;
use asyncio::ip::*;
fn main() | let (len, ep) = soc.receive_from(&mut recv_buf, 0).unwrap();
println!("receive from {}", ep);
println!("{}", str::from_utf8(&recv_buf[..len]).unwrap());
}
| {
let host = args().nth(1).unwrap_or_else(|| {
println!("usage: client <host>");
exit(1);
});
let ctx = &IoContext::new().unwrap();
let ep = UdpResolver::new(ctx)
.resolve((Udp::v4(), host, "daytime"))
.unwrap()
.next()
.unwrap();
let soc = UdpSocke... | identifier_body |
daytime4_a_synchronous_udp_daytime_client.rs | extern crate asyncio;
use std::env::args;
use std::process::exit;
use std::str;
use asyncio::*;
use asyncio::ip::*;
fn | () {
let host = args().nth(1).unwrap_or_else(|| {
println!("usage: client <host>");
exit(1);
});
let ctx = &IoContext::new().unwrap();
let ep = UdpResolver::new(ctx)
.resolve((Udp::v4(), host, "daytime"))
.unwrap()
.next()
.unwrap();
let soc = UdpSocket... | main | identifier_name |
sub.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 ... |
(_, &ty::ty_bot) => {
Err(ty::terr_sorts(expected_found(self, a, b)))
}
_ => {
super_tys(self, a, b)
}
}
}
fn fn_sigs(&self, a: &ty::FnSig, b: &ty::FnSig) -> cres<ty::FnSig> {
debug!("fn_sigs(a={}, b={})",
... | Ok(a)
} | random_line_split |
sub.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 regions(&self, a: ty::Region, b: ty::Region) -> cres<ty::Region> {
debug!("{}.regions({}, {})",
self.tag(),
a.repr(self.fields.infcx.tcx),
b.repr(self.fields.infcx.tcx));
self.fields.infcx.region_vars.make_subregion(Subtype(self.trace()), a, b);
... | {
let opp = CombineFields {
a_is_expected: !self.fields.a_is_expected,
..self.fields.clone()
};
Sub(opp).regions(b, a)
} | identifier_body |
sub.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 ... | (&self, a: FnStyle, b: FnStyle) -> cres<FnStyle> {
self.lub().fn_styles(a, b).compare(b, || {
ty::terr_fn_style_mismatch(expected_found(self, a, b))
})
}
fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<Onceness> {
self.lub().oncenesses(a, b).compare(b, || {
... | fn_styles | identifier_name |
link.rs | #![crate_name = "uu_link"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uucore;
us... | (args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(err) => panic!("{}", err),
... | uumain | identifier_name |
link.rs | #![crate_name = "uu_link"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
|
use std::fs::hard_link;
use std::io::Write;
use std::path::Path;
static NAME: &'static str = "link";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.o... | extern crate getopts;
#[macro_use]
extern crate uucore; | random_line_split |
link.rs | #![crate_name = "uu_link"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uucore;
us... | {0} [OPTIONS] FILE1 FILE2
Create a link named FILE2 to FILE1.", NAME, VERSION);
println!("{}", opts.usage(&msg));
if matches.free.len()!= 2 {
return 1;
}
return 0;
}
let old = Path::new(&matches.free[0]);
let new = Path::new(&matches.free[1]);
match hard... | {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_pre... | identifier_body |
lib.rs | /*
The library provides a simple datastructure to access geolocated labels with an additional
elimination time t and a label size factor. The library provides method to query a set of
such labels with a bounding box and a minimum elimination time.
Copyright (C) {2017} {Filip Krumpe <filip.krumpe@fmi.u... | #[no_mangle]
pub extern "C" fn get_data(ds: &DataStructure,
min_t: f64,
min_x: f64,
max_x: f64,
min_y: f64,
max_y: f64)
-> C_Result {
use std::mem::forget... | ///
/// The ownership of the result returned by this function is passed to the caller.
/// To safely deallocate the result pass it to the function `free_result`. | random_line_split |
lib.rs | /*
The library provides a simple datastructure to access geolocated labels with an additional
elimination time t and a label size factor. The library provides method to query a set of
such labels with a bounding box and a minimum elimination time.
Copyright (C) {2017} {Filip Krumpe <filip.krumpe@fmi.u... |
};
let bb = primitives::bbox::BBox::new(min_x, min_y, max_x, max_y);
let r = pst.get(&bb, min_t);
result = Vec::with_capacity(r.len());
for e in &r {
let c_label = CString::new(e.get_label().as_str()).unwrap();
result.push(C_Label {
x: e.get_x(),
... | {
result = Vec::with_capacity(0);
let len = 0;
pointer = result.as_mut_ptr();
forget(result);
return C_Result {
size: len,
data: pointer,
};
} | conditional_block |
lib.rs | /*
The library provides a simple datastructure to access geolocated labels with an additional
elimination time t and a label size factor. The library provides method to query a set of
such labels with a bounding box and a minimum elimination time.
Copyright (C) {2017} {Filip Krumpe <filip.krumpe@fmi.u... | () {
let instance = random_label_instance(TEST_SIZE);
let mut data_box = bbox::BBox::new_empty();
for l in &instance {
data_box.add_to_box(l);
}
let pskdt = pst_3d::Pst3d::new(instance.clone());
let mut rng = rand::thread_rng();
for _ in 0..TEST_... | randomized_test | identifier_name |
exec.rs | use ffi::SystemError;
use core::ThreadCallStack;
use reactor::Reactor;
use std::io;
use std::sync::{Arc, Condvar, Mutex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::collections::VecDeque;
use std::ops::Deref;
pub trait Perform: Send +'static {
fn perform(self: Box<Self>, this: &mut Threa... | else if self.stopped() {
return None;
}
queue = self.0.condvar.wait(queue).unwrap();
}
}
pub fn post<F>(&self, func: F)
where
F: FnOnce(&IoContext) + Send +'static,
{
self.do_post(func)
}
fn push(&self, exec: Box<Exec>) {
... | {
return Some(exec);
} | conditional_block |
exec.rs | use ffi::SystemError;
use core::ThreadCallStack;
use reactor::Reactor;
use std::io;
use std::sync::{Arc, Condvar, Mutex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::collections::VecDeque;
use std::ops::Deref;
pub trait Perform: Send +'static {
fn perform(self: Box<Self>, this: &mut Threa... |
let mut this = ThreadIoContext::new(self, Default::default());
this.init();
self.push(Box::new(ExecutorRef(&*self.0)));
while let Some(exec) = self.pop() {
exec.call_box(&mut this);
while!this.pending_queue.is_empty() {
let vec: Vec<_> = this.pen... | return;
} | random_line_split |
exec.rs | use ffi::SystemError;
use core::ThreadCallStack;
use reactor::Reactor;
use std::io;
use std::sync::{Arc, Condvar, Mutex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::collections::VecDeque;
use std::ops::Deref;
pub trait Perform: Send +'static {
fn perform(self: Box<Self>, this: &mut Threa... | (&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
pub unsafe trait AsIoContext {
fn as_ctx(&self) -> &IoContext;
}
pub struct IoContextWork(IoContext);
impl IoContextWork {
pub fn new(ctx: &IoContext) -> Self {
(ctx.0).outstanding_work.fetch_add(1, Ordering::Relaxed);
... | eq | identifier_name |
mod.rs | use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use std::error::Error;
use std::io::prelude::*;
use crate::deserialize::{self, FromSql, FromSqlRow};
use crate::expression::AsExpression;
use crate::pg::{Pg, PgValue};
use crate::serialize::{self, IsNull, Output, ToSql};
use crate::sql_types;
#[cfg(feature ... | <W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
let sign = match *self {
PgNumeric::Positive {.. } => 0,
PgNumeric::Negative {.. } => 0x4000,
PgNumeric::NaN => 0xC000,
};
let empty_vec = Vec::new();
let digits = match *self {
... | to_sql | identifier_name |
mod.rs | use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use std::error::Error;
use std::io::prelude::*;
use crate::deserialize::{self, FromSql, FromSqlRow};
use crate::expression::AsExpression;
use crate::pg::{Pg, PgValue};
use crate::serialize::{self, IsNull, Output, ToSql};
use crate::sql_types;
#[cfg(feature ... | };
out.write_u16::<NetworkEndian>(digits.len() as u16)?;
out.write_i16::<NetworkEndian>(weight)?;
out.write_u16::<NetworkEndian>(sign)?;
out.write_u16::<NetworkEndian>(scale)?;
for digit in digits.iter() {
out.write_i16::<NetworkEndian>(*digit)?;
}
... | {
let sign = match *self {
PgNumeric::Positive { .. } => 0,
PgNumeric::Negative { .. } => 0x4000,
PgNumeric::NaN => 0xC000,
};
let empty_vec = Vec::new();
let digits = match *self {
PgNumeric::Positive { ref digits, .. } | PgNumeric::Negati... | identifier_body |
mod.rs | use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use std::error::Error;
use std::io::prelude::*;
use crate::deserialize::{self, FromSql, FromSqlRow};
use crate::expression::AsExpression;
use crate::pg::{Pg, PgValue};
use crate::serialize::{self, IsNull, Output, ToSql};
use crate::sql_types;
#[cfg(feature ... | }),
0x4000 => Ok(PgNumeric::Negative {
weight: weight,
scale: scale,
digits: digits,
}),
0xC000 => Ok(PgNumeric::NaN),
invalid => Err(Box::new(InvalidNumericSign(invalid))),
}
}
}
impl ToSql<sql_type... | 0 => Ok(PgNumeric::Positive {
weight: weight,
scale: scale,
digits: digits, | random_line_split |
port.rs | #![allow(dead_code)]
/// Primary structure for communicating with serial ports.
pub struct Serial {
port: u16
}
impl Serial {
/// Create an instance of `Serial` from a 16-bit address.
pub fn new(port: u16) -> Serial {
Serial { port: port }
}
/// Write a single byte to the serial port.
pub fn | (&self, byte: u8) {
unsafe { outport_b(byte, self.port) };
}
/// Read a single byte from the serial port.
/// On the event no byte is available, `0` will be returned.
pub fn inb(&self) -> u8 {
unsafe { inport_b(self.port) }
}
}
/// Implementation of Write for the Serial port.
impl ::core::fmt::Write... | outb | identifier_name |
port.rs | #![allow(dead_code)]
/// Primary structure for communicating with serial ports.
pub struct Serial {
port: u16
}
impl Serial {
/// Create an instance of `Serial` from a 16-bit address.
pub fn new(port: u16) -> Serial {
Serial { port: port }
}
/// Write a single byte to the serial port.
pub fn outb(&se... |
}
/// Implementation of Write for the Serial port.
impl ::core::fmt::Write for Serial {
fn write_str(&mut self, src: &str) -> ::core::fmt::Result {
for byte in src.bytes() {
self.outb(byte);
}
Ok(())
}
}
/// Externally defined in `port.s`, assembly label
/// which writes a byte to the giv... | {
unsafe { inport_b(self.port) }
} | identifier_body |
port.rs | #![allow(dead_code)]
/// Primary structure for communicating with serial ports.
pub struct Serial { | /// Create an instance of `Serial` from a 16-bit address.
pub fn new(port: u16) -> Serial {
Serial { port: port }
}
/// Write a single byte to the serial port.
pub fn outb(&self, byte: u8) {
unsafe { outport_b(byte, self.port) };
}
/// Read a single byte from the serial port.
/// On the event ... | port: u16
}
impl Serial { | random_line_split |
region-object-lifetime-5.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... | () {}
| main | identifier_name |
region-object-lifetime-5.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... | {} | identifier_body | |
region-object-lifetime-5.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 owned_receiver(x: Box<Foo>) -> &'static () {
x.borrowed() //~ ERROR `*x` does not live long enough
}
fn main() {} | fn borrowed<'a>(&'a self) -> &'a ();
}
// Here, the object is bounded by an anonymous lifetime and returned
// as `&'static`, so you get an error. | 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/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces... | extern crate tenacious;
use rustc::lint::LintPassObject;
use rustc::plugin::Registry;
use syntax::ext::base::{Decorator, Modifier};
use syntax::parse::token::intern;
// Public for documentation to show up
/// Handles the auto-deriving for `#[jstraceable]`
pub mod jstraceable;
/// Autogenerates implementations of Ref... | extern crate rustc;
| 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/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces... | {
reg.register_syntax_extension(intern("dom_struct"), Modifier(box jstraceable::expand_dom_struct));
reg.register_syntax_extension(intern("jstraceable"), Decorator(box jstraceable::expand_jstraceable));
reg.register_syntax_extension(intern("_generate_reflector"), Decorator(box reflector::expand_reflector));... | 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/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces... | (reg: &mut Registry) {
reg.register_syntax_extension(intern("dom_struct"), Modifier(box jstraceable::expand_dom_struct));
reg.register_syntax_extension(intern("jstraceable"), Decorator(box jstraceable::expand_jstraceable));
reg.register_syntax_extension(intern("_generate_reflector"), Decorator(box reflector... | plugin_registrar | identifier_name |
webhook.rs | //! Webhook model and implementations.
use super::{
id::{
ChannelId,
GuildId,
WebhookId
},
user::User
};
#[cfg(feature = "model")]
use builder::ExecuteWebhook;
#[cfg(feature = "model")]
use internal::prelude::*;
#[cfg(feature = "model")]
use std::mem;
#[cfg(feature = "model")]
use ... | /// use serenity::http;
///
/// let id = 245037420704169985;
/// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
///
/// let mut webhook = http::get_webhook_with_token(id, token)
/// .expect("valid webhook");
///
/// let _ = webhook.execute(fals... | /// # Examples
///
/// Execute a webhook with message content of `test`:
///
/// ```rust,no_run | random_line_split |
webhook.rs | //! Webhook model and implementations.
use super::{
id::{
ChannelId,
GuildId,
WebhookId
},
user::User
};
#[cfg(feature = "model")]
use builder::ExecuteWebhook;
#[cfg(feature = "model")]
use internal::prelude::*;
#[cfg(feature = "model")]
use std::mem;
#[cfg(feature = "model")]
use ... | (&mut self, name: Option<&str>, avatar: Option<&str>) -> Result<()> {
if name.is_none() && avatar.is_none() {
return Ok(());
}
let mut map = Map::new();
if let Some(avatar) = avatar {
map.insert(
"avatar".to_string(),
if avatar.is... | edit | identifier_name |
webhook.rs | //! Webhook model and implementations.
use super::{
id::{
ChannelId,
GuildId,
WebhookId
},
user::User
};
#[cfg(feature = "model")]
use builder::ExecuteWebhook;
#[cfg(feature = "model")]
use internal::prelude::*;
#[cfg(feature = "model")]
use std::mem;
#[cfg(feature = "model")]
use ... | ,
);
}
if let Some(name) = name {
map.insert("name".to_string(), Value::String(name.to_string()));
}
match http::edit_webhook_with_token(self.id.0, &self.token, &map) {
Ok(replacement) => {
mem::replace(self, replacement);
... | {
Value::String(avatar.to_string())
} | conditional_block |
webhook.rs | //! Webhook model and implementations.
use super::{
id::{
ChannelId,
GuildId,
WebhookId
},
user::User
};
#[cfg(feature = "model")]
use builder::ExecuteWebhook;
#[cfg(feature = "model")]
use internal::prelude::*;
#[cfg(feature = "model")]
use std::mem;
#[cfg(feature = "model")]
use ... |
}
#[cfg(feature = "model")]
impl WebhookId {
/// Retrieves the webhook by the Id.
///
/// **Note**: Requires the [Manage Webhooks] permission.
///
/// [Manage Webhooks]:../../model/permissions/struct.Permissions.html#associatedconstant.MANAGE_WEBHOOKS
#[inline]
#[deprecated(since = "0.5.8"... | {
match http::get_webhook_with_token(self.id.0, &self.token) {
Ok(replacement) => {
let _ = mem::replace(self, replacement);
Ok(())
},
Err(why) => Err(why),
}
} | identifier_body |
powerpc64le_unknown_linux_gnu.rs | // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
let mut base = super::linux_base::opts();
base.cpu = "ppc64le".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "powerpc64le-unknown-linux-gnu".to_string(),
target_endian: "lit... | identifier_body | |
powerpc64le_unknown_linux_gnu.rs | // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // except according to those terms.
use spec::{LinkerFlavor, Target, TargetResult};
pub fn target() -> TargetResult {
let mut base = super::linux_base::opts();
base.cpu = "ppc64le".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.max_atomic_width = So... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
powerpc64le_unknown_linux_gnu.rs | // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () -> TargetResult {
let mut base = super::linux_base::opts();
base.cpu = "ppc64le".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "powerpc64le-unknown-linux-gnu".to_string(),
... | target | identifier_name |
engine.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt::Debug;
use crate::*;
// FIXME: Revisit the remaining types and methods on KvEngine. Some of these are
// here for lack of somewhere better to put them at the time of writing.
// Consider moving everything into other traits and making Kv... | + Sync
+ Clone
+ Debug
+ Unpin
+'static
{
/// A consistent read-only snapshot of the database
type Snapshot: Snapshot;
/// Create a snapshot
fn snapshot(&self) -> Self::Snapshot;
/// Syncs any writes to disk
fn sync(&self) -> Result<()>;
/// Flush metrics to prometheus... | + PerfContextExt
+ MiscExt
+ Send | random_line_split |
engine.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt::Debug;
use crate::*;
// FIXME: Revisit the remaining types and methods on KvEngine. Some of these are
// here for lack of somewhere better to put them at the time of writing.
// Consider moving everything into other traits and making Kv... | (&self, _instance: &str) {}
/// Reset internal statistics
fn reset_statistics(&self) {}
/// Cast to a concrete engine type
///
/// This only exists as a temporary hack during refactoring.
/// It cannot be used forever.
fn bad_downcast<T:'static>(&self) -> &T;
}
| flush_metrics | identifier_name |
engine.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt::Debug;
use crate::*;
// FIXME: Revisit the remaining types and methods on KvEngine. Some of these are
// here for lack of somewhere better to put them at the time of writing.
// Consider moving everything into other traits and making Kv... |
/// Cast to a concrete engine type
///
/// This only exists as a temporary hack during refactoring.
/// It cannot be used forever.
fn bad_downcast<T:'static>(&self) -> &T;
}
| {} | identifier_body |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | else {Inconsistent}
}
}
}
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.tail.get();
while!cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = Box::from_raw(cur);
... | {Empty} | conditional_block |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | * those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of Dmitry Vyukov.
*/
//! A mostly lock-free multi-producer, single consumer queue.
//!
//! This module contains an implementation of a concurrent MPSC queue. This
//! queue can be used to share dat... | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are | random_line_split |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | <T> {
next: AtomicPtr<Node<T>>,
value: Option<T>,
}
/// The multi-producer single-consumer structure. This is not cloneable, but it
/// may be safely shared so long as it is guaranteed that there is only one
/// popper at a time (many pushers are allowed).
pub struct Queue<T> {
head: AtomicPtr<Node<T>>,
... | Node | identifier_name |
contenttest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... |
fn find_tests(config: Config) -> Vec<TestDescAndFn> {
let files_res = fs::readdir(&Path::new(config.source_dir));
let mut files = match files_res {
Ok(files) => files,
_ => panic!("Error reading directory."),
};
files.retain(|file| file.extension_str() == Some("html") );
return fil... | {
TestOpts {
filter: config.filter,
run_ignored: false,
run_tests: true,
run_benchmarks: false,
logfile: None,
nocapture: false,
color: AutoColor,
}
} | identifier_body |
contenttest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | (config: Config) -> Vec<TestDescAndFn> {
let files_res = fs::readdir(&Path::new(config.source_dir));
let mut files = match files_res {
Ok(files) => files,
_ => panic!("Error reading directory."),
};
files.retain(|file| file.extension_str() == Some("html") );
return files.iter().map(|... | find_tests | identifier_name |
contenttest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | {
Ok(p) => p,
_ => panic!("Unable to spawn process."),
};
let mut output = Vec::new();
loop {
let byte = prc.stdout.as_mut().unwrap().read_byte();
match byte {
Ok(byte) => {
print!("{}", byte as char);
output.push(byte);
... | .args(args.as_slice())
.stdin(Ignored)
.stdout(stdout)
.stderr(stderr)
.spawn() | random_line_split |
extension_class_impl.rs | /*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
| #[serde(rename = "_links", skip_serializing_if = "Option::is_none")]
pub _links: Option<Box<crate::models::ExtensionClassImpllinks>>,
#[serde(rename = "classes", skip_serializing_if = "Option::is_none")]
pub classes: Option<Vec<String>>,
}
impl ExtensionClassImpl {
pub fn new() -> ExtensionClassImp... |
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct ExtensionClassImpl {
#[serde(rename = "_class", skip_serializing_if = "Option::is_none")]
pub _class: Option<String>, | random_line_split |
extension_class_impl.rs | /*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct | {
#[serde(rename = "_class", skip_serializing_if = "Option::is_none")]
pub _class: Option<String>,
#[serde(rename = "_links", skip_serializing_if = "Option::is_none")]
pub _links: Option<Box<crate::models::ExtensionClassImpllinks>>,
#[serde(rename = "classes", skip_serializing_if = "Option::is_none... | ExtensionClassImpl | identifier_name |
mod.rs | //!
//! Module which provide handlers to send the log records to the appropriate destination.
//!
pub mod streams;
use handlers::streams::file::FileHandler;
use handlers::streams::net::TCPHandler;
use handlers::streams::stdout::StdoutHandler;
use log::LogLevelFilter;
use ExtendedLogRecord;
use std::sync::Mutex;
/// A... | (hdlr: FileHandler) -> Handler {
Handler::File(hdlr)
}
}
impl From<TCPHandler> for Handler {
fn from(hdlr: TCPHandler) -> Handler {
Handler::TCP(hdlr)
}
}
///
/// A dummy handler which does nothing
///
pub struct NullHandler;
impl Filter for NullHandler {
/// Always accept the record
... | from | identifier_name |
mod.rs | //!
//! Module which provide handlers to send the log records to the appropriate destination.
//!
pub mod streams;
use handlers::streams::file::FileHandler;
use handlers::streams::net::TCPHandler;
use handlers::streams::stdout::StdoutHandler;
use log::LogLevelFilter;
use ExtendedLogRecord;
use std::sync::Mutex;
/// A... |
///
/// A dummy handler which does nothing
///
pub struct NullHandler;
impl Filter for NullHandler {
/// Always accept the record
fn filter(&self, record: &ExtendedLogRecord) -> bool { true }
}
impl Handle for NullHandler {
fn handle(&mut self, record: &ExtendedLogRecord) {}
fn emit(&mut self, record... | fn from(hdlr: TCPHandler) -> Handler {
Handler::TCP(hdlr)
}
} | random_line_split |
mutex.rs | use crate::detail::UntypedMutex;
use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
pub struct Mutex<T:?Sized> {
mutex: UntypedMutex,
data: UnsafeCell<T>,
}
unsafe impl<T:?Sized + Send> Send for Mutex<T> {}
unsafe impl<T:?Sized + Send> Sync for Mutex<T> {}
impl<T> Mu... | }
unsafe impl<'mutex, T:?Sized + Sync> Sync for MutexGuard<'mutex, T> {}
impl<'mutex, T:?Sized> Drop for MutexGuard<'mutex, T> {
fn drop(&mut self) {
self.mutex.mutex.unlock();
}
}
impl<'mutex, T:?Sized> Deref for MutexGuard<'mutex, T> {
type Target = T;
fn deref(&self) -> &T {
unsaf... | pub struct MutexGuard<'mutex, T: ?Sized + 'mutex> {
mutex: &'mutex Mutex<T>,
_pd: PhantomData<*mut T>, | random_line_split |
mutex.rs | use crate::detail::UntypedMutex;
use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
pub struct Mutex<T:?Sized> {
mutex: UntypedMutex,
data: UnsafeCell<T>,
}
unsafe impl<T:?Sized + Send> Send for Mutex<T> {}
unsafe impl<T:?Sized + Send> Sync for Mutex<T> {}
impl<T> Mu... | (&mut self) -> &mut T {
unsafe { &mut *self.mutex.data.get() }
}
}
| deref_mut | identifier_name |
mutex.rs | use crate::detail::UntypedMutex;
use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
pub struct Mutex<T:?Sized> {
mutex: UntypedMutex,
data: UnsafeCell<T>,
}
unsafe impl<T:?Sized + Send> Send for Mutex<T> {}
unsafe impl<T:?Sized + Send> Sync for Mutex<T> {}
impl<T> Mu... |
}
impl<'mutex, T:?Sized> DerefMut for MutexGuard<'mutex, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.mutex.data.get() }
}
}
| {
unsafe { &*self.mutex.data.get() }
} | identifier_body |
custom_table.rs | use std::convert::TryFrom;
use multihash::derive::Multihash;
use multihash::{Error, Hasher, MultihashDigest, MultihashGeneric, Sha2_256};
// You can implement a custom hasher. This is a SHA2 256-bit hasher that returns a hash that is
// truncated to 160 bits.
#[derive(Default, Debug)]
pub struct Sha2_256Truncated20(S... |
fn finalize(&mut self) -> &[u8] {
&self.0.finalize()[..20]
}
fn reset(&mut self) {
self.0.reset();
}
}
#[derive(Clone, Copy, Debug, Eq, Multihash, PartialEq)]
#[mh(alloc_size = 64)]
pub enum Code {
/// Example for using a custom hasher which returns truncated hashes
#[mh(code =... | {
self.0.update(input)
} | identifier_body |
custom_table.rs | use std::convert::TryFrom;
use multihash::derive::Multihash;
use multihash::{Error, Hasher, MultihashDigest, MultihashGeneric, Sha2_256};
// You can implement a custom hasher. This is a SHA2 256-bit hasher that returns a hash that is
// truncated to 160 bits.
#[derive(Default, Debug)]
pub struct Sha2_256Truncated20(S... | (&mut self, input: &[u8]) {
self.0.update(input)
}
fn finalize(&mut self) -> &[u8] {
&self.0.finalize()[..20]
}
fn reset(&mut self) {
self.0.reset();
}
}
#[derive(Clone, Copy, Debug, Eq, Multihash, PartialEq)]
#[mh(alloc_size = 64)]
pub enum Code {
/// Example for using ... | update | identifier_name |
custom_table.rs | use std::convert::TryFrom;
use multihash::derive::Multihash;
use multihash::{Error, Hasher, MultihashDigest, MultihashGeneric, Sha2_256};
// You can implement a custom hasher. This is a SHA2 256-bit hasher that returns a hash that is
// truncated to 160 bits.
#[derive(Default, Debug)]
pub struct Sha2_256Truncated20(S... | /// Example for using a custom hasher which returns truncated hashes
#[mh(code = 0x12, hasher = Sha2_256Truncated20)]
Sha2_256Truncated20,
/// Example for using a hasher with a bit size that is not exported by default
#[mh(code = 0xb219, hasher = multihash::Blake2bHasher::<25>)]
Blake2b200,
}
f... | }
#[derive(Clone, Copy, Debug, Eq, Multihash, PartialEq)]
#[mh(alloc_size = 64)]
pub enum Code { | random_line_split |
chanclient.rs | use std::sync::mpsc::{channel, Receiver, Sender};
use ndarray::Array2;
use super::Client;
use routing::{NodeHandle, EffectMeta, EffectId};
/// Client that turns all messages into an enum variant
/// and sends them accross a thread-safe channel.
#[derive(Debug)]
pub struct MpscClient {
tx: Sender<ClientMessage>,
... | fn node_id(&mut self, handle: &NodeHandle, id: &EffectId) {
self.send(ClientMessage::NodeId(*handle, id.clone()));
}
} | random_line_split | |
chanclient.rs | use std::sync::mpsc::{channel, Receiver, Sender};
use ndarray::Array2;
use super::Client;
use routing::{NodeHandle, EffectMeta, EffectId};
/// Client that turns all messages into an enum variant
/// and sends them accross a thread-safe channel.
#[derive(Debug)]
pub struct MpscClient {
tx: Sender<ClientMessage>,
... | (&self, msg: ClientMessage) {
trace!("Sending message to Client: {:?}", msg);
if let Err(msg) = self.tx.send(msg) {
warn!("Unable to send message to Client: {:?}", msg);
}
}
}
impl Client for MpscClient {
fn audio_rendered(&mut self, buffer: Array2<f32>, idx: u64) {
... | send | identifier_name |
chanclient.rs | use std::sync::mpsc::{channel, Receiver, Sender};
use ndarray::Array2;
use super::Client;
use routing::{NodeHandle, EffectMeta, EffectId};
/// Client that turns all messages into an enum variant
/// and sends them accross a thread-safe channel.
#[derive(Debug)]
pub struct MpscClient {
tx: Sender<ClientMessage>,
... |
fn node_id(&mut self, handle: &NodeHandle, id: &EffectId) {
self.send(ClientMessage::NodeId(*handle, id.clone()));
}
}
| {
self.send(ClientMessage::NodeMeta(*handle, meta.clone()));
} | identifier_body |
chanclient.rs | use std::sync::mpsc::{channel, Receiver, Sender};
use ndarray::Array2;
use super::Client;
use routing::{NodeHandle, EffectMeta, EffectId};
/// Client that turns all messages into an enum variant
/// and sends them accross a thread-safe channel.
#[derive(Debug)]
pub struct MpscClient {
tx: Sender<ClientMessage>,
... |
}
}
impl Client for MpscClient {
fn audio_rendered(&mut self, buffer: Array2<f32>, idx: u64) {
self.send(ClientMessage::AudioRendered(buffer, idx));
}
fn node_meta(&mut self, handle: &NodeHandle, meta: &EffectMeta) {
self.send(ClientMessage::NodeMeta(*handle, meta.clone()));
}
... | {
warn!("Unable to send message to Client: {:?}", msg);
} | conditional_block |
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/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... |
pub fn pinch_zoom_level(&self) -> f32 {
self.compositor.pinch_zoom_level()
}
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
pub fn setup_logging(&self) {
let constellation_chan = self.constellation_chan.clone();
log::set_logg... | {
self.compositor.repaint_synchronously()
} | 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/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... |
if let Some(url) = url {
constellation_chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap();
};
// channels to communicate with Service Worker Manager
let sw_senders = SWManagerSenders {
swmanager_sender: from_swmanager_sender,
resource_sender: resource_sender
};
(c... | {
// WebVR initialization
let (mut handler, sender) = WebVRCompositorHandler::new();
let webvr_thread = WebVRThread::spawn(constellation_chan.clone(), sender);
handler.set_webvr_thread_sender(webvr_thread.clone());
webrender.set_vr_compositor_handler(handler);
constellat... | conditional_block |
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/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... | (user_agent: Cow<'static, str>,
config_dir: Option<PathBuf>,
url: Option<ServoUrl>,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::Profi... | create_constellation | 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/. */
//! Servo, the mighty web browser engine from the future.
//!
//! This is a very simple library that wires all of ... | pub use gleam::gl;
pub use servo_config as config;
pub use servo_url as url;
/// The in-process interface to Servo.
///
/// It does everything necessary to render the web, primarily
/// orchestrating the interaction between JavaScript, CSS layout,
/// rendering, and the client window.
///
/// Clients create a `Browser... | random_line_split | |
term_weight.rs | use Term;
use query::Weight;
use core::SegmentReader;
use query::Scorer;
use postings::SegmentPostingsOption;
use postings::SegmentPostings;
use super::term_scorer::TermScorer;
use Result;
pub struct TermWeight {
pub num_docs: u32,
pub doc_freq: u32,
pub term: Term,
pub segment_postings_options: Segmen... |
}
| {
let field = self.term.field();
let fieldnorm_reader_opt = reader.get_fieldnorms_reader(field);
Ok(reader
.read_postings(&self.term, self.segment_postings_options)
.map(|segment_postings| {
TermScorer {
idf: self.... | identifier_body |
term_weight.rs | use Term;
use query::Weight;
use core::SegmentReader;
use query::Scorer;
use postings::SegmentPostingsOption;
use postings::SegmentPostings;
use super::term_scorer::TermScorer;
use Result;
pub struct TermWeight {
pub num_docs: u32,
pub doc_freq: u32,
pub term: Term,
pub segment_postings_options: Segmen... | 1.0 + (self.num_docs as f32 / (self.doc_freq as f32 + 1.0)).ln()
}
pub fn specialized_scorer<'a>(&'a self,
reader: &'a SegmentReader)
-> Result<TermScorer<SegmentPostings<'a>>> {
let field = self.term.field();
let field... | random_line_split | |
term_weight.rs | use Term;
use query::Weight;
use core::SegmentReader;
use query::Scorer;
use postings::SegmentPostingsOption;
use postings::SegmentPostings;
use super::term_scorer::TermScorer;
use Result;
pub struct | {
pub num_docs: u32,
pub doc_freq: u32,
pub term: Term,
pub segment_postings_options: SegmentPostingsOption,
}
impl Weight for TermWeight {
fn scorer<'a>(&'a self, reader: &'a SegmentReader) -> Result<Box<Scorer + 'a>> {
let specialized_scorer = try!(self.specialized_scorer(reader));
... | TermWeight | identifier_name |
test.rs | st functions, eliding any
// existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: &ParseSess,
cfg: &ast::CrateConfig,
krate: ast::Crate,
span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate {
/... | let sym = token::gensym_ident("__test_reexports");
let it = P(ast::Item {
ident: sym.clone(),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: ast::ItemMod(reexport_mod),
vis: ast::Public,
span: DUMMY_SP,
});
(it, sym)
}
fn generate_test_harness(sess: &P... | random_line_split | |
test.rs | t functions, eliding any
// existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: &ParseSess,
cfg: &ast::CrateConfig,
krate: ast::Crate,
span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate {
//... | (cx: &TestCtxt) -> P<ast::Expr> {
debug!("building test vector from {} tests", cx.testfns.len());
P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprAddrOf(ast::MutImmutable,
P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprVec(cx.testfns.iter()... | mk_test_descs | identifier_name |
test.rs | t functions, eliding any
// existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: &ParseSess,
cfg: &ast::CrateConfig,
krate: ast::Crate,
span_diagnostic: &diagnostic::SpanHandler) -> ast::Crate {
//... |
/*
We're going to be building a module that looks more or less like:
mod __test {
extern crate test (name = "test", vers = "...");
fn main() {
test::test_main_static(&::os::args()[], tests)
}
static tests : &'static [test::TestDescAndFn] = &[
... the list of tests in the crate...
];
}
*/
fn mk_s... | {
match i.attrs.iter().find(|attr| attr.check_name("should_fail")) {
Some(attr) => {
let msg = attr.meta_item_list()
.and_then(|list| list.iter().find(|mi| mi.check_name("expected")))
.and_then(|mi| mi.value_str());
ShouldFail::Yes(msg)
}
... | identifier_body |
source_map.rs | use std::slice::Iter;
use crate::base::pos::Line;
use crate::base::symbol::Symbol;
use crate::base::types::ArcType;
use crate::types::VmIndex;
#[derive(Debug, Default, Eq, PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serde_derive", derive(Deserialize, Serialize))]
pub struct SourceMap {
/// The index of the fi... |
#[derive(Debug, Default, Eq, PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serde_derive", derive(DeserializeState, SerializeState))]
#[cfg_attr(
feature = "serde_derive",
serde(
deserialize_state = "crate::serialization::DeSeed<'gc>",
de_parameters = "'gc"
)
)]
#[cfg_attr(
feature = "s... | random_line_split | |
source_map.rs | use std::slice::Iter;
use crate::base::pos::Line;
use crate::base::symbol::Symbol;
use crate::base::types::ArcType;
use crate::types::VmIndex;
#[derive(Debug, Default, Eq, PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serde_derive", derive(Deserialize, Serialize))]
pub struct SourceMap {
/// The index of the fi... |
}
/// Returns an iterator over the variables in scope at `instruction_index`
pub fn locals(&self, instruction_index: usize) -> LocalIter {
LocalIter {
locals: self.map.iter(),
instruction_index: instruction_index,
}
}
}
pub struct LocalIter<'a> {
locals: It... | {
local.end = instruction_index;
} | conditional_block |
source_map.rs | use std::slice::Iter;
use crate::base::pos::Line;
use crate::base::symbol::Symbol;
use crate::base::types::ArcType;
use crate::types::VmIndex;
#[derive(Debug, Default, Eq, PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serde_derive", derive(Deserialize, Serialize))]
pub struct SourceMap {
/// The index of the fi... | () -> SourceMap {
SourceMap { map: Vec::new() }
}
/// Defines the instruction at `instruction_index` to be at `current_line`.
/// This function must be called with indexes in increasing order
pub fn emit(&mut self, instruction_index: usize, current_line: Line) {
let last_emitted_line = ... | new | identifier_name |
timer.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 ... | /// timer.sleep(10); // block the task for awhile
///
/// let timeout = timer.oneshot(10);
/// // do some work
/// timeout.recv(); // wait for the timeout to expire
///
/// let periodic = timer.periodic(10);
/// loop {
/// periodic.recv();
/// // this loop is only executed once every 10ms
/// }
/// # }
/// ```
... | ///
/// let mut timer = Timer::new().unwrap(); | random_line_split |
timer.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 ... | (msecs: u64) {
let timer = Timer::new();
let mut timer = timer.ok().expect("timer::sleep: could not create a Timer");
timer.sleep(msecs)
}
impl Timer {
/// Creates a new timer which can be used to put the current task to sleep
/// for a number of milliseconds, or to possibly create channels which ... | sleep | identifier_name |
timer.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(test)]
mod test {
iotest!(fn test_io_timer_sleep_simple() {
let mut timer = Timer::new().unwrap();
timer.sleep(1);
})
iotest!(fn test_io_timer_sleep_oneshot() {
let mut timer = Timer::new().unwrap();
timer.oneshot(1).recv();
})
iotest!(fn test_io_timer_sle... | {
self.obj.period(msecs)
} | identifier_body |
db.rs | //! Db executor actor
use actix::prelude::*;
use diesel;
use diesel::prelude::*;
use diesel::result::Error;
use rand::{thread_rng, Rng, ThreadRng};
use std::io;
use models;
pub struct | {
conn: PgConnection,
rng: ThreadRng,
}
unsafe impl Send for DbExecutor {}
impl Actor for DbExecutor {
type Context = SyncContext<Self>;
}
impl DbExecutor {
pub fn new(db_url: &str) -> DbExecutor {
DbExecutor {
conn: PgConnection::establish(db_url)
.expect(&format!... | DbExecutor | identifier_name |
db.rs | //! Db executor actor
use actix::prelude::*;
use diesel;
use diesel::prelude::*;
use diesel::result::Error;
use rand::{thread_rng, Rng, ThreadRng};
use std::io;
use models;
pub struct DbExecutor {
conn: PgConnection,
rng: ThreadRng,
}
unsafe impl Send for DbExecutor {}
impl Actor for DbExecutor {
type C... | .filter(id.eq(w.id))
.set(randomnumber.eq(w.randomnumber))
.execute(&self.conn);
}
Ok(())
});
Ok(worlds)
}
}
pub struct TellFortune;
impl Message for TellFortune {
type Result = io::Result<Vec<models::Fortune>>;
... | for w in &worlds {
let _ = diesel::update(world) | random_line_split |
lib.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 mod char;
pub mod str {
pub use u_str::{UnicodeStr, SplitWhitespace, Words, Graphemes, GraphemeIndices};
pub use u_str::{utf8_char_width, is_utf16, Utf16Items, Utf16Item};
pub use u_str::{utf16_items, Utf16Encoder};
}
// For use in libcollections, not re-exported in libstd.
pub mod derived_property {
... | random_line_split | |
main.rs | event loop exits.
event_loop.run(move |event, _, control_flow| {
*control_flow = winit::event_loop::ControlFlow::Wait;
match event {
winit::event::Event::WindowEvent { event,.. } => match event {
winit::event::WindowEvent::CloseRequested => {
*contro... |
_ => {}
},
winit::event::Event::RedrawEventsCleared => {
renderer.render();
}
_ => {}
}
});
}
struct Renderer<B: hal::Backend> {
instance: Option<B::Instance>,
device: B::Device,
queue_group: QueueGroup<B>,
des... | {
println!("resized to {:?}", dims);
renderer.dimensions = window::Extent2D {
width: dims.width,
height: dims.height,
};
renderer.recreate_swapchain();
} | conditional_block |
main.rs | }
winit::event::WindowEvent::KeyboardInput {
input:
winit::event::KeyboardInput {
virtual_keycode: Some(winit::event::VirtualKeyCode::Escape),
..
},
..
... | recreate_swapchain | identifier_name | |
main.rs | renderer.recreate_swapchain();
}
_ => {}
},
winit::event::Event::RedrawEventsCleared => {
renderer.render();
}
_ => {}
}
});
}
struct Renderer<B: hal::Backend> {
instance: Option<B::Insta... | {
let caps = self.surface.capabilities(&self.adapter.physical_device);
let swap_config = window::SwapchainConfig::from_caps(&caps, self.format, self.dimensions);
println!("{:?}", swap_config);
let extent = swap_config.extent.to_extent();
self.viewport.rect.w = extent.width as _;... | identifier_body | |
main.rs |
for adapter in &adapters {
println!("{:?}", adapter.info);
}
let adapter = adapters.drain(..).next().unwrap();
let mut renderer = Renderer::new(instance, surface, adapter);
renderer.render();
// It is important that the closure move captures the Renderer,
// otherwise it will no... | let adapters = surface.enumerate_adapters();
(window, None, adapters, surface)
}; | random_line_split | |
x86_64_unknown_linux_gnu.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 ... | data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(),
llvm_target: "x86_64-unknown-linux-gnu".to_string(),
target_endian: "littl... | let mut base = super::linux_base::opts();
base.pre_link_args.push("-m64".to_string());
Target { | random_line_split |
x86_64_unknown_linux_gnu.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 ... | () -> Target {
let mut base = super::linux_base::opts();
base.pre_link_args.push("-m64".to_string());
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
s0:64:64-f80:128:1... | target | identifier_name |
x86_64_unknown_linux_gnu.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 mut base = super::linux_base::opts();
base.pre_link_args.push("-m64".to_string());
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
s0:64:64-f80:128:128-n8:16:32:6... | identifier_body | |
trianglesonarectangle.rs | use std::io;
use std::cmp::max;
fn get_line() -> Vec<i64> { |
fn main() {
let mut t = get_line()[0];
while t > 0 {
t -= 1;
let mut line = get_line();
let (w, h) = (line[0], line[1]);
line = get_line();
let (minx1, maxx1) = (line[1], line[line[0] as usize]);
line = get_line();
let (minx2, maxx2) = (line[1], line[line... | let mut input = String::new();
io::stdin().read_line(&mut input).expect("could not read line");
return input.trim().split_whitespace().map(|x| x.parse().unwrap()).collect::<Vec<_>>();
} | random_line_split |
trianglesonarectangle.rs | use std::io;
use std::cmp::max;
fn get_line() -> Vec<i64> {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("could not read line");
return input.trim().split_whitespace().map(|x| x.parse().unwrap()).collect::<Vec<_>>();
}
fn | () {
let mut t = get_line()[0];
while t > 0 {
t -= 1;
let mut line = get_line();
let (w, h) = (line[0], line[1]);
line = get_line();
let (minx1, maxx1) = (line[1], line[line[0] as usize]);
line = get_line();
let (minx2, maxx2) = (line[1], line[line[0] as u... | main | identifier_name |
trianglesonarectangle.rs | use std::io;
use std::cmp::max;
fn get_line() -> Vec<i64> |
fn main() {
let mut t = get_line()[0];
while t > 0 {
t -= 1;
let mut line = get_line();
let (w, h) = (line[0], line[1]);
line = get_line();
let (minx1, maxx1) = (line[1], line[line[0] as usize]);
line = get_line();
let (minx2, maxx2) = (line[1], line[lin... | {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("could not read line");
return input.trim().split_whitespace().map(|x| x.parse().unwrap()).collect::<Vec<_>>();
} | identifier_body |
member_churn.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | else {
Ok(NodeDuty::NoOp)
}
}
}
| {
info!(
"Registering wallet of node: {} (since not found in received state)",
node_id,
);
Ok(NodeDuty::Send(
Self::register_wallet(network_api, reward_key).await,
))
} | conditional_block |
member_churn.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | elder.meta_data.write().await.update(metadata).await?;
*elder.received_initial_sync.write().await = true;
let node_id = network_api.our_name().await;
let no_wallet_found = node_wallets.get(&node_id).is_none();
if no_wallet_found {
info!(
"Registerin... | .write()
.await
.set_node_wallet(*key, *wallet, *age)
}
// --------- merge in provided metadata --------- | random_line_split |
member_churn.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | let transfers = Transfers::new(replicas, store_cost);
//
// start handling node rewards
let section_funds = SectionFunds::KeepingNodeWallets(RewardWallets::new(BTreeMap::<
XorName,
(NodeAge, PublicKey),
>::new()));
self.role = Role::Elder(ElderRo... | {
self.used_space.reset().await?;
let adult_storage_info = AdultsStorageInfo::new();
let adult_reader = AdultReader::new(self.network_api.clone());
let capacity_reader = CapacityReader::new(adult_storage_info.clone(), adult_reader.clone());
let capacity_writer = CapacityWriter::... | identifier_body |
member_churn.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | (
elder: &ElderRole,
reward_key: PublicKey,
network_api: &Network,
node_wallets: BTreeMap<XorName, (NodeAge, PublicKey)>,
user_wallets: BTreeMap<PublicKey, ActorHistory>,
metadata: DataExchange,
) -> Result<NodeDuty> {
if *elder.received_initial_sync.read().aw... | synch_state | identifier_name |
script_msg.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 canvas_traits::CanvasMsg;
use euclid::point::Point2D;
use euclid::size::Size2D;
use ipc_channel::ipc::IpcSende... | {
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(PipelineId, AnimationState),
/// Requests that a new 2D canvas thread be created. (This is done in the constellation because
/// 2D canvases may use the GPU and we don't want to give untrusted content ac... | ScriptMsg | identifier_name |
script_msg.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 canvas_traits::CanvasMsg;
use euclid::point::Point2D;
use euclid::size::Size2D;
use ipc_channel::ipc::IpcSende... | /// Layout thread failure.
Failure(Failure),
/// Requests that the constellation inform the compositor of the a cursor change.
SetCursor(Cursor),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
}
/// Mess... | ChangeRunningAnimationsState(PipelineId, AnimationState), | random_line_split |
generic-static-methods.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_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), vec!(2,3,4));
} | random_line_split | |
generic-static-methods.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 ... | <U, F>(x: &Vec<T>, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
let mut r = Vec::new();
for elt in x {
r.push(f(elt));
}
r
}
}
pub fn main() {
assert_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), vec!(2,3,4));
}
| map_ | identifier_name |
generic-static-methods.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_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), vec!(2,3,4));
}
| {
let mut r = Vec::new();
for elt in x {
r.push(f(elt));
}
r
} | identifier_body |
render.rs | use syntax::ast::{Expr, Ident, Pat, Stmt, TokenTree};
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::ptr::P;
use maud;
#[derive(Copy, Clone)]
pub enum Escape {
PassThru,
Escape,
}
pub struct Renderer<'cx> {
pub cx: &'cx ExtCtxt<'cx>,
w: Ident... |
pub fn attribute_empty(&mut self, name: &str) {
self.push_str(" ");
self.push_str(name);
}
pub fn attribute_end(&mut self) {
self.push_str("\"");
}
pub fn element_open_end(&mut self) {
self.push_str(">");
}
pub fn element_close(&mut self, name: &str) {
... | {
self.push_str(" ");
self.push_str(name);
self.push_str("=\"");
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.