file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | extern crate sdl2;
extern crate rustc_serialize;
use sdl2::keycode::KeyCode;
use sdl2::event::Event;
use sdl2::timer::get_ticks;
mod sprite;
mod assets;
mod draw;
mod player;
mod tile;
mod map;
mod physics;
use sprite::Sprite;
use player::Player;
use player::PlayerStatus;
use draw::Draw;
fn main() { | let window = sdl_context.window("Rust-Man", 640, 480)
.position_centered()
.build()
.ok().expect("Failed to create window.");
//create a renderer
let mut renderer = window.renderer().accelerated().build()
.ok().expect("Failed to create accelerated renderer.");
//create a new player
let mut... | //initialize sdl
let sdl_context = sdl2::init().video().events().build()
.ok().expect("Failed to initialize SDL.");
//create a window | random_line_split |
main.rs | extern crate sdl2;
extern crate rustc_serialize;
use sdl2::keycode::KeyCode;
use sdl2::event::Event;
use sdl2::timer::get_ticks;
mod sprite;
mod assets;
mod draw;
mod player;
mod tile;
mod map;
mod physics;
use sprite::Sprite;
use player::Player;
use player::PlayerStatus;
use draw::Draw;
fn main() {
//initialize ... | }
}
//move player
player.update();
//draw
drawer.clear();
player.draw(&mut drawer, &None);
drawer.present();
//more timer stuff
prev_time = get_ticks();
}
}
println!("Goodbye, world!");
}
| {
//handle event queue
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown {keycode: KeyCode::Escape, .. } => {
running = false
},
Event::KeyDown {keycode: KeyCode::Left, .. } => {
player.status = PlayerStatus::M... | conditional_block |
unsafe_lib.rs | use std::collections::HashMap;
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::ops::{Index, IndexMut};
use std::fmt::Debug;
pub struct MutMap<K, V: Default> {
map: HashMap<K, RefCell<V>>,
}
impl<K: Eq + Hash, V: Default> MutMap<K, V> {
pub fn new() -> Self {
MutMap { map: HashMap::new() ... |
}
impl<T: Hash + Eq + Clone> IndexMut<T> for Counter<T> {
fn index_mut(&mut self, idx: T) -> &mut Self::Output {
if self.map.contains_key(&idx) {
let cntp = self.map[&idx].as_ptr();
unsafe { &mut *cntp }
} else {
self.map.insert(idx.clone(), Cell::new(0));
... | {
if self.map.contains_key(&idx) {
let cntp = self.map[&idx].as_ptr();
unsafe { &*cntp }
} else {
//map.insert(idx, Cell::new(0));
//let mut cntp = map[&idx].as_ptr();
//unsafe {& *cntp}
&ZERO
}
} | identifier_body |
unsafe_lib.rs | use std::collections::HashMap;
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::ops::{Index, IndexMut};
use std::fmt::Debug;
pub struct MutMap<K, V: Default> {
map: HashMap<K, RefCell<V>>,
}
impl<K: Eq + Hash, V: Default> MutMap<K, V> {
pub fn new() -> Self {
MutMap { map: HashMap::new() ... | // Pythonesque Counter implementation
// XXX Move to a separate module
static ZERO: usize = 0;
pub struct Counter<T: Hash + Eq + Clone> {
pub map: HashMap<T, Cell<usize>>,
}
impl<T: Hash + Eq + Clone> Counter<T> {
pub fn new() -> Self {
Counter { map: HashMap::new() }
}
pub fn len(&self) -> usiz... | }
| random_line_split |
unsafe_lib.rs | use std::collections::HashMap;
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::ops::{Index, IndexMut};
use std::fmt::Debug;
pub struct MutMap<K, V: Default> {
map: HashMap<K, RefCell<V>>,
}
impl<K: Eq + Hash, V: Default> MutMap<K, V> {
pub fn new() -> Self {
MutMap { map: HashMap::new() ... | () -> Self {
Counter { map: HashMap::new() }
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn remove(&mut self, idx: &T) {
self.map.remove(idx);
}
}
impl<T: Hash + Eq + Clone> Index<T> for Counter<T> {
type Output = usize;
fn index(&self, idx: T) -> &Self::Outpu... | new | identifier_name |
unsafe_lib.rs | use std::collections::HashMap;
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::ops::{Index, IndexMut};
use std::fmt::Debug;
pub struct MutMap<K, V: Default> {
map: HashMap<K, RefCell<V>>,
}
impl<K: Eq + Hash, V: Default> MutMap<K, V> {
pub fn new() -> Self {
MutMap { map: HashMap::new() ... | else {
self.map.insert(idx.clone(), Cell::new(0));
let cntp = self.map[&idx].as_ptr();
unsafe { &mut *cntp }
}
}
}
| {
let cntp = self.map[&idx].as_ptr();
unsafe { &mut *cntp }
} | conditional_block |
c_win32.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 ... | else {
func
})
})
}
/// Macro for creating a compatibility fallback for a Windows function
///
/// # Example
/// ```
/// compat_fn!(adll32::SomeFunctionW(_arg: LPCWSTR) {
/// // Fallback implementation
/// })
/// ```
///
/// Note that... | {
fallback
} | conditional_block |
c_win32.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 ... | unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); }
0
})
compat_fn!(kernel32::GetFinalPathNameByHandleW(_hFile: HANDLE,
_lpszFilePath: LPCWSTR,
_cchFilePath: D... | compat_fn!(kernel32::CreateSymbolicLinkW(_lpSymlinkFileName: LPCWSTR,
_lpTargetFileName: LPCWSTR,
_dwFlags: DWORD) -> BOOLEAN { | random_line_split |
c_win32.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 ... | (ptr: *mut uint, module: &str, symbol: &str, fallback: uint) {
let module: Vec<u16> = module.utf16_units().collect();
let module = module.append_one(0);
symbol.with_c_str(|symbol| {
let handle = GetModuleHandleW(module.as_ptr());
let func: uint = transmute(GetProcAddress(... | store_func | identifier_name |
video.rs | const VI_V_CURRENT_REG: u32 = 0x10;
const VI_INTR_REG: u32 = 0x0c;
const VI_H_START_REG: u32 = 0x24;
#[derive(Default, Debug)]
pub struct Video {
intr_half_line: u32,
horizontal_video_start: u16,
horizontal_video_end: u16,
current_vertical_line: u16,
}
impl Video {
pub fn read(&self, addr: u32) -... | self.current_vertical_line = (value & 0x3ff) as u16;
// TODO clear interrupt line
}
} | self.current_vertical_line & 0x3ff
}
fn write_current_vertical_line(&mut self, value: u32) { | random_line_split |
video.rs | const VI_V_CURRENT_REG: u32 = 0x10;
const VI_INTR_REG: u32 = 0x0c;
const VI_H_START_REG: u32 = 0x24;
#[derive(Default, Debug)]
pub struct Video {
intr_half_line: u32,
horizontal_video_start: u16,
horizontal_video_end: u16,
current_vertical_line: u16,
}
impl Video {
pub fn read(&self, addr: u32) -... | (&mut self, addr: u32, value: u32) {
match addr {
VI_INTR_REG => self.write_halfline(value),
VI_H_START_REG => self.write_h_video(value),
VI_V_CURRENT_REG => self.write_current_vertical_line(value),
_ => {
panic!("Cannot write to register in Video ... | write | identifier_name |
video.rs | const VI_V_CURRENT_REG: u32 = 0x10;
const VI_INTR_REG: u32 = 0x0c;
const VI_H_START_REG: u32 = 0x24;
#[derive(Default, Debug)]
pub struct Video {
intr_half_line: u32,
horizontal_video_start: u16,
horizontal_video_end: u16,
current_vertical_line: u16,
}
impl Video {
pub fn read(&self, addr: u32) -... |
fn write_halfline(&mut self, value: u32) {
self.intr_half_line = value & 0x3ff;
}
fn read_h_video(&self) -> u32 {
(self.horizontal_video_start as u32) << 16 | (self.horizontal_video_end as u32)
}
fn write_h_video(&mut self, value: u32) {
self.horizontal_video_start = (val... | {
self.intr_half_line
} | identifier_body |
uid_filter.rs | use filter;
use filter::Filter;
use walkdir::DirEntry;
use std::os::unix::fs::MetadataExt;
use std::process;
pub struct UidFilter {
uid: u32,
comp_op: filter::CompOp,
}
impl UidFilter {
pub fn new(comp_op: filter::CompOp, uid: u32) -> UidFilter {
UidFilter{comp_op: comp_op, uid: uid}
}
}
impl... | _ => {
eprintln!("Operator {:?} not covered for attribute uid!", self.comp_op);
process::exit(1);
},
}
}
} | filter::CompOp::Unequal => self.uid != dir_entry.metadata().unwrap().uid(), | random_line_split |
uid_filter.rs | use filter;
use filter::Filter;
use walkdir::DirEntry;
use std::os::unix::fs::MetadataExt;
use std::process;
pub struct UidFilter {
uid: u32,
comp_op: filter::CompOp,
}
impl UidFilter {
pub fn new(comp_op: filter::CompOp, uid: u32) -> UidFilter {
UidFilter{comp_op: comp_op, uid: uid}
}
}
impl... | (&self, dir_entry: &DirEntry) -> bool {
match self.comp_op {
filter::CompOp::Equal => self.uid == dir_entry.metadata().unwrap().uid(),
filter::CompOp::Unequal => self.uid!= dir_entry.metadata().unwrap().uid(),
_ => {
eprintln!("Operator {... | test | identifier_name |
tail.rs | #![crate_name = "tail"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Morten Olsen Lysgaard <morten@lysgaard.no>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with... |
#[inline]
fn print_byte<T: Writer>(stdout: &mut T, ch: &u8) {
if let Err(err) = stdout.write_u8(*ch) {
crash!(1, "{}", err);
}
}
#[inline]
fn print_string<T: Writer>(_: &mut T, s: &String) {
print!("{}", s);
}
fn version () {
println!("{} v{}", NAME, VERSION);
}
| {
if lines {
tail_impl!(String, lines, print_string, reader, line_count, beginning);
} else {
tail_impl!(u8, bytes, print_byte, reader, byte_count, beginning);
}
// if we follow the file, sleep a bit and print the rest if the file has grown.
while follow {
sleep(Duration::mi... | identifier_body |
tail.rs | #![crate_name = "tail"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Morten Olsen Lysgaard <morten@lysgaard.no>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with... |
None => match given_options.opt_str("c") {
Some(n) => {
let mut slice = n.as_slice();
if slice.len() > 0 && slice.char_at(0) == '+' {
beginning = true;
slice = &slice[1..];
}
byte_count = match p... | {
let mut slice = n.as_slice();
if slice.len() > 0 && slice.char_at(0) == '+' {
beginning = true;
slice = &slice[1..];
}
line_count = match parse_size(slice) {
Some(m) => m,
None => {
show... | conditional_block |
tail.rs | #![crate_name = "tail"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Morten Olsen Lysgaard <morten@lysgaard.no>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with... |
// if we follow the file, sleep a bit and print the rest if the file has grown.
while follow {
sleep(Duration::milliseconds(sleep_msec as i64));
for io_line in reader.lines() {
match io_line {
Ok(line) => print!("{}", line),
Err(err) => panic!(err)
... | } else {
tail_impl!(u8, bytes, print_byte, reader, byte_count, beginning);
} | random_line_split |
tail.rs | #![crate_name = "tail"]
#![feature(collections, core, old_io, old_path, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Morten Olsen Lysgaard <morten@lysgaard.no>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with... | <T: Reader>(reader: &mut BufferedReader<T>, mut line_count: usize, mut byte_count: usize, beginning: bool, lines: bool, follow: bool, sleep_msec: u64) {
if lines {
tail_impl!(String, lines, print_string, reader, line_count, beginning);
} else {
tail_impl!(u8, bytes, print_byte, reader, byte_coun... | tail | identifier_name |
textedit.rs | //! Editing text in this library is handled by either `nk_edit_string` or
//! `nk_edit_buffer`. But like almost everything in this library there are multiple
//! ways of doing it and a balance between control and ease of use with memory
//! as well as functionality controlled by flags.
//!
//! This library genera... | //! The final way is using a dynamically growing nk_text_edit struct, which
//! has both a default version if you don't care where memory comes from and an
//! allocator version if you do. While the text editor is quite powerful for its
//! complexity I would not recommend editing gigabytes of data with it.
//! It ... | random_line_split | |
context.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//
//! `x86_64` execution contexts.
//!
//! This is inteded t... | use super::InterruptFrame;
assert_eq!(size_of::<InterruptFrame>(), 32);
}
}
impl fmt::Debug for InterruptFrame {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( f
, "Interrupt Frame: \
\n instruction pointer: {:p} \
\n cod... | #[cfg(test)]
mod test {
#[test]
fn test_interrupt_frame_correct_size() {
use core::mem::size_of; | random_line_split |
context.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//
//! `x86_64` execution contexts.
//!
//! This is inteded t... | () {
use core::mem::size_of;
use super::InterruptFrame;
assert_eq!(size_of::<InterruptFrame>(), 32);
}
}
impl fmt::Debug for InterruptFrame {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( f
, "Interrupt Frame: \
\n instruction poi... | test_interrupt_frame_correct_size | identifier_name |
mod.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... | (time: &Duration) -> String {
format!("{}.{:.9}s", time.as_secs(), time.subsec_nanos())
}
/// Formats the time as microseconds.
pub fn as_micros(time: &Duration) -> u64 {
time.as_secs() * 1_000_000 + time.subsec_nanos() as u64 / 1_000
}
/// Converts U256 into string.
/// TODO Overcomes: https://github.com/paritytec... | format_time | identifier_name |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | else {
format!("\"{:x}\"", v)
}
}
| {
"\"0x0\"".into()
} | conditional_block |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity. | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of t... |
// 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 | random_line_split |
mod.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... |
/// Formats the time as microseconds.
pub fn as_micros(time: &Duration) -> u64 {
time.as_secs() * 1_000_000 + time.subsec_nanos() as u64 / 1_000
}
/// Converts U256 into string.
/// TODO Overcomes: https://github.com/paritytech/bigint/issues/13
pub fn u256_as_str(v: &U256) -> String {
if v.is_zero() {
"\"0x0\"".... | {
format!("{}.{:.9}s", time.as_secs(), time.subsec_nanos())
} | identifier_body |
lib.rs | //! A Rust library for allocation-limited computation of the Discrete Cosine Transform.
//!
//! 1D DCTs are allocation-free but 2D requires allocation.
//!
//! Features:
//!
//! * `simd`: use SIMD types to speed computation (2D DCT only)
//! * `cos-approx`: use a Taylor series approximation of cosine instead of the std... |
}
}
fn dct_1dx2(vec: Vec<f64x2>) -> Vec<f64x2> {
let mut out = Vec::with_capacity(vec.len());
for u in 0.. vec.len() {
let mut z = valx2!(0.0);
for x in 0.. vec.len() {
z += vec[x] * cos_approx(
PI * valx2!(
... | .map(f64x2)
.collect();
dct_1dx2(vals); | random_line_split |
lib.rs | //! A Rust library for allocation-limited computation of the Discrete Cosine Transform.
//!
//! 1D DCTs are allocation-free but 2D requires allocation.
//!
//! Features:
//!
//! * `simd`: use SIMD types to speed computation (2D DCT only)
//! * `cos-approx`: use a Taylor series approximation of cosine instead of the std... |
let test_values = [PI, PI / 2.0, PI / 4.0, 1.0, -1.0, 2.0 * PI, 3.0 * PI, 4.0 / 3.0 * PI];
for &x in &test_values {
test_cos_approx(x);
test_cos_approx(-x);
}
}
/*
#[cfg(feature = "simd")]
mod dct_simd {
use simdty::f64x2;
use std::f64::consts::{PI, SQRT_2};
macro_rules... | {
let approx = cos(x);
let cos = x.cos();
assert!(
approx.abs_sub(x.cos()) <= ERROR,
"Approximation cos({x}) = {approx} was outside a tolerance of {error}; control value: {cos}",
x = x, approx = approx, error = ERROR, cos = cos,
);
} | identifier_body |
lib.rs | //! A Rust library for allocation-limited computation of the Discrete Cosine Transform.
//!
//! 1D DCTs are allocation-free but 2D requires allocation.
//!
//! Features:
//!
//! * `simd`: use SIMD types to speed computation (2D DCT only)
//! * `cos-approx`: use a Taylor series approximation of cosine instead of the std... | else {
x.cos()
}
}
/// Perform a 2D DCT on a 1D-packed vector with a given rowstride.
///
/// E.g. a vector of length 9 with a rowstride of 3 will be processed as a 3x3 matrix.
///
/// Returns a vector of the same size packed in the same way.
pub fn dct_2d(packed_2d: &[f64], rowstride: usize) -> Vec<f64> ... | {
// Normalize to [0, pi] or else the Taylor series spits out very wrong results.
let x = (x.abs() + PI) % (2.0 * PI) - PI;
// Approximate the cosine of `val` using a 4-term Taylor series.
// Can be expanded for higher precision.
let x2 = x.powi(2);
let x4 = x.powi(4);
... | conditional_block |
lib.rs | //! A Rust library for allocation-limited computation of the Discrete Cosine Transform.
//!
//! 1D DCTs are allocation-free but 2D requires allocation.
//!
//! Features:
//!
//! * `simd`: use SIMD types to speed computation (2D DCT only)
//! * `cos-approx`: use a Taylor series approximation of cosine instead of the std... | (packed_2d: &[f64], rowstride: usize) -> Vec<f64> {
assert_eq!(packed_2d.len() % rowstride, 0);
let mut row_dct: Vec<f64> = packed_2d
.chunks(rowstride)
.flat_map(DCT1D::new)
.collect();
swap_rows_columns(&mut row_dct, rowstride);
let mut column_dct: Vec<f64> = packed_2d
.... | dct_2d | identifier_name |
constants.rs | // The MIT License (MIT)
// Copyright © 2014-2018 Miguel Peláez <kernelfreeze@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction, including without limitation... | pub const VERSION_TEXT: &str = "Litecraft A1\nMinecraft 1.13.1"; | /// Debug version string | random_line_split |
real_ints.rs | //! Defines basic operations defined under Real_Ints theory in SMTLIB2.
use std::fmt;
#[macro_use]
use crate::backends::backend::SMTNode;
#[derive(Clone, Debug)]
pub enum OpCodes {
Neg,
Sub,
Add,
Mul,
Div,
Lte,
Lt,
Gte,
Gt,
ToReal,
ToInt,
IsInt,
ConstInt(u64),
... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match *self {
OpCodes::Neg => "-".to_owned(),
OpCodes::Sub => "-".to_owned(),
OpCodes::Add => "+".to_owned(),
OpCodes::Mul => "*".to_owned(),
OpCodes::Div => "/".to_owned(),
OpCodes::... | fmt | identifier_name |
real_ints.rs | //! Defines basic operations defined under Real_Ints theory in SMTLIB2.
use std::fmt;
#[macro_use]
use crate::backends::backend::SMTNode;
#[derive(Clone, Debug)]
pub enum OpCodes { | Neg,
Sub,
Add,
Mul,
Div,
Lte,
Lt,
Gte,
Gt,
ToReal,
ToInt,
IsInt,
ConstInt(u64),
ConstReal(f64),
FreeVar(String),
}
impl fmt::Display for OpCodes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match *self {
OpCodes::Ne... | random_line_split | |
http.rs | use crate::real_std::{
fmt, fs,
path::PathBuf,
pin::Pin,
sync::{Arc, Mutex},
};
use {
collect_mac::collect,
futures::{
future::{self, BoxFuture},
prelude::*,
ready,
task::{self, Poll},
},
http::{
header::{HeaderMap, HeaderName, HeaderValue},
... | (vm: &Thread) -> ArcType {
let r = generic::R::make_type(vm);
Type::app(
vm.find_type_info("std.http.types.HttpEffect")
.map(|alias| alias.into_type())
.unwrap_or_else(|_| Type::hole()),
collect![r],
)
}
}
pub type EffectHandler<T> = Eff... | make_type | identifier_name |
http.rs | use crate::real_std::{
fmt, fs,
path::PathBuf,
pin::Pin,
sync::{Arc, Mutex},
};
use {
collect_mac::collect,
futures::{
future::{self, BoxFuture},
prelude::*,
ready,
task::{self, Poll},
},
http::{
header::{HeaderMap, HeaderName, HeaderValue},
... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "hyper::Body")
}
}
// Since `Body` implements `Userdata` gluon will automatically marshal the gluon representation
// into `&Body` argument
fn read_chunk(body: &Body) -> impl Future<Output = IO<Option<PushAsRef<Bytes, [u8]>>>> {
use f... | impl fmt::Debug for Body { | random_line_split |
http.rs | use crate::real_std::{
fmt, fs,
path::PathBuf,
pin::Pin,
sync::{Arc, Mutex},
};
use {
collect_mac::collect,
futures::{
future::{self, BoxFuture},
prelude::*,
ready,
task::{self, Poll},
},
http::{
header::{HeaderMap, HeaderName, HeaderValue},
... |
pub fn handle<E>(
&mut self,
method: http::Method,
uri: http::Uri,
body: impl Stream<Item = Result<Bytes, E>> + Send +'static,
) -> BoxFuture<'static, crate::Result<hyper::Response<hyper::Body>>>
where
E: fmt::Display + Send +'static,
{
let child_thread =... |
// Retrieve the `handle` function from the http module which we use to evaluate values of type
// `EffectHandler Response`
let handle: Function<RootedThread, ListenFn> = thread
.get_global("std.http.handle")
.unwrap_or_else(|err| panic!("{}", err));
Self { handle... | identifier_body |
arc-rw-read-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 = ~arc::RWArc::new(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
//~^ ERROR cannot infer an appropriate lifetime
}
y.unwrap();
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).rea... | identifier_body | |
arc-rw-read-mode-shouldnt-escape.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.
extern mod extra;
use extra::arc;
fn main() {
let x = ~arc::RWArc::new(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = S... | // 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 |
arc-rw-read-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 = ~arc::RWArc::new(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
//~^ ERROR cannot infer an appropriate lifetime
}
y.unwrap();
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).... | main | identifier_name |
lib.rs | #![feature(if_let)]
use std::os;
use std::io::Command;
use std::io::process::InheritFd;
use std::default::Default;
/// Extra configuration to pass to gcc.
pub struct Config {
/// Directories where gcc will look for header files.
pub include_directories: Vec<Path>,
/// Additional definitions (`-DKEY` or `-... | os::getenv("AR").unwrap_or(if is_android {
format!("{}-ar", target)
} else {
"ar".to_string()
})
}
fn cflags() -> Vec<String> {
os::getenv("CFLAGS").unwrap_or(String::new())
.as_slice().words().map(|s| s.to_string())
.collect()
}
fn ios_flags(target: &str) -> Vec<String> {
... |
fn ar(target: &str) -> String {
let is_android = target.find_str("android").is_some();
| random_line_split |
lib.rs | #![feature(if_let)]
use std::os;
use std::io::Command;
use std::io::process::InheritFd;
use std::default::Default;
/// Extra configuration to pass to gcc.
pub struct Config {
/// Directories where gcc will look for header files.
pub include_directories: Vec<Path>,
/// Additional definitions (`-DKEY` or `-... | else if is_android {
format!("{}-gcc", target)
} else {
"cc".to_string()
})
}
fn ar(target: &str) -> String {
let is_android = target.find_str("android").is_some();
os::getenv("AR").unwrap_or(if is_android {
format!("{}-ar", target)
} else {
"ar".to_string()
})... | {
"gcc".to_string()
} | conditional_block |
lib.rs | #![feature(if_let)]
use std::os;
use std::io::Command;
use std::io::process::InheritFd;
use std::default::Default;
/// Extra configuration to pass to gcc.
pub struct Config {
/// Directories where gcc will look for header files.
pub include_directories: Vec<Path>,
/// Additional definitions (`-DKEY` or `-... |
fn cflags() -> Vec<String> {
os::getenv("CFLAGS").unwrap_or(String::new())
.as_slice().words().map(|s| s.to_string())
.collect()
}
fn ios_flags(target: &str) -> Vec<String> {
let mut is_device_arch = false;
let mut res = Vec::new();
if target.starts_with("arm-") {
res.push("-arch... | {
let is_android = target.find_str("android").is_some();
os::getenv("AR").unwrap_or(if is_android {
format!("{}-ar", target)
} else {
"ar".to_string()
})
} | identifier_body |
lib.rs | #![feature(if_let)]
use std::os;
use std::io::Command;
use std::io::process::InheritFd;
use std::default::Default;
/// Extra configuration to pass to gcc.
pub struct | {
/// Directories where gcc will look for header files.
pub include_directories: Vec<Path>,
/// Additional definitions (`-DKEY` or `-DKEY=VALUE`).
pub definitions: Vec<(String, Option<String>)>,
/// Additional object files to link into the final archive
pub objects: Vec<Path>,
}
impl Default f... | Config | identifier_name |
vperm2i128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vperm2i128_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM0)), operand2: Some(D... | } | random_line_split | |
vperm2i128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM0)), operand2: Some(Direct(YMM5)), operand3: Some(Direct(YMM1)), operand4: Some(Literal8(22)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 85, 70, 193, 22], OperandSiz... | vperm2i128_1 | identifier_name |
vperm2i128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vperm2i128_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM0)), operand2: Some(D... |
fn vperm2i128_4() {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM5)), operand2: Some(Direct(YMM4)), operand3: Some(IndirectScaledDisplaced(RCX, Eight, 707114910, Some(OperandSize::Ymmword), None)), operand4: Some(Literal8(11)), lock: false, rounding_mode: None, merge_mode: None... | {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM4)), operand2: Some(Direct(YMM1)), operand3: Some(Direct(YMM5)), operand4: Some(Literal8(103)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 117, 70, 229, 103], OperandSiz... | identifier_body |
mod.rs | #![macro_escape]
use serialize::json::{Json, ParserError};
use url::Url;
use std::collections::HashMap;
use std::io::IoError;
use std::local_data::Ref;
#[cfg(not(teepee))]
pub use self::http::Client;
#[cfg(teepee)]
pub use self::teepee::Client;
mod http;
mod teepee;
macro_rules! params {
{$($key:expr: $val:ex... |
pub fn has_modhash() -> bool {
_modhash.get().is_some()
}
/// Map a std::io::IoError to a serialize::json::IoError (ParserError variant)
pub fn err_io_to_json_io(err: IoError) -> ParserError {
super::serialize::json::IoError(err.kind, err.desc)
}
#[test]
fn test_params() {
let params = params!{
... | {
_modhash.get()
} | identifier_body |
mod.rs | #![macro_escape]
use serialize::json::{Json, ParserError};
use url::Url;
use std::collections::HashMap;
use std::io::IoError;
use std::local_data::Ref;
#[cfg(not(teepee))]
pub use self::http::Client;
#[cfg(teepee)]
pub use self::teepee::Client;
mod http;
mod teepee;
macro_rules! params {
{$($key:expr: $val:ex... |
#[test]
fn test_params() {
let params = params!{
"hello": "goodbye",
"yes": "no",
};
drop(params);
} | random_line_split | |
mod.rs | #![macro_escape]
use serialize::json::{Json, ParserError};
use url::Url;
use std::collections::HashMap;
use std::io::IoError;
use std::local_data::Ref;
#[cfg(not(teepee))]
pub use self::http::Client;
#[cfg(teepee)]
pub use self::teepee::Client;
mod http;
mod teepee;
macro_rules! params {
{$($key:expr: $val:ex... | (modhash: &str) {
_modhash.replace(Some(modhash.into_string()));
}
pub fn get_modhash() -> Option<Ref<String>> {
_modhash.get()
}
pub fn has_modhash() -> bool {
_modhash.get().is_some()
}
/// Map a std::io::IoError to a serialize::json::IoError (ParserError variant)
pub fn err_io_to_json_io(err: IoError)... | set_modhash | identifier_name |
single_thread_calculator.rs | use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
... |
}
return cnt;
}
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
#[inline]
fn new(_n: usize) -> SingleThreadCalculator {
return SingleThreadCalculator {};
}
#[inline]
fn gen_randoms(&self, n: usize) -> (Vec<f64>, Vec<f64>) {
return SingleThreadCalcul... | {
cnt += 1;
} | conditional_block |
single_thread_calculator.rs | use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
... | (xs: &Arc<Vec<f64>>, ys: &Arc<Vec<f64>>, n: usize) -> u64 {
let mut cnt = 0;
for i in 0..n {
if (xs[i] * xs[i] + ys[i] * ys[i] < 1.0) {
cnt += 1;
}
}
return cnt;
}
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
#[inline]
f... | cal_static | identifier_name |
single_thread_calculator.rs | use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
... |
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
#[inline]
fn new(_n: usize) -> SingleThreadCalculator {
return SingleThreadCalculator {};
}
#[inline]
fn gen_randoms(&self, n: usize) -> (Vec<f64>, Vec<f64>) {
return SingleThreadCalculator::gen_randoms_static(n);
}
... | {
let mut cnt = 0;
for i in 0..n {
if (xs[i] * xs[i] + ys[i] * ys[i] < 1.0) {
cnt += 1;
}
}
return cnt;
} | identifier_body |
single_thread_calculator.rs | use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
... | fn cal_static(xs: &Arc<Vec<f64>>, ys: &Arc<Vec<f64>>, n: usize) -> u64 {
let mut cnt = 0;
for i in 0..n {
if (xs[i] * xs[i] + ys[i] * ys[i] < 1.0) {
cnt += 1;
}
}
return cnt;
}
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
... |
#[inline]
#[allow(unused_parens)] | random_line_split |
square.rs | use malachite_base::num::arithmetic::traits::UnsignedAbs;
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conve... |
#[test]
fn square_properties() {
apply_fn_to_unsigneds!(square_properties_helper_unsigned);
apply_fn_to_unsigned_signed_pairs!(square_properties_helper_signed);
apply_fn_to_primitive_floats!(square_properties_helper_primitive_float);
}
| {
primitive_float_gen::<T>().test_properties(|x| {
let mut square = x;
square.square_assign();
assert_eq!(NiceFloat(square), NiceFloat(x.square()));
assert_eq!(NiceFloat(square), NiceFloat(x.pow(2)));
assert_eq!(NiceFloat((-x).square()), NiceFloat(square));
});
} | identifier_body |
square.rs | use malachite_base::num::arithmetic::traits::UnsignedAbs;
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conve... |
assert_eq!(
U::wrapping_from(square).checked_sqrt().unwrap(),
x.unsigned_abs()
);
});
}
fn square_properties_helper_primitive_float<T: PrimitiveFloat>() {
primitive_float_gen::<T>().test_properties(|x| {
let mut square = x;
square.square_assign();
... | {
assert_eq!((-x).square(), square);
} | conditional_block |
square.rs | use malachite_base::num::arithmetic::traits::UnsignedAbs;
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conve... | <T: PrimitiveFloat>() {
primitive_float_gen::<T>().test_properties(|x| {
let mut square = x;
square.square_assign();
assert_eq!(NiceFloat(square), NiceFloat(x.square()));
assert_eq!(NiceFloat(square), NiceFloat(x.pow(2)));
assert_eq!(NiceFloat((-x).square()), NiceFloat(square... | square_properties_helper_primitive_float | identifier_name |
square.rs | use malachite_base::num::arithmetic::traits::UnsignedAbs;
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conve... | });
}
fn square_properties_helper_signed<
U: PrimitiveUnsigned + WrappingFrom<S>,
S: PrimitiveSigned + UnsignedAbs<Output = U> + WrappingFrom<U>,
>() {
signed_gen_var_10::<U, S>().test_properties(|x| {
let mut square = x;
square.square_assign();
assert_eq!(square, x.square());
... | assert_eq!(square.checked_log_base(x), Some(2));
} | random_line_split |
token.rs | use std;
/// A token.
#[derive(Clone,Debug,PartialEq,Eq)]
pub enum Token
{
/// A word.
Word(String),
/// A string literal.
String(String),
/// An integer literal.
// TODO: use BigNum
Integer(i64),
/// A comment.
///
/// If the comment is inline, it existed on the same line
/... | pub fn is_symbol(&self) -> bool {
if let Token::Symbol(..) = *self { true } else { false }
}
pub fn is_comment(&self) -> bool {
if let Token::Comment {.. } = *self { true } else { false }
}
pub fn is_new_line(&self) -> bool {
if let Token::NewLine = *self { true } else { fa... |
pub fn is_integer(&self) -> bool {
if let Token::String(..) = *self { true } else { false }
}
| random_line_split |
token.rs | use std;
/// A token.
#[derive(Clone,Debug,PartialEq,Eq)]
pub enum Token
{
/// A word.
Word(String),
/// A string literal.
String(String),
/// An integer literal.
// TODO: use BigNum
Integer(i64),
/// A comment.
///
/// If the comment is inline, it existed on the same line
/... | () -> Self { Token::symbol(")") }
pub fn at_sign() -> Self { Token::symbol("@") }
pub fn percent_sign() -> Self { Token::symbol("%") }
pub fn left_curly_brace() -> Self { Token::symbol("{") }
pub fn right_curly_brace() -> Self { Token::symbol("}") }
pub fn equal_sign() -> Self { Token::symbol("=") }... | right_parenthesis | identifier_name |
token.rs | use std;
/// A token.
#[derive(Clone,Debug,PartialEq,Eq)]
pub enum Token
{
/// A word.
Word(String),
/// A string literal.
String(String),
/// An integer literal.
// TODO: use BigNum
Integer(i64),
/// A comment.
///
/// If the comment is inline, it existed on the same line
/... |
}
pub fn is_integer(&self) -> bool {
if let Token::String(..) = *self { true } else { false }
}
pub fn is_symbol(&self) -> bool {
if let Token::Symbol(..) = *self { true } else { false }
}
pub fn is_comment(&self) -> bool {
if let Token::Comment {.. } = *self { true }... | { false } | conditional_block |
arguments.rs | use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Comm {
Type1,
Type2,
None,
}
/// A type of paired token
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Field {
/// Processes (ex: `$(..)`)
Proc,
/// Literal array (ex: `[ 1.. 3 ]`)
Array,
/// Brace exp... | <B: Iterator<Item = u8>>(&mut self, bytes: &mut B) {
while let Some(character) = bytes.next() {
match character {
b'\\' => {
self.read += 2;
let _ = bytes.next();
continue;
}
b'\'' => break,
... | scan_singlequotes | identifier_name |
arguments.rs | use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Comm {
Type1,
Type2,
None,
}
/// A type of paired token
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Field {
/// Processes (ex: `$(..)`)
Proc,
/// Literal array (ex: `[ 1.. 3 ]`)
Array,
/// Brace exp... | b''=> {
if!self.quotes &&!self.method && levels.are_rooted() {
break;
}
}
_ => (),
}
self.read += 1;
// disable COMM_1 and COMM_2
self.comm = Comm::None;
... | random_line_split | |
arguments.rs | use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Comm {
Type1,
Type2,
None,
}
/// A type of paired token
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Field {
/// Processes (ex: `$(..)`)
Proc,
/// Literal array (ex: `[ 1.. 3 ]`)
Array,
/// Brace exp... |
}
| {
let input = "echo 'one two \"three four\"' \"five six 'seven eight'\"";
let expected = vec!["echo", "'one two \"three four\"'", "\"five six 'seven eight'\""];
compare(input, expected);
} | identifier_body |
lib.rs | //! #rust-hackchat
//! A client library for Hack.chat.
//!
//! This library allows you to make custom clients and bots for Hack.chat using Rust.
//!
//! #Examples
//!
//! ```
//! extern crate hackchat;
//! use hackchat::{ChatClient, ChatEvent};
//!
//! fn main() {
//! let mut conn = ChatClient::new("TestBot", "botD... |
}
},
Type::Ping => {
self.sender.lock().unwrap().send_message(&Message::pong(message.payload)).unwrap();
},
_ => {
return None;
}
};
return None;
}... | {
println!("Unsupported message type");
continue;
} | conditional_block |
lib.rs | //! #rust-hackchat
//! A client library for Hack.chat.
//!
//! This library allows you to make custom clients and bots for Hack.chat using Rust.
//!
//! #Examples
//!
//! ```
//! extern crate hackchat;
//! use hackchat::{ChatClient, ChatEvent};
//!
//! fn main() {
//! let mut conn = ChatClient::new("TestBot", "botD... | /// ChatEvent::LeaveRoom(nick) => {
/// chat.send_message(format!("Goodbye {}, see you later!", nick));
/// },
/// _ => {}
/// }
/// }
/// ```
pub fn iter(&mut self) -> ChatClient {
return self.clone();
}
}
impl Iterator for ChatClient... | /// for event in chat.iter() {
/// match event {
/// ChatEvent::JoinRoom(nick) => {
/// chat.send_message(format!("Welcome to the chat {}!", nick));
/// }, | random_line_split |
lib.rs | //! #rust-hackchat
//! A client library for Hack.chat.
//!
//! This library allows you to make custom clients and bots for Hack.chat using Rust.
//!
//! #Examples
//!
//! ```
//! extern crate hackchat;
//! use hackchat::{ChatClient, ChatEvent};
//!
//! fn main() {
//! let mut conn = ChatClient::new("TestBot", "botD... | (&mut self) {
let stats_packet = json!({
"cmd": "stats"
});
let message = Message::text(stats_packet.to_string());
self.sender.lock().unwrap().send_message(&message).unwrap();
}
/// Starts the ping thread, which sends regular pings to keep the connection open.
pu... | send_stats_request | identifier_name |
extern-stress.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 ... | do task::spawn {
assert!(count(5u) == 16u);
};
}
} | random_line_split | |
extern-stress.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 count(n: uint) -> uint {
unsafe {
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
for old_iter::repeat(100u) {
do task::spawn {
assert!(count(5u) == 16u);
};
}
}
| {
task::yield();
count(data - 1u) + count(data - 1u)
} | conditional_block |
extern-stress.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 ... | {
for old_iter::repeat(100u) {
do task::spawn {
assert!(count(5u) == 16u);
};
}
} | identifier_body | |
extern-stress.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 {
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
for old_iter::repeat(100u) {
do task::spawn {
assert!(count(5u) == 16u);
};
}
}
| count | identifier_name |
main.rs | use std::env;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn | (c: char) -> bool
{
match c {
'' => true,
'x' => true,
'y' => true,
'=' => true,
_ => false,
}
}
const WIDTH: usize = 50;
const HEIGHT: usize = 6;
fn main() {
let args: Vec<String> = env::args().collect();
let f = File::open(&args[1]).expect("Could not open file"... | is_splitpoint | identifier_name |
main.rs | use std::env;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn is_splitpoint(c: char) -> bool
{
match c {
'' => true,
'x' => true,
'y' => true,
'=' => true,
_ => false,
}
}
const WIDTH: usize = 50;
const HEIGHT: usize = 6;
fn main() {
let args:... | println!("");
}
println!("{} lights active.", count);
} | print!(" ");
}
} | random_line_split |
main.rs | use std::env;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn is_splitpoint(c: char) -> bool
|
const WIDTH: usize = 50;
const HEIGHT: usize = 6;
fn main() {
let args: Vec<String> = env::args().collect();
let f = File::open(&args[1]).expect("Could not open file");
let reader = BufReader::new(f);
let mut lights = [[false; HEIGHT]; WIDTH];
for line in reader.lines() {
let contents = ... | {
match c {
' ' => true,
'x' => true,
'y' => true,
'=' => true,
_ => false,
}
} | identifier_body |
mod.rs | pub mod md5;
pub mod sha1;
pub trait Hasher
{
/**
* Reset the hasher's state.
*/
fn reset(&mut self);
/**
* Provide input data.
*/
fn update(&mut self, data: &[u8]);
/**
* Retrieve digest result. The output must be large enough to contains result
* size (from output_... | (&self) -> Vec<u8>
{
let size = self.output_size();
let mut buf = Vec::from_elem(size, 0u8);
self.output(buf.as_mut_slice());
buf
}
}
pub trait Hashable {
/**
* Feed the value to the hasher passed in parameter.
*/
fn feed<H: Hasher>(&self, h: &mut H);
/... | digest | identifier_name |
mod.rs | pub mod md5;
pub mod sha1;
pub trait Hasher
{
/**
* Reset the hasher's state.
*/
fn reset(&mut self);
/**
* Provide input data.
*/
fn update(&mut self, data: &[u8]);
/**
* Retrieve digest result. The output must be large enough to contains result
* size (from output_... |
}
| {
h.update(*self)
} | identifier_body |
mod.rs | pub mod md5;
pub mod sha1;
pub trait Hasher
{
/**
* Reset the hasher's state.
*/
fn reset(&mut self);
/**
* Provide input data.
*/
fn update(&mut self, data: &[u8]);
/**
* Retrieve digest result. The output must be large enough to contains result
* size (from output_... | * Get the block size in bytes.
*/
fn block_size(&self) -> uint
{
(self.block_size_bits() + 7) / 8
}
fn digest(&self) -> Vec<u8>
{
let size = self.output_size();
let mut buf = Vec::from_elem(size, 0u8);
self.output(buf.as_mut_slice());
buf
}
}
... | (self.output_size_bits() + 7) / 8
}
/** | random_line_split |
usage.rs | use crate as utils;
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_hir::intravisit;
use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
use rustc_hir::HirIdSet;
use rustc_hir::{Expr, ExprKind, HirId, Path};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_lint::LateContext;
use rustc_middle::hir::map::Ma... |
}
}
| {
intravisit::walk_expr(self, expr);
} | conditional_block |
usage.rs | use crate as utils;
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_hir::intravisit;
use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
use rustc_hir::HirIdSet;
use rustc_hir::{Expr, ExprKind, HirId, Path};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_lint::LateContext;
use rustc_middle::hir::map::Ma... | let mut finder = ParamBindingIdCollector {
binding_hir_ids: Vec::new(),
};
finder.visit_param(param);
for hir_id in &finder.binding_hir_ids {
hir_ids.push(*hir_id);
}
}
hir_ids
}
}
impl<'tcx> intravisit::Visi... | random_line_split | |
usage.rs | use crate as utils;
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_hir::intravisit;
use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
use rustc_hir::HirIdSet;
use rustc_hir::{Expr, ExprKind, HirId, Path};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_lint::LateContext;
use rustc_middle::hir::map::Ma... | (&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
intravisit::NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
}
}
struct ReturnBreakContinueMacroVisitor {
seen_return_break_continue: bool,
}
impl ReturnBreakContinueMacroVisitor {
fn new() -> ReturnBreakContinueMacroVisitor {
ReturnB... | nested_visit_map | identifier_name |
usage.rs | use crate as utils;
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_hir::intravisit;
use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
use rustc_hir::HirIdSet;
use rustc_hir::{Expr, ExprKind, HirId, Path};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_lint::LateContext;
use rustc_middle::hir::map::Ma... |
}
impl<'tcx> intravisit::Visitor<'tcx> for ParamBindingIdCollector {
type Map = Map<'tcx>;
fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
if let hir::PatKind::Binding(_, hir_id,..) = pat.kind {
self.binding_hir_ids.push(hir_id);
}
intravisit::walk_pat(self, pat);
... | {
let mut hir_ids: Vec<hir::HirId> = Vec::new();
for param in body.params.iter() {
let mut finder = ParamBindingIdCollector {
binding_hir_ids: Vec::new(),
};
finder.visit_param(param);
for hir_id in &finder.binding_hir_ids {
... | identifier_body |
markdown.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 input_str = load_or_return!(input, 1, 2);
let mut collector = Collector::new(input.to_string(), libs, externs, true);
find_testable_code(input_str.as_slice(), &mut collector);
test_args.insert(0, "rustdoctest".to_string());
testing::test_main(test_args.as_slice(), collector.tests);
0
} | identifier_body | |
markdown.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 ... | <'a>(s: &'a str) -> (Vec<&'a str>, &'a str) {
let mut metadata = Vec::new();
for line in s.lines() {
if line.starts_with("%") {
// remove %<whitespace>
metadata.push(line[1..].trim_left())
} else {
let line_start_byte = s.subslice_offset(line);
ret... | extract_leading_metadata | identifier_name |
markdown.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 ... | <title>{title}</title>
{css}
{in_header}
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
{before_content}
<h1 class="title">{title}</h1>
{text}... | <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc"> | random_line_split |
lib.rs | #[derive(Debug, PartialEq)]
pub struct Clock {
hours: i16,
minutes: i16,
}
impl Clock {
pub fn new(hours: i16, minutes: i16) -> Self {
Clock { hours, minutes }.normalize()
}
pub fn add_minutes(mut self, n: i16) -> Self {
self.minutes += n;
self.normalize()
}
pub fn... |
fn normalize(mut self) -> Self {
self.hours += self.minutes / 60;
self.minutes %= 60;
self.hours %= 24;
if self.minutes < 0 {
self.hours -= 1;
self.minutes += 60;
}
if self.hours < 0 {
self.hours += 24;
}
self
... | {
format!("{:02}:{:02}", self.hours, self.minutes)
} | identifier_body |
lib.rs | #[derive(Debug, PartialEq)]
pub struct Clock {
hours: i16,
minutes: i16,
}
impl Clock {
pub fn new(hours: i16, minutes: i16) -> Self {
Clock { hours, minutes }.normalize()
}
pub fn add_minutes(mut self, n: i16) -> Self {
self.minutes += n;
self.normalize()
}
pub fn... |
self
}
}
| {
self.hours += 24;
} | conditional_block |
lib.rs | #[derive(Debug, PartialEq)]
pub struct Clock {
hours: i16,
minutes: i16,
}
impl Clock {
pub fn new(hours: i16, minutes: i16) -> Self {
Clock { hours, minutes }.normalize()
}
pub fn add_minutes(mut self, n: i16) -> Self {
self.minutes += n;
self.normalize()
}
pub fn... | (mut self) -> Self {
self.hours += self.minutes / 60;
self.minutes %= 60;
self.hours %= 24;
if self.minutes < 0 {
self.hours -= 1;
self.minutes += 60;
}
if self.hours < 0 {
self.hours += 24;
}
self
}
}
| normalize | identifier_name |
lib.rs | #[derive(Debug, PartialEq)]
pub struct Clock { | minutes: i16,
}
impl Clock {
pub fn new(hours: i16, minutes: i16) -> Self {
Clock { hours, minutes }.normalize()
}
pub fn add_minutes(mut self, n: i16) -> Self {
self.minutes += n;
self.normalize()
}
pub fn to_string(&self) -> String {
format!("{:02}:{:02}", se... | hours: i16, | random_line_split |
step6_file.rs | use std::rc::Rc;
//use std::collections::HashMap;
use fnv::FnvHashMap;
use itertools::Itertools;
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate itertools;
extern crate fnv;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
#[macro_use]
mod types;
use types::... |
fn rep(str: &str, env: &Env) -> Result<String,MalErr> {
let ast = read(str)?;
let exp = eval(ast, env.clone())?;
Ok(print(&exp))
}
fn main() {
let mut args = std::env::args();
let arg1 = args.nth(1);
// `()` can be used when no completer is required
let mut rl = Editor::<()>::new();
if rl.load_histo... | {
ast.pr_str(true)
} | identifier_body |
step6_file.rs | use std::rc::Rc;
//use std::collections::HashMap;
use fnv::FnvHashMap;
use itertools::Itertools;
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate itertools;
extern crate fnv;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
#[macro_use]
mod types;
use types::... | ,
_ => Ok(Nil)
}
},
Sym(ref a0sym) if a0sym == "fn*" => {
let (a1, a2) = (l[1].clone(), l[2].clone());
Ok(MalFunc{eval: eval, ast: Rc::new(a2), env: env,
params: Rc::new(a1), is_macro: false,
meta: Rc::new(Nil)})
... | {
ast = l[2].clone();
continue 'tco;
} | conditional_block |
step6_file.rs | use std::rc::Rc;
//use std::collections::HashMap;
use fnv::FnvHashMap;
use itertools::Itertools;
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate itertools;
extern crate fnv;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
#[macro_use]
mod types;
use types::... | }
}
}
},
_ => eval_ast(&ast, &env),
};
break;
} // end 'tco loop
ret
}
// print
fn print(ast: &MalVal) -> String {
ast.pr_str(true)
}
fn rep(str: &str, env: &Env) -> Result<String,MalErr> {
let ast = read(str)?;
let exp = eval(ast, env.clone())?;
Ok(print(&exp))
}
f... | }
},
_ => {
error("expected a list")
} | random_line_split |
step6_file.rs | use std::rc::Rc;
//use std::collections::HashMap;
use fnv::FnvHashMap;
use itertools::Itertools;
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate itertools;
extern crate fnv;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
#[macro_use]
mod types;
use types::... | (str: &str, env: &Env) -> Result<String,MalErr> {
let ast = read(str)?;
let exp = eval(ast, env.clone())?;
Ok(print(&exp))
}
fn main() {
let mut args = std::env::args();
let arg1 = args.nth(1);
// `()` can be used when no completer is required
let mut rl = Editor::<()>::new();
if rl.load_history(".mal... | rep | identifier_name |
mod.rs | //! Provides functions for maintaining database schema.
//!
//! A database migration always provides procedures to update the schema, as well as to revert
//! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking
//! which migrations have already been run automatically. Your mi... | //! ## Example
//!
//! ```text
//! # Directory Structure
//! - 20151219180527_create_users
//! - up.sql
//! - down.sql
//! - 20160107082941_create_posts
//! - up.sql
//! - down.sql
//! ```
//!
//! ```sql
//! -- 20151219180527_create_users/up.sql
//! CREATE TABLE users (
//! id SERIAL PRIMARY KEY,
//! ... | //! Individual migrations should be a folder containing exactly two files, `up.sql` and `down.sql`.
//! `up.sql` will be used to run the migration, while `down.sql` will be used for reverting it. The
//! folder itself should have the structure `{version}_{migration_name}`. It is recommended that
//! you use the timesta... | random_line_split |
mod.rs | //! Provides functions for maintaining database schema.
//!
//! A database migration always provides procedures to update the schema, as well as to revert
//! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking
//! which migrations have already been run automatically. Your mi... | () {
let dir = TempDir::new("diesel").unwrap();
let temp_path = dir.path().canonicalize().unwrap();
let migrations_path = temp_path.join("migrations");
let child_path = temp_path.join("child");
fs::create_dir(&child_path).unwrap();
fs::create_dir(&migrations_path).unwrap... | migration_directory_checks_parents | identifier_name |
mod.rs | //! Provides functions for maintaining database schema.
//!
//! A database migration always provides procedures to update the schema, as well as to revert
//! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking
//! which migrations have already been run automatically. Your mi... |
#[doc(hidden)]
pub fn revert_migration_with_version(conn: &Connection, ver: &str) -> Result<(), RunMigrationsError> {
migration_with_version(ver)
.map_err(|e| e.into())
.and_then(|m| revert_migration(conn, m))
}
#[doc(hidden)]
pub fn run_migration_with_version(conn: &Connection, ver: &str) -> Resul... | {
try!(create_schema_migrations_table_if_needed(conn));
let latest_migration_version = try!(latest_run_migration_version(conn));
revert_migration_with_version(conn, &latest_migration_version)
.map(|_| latest_migration_version)
} | identifier_body |
life.rs | #![cfg(test)]
use traits::Cell;
use traits::Coord;
use traits::Engine;
use traits::Consumer;
use traits::Grid;
use engine::Sequential;
use grid::twodim::TwodimGrid;
use grid::nhood::MooreNhood;
use grid::EmptyState;
use utils::find_cell;
/// Implementation of Conway's Game of Life.
#[derive(Clone, Debug, PartialEq, Se... | (&self, alive: u32) -> LifeState {
match alive {
3 => LifeState::Alive,
_ => LifeState::Dead,
}
}
#[inline]
fn alive_state(&self, alive: u32) -> LifeState {
match alive {
2 | 3 => LifeState::Alive,
_ => LifeState::Dead,
}
}... | dead_state | identifier_name |
life.rs | #![cfg(test)]
use traits::Cell;
use traits::Coord;
use traits::Engine;
use traits::Consumer;
use traits::Grid;
use engine::Sequential;
use grid::twodim::TwodimGrid;
use grid::nhood::MooreNhood;
use grid::EmptyState;
use utils::find_cell;
/// Implementation of Conway's Game of Life.
#[derive(Clone, Debug, PartialEq, Se... |
// Should be in default state
let default_state = LifeState::Dead;
assert!(grid.cells()
.iter()
.all(|c| c.state == default_state));
// Vertical spinner
// D | A | D
// D | A | D
// D | A | D
let cells = vec![Life {
state: LifeState::Alive,
... | let mut grid: TwodimGrid<Life, _, _> = TwodimGrid::new(3, 3, nhood, EmptyState, 1); | random_line_split |
lib.rs | Data::Union(_) => Error::new(Span::call_site(), "unsupported on unions").to_compile_error(),
}
}
fn derive_unaligned(s: Structure<'_>) -> proc_macro2::TokenStream {
match &s.ast().data {
Data::Struct(strct) => derive_unaligned_struct(&s, strct),
Data::Enum(enm) => derive_unaligned_enum(&s, e... | config_overlaps | identifier_name | |
lib.rs | |
// help: required by the derive of FromBytes
//
// Instead, we have more verbose error messages like "unsupported representation
// for deriving FromBytes, AsBytes, or Unaligned on an enum"
//
// This will probably require Span::error
// (https://doc.rust-lang.org/nightly/proc_macro/struct.Span.html#method.error),
... |
#[rustfmt::skip]
const STRUCT_AS_BYTES_CFG: Config<StructRepr> = {
use StructRepr::*;
Config {
// NOTE: Since disallowed_but_legal_combinations is empty, this message
// will never actually be emitted.
allowed_combinations_message: r#"AsBytes requires repr of "C", "transparent", or "pa... | {
// TODO(joshlf): Support type parameters.
if !s.ast().generics.params.is_empty() {
return Error::new(Span::call_site(), "unsupported on types with type parameters")
.to_compile_error();
}
let reprs = try_or_print!(STRUCT_AS_BYTES_CFG.validate_reprs(s.ast()));
let require_size... | identifier_body |
lib.rs | |
// help: required by the derive of FromBytes
//
// Instead, we have more verbose error messages like "unsupported representation
// for deriving FromBytes, AsBytes, or Unaligned on an enum"
//
// This will probably require Span::error
// (https://doc.rust-lang.org/nightly/proc_macro/struct.Span.html#method.error),... | }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_repr_orderings() {
// Validate that the repr lists in the various configs are in the
// canonical order. If they aren't, then our algorithm to look up in
// those lists won't work.
// TODO(joshlf): Remove once... | random_line_split | |
restyle_hints.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Restyle hints: an optimization to avoid unnecessarily matching selectors.
#[cfg(feature = "gecko")]
use crat... |
/// Returns whether the hint specifies that selector matching must be re-run
/// for the element.
#[inline]
pub fn match_self(&self) -> bool {
self.intersects(RestyleHint::RESTYLE_SELF)
}
/// Returns whether the hint specifies that some cascade levels must be
/// replaced.
#[i... | {
!(*self & !Self::for_animations()).is_empty()
} | identifier_body |
restyle_hints.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Restyle hints: an optimization to avoid unnecessarily matching selectors.
#[cfg(feature = "gecko")]
use crat... | /// descendants.
pub fn contains_subtree(&self) -> bool {
self.contains(RestyleHint::RESTYLE_SELF | RestyleHint::RESTYLE_DESCENDANTS)
}
/// Returns whether we need to restyle this element.
pub fn has_non_animation_invalidations(&self) -> bool {
self.intersects(
RestyleHi... | /// Returns whether this hint invalidates the element and all its | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.