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 |
|---|---|---|---|---|
shader.rs | use vecmath::Matrix4;
use gfx;
use gfx::{Device, DeviceHelper, ToSlice};
use device;
use device::draw::CommandBuffer;
use render;
static VERTEX: gfx::ShaderSource = shaders! {
GLSL_120: b"
#version 120
uniform mat4 projection, view;
attribute vec2 tex_coord;
attribute vec3 color, position;
varyin... | (&mut self, view_mat: Matrix4<f32>) {
self.params.view = view_mat;
}
pub fn clear(&mut self) {
self.graphics.clear(self.cd, gfx::COLOR | gfx::DEPTH, &self.frame);
}
pub fn create_buffer(&mut self, data: &[Vertex]) -> Buffer {
let buf = self.graphics.device.create_buffer(data.le... | set_view | identifier_name |
reader.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 self.reader.read_at_least(v.len(), v) {
Ok(_) => {}
Err(e) => panic!("ReaderRng.fill_bytes error: {}", e)
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::ReaderRng;
use io::MemReader;
use num::Int;
use rand::Rng;
#[test]
fn test_... | { return } | conditional_block |
reader.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 ... |
fn next_u64(&mut self) -> u64 {
// see above for explanation.
if cfg!(target_endian="little") {
self.reader.read_le_u64().unwrap()
} else {
self.reader.read_be_u64().unwrap()
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { retur... | {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="little") {
self.reader.read_le_u32().unwrap()
} else {
... | identifier_body |
reader.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 ... | (&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
match self.reader.read_at_least(v.len(), v) {
Ok(_) => {}
Err(e) => panic!("ReaderRng.fill_bytes error: {}", e)
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::ReaderRng;
use io::MemReader;
... | fill_bytes | identifier_name |
reader.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 ... | }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
match self.reader.read_at_least(v.len(), v) {
Ok(_) => {}
Err(e) => panic!("ReaderRng.fill_bytes error: {}", e)
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::R... | self.reader.read_be_u64().unwrap() | random_line_split |
main.rs | //! # Synacor Challenge
//!
//! A Rust based runtime for the Synacor challenge architecture.
#![warn(missing_docs)]
extern crate byteorder;
extern crate termion;
#[macro_use] extern crate chan;
extern crate chan_signal;
extern crate libc;
extern crate synacor;
mod command;
mod debugger;
use debugger::Debugger;
use s... | () {
let binary = if let Some(val) = args().nth(1) {
let mut buffer = Vec::new();
let mut in_file = File::open(val)
.expect("Failed to open challenge binary.");
in_file.read_to_end(&mut buffer)
.expect("Failed to read in binary contents.");
buffer
} else {
... | main | identifier_name |
main.rs | //! # Synacor Challenge
//!
//! A Rust based runtime for the Synacor challenge architecture.
#![warn(missing_docs)]
extern crate byteorder;
extern crate termion;
#[macro_use] extern crate chan;
extern crate chan_signal;
extern crate libc;
extern crate synacor;
mod command;
mod debugger;
use debugger::Debugger;
use s... | else {
Vec::new()
};
let injections = if let Some(val) = args().nth(3) {
let mut buffer = String::new();
let mut injection_file = File::open(val)
.expect("Failed to open injection file");
injection_file.read_to_string(&mut buffer)
.expect("Failed to read i... | {
let mut buffer = String::new();
let mut replay_file = File::open(val)
.expect("Failed to open replay file");
replay_file.read_to_string(&mut buffer)
.expect("Failed to read in replay file");
let mut buffer: Vec<_> = buffer.chars().collect();
buffer.rever... | conditional_block |
main.rs | //! # Synacor Challenge
//!
//! A Rust based runtime for the Synacor challenge architecture.
#![warn(missing_docs)]
extern crate byteorder;
extern crate termion;
#[macro_use] extern crate chan;
extern crate chan_signal;
extern crate libc;
extern crate synacor;
mod command;
mod debugger;
use debugger::Debugger;
use s... | buffer
} else {
Vec::new()
};
let injections = if let Some(val) = args().nth(3) {
let mut buffer = String::new();
let mut injection_file = File::open(val)
.expect("Failed to open injection file");
injection_file.read_to_string(&mut buffer)
.expe... | random_line_split | |
main.rs | //! # Synacor Challenge
//!
//! A Rust based runtime for the Synacor challenge architecture.
#![warn(missing_docs)]
extern crate byteorder;
extern crate termion;
#[macro_use] extern crate chan;
extern crate chan_signal;
extern crate libc;
extern crate synacor;
mod command;
mod debugger;
use debugger::Debugger;
use s... | buffer.reverse();
println!("Replay buffer loaded");
buffer
} else {
Vec::new()
};
let injections = if let Some(val) = args().nth(3) {
let mut buffer = String::new();
let mut injection_file = File::open(val)
.expect("Failed to open injection file");... | {
let binary = if let Some(val) = args().nth(1) {
let mut buffer = Vec::new();
let mut in_file = File::open(val)
.expect("Failed to open challenge binary.");
in_file.read_to_end(&mut buffer)
.expect("Failed to read in binary contents.");
buffer
} else {
... | identifier_body |
rectangle.rs | use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
} | top_left: top_left,
bottom_right: Point {
x: top_left.x + width as i16,
y: top_left.y + height as i16,
}
}
}
pub fn centre(&self) -> Point<i16> {
Point {
x: ((self.top_left.x + self.bottom_right.x) / 2),
... |
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle { | random_line_split |
rectangle.rs | use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right:... |
if self.top_left.y < top {
let diff = top - self.top_left.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
if self.bottom_right.x > right {
let diff = right - self.bottom_right.x;
self.top_left.x += diff;
self.bo... | {
let diff = left - self.top_left.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
} | conditional_block |
rectangle.rs | use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right:... |
pub fn is_intersecting(&self, other: &Rectangle) -> bool {
self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x
&& self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y
}
pub fn clamp_to(&mut self, (left, top): (i16, i16), (ri... | {
Point {
x: ((self.top_left.x + self.bottom_right.x) / 2),
y: ((self.top_left.y + self.bottom_right.y) / 2),
}
} | identifier_body |
rectangle.rs | use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right:... | (&self, other: &Rectangle) -> bool {
self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x
&& self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y
}
pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) {
... | is_intersecting | identifier_name |
dep-graph-caller-callee.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... | }
mod z {
use y;
// These are expected to yield errors, because changes to `x`
// affect the BODY of `y`, but not its signature.
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path
pub fn z() {
y::y();
}
} | random_line_split | |
dep-graph-caller-callee.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... |
}
mod y {
use x;
// These dependencies SHOULD exist:
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
pub fn y() {
x::x();
}
}
mod z {
use y;
// These are expected to yield errors, because changes to `x`
// affect the BODY of `y`, but not its signature.
#[rustc_t... | { } | identifier_body |
dep-graph-caller-callee.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... | () {
y::y();
}
}
| z | identifier_name |
games.rs | use crate::*;
#[get("/newgame")]
pub fn newgame<'a>() -> ContRes<'a> {
respond_page("newgame", newgame_con())
}
pub fn newgame_con() -> Context {
let conn = lock_database();
let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap();
let names: Vec<_> = stmt.query_map(NO_PA... | f.home == f.away || f.home_score > 10 || f.away_score > 10 {
let mut context = newgame_con();
context.insert("fejl",
&"Den indtastede kamp er ikke lovlig 😜");
return Resp::cont(respond_page("newgame_fejl", context));
}
let res = lock_database().execute("I... |
if !(f.home_score == 10 || f.away_score == 10) || f.home_score == f.away_score || | random_line_split |
games.rs | use crate::*;
#[get("/newgame")]
pub fn newgame<'a>() -> ContRes<'a> {
respond_page("newgame", newgame_con())
}
pub fn newgame_con() -> Context {
let conn = lock_database();
let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap();
let names: Vec<_> = stmt.query_map(NO_PA... | if!(f.home_score == 10 || f.away_score == 10) || f.home_score == f.away_score ||
f.home == f.away || f.home_score > 10 || f.away_score > 10 {
let mut context = newgame_con();
context.insert("fejl",
&"Den indtastede kamp er ikke lovlig 😜");
return Resp::cont(res... | {
let mut context = newgame_con();
context.insert("fejl", &"Det indtastede kodeord er forkert 💩");
return Resp::cont(respond_page("newgame_fejl", context));
}
| conditional_block |
games.rs | use crate::*;
#[get("/newgame")]
pub fn newgame<'a>() -> ContRes<'a> {
respond_page("newgame", newgame_con())
}
pub fn newgame_con() -> Context | })
.unwrap()
.map(Result::unwrap)
.collect();
let mut context = create_context("games");
context.insert("names", &names);
context.insert("balls", &balls);
context
}
#[derive(FromForm)]
pub struct NewGame {
home: i32,
away: i32,
home_score: i32,
away_score: i32,
... | {
let conn = lock_database();
let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap();
let names: Vec<_> = stmt.query_map(NO_PARAMS, |row| {
Named {
id: row.get(0),
name: row.get(1)
}
})
.unwrap()
... | identifier_body |
games.rs | use crate::*;
#[get("/newgame")]
pub fn newgame<'a>() -> ContRes<'a> {
respond_page("newgame", newgame_con())
}
pub fn | () -> Context {
let conn = lock_database();
let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap();
let names: Vec<_> = stmt.query_map(NO_PARAMS, |row| {
Named {
id: row.get(0),
name: row.get(1)
}
})
.unwr... | newgame_con | identifier_name |
util.rs | #![allow(dead_code)]
use std::env;
use std::fs::{self, File};
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::symlink as symlink_file;
#[cfg(windows)]
use std::os::windows::fs::symlink_file;
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::from_utf8;
#[macro_export]
macro_rules! ... |
pub fn symlink(src: &str, dst: &str) {
symlink_file(src, dst).unwrap();
}
pub fn is_symlink(path: &str) -> bool {
match fs::symlink_metadata(path) {
Ok(m) => m.file_type().is_symlink(),
Err(_) => false
}
}
pub fn resolve_link(path: &str) -> String {
match fs::read_link(path) {
... | {
File::create(Path::new(file)).unwrap();
} | identifier_body |
util.rs | #![allow(dead_code)]
use std::env;
use std::fs::{self, File};
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::symlink as symlink_file;
#[cfg(windows)]
use std::os::windows::fs::symlink_file;
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::from_utf8;
#[macro_export]
macro_rules! ... | pub fn touch(file: &str) {
File::create(Path::new(file)).unwrap();
}
pub fn symlink(src: &str, dst: &str) {
symlink_file(src, dst).unwrap();
}
pub fn is_symlink(path: &str) -> bool {
match fs::symlink_metadata(path) {
Ok(m) => m.file_type().is_symlink(),
Err(_) => false
}
}
pub fn res... | }
| random_line_split |
util.rs | #![allow(dead_code)]
use std::env;
use std::fs::{self, File};
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::symlink as symlink_file;
#[cfg(windows)]
use std::os::windows::fs::symlink_file;
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::from_utf8;
#[macro_export]
macro_rules! ... | (path: &str) -> fs::Metadata {
match fs::metadata(path) {
Ok(m) => m,
Err(e) => panic!("{}", e)
}
}
pub fn file_exists(path: &str) -> bool {
match fs::metadata(path) {
Ok(m) => m.is_file(),
Err(_) => false
}
}
pub fn dir_exists(path: &str) -> bool {
match fs::metada... | metadata | identifier_name |
canvasgradient.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle};
use ... | let color = CSSColor::parse(&mut parser);
let color = if parser.is_exhausted() {
match color {
Ok(CSSColor::RGBA(rgba)) => rgba,
Ok(CSSColor::CurrentColor) => RGBA::new(0, 0, 0, 255),
_ => return Err(Error::Syntax)
}
} else ... | }
let mut input = ParserInput::new(&color);
let mut parser = Parser::new(&mut input); | random_line_split |
canvasgradient.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle};
use ... | {
Linear(LinearGradientStyle),
Radial(RadialGradientStyle),
}
impl CanvasGradient {
fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient {
CanvasGradient {
reflector_: Reflector::new(),
style: style,
stops: DOMRefCell::new(Vec::new()),
}
}
... | CanvasGradientStyle | identifier_name |
canvasgradient.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle};
use ... |
CanvasGradientStyle::Radial(ref gradient) => {
FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new(gradient.x0,
gradient.y0,
gradient.... | {
FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new(gradient.x0,
gradient.y0,
gradient.x1,
... | conditional_block |
lib.rs | //! A Rust crate to connect a HD44780 lcd display
//!
//! # Example
//! ```no_run
//! use pi_lcd::*;
//!
//! // create a new lcd
//! let lcd = HD44780::new(11,10,[6,5,4,1],20,4);
//!
//! // send a String to the lcd at row 0
//! lcd.send_string("Hello World".to_string(),0);
//! ```
extern crate cupi;
extern crate regex... | }
if bits & 0x04 == 0x04 {
self.data[2].borrow_mut().high().unwrap();
}
if bits & 0x08 == 0x08 {
self.data[3].borrow_mut().high().unwrap();
}
e_wait();
self.e.borrow_mut().high().unwrap();
e_wait();
self.e.borrow_mut().low()... | random_line_split | |
lib.rs | //! A Rust crate to connect a HD44780 lcd display
//!
//! # Example
//! ```no_run
//! use pi_lcd::*;
//!
//! // create a new lcd
//! let lcd = HD44780::new(11,10,[6,5,4,1],20,4);
//!
//! // send a String to the lcd at row 0
//! lcd.send_string("Hello World".to_string(),0);
//! ```
extern crate cupi;
extern crate regex... | () {
std::thread::sleep(Duration::new(0, 50));
}
| e_wait | identifier_name |
lib.rs | //! A Rust crate to connect a HD44780 lcd display
//!
//! # Example
//! ```no_run
//! use pi_lcd::*;
//!
//! // create a new lcd
//! let lcd = HD44780::new(11,10,[6,5,4,1],20,4);
//!
//! // send a String to the lcd at row 0
//! lcd.send_string("Hello World".to_string(),0);
//! ```
extern crate cupi;
extern crate regex... |
fn select_row(&self, row: u32) {
// select the row where the String should be printed at
self.send_byte(self.lines[row as usize], COMMAND);
}
fn write(&self, charlist: Vec<u8>) {
// send every single char to send_byte
for x in charlist {
self.send_byte(x, DATA)... | {
// send new custom character to cgram address
match address {
0...7 => {
self.command(CGRAM_ADDRESS | address << 3);
for row in &bitmap {
self.send_byte(bitmap[*row as usize], DATA);
}
Ok(address)
... | identifier_body |
constellation_msg.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling... | (&self) -> Option<String> {
match *self {
MozBrowserEvent::AsyncScroll | MozBrowserEvent::Close | MozBrowserEvent::ContextMenu |
MozBrowserEvent::Error | MozBrowserEvent::IconChange | MozBrowserEvent::LoadEnd |
MozBrowserEvent::LoadStart | MozBrowserEvent::OpenWindow | MozBro... | detail | identifier_name |
constellation_msg.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling... | /// Requests that the constellation retrieve the current contents of the clipboard
GetClipboardContents(IpcSender<String>),
/// Requests that the constellation set the contents of the clipboard
SetClipboardContents(String),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
... | /// with the provided parent pipeline id and subpage id
GetFrame(PipelineId, SubpageId, IpcSender<Option<FrameId>>),
/// Notifies the constellation that this frame has received focus.
Focus(PipelineId), | random_line_split |
update-downloads.rs | #![deny(warnings)]
#![feature(std_misc, core, os, io, env)]
extern crate "cargo-registry" as cargo_registry;
extern crate postgres;
extern crate semver;
extern crate time;
extern crate env_logger;
use std::env;
use std::collections::HashMap;
use std::time::Duration;
use cargo_registry::{VersionDownload, Version, Mod... | tx.execute("INSERT INTO version_downloads \
(version_id, downloads, counted, date, processed)
VALUES ($1, 1, 0, current_date, false)",
&[&version.id]).unwrap();
::update(&tx).unwrap();
assert_eq!(Version::find(&tx, version.id).unwrap().d... | random_line_split | |
update-downloads.rs | #![deny(warnings)]
#![feature(std_misc, core, os, io, env)]
extern crate "cargo-registry" as cargo_registry;
extern crate postgres;
extern crate semver;
extern crate time;
extern crate env_logger;
use std::env;
use std::collections::HashMap;
use std::time::Duration;
use cargo_registry::{VersionDownload, Version, Mod... | (conn: &postgres::Transaction) -> User{
User::find_or_insert(conn, "login", None, None, None,
"access_token", "api_token").unwrap()
}
fn crate_downloads(tx: &postgres::Transaction, id: i32, expected: usize) {
let stmt = tx.prepare("SELECT * FROM crate_downloads
... | user | identifier_name |
update-downloads.rs | #![deny(warnings)]
#![feature(std_misc, core, os, io, env)]
extern crate "cargo-registry" as cargo_registry;
extern crate postgres;
extern crate semver;
extern crate time;
extern crate env_logger;
use std::env;
use std::collections::HashMap;
use std::time::Duration;
use cargo_registry::{VersionDownload, Version, Mod... | assert_eq!(Crate::find(&tx, krate.id).unwrap().downloads, 2);
crate_downloads(&tx, krate.id, 2);
::update(&tx).unwrap();
assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 2);
}
}
| {
let conn = conn();
let tx = conn.transaction().unwrap();
let user = user(&tx);
let krate = Crate::find_or_insert(&tx, "foo", user.id, &None,
&None, &None, &None, &[], &None,
&None, &None).unwrap();
... | identifier_body |
issue-5791.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 ... | () {}
| main | identifier_name |
issue-5791.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 ... | fn malloc2(len: libc::c_int, foo: libc::c_int) -> *const libc::c_void;
}
pub fn main () {} | #[link_name = "malloc"]
fn malloc1(len: libc::c_int) -> *const libc::c_void;
#[link_name = "malloc"] | random_line_split |
issue-5791.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 ... | {} | identifier_body | |
lib.rs | // this module adds some functionality based on the required implementations
// here like: `LinkedList::pop_back` or `Clone for LinkedList<T>`
// You are free to use anything in it, but it's mainly for the test framework.
mod pre_implemented;
pub struct LinkedList<T>(std::marker::PhantomData<T>);
pub struct Cursor<'a... |
}
// the cursor is expected to act as if it is at the position of an element
// and it also has to work with and be able to insert into an empty list.
impl<T> Cursor<'_, T> {
/// Take a mutable reference to the current element
pub fn peek_mut(&mut self) -> Option<&mut T> {
unimplemented!()
}
... | {
unimplemented!()
} | identifier_body |
lib.rs | // this module adds some functionality based on the required implementations
// here like: `LinkedList::pop_back` or `Clone for LinkedList<T>`
// You are free to use anything in it, but it's mainly for the test framework.
mod pre_implemented;
pub struct LinkedList<T>(std::marker::PhantomData<T>);
pub struct Cursor<'a... | /// return a reference to the new position
pub fn prev(&mut self) -> Option<&mut T> {
unimplemented!()
}
/// Remove and return the element at the current position and move the cursor
/// to the neighboring element that's closest to the back. This can be
/// either the next or previous p... | /// Move one position backward (towards the front) and | random_line_split |
lib.rs | // this module adds some functionality based on the required implementations
// here like: `LinkedList::pop_back` or `Clone for LinkedList<T>`
// You are free to use anything in it, but it's mainly for the test framework.
mod pre_implemented;
pub struct LinkedList<T>(std::marker::PhantomData<T>);
pub struct Cursor<'a... | (&mut self) -> Cursor<'_, T> {
unimplemented!()
}
/// Return a cursor positioned on the back element
pub fn cursor_back(&mut self) -> Cursor<'_, T> {
unimplemented!()
}
/// Return an iterator that moves from front to back
pub fn iter(&self) -> Iter<'_, T> {
unimplemente... | cursor_front | identifier_name |
temporary_page.rs | //! Temporarily map a page
//! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html)
use memory::Frame;
use super::{ActivePageTable, Page, VirtualAddress};
use super::entry::EntryFlags;
use super::table::{Table, Level1};
pub struct TemporaryPage {
page: Page,
}
impl TemporaryPage {
pub fn | (page: Page) -> TemporaryPage {
TemporaryPage {
page: page,
}
}
pub fn start_address (&self) -> VirtualAddress {
self.page.start_address()
}
/// Maps the temporary page to the given frame in the active table.
/// Returns the start address of the temporary page.
... | new | identifier_name |
temporary_page.rs | //! Temporarily map a page
//! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html)
use memory::Frame;
use super::{ActivePageTable, Page, VirtualAddress};
use super::entry::EntryFlags;
use super::table::{Table, Level1};
pub struct TemporaryPage {
page: Page,
}
impl TemporaryPage {
pub fn new... |
/// Maps the temporary page to the given frame in the active table.
/// Returns the start address of the temporary page.
pub fn map(&mut self, frame: Frame, flags: EntryFlags, active_table: &mut ActivePageTable) -> VirtualAddress {
assert!(active_table.translate_page(self.page).is_none(), "tempora... | {
self.page.start_address()
} | identifier_body |
temporary_page.rs | //! Temporarily map a page
//! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html)
use memory::Frame;
use super::{ActivePageTable, Page, VirtualAddress};
use super::entry::EntryFlags;
use super::table::{Table, Level1};
pub struct TemporaryPage {
page: Page,
}
impl TemporaryPage {
pub fn new... | }
/// Unmaps the temporary page in the active table.
pub fn unmap(&mut self, active_table: &mut ActivePageTable) {
active_table.unmap(self.page)
}
} | unsafe { &mut *(self.map(frame, flags, active_table).get() as *mut Table<Level1>) } | random_line_split |
borrow-tuple-fields.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 ... | (isize, isize);
fn main() {
let x: (Box<_>, _) = (box 1, 2);
let r = &x.0;
let y = x; //~ ERROR cannot move out of `x` because it is borrowed
let mut x = (1, 2);
let a = &x.0;
let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as
let mut x = (1, 2);
... | Bar | identifier_name |
borrow-tuple-fields.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 ... |
struct Foo(Box<isize>, isize);
struct Bar(isize, isize);
fn main() {
let x: (Box<_>, _) = (box 1, 2);
let r = &x.0;
let y = x; //~ ERROR cannot move out of `x` because it is borrowed
let mut x = (1, 2);
let a = &x.0;
let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is al... | #![feature(box_syntax)] | random_line_split |
os.rs | #![deny(unsafe_op_in_unsafe_fn)]
use crate::any::Any;
use crate::error::Error as StdError;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::os::wasi::prelude::*;
use crate::path::{self, PathBuf};
use crate::str;
use crate::sys::memchr;
use crat... |
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let nbuf = CString::new(n.as_bytes())?;
unsafe {
let _guard = env_lock();
cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
}
}
pub fn temp_dir() -> PathBuf {
panic!("no filesystem on wasm")
}
pub fn home_dir() -> Option<PathBuf> {
None
... | {
let k = CString::new(k.as_bytes())?;
let v = CString::new(v.as_bytes())?;
unsafe {
let _guard = env_lock();
cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
}
} | identifier_body |
os.rs | #![deny(unsafe_op_in_unsafe_fn)]
use crate::any::Any;
use crate::error::Error as StdError;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::os::wasi::prelude::*;
use crate::path::{self, PathBuf};
use crate::str;
use crate::sys::memchr;
use crat... | else {
let error = io::Error::last_os_error();
if error.raw_os_error()!= Some(libc::ERANGE) {
return Err(error);
}
}
// Trigger the internal buffer resizing logic of `Vec` by requiring
// more space than the curren... | {
let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
buf.set_len(len);
buf.shrink_to_fit();
return Ok(PathBuf::from(OsString::from_vec(buf)));
} | conditional_block |
os.rs | #![deny(unsafe_op_in_unsafe_fn)]
use crate::any::Any;
use crate::error::Error as StdError;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::os::wasi::prelude::*;
use crate::path::{self, PathBuf};
use crate::str;
use crate::sys::memchr;
use crat... | }
}
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
let k = CString::new(k.as_bytes())?;
let v = CString::new(v.as_bytes())?;
unsafe {
let _guard = env_lock();
cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
}
}
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let... | if s.is_null() {
None
} else {
Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
} | random_line_split |
os.rs | #![deny(unsafe_op_in_unsafe_fn)]
use crate::any::Any;
use crate::error::Error as StdError;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::os::wasi::prelude::*;
use crate::path::{self, PathBuf};
use crate::str;
use crate::sys::memchr;
use crat... | () -> io::Result<PathBuf> {
unsupported()
}
pub struct Env {
iter: vec::IntoIter<(OsString, OsString)>,
}
impl!Send for Env {}
impl!Sync for Env {}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> {
self.iter.next()
}
fn size_... | current_exe | identifier_name |
atom.rs | use joker::word::{Atom, Name};
use tristate::TriState;
pub trait AtomExt {
fn is_strict_reserved(&self) -> TriState;
fn is_illegal_strict_binding(&self) -> bool;
}
| match self {
&Name::Atom(ref atom) => atom.is_strict_reserved(),
_ => TriState::No
}
}
fn is_illegal_strict_binding(&self) -> bool {
match *self {
Name::Atom(ref atom) => atom.is_illegal_strict_binding(),
_ => false
}
}
}
impl... | impl AtomExt for Name {
fn is_strict_reserved(&self) -> TriState { | random_line_split |
atom.rs | use joker::word::{Atom, Name};
use tristate::TriState;
pub trait AtomExt {
fn is_strict_reserved(&self) -> TriState;
fn is_illegal_strict_binding(&self) -> bool;
}
impl AtomExt for Name {
fn is_strict_reserved(&self) -> TriState {
match self {
&Name::Atom(ref atom) => atom.is_strict_re... | (&self) -> bool {
match *self {
Name::Atom(ref atom) => atom.is_illegal_strict_binding(),
_ => false
}
}
}
impl AtomExt for Atom {
fn is_strict_reserved(&self) -> TriState {
match *self {
// 11.6.2.2
Atom::Await => TriState::Unknown,
... | is_illegal_strict_binding | identifier_name |
atom.rs | use joker::word::{Atom, Name};
use tristate::TriState;
pub trait AtomExt {
fn is_strict_reserved(&self) -> TriState;
fn is_illegal_strict_binding(&self) -> bool;
}
impl AtomExt for Name {
fn is_strict_reserved(&self) -> TriState {
match self {
&Name::Atom(ref atom) => atom.is_strict_re... |
// 12.1.1
fn is_illegal_strict_binding(&self) -> bool {
match *self {
Atom::Arguments
| Atom::Eval => true,
_ => false
}
}
}
| {
match *self {
// 11.6.2.2
Atom::Await => TriState::Unknown,
// 12.1.1
Atom::Implements
| Atom::Interface
| Atom::Let
| Atom::Package
| Atom::Private
| Atom::Protected
| Atom::Public
... | identifier_body |
main.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// aux-build:crate_with_invalid_spans.rs
// pretty-expanded FIXME #23616
extern crate crate_with_invalid_spans;
fn main() {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
/... | // 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 | random_line_split |
main.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo() > span.hi().
// Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
}
| main | identifier_name |
main.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo() > span.hi().
// Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
} | identifier_body | |
vga.rs | use extra::prelude::*;
use cpu;
use cpu::io;
#[packed]
pub struct | {
char: u8,
attr: u8,
}
static SCREEN_ROWS: uint = 25;
static SCREEN_COLS: uint = 80;
static SCREEN_SIZE: uint = SCREEN_ROWS*SCREEN_COLS;
type screen_buf = [character,..SCREEN_SIZE];
static screen: *mut screen_buf = 0xB8000 as *mut screen_buf;
static mut cur_pos: uint = 0;
pub fn init() {
unsafe {
... | character | identifier_name |
vga.rs | use extra::prelude::*;
use cpu;
use cpu::io;
#[packed]
pub struct character {
char: u8,
attr: u8,
}
static SCREEN_ROWS: uint = 25;
static SCREEN_COLS: uint = 80;
static SCREEN_SIZE: uint = SCREEN_ROWS*SCREEN_COLS;
type screen_buf = [character,..SCREEN_SIZE];
static screen: *mut screen_buf = 0xB8000 as *mut sc... | }
#[inline]
unsafe fn mem_ptr_of(row: uint, col: uint) -> uint {
screen as uint +
row * SCREEN_COLS * mem::size_of::<character>() +
col * mem::size_of::<character>()
} | unsafe fn cursor_to(pos: uint) {
io::outb(0x3D4, 14);
io::outb(0x3D5, (pos >> 8) as u8);
io::outb(0x3D4, 15);
io::outb(0x3D5, pos as u8); | random_line_split |
vga.rs | use extra::prelude::*;
use cpu;
use cpu::io;
#[packed]
pub struct character {
char: u8,
attr: u8,
}
static SCREEN_ROWS: uint = 25;
static SCREEN_COLS: uint = 80;
static SCREEN_SIZE: uint = SCREEN_ROWS*SCREEN_COLS;
type screen_buf = [character,..SCREEN_SIZE];
static screen: *mut screen_buf = 0xB8000 as *mut sc... |
pub fn puts(string: &str, attr: term::color::Color) {
stdio::puts(string, attr, putc, new_line);
}
pub fn putc(c: char, attr: term::color::Color) {
unsafe {
put_char(cur_pos, character{char: c as u8, attr: attr as u8});
cursor_move(1);
}
}
pub fn new_line() {
unsafe {
cursor_... | {
unsafe {
cur_pos = cursor_pos();
}
} | identifier_body |
vga.rs | use extra::prelude::*;
use cpu;
use cpu::io;
#[packed]
pub struct character {
char: u8,
attr: u8,
}
static SCREEN_ROWS: uint = 25;
static SCREEN_COLS: uint = 80;
static SCREEN_SIZE: uint = SCREEN_ROWS*SCREEN_COLS;
type screen_buf = [character,..SCREEN_SIZE];
static screen: *mut screen_buf = 0xB8000 as *mut sc... |
cursor_to(cur_pos);
}
#[inline]
unsafe fn put_char(pos: uint, c: character) {
(*screen)[pos] = c;
}
#[inline]
unsafe fn cursor_pos() -> uint {
let mut pos: uint;
io::outb(0x3D4, 14);
pos = (io::inb(0x3D5) as uint) << 8;
io::outb(0x3D4, 15);
pos |= io::inb(0x3D5) as uint;
pos
}
#[inli... | {
cpu::memmove(mem_ptr_of(0, 0), mem_ptr_of(1, 0),
(SCREEN_SIZE - SCREEN_COLS) * mem::size_of::<character>());
let mut i = SCREEN_SIZE - SCREEN_COLS;
while i < SCREEN_SIZE {
put_char(i, character{char: ' ' as u8, attr: term::color::BLACK as u8});
i += 1;
... | conditional_block |
lib.rs | pub fn score(word: &str) -> usize | {
// lowercase for case insensitivity
// use map to convert to numbers
// sum them
word.to_lowercase()
.chars()
.map(|c| match c {
'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' | 's' | 't' => 1,
'd' | 'g' => 2,
'b' | 'c' | 'm' | 'p' => 3,
'... | identifier_body | |
lib.rs | pub fn | (word: &str) -> usize {
// lowercase for case insensitivity
// use map to convert to numbers
// sum them
word.to_lowercase()
.chars()
.map(|c| match c {
'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' |'s' | 't' => 1,
'd' | 'g' => 2,
'b' | 'c' |'m' | 'p' =... | score | identifier_name |
lib.rs | pub fn score(word: &str) -> usize {
// lowercase for case insensitivity
// use map to convert to numbers | 'd' | 'g' => 2,
'b' | 'c' |'m' | 'p' => 3,
'f' | 'h' | 'v' | 'w' | 'y' => 4,
'k' => 5,
'j' | 'x' => 8,
'q' | 'z' => 10,
_ => 0,
})
.fold(0, |accu, x| accu + x)
} | // sum them
word.to_lowercase()
.chars()
.map(|c| match c {
'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' | 's' | 't' => 1, | random_line_split |
advance.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use collections::HashMap;
use concurrency_manager::ConcurrencyManager;
use engine_traits::KvEngine;
use futures::compat::Future01CompatExt;
use grpcio::{ChannelBuilder, Environment};
use kvproto::k... | .filter_map(|resp| match resp {
Ok(resp) => Some(resp),
Err(e) => {
debug!("resolved-ts check leader error"; "err" =>?e);
None
}
})
.map(|(store_id, resp)| {
resp.regions
... | });
let resps = futures::future::join_all(stores).await;
resps
.into_iter() | random_line_split |
advance.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use collections::HashMap;
use concurrency_manager::ConcurrencyManager;
use engine_traits::KvEngine;
use futures::compat::Future01CompatExt;
use grpcio::{ChannelBuilder, Environment};
use kvproto::k... |
}
impl<E: KvEngine> AdvanceTsWorker<E> {
pub fn advance_ts_for_regions(&self, regions: Vec<u64>) {
let pd_client = self.pd_client.clone();
let scheduler = self.scheduler.clone();
let cm: ConcurrencyManager = self.concurrency_manager.clone();
let env = self.env.clone();
let ... | {
let worker = Builder::new_multi_thread()
.thread_name("advance-ts")
.worker_threads(1)
.enable_time()
.build()
.unwrap();
Self {
env,
security_mgr,
scheduler,
pd_client,
worker,
... | identifier_body |
advance.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use collections::HashMap;
use concurrency_manager::ConcurrencyManager;
use engine_traits::KvEngine;
use futures::compat::Future01CompatExt;
use grpcio::{ChannelBuilder, Environment};
use kvproto::k... | <E: KvEngine> {
store_meta: Arc<Mutex<StoreMeta>>,
region_read_progress: RegionReadProgressRegistry,
pd_client: Arc<dyn PdClient>,
timer: SteadyTimer,
worker: Runtime,
scheduler: Scheduler<Task<E::Snapshot>>,
/// The concurrency manager for transactions. It's needed for CDC to check locks wh... | AdvanceTsWorker | identifier_name |
day_5.rs | pub use tdd_kata::lcd_kata::day_5::Display;
pub use tdd_kata::lcd_kata::day_5::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero};
pub use tdd_kata::lcd_kata::day_5::Data::{NotANumber, Output};
pub use expectest::prelude::be_equal_to;
describe! lcd_tests {
before_each {
let mut display ... | it "should output all numbers" {
display.input("1234567890");
expect!(display.output()).to(be_equal_to(Output(vec![One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero])));
}
it "should show error when input is not a number" {
display.input("abc");
expect!(display.ou... | random_line_split | |
print_with_newline.rs | // FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934
// // run-rustfix
#![allow(clippy::print_literal)]
#![warn(clippy::print_with_newline)]
fn | () {
print!("Hello\n");
print!("Hello {}\n", "world");
print!("Hello {} {}\n", "world", "#2");
print!("{}\n", 1265);
print!("\n");
// these are all fine
print!("");
print!("Hello");
println!("Hello");
println!("Hello\n");
println!("Hello {}\n", "world");
print!("Issue\n{... | main | identifier_name |
print_with_newline.rs | // FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934
// // run-rustfix
#![allow(clippy::print_literal)]
#![warn(clippy::print_with_newline)]
fn main() {
print!("Hello\n");
print!("Hello {}\n", "world");
print!("Hello {} {}\n", "world", "#2");
print!("{}\n", 1... | );
print!(
r"
"
);
// Don't warn on CRLF (#4208)
print!("\r\n");
print!("foo\r\n");
print!("\\r\n"); //~ ERROR
print!("foo\rbar\n") // ~ ERROR
} | print!(
"
" | random_line_split |
print_with_newline.rs | // FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934
// // run-rustfix
#![allow(clippy::print_literal)]
#![warn(clippy::print_with_newline)]
fn main() | println!("\nbla\n\n"); // #3126
// Escaping
print!("\\n"); // #3514
print!("\\\n"); // should fail
print!("\\\\n");
// Raw strings
print!(r"\n"); // #3778
// Literal newlines should also fail
print!(
"
"
);
print!(
r"
"
);
// Don't warn on CRLF (#4... | {
print!("Hello\n");
print!("Hello {}\n", "world");
print!("Hello {} {}\n", "world", "#2");
print!("{}\n", 1265);
print!("\n");
// these are all fine
print!("");
print!("Hello");
println!("Hello");
println!("Hello\n");
println!("Hello {}\n", "world");
print!("Issue\n{}",... | identifier_body |
cache.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use kvproto::coprocessor::Response;
use crate::coprocessor::RequestHandler;
use crate::coprocessor::*;
use crate::storage::Snapshot;
pub struct CachedRequestHandler {
data_version: Option<u64>,
}
impl CachedRequestH... |
}
| {
let mut resp = Response::default();
resp.set_is_cache_hit(true);
if let Some(v) = self.data_version {
resp.set_cache_last_version(v);
}
Ok(resp)
} | identifier_body |
cache.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use kvproto::coprocessor::Response;
use crate::coprocessor::RequestHandler;
use crate::coprocessor::*;
use crate::storage::Snapshot;
pub struct CachedRequestHandler {
data_version: Option<u64>,
}
impl CachedRequestH... | resp.set_cache_last_version(v);
}
Ok(resp)
}
} | resp.set_is_cache_hit(true);
if let Some(v) = self.data_version { | random_line_split |
cache.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use kvproto::coprocessor::Response;
use crate::coprocessor::RequestHandler;
use crate::coprocessor::*;
use crate::storage::Snapshot;
pub struct CachedRequestHandler {
data_version: Option<u64>,
}
impl CachedRequestH... | <S: Snapshot>(snap: S) -> Self {
Self {
data_version: snap.get_data_version(),
}
}
pub fn builder<S: Snapshot>() -> RequestHandlerBuilder<S> {
Box::new(|snap, _req_ctx: &ReqContext| Ok(CachedRequestHandler::new(snap).into_boxed()))
}
}
#[async_trait]
impl RequestHandler... | new | identifier_name |
cache.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use kvproto::coprocessor::Response;
use crate::coprocessor::RequestHandler;
use crate::coprocessor::*;
use crate::storage::Snapshot;
pub struct CachedRequestHandler {
data_version: Option<u64>,
}
impl CachedRequestH... |
Ok(resp)
}
}
| {
resp.set_cache_last_version(v);
} | conditional_block |
error.rs | /*
* Copyright 2021 Google LLC
*
* 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 i... |
}
/// An error representing failure to convert a filter's protobuf configuration
/// to its static representation.
#[derive(Debug, PartialEq, thiserror::Error)]
#[error(
"{}failed to convert protobuf config: {}",
self.field.as_ref().map(|f| format!("Field `{f}`")).unwrap_or_default(),
reason
)]
pub struct... | {
Error::InitializeMetricsFailed(error.to_string())
} | identifier_body |
error.rs | /*
* Copyright 2021 Google LLC
*
* 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 i... | #[derive(Debug, PartialEq, thiserror::Error)]
pub enum Error {
#[error("filter `{}` not found",.0)]
NotFound(String),
#[error("filter `{}` requires configuration, but none provided",.0)]
MissingConfig(&'static str),
#[error("field `{}` is invalid, reason: {}", field, reason)]
FieldInvalid { fiel... | /// a [`FilterFactory`]. | random_line_split |
error.rs | /*
* Copyright 2021 Google LLC
*
* 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 i... | {
/// Reason for the failure.
reason: String,
/// Set if the failure is specific to a single field in the config.
field: Option<String>,
}
impl ConvertProtoConfigError {
pub fn new(reason: impl std::fmt::Display, field: Option<String>) -> Self {
Self {
reason: reason.to_string(... | ConvertProtoConfigError | identifier_name |
mod.rs | use std::rc::Rc;
use std::cell::RefCell;
use rand;
use rand::XorShiftRng;
use rand::Rng;
use gmath::vectors::Vec2;
use game::entity::{Object, Physics};
use game::entity::creature::Creature;
use keyboard::KeyboardState;
use sdl2::keycode;
pub trait Controller<A> {
/// Update the controller
/// # Arguments
... | (&mut self, object: &mut Creature, _: f32) {
let keyboard = self.keyboard.borrow();
let move_accel = object.move_accel;
let x_accel =
if keyboard.is_keydown(keycode::LeftKey) {
-move_accel * if object.is_on_ground() { 1.0 } else { 0.6 }
}
else... | update | identifier_name |
mod.rs | use std::rc::Rc;
use std::cell::RefCell;
use rand;
use rand::XorShiftRng;
use rand::Rng;
use gmath::vectors::Vec2;
use game::entity::{Object, Physics};
use game::entity::creature::Creature;
use keyboard::KeyboardState;
use sdl2::keycode;
pub trait Controller<A> {
/// Update the controller
/// # Arguments
... |
else if keyboard.is_keydown(keycode::RightKey) {
move_accel * if object.is_on_ground() { 1.0 } else { 0.6 }
}
else {
0.0
};
let new_accel = Vec2::new(x_accel, object.acceleration().y);
object.set_acceleration(new_accel);
... | {
-move_accel * if object.is_on_ground() { 1.0 } else { 0.6 }
} | conditional_block |
mod.rs | use std::rc::Rc;
use std::cell::RefCell;
use rand;
use rand::XorShiftRng;
use rand::Rng;
use gmath::vectors::Vec2;
use game::entity::{Object, Physics};
use game::entity::creature::Creature;
use keyboard::KeyboardState;
use sdl2::keycode;
pub trait Controller<A> {
/// Update the controller
/// # Arguments
... | impl Controller<Creature> for KeyboardController {
fn update(&mut self, object: &mut Creature, _: f32) {
let keyboard = self.keyboard.borrow();
let move_accel = object.move_accel;
let x_accel =
if keyboard.is_keydown(keycode::LeftKey) {
-move_accel * if object.is... | }
| random_line_split |
mod.rs | use std::rc::Rc;
use std::cell::RefCell;
use rand;
use rand::XorShiftRng;
use rand::Rng;
use gmath::vectors::Vec2;
use game::entity::{Object, Physics};
use game::entity::creature::Creature;
use keyboard::KeyboardState;
use sdl2::keycode;
pub trait Controller<A> {
/// Update the controller
/// # Arguments
... |
}
pub struct NoneController<A>;
impl<A: Object> NoneController<A> {
pub fn new() -> NoneController<A> {
NoneController
}
}
impl<A: Object> Controller<A> for NoneController<A> {
// Just use default trait implementations
}
/// A controller that controls objects using the keyboard
pub struct Keyb... | {
} | identifier_body |
p_2_0_01.rs | // P_2_0_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
| conditional_block | |
p_2_0_01.rs | // P_2_0_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | draw.to_frame(app, &frame).unwrap();
if app.keys.down.contains(&Key::S) {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
| // Prepare to draw.
let draw = app.draw();
let win = app.window_rect();
let circle_resolution = map_range(app.mouse.y, win.top(), win.bottom(), 2, 80);
let radius = app.mouse.x - win.left();
let angle = TAU / circle_resolution as f32;
draw.background().color(BLACK);
for i in 0..circle_r... | identifier_body |
p_2_0_01.rs | // P_2_0_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | p: &App, frame: Frame) {
// Prepare to draw.
let draw = app.draw();
let win = app.window_rect();
let circle_resolution = map_range(app.mouse.y, win.top(), win.bottom(), 2, 80);
let radius = app.mouse.x - win.left();
let angle = TAU / circle_resolution as f32;
draw.background().color(BLACK);... | w(ap | identifier_name |
p_2_0_01.rs | // P_2_0_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | .caps_round()
.color(WHITE);
}
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
if app.keys.down.contains(&Key::S) {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
} | .stroke_weight(app.mouse.y / 20.0) | random_line_split |
convert.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 ... |
}
// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D:?Sized + Deref, U:?Sized> AsMut<U> for D where D::Target: AsMut<U> {
// fn as_mut(&mut self) -> &mut U {
// self.deref_mut().as_mut()
// }
// }
// From implies Into
#[st... | {
(*self).as_mut()
} | identifier_body |
convert.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 ... | (&mut self) -> &mut U {
(*self).as_mut()
}
}
// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D:?Sized + Deref, U:?Sized> AsMut<U> for D where D::Target: AsMut<U> {
// fn as_mut(&mut self) -> &mut U {
// self.deref_m... | as_mut | identifier_name |
convert.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 ... | /// Both `String` and `&str` implement `AsRef<str>`:
///
/// ```
/// fn is_hello<T: AsRef<str>>(s: T) {
/// assert_eq!("hello", s.as_ref());
/// }
///
/// let s = "hello";
/// is_hello(s);
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T:?S... | ///
/// # Examples
/// | random_line_split |
dirichlet.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This fil... | /// # Example
///
/// ```
/// use rand::prelude::*;
/// use rand_distr::Dirichlet;
///
/// let dirichlet = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
/// let samples = dirichlet.sample(&mut rand::thread_rng());
/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples);
/// ```
#[cfg_attr(doc_cfg, ... | random_line_split | |
dirichlet.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This fil... | (alpha: F, size: usize) -> Result<Dirichlet<F>, Error> {
if!(alpha > F::zero()) {
return Err(Error::AlphaTooSmall);
}
if size < 2 {
return Err(Error::SizeTooSmall);
}
Ok(Dirichlet {
alpha: vec![alpha; size].into_boxed_slice(),
})
}
... | new_with_size | identifier_name |
dirichlet.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This fil... |
}
Ok(Dirichlet { alpha: alpha.to_vec().into_boxed_slice() })
}
/// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`.
///
/// Requires `size >= 2`.
#[inline]
pub fn new_with_size(alpha: F, size: usize) -> Result<Dirichlet<F>, Error> {
if!(al... | {
return Err(Error::AlphaTooSmall);
} | conditional_block |
dirichlet.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This fil... |
#[test]
fn test_dirichlet_with_param() {
let alpha = 0.5f64;
let size = 2;
let d = Dirichlet::new_with_size(alpha, size).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
... | {
let d = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();... | identifier_body |
disk.rs | #![feature(plugin, custom_derive, custom_attribute)]
#![plugin(serde_macros)]
extern crate drum;
extern crate serde;
use drum::*;
use std::io::*;
use std::collections::*;
use std::fs::{OpenOptions};
#[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)]
enum Value {
Array(Vec<Value>),
Object(BTreeMap<V... | ,
_ => panic!()
}
},
_ => ()
}
Ok(())
}
fn main() {
run().unwrap();
return;
} | {
println!("previous: {}", num);
} | conditional_block |
disk.rs | #![feature(plugin, custom_derive, custom_attribute)]
#![plugin(serde_macros)]
extern crate drum;
extern crate serde;
use drum::*;
use std::io::*;
use std::collections::*;
use std::fs::{OpenOptions};
#[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)]
enum Value {
Array(Vec<Value>),
Object(BTreeMap<V... | () {
run().unwrap();
return;
} | main | identifier_name |
disk.rs | #![feature(plugin, custom_derive, custom_attribute)]
#![plugin(serde_macros)]
extern crate drum;
extern crate serde;
use drum::*;
use std::io::*;
use std::collections::*;
use std::fs::{OpenOptions};
#[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)]
enum Value {
Array(Vec<Value>),
Object(BTreeMap<V... | {
run().unwrap();
return;
} | identifier_body | |
disk.rs | #![feature(plugin, custom_derive, custom_attribute)]
#![plugin(serde_macros)]
extern crate drum;
extern crate serde;
use drum::*;
use std::io::*;
use std::collections::*;
use std::fs::{OpenOptions};
#[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)]
enum Value {
Array(Vec<Value>),
Object(BTreeMap<V... | } | random_line_split | |
builders.rs | use std::fmt;
use std::rc::Rc;
use quire::validate as V;
use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor};
use serde::ser::{Serializer, Serialize};
use crate::build_step::{Step, BuildStep};
use crate::builder::commands as cmd;
macro_rules! define_commands {
($($module: ident :... | {
if false { unreachable!() }
$(
else if let Some(b) =
self.0.downcast_ref::<cmd::$module::$item>()
{
b.serialize(s)
}
)*
else {
... | -> Result<S::Ok, S::Error> | random_line_split |
builders.rs | use std::fmt;
use std::rc::Rc;
use quire::validate as V;
use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor};
use serde::ser::{Serializer, Serialize};
use crate::build_step::{Step, BuildStep};
use crate::builder::commands as cmd;
macro_rules! define_commands {
($($module: ident :... | ;
fn decode<'x, T, V>(v: V)
-> Result<Step, V::Error>
where
T: BuildStep + Deserialize<'x> +'static,
V: VariantAccess<'x>,
{
v.newtype_variant::<T>().map(|x| Step(Rc::new(x) as Rc<dyn BuildStep>))
}
impl<'a> Deserialize<'a> for CommandName {
fn deserialize<D: Deserializer<'a>>(d: D) -... | StepVisitor | identifier_name |
builders.rs | use std::fmt;
use std::rc::Rc;
use quire::validate as V;
use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor};
use serde::ser::{Serializer, Serialize};
use crate::build_step::{Step, BuildStep};
use crate::builder::commands as cmd;
macro_rules! define_commands {
($($module: ident :... |
}
impl<'a> Deserialize<'a> for Step {
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Step, D::Error> {
d.deserialize_enum("BuildStep", COMMANDS, StepVisitor)
}
}
| {
d.deserialize_identifier(NameVisitor)
} | identifier_body |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use package_id::PackageId;
use util::{CraftResult, Human, Freshness, internal, ChainError, profile, paths};
use super::job::Work;
use super::{fingerprint, Kind, Context, Unit};
... |
// Parses the output of a script.
// The `pkg_name` is used for error messages.
pub fn parse(input: &[u8], pkg_name: &str) -> CraftResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
let mut metadata = Vec::new();
let mut rerun_if_c... | {
let contents = paths::read_bytes(path)?;
BuildOutput::parse(&contents, pkg_name)
} | identifier_body |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use package_id::PackageId;
use util::{CraftResult, Human, Freshness, internal, ChainError, profile, paths};
use super::job::Work;
use super::{fingerprint, Kind, Context, Unit};
... | <'a, 'b, 'cfg>(out: &'a mut HashMap<Unit<'b>, BuildScripts>,
cx: &Context<'b, 'cfg>,
unit: &Unit<'b>)
-> CraftResult<&'a BuildScripts> {
// Do a quick pre-flight check to see if we've already calculated the
// set of depend... | build | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.