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 |
|---|---|---|---|---|
component.rs | use std::comm::{TryRecvError,Empty,Disconnected};
use std::fmt;
use message::{Message,MessageData};
use message::MessageData::{MsgStart};
#[deriving(PartialEq,Clone)]
pub enum ComponentType {
ManagerComponent,
ExtractorComponent,
AudioDecoderComponent,
VideoDecoderComponent,
ClockComponent,
Aud... | component_type: component_type,
mgr_sender: None,
receiver: receiver,
sender: Some(sender),
}
}
pub fn set_mgr_sender(&mut self, sender: Sender<Message>) {
self.mgr_sender= Some(sender);
}
pub fn take_sender(&mut self) -> Sender<Message> {
... |
impl ComponentStruct {
pub fn new(component_type: ComponentType) -> ComponentStruct {
let (sender, receiver) = channel::<Message>();
ComponentStruct { | random_line_split |
component.rs | use std::comm::{TryRecvError,Empty,Disconnected};
use std::fmt;
use message::{Message,MessageData};
use message::MessageData::{MsgStart};
#[deriving(PartialEq,Clone)]
pub enum ComponentType {
ManagerComponent,
ExtractorComponent,
AudioDecoderComponent,
VideoDecoderComponent,
ClockComponent,
Aud... |
pub fn set_mgr_sender(&mut self, sender: Sender<Message>) {
self.mgr_sender= Some(sender);
}
pub fn take_sender(&mut self) -> Sender<Message> {
self.sender.take().unwrap()
}
pub fn send(&self, to: ComponentType, msg:MessageData) -> bool {
match self.mgr_sender.as_ref().unwra... | {
let (sender, receiver) = channel::<Message>();
ComponentStruct {
component_type: component_type,
mgr_sender: None,
receiver: receiver,
sender: Some(sender),
}
} | identifier_body |
codemap.rs | Add<CharPos,CharPos> for CharPos {
fn add(&self, rhs: &CharPos) -> CharPos {
CharPos(self.to_uint() + rhs.to_uint())
}
}
impl Sub<CharPos,CharPos> for CharPos {
fn sub(&self, rhs: &CharPos) -> CharPos {
CharPos(self.to_uint() - rhs.to_uint())
}
}
/**
Spans represent a region of code, ... | return fm.clone();
}
}
panic!("asking for {} which we don't know about", filename);
}
pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
let idx = self.lookup_filemap_idx(bpos);
let fm = (*self.files.borrow())[idx].clone();
... | for fm in self.files.borrow().iter() {
if filename == fm.name.as_slice() { | random_line_split |
codemap.rs | <CharPos,CharPos> for CharPos {
fn add(&self, rhs: &CharPos) -> CharPos {
CharPos(self.to_uint() + rhs.to_uint())
}
}
impl Sub<CharPos,CharPos> for CharPos {
fn sub(&self, rhs: &CharPos) -> CharPos {
CharPos(self.to_uint() - rhs.to_uint())
}
}
/**
Spans represent a region of code, used... |
/// Converts an absolute BytePos to a CharPos relative to the filemap and above.
pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
let idx = self.lookup_filemap_idx(bpos);
let files = self.files.borrow();
let map = &(*files)[idx];
// The number of extra bytes d... | {
let idx = self.lookup_filemap_idx(bpos);
let fm = (*self.files.borrow())[idx].clone();
let offset = bpos - fm.start_pos;
FileMapAndBytePos {fm: fm, pos: offset}
} | identifier_body |
codemap.rs | <CharPos,CharPos> for CharPos {
fn add(&self, rhs: &CharPos) -> CharPos {
CharPos(self.to_uint() + rhs.to_uint())
}
}
impl Sub<CharPos,CharPos> for CharPos {
fn sub(&self, rhs: &CharPos) -> CharPos {
CharPos(self.to_uint() - rhs.to_uint())
}
}
/**
Spans represent a region of code, used... | else {
String::from_str(src.as_slice())
};
// Append '\n' in case it's not already there.
// This is a workaround to prevent CodeMap.lookup_filemap_idx from accidentally
// overflowing into the next filemap in case the last byte of span is also the last
// byte of f... | {
String::from_str(src.as_slice().slice_from(3))
} | conditional_block |
codemap.rs | <CharPos,CharPos> for CharPos {
fn add(&self, rhs: &CharPos) -> CharPos {
CharPos(self.to_uint() + rhs.to_uint())
}
}
impl Sub<CharPos,CharPos> for CharPos {
fn sub(&self, rhs: &CharPos) -> CharPos {
CharPos(self.to_uint() - rhs.to_uint())
}
}
/**
Spans represent a region of code, used... | { pub fm: Rc<FileMap>, pub pos: BytePos }
/// The syntax with which a macro was invoked.
#[deriving(Clone, Hash, Show)]
pub enum MacroFormat {
/// e.g. #[deriving(...)] <item>
MacroAttribute,
/// e.g. `format!()`
MacroBang
}
#[deriving(Clone, Hash, Show)]
pub struct NameAndSpan {
/// The name of ... | FileMapAndBytePos | identifier_name |
main.rs | extern crate report;
use report::report_builder::ReportBuilder;
use report::report_builder::html_report_builder::HtmlReportBuilder;
use report::report_builder::markdown_report_builder::MarkdownReportBuilder;
fn main() {
let html_report = HtmlReportBuilder::new()
.with_header("Solar Deities : Hindu Mytholog... | of Solar Deities.")
.with_paragraph("Ravana once went to challenge Surya, the Sun-God, to a fight. \
When he reached the Solar Region he saw that the sun was about to rise and sent an envoy \
to inform Surya of his arrival and the reason for his coming.")
.finish();
println!("... | random_line_split | |
main.rs | extern crate report;
use report::report_builder::ReportBuilder;
use report::report_builder::html_report_builder::HtmlReportBuilder;
use report::report_builder::markdown_report_builder::MarkdownReportBuilder;
fn | () {
let html_report = HtmlReportBuilder::new()
.with_header("Solar Deities : Hindu Mythological Story")
.with_paragraph("Let us enjoy reading this Hindu Mythological Story \
of Solar Deities.")
.with_paragraph("Ravana once went to challenge Surya, the Sun-God, to a fight. \
Whe... | main | identifier_name |
main.rs | extern crate report;
use report::report_builder::ReportBuilder;
use report::report_builder::html_report_builder::HtmlReportBuilder;
use report::report_builder::markdown_report_builder::MarkdownReportBuilder;
fn main() | .with_paragraph("Third paragraph")
.finish();
println!("{}", markdown_report);
}
| {
let html_report = HtmlReportBuilder::new()
.with_header("Solar Deities : Hindu Mythological Story")
.with_paragraph("Let us enjoy reading this Hindu Mythological Story \
of Solar Deities.")
.with_paragraph("Ravana once went to challenge Surya, the Sun-God, to a fight. \
Whe... | identifier_body |
compound3.rs | extern crate nalgebra as na;
use na::{Isometry3, Point3, RealField, Vector3};
use ncollide3d::shape::{Capsule, Compound, Cuboid, ShapeHandle};
use nphysics3d::force_generator::DefaultForceGeneratorSet;
use nphysics3d::joint::DefaultJointConstraintSet;
use nphysics3d::object::{
BodyPartHandle, ColliderDesc, Default... | for i in 0usize..num {
for j in 0usize..num {
for k in 0usize..num {
let x = r!(i as f64) * shift - centerx;
let y = r!(j as f64) * shift + centery;
let z = r!(k as f64) * shift - centerz;
// Build the rigid body.
l... | random_line_split | |
compound3.rs | extern crate nalgebra as na;
use na::{Isometry3, Point3, RealField, Vector3};
use ncollide3d::shape::{Capsule, Compound, Cuboid, ShapeHandle};
use nphysics3d::force_generator::DefaultForceGeneratorSet;
use nphysics3d::joint::DefaultJointConstraintSet;
use nphysics3d::object::{
BodyPartHandle, ColliderDesc, Default... |
let ground_handle = bodies.insert(Ground::new());
let co = ColliderDesc::new(ground_shape)
.translation(Vector3::y() * -ground_thickness)
.build(BodyPartHandle(ground_handle, 0));
colliders.insert(co);
/*
* U-shaped geometry.
*/
let large_rad = r!(2.5);
let small_rad = ... | {
/*
* World
*/
let mechanical_world = DefaultMechanicalWorld::new(Vector3::new(r!(0.0), r!(-9.81), r!(0.0)));
let geometrical_world = DefaultGeometricalWorld::new();
let mut bodies = DefaultBodySet::new();
let mut colliders = DefaultColliderSet::new();
let joint_constraints = DefaultJ... | identifier_body |
compound3.rs | extern crate nalgebra as na;
use na::{Isometry3, Point3, RealField, Vector3};
use ncollide3d::shape::{Capsule, Compound, Cuboid, ShapeHandle};
use nphysics3d::force_generator::DefaultForceGeneratorSet;
use nphysics3d::joint::DefaultJointConstraintSet;
use nphysics3d::object::{
BodyPartHandle, ColliderDesc, Default... | () {
let testbed = Testbed::<f32>::from_builders(0, vec![("Compound", init_world)]);
testbed.run()
}
| main | identifier_name |
bench-serde.rs | #![feature(test)]
extern crate quick_xml;
extern crate serde;
extern crate serde_xml_rs;
extern crate test;
use serde::Deserialize;
use test::Bencher;
const SOURCE: &str = include_str!("../../tests/sample_rss.xml");
#[derive(Debug, Deserialize)]
struct Rss {
channel: Channel,
}
#[derive(Debug, Deserialize)]
st... | b.iter(|| {
let rss: Rss = quick_xml::de::from_str(SOURCE).unwrap();
assert_eq!(rss.channel.items.len(), 99);
});
}
#[bench]
fn bench_serde_xml_rs(b: &mut Bencher) {
b.iter(|| {
let rss: Rss = serde_xml_rs::from_str(SOURCE).unwrap();
assert_eq!(rss.channel.items.len(), 99);
... | fn bench_serde_quick_xml(b: &mut Bencher) { | random_line_split |
bench-serde.rs | #![feature(test)]
extern crate quick_xml;
extern crate serde;
extern crate serde_xml_rs;
extern crate test;
use serde::Deserialize;
use test::Bencher;
const SOURCE: &str = include_str!("../../tests/sample_rss.xml");
#[derive(Debug, Deserialize)]
struct Rss {
channel: Channel,
}
#[derive(Debug, Deserialize)]
st... | {
url: String,
length: String,
#[serde(rename = "type")]
typ: String,
}
#[bench]
fn bench_serde_quick_xml(b: &mut Bencher) {
b.iter(|| {
let rss: Rss = quick_xml::de::from_str(SOURCE).unwrap();
assert_eq!(rss.channel.items.len(), 99);
});
}
#[bench]
fn bench_serde_xml_rs(b: &m... | Enclosure | identifier_name |
deriving-hash.rs | //
// 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
// except according to those terms.
use std::hash::{... | // 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. | random_line_split | |
deriving-hash.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 person1 = Person {
id: 5,
name: "Janet".to_string(),
phone: 555_666_7777
};
let person2 = Person {
id: 5,
name: "Bob".to_string(),
phone: 555_666_7777
};
assert!(hash(&person1) == hash(&person1));
assert!(hash(&person1)!= hash(&person2));
... | main | identifier_name |
issue_427.rs | #![cfg(feature = "derive")]
/// HID-IO Packet Buffer Struct
///
/// # Remarks
/// Used to store HID-IO data chunks. Will be chunked into individual packets on transmission.
#[repr(C)]
#[derive(PartialEq, Clone, Debug, bincode::Encode)] | /// Type of packet (Continued is automatically set if needed)
pub ptype: u32,
/// Packet Id
pub id: u32,
/// Packet length for serialization (in bytes)
pub max_len: u32,
/// Payload data, chunking is done automatically by serializer
pub data: [u8; H],
/// Set False if buffer is not c... | pub struct HidIoPacketBuffer<const H: usize> { | random_line_split |
issue_427.rs | #![cfg(feature = "derive")]
/// HID-IO Packet Buffer Struct
///
/// # Remarks
/// Used to store HID-IO data chunks. Will be chunked into individual packets on transmission.
#[repr(C)]
#[derive(PartialEq, Clone, Debug, bincode::Encode)]
pub struct HidIoPacketBuffer<const H: usize> {
/// Type of packet (Continued is... | {
SupportedIds = 0x00,
GetInfo = 0x01,
TestPacket = 0x02,
ResetHidIo = 0x03,
Reserved = 0x04, //... 0x0F
GetProperties = 0x10,
KeyState = 0x11,
KeyboardLayout = 0x12,
KeyLayout = 0x13,
KeyShapes = 0x14,
LedLayout = 0x15,
FlashMode = 0x16,
UnicodeText = 0x17,
Uni... | HidIoCommandId | identifier_name |
random.rs | extern crate rand;
use std::thread;
use rand::Rng;
static NTHREADS: i32 = 15;
const LEN: usize = 10000;
fn main() {
let mut child = vec![];
//writeln!(w, "{}: {}", i, test()).unwrap()
// println!("{}", i)
for i in 0..NTHREADS {
child.push(thread::spawn(move || {
println!("{}: {}", i, test())
}));
}
fo... |
}
counter
}
fn rand(t: &mut Vec<bool>) {
let mut rng = rand::thread_rng();
for _i in 0..t.len() {
let rand: usize = rng.gen_range(0, t.len());
t[rand] = true;
}
}
fn count(t: &Vec<bool>) -> (i32, i32) {
let mut tc = 0;
let mut fc = 0;
for x in 0..t.len() {
if t[x] {
tc += 1;
} else {
fc += 1;
... | {
break;
} | conditional_block |
random.rs | extern crate rand;
use std::thread;
use rand::Rng;
static NTHREADS: i32 = 15; | fn main() {
let mut child = vec![];
//writeln!(w, "{}: {}", i, test()).unwrap()
// println!("{}", i)
for i in 0..NTHREADS {
child.push(thread::spawn(move || {
println!("{}: {}", i, test())
}));
}
for c in child {
let _ = c.join();
}
}
fn test() -> i32 {
let mut t: Vec<bool> = Vec::new();
for _i ... | const LEN: usize = 10000; | random_line_split |
random.rs | extern crate rand;
use std::thread;
use rand::Rng;
static NTHREADS: i32 = 15;
const LEN: usize = 10000;
fn main() {
let mut child = vec![];
//writeln!(w, "{}: {}", i, test()).unwrap()
// println!("{}", i)
for i in 0..NTHREADS {
child.push(thread::spawn(move || {
println!("{}: {}", i, test())
}));
}
fo... |
fn count(t: &Vec<bool>) -> (i32, i32) {
let mut tc = 0;
let mut fc = 0;
for x in 0..t.len() {
if t[x] {
tc += 1;
} else {
fc += 1;
}
}
(tc, fc)
}
| {
let mut rng = rand::thread_rng();
for _i in 0..t.len() {
let rand: usize = rng.gen_range(0, t.len());
t[rand] = true;
}
} | identifier_body |
random.rs | extern crate rand;
use std::thread;
use rand::Rng;
static NTHREADS: i32 = 15;
const LEN: usize = 10000;
fn main() {
let mut child = vec![];
//writeln!(w, "{}: {}", i, test()).unwrap()
// println!("{}", i)
for i in 0..NTHREADS {
child.push(thread::spawn(move || {
println!("{}: {}", i, test())
}));
}
fo... | (t: &Vec<bool>) -> (i32, i32) {
let mut tc = 0;
let mut fc = 0;
for x in 0..t.len() {
if t[x] {
tc += 1;
} else {
fc += 1;
}
}
(tc, fc)
}
| count | identifier_name |
main.rs | //! main.rs - The entry point for the Ante compiler.
//! Handles command-line argument parsing and dataflow between
//! each compiler phase. The compiler as a whole is separated into
//! the following phases (in order):
//!
//! lexing -> parsing -> name resolution -> type inference -> lifetime inference -> codegen
//!
... | () {
let args = App::new("ante")
.version("0.1.1")
.author("Jake Fecher <jfecher11@gmail.com>")
.about("Compiler for the Ante programming language")
.arg(Arg::with_name("lex").long("lex").help("Lex the file and output the resulting list of tokens"))
.arg(Arg::with_name("parse").lo... | main | identifier_name |
main.rs | //! main.rs - The entry point for the Ante compiler.
//! Handles command-line argument parsing and dataflow between
//! each compiler phase. The compiler as a whole is separated into
//! the following phases (in order):
//!
//! lexing -> parsing -> name resolution -> type inference -> lifetime inference -> codegen
//!
... |
// Phase 5: Lifetime inference
util::timing::start_time("Lifetime Inference");
lifetimes::infer(ast, &mut cache);
if args.is_present("show-lifetimes") {
println!("{}", ast);
}
// Phase 6: Codegen
if error::get_error_count() == 0 {
llvm::run(&filename, ast, &mut cache,
... | {
return;
} | conditional_block |
main.rs | //! main.rs - The entry point for the Ante compiler.
//! Handles command-line argument parsing and dataflow between
//! each compiler phase. The compiler as a whole is separated into
//! the following phases (in order):
//!
//! lexing -> parsing -> name resolution -> type inference -> lifetime inference -> codegen
//!
... |
/// Convenience macro for unwrapping a Result or printing an error message and returning () on Err.
macro_rules! expect {( $result:expr, $fmt_string:expr $(, $($msg:tt)* )? ) => ({
match $result {
Ok(t) => t,
Err(_) => {
print!($fmt_string $(, $($msg)* )? );
return ();
... | {
let resolver = cache.name_resolvers.get_mut(0).unwrap();
let mut definitions = resolver.exports.definitions.iter().collect::<Vec<_>>();
// Make sure the output has a deterministic order for testing
definitions.sort();
for (name, definition_id) in definitions {
let info = &cache.definitio... | identifier_body |
main.rs | //! main.rs - The entry point for the Ante compiler.
//! Handles command-line argument parsing and dataflow between
//! each compiler phase. The compiler as a whole is separated into
//! the following phases (in order):
//!
//! lexing -> parsing -> name resolution -> type inference -> lifetime inference -> codegen
//!
... | .arg(Arg::with_name("show-types").long("show-types").help("Print out the type of each definition"))
.arg(Arg::with_name("show-lifetimes").long("show-lifetimes").help("Print out the input file annotated with inferred lifetimes of heap allocations"))
.arg(Arg::with_name("file").help("The file to comp... | .arg(Arg::with_name("O").short("O").value_name("level").default_value("0").validator(validate_opt_argument).help("Sets the current optimization level from 0 (no optimization) to 3 (aggressive optimization). Set to s or z to optimize for size."))
.arg(Arg::with_name("no-color").long("no-color").help("Use... | random_line_split |
exports.rs | use crate::ty;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def::Res;
use rustc_hir::def_id::LocalDefId;
use rustc_macros::HashStable;
use rustc_span::symbol::Ident;
use rustc_span::Span;
use std::fmt::Debug;
/// This is the replacement export map. It maps a module to all of the exports
/// within.
pub t... |
}
| {
Export { ident: self.ident, res: self.res.map_id(map), span: self.span, vis: self.vis }
} | identifier_body |
exports.rs | use crate::ty;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def::Res;
use rustc_hir::def_id::LocalDefId;
use rustc_macros::HashStable;
use rustc_span::symbol::Ident; | /// This is the replacement export map. It maps a module to all of the exports
/// within.
pub type ExportMap<Id> = FxHashMap<LocalDefId, Vec<Export<Id>>>;
#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
pub struct Export<Id> {
/// The name of the target.
pub ident: Ident,
/// The resol... | use rustc_span::Span;
use std::fmt::Debug;
| random_line_split |
exports.rs | use crate::ty;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def::Res;
use rustc_hir::def_id::LocalDefId;
use rustc_macros::HashStable;
use rustc_span::symbol::Ident;
use rustc_span::Span;
use std::fmt::Debug;
/// This is the replacement export map. It maps a module to all of the exports
/// within.
pub t... | <Id> {
/// The name of the target.
pub ident: Ident,
/// The resolution of the target.
pub res: Res<Id>,
/// The span of the target.
pub span: Span,
/// The visibility of the export.
/// We include non-`pub` exports for hygienic macros that get used from extern crates.
pub vis: ty::V... | Export | identifier_name |
simple.rs | pub fn | () {
let a = true;
let b = false;
if a {
print!("a");
} else if b {
print!("b");
} else {
print!("c")
}
let mut a: int = 0;
let b: bool = true;
let c: bool = false;
let _numbers = [1, 2, 3];
let t = _numbers[a..];
// As a naked if
if b || c ... | main | identifier_name |
simple.rs | pub fn main() {
let a = true;
let b = false;
if a {
print!("a");
} else if b {
print!("b");
} else {
print!("c")
}
let mut a: int = 0;
let b: bool = true;
let c: bool = false;
let _numbers = [1, 2, 3];
let t = _numbers[a..];
// As a naked if
... |
// Tuple expressions. They are not at all ambiguious.
(0,);
(0.0, 4.5);
("a", 4u, true);
// Tuple destructuring let with a statement block!
let (_cap, _cap_name, _oldflags) = {
(1, 2, 3)
};
} | }
println!("{}", a); | random_line_split |
simple.rs | pub fn main() | a = 1;
}
a << 32 > a << 16;
a >> 32 < a >> 16;
a >>= 1;
println!("{}", a);
// As an expression
a = if!c {
10
} else {
20
};
'foo: loop {
println!("{}", a);
break 'foo;
}
println!("{}", a);
// Tuple expressions. They are n... | {
let a = true;
let b = false;
if a {
print!("a");
} else if b {
print!("b");
} else {
print!("c")
}
let mut a: int = 0;
let b: bool = true;
let c: bool = false;
let _numbers = [1, 2, 3];
let t = _numbers[a..];
// As a naked if
if b || c { | identifier_body |
simple.rs | pub fn main() {
let a = true;
let b = false;
if a {
print!("a");
} else if b | else {
print!("c")
}
let mut a: int = 0;
let b: bool = true;
let c: bool = false;
let _numbers = [1, 2, 3];
let t = _numbers[a..];
// As a naked if
if b || c {
a = 1;
}
a << 32 > a << 16;
a >> 32 < a >> 16;
a >>= 1;
println!("{}", a);
// As ... | {
print!("b");
} | conditional_block |
sync-rwlock-write-mode-shouldnt-escape.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 main() {
let x = ~sync::RWLock::new();
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(write_mode);
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).write { }
} | // error-pattern: lifetime of variable does not enclose its declaration
extern mod extra;
use extra::sync; | random_line_split |
sync-rwlock-write-mode-shouldnt-escape.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 x = ~sync::RWLock::new();
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(write_mode);
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).write { }
} | identifier_body | |
sync-rwlock-write-mode-shouldnt-escape.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 x = ~sync::RWLock::new();
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(write_mode);
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).write { }
}
| main | identifier_name |
main.rs | #![feature(slice_concat_ext)]
extern crate ramp;
extern crate bufstream;
extern crate regex;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{RwLock, Arc};
use std::net::{TcpListener, TcpStream};
use std::io::{Read, BufRead, Write};
use regex::Regex;
use std::slice::SliceConcatExt;
#[macro_use]
extern c... | ,
None => {
stream.write("NOT FOUND\n".as_bytes());
}
};
}
continue
}
}
}
| {
let d = version.dependencies.join(",");
let response = format!("{} {} {}\n",
version.value,
version.timestamp,
d);
... | conditional_block |
main.rs | #![feature(slice_concat_ext)]
extern crate ramp;
extern crate bufstream;
extern crate regex;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{RwLock, Arc};
use std::net::{TcpListener, TcpStream};
use std::io::{Read, BufRead, Write};
use regex::Regex;
use std::slice::SliceConcatExt;
#[macro_use]
extern c... | () {
/*
Logger notes:
RUST_LOG=error./main
RUST_LOG=info
http://rust-lang.github.io/log/env_logger/
*/
info!("Starting up RAMP socket server!");
let db = Arc::new(RwLock::new(Database::new()));
let listener = TcpListener::bind("127.0.0.1:6000").unwrap();
info!("Socket bound");
... | main | identifier_name |
main.rs | #![feature(slice_concat_ext)]
extern crate ramp;
extern crate bufstream;
extern crate regex;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{RwLock, Arc};
use std::net::{TcpListener, TcpStream};
use std::io::{Read, BufRead, Write};
use regex::Regex;
use std::slice::SliceConcatExt;
#[macro_use]
extern c... | handle_client(stream, db2)
});
},
Err(e) => {}
}
}
info!("Goodbye forever.");
}
fn handle_client(mut stream: TcpStream, mut db: DB ) {
info!("Starting new client thread, creating regexes");
let prepare = Regex::new(r"prepare\s+(... | {
/*
Logger notes:
RUST_LOG=error ./main
RUST_LOG=info
http://rust-lang.github.io/log/env_logger/
*/
info!("Starting up RAMP socket server!");
let db = Arc::new(RwLock::new(Database::new()));
let listener = TcpListener::bind("127.0.0.1:6000").unwrap();
info!("Socket bound");
... | identifier_body |
main.rs | #![feature(slice_concat_ext)]
extern crate ramp;
extern crate bufstream;
extern crate regex;
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{RwLock, Arc};
use std::net::{TcpListener, TcpStream};
use std::io::{Read, BufRead, Write};
use regex::Regex;
use std::slice::SliceConcatExt;
#[macro_use]
extern c... | d);
stream.write(response.as_bytes());
},
None => {
stream.write("NOT FOUND\n".as_bytes());
}
};
}
continue
}
... | random_line_split | |
lib.rs | // This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Twig library for rust.
//!
//! # Examples
//!
//! ```
//! use twig::engine::Setup;
//! use twig::loader;
//! use twig::runtime::Runtime;
//! use twig::t... | //! let compiled = engine.load_template("greetings", None).unwrap();
//! assert_eq!(&compiled.render(&runtime).unwrap(), "Hello world!")
//! ```
extern crate regex;
#[macro_use]pub mod api;
pub mod engine;
pub mod runtime;
pub mod loader;
pub mod template;
pub mod extension;
pub use engine::Engine;
pub use engine::S... | //! runtime.set("name", "world");
//! | random_line_split |
msgsend-ring-mutex-arcs.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 mut futures = Vec::new();
for i in range(1u, num_tasks) {
//println!("spawning %?", i);
let (new_chan, num_port) = init();
let num_chan_2 = num_chan.clone();
let new_future = Future::spawn(move|| {
thread_ring(i, msg_per_task, num_chan... | {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "100".to_string(), "10000".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10".to_string(), "100".to_string())
} else {
args.clone().into_iter().collect()
};
... | identifier_body |
msgsend-ring-mutex-arcs.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 args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "100".to_string(), "10000".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10".to_string(), "100".to_string())
} else {
args.clone().into_iter().collect()
};
... | main | identifier_name |
msgsend-ring-mutex-arcs.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 ... | });
futures.push(new_future);
num_chan = new_chan;
};
// do our iteration
thread_ring(0, msg_per_task, num_chan, num_port);
// synchronize
for f in futures.iter_mut() {
f.get()
}
});
// all done, report stats.
... | let (new_chan, num_port) = init();
let num_chan_2 = num_chan.clone();
let new_future = Future::spawn(move|| {
thread_ring(i, msg_per_task, num_chan_2, num_port) | random_line_split |
lib.rs | //! A very simple HTTP server which responds with the plain text "Hello, World!" to every request.
#![crate_name = "ruster"]
extern crate time;
extern crate http;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::Writer;
use http::server::{Config, Server, Request, ResponseWriter};
use http::headers::conten... | impl Server for HelloWorldServer {
fn get_config(&self) -> Config {
Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8001 } }
}
fn handle_request(&self, _r: Request, w: &mut ResponseWriter) {
w.headers.date = Some(time::now_utc());
w.headers.content_length = Some(14);
w.heade... | random_line_split | |
lib.rs | //! A very simple HTTP server which responds with the plain text "Hello, World!" to every request.
#![crate_name = "ruster"]
extern crate time;
extern crate http;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::Writer;
use http::server::{Config, Server, Request, ResponseWriter};
use http::headers::conten... |
}
| {
w.headers.date = Some(time::now_utc());
w.headers.content_length = Some(14);
w.headers.content_type = Some(MediaType {
type_: String::from_str("text"),
subtype: String::from_str("plain"),
parameters: vec!((String::from_str("charset"), String::from_str("UTF-8")))
});
w.headers.ser... | identifier_body |
lib.rs | //! A very simple HTTP server which responds with the plain text "Hello, World!" to every request.
#![crate_name = "ruster"]
extern crate time;
extern crate http;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::Writer;
use http::server::{Config, Server, Request, ResponseWriter};
use http::headers::conten... | (&self) -> Config {
Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8001 } }
}
fn handle_request(&self, _r: Request, w: &mut ResponseWriter) {
w.headers.date = Some(time::now_utc());
w.headers.content_length = Some(14);
w.headers.content_type = Some(MediaType {
type_: St... | get_config | identifier_name |
deadline.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | }
#[cfg(test)]
mod tests {
use std::io;
use std::time::Duration;
use futures::{Future, empty, done};
use tokio_core::reactor::Core;
use super::{deadline, DeadlineStatus};
//#[test] TODO: not working
fn _deadline_timeout_works() {
let mut core = Core::new().unwrap();
let deadline = deadline(Duration::from_m... | Ok(Async::NotReady) => Ok(Async::NotReady),
Err((err, _other)) => Err(err),
}
} | random_line_split |
deadline.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
/// Deadline future completion status.
#[derive(Debug, PartialEq)]
pub enum DeadlineStatus<T> {
/// Completed a future.
Meet(T),
/// Faled with timeout.
Timeout,
}
/// Future, which waits for passed future completion within given period, or fails with timeout.
pub struct Deadline<F> where F: Future {
future: Se... | {
let timeout: DeadlineBox<F> = Box::new(Timeout::new(duration, handle)?.map(|_| DeadlineStatus::Timeout));
let future: DeadlineBox<F> = Box::new(future.map(DeadlineStatus::Meet));
let deadline = Deadline {
future: timeout.select(future),
};
Ok(deadline)
} | identifier_body |
deadline.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | <F, T>(duration: Duration, handle: &Handle, future: F) -> Result<Deadline<F>, io::Error>
where F: Future<Item = T, Error = io::Error> + Send +'static, T:'static {
let timeout: DeadlineBox<F> = Box::new(Timeout::new(duration, handle)?.map(|_| DeadlineStatus::Timeout));
let future: DeadlineBox<F> = Box::new(future.map... | deadline | identifier_name |
unwind-no-uwtable.rs | // run-pass
// needs-unwind
// ignore-windows target requires uwtable
// ignore-wasm32-bare no proper panic=unwind support
// compile-flags: -C panic=unwind -C force-unwind-tables=n
use std::panic::{self, AssertUnwindSafe};
struct Increase<'a>(&'a mut u8);
impl Drop for Increase<'_> {
fn drop(&mut self) {
... | () {
let mut count = 0;
assert!(panic::catch_unwind(AssertUnwindSafe(
#[inline(never)]
|| increase(&mut count)
)).is_err());
assert_eq!(count, 1);
}
| main | identifier_name |
unwind-no-uwtable.rs | // run-pass
// needs-unwind
// ignore-windows target requires uwtable
// ignore-wasm32-bare no proper panic=unwind support
// compile-flags: -C panic=unwind -C force-unwind-tables=n
use std::panic::{self, AssertUnwindSafe};
struct Increase<'a>(&'a mut u8);
impl Drop for Increase<'_> {
fn drop(&mut self) {
... |
#[inline(never)]
fn increase(count: &mut u8) {
let _increase = Increase(count);
unwind();
}
fn main() {
let mut count = 0;
assert!(panic::catch_unwind(AssertUnwindSafe(
#[inline(never)]
|| increase(&mut count)
)).is_err());
assert_eq!(count, 1);
}
| {
panic!();
} | identifier_body |
unwind-no-uwtable.rs | // run-pass
// needs-unwind
// ignore-windows target requires uwtable
// ignore-wasm32-bare no proper panic=unwind support
// compile-flags: -C panic=unwind -C force-unwind-tables=n
use std::panic::{self, AssertUnwindSafe};
struct Increase<'a>(&'a mut u8);
impl Drop for Increase<'_> {
fn drop(&mut self) {
... |
#[inline(never)]
fn increase(count: &mut u8) {
let _increase = Increase(count);
unwind();
}
fn main() {
let mut count = 0;
assert!(panic::catch_unwind(AssertUnwindSafe(
#[inline(never)]
|| increase(&mut count)
)).is_err());
assert_eq!(count, 1);
} |
#[inline(never)]
fn unwind() {
panic!();
} | random_line_split |
scheduler.rs | #![allow(unused)]
extern crate fringe;
use self::fringe::generator::{Generator, Yielder};
use self::fringe::OwnedStack;
use alloc::vec::Vec;
use time::{Duration, Instant};
#[derive(Debug)]
pub struct WaitRequest {
timeout: Option<Instant>,
event: Option<WaitEvent>,
}
#[derive(Debug)]
pub enum WaitResult {
... | <F: FnOnce(Io) + Send + 'a>(&mut self, stack_size: usize, f: F) {
let stack = OwnedStack::new(stack_size);
let thread = Thread {
generator: Generator::unsafe_new(stack, move |yielder, _| f(Io(yielder))),
waiting_for: WaitRequest {
timeout: None,
ev... | spawn | identifier_name |
scheduler.rs | #![allow(unused)]
extern crate fringe;
use self::fringe::generator::{Generator, Yielder};
use self::fringe::OwnedStack;
use alloc::vec::Vec;
use time::{Duration, Instant};
#[derive(Debug)]
pub struct WaitRequest {
timeout: Option<Instant>,
event: Option<WaitEvent>,
}
#[derive(Debug)]
pub enum WaitResult {
... | }
if event.completed() =>
{
thread.generator.resume(WaitResult::Completed)
}
WaitRequest {
timeout: None,
event: None,
} => ... | thread.generator.resume(WaitResult::TimedOut)
}
WaitRequest {
event: Some(ref event),
.. | random_line_split |
lib.rs | #![deny(unused)]
#![feature(collections, hash, io, libc, os, path, std_misc, unicode, env, core)]
#![cfg_attr(test, deny(warnings))]
extern crate libc;
extern crate "rustc-serialize" as rustc_serialize;
extern crate regex;
extern crate term;
extern crate time;
#[macro_use] extern crate log;
extern crate curl;
extern ... | let json = try!(json_from_stdin::<U>());
exec(flags, json, shell)
}
pub fn execute_main_without_stdin<T, V>(
exec: fn(T, &Config) -> CliResult<Option<V>>,
options_first: bool,
usage: &str)
whe... | args: &[String],
options_first: bool) -> CliResult<Option<V>>
where V: Encodable, T: Decodable, U: Decodable
{
let flags = try!(flags_from_args::<T>(usage, args, options_first)); | random_line_split |
lib.rs | #![deny(unused)]
#![feature(collections, hash, io, libc, os, path, std_misc, unicode, env, core)]
#![cfg_attr(test, deny(warnings))]
extern crate libc;
extern crate "rustc-serialize" as rustc_serialize;
extern crate regex;
extern crate term;
extern crate time;
#[macro_use] extern crate log;
extern crate curl;
extern ... |
print(cause.to_string(), shell);
err = cause.cause();
}
fn print(error: String, shell: &mut MultiShell) {
let _ = shell.err().say("\nCaused by:", BLACK);
let _ = shell.err().say(format!(" {}", error), BLACK);
}
}
pub fn version() -> String {
format!("cargo {}", match ... | { return false } | conditional_block |
lib.rs | #![deny(unused)]
#![feature(collections, hash, io, libc, os, path, std_misc, unicode, env, core)]
#![cfg_attr(test, deny(warnings))]
extern crate libc;
extern crate "rustc-serialize" as rustc_serialize;
extern crate regex;
extern crate term;
extern crate time;
#[macro_use] extern crate log;
extern crate curl;
extern ... |
pub fn call_main<T, U, V>(
exec: fn(T, U, &Config) -> CliResult<Option<V>>,
shell: &Config,
usage: &str,
args: &[String],
options_first: bool) -> CliResult<Option<V>>
where V: Encodable, T: Decodable, U: Decodable
{
let flags = try!(flags_from_args::... | {
process::<V, _>(|rest, shell| {
call_main(exec, shell, usage, rest, options_first)
});
} | identifier_body |
lib.rs | #![deny(unused)]
#![feature(collections, hash, io, libc, os, path, std_misc, unicode, env, core)]
#![cfg_attr(test, deny(warnings))]
extern crate libc;
extern crate "rustc-serialize" as rustc_serialize;
extern crate regex;
extern crate term;
extern crate time;
#[macro_use] extern crate log;
extern crate curl;
extern ... | <'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.as_slice()))
... | flags_from_args | identifier_name |
cmp.rs | use rational_sequences::RationalSequence;
use std::cmp::Ordering;
impl<T: Eq + Ord> PartialOrd for RationalSequence<T> {
/// Compares a `RationalSequence` to another `RationalSequence`.
///
/// See the documentation for the `Ord` implementation.
#[inline]
fn partial_cmp(&self, other: &RationalSeque... | /// assert!(
/// RationalSequence::from_slice(&[1, 2, 3]) <
/// RationalSequence::from_slices(&[1, 2], &[3, 4])
/// );
/// ```
fn cmp(&self, other: &RationalSequence<T>) -> Ordering {
if self == other {
Ordering::Equal
} else {
Iterator::cmp(se... | random_line_split | |
cmp.rs | use rational_sequences::RationalSequence;
use std::cmp::Ordering;
impl<T: Eq + Ord> PartialOrd for RationalSequence<T> {
/// Compares a `RationalSequence` to another `RationalSequence`.
///
/// See the documentation for the `Ord` implementation.
#[inline]
fn partial_cmp(&self, other: &RationalSeque... |
}
}
| {
Iterator::cmp(self.iter(), other.iter())
} | conditional_block |
cmp.rs | use rational_sequences::RationalSequence;
use std::cmp::Ordering;
impl<T: Eq + Ord> PartialOrd for RationalSequence<T> {
/// Compares a `RationalSequence` to another `RationalSequence`.
///
/// See the documentation for the `Ord` implementation.
#[inline]
fn partial_cmp(&self, other: &RationalSeque... |
}
| {
if self == other {
Ordering::Equal
} else {
Iterator::cmp(self.iter(), other.iter())
}
} | identifier_body |
cmp.rs | use rational_sequences::RationalSequence;
use std::cmp::Ordering;
impl<T: Eq + Ord> PartialOrd for RationalSequence<T> {
/// Compares a `RationalSequence` to another `RationalSequence`.
///
/// See the documentation for the `Ord` implementation.
#[inline]
fn partial_cmp(&self, other: &RationalSeque... | (&self, other: &RationalSequence<T>) -> Ordering {
if self == other {
Ordering::Equal
} else {
Iterator::cmp(self.iter(), other.iter())
}
}
}
| cmp | identifier_name |
chap06.rs | /*
* Chap.6 Enum and Pattern Matching
*
*/
#[derive(Debug)]
enum MonitorState {
Success,
Warning,
Error,
}
#[derive(Debug)] | state: MonitorState,
}
#[derive(Debug)]
enum ServicePort {
HTTP(u32),
HTTPS(u32),
}
#[derive(Debug)]
enum Service {
API(String, ServicePort),
Frontend(String, ServicePort),
}
#[derive(Debug)]
enum NamedPort {
HTTPS = 443,
}
#[derive(Debug)]
enum ServiceAction {
Reload, //... | struct Monitor {
service: String, | random_line_split |
chap06.rs | /*
* Chap.6 Enum and Pattern Matching
*
*/
#[derive(Debug)]
enum MonitorState {
Success,
Warning,
Error,
}
#[derive(Debug)]
struct Monitor {
service: String,
state: MonitorState,
}
#[derive(Debug)]
enum ServicePort {
HTTP(u32),
HTTPS(u32),
}
#[derive(Debug)]
enum Service {
API(Str... | (num: Option<i32>) -> i32 {
match num {
None => 0,
Some(i) => i,
}
}
| handle_option_normalization | identifier_name |
inheritance.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/. */
//! The `Castable` trait.
pub use dom::bindings::codegen::InheritTypes::*;
use dom::bindings::conversions::{Deri... |
}
}
| {
None
} | conditional_block |
inheritance.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/. */
//! The `Castable` trait.
pub use dom::bindings::codegen::InheritTypes::*;
use dom::bindings::conversions::{Deri... |
}
| {
if self.is::<T>() {
Some(unsafe { mem::transmute(self) })
} else {
None
}
} | identifier_body |
inheritance.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/. */
//! The `Castable` trait.
pub use dom::bindings::codegen::InheritTypes::*;
use dom::bindings::conversions::{Deri... | <T>(&self) -> Option<&T>
where T: DerivedFrom<Self>
{
if self.is::<T>() {
Some(unsafe { mem::transmute(self) })
} else {
None
}
}
}
| downcast | identifier_name |
inheritance.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 |
//! The `Castable` trait.
pub use dom::bindings::codegen::InheritTypes::*;
use dom::bindings::conversions::{DerivedFrom, IDLInterface};
use dom::bindings::conversions::get_dom_class;
use dom::bindings::reflector::DomObject;
use std::mem;
/// A trait to hold the cast functions of IDL interfaces that either derive
//... | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split |
intrinsic-return-address.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 main() {
let mut intrinsic_reported_address = 0;
let pt = f(&mut intrinsic_reported_address);
let actual_address = &pt as *const Point as uint;
assert_eq!(intrinsic_reported_address, actual_address);
}
| {
unsafe {
*result = return_address() as uint;
Point {
x: 1.0,
y: 2.0,
z: 3.0,
}
}
} | identifier_body |
intrinsic-return-address.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 main() {
let mut intrinsic_reported_address = 0;
let pt = f(&mut intrinsic_reported_address);
let actual_address = &pt as *const Point as uint;
assert_eq!(intrinsic_reported_address, actual_address);
} | y: 2.0,
z: 3.0,
}
}
| random_line_split |
intrinsic-return-address.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... | {
x: f32,
y: f32,
z: f32,
}
extern "rust-intrinsic" {
fn return_address() -> *const u8;
}
fn f(result: &mut uint) -> Point {
unsafe {
*result = return_address() as uint;
Point {
x: 1.0,
y: 2.0,
z: 3.0,
}
}
}
fn main() {
let mut... | Point | identifier_name |
linker.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
self.cmd.arg("-Wl,-Bstatic");
}
fn hint_dynamic(&mut self) {
if!self.takes_hints() { return }
self.cmd.arg("-Wl,-Bdynamic");
}
fn export_symbols(&mut self, _: &Session, _: &CrateTranslation, _: &Path) {
// noop, visibility in object files takes care of this
}
}
pu... | { return } | conditional_block |
linker.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn framework_path(&mut self, _path: &Path) {
panic!("frameworks are not supported on windows")
}
fn link_framework(&mut self, _framework: &str) {
panic!("frameworks are not supported on windows")
}
fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
//... | } | random_line_split |
linker.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn export_symbols(&mut self, _: &Session, _: &CrateTranslation, _: &Path) {
// noop, visibility in object files takes care of this
}
}
pub struct MsvcLinker<'a> {
pub cmd: &'a mut Command,
pub sess: &'a Session,
}
impl<'a> Linker for MsvcLinker<'a> {
fn link_rlib(&mut self, lib: &Path) {... | {
if !self.takes_hints() { return }
self.cmd.arg("-Wl,-Bdynamic");
} | identifier_body |
linker.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self, args: &[String]) { self.cmd.args(args); }
fn build_dylib(&mut self, _out_filename: &Path) { self.cmd.arg("/DLL"); }
fn gc_sections(&mut self, _is_dylib: bool) { self.cmd.arg("/OPT:REF,ICF"); }
fn link_dylib(&mut self, lib: &str) {
self.cmd.arg(&format!("{}.lib", lib));
}
fn lin... | args | identifier_name |
dropck.rs | use crate::check::regionck::RegionCtxt;
use crate::hir;
use crate::hir::def_id::{DefId, LocalDefId};
use rustc_errors::{struct_span_err, ErrorReported};
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::infer::{InferOk, RegionckMode, TyCtxtInferExt};
use rustc_infer::traits::TraitEngineExt as... | // to take on a structure that is roughly an alpha-renaming of
// the generic parameters of the item definition.)
// This path now just checks *all* predicates via an instantiation of
// the `SimpleEqRelation`, which simply forwards to the `relate` machinery
// after taking care... | // expressions etc because the Drop impls are already forced | random_line_split |
dropck.rs | use crate::check::regionck::RegionCtxt;
use crate::hir;
use crate::hir::def_id::{DefId, LocalDefId};
use rustc_errors::{struct_span_err, ErrorReported};
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::infer::{InferOk, RegionckMode, TyCtxtInferExt};
use rustc_infer::traits::TraitEngineExt as... |
_ => predicate == p,
}
};
if!assumptions_in_impl_context.iter().copied().any(predicate_matches_closure) {
let item_span = tcx.hir().span(self_type_hir_id);
let self_descr = tcx.def_kind(self_type_did).descr(self_type_did.to_def_id());
str... | {
relator.relate(predicate.rebind(ty_a), p.rebind(ty_b)).is_ok()
&& relator.relate(predicate.rebind(lt_a), p.rebind(lt_b)).is_ok()
} | conditional_block |
dropck.rs | use crate::check::regionck::RegionCtxt;
use crate::hir;
use crate::hir::def_id::{DefId, LocalDefId};
use rustc_errors::{struct_span_err, ErrorReported};
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::infer::{InferOk, RegionckMode, TyCtxtInferExt};
use rustc_infer::traits::TraitEngineExt as... |
}
impl TypeRelation<'tcx> for SimpleEqRelation<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn param_env(&self) -> ty::ParamEnv<'tcx> {
self.param_env
}
fn tag(&self) -> &'static str {
"dropck::SimpleEqRelation"
}
fn a_is_expected(&self) -> bool {
t... | {
SimpleEqRelation { tcx, param_env }
} | identifier_body |
dropck.rs | use crate::check::regionck::RegionCtxt;
use crate::hir;
use crate::hir::def_id::{DefId, LocalDefId};
use rustc_errors::{struct_span_err, ErrorReported};
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::infer::{InferOk, RegionckMode, TyCtxtInferExt};
use rustc_infer::traits::TraitEngineExt as... | (&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
debug!("SimpleEqRelation::tys(a={:?}, b={:?})", a, b);
ty::relate::super_relate_tys(self, a, b)
}
fn regions(
&mut self,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) -> RelateResult<'tcx, ty::Regi... | tys | identifier_name |
pwm1.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM1
// FIXME doesn't seem to work :-(
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
ex... | let tim1 = TIM1.access(prio, thr);
let pwm = Pwm(&*tim1);
pwm.init(FREQUENCY.invert(), afio, gpioa, rcc);
let duty = pwm.get_max_duty() / 16;
const CHANNELS: [Channel; 4] =
[Channel::_1, Channel::_2, Channel::_3, Channel::_4];
for c in &CHANNELS {
pwm.set_duty(*c, duty);
... | let rcc = &RCC.access(prio, thr); | random_line_split |
pwm1.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM1
// FIXME doesn't seem to work :-(
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
ex... |
// TASKS
tasks!(stm32f103xx, {});
| {
// Sleep
loop {
rtfm::wfi();
}
} | identifier_body |
pwm1.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM1
// FIXME doesn't seem to work :-(
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
ex... | (ref prio: P0, thr: &TMax) {
let afio = &AFIO.access(prio, thr);
let gpioa = &GPIOA.access(prio, thr);
let rcc = &RCC.access(prio, thr);
let tim1 = TIM1.access(prio, thr);
let pwm = Pwm(&*tim1);
pwm.init(FREQUENCY.invert(), afio, gpioa, rcc);
let duty = pwm.get_max_duty() / 16;
const ... | init | identifier_name |
fullscreen.rs | mod support;
use glutin::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::monitor::{MonitorHandle, VideoMode};
use glutin::window::{Fullscreen, WindowBuilder};
use std::io::{stdin, stdout, Write};
fn main() |
let wb = WindowBuilder::new().with_title("Hello world!").with_fullscreen(fullscreen.clone());
let windowed_context = glutin::ContextBuilder::new().build_windowed(wb, &el).unwrap();
let windowed_context = unsafe { windowed_context.make_current().unwrap() };
let gl = support::load(&windowed_context.con... | {
let el = EventLoop::new();
print!("Please choose the fullscreen mode: (1) exclusive, (2) borderless: ");
stdout().flush().unwrap();
let mut num = String::new();
stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let fullscreen = Some... | identifier_body |
fullscreen.rs | mod support;
use glutin::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::monitor::{MonitorHandle, VideoMode};
use glutin::window::{Fullscreen, WindowBuilder};
use std::io::{stdin, stdout, Write};
fn main() {
let el = EventLoop... | println!("Using {:?}", monitor.name());
monitor
}
fn prompt_for_video_mode(monitor: &MonitorHandle) -> VideoMode {
for (i, video_mode) in monitor.video_modes().enumerate() {
println!("Video mode #{}: {}", i, video_mode);
}
print!("Please write the number of the video mode to use: ");
... | let monitor = el.available_monitors().nth(num).expect("Please enter a valid ID");
| random_line_split |
fullscreen.rs | mod support;
use glutin::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::monitor::{MonitorHandle, VideoMode};
use glutin::window::{Fullscreen, WindowBuilder};
use std::io::{stdin, stdout, Write};
fn main() {
let el = EventLoop... | (monitor: &MonitorHandle) -> VideoMode {
for (i, video_mode) in monitor.video_modes().enumerate() {
println!("Video mode #{}: {}", i, video_mode);
}
print!("Please write the number of the video mode to use: ");
stdout().flush().unwrap();
let mut num = String::new();
stdin().read_line(&... | prompt_for_video_mode | identifier_name |
mysql.rs | use crate::prelude::*;
#[cfg(feature = "db-diesel-mysql")]
mod diesel_mysql {
use super::*;
use ::diesel::{
deserialize::{self, FromSql},
mysql::Mysql,
serialize::{self, IsNull, Output, ToSql},
sql_types::Numeric,
};
use std::io::Write;
use std::str::FromStr;
im... |
#[test]
fn read_numeric_type() {
let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() {
let items: Vec<Test> = sql_query(format!(
... | {
let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
// Test NULL
let items: Vec<NullableTest> = sql_query("SELECT CAST(NULL AS DECIMAL) AS value")
.load(&connection)
.expect("Unable to query value");... | identifier_body |
mysql.rs | use crate::prelude::*;
#[cfg(feature = "db-diesel-mysql")]
mod diesel_mysql {
use super::*;
use ::diesel::{
deserialize::{self, FromSql},
mysql::Mysql,
serialize::{self, IsNull, Output, ToSql},
sql_types::Numeric,
};
use std::io::Write;
use std::str::FromStr;
im... | () {
let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
// Test NULL
let items: Vec<NullableTest> = sql_query("SELECT CAST(NULL AS DECIMAL) AS value")
.load(&connection)
.expect("Unable to query value")... | test_null | identifier_name |
mysql.rs | use crate::prelude::*;
#[cfg(feature = "db-diesel-mysql")]
mod diesel_mysql {
use super::*;
use ::diesel::{
deserialize::{self, FromSql},
mysql::Mysql,
serialize::{self, IsNull, Output, ToSql},
sql_types::Numeric,
};
use std::io::Write;
use std::str::FromStr;
im... |
"mysql://root@127.0.0.1/mysql".to_string()
}
#[test]
fn test_null() {
let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
// Test NULL
let items: Vec<NullableTest> = sql_query("SELECT CAST(NULL A... | {
return url;
} | conditional_block |
mysql.rs | use crate::prelude::*;
#[cfg(feature = "db-diesel-mysql")]
mod diesel_mysql {
use super::*;
use ::diesel::{
deserialize::{self, FromSql},
mysql::Mysql,
serialize::{self, IsNull, Output, ToSql},
sql_types::Numeric,
};
use std::io::Write;
use std::str::FromStr;
im... | }
pub static TEST_DECIMALS: &[(u32, u32, &str, &str)] = &[
// precision, scale, sent, expected
(1, 0, "1", "1"),
(6, 2, "1", "1.00"),
(6, 2, "9999.99", "9999.99"),
(35, 6, "3950.123456", "3950.123456"),
(10, 2, "3950.123456", "3950... | let value = row.get("value")?;
Ok(NullableTest { value })
} | random_line_split |
gauge.rs | use std::f64;
use std::mem;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug)]
pub struct Gauge {
value: AtomicU64,
}
impl Gauge {
pub fn new() -> Gauge {
let bits = unsafe { mem::transmute(f64::NAN) };
Gauge { value: AtomicU64::new(bits) }
}
pub fn clear(&mut self) {
... | () {
let mut c: Gauge = Gauge::new();
let s1 = c.snapshot();
c.set(1f64);
let s2 = c.snapshot();
assert!(f64::is_nan(s1));
assert!(s2 == 1f64);
}
}
| snapshot | identifier_name |
gauge.rs | use std::f64;
use std::mem;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug)]
pub struct Gauge {
value: AtomicU64,
}
impl Gauge {
pub fn new() -> Gauge {
let bits = unsafe { mem::transmute(f64::NAN) };
Gauge { value: AtomicU64::new(bits) }
}
pub fn clear(&mut self) |
pub fn set(&mut self, value: f64) {
let bits = unsafe { mem::transmute(value) };
self.value.store(bits, Ordering::Relaxed);
}
pub fn snapshot(&self) -> f64 {
let bits = self.value.load(Ordering::Relaxed);
unsafe { mem::transmute(bits) }
}
}
#[cfg(test)]
mod test {
... | {
let bits = unsafe { mem::transmute(f64::NAN) };
self.value.store(bits, Ordering::Relaxed);
} | identifier_body |
gauge.rs | use std::f64;
use std::mem;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug)]
pub struct Gauge {
value: AtomicU64,
}
impl Gauge {
pub fn new() -> Gauge {
let bits = unsafe { mem::transmute(f64::NAN) };
Gauge { value: AtomicU64::new(bits) }
}
pub fn clear(&mut self) {
... |
#[test]
fn snapshot() {
let mut c: Gauge = Gauge::new();
let s1 = c.snapshot();
c.set(1f64);
let s2 = c.snapshot();
assert!(f64::is_nan(s1));
assert!(s2 == 1f64);
}
} |
use std::f64; | random_line_split |
genericitesource0.rs | // A est un type concret.
struct A;
// Lorsque nous déclarons `Single`, la première occurrence de `A` n'est
// pas précédée du type générique `<A>`. Le type `Single` et `A` sont donc
// concrets.
struct Single(A);
// ^ Voici la première occurrence du type `A`.
// En revanche, ici, `<T>` précède la premiè... | {
// `Single` est un type concret et prend explicitement un paramètre
// de type `A`.
let _s = Single(A);
// On créé une variable nommée `_char` de type `SingleGen<char>`
// et on lui assigne la valeur `SingleGen('a')`.
// Le type requis du paramètre passé pour cette instance de `SingleGen`
... | n main() | identifier_name |
genericitesource0.rs | // A est un type concret.
struct A;
// Lorsque nous déclarons `Single`, la première occurrence de `A` n'est
// pas précédée du type générique `<A>`. Le type `Single` et `A` sont donc
// concrets.
struct Single(A); | // `SingleGen` est générique. Puisque le type `T` est générique, cela pourrait être
// "n'importe quoi", y compris le type concret `A` déclaré au début du fichier.
struct SingleGen<T>(T);
fn main() {
// `Single` est un type concret et prend explicitement un paramètre
// de type `A`.
let _s = Single(A);
... | // ^ Voici la première occurrence du type `A`.
// En revanche, ici, `<T>` précède la première occurrence `T`, donc le type | random_line_split |
vreyeparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VREyeParame... | (&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new(self.offset.get())
}
// https://w3c.github.io/webvr/#dom-vreyeparameters-fieldofview
fn FieldOfView(&self) -> Root<VRFieldOfView> {
Root::from_ref(&*self.fov)
}
// https://w3c.github.io/webvr/#dom-vreyeparameters... | Offset | identifier_name |
vreyeparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VREyeParame... |
}
impl VREyeParametersMethods for VREyeParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vreyeparameters-offset
unsafe fn Offset(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new(self.offset.get())
}
// https://w3c.github.io/webvr/#dom-vreyeparamete... | {
reflect_dom_object(box VREyeParameters::new_inherited(parameters, global),
global,
VREyeParametersBinding::Wrap)
} | identifier_body |
vreyeparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VREyeParame... |
pub fn new(parameters: WebVREyeParameters, global: &GlobalScope) -> Root<VREyeParameters> {
reflect_dom_object(box VREyeParameters::new_inherited(parameters, global),
global,
VREyeParametersBinding::Wrap)
}
}
impl VREyeParametersMethods for VREyePa... | result.offset.set(slice_to_array_buffer_view(global.get_cx(), &result.parameters.borrow().offset));
}
result
} | random_line_split |
main.rs | use rand::{thread_rng, seq::SliceRandom};
use mcc4::*; | let game = ConnectFour::<BitState>::new(7, 6).unwrap();
let human_player = HumanPlayer::new();
let ai_player = TreeSearchPlayer::new(&game);
let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_player), Box::new(ai_player)];
players.shuffle(&mut thread_rng());
println!("\x1B[2J\... |
fn main() {
env_logger::init(); | random_line_split |
main.rs | use rand::{thread_rng, seq::SliceRandom};
use mcc4::*;
fn main() {
env_logger::init();
let game = ConnectFour::<BitState>::new(7, 6).unwrap();
let human_player = HumanPlayer::new();
let ai_player = TreeSearchPlayer::new(&game);
let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_p... |
};
}
}
| {} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.