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 |
|---|---|---|---|---|
variablenbindung.rs | fn | () {
// let - Variablenbindung erstellen, Standard: immutable (Wert ist unveränderbar)
let a = 1;
println!("a = {}", a);
// Muster sind bei einer Variablenbindung möglich, z.B.
let (b, c, d) = (2, 3, 4);
println!("b = {}, c = {}, d = {}", b, c, d);
// Variablenbindung mit Typangabe
... | main | identifier_name |
variablenbindung.rs | fn main() {
// let - Variablenbindung erstellen, Standard: immutable (Wert ist unveränderbar)
let a = 1;
println!("a = {}", a);
// Muster sind bei einer Variablenbindung möglich, z.B.
let (b, c, d) = (2, 3, 4);
println!("b = {}, c = {}, d = {}", b, c, d);
| // Variablenbindung mit Typangabe
// ohne Typangabe versucht Rust den Typ alleine herauszufinden
// i - vorzeichenbehaft u - vorzeichenlos
// Ganzzahlen: 8, 16, 32, 64 Bits
let e: i32 = 5;
println!("e = {}", e);
// mut - mutable (Wert ist veränderbar)
let mut f = 1;
f = 6;
print... | random_line_split | |
btree.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 ... | (k: K, v: V) -> LeafElt<K, V> {
LeafElt {
key: k,
value: v
}
}
///Compares another LeafElt against itself and determines whether
///the original LeafElt's key is less than the other one's key.
fn less_than(&self, other: LeafElt<K, V>) -> bool {
let order ... | new | identifier_name |
btree.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 ... | Less => true,
_ => false
}
}
///Compares another LeafElt against itself and determines whether
///the original LeafElt's key is greater than the other one's key.
fn greater_than(&self, other: LeafElt<K, V>) -> bool {
let order = self.key.cmp(&other.key);
... | ///the original LeafElt's key is less than the other one's key.
fn less_than(&self, other: LeafElt<K, V>) -> bool {
let order = self.key.cmp(&other.key);
match order { | random_line_split |
component_len.rs | use malachite_base_test_util::bench::bucketers::rational_sequence_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_rational_sequence_gen;
use malachite_base_test_u... |
fn demo_rational_sequence_component_len(gm: GenMode, config: GenConfig, limit: usize) {
for xs in unsigned_rational_sequence_gen::<u8>()
.get(gm, &config)
.take(limit)
{
println!("component_len({}) = {}", xs, xs.component_len());
}
}
fn benchmark_rational_sequence_component_len(
... | {
register_demo!(runner, demo_rational_sequence_component_len);
register_bench!(runner, benchmark_rational_sequence_component_len);
} | identifier_body |
component_len.rs | use malachite_base_test_util::bench::bucketers::rational_sequence_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_rational_sequence_gen;
use malachite_base_test_u... | );
} | random_line_split | |
component_len.rs | use malachite_base_test_util::bench::bucketers::rational_sequence_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_rational_sequence_gen;
use malachite_base_test_u... | (gm: GenMode, config: GenConfig, limit: usize) {
for xs in unsigned_rational_sequence_gen::<u8>()
.get(gm, &config)
.take(limit)
{
println!("component_len({}) = {}", xs, xs.component_len());
}
}
fn benchmark_rational_sequence_component_len(
gm: GenMode,
config: GenConfig,
... | demo_rational_sequence_component_len | identifier_name |
leader_reputation_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::liveness::{
leader_reputation::{
ActiveInactiveHeuristic, LeaderReputation, MetadataBackend, ReputationHeuristic,
},
proposer_election::{next, ProposerElection},
};
use consensus_types::{
block::{block... | assert!(proposer_election.is_valid_proposal(&good_proposal));
} | random_line_split | |
leader_reputation_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::liveness::{
leader_reputation::{
ActiveInactiveHeuristic, LeaderReputation, MetadataBackend, ReputationHeuristic,
},
proposer_election::{next, ProposerElection},
};
use consensus_types::{
block::{block... | (proposer: Author, voters: Vec<&ValidatorSigner>) -> NewBlockEvent {
NewBlockEvent::new(0, proposer, voters.iter().map(|v| v.author()).collect(), 0)
}
#[test]
fn test_simple_heuristic() {
let active_weight = 9;
let inactive_weight = 1;
let mut proposers = vec![];
let mut signers = vec![];
for i... | create_block | identifier_name |
leader_reputation_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::liveness::{
leader_reputation::{
ActiveInactiveHeuristic, LeaderReputation, MetadataBackend, ReputationHeuristic,
},
proposer_election::{next, ProposerElection},
};
use consensus_types::{
block::{block... |
#[test]
fn test_simple_heuristic() {
let active_weight = 9;
let inactive_weight = 1;
let mut proposers = vec![];
let mut signers = vec![];
for i in 0..8 {
let signer = ValidatorSigner::random([i; 32]);
proposers.push(signer.author());
signers.push(signer);
}
let heu... | {
NewBlockEvent::new(0, proposer, voters.iter().map(|v| v.author()).collect(), 0)
} | identifier_body |
leader_reputation_test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::liveness::{
leader_reputation::{
ActiveInactiveHeuristic, LeaderReputation, MetadataBackend, ReputationHeuristic,
},
proposer_election::{next, ProposerElection},
};
use consensus_types::{
block::{block... | ;
self.data[start..].to_vec()
}
}
fn create_block(proposer: Author, voters: Vec<&ValidatorSigner>) -> NewBlockEvent {
NewBlockEvent::new(0, proposer, voters.iter().map(|v| v.author()).collect(), 0)
}
#[test]
fn test_simple_heuristic() {
let active_weight = 9;
let inactive_weight = 1;
let m... | {
0
} | conditional_block |
chunks.rs | //! Iterating over a file by chunks, starting at the end of the file.
//!
//! Use [`ReverseChunks::new`] to create a new iterator over chunks of
//! bytes from the file.
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
/// When reading files in reverse in `bounded_tail`, this is the size of each
/// block read ... | ;
// Seek backwards by the next chunk, read the full chunk into
// `buf`, and then seek back to the start of the chunk again.
let mut buf = vec![0; BLOCK_SIZE as usize];
let pos = self
.file
.seek(SeekFrom::Current(-(block_size as i64)))
.unwrap();
... | {
BLOCK_SIZE
} | conditional_block |
chunks.rs | //! Iterating over a file by chunks, starting at the end of the file.
//!
//! Use [`ReverseChunks::new`] to create a new iterator over chunks of
//! bytes from the file.
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
/// When reading files in reverse in `bounded_tail`, this is the size of each
/// block read ... | (&mut self) -> Option<Self::Item> {
// If there are no more chunks to read, terminate the iterator.
if self.block_idx >= self.max_blocks_to_read {
return None;
}
// The chunk size is `BLOCK_SIZE` for all but the last chunk
// (that is, the chunk closest to the beginn... | next | identifier_name |
chunks.rs | //! Iterating over a file by chunks, starting at the end of the file.
//!
//! Use [`ReverseChunks::new`] to create a new iterator over chunks of
//! bytes from the file.
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
/// When reading files in reverse in `bounded_tail`, this is the size of each
/// block read ... | ReverseChunks {
file,
size,
max_blocks_to_read,
block_idx,
}
}
}
impl<'a> Iterator for ReverseChunks<'a> {
type Item = Vec<u8>;
fn next(&mut self) -> Option<Self::Item> {
// If there are no more chunks to read, terminate the iterator.... | impl<'a> ReverseChunks<'a> {
pub fn new(file: &'a mut File) -> ReverseChunks<'a> {
let size = file.seek(SeekFrom::End(0)).unwrap();
let max_blocks_to_read = (size as f64 / BLOCK_SIZE as f64).ceil() as usize;
let block_idx = 0; | random_line_split |
mod.rs | extern crate libc;
mod cursor;
pub mod raw;
mod row;
#[doc(hidden)]
pub mod result;
mod stmt;
use std::cell::Cell;
use std::ffi::{CString, CStr};
use std::rc::Rc;
use connection::{SimpleConnection, Connection};
use pg::{Pg, PgQueryBuilder};
use query_builder::{AsQuery, QueryFragment, QueryId};
use query_builder::bin... |
query.map(|_| ())
}
}
extern "C" fn noop_notice_processor(_: *mut libc::c_void, _message: *const libc::c_char) {
}
extern "C" fn default_notice_processor(_: *mut libc::c_void, message: *const libc::c_char) {
use std::io::Write;
let c_str = unsafe { CStr::from_ptr(message) };
::std::io::stderr... | {
self.transaction_depth.set(self.transaction_depth.get() + by);
} | conditional_block |
mod.rs | extern crate libc;
mod cursor;
pub mod raw;
mod row;
#[doc(hidden)]
pub mod result;
mod stmt;
use std::cell::Cell;
use std::ffi::{CString, CStr};
use std::rc::Rc;
use connection::{SimpleConnection, Connection};
use pg::{Pg, PgQueryBuilder};
use query_builder::{AsQuery, QueryFragment, QueryId};
use query_builder::bin... | (&self) -> QueryResult<()> {
let transaction_depth = self.transaction_depth.get();
self.change_transaction_depth(-1, if transaction_depth <= 1 {
self.execute("COMMIT")
} else {
self.execute(&format!("RELEASE SAVEPOINT diesel_savepoint_{}",
... | commit_transaction | identifier_name |
mod.rs | extern crate libc;
mod cursor;
pub mod raw;
mod row;
#[doc(hidden)]
pub mod result;
mod stmt;
use std::cell::Cell;
use std::ffi::{CString, CStr};
use std::rc::Rc;
use connection::{SimpleConnection, Connection};
use pg::{Pg, PgQueryBuilder};
use query_builder::{AsQuery, QueryFragment, QueryId};
use query_builder::bin... |
#[test]
fn different_queries_have_unique_names() {
let connection = connection();
let one = AsExpression::<Integer>::as_expression(1);
let query = ::select(one);
let query2 = ::select(one.eq(one));
assert_eq!(Ok(1), query.get_result(&connection));
assert_eq!(O... | {
let connection = connection();
let query = ::select(AsExpression::<Integer>::as_expression(1));
assert_eq!(Ok(1), query.get_result(&connection));
assert_eq!(Ok(1), query.get_result(&connection));
assert_eq!(1, connection.statement_cache.len());
} | identifier_body |
mod.rs | extern crate libc;
mod cursor;
pub mod raw;
mod row;
#[doc(hidden)]
pub mod result;
mod stmt;
use std::cell::Cell;
use std::ffi::{CString, CStr};
use std::rc::Rc;
use connection::{SimpleConnection, Connection};
use pg::{Pg, PgQueryBuilder};
use query_builder::{AsQuery, QueryFragment, QueryId};
use query_builder::bin... |
#[test]
fn queries_with_identical_sql_but_different_types_are_cached_separately() {
let connection = connection();
let query = ::select(AsExpression::<Integer>::as_expression(1));
let query2 = ::select(AsExpression::<VarChar>::as_expression("hi"));
assert_eq!(Ok(1), query.get_... | assert_eq!(Ok(true), query2.get_result(&connection));
let statement_names = connection.statement_cache.statement_names();
assert_eq!(2, statement_names.len());
} | random_line_split |
trait.rs | // 不可复制的类型。
struct Empty;
struct Null;
// 用到 `T` 的trait 泛型。
trait DoubleDrop<T> {
// 定义一个关于调用者的方法,接受一个额外的单一参量 `T`,
// 且没有任何操作。
fn double_drop(self, _: T);
}
// 针对泛型参量 `T` 和调用者 `U` 实现了 `DoubleDrop<T>` 。
impl<T, U> DoubleDrop<T> for U {
// 此方法获得了两个传入参数的所有权,并释放这两个参数。
fn double_drop(self, _: T) {}
} | fn main() {
let empty = Empty;
let null = Null;
// 释放 `empty` 和 `null`。
empty.double_drop(null);
//empty;
//null;
// ^ 试一试:去掉这两行的注释。
} | random_line_split | |
trait.rs | // 不可复制的类型。
struct Empty;
struct Nu | // 用到 `T` 的trait 泛型。
trait DoubleDrop<T> {
// 定义一个关于调用者的方法,接受一个额外的单一参量 `T`,
// 且没有任何操作。
fn double_drop(self, _: T);
}
// 针对泛型参量 `T` 和调用者 `U` 实现了 `DoubleDrop<T>` 。
impl<T, U> DoubleDrop<T> for U {
// 此方法获得了两个传入参数的所有权,并释放这两个参数。
fn double_drop(self, _: T) {}
}
fn main() {
let empty = Empty;
l... | ll;
| identifier_name |
many_shr_bor.rs | // Make sure validation can handle many overlapping shared borrows for different parts of a data structure
use std::cell::RefCell;
struct Test {
a: u32,
b: u32,
}
fn test1() {
let t = &mut Test { a: 0, b: 0 };
{
let x;
{
let y = &t.a;
x = &t;
let _y ... | let mut x_ref = x.borrow_mut();
let x_inner : &mut i32 = &mut *x_ref; // new inner write lock, with same lifetime as outer lock
let _x_inner_shr = &*x_inner; // releasing inner write lock, recording suspension
let _y = &*r; // second suspension for the outer write lock
let _x_inner_shr2 = &*x_inner;... | fn test2(r: &mut RefCell<i32>) {
let x = &*r; // releasing write lock, first suspension recorded | random_line_split |
many_shr_bor.rs | // Make sure validation can handle many overlapping shared borrows for different parts of a data structure
use std::cell::RefCell;
struct Test {
a: u32,
b: u32,
}
fn test1() {
let t = &mut Test { a: 0, b: 0 };
{
let x;
{
let y = &t.a;
x = &t;
let _y ... | (r: &mut RefCell<i32>) {
let x = &*r; // releasing write lock, first suspension recorded
let mut x_ref = x.borrow_mut();
let x_inner : &mut i32 = &mut *x_ref; // new inner write lock, with same lifetime as outer lock
let _x_inner_shr = &*x_inner; // releasing inner write lock, recording suspension
l... | test2 | 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/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead o... | {
/// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
/// Events from the compositor that the script task needs to know about
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData),
/// A point was c... | MouseButton | 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/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead o... | /// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
/// Events from the compositor that the script task needs to know about
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData),
/// A point was clic... |
/// The mouse button involved in the event.
#[derive(Clone, Debug)]
pub enum MouseButton { | random_line_split |
encoder.rs | use crate::{Key, Value};
use std::fmt::{self, Write};
use std::sync::atomic::{AtomicUsize, Ordering};
static ENCODER_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Encoder is a mechanism for serializing an attribute set into a specific string
/// representation that supports caching, to avoid repeated serializati... |
if write!(acc, "{}", key).is_err() {
acc.truncate(offset);
return acc;
}
acc.push('=');
if write!(acc, "{}", value).is_err() {
acc.truncate(offset);
return acc;
... | {
acc.push(',')
} | conditional_block |
encoder.rs | use crate::{Key, Value};
use std::fmt::{self, Write};
use std::sync::atomic::{AtomicUsize, Ordering};
static ENCODER_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Encoder is a mechanism for serializing an attribute set into a specific string
/// representation that supports caching, to avoid repeated serializati... | return acc;
}
acc
})
}
fn id(&self) -> EncoderId {
new_encoder_id()
}
}
/// Build a new default encoder
pub fn default_encoder() -> Box<dyn Encoder + Send + Sync> {
Box::new(DefaultAttributeEncoder)
}
/// Build a new encoder id
... | random_line_split | |
encoder.rs | use crate::{Key, Value};
use std::fmt::{self, Write};
use std::sync::atomic::{AtomicUsize, Ordering};
static ENCODER_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// Encoder is a mechanism for serializing an attribute set into a specific string
/// representation that supports caching, to avoid repeated serializati... | (&self, attributes: &mut dyn Iterator<Item = (&Key, &Value)>) -> String {
attributes
.enumerate()
.fold(String::new(), |mut acc, (idx, (key, value))| {
let offset = acc.len();
if idx > 0 {
acc.push(',')
}
... | encode | identifier_name |
shift-various-types.rs | // run-pass
// Test that we can do shifts by any integral type.
struct Panolpy {
i8: i8,
i16: i16,
i32: i32,
i64: i64,
isize: isize,
u8: u8,
u16: u16,
u32: u32,
u64: u64,
usize: usize,
}
fn | (p: &Panolpy) {
assert_eq!(22 >> p.i8, 11);
assert_eq!(22 >> p.i16, 11);
assert_eq!(22 >> p.i32, 11);
assert_eq!(22 >> p.i64, 11);
assert_eq!(22 >> p.isize, 11);
assert_eq!(22 >> p.u8, 11);
assert_eq!(22 >> p.u16, 11);
assert_eq!(22 >> p.u32, 11);
assert_eq!(22 >> p.u64, 11);
as... | foo | identifier_name |
shift-various-types.rs | // run-pass
// Test that we can do shifts by any integral type. |
struct Panolpy {
i8: i8,
i16: i16,
i32: i32,
i64: i64,
isize: isize,
u8: u8,
u16: u16,
u32: u32,
u64: u64,
usize: usize,
}
fn foo(p: &Panolpy) {
assert_eq!(22 >> p.i8, 11);
assert_eq!(22 >> p.i16, 11);
assert_eq!(22 >> p.i32, 11);
assert_eq!(22 >> p.i64, 11);
... | random_line_split | |
reactor.rs | use std::io::{Result};
use std::net::ToSocketAddrs;
use mio::{Sender, Evented, EventLoop, EventLoopConfig, Token, TimerResult, Timeout};
use reactor_handler::{ReactorHandler};
use context::{Context};
use reactor_ctrl::{ReactorCtrl,
ReactorConfig,
ReactorState,
T... | (&mut self) {
self.handler.state = self.state.take();
self.event_loop.run(&mut self.handler).map_err(|_| ()).unwrap();
self.state = self.handler.state.take();
}
/// process all incoming and outgoing events in a loop
pub fn run_once(&mut self) {
self.handler.state = self.stat... | run | identifier_name |
reactor.rs | use std::io::{Result};
use std::net::ToSocketAddrs;
use mio::{Sender, Evented, EventLoop, EventLoopConfig, Token, TimerResult, Timeout};
use reactor_handler::{ReactorHandler};
use context::{Context};
use reactor_ctrl::{ReactorCtrl,
ReactorConfig,
ReactorState,
T... | .deregister(token)
}
/// process all incoming and outgoing events in a loop
pub fn run(&mut self) {
self.handler.state = self.state.take();
self.event_loop.run(&mut self.handler).map_err(|_| ()).unwrap();
self.state = self.handler.state.take();
}
/// process all ... | /// from the event_loop
pub fn deregister(&mut self, token: Token) -> Result<Box<Context>>
{
ReactorCtrl::new(self.state.as_mut().unwrap(), &mut self.event_loop) | random_line_split |
reactor.rs | use std::io::{Result};
use std::net::ToSocketAddrs;
use mio::{Sender, Evented, EventLoop, EventLoopConfig, Token, TimerResult, Timeout};
use reactor_handler::{ReactorHandler};
use context::{Context};
use reactor_ctrl::{ReactorCtrl,
ReactorConfig,
ReactorState,
T... |
/// fetch the event_loop channel for notifying the event_loop of new outbound data
pub fn channel(&self) -> Sender<TaggedBuf> {
self.event_loop.channel()
}
/// Set a timeout to be executed by the event loop after duration milliseconds
/// The supplied handler, which is a FnMut will be inv... | {
ReactorCtrl::new(self.state.as_mut().unwrap(), &mut self.event_loop)
.listen(addr, handler)
} | identifier_body |
borrowck-multiple-captures.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 ... | thread::spawn(move|| {
drop(x); //~ ERROR cannot move `x` into closure because it is borrowed
drop(x); //~ ERROR use of moved value: `x`
});
borrow(&*p);
}
fn same_var_after_move() {
let x: Box<_> = box 1;
drop(x);
thread::spawn(move|| {
drop(x); //~ ERROR capture of mov... | let x: Box<_> = box 1;
let p = &x; | random_line_split |
borrowck-multiple-captures.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 ... | () {
different_vars_after_borrows();
different_vars_after_moves();
same_var_after_borrow();
same_var_after_move();
}
| main | identifier_name |
borrowck-multiple-captures.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 ... |
fn same_var_after_borrow() {
let x: Box<_> = box 1;
let p = &x;
thread::spawn(move|| {
drop(x); //~ ERROR cannot move `x` into closure because it is borrowed
drop(x); //~ ERROR use of moved value: `x`
});
borrow(&*p);
}
fn same_var_after_move() {
let x: Box<_> = box 1;
dro... | {
let x1: Box<_> = box 1;
drop(x1);
let x2: Box<_> = box 2;
drop(x2);
thread::spawn(move|| {
drop(x1); //~ ERROR capture of moved value: `x1`
drop(x2); //~ ERROR capture of moved value: `x2`
});
} | identifier_body |
expr-if-struct.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 test_rec() {
let rs = if true { I {i: 100} } else { I {i: 101} };
assert_eq!(rs.i, 100);
}
#[derive(Copy, Debug)]
enum mood { happy, sad, }
impl PartialEq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool {!(*sel... | random_line_split | |
expr-if-struct.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 ... |
pub fn main() { test_rec(); test_tag(); }
| {
let rs = if true { mood::happy } else { mood::sad };
assert_eq!(rs, mood::happy);
} | identifier_body |
expr-if-struct.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 rs = if true { I {i: 100} } else { I {i: 101} };
assert_eq!(rs.i, 100);
}
#[derive(Copy, Debug)]
enum mood { happy, sad, }
impl PartialEq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool {!(*self).eq(other... | test_rec | identifier_name |
expr-if-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else { mood::sad };
assert_eq!(rs, mood::happy);
}
pub fn main() { test_rec(); test_tag(); }
| { mood::happy } | conditional_block |
crayon.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/.
//! A module for styling terminal output.
//!
//! It would be fair to say that this module ~~is a rip off of~~ is *he... | (&self) -> Style {
Style { italic: true,..*self }
}
/// Applies the 'underline' property.
pub fn underline(&self) -> Style {
Style { underline: true,..*self }
}
/// Applies the 'blink' property.
pub fn blink(&self) -> Style {
Style { blink: true,..*self }
}
///... | italic | identifier_name |
crayon.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/.
//! A module for styling terminal output.
//!
//! It would be fair to say that this module ~~is a rip off of~~ is *he... |
/// Returns a [`Style`] with the 'underline' property set and the foreground
/// colour set to this colour.
///
/// [`Style`]: struct.Style.html
pub fn underline(self) -> Style {
Style { foreground: Some(self), underline: true,..Style::default() }
}
/// Returns a [`Style`] with th... | {
Style { foreground: Some(self), italic: true, ..Style::default() }
} | identifier_body |
crayon.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/.
//! A module for styling terminal output.
//!
//! It would be fair to say that this module ~~is a rip off of~~ is *he... | pub fn reverse(self) -> Style {
Style { foreground: Some(self), reverse: true,..Style::default() }
}
/// Returns a [`Style`] with the 'hidden' property set and the foreground
/// colour set to this colour.
///
/// [`Style`]: struct.Style.html
pub fn hidden(self) -> Style {
S... | random_line_split | |
gemm3_ab_bc_kernel.rs | extern crate momms;
extern crate core;
extern crate typenum;
extern crate hwloc;
extern crate libc;
use typenum::{Unsigned};
use std::time::{Instant};
pub use momms::matrix::{ColumnPanelMatrix, Matrix, Mat};
pub use momms::composables::{GemmNode};
pub use momms::algorithms::{Dgemm3, GotoDgemm3,
... | () {
let mut chained = Dgemm3::new();
let mut goto = GotoDgemm3::new();
let flusher_len = 4*1024*1024; //32MB
let mut flusher: Vec<f64> = Vec::with_capacity(flusher_len);
for _ in 0..flusher_len {
flusher.push(0.0);
}
for index in 1..308 {//512 {
let mut best_time: f64 = 99... | test_gemm3 | identifier_name |
gemm3_ab_bc_kernel.rs | extern crate momms;
extern crate core;
extern crate typenum;
extern crate hwloc;
extern crate libc;
use typenum::{Unsigned};
use std::time::{Instant};
pub use momms::matrix::{ColumnPanelMatrix, Matrix, Mat};
pub use momms::composables::{GemmNode};
pub use momms::algorithms::{Dgemm3, GotoDgemm3,
... | let mut b: Matrix<f64> = Matrix::new(k, l);
let mut c: Matrix<f64> = Matrix::new(l, n);
let mut d: Matrix<f64> = Matrix::new(m, n);
a.fill_rand(); b.fill_rand(); c.fill_rand(); d.fill_zero();
let mut tmp = ColPM::<f64>::new(Dgemm3TmpWidth::to_usize(),
... | {
let mut chained = Dgemm3::new();
let mut goto = GotoDgemm3::new();
let flusher_len = 4*1024*1024; //32MB
let mut flusher: Vec<f64> = Vec::with_capacity(flusher_len);
for _ in 0..flusher_len {
flusher.push(0.0);
}
for index in 1..308 {//512 {
let mut best_time: f64 = 99999... | identifier_body |
gemm3_ab_bc_kernel.rs | extern crate momms;
extern crate core;
extern crate typenum;
extern crate hwloc;
extern crate libc;
use typenum::{Unsigned};
use std::time::{Instant};
pub use momms::matrix::{ColumnPanelMatrix, Matrix, Mat};
pub use momms::composables::{GemmNode};
pub use momms::algorithms::{Dgemm3, GotoDgemm3,
... | let mut flusher: Vec<f64> = Vec::with_capacity(flusher_len);
for _ in 0..flusher_len {
flusher.push(0.0);
}
for index in 1..308 {//512 {
let mut best_time: f64 = 9999999999.0;
let mut best_time_stock: f64 = 9999999999.0;
let mut worst_err: f64 = 0.0;
let size = i... | let flusher_len = 4*1024*1024; //32MB | random_line_split |
typeck-default-trait-impl-cross-crate-coherence.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 ... | struct C;
struct D<T>(T);
impl DefaultedTrait for Box<C> { } //~ ERROR E0321
impl DefaultedTrait for lib::Something<C> { } //~ ERROR E0117
impl DefaultedTrait for D<C> { } // OK
fn main() { } | impl !DefaultedTrait for (B,) { } //~ ERROR E0117
| random_line_split |
typeck-default-trait-impl-cross-crate-coherence.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 ... | ;
struct D<T>(T);
impl DefaultedTrait for Box<C> { } //~ ERROR E0321
impl DefaultedTrait for lib::Something<C> { } //~ ERROR E0117
impl DefaultedTrait for D<C> { } // OK
fn main() { }
| C | identifier_name |
get_profile.rs | //! [GET /_matrix/client/r0/profile/{userId}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-profile-userid)
use ruma_api::ruma_api;
use ruma_identifiers::UserId;
ruma_api! {
metadata {
description: "Get all profile information of an user.",
method: GET,
name: "get_... | request {
/// The user whose profile will be retrieved.
#[ruma_api(path)]
pub user_id: UserId,
}
response {
/// The user's avatar URL, if set.
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<String>,
/// The user's display na... | rate_limited: false,
requires_authentication: false,
}
| random_line_split |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() {
fn | (n: usize) -> bool {
let primes: Vec<usize> = vec![1, 2, 3, 5, 7];
match n < 1 || n % 2 == 0 || n % 3 == 0 ||
primes.iter().filter(|&x| *x == n).collect::<Vec<_>>().len() > 0 {
true => return false,
false => {
let mut i = 5;
loop {
... | is_prime | identifier_name |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() {
fn is_prime(n: usize... |
timeit!(get_prime(10001))
}
| {
(12..)
.filter(|&x| is_prime(x))
.take(n - 5)
.max()
.unwrap()
} | identifier_body |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1); | fn main() {
fn is_prime(n: usize) -> bool {
let primes: Vec<usize> = vec![1, 2, 3, 5, 7];
match n < 1 || n % 2 == 0 || n % 3 == 0 ||
primes.iter().filter(|&x| *x == n).collect::<Vec<_>>().len() > 0 {
true => return false,
false => {
let mut i =... | println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
| random_line_split |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() {
fn is_prime(n: usize... | else {
if n % i == 0 || n % (i + 2) == 0 {
return false;
}
}
i = i + 6;
}
}
}
true
}
fn get_prime(n: usize) -> usize {
(12..)
.filt... | {
break;
} | conditional_block |
parser.rs | use std::fs::File;
use std::io::prelude::*;
use png::errors::PNGError;
use super::chunk::{Chunk, ChunkBuilder};
pub struct ChunkIterator<'a> {
parser: &'a PNGParser<'a>,
}
impl<'a> Iterator for ChunkIterator<'a> {
type Item = Chunk;
fn next (&mut self) -> Option<Chunk> {
self.parser.read_chunk(... | ChunkIterator { parser: self }
}
} | .and_then(|b| b.read_data(self.source))
.map(|b| b.as_chunk())
}
pub fn iter_chunks(&'a self) -> ChunkIterator { | random_line_split |
parser.rs | use std::fs::File;
use std::io::prelude::*;
use png::errors::PNGError;
use super::chunk::{Chunk, ChunkBuilder};
pub struct ChunkIterator<'a> {
parser: &'a PNGParser<'a>,
}
impl<'a> Iterator for ChunkIterator<'a> {
type Item = Chunk;
fn next (&mut self) -> Option<Chunk> {
self.parser.read_chunk(... |
else {
Err(PNGError::InvalidHeader)
}
})
}
pub fn read_chunk(&'a self) -> Result<Chunk, PNGError>{
ChunkBuilder::default()
.read_header(self.source)
.and_then(|b| b.read_data(self.source))
... | {
Ok(())
} | conditional_block |
parser.rs | use std::fs::File;
use std::io::prelude::*;
use png::errors::PNGError;
use super::chunk::{Chunk, ChunkBuilder};
pub struct ChunkIterator<'a> {
parser: &'a PNGParser<'a>,
}
impl<'a> Iterator for ChunkIterator<'a> {
type Item = Chunk;
fn next (&mut self) -> Option<Chunk> {
self.parser.read_chunk(... | (&'a self) -> ChunkIterator {
ChunkIterator { parser: self }
}
}
| iter_chunks | identifier_name |
issue-11577.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 sbar = SBar { num: 2 };
let SBar { num } = sbar;
assert_eq!(num, 2);
} | random_line_split | |
issue-11577.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 vbar = Foo::VBar { num: 1 };
let Foo::VBar { num } = vbar;
assert_eq!(num, 1);
let sbar = SBar { num: 2 };
let SBar { num } = sbar;
assert_eq!(num, 2);
}
| main | identifier_name |
hir_id_validator.rs | use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator};
use rustc_hir as hir;
use rustc_hir::def_id::{LocalDefId, CRATE_DEF_INDEX};
use rustc_hir::intravisit;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::{HirId, ItemLocalId};
use rustc_middle::hir:... | <'a, 'hir> {
hir_map: Map<'hir>,
errors: &'a Lock<Vec<String>>,
}
impl<'a, 'hir> OuterVisitor<'a, 'hir> {
fn new_inner_visitor(&self, hir_map: Map<'hir>) -> HirIdValidator<'a, 'hir> {
HirIdValidator {
hir_map,
owner: None,
hir_ids_seen: Default::default(),
... | OuterVisitor | identifier_name |
hir_id_validator.rs | use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator};
use rustc_hir as hir;
use rustc_hir::def_id::{LocalDefId, CRATE_DEF_INDEX};
use rustc_hir::intravisit;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::{HirId, ItemLocalId};
use rustc_middle::hir:... |
}
impl<'a, 'hir> ItemLikeVisitor<'hir> for OuterVisitor<'a, 'hir> {
fn visit_item(&mut self, i: &'hir hir::Item<'hir>) {
let mut inner_visitor = self.new_inner_visitor(self.hir_map);
inner_visitor.check(i.hir_id(), |this| intravisit::walk_item(this, i));
}
fn visit_trait_item(&mut self, i... | {
HirIdValidator {
hir_map,
owner: None,
hir_ids_seen: Default::default(),
errors: self.errors,
}
} | identifier_body |
hir_id_validator.rs | use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator};
use rustc_hir as hir;
use rustc_hir::def_id::{LocalDefId, CRATE_DEF_INDEX};
use rustc_hir::intravisit;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::{HirId, ItemLocalId};
use rustc_middle::hir:... | self.hir_map.def_path(hir_id.owner).to_string_no_crate_verbose(),
self.hir_map.def_path(owner).to_string_no_crate_verbose()
)
});
}
self.hir_ids_seen.insert(hir_id.local_id);
}
fn visit_impl_item_ref(&mut self, _: &'hir hir::I... | self.hir_map.node_to_string(hir_id), | random_line_split |
hir_id_validator.rs | use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator};
use rustc_hir as hir;
use rustc_hir::def_id::{LocalDefId, CRATE_DEF_INDEX};
use rustc_hir::intravisit;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::{HirId, ItemLocalId};
use rustc_middle::hir:... |
self.hir_ids_seen.insert(hir_id.local_id);
}
fn visit_impl_item_ref(&mut self, _: &'hir hir::ImplItemRef<'hir>) {
// Explicitly do nothing here. ImplItemRefs contain hir::Visibility
// values that actually belong to an ImplItem instead of the ItemKind::Impl
// we are currently... | {
self.error(|| {
format!(
"HirIdValidator: The recorded owner of {} is {} instead of {}",
self.hir_map.node_to_string(hir_id),
self.hir_map.def_path(hir_id.owner).to_string_no_crate_verbose(),
self.hir_map.def_p... | conditional_block |
mod.rs | /*!
Generates an iterator type `Matcher` that looks roughly like
```ignore
mod intern_token {
extern crate regex as regex;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Token<'input>(pub usize, pub &'input str);
// ~~~~~~ ~~~~~~~~~~~
// ... | prefix
);
rust!(out, "{}fmt::Display::fmt(self.1, formatter)", prefix);
rust!(out, "}}");
rust!(out, "}}");
rust!(out, "");
rust!(out, "pub struct {}MatcherBuilder {{", prefix);
rust!(out, "regex_set: {}regex::RegexSet,", prefix);
rust!(out, "regex_vec: Vec<{}regex::Regex>,", pre... | {
let prefix = &grammar.prefix;
rust!(out, "#[cfg_attr(rustfmt, rustfmt_skip)]");
rust!(out, "mod {}intern_token {{", prefix);
rust!(out, "#![allow(unused_imports)]");
try!(out.write_uses("", &grammar));
rust!(out, "extern crate regex as {}regex;", prefix);
rust!(out, "use std::fmt as {}fmt... | identifier_body |
mod.rs | /*!
Generates an iterator type `Matcher` that looks roughly like
```ignore
mod intern_token {
extern crate regex as regex;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Token<'input>(pub usize, pub &'input str);
// ~~~~~~ ~~~~~~~~~~~
// ... | rust!(out, "}}"); // else
rust!(out, "}}"); // fn
rust!(out, "}}"); // impl
rust!(out, "}}"); // mod
Ok(())
} |
rust!(out, "}}"); // else | random_line_split |
mod.rs | /*!
Generates an iterator type `Matcher` that looks roughly like
```ignore
mod intern_token {
extern crate regex as regex;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Token<'input>(pub usize, pub &'input str);
// ~~~~~~ ~~~~~~~~~~~
// ... | <W: Write>(
grammar: &Grammar,
intern_token: &InternToken,
out: &mut RustWrite<W>,
) -> io::Result<()> {
let prefix = &grammar.prefix;
rust!(out, "#[cfg_attr(rustfmt, rustfmt_skip)]");
rust!(out, "mod {}intern_token {{", prefix);
rust!(out, "#![allow(unused_imports)]");
try!(out.write_u... | compile | identifier_name |
lib.rs | pub struct Luhn {
result: Option<String>,
}
#[inline]
fn is_valid(id: &str) -> bool {
let mut index: u32 = 0;
let mut sum: u32 = 0; |
let mut v = match c.to_digit(10) {
Some(d) => d,
None => return false,
};
if index & 1!= 0 {
v *= 2;
if v > 9 {
v -= 9;
}
}
index += 1;
sum += v;
}
index >= 2 && sum % 10 == 0
}
impl... |
for c in id.chars().rev() {
if c.is_whitespace() {
continue;
} | random_line_split |
lib.rs | pub struct Luhn {
result: Option<String>,
}
#[inline]
fn | (id: &str) -> bool {
let mut index: u32 = 0;
let mut sum: u32 = 0;
for c in id.chars().rev() {
if c.is_whitespace() {
continue;
}
let mut v = match c.to_digit(10) {
Some(d) => d,
None => return false,
};
if index & 1!= 0 {
... | is_valid | identifier_name |
lib.rs | pub struct Luhn {
result: Option<String>,
}
#[inline]
fn is_valid(id: &str) -> bool {
let mut index: u32 = 0;
let mut sum: u32 = 0;
for c in id.chars().rev() {
if c.is_whitespace() {
continue;
}
let mut v = match c.to_digit(10) {
Some(d) => d,
... |
}
index += 1;
sum += v;
}
index >= 2 && sum % 10 == 0
}
impl<T> From<T> for Luhn
where
T: ToString,
{
fn from(id: T) -> Self {
let string = id.to_string();
if is_valid(&string) {
return Luhn {
result: Some(string),
};
... | {
v -= 9;
} | conditional_block |
applicationstate.rs | //! The wrapper around the information needed to meaningfully run this program
//!
//! NOTE: in the process of further abstracting IO logic with this --
//! expect things to break
use std;
use crate::cpu;
use crate::debugger::graphics::*;
use crate::io::constants::*;
use crate::io::applicationsettings::ApplicationSe... | let renderer: Box<Renderer> = if app_settings.vulkan_mode {
Box::new(graphics::vulkan::VulkanRenderer::new(&app_settings)?)
} else {
Box::new(graphics::sdl2::Sdl2Renderer::new(&app_settings)?)
};
#[cfg(not(feature = "vulkan"))]
let renderer: Box<Renderer>... | None
};
#[cfg(feature = "vulkan")] | random_line_split |
applicationstate.rs | //! The wrapper around the information needed to meaningfully run this program
//!
//! NOTE: in the process of further abstracting IO logic with this --
//! expect things to break
use std;
use crate::cpu;
use crate::debugger::graphics::*;
use crate::io::constants::*;
use crate::io::applicationsettings::ApplicationSe... |
// Faking hsync to get the games running
let fake_display_hsync = true;
if fake_display_hsync {
// update LY respective to cycles spent execing instruction
let cycle_count = self.cycle_count;
loop {
if cycle_count ... | {
// std::thread::sleep_ms(16);
// trace!("Incrementing the timer!");
self.gameboy.timer_cycle();
self.timer_cycles -= cpu_cycles_per_timer_counter_step;
} | conditional_block |
applicationstate.rs | //! The wrapper around the information needed to meaningfully run this program
//!
//! NOTE: in the process of further abstracting IO logic with this --
//! expect things to break
use std;
use crate::cpu;
use crate::debugger::graphics::*;
use crate::io::constants::*;
use crate::io::applicationsettings::ApplicationSe... | (&mut self) {
//TODO optimize here (quite a bit; need to reduce branches and
// allow for more consecutive instructions to be executed)
let (cycles_per_vblank, cycles_per_hsync, cycles_per_second, cycles_per_divider_step) =
if self.gameboy.gbc_mode && self.gameboy.double_speed {
... | step | identifier_name |
applicationstate.rs | //! The wrapper around the information needed to meaningfully run this program
//!
//! NOTE: in the process of further abstracting IO logic with this --
//! expect things to break
use std;
use crate::cpu;
use crate::debugger::graphics::*;
use crate::io::constants::*;
use crate::io::applicationsettings::ApplicationSe... | let current_op_time = if self.gameboy.state!= cpu::constants::CpuState::Crashed {
self.gameboy.dispatch_opcode() as u64
} else {
10 // FIXME think about what to return here or refactor code around this
};
self.cycle_count += current_op_tim... | {
//TODO optimize here (quite a bit; need to reduce branches and
// allow for more consecutive instructions to be executed)
let (cycles_per_vblank, cycles_per_hsync, cycles_per_second, cycles_per_divider_step) =
if self.gameboy.gbc_mode && self.gameboy.double_speed {
... | identifier_body |
extfn.rs | // Copyright 2013 The SAX-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of ... | (ctx: *const c_void) {
unsafe {
sender_from_ptr(ctx).send(
Ok(StartDocument)
);
}
}
extern "C" fn end_document(ctx: *const c_void) {
unsafe {
sender_from_ptr(ctx).send(
Ok(EndDocument)
);
}
}
extern "C" fn start_element(ctx: *const c_void, name: ... | start_document | identifier_name |
extfn.rs | // Copyright 2013 The SAX-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of ... | isStandalone: None,
hasInternalSubset: None,
hasExternalSubset: None,
resolveEntity: None,
getEntity: None,
entityDecl: None,
notationDecl: None,
attributeDecl: None,
elementD... |
pub fn new_handler() -> ffi::xmlSAXHandler {
ffi::xmlSAXHandler {
internalSubset: None, | random_line_split |
extfn.rs | // Copyright 2013 The SAX-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of ... | {
unsafe {
ErrorData::from_ptr(error).map(|err| {
sender_from_ptr(ctx).send(Err(err.clone()));
});
}
} | identifier_body | |
heap.rs | // Copyright (c) 2017 FaultyRAM
//
// 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 t... | (len: usize, align: usize) -> Result<*mut u8> {
check_len_and_align(len, align).and_then(|_| check_ptr(__rust_allocate(len, align)))
}
#[inline]
/// Allocates a block of memory with all bytes initialized to zero, using the specified length
/// and alignment.
pub unsafe fn allocate_zeroed(len: usize, align: usize) ... | allocate | identifier_name |
heap.rs | // Copyright (c) 2017 FaultyRAM
//
// 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 t... | __rust_deallocate(ptr, len, align)
} | /// Deallocates a block of memory.
pub unsafe fn deallocate(ptr: *mut u8, len: usize, align: usize) { | random_line_split |
heap.rs | // Copyright (c) 2017 FaultyRAM
//
// 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 t... |
}
#[inline]
/// Allocates a block of memory using the specified length and alignment.
pub unsafe fn allocate(len: usize, align: usize) -> Result<*mut u8> {
check_len_and_align(len, align).and_then(|_| check_ptr(__rust_allocate(len, align)))
}
#[inline]
/// Allocates a block of memory with all bytes initialized t... | {
Ok(ptr)
} | conditional_block |
heap.rs | // Copyright (c) 2017 FaultyRAM
//
// 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 t... |
#[inline]
/// Deallocates a block of memory.
pub unsafe fn deallocate(ptr: *mut u8, len: usize, align: usize) {
__rust_deallocate(ptr, len, align)
}
| {
check_len_and_align(len, align).map(|_| __rust_reallocate_inplace(ptr, old_len, len, align))
} | identifier_body |
explicit-self.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {b}
}
}
fn select_based_on_unit_circle<'r, T>(
threshold: float, a: &'r T, b: &'r T) -> &'r T {
let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0);
shape.select(threshold, a, b)
}
#[deriving(Clone)]
struct thing {
x: A
}
#[deriving(Clone)]
struct A {
a: @int
}
fn thing(x: A) -> thing {
... | {a} | conditional_block |
explicit-self.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 ... | {w: float, h: float}
enum shape {
circle(Point, float),
rectangle(Point, Size)
}
fn compute_area(shape: &shape) -> float {
match *shape {
circle(_, radius) => 0.5 * tau * radius * radius,
rectangle(_, ref size) => size.w * size.h
}
}
impl shape {
// self is in the implicit self r... | Size | identifier_name |
explicit-self.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 select_based_on_unit_circle<'r, T>(
threshold: float, a: &'r T, b: &'r T) -> &'r T {
let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0);
shape.select(threshold, a, b)
}
#[deriving(Clone)]
struct thing {
x: A
}
#[deriving(Clone)]
struct A {
a: @int
}
fn thing(x: A) -> thing {
thing {
... | }
| random_line_split |
explicit-self.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 ... |
pub fn quux(&self) -> int { *self.x.a }
pub fn baz<'a>(&'a self) -> &'a A { &self.x }
pub fn spam(self) -> int { *self.x.a }
}
trait Nus { fn f(&self); }
impl Nus for thing { fn f(&self) {} }
pub fn main() {
let x = @thing(A {a: @10});
assert_eq!(x.foo(), 10);
assert_eq!(x.quux(), 10);
... | { *self.x.a } | identifier_body |
extern-yield.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 ... |
#[fixed_stack_segment] #[inline(never)]
fn count(n: uint) -> uint {
unsafe {
task::deschedule();
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
do 10u.times {
do task::spawn {
let result = count(5u);
info!("result = %?", result);
assert_eq!(re... | {
if data == 1u {
data
} else {
count(data - 1u) + count(data - 1u)
}
} | identifier_body |
extern-yield.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 ... | (n: uint) -> uint {
unsafe {
task::deschedule();
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
do 10u.times {
do task::spawn {
let result = count(5u);
info!("result = %?", result);
assert_eq!(result, 16u);
};
}
}
| count | identifier_name |
extern-yield.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // <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::libc;
use std::task;
mod rustrt {
use std::libc;
extern {
pub fn rust_dbg_call(cb: extern "C" fn (libc::uintptr_t) -> libc::uin... | // 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 | random_line_split |
extern-yield.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 ... |
}
#[fixed_stack_segment] #[inline(never)]
fn count(n: uint) -> uint {
unsafe {
task::deschedule();
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
do 10u.times {
do task::spawn {
let result = count(5u);
info!("result = %?", result);
assert_eq!(... | {
count(data - 1u) + count(data - 1u)
} | conditional_block |
filemanager_thread.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 ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use super::{LoadConsumer, LoadData};
use uuid::Uuid;
#[d... | Exit,
}
pub type FileManagerResult<T> = Result<T, FileManagerThreadError>;
#[derive(Debug, Deserialize, Serialize)]
pub enum FileManagerThreadError {
/// The selection action is invalid, nothing is selected
InvalidSelection,
/// Failure to process file information such as file name, modified time etc.... | /// Shut down this thread | random_line_split |
filemanager_thread.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 ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use super::{LoadConsumer, LoadData};
use uuid::Uuid;
#[d... | {
pub id: Uuid,
pub filename: PathBuf,
pub modified: u64,
// https://w3c.github.io/FileAPI/#dfn-type
pub type_string: String,
}
#[derive(Deserialize, Serialize)]
pub enum FileManagerThreadMsg {
/// Select a single file, return triple (FileID, FileName, lastModified)
SelectFile(IpcSender<Fi... | SelectedFile | identifier_name |
pin-needed-to-poll-2.rs | use std::{
future::Future,
pin::Pin,
marker::Unpin,
task::{Context, Poll}, |
struct Sleep(std::marker::PhantomPinned);
impl Future for Sleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(())
}
}
impl Drop for Sleep {
fn drop(&mut self) {}
}
fn sleep() -> Sleep {
Sleep(std::marker::PhantomPinned)
}
s... | }; | random_line_split |
pin-needed-to-poll-2.rs | use std::{
future::Future,
pin::Pin,
marker::Unpin,
task::{Context, Poll},
};
struct Sleep(std::marker::PhantomPinned);
impl Future for Sleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(())
}
}
impl Drop for Sleep {
... | () -> Self {
Self {
sleep: sleep(),
}
}
}
impl Future for MyFuture {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.sleep).poll(cx)
//~^ ERROR `PhantomPinned` cannot be unpinned
}
}
fn ma... | new | identifier_name |
pin-needed-to-poll-2.rs | use std::{
future::Future,
pin::Pin,
marker::Unpin,
task::{Context, Poll},
};
struct Sleep(std::marker::PhantomPinned);
impl Future for Sleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(())
}
}
impl Drop for Sleep {
... | {} | identifier_body | |
strcmp.rs | #[macro_export]
macro_rules! strcmp_tests {
( $TestRegion:path ) => {
use libc::{c_char, c_int, c_void, strcmp};
use lucet_runtime::vmctx::lucet_vmctx;
use lucet_runtime::{lucet_hostcalls, Error, Limits, Region, Val, WASM_PAGE_SIZE};
use std::ffi::CString;
use std::sync::Arc;... | .into_bytes_with_nul();
assert!(s1.len() + s2.len() < WASM_PAGE_SIZE as usize);
let module = test_module_c("strcmp", "guest.c").expect("compile module");
let region = TestRegion::create(10, &Limits::default()).expect("region can be created");
let mut inst... | .into_bytes_with_nul();
let s2 = CString::new(s2)
.expect("s2 is a valid CString") | random_line_split |
text_run.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 app_units::Au;
use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags};
use font::{RunMetrics, ShapingO... | (font: &mut Font, text: &str, options: &ShapingOptions,
breaker: &mut Option<LineBreakLeafIter>) -> (Vec<GlyphRun>, bool) {
let mut glyphs = vec!();
let mut slice = 0..0;
let mut finished = false;
let mut break_at_zero = false;
if breaker.is_none() {
... | break_and_shape | identifier_name |
text_run.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 app_units::Au;
use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags};
use font::{RunMetrics, ShapingO... | })
}
pub fn minimum_splittable_inline_size(&self, range: &Range<ByteIndex>) -> Au {
match self.natural_word_slices_in_range(range).next() {
None => Au(0),
Some(slice) => self.advance_for_range(&slice.range),
}
}
/// Returns the index of the first glyph r... | debug!("iterated on {:?}[{:?}]", slice.offset, slice.range);
max(max_piece_width, self.advance_for_range(&slice.range)) | random_line_split |
text_run.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 app_units::Au;
use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags};
use font::{RunMetrics, ShapingO... |
*breaker = Some(LineBreakLeafIter::new(&text, 0));
}
let breaker = breaker.as_mut().unwrap();
while!finished {
let (idx, _is_hard_break) = breaker.next(text);
if idx == text.len() {
finished = true;
}
if idx == 0 {
... | {
return (glyphs, true)
} | conditional_block |
text_run.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 app_units::Au;
use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags};
use font::{RunMetrics, ShapingO... |
pub fn metrics_for_slice(&self, glyphs: &GlyphStore, slice_range: &Range<ByteIndex>)
-> RunMetrics {
RunMetrics::new(glyphs.advance_for_byte_range(slice_range, self.extra_word_spacing),
self.font_metrics.ascent,
self.font_metrics... | {
RunMetrics::new(self.advance_for_range(range),
self.font_metrics.ascent,
self.font_metrics.descent)
} | identifier_body |
pla.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
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,
th... | /// The index for each input is the index of the corresponding AND term in the same PLA.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
pub struct XC2PLAOrTerm {
/// Indicates whether a particular PLA AND term is a part of this OR term.
///
/// `true` = part of or, `false` = not ... | /// Represents one single OR term in the PLA. Each OR term can perform an OR function on any subset of its inputs. | random_line_split |
pla.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
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,
th... | else {
self.input[i / 8] |= 1 << (i % 8);
}
}
/// Sets whether the `i`th input complement is used in this AND term
pub fn set_b(&mut self, i: usize, val: bool) {
if!val {
self.input_b[i / 8] &= !(1 << (i % 8));
} else {
self.input_b[i / 8] |= 1... | {
self.input[i / 8] &= !(1 << (i % 8));
} | conditional_block |
pla.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
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,
th... | () -> Self {
XC2PLAOrTerm {
input: [0u8; ANDTERMS_PER_FB / 8],
}
}
}
impl XC2PLAOrTerm {
/// Internal function that reads one single OR term from a block of fuses using logical fuse indexing
pub fn from_jed(fuses: &[bool], block_idx: usize, term_idx: usize) -> XC2PLAOrTerm {
... | default | identifier_name |
rc.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/lib/mem/rc.rs
//! Reference-counted shared allocation
use core::{ops,fmt};
use super::grc::Grc;
/// Non-atomic reference counted type
pub struct Rc<T:?Sized> {
_inner: Grc<::core::cell::Cell<usize>, T>,
}
// Rc is not Send or Sync
impl<T:?Sized>!Send... |
}
impl<T:?Sized> Clone for Rc<T> {
fn clone(&self) -> Rc<T> {
Rc { _inner: self._inner.clone() }
}
}
impl<T:?Sized + fmt::Display> fmt::Display for Rc<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
<T as fmt::Display>::fmt(&**self, f)
}
}
impl<T:?Sized + fmt::Debug> fmt::Debug for Rc<T> {
fn fm... | {
self._inner.is_same( &other._inner )
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.