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 |
|---|---|---|---|---|
iterable.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {}
| {
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
it.iter().next()
} | identifier_body |
iterable.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 ... | //~^ ERROR lifetime parameters are not allowed on this type [E0110]
fn iter<'a>(&'a self) -> Self::Iter<'a>;
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
}
// Impl for struct type
impl<T> Iterable for Vec<T> {
type Item<'a> = &'a T;
type Iter<'a> = std::slice::Iter<'a, T>;
... | // follow-up PR.
trait Iterable {
type Item<'a>;
type Iter<'a>: Iterator<Item = Self::Item<'a>>; | random_line_split |
iterable.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 ... | <'a, I: Iterable>(it: &'a I) -> Option<I::Item<'a>> {
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
it.iter().next()
}
fn main() {}
| get_first | identifier_name |
xor-joiner.rs | // Exercise 2.3
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) { | }
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let fname1 = &args[1];
let fname2 = &args[2];
let path1 = Path::new(fname1.clone());
let path2 = Path::new(fname2.clone());
... | ret.push(a[i] ^ b[i]);
}
ret | random_line_split |
xor-joiner.rs | // Exercise 2.3
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>",... | ,
(_, _) => fail!("Error opening input files!")
}
}
}
| {
let share1bytes: ~[u8] = share1.read_to_end();
let share2bytes: ~[u8] = share2.read_to_end();
print!("{:s}", std::str::from_utf8_owned(
xor(share1bytes, share2bytes)));
} | conditional_block |
xor-joiner.rs | // Exercise 2.3
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn | () {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let fname1 = &args[1];
let fname2 = &args[2];
let path1 = Path::new(fname1.clone());
let path2 = Path::new(fname2.clone());
let share... | main | identifier_name |
xor-joiner.rs | // Exercise 2.3
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn main() | }
}
}
| {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let fname1 = &args[1];
let fname2 = &args[2];
let path1 = Path::new(fname1.clone());
let path2 = Path::new(fname2.clone());
let share_f... | identifier_body |
upsert_resolution.rs | // Copyright 2016 Mozilla
//
// 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 the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... |
},
&Term::AddOrRetract(OpType::Add, Right(ref t), a, ref x @ Left(_)) => {
temp_ids.insert(t.clone());
let attribute: &Attribute = schema.require_attribute_for_entid(a)?;
if attribute.unique == Some(attribute::Unique::Identity)... | {
tempid_avs.entry((a, Right(t2.clone()))).or_insert(vec![]).push(t1.clone());
} | conditional_block |
upsert_resolution.rs | // Copyright 2016 Mozilla
//
// 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 the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... |
/// Evolve potential upserts that haven't resolved into allocations.
pub(crate) fn allocate_unresolved_upserts(&mut self) -> Result<()> {
let mut upserts_ev = vec![];
::std::mem::swap(&mut self.upserts_ev, &mut upserts_ev);
self.allocations.extend(upserts_ev.into_iter().map(|UpsertEV(... | {
let mut temp_id_avs: Vec<(TempIdHandle, AVPair)> = vec![];
// TODO: map/collect.
for &UpsertE(ref t, ref a, ref v) in &self.upserts_e {
// TODO: figure out how to make this less expensive, i.e., don't require
// clone() of an arbitrary value.
temp_id_avs.pus... | identifier_body |
upsert_resolution.rs | // Copyright 2016 Mozilla
//
// 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 the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... | &Term::AddOrRetract(OpType::Add, Right(ref t1), a, Right(ref t2)) => {
temp_ids.insert(t1.clone());
temp_ids.insert(t2.clone());
let attribute: &Attribute = schema.require_attribute_for_entid(a)?;
if attribute.unique == Some... | random_line_split | |
upsert_resolution.rs | // Copyright 2016 Mozilla
//
// 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 the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... | (&self) -> bool {
!self.upserts_e.is_empty()
}
/// Evolve this generation one step further by rewriting the existing :db/add entities using the
/// given temporary IDs.
///
/// TODO: Considering doing this in place; the function already consumes `self`.
pub(crate) fn evolve_one_step(self... | can_evolve | identifier_name |
early-vtbl-resolution.rs | // Copyright 2012 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait thing<A> {
... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
early-vtbl-resolution.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 ... | <A, B: thing<A>>(x: B) -> Option<A> { x.foo() }
struct A { a: int }
pub fn main() {
for old_iter::eachi(&(Some(A {a: 0}))) |i, a| {
debug!("%u %d", i, a.a);
}
let _x: Option<float> = foo_func(0);
}
| foo_func | identifier_name |
early-vtbl-resolution.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: Option<float> = foo_func(0);
}
| {
for old_iter::eachi(&(Some(A {a: 0}))) |i, a| {
debug!("%u %d", i, a.a);
} | identifier_body |
download.rs | use std::fmt::{self, Display, Formatter};
use uuid::Uuid;
/// Details of a package for downloading.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
pub struct Package {
pub name: String,
pub version: String
}
impl Display for Package {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
... | pub struct UpdateRequest {
pub requestId: Uuid,
pub status: RequestStatus,
pub packageId: Package,
pub installPos: i32,
pub createdAt: String,
}
/// The current status of an `UpdateRequest`.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
pub enum RequestStatus {
Pending,
... |
/// A request for the device to install a new update.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
#[allow(non_snake_case)] | random_line_split |
download.rs | use std::fmt::{self, Display, Formatter};
use uuid::Uuid;
/// Details of a package for downloading.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
pub struct Package {
pub name: String,
pub version: String
}
impl Display for Package {
fn fmt(&self, f: &mut Formatter) -> fmt::Result |
}
/// A request for the device to install a new update.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
#[allow(non_snake_case)]
pub struct UpdateRequest {
pub requestId: Uuid,
pub status: RequestStatus,
pub packageId: Package,
pub installPos: i32,
pub createdAt: String,
}
... | {
write!(f, "{} {}", self.name, self.version)
} | identifier_body |
download.rs | use std::fmt::{self, Display, Formatter};
use uuid::Uuid;
/// Details of a package for downloading.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
pub struct Package {
pub name: String,
pub version: String
}
impl Display for Package {
fn | (&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{} {}", self.name, self.version)
}
}
/// A request for the device to install a new update.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
#[allow(non_snake_case)]
pub struct UpdateRequest {
pub requestId: Uuid,
pub status: ... | fmt | identifier_name |
imgwin.rs | use glium;
use glium::index::PrimitiveType;
use glium::Surface;
use image;
use std::time::{Duration, Instant};
use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent};
use glium::glutin::event_loop::{ControlFlow, EventLoop};
use glium::glutin::window::WindowBuilder;
use glium::glutin::... |
pub fn new_window(&self, title: impl Into<String>) -> ImgWindow {
ImgWindow::new(title, &self.main_loop)
}
/// Execute the main loop without ever returning. Events are delegated to the given `handler`
/// and `handler.next_frame` is called `fps` times per seconds.
/// Whenever `handler.sh... | {
Application {
main_loop: EventLoop::new(),
}
} | identifier_body |
imgwin.rs | use glium;
use glium::index::PrimitiveType;
use glium::Surface;
use image;
use std::time::{Duration, Instant};
use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent};
use glium::glutin::event_loop::{ControlFlow, EventLoop};
use glium::glutin::window::WindowBuilder;
use glium::glutin::... |
_ => (),
},
Event::NewEvents(StartCause::ResumeTimeReached {.. })
| Event::NewEvents(StartCause::Init) => handler.next_frame(),
_ => (),
}
if handler.should_exit() {
*control_flow = ControlFlow:... | {
handler.key_event(input.virtual_keycode)
} | conditional_block |
imgwin.rs | use glium;
use glium::index::PrimitiveType;
use glium::Surface;
use image;
use std::time::{Duration, Instant};
use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent};
use glium::glutin::event_loop::{ControlFlow, EventLoop};
use glium::glutin::window::WindowBuilder;
use glium::glutin::... | struct Vertex {
position: [f32; 2],
tex_coords: [f32; 2],
}
implement_vertex!(Vertex, position, tex_coords);
/// An Application creates windows and runs a main loop
pub struct Application {
main_loop: EventLoop<()>,
}
impl Application {
pub fn new() -> Application {
Application {
... | use glium::texture::{CompressedSrgbTexture2d, RawImage2d};
use glium::{implement_vertex, program, uniform};
#[derive(Copy, Clone)] | random_line_split |
imgwin.rs | use glium;
use glium::index::PrimitiveType;
use glium::Surface;
use image;
use std::time::{Duration, Instant};
use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent};
use glium::glutin::event_loop::{ControlFlow, EventLoop};
use glium::glutin::window::WindowBuilder;
use glium::glutin::... | (&self) {
let mut target = self.facade.draw();
target.clear_color(0.0, 0.0, 0.0, 0.0);
if let Some(ref texture) = self.texture {
let uniforms = uniform! {
matrix: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
... | redraw | identifier_name |
f23.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut x = 23;
let mut y = 23;
let mut z = 23;
while x > 0 {
x -= 1;
while y > 0 {
y -= 1;
while z > 0 { z -= 1; }
if x > 10 {
return;
"unreachable";
}
}
}
}
| expr_while_23 | identifier_name |
f23.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 ... |
}
}
}
| {
return;
"unreachable";
} | conditional_block |
f23.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 ... | #[allow(unreachable_code)]
pub fn expr_while_23() {
let mut x = 23;
let mut y = 23;
let mut z = 23;
while x > 0 {
x -= 1;
while y > 0 {
y -= 1;
while z > 0 { z -= 1; }
if x > 10 {
return;
"unreachable";
}... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
f23.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut x = 23;
let mut y = 23;
let mut z = 23;
while x > 0 {
x -= 1;
while y > 0 {
y -= 1;
while z > 0 { z -= 1; }
if x > 10 {
return;
"unreachable";
}
}
}
} | identifier_body | |
plugins.rs | // Copyright 2012-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-MI... | n.push_str(".dll");
n
}
#[cfg(target_os="macos")]
fn libname(mut n: String) -> String {
n.push_str(".dylib");
n
}
#[cfg(all(not(target_os="windows"), not(target_os="macos")))]
fn libname(n: String) -> String {
let mut i = String::from_str("lib");
i.push_str(&n);
i.push_str(".so");
i
} | #[cfg(target_os = "windows")]
fn libname(mut n: String) -> String { | random_line_split |
plugins.rs | // Copyright 2012-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-MI... |
/// Load a plugin with the given name.
///
/// Turns `name` into the proper dynamic library filename for the given
/// platform. On windows, it turns into name.dll, on OS X, name.dylib, and
/// elsewhere, libname.so.
pub fn load_plugin(&mut self, name: String) {
let x = self.prefix.joi... | {
PluginManager {
dylibs: Vec::new(),
callbacks: Vec::new(),
prefix: prefix,
}
} | identifier_body |
plugins.rs | // Copyright 2012-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-MI... | (prefix: PathBuf) -> PluginManager {
PluginManager {
dylibs: Vec::new(),
callbacks: Vec::new(),
prefix: prefix,
}
}
/// Load a plugin with the given name.
///
/// Turns `name` into the proper dynamic library filename for the given
/// platform. On... | new | identifier_name |
const-enum-vector.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 ... | { V1(int), V0 }
static C: [E; 3] = [E::V0, E::V1(0xDEADBEE), E::V0];
pub fn main() {
match C[1] {
E::V1(n) => assert!(n == 0xDEADBEE),
_ => panic!()
}
match C[2] {
E::V0 => (),
_ => panic!()
}
}
| E | identifier_name |
const-enum-vector.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum E { V1(int), V0 }
static C: [E; 3] = [E::V0, E::V1(0xDEADBEE), E::V0];
pub fn main... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
const-enum-vector.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 ... | {
match C[1] {
E::V1(n) => assert!(n == 0xDEADBEE),
_ => panic!()
}
match C[2] {
E::V0 => (),
_ => panic!()
}
} | identifier_body | |
hessenberg.rs | use std::cmp;
use nl::Hessenberg;
use na::{DMatrix, Matrix4};
quickcheck!{
fn hessenberg(n: usize) -> bool {
if n!= 0 {
let n = cmp::min(n, 25);
let m = DMatrix::<f64>::new_random(n, n);
match Hessenberg::new(m.clone()) {
Some(hess) => {
... | }
}
} | relative_eq!(m, p * h * p.transpose(), epsilon = 1.0e-7)
},
None => true | random_line_split |
mpq.rs |
use std::fs::File;
use std::io::Read;
use std::ptr::copy_nonoverlapping;
// Result:
// 11011010100010101000001001101
// 1101101010001
fn sp(){
let bytes: [u8; 4] = [77, 80, 81, 27];
let buf_a: [u8; 2] = [77, 80];
let buf_b: [u8; 2] = [81, 27];
let mut num_a: u32 = 0;
let mut num_b: u32 = 0;
... | {
sp();
let mut f: File = File::open("test.replay").unwrap();
let mut buf = [0u8; 4];
let size = f.read(&mut buf).unwrap();
let mut data: u32 = 0;
unsafe {
copy_nonoverlapping(buf.as_ptr(), &mut data as *mut u32 as *mut u8, 4)
}
let bits = data.to_le();
let _string = std::s... | identifier_body | |
mpq.rs |
use std::fs::File;
use std::io::Read;
use std::ptr::copy_nonoverlapping;
// Result:
// 11011010100010101000001001101
// 1101101010001
fn | (){
let bytes: [u8; 4] = [77, 80, 81, 27];
let buf_a: [u8; 2] = [77, 80];
let buf_b: [u8; 2] = [81, 27];
let mut num_a: u32 = 0;
let mut num_b: u32 = 0;
unsafe {
copy_nonoverlapping(buf_a.as_ptr(), &mut num_a as *mut u32 as *mut u8, 2);
copy_nonoverlapping(buf_b.as_ptr(), &mut n... | sp | identifier_name |
mpq.rs | use std::fs::File;
use std::io::Read;
use std::ptr::copy_nonoverlapping;
// Result: | let bytes: [u8; 4] = [77, 80, 81, 27];
let buf_a: [u8; 2] = [77, 80];
let buf_b: [u8; 2] = [81, 27];
let mut num_a: u32 = 0;
let mut num_b: u32 = 0;
unsafe {
copy_nonoverlapping(buf_a.as_ptr(), &mut num_a as *mut u32 as *mut u8, 2);
copy_nonoverlapping(buf_b.as_ptr(), &mut num_b... | // 11011010100010101000001001101
// 1101101010001
fn sp(){ | random_line_split |
lib.rs | /*!
# Kiss3d
Keep It Simple, Stupid 3d graphics engine.
This library is born from the frustration in front of the fact that today’s 3D
graphics library are:
* either too low level: you have to write your own shaders and opening a
window steals you 8 hours, 300 lines of code and 10L of coffee.
* or high level but t... |
c.set_color(1.0, 0.0, 0.0);
window.set_light(Light::StickToCamera);
let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014);
while window.render() {
c.prepend_to_local_rotation(&rot);
}
}
```
The same example, but that will compile for both WASM and native platforms is slig... | random_line_split | |
interpreter.rs | use std::io::{Read, stdin};
use operations::Op;
pub struct Interpreter {
memory: Vec<u8>,
pointer: i64,
ops: Vec<Op>,
}
impl Interpreter {
pub fn new(ops: Vec<Op>) -> Interpreter {
let m = (0.. 30000).map(|_| 0).collect();
Interpreter { memory: m, pointer: 0, ops: ops }
}
pub ... |
}
| {
let mut bal = 0i32;
loop {
if self.ops[*program_counter] == Op::Jump {
bal += 1;
} else if self.ops[*program_counter] == Op::JumpBack {
bal -= 1;
}
*program_counter -= 1;
if bal == 0 {
break;
... | identifier_body |
interpreter.rs | use std::io::{Read, stdin};
use operations::Op;
pub struct Interpreter {
memory: Vec<u8>,
pointer: i64,
ops: Vec<Op>,
}
impl Interpreter {
pub fn new(ops: Vec<Op>) -> Interpreter {
let m = (0.. 30000).map(|_| 0).collect();
Interpreter { memory: m, pointer: 0, ops: ops }
}
pub ... | (&mut self) {
self.memory[self.pointer as usize] -= 1;
}
fn output(&self) {
print!("{}", (self.memory[self.pointer as usize]) as char);
}
fn jump(&mut self, program_counter: &mut usize) {
let mut bal = 1i32;
if self.memory[self.pointer as usize] == 0u8 {
loo... | decrement | identifier_name |
interpreter.rs | use std::io::{Read, stdin};
use operations::Op;
pub struct Interpreter {
memory: Vec<u8>,
pointer: i64,
ops: Vec<Op>,
}
impl Interpreter {
pub fn new(ops: Vec<Op>) -> Interpreter {
let m = (0.. 30000).map(|_| 0).collect();
Interpreter { memory: m, pointer: 0, ops: ops }
}
pub ... | self.pointer -= 1;
}
fn right(&mut self) {
self.pointer += 1;
}
fn input(&mut self) {
let mut input = String::new();
stdin()
.read_line(&mut input).ok().expect("Error reading user input");
self.memory[self.pointer as usize] = input.bytes().next().exp... | }
fn left(&mut self) { | random_line_split |
contracts.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... | // (at your option) any later version.
//
// This program 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... | random_line_split | |
contracts.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... | {
pub contract_context: ContractContext,
}
// AARON: this is an increasingly useless wrapper around a ContractContext struct.
// will probably be removed soon.
impl Contract {
pub fn initialize_from_ast(
contract_identifier: QualifiedContractIdentifier,
contract: &ContractAST,
... | Contract | identifier_name |
regression_fuzz.rs | // These tests are only run for the "default" test target because some of them
// can take quite a long time. Some of them take long enough that it's not
// practical to run them in debug mode. :-/
// See: https://oss-fuzz.com/testcase-detail/5673225499181056
//
// Ignored by default since it takes too long in debug m... |
// See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505
// See: https://github.com/rust-lang/regex/issues/722
#[test]
fn empty_any_errors_no_panic() {
assert!(regex_new!(r"\P{any}").is_err());
}
// This tests that a very large regex errors during compilation instead of
// using gratuitous amounts of ... | {
regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**");
} | identifier_body |
regression_fuzz.rs | // These tests are only run for the "default" test target because some of them
// can take quite a long time. Some of them take long enough that it's not
// practical to run them in debug mode. :-/ | #[test]
#[ignore]
fn fuzz1() {
regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**");
}
// See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505
// See: https://github.com/rust-lang/regex/issues/722
#[test]
fn empty_any_errors_no_panic() {
assert!(regex_new!(r"\P{any}").is_err());
}
// This tests th... |
// See: https://oss-fuzz.com/testcase-detail/5673225499181056
//
// Ignored by default since it takes too long in debug mode (almost a minute). | random_line_split |
regression_fuzz.rs | // These tests are only run for the "default" test target because some of them
// can take quite a long time. Some of them take long enough that it's not
// practical to run them in debug mode. :-/
// See: https://oss-fuzz.com/testcase-detail/5673225499181056
//
// Ignored by default since it takes too long in debug m... | () {
regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**");
}
// See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505
// See: https://github.com/rust-lang/regex/issues/722
#[test]
fn empty_any_errors_no_panic() {
assert!(regex_new!(r"\P{any}").is_err());
}
// This tests that a very large regex erro... | fuzz1 | identifier_name |
lexer.rs | pub type Spanned<Tok, Loc, Error> = Result<(Loc, Tok, Loc), Error>;
#[derive(Debug)]
pub enum Tok {
Space,
Tab,
Linefeed,
}
#[derive(Debug)]
pub enum LexicalError {
// Not possible
}
use std::str::CharIndices;
pub struct | <'input> {
chars: CharIndices<'input>,
}
impl<'input> Lexer<'input> {
pub fn new(input: &'input str) -> Self {
Lexer { chars: input.char_indices() }
}
}
impl<'input> Iterator for Lexer<'input> {
type Item = Spanned<Tok, usize, LexicalError>;
fn next(&mut self) -> Option<Self::Item> {
... | Lexer | identifier_name |
lexer.rs | pub type Spanned<Tok, Loc, Error> = Result<(Loc, Tok, Loc), Error>;
#[derive(Debug)]
pub enum Tok {
Space,
Tab,
Linefeed,
}
#[derive(Debug)]
pub enum LexicalError {
// Not possible
}
use std::str::CharIndices;
pub struct Lexer<'input> {
chars: CharIndices<'input>,
}
impl<'input> Lexer<'input> {... | }
}
impl<'input> Iterator for Lexer<'input> {
type Item = Spanned<Tok, usize, LexicalError>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.chars.next() {
Some((i,'')) => return Some(Ok((i, Tok::Space, i+1))),
Some((i, '\t')) => return Some... | Lexer { chars: input.char_indices() } | random_line_split |
lib.rs | #![deny(missing_docs,
missing_debug_implementations, missing_copy_implementations,
trivial_casts, trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces, unused_qualifications)]
#![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")]
//! Crate allowing creation and manipulation of ... |
/// Render this graph to a Graphviz file
pub fn render_to<W: Write>(&self, output: &mut W) {
match dot::render(self, output) {
Ok(_) => println!("Wrote factor graph"),
Err(_) => panic!("An error occurred writing the factor graph"),
}
}
/// Make a spanning tree ... | {
for var in variables.iter() {
match self.variables.get_mut(var) {
Some(var_obj) => {
var_obj.add_factor(Factor::new(self.next_id,variables.clone(), func));
},
None => panic!("The variable {} was not found in the factor graph.", va... | identifier_body |
lib.rs | #![deny(missing_docs,
missing_debug_implementations, missing_copy_implementations,
trivial_casts, trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces, unused_qualifications)]
#![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")]
//! Crate allowing creation and manipulation of ... | mod tests {
use super::*;
fn dummy_func(args: &[u32]) -> i32 {
args.len() as i32
}
#[test]
#[should_panic]
fn factor_with_nonexistent_var() {
let mut graph = FactorGraph::new();
graph.add_discrete_var("first", vec![1, 2]);
graph.add_factor::<i32>(vec!(String::f... | random_line_split | |
lib.rs | #![deny(missing_docs,
missing_debug_implementations, missing_copy_implementations,
trivial_casts, trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces, unused_qualifications)]
#![doc(html_root_url = "https://cannon10100.github.io/factor_graph/")]
//! Crate allowing creation and manipulation of ... | <W: Write>(&self, root_var: &str, output: &mut W) {
self.make_spanning_tree(root_var).render_to(output)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn dummy_func(args: &[u32]) -> i32 {
args.len() as i32
}
#[test]
#[should_panic]
fn factor_with_nonexistent_var() {
le... | render_spanning_tree_to | identifier_name |
aliased.rs | use backend::Backend;
use expression::{Expression, NonAggregate, SelectableExpression};
use query_builder::*;
use query_builder::nodes::{Identifier, InfixNode};
use query_source::*;
#[derive(Debug, Clone, Copy)]
pub struct | <'a, Expr> {
expr: Expr,
alias: &'a str,
}
impl<'a, Expr> Aliased<'a, Expr> {
pub fn new(expr: Expr, alias: &'a str) -> Self {
Aliased {
expr: expr,
alias: alias,
}
}
}
pub struct FromEverywhere;
impl<'a, T> Expression for Aliased<'a, T> where
T: Expression... | Aliased | identifier_name |
aliased.rs | use backend::Backend;
use expression::{Expression, NonAggregate, SelectableExpression};
use query_builder::*;
use query_builder::nodes::{Identifier, InfixNode};
use query_source::*;
#[derive(Debug, Clone, Copy)]
pub struct Aliased<'a, Expr> {
expr: Expr,
alias: &'a str,
}
impl<'a, Expr> Aliased<'a, Expr> {
... | fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult {
out.push_identifier(&self.alias)
}
}
// FIXME This is incorrect, should only be selectable from WithQuerySource
impl<'a, T, QS> SelectableExpression<QS> for Aliased<'a, T> where
Aliased<'a, T>: Expression,
{
}
impl<'a, T: Expressio... |
impl<'a, T, DB> QueryFragment<DB> for Aliased<'a, T> where
DB: Backend,
T: QueryFragment<DB>,
{ | random_line_split |
aliased.rs | use backend::Backend;
use expression::{Expression, NonAggregate, SelectableExpression};
use query_builder::*;
use query_builder::nodes::{Identifier, InfixNode};
use query_source::*;
#[derive(Debug, Clone, Copy)]
pub struct Aliased<'a, Expr> {
expr: Expr,
alias: &'a str,
}
impl<'a, Expr> Aliased<'a, Expr> {
... |
}
pub struct FromEverywhere;
impl<'a, T> Expression for Aliased<'a, T> where
T: Expression,
{
type SqlType = T::SqlType;
}
impl<'a, T, DB> QueryFragment<DB> for Aliased<'a, T> where
DB: Backend,
T: QueryFragment<DB>,
{
fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult {
ou... | {
Aliased {
expr: expr,
alias: alias,
}
} | identifier_body |
font.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 euclid::{Point2D, Rect, Size2D};
use smallvec::SmallVec;
use std::borrow::ToOwned;
use std::cell::RefCell;
use... | {
/// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property.
/// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null.
pub letter_spacing: Option<Au>,
/// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` ... | ShapingOptions | identifier_name |
font.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 euclid::{Point2D, Rect, Size2D};
use smallvec::SmallVec;
use std::borrow::ToOwned;
use std::cell::RefCell;
use... | }
impl RunMetrics {
pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics {
let bounds = Rect::new(Point2D::new(Au(0), -ascent),
Size2D::new(advance, ascent + descent));
// TODO(Issue #125): support loose and tight bounding boxes; using the
// ascent... | // this bounding box is relative to the left origin baseline.
// so, bounding_box.position.y = -ascent
pub bounding_box: Rect<Au> | random_line_split |
hint.rs | use std::slice;
use std::sync::Arc;
use super::*;
#[derive(Debug)]
#[allow(dead_code)]
pub enum StateOperation {
Remove = 0, // _NET_WM_STATE_REMOVE
Add = 1, // _NET_WM_STATE_ADD
Toggle = 2, // _NET_WM_STATE_TOGGLE
}
impl From<bool> for StateOperation {
fn from(op: bool) -> Self {
if op {
... |
pub fn set_wm_hints(
&self,
window: ffi::Window,
wm_hints: XSmartPointer<'_, ffi::XWMHints>,
) -> Flusher<'_> {
unsafe {
(self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr);
}
Flusher::new(self)
}
pub fn get_normal_hints(&self, windo... | {
let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) };
self.check_errors()?;
let wm_hints = if wm_hints.is_null() {
self.alloc_wm_hints()
} else {
XSmartPointer::new(self, wm_hints).unwrap()
};
Ok(wm_hints)
} | identifier_body |
hint.rs | use std::slice;
use std::sync::Arc;
use super::*;
#[derive(Debug)]
#[allow(dead_code)]
pub enum StateOperation {
Remove = 0, // _NET_WM_STATE_REMOVE
Add = 1, // _NET_WM_STATE_ADD
Toggle = 2, // _NET_WM_STATE_TOGGLE
}
impl From<bool> for StateOperation {
fn from(op: bool) -> Self {
if op {
... | };
unsafe { xconn.get_atom_unchecked(atom_name) }
}
}
pub struct MotifHints {
hints: MwmHints,
}
#[repr(C)]
struct MwmHints {
flags: c_ulong,
functions: c_ulong,
decorations: c_ulong,
input_mode: c_long,
status: c_ulong,
}
#[allow(dead_code)]
mod mwm {
use libc::c_ulon... | Dnd => b"_NET_WM_WINDOW_TYPE_DND\0",
Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", | random_line_split |
hint.rs | use std::slice;
use std::sync::Arc;
use super::*;
#[derive(Debug)]
#[allow(dead_code)]
pub enum StateOperation {
Remove = 0, // _NET_WM_STATE_REMOVE
Add = 1, // _NET_WM_STATE_ADD
Toggle = 2, // _NET_WM_STATE_TOGGLE
}
impl From<bool> for StateOperation {
fn from(op: bool) -> Self {
if op {
... | else {
self.size_hints.flags &=!ffi::PBaseSize;
}
}
}
impl XConnection {
pub fn get_wm_hints(
&self,
window: ffi::Window,
) -> Result<XSmartPointer<'_, ffi::XWMHints>, XError> {
let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) };
sel... | {
self.size_hints.flags |= ffi::PBaseSize;
self.size_hints.base_width = base_width as c_int;
self.size_hints.base_height = base_height as c_int;
} | conditional_block |
hint.rs | use std::slice;
use std::sync::Arc;
use super::*;
#[derive(Debug)]
#[allow(dead_code)]
pub enum StateOperation {
Remove = 0, // _NET_WM_STATE_REMOVE
Add = 1, // _NET_WM_STATE_ADD
Toggle = 2, // _NET_WM_STATE_TOGGLE
}
impl From<bool> for StateOperation {
fn from(op: bool) -> Self {
if op {
... | (&mut self, maximizable: bool) {
if maximizable {
self.add_func(mwm::MWM_FUNC_MAXIMIZE);
} else {
self.remove_func(mwm::MWM_FUNC_MAXIMIZE);
}
}
fn add_func(&mut self, func: c_ulong) {
if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS!= 0 {
if sel... | set_maximizable | identifier_name |
input.rs | // Copyright 2015, 2016 Ethcore (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 later version.... |
let ref key_str: Option<String> = keyval[0];
let ref val_str: Option<String> = keyval[1];
let key = match *key_str {
Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)),
Some(ref k) => Bytes::new(k.clone().into_bytes()),
None => { break; }
};
let val = ma... | {
return Err(Error::custom("Invalid key value pair."));
} | conditional_block |
input.rs | // Copyright 2015, 2016 Ethcore (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 later version.... | <D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer
{
deserializer.deserialize(InputVisitor)
}
}
struct InputVisitor;
impl Visitor for InputVisitor {
type Value = Input;
fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor {
let mut result = ... | deserialize | identifier_name |
input.rs | // Copyright 2015, 2016 Ethcore (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 later version.... |
try!(visitor.end());
let input = Input {
data: result
};
Ok(input)
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use serde_json;
use bytes::Bytes;
use super::Input;
#[test]
fn input_deserialization_from_map() {
let s = r#"{
"0x0045" : "0x0123456789",
"be" : "e",
"0x0a" :... | };
result.insert(key, val);
} | random_line_split |
htmlstyleelement.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 cssparser::{Parser as CssParser, ParserInput};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen... |
impl HTMLStyleElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
creator: ElementCreator) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(local_name, prefi... | any_failed_load: Cell<bool>,
line_number: u64,
} | random_line_split |
htmlstyleelement.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 cssparser::{Parser as CssParser, ParserInput};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen... | (&self, succeeded: bool) -> Option<bool> {
assert!(self.pending_loads.get() > 0, "What finished?");
if!succeeded {
self.any_failed_load.set(true);
}
self.pending_loads.set(self.pending_loads.get() - 1);
if self.pending_loads.get()!= 0 {
return None;
... | load_finished | identifier_name |
htmlstyleelement.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 cssparser::{Parser as CssParser, ParserInput};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen... |
}
| {
self.get_cssom_stylesheet().map(DomRoot::upcast)
} | identifier_body |
htmlstyleelement.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 cssparser::{Parser as CssParser, ParserInput};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen... |
self.pending_loads.set(self.pending_loads.get() - 1);
if self.pending_loads.get()!= 0 {
return None;
}
let any_failed = self.any_failed_load.get();
self.any_failed_load.set(false);
Some(any_failed)
}
fn parser_inserted(&self) -> bool {
self... | {
self.any_failed_load.set(true);
} | conditional_block |
crate-method-reexport-grrrrrrr.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
use crate_method_reexport_grrrrrrr2::rust::add;
use crate_method_reexport_grrrrrrr2::rust::cx;
let x: Box<_> = box () ();
x.cx();
let y = ();
y.add("hi".to_string());
} | identifier_body | |
crate-method-reexport-grrrrrrr.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // aux-build:crate-method-reexport-grrrrrrr2.rs
extern crate crate_method_reexport_grrrrrrr2;
pub fn main() {
use crate_method_reexport_grrrrrrr2::rust::add;
use crate_method_reexport_grrrrrrr2::rust::cx;
let x: Box<_> = box () ();
x.cx();
let y = ();
y.add("hi".to_string());
} |
// This is a regression test that the metadata for the
// name_pool::methods impl in the other crate is reachable from this
// crate.
| random_line_split |
crate-method-reexport-grrrrrrr.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
use crate_method_reexport_grrrrrrr2::rust::add;
use crate_method_reexport_grrrrrrr2::rust::cx;
let x: Box<_> = box () ();
x.cx();
let y = ();
y.add("hi".to_string());
}
| main | identifier_name |
timer.rs | //! Timing and measurement functions.
//!
//! ggez does not try to do any framerate limitation by default. If
//! you want to run at anything other than full-bore max speed all the
//! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html)
//! (or [`timer::yield_now()`](fn.yield_now.... |
}
/// A convenience function to convert a Rust `Duration` type
/// to a (less precise but more useful) `f64`.
///
/// Does not make sure that the `Duration` is within the bounds
/// of the `f64`.
pub fn duration_to_f64(d: time::Duration) -> f64 {
let seconds = d.as_secs() as f64;
let nanos = f64::from(d.subse... | {
sum / u32::try_from(tc.frame_durations.samples).unwrap()
} | conditional_block |
timer.rs | //! Timing and measurement functions.
//!
//! ggez does not try to do any framerate limitation by default. If
//! you want to run at anything other than full-bore max speed all the
//! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html)
//! (or [`timer::yield_now()`](fn.yield_now.... | frame_durations: LogBuffer::new(TIME_LOG_FRAMES, initial_dt),
residual_update_dt: time::Duration::from_secs(0),
frame_count: 0,
}
}
/// Update the state of the `TimeContext` to record that
/// another frame has taken place. Necessary for the FPS
/// tracking... | let initial_dt = time::Duration::from_millis(16);
TimeContext {
init_instant: time::Instant::now(),
last_instant: time::Instant::now(), | random_line_split |
timer.rs | //! Timing and measurement functions.
//!
//! ggez does not try to do any framerate limitation by default. If
//! you want to run at anything other than full-bore max speed all the
//! time, call [`thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html)
//! (or [`timer::yield_now()`](fn.yield_now.... | () -> TimeContext {
let initial_dt = time::Duration::from_millis(16);
TimeContext {
init_instant: time::Instant::now(),
last_instant: time::Instant::now(),
frame_durations: LogBuffer::new(TIME_LOG_FRAMES, initial_dt),
residual_update_dt: time::Duration::fr... | new | identifier_name |
reference.rs | use crate::real_std::{any::Any, fmt, marker::PhantomData, sync::Mutex};
use crate::{
api::{generic::A, Generic, Unrooted, Userdata, WithVM, IO},
gc::{CloneUnrooted, GcPtr, GcRef, Move, Trace},
thread::ThreadInternal,
value::{Cloner, Value},
vm::Thread,
ExternModule, Result,
};
#[derive(VmType)... | pub mod reference {
pub use crate::reference as prim;
}
}
pub fn load(vm: &Thread) -> Result<ExternModule> {
let _ = vm.register_type::<Reference<A>>("std.reference.Reference", &["a"]);
ExternModule::new(
vm,
record! {
type Reference a => Reference<A>,
(s... | mod std { | random_line_split |
reference.rs | use crate::real_std::{any::Any, fmt, marker::PhantomData, sync::Mutex};
use crate::{
api::{generic::A, Generic, Unrooted, Userdata, WithVM, IO},
gc::{CloneUnrooted, GcPtr, GcRef, Move, Trace},
thread::ThreadInternal,
value::{Cloner, Value},
vm::Thread,
ExternModule, Result,
};
#[derive(VmType)... | (a: WithVM<Generic<A>>) -> IO<Reference<A>> {
// SAFETY The returned, unrooted value gets pushed immediately to the stack
unsafe {
IO::Value(Reference {
value: Mutex::new(a.value.get_value().clone_unrooted()),
thread: GcPtr::from_raw(a.vm),
_marker: PhantomData,
... | make_ref | identifier_name |
remove.rs | use cli::parse_args;
use Slate;
use message::Message;
use results::CommandResult;
use errors::CommandError;
const USAGE: &'static str = "
Slate: Remove an element.
Usage:
slate remove ([options] | <key>)
Options:
-h --help Show this screen.
-a --all Remove all keys.
Examples:
slate remove --all
#=> A... | (slate: &Slate, argv: &Vec<String>) -> CommandResult {
let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit());
if args.flag_all {
try!(slate.clear());
Ok(Some(Message::Info("All keys have been removed".to_string())))
} else {
let key: String = match args.arg_key {
... | run | identifier_name |
remove.rs | use cli::parse_args;
use Slate;
use message::Message;
use results::CommandResult;
use errors::CommandError;
const USAGE: &'static str = "
Slate: Remove an element.
Usage:
slate remove ([options] | <key>)
Options:
-h --help Show this screen.
-a --all Remove all keys.
Examples:
slate remove --all
#=> A... | {
let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit());
if args.flag_all {
try!(slate.clear());
Ok(Some(Message::Info("All keys have been removed".to_string())))
} else {
let key: String = match args.arg_key {
Some(string) => string,
None => ... | identifier_body | |
remove.rs | use cli::parse_args;
use Slate;
use message::Message;
use results::CommandResult;
use errors::CommandError;
const USAGE: &'static str = "
Slate: Remove an element.
Usage:
slate remove ([options] | <key>)
Options:
-h --help Show this screen.
-a --all Remove all keys.
Examples: |
slate remove foo
#=> The key has been removed
";
#[derive(Debug, Deserialize)]
struct Args {
arg_key: Option<String>,
flag_all: bool,
}
pub fn run(slate: &Slate, argv: &Vec<String>) -> CommandResult {
let args: Args = parse_args(USAGE, argv).unwrap_or_else(|e| e.exit());
if args.flag_all {
... | slate remove --all
#=> All keys have been removed | random_line_split |
transform.rs | use geometry::Transformable;
use math;
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Transform {
Translate { value: [f32; 3] },
Scale { value: [f32; 3] },
RotateX { value: f32 },
RotateY { value: f32 },
RotateZ { value: f32 },
}
impl Transform {
pub fn to_transform(&self) -> ma... |
}
| {
let transform = self.to_transform();
transformable.transform(&transform);
} | identifier_body |
transform.rs | use geometry::Transformable;
use math;
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Transform {
Translate { value: [f32; 3] },
Scale { value: [f32; 3] },
RotateX { value: f32 },
RotateY { value: f32 },
RotateZ { value: f32 },
}
impl Transform {
pub fn | (&self) -> math::Transform {
match *self {
Transform::Translate { value } => {
math::Transform::new(math::Matrix4::translate(value[0], value[1], value[2]))
}
Transform::Scale { value } => {
math::Transform::new(math::Matrix4::scale(value[0], va... | to_transform | identifier_name |
transform.rs | use geometry::Transformable;
use math;
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Transform {
Translate { value: [f32; 3] },
Scale { value: [f32; 3] },
RotateX { value: f32 },
RotateY { value: f32 },
RotateZ { value: f32 },
}
impl Transform {
pub fn to_transform(&self) -> ma... |
Transform::RotateX { value } => math::Transform::new(math::Matrix4::rot_x(value)),
Transform::RotateY { value } => math::Transform::new(math::Matrix4::rot_y(value)),
Transform::RotateZ { value } => math::Transform::new(math::Matrix4::rot_z(value)),
}
}
pub fn perfor... | {
math::Transform::new(math::Matrix4::scale(value[0], value[1], value[2]))
} | conditional_block |
transform.rs | use geometry::Transformable;
use math;
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Transform {
Translate { value: [f32; 3] },
Scale { value: [f32; 3] },
RotateX { value: f32 },
RotateY { value: f32 },
RotateZ { value: f32 },
}
impl Transform {
pub fn to_transform(&self) -> ma... |
pub fn perform(&self, transformable: &mut dyn Transformable) {
let transform = self.to_transform();
transformable.transform(&transform);
}
} | random_line_split | |
rt.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use st... | assert_initialized_main_thread!();
unsafe { ffi::gdk_screen_height_mm() }
}
pub fn beep() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_flush() }
}
pub fn error_trap_push() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_error_trap_push() }
}
pub fn error_trap_pop() -> i32 {
... | unsafe { ffi::gdk_screen_width_mm() }
}
pub fn screen_height_mm() -> i32 { | random_line_split |
rt.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use st... | -> Option<String> {
assert_initialized_main_thread!();
unsafe {
from_glib_none(ffi::gdk_get_display_arg_name())
}
}
pub fn notify_startup_complete() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_notify_startup_complete() }
}
pub fn notify_startup_complete_with_id(startup_id: &str... | t_display_arg_name() | identifier_name |
rt.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use st... | else if is_initialized() {
panic!("Attempted to initialize GDK from two different threads.");
}
INITIALIZED.store(true, Ordering::Release);
IS_MAIN_THREAD.with(|c| c.set(true));
}
pub fn init() {
assert_not_initialized!();
unsafe {
ffi::gdk_init(ptr::null_mut(), ptr::null_mut());... | return;
}
| conditional_block |
rt.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use st... | pub fn init() {
assert_not_initialized!();
unsafe {
ffi::gdk_init(ptr::null_mut(), ptr::null_mut());
set_initialized();
}
}
pub fn get_display_arg_name() -> Option<String> {
assert_initialized_main_thread!();
unsafe {
from_glib_none(ffi::gdk_get_display_arg_name())
}
}
... | skip_assert_initialized!();
if is_initialized_main_thread() {
return;
}
else if is_initialized() {
panic!("Attempted to initialize GDK from two different threads.");
}
INITIALIZED.store(true, Ordering::Release);
IS_MAIN_THREAD.with(|c| c.set(true));
}
| identifier_body |
basic_client.rs | // use std::io::prelude::*;
use std::net::{Shutdown, TcpStream};
use std::ffi::CString;
use std::thread;
use std::str;
extern crate mbedtls;
use mbedtls::mbed;
use mbedtls::mbed::ssl::error::SSLError;
const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n";
fn main() {
let mut stream = TcpStream::connect("... |
stream.shutdown(Shutdown::Both).unwrap();
}
fn attempt_io<I, F: FnMut() -> Result<I, SSLError>>(mut f: F) -> I {
loop {
match f() {
Ok(i) => return i,
Err(SSLError::WantRead) | Err(SSLError::WantWrite) => {
thread::sleep_ms(100);
continue
... | );
attempt_io(|| ssl_context.close_notify());
} | random_line_split |
basic_client.rs | // use std::io::prelude::*;
use std::net::{Shutdown, TcpStream};
use std::ffi::CString;
use std::thread;
use std::str;
extern crate mbedtls;
use mbedtls::mbed;
use mbedtls::mbed::ssl::error::SSLError;
const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n";
fn | () {
let mut stream = TcpStream::connect("216.58.210.78:443").unwrap();
{
let mut entropy = mbedtls::mbed::entropy::EntropyContext::new();
let mut entropy_func = |d : &mut[u8] | entropy.entropy_func(d);
let mut ctr_drbg = mbed::ctr_drbg::CtrDrbgContext::with_seed(
&mut entr... | main | identifier_name |
basic_client.rs | // use std::io::prelude::*;
use std::net::{Shutdown, TcpStream};
use std::ffi::CString;
use std::thread;
use std::str;
extern crate mbedtls;
use mbedtls::mbed;
use mbedtls::mbed::ssl::error::SSLError;
const TO_WRITE : &'static [u8] = b"GET / HTTP/1.1\r\n\r\n";
fn main() {
let mut stream = TcpStream::connect("... | {
loop {
match f() {
Ok(i) => return i,
Err(SSLError::WantRead) | Err(SSLError::WantWrite) => {
thread::sleep_ms(100);
continue
},
Err(e) => panic!("Got error: {}", e),
}
}
} | identifier_body | |
lib.rs | //! Prime number generator and related functions.
#![warn(
bad_style,
missing_docs,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))]
extern crate... |
while let Some(p) = self.iter.next() {
let p: T = FromPrimitive::from_u64(p).unwrap();
if p.clone() * p.clone() > self.num {
let n = mem::replace(&mut self.num, One::one());
return Some((n, 1));
}
if self.num.is_multiple_of(&p) {... | {
return None;
} | conditional_block |
lib.rs | //! Prime number generator and related functions.
#![warn(
bad_style,
missing_docs,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))]
extern crate... | (&mut self, n: T) {
for (b, e) in n.factorize(self.ps) {
match self.map.entry(b) {
Vacant(entry) => {
let _ = entry.insert(e);
}
Occupied(entry) => {
let p = entry.into_mut();
*p = cmp::max(e,... | lcm_with | identifier_name |
lib.rs | //! Prime number generator and related functions.
#![warn(
bad_style,
missing_docs,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))]
extern crate... |
#[test]
fn multi_iter() {
let ps = PrimeSet::new();
for (p1, p2) in ps.iter().zip(ps.iter()).take(500) {
assert_eq!(p1, p2);
}
}
#[test]
fn clone_clones_data() {
let p1 = PrimeSet::new_empty();
let p2 = p1.clone();
let _ = p1.nth(5000);
... | {
let ps = PrimeSet::new();
assert!(!ps.contains(0));
assert!(!ps.contains(1));
assert!(ps.contains(2));
assert!(ps.contains(3));
assert!(!ps.contains(4));
assert!(ps.contains(5));
assert!(!ps.contains(6));
assert!(ps.contains(7));
assert!(... | identifier_body |
lib.rs | //! Prime number generator and related functions.
#![warn(
bad_style,
missing_docs,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))]
extern crate... | (48, 10),
(60, 12),
(50, 6),
];
let ps = PrimeSet::new();
for &(n, num_div) in pairs {
assert_eq!(num_div, n.num_of_divisor(&ps));
assert_eq!(num_div, (-n).num_of_divisor(&ps));
}
}
#[test]
fn sum_of_divisor() {
... | (24, 8),
(36, 9), | random_line_split |
init-res-into-things.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 i = @mut 0;
{
let a = Box {x: r(i)};
}
assert_eq!(*i, 1);
}
fn test_tag() {
enum t {
t0(r),
}
let i = @mut 0;
{
let a = t0(r(i));
}
assert_eq!(*i, 1);
}
fn test_tup() {
let i = @mut 0;
{
let a = (r(i), 0);
}
... | {
let i = @mut 0;
{
let a = @r(i);
}
assert_eq!(*i, 1);
} | identifier_body |
init-res-into-things.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 ... | struct Box { x: r }
#[unsafe_destructor]
impl Drop for r {
fn drop(&self) {
unsafe {
*(self.i) = *(self.i) + 1;
}
}
}
fn r(i: @mut int) -> r {
r {
i: i
}
}
fn test_box() {
let i = @mut 0;
{
let a = @r(i);
}
assert_eq!(*i, 1);
}
fn test_rec(... | struct r {
i: @mut int,
}
| random_line_split |
init-res-into-things.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 i = @mut 0;
{
let a = (r(i), 0);
}
assert_eq!(*i, 1);
}
fn test_unique() {
let i = @mut 0;
{
let a = ~r(i);
}
assert_eq!(*i, 1);
}
fn test_box_rec() {
let i = @mut 0;
{
let a = @Box {
x: r(i)
};
}
assert_eq!(*i, 1);
}... | test_tup | identifier_name |
keyframes.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 cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser,... | {
pub selector: KeyframeSelector,
/// `!important` is not allowed in keyframe declarations,
/// so the second value of these tuples is always `Importance::Normal`.
/// But including them enables `compute_style_for_animation_step` to create a `ApplicableDeclarationBlock`
/// by cloning an `Arc<_>` ... | Keyframe | identifier_name |
keyframes.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 cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser,... | let mut results = Vec::new();
match PropertyDeclaration::parse(name, self.context, input, &mut results, true) {
PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => {}
_ => return Err(())
}
Ok(results)
}
} | identifier_body | |
keyframes.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 cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser,... | _ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///... | block.read().declarations.iter().any(|&(ref prop_decl, _)| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
| conditional_block |
keyframes.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 cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser,... | Some(KeyframesAnimation {
steps: steps,
properties_changed: animated_properties,
})
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a> {
context: &'a ParserConte... | if steps.last().unwrap().start_percentage.0 != 1. {
steps.push(KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues));
}
| random_line_split |
p074.rs | //! [Problem 74](https://projecteuler.net/problem=74) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::collections::HashMap;
#[derive(Clone)]
enum Length {
Loop(usize),
Chain(usize),
Unknown,
}
fn fa... | () {
let factorial = {
let mut val = [1; 10];
for i in 1..10 {
val[i] = val[i - 1] * (i as u32);
}
val
};
let mut map = iter::repeat(super::Length::Unknown)
.take((factorial[9] * 6 + 1) as usize)
.collect::<Vec... | len | identifier_name |
p074.rs | //! [Problem 74](https://projecteuler.net/problem=74) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::collections::HashMap;
#[derive(Clone)]
enum Length {
Loop(usize),
Chain(usize),
Unknown, | fn fact_sum(mut n: u32, fs: &[u32; 10]) -> u32 {
if n == 0 {
return 1;
}
let mut sum = 0;
while n > 0 {
sum += fs[(n % 10) as usize];
n /= 10;
}
sum
}
fn get_chain_len(n: u32, map: &mut [Length], fs: &[u32; 10]) -> usize {
let mut chain_map = HashMap::new();
let... | }
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.