file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | // Copyright (C) 2015 Sam Henson
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distribute... |
}
}
// move contents of source directory into current directory
for entry in fs::read_dir(src_dir).unwrap() {
let entry = entry.unwrap();
let e_path = entry.path();
let src = e_path.clone();
let dest = e_path.relative_from(src_dir).unwrap();
println!("movin... | {
panic!("{:?} is neither a file nor a directory", e_path)
} | conditional_block |
main.rs | // Copyright (C) 2015 Sam Henson
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distribute... | umount("run");
umount("sys");
// move the mounted devtmpfs out of the way
fs::create_dir("old_dev").unwrap();
move_mount("dev", "old_dev");
// delete everything except the new_root, dev, and lost+found directories
for entry in fs::read_dir("/").unwrap() {
let entry = entry.unwrap()... | {
// verify source directory
let src_dir = Path::new("/new_root");
if src_dir.exists() == false || src_dir.is_dir() == false {
println!("Error: /new_root does not exist or is not a directory");
return;
}
// remount the root device read-write
remount_root(0);
// deleting fil... | identifier_body |
main.rs | // Copyright (C) 2015 Sam Henson
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distribute... | (from : &str, to : &str) {
let ret = unsafe {
syscall!(MOUNT, format!("{}\0", from).as_ptr(), format!("{}\0", to).as_ptr(), 0, MS_MOVE, 0)
};
println!("move_mount() -> {}", ret);
}
fn sync() {
unsafe {
syscall!(SYNC)
};
}
const LINUX_REBOOT_MAGIC1 : u32 = 0xfee1dead;
const LINUX_RE... | move_mount | identifier_name |
main.rs | /*
src/main.rs, 2017-09-02
Copyright (c) 2017 Juuso Tuononen
This file is licensed under
Apache License, Version 2.0
or
MIT License
*/
//! Source code for Space Boss Battles.
//!
//! Main function and game loop is in this file.
#[cfg(not(feature = "glutin_window"))]
extern crate sdl2;
#[cfg(feature = "glutin_wi... |
};
if arguments.show_help() {
println!("{}", COMMAND_LINE_HELP_TEXT);
return;
}
#[cfg(not(feature = "gles"))]
let rendering_context = RenderingContext::OpenGL;
#[cfg(feature = "gles")]
let rendering_context = RenderingContext::OpenGLES;
#[cfg(not(feature = "glutin_w... | {
println!("unknown argument: \"{}\"", unknown_argument);
println!("{}", COMMAND_LINE_HELP_TEXT);
return;
} | conditional_block |
main.rs | /*
src/main.rs, 2017-09-02
Copyright (c) 2017 Juuso Tuononen
This file is licensed under
Apache License, Version 2.0
or
MIT License
*/
//! Source code for Space Boss Battles.
//!
//! Main function and game loop is in this file.
#[cfg(not(feature = "glutin_window"))]
extern crate sdl2;
#[cfg(feature = "glutin_wi... | <W: Window> {
game_logic: Logic,
quit: bool,
input: InputManager,
fps_counter: FpsCounter,
timer: GameLoopTimer,
gui: GUI,
renderer: OpenGLRenderer,
settings: Settings,
audio_manager: AudioManager<W::AudioPlayer>,
update_game: bool,
render_game: bool,
time_manager: TimeMa... | Game | identifier_name |
main.rs | /*
src/main.rs, 2017-09-02
Copyright (c) 2017 Juuso Tuononen
This file is licensed under
Apache License, Version 2.0
or
MIT License
*/
//! Source code for Space Boss Battles.
//!
//! Main function and game loop is in this file.
#[cfg(not(feature = "glutin_window"))]
extern crate sdl2;
#[cfg(feature = "glutin_wi... |
pub fn handle_events(&mut self) {
self.window.handle_events(
&mut self.input,
&mut self.renderer,
&mut self.settings,
&mut self.gui,
&mut self.game_logic,
&mut self.quit,
&self.time_manager
);
}
/// Render... | {
self.quit
} | identifier_body |
main.rs | /*
src/main.rs, 2017-09-02
Copyright (c) 2017 Juuso Tuononen
This file is licensed under
Apache License, Version 2.0
or
MIT License
*/
//! Source code for Space Boss Battles.
//!
//! Main function and game loop is in this file.
#[cfg(not(feature = "glutin_window"))]
extern crate sdl2;
#[cfg(feature = "glutin_wi... | // This function will not return because last parameter named `simulate_infinite_loop` is true.
// Function documentation: https://kripken.github.io/emscripten-site/docs/api_reference/emscripten.h.html#c.emscripten_set_main_loop_arg
emscripten_sys::emscripten_set_main_loop_arg(Some(g... | #[cfg(target_os = "emscripten")]
{
let game_ptr: *mut Game = &mut game;
unsafe { | random_line_split |
main.rs | /*
== run-info == (Matthias Drescher, 2016/2017)
This program shows the current cpu and memory load of the machine within a terminal UI.
Since it depends on linux-specific system files, it will only run on a linux machine.
*/
extern crate term;
extern crate clap;
use clap::{
Arg, App
};
extern crate time;
use ... | () {
let matches = App::new("run-info")
.version("0.5.1")
.about("Shows current CPU and memory load")
.arg(Arg::with_name("delay")
.short("d")
.long("delay")
.help("Sets the delay between updating the information (in ms)")
.takes_value(true))
.arg(Arg::with_name("no-... | main | identifier_name |
main.rs | /*
== run-info == (Matthias Drescher, 2016/2017)
This program shows the current cpu and memory load of the machine within a terminal UI.
Since it depends on linux-specific system files, it will only run on a linux machine.
*/
extern crate term;
extern crate clap;
use clap::{
Arg, App
};
extern crate time;
use ... | Err(_) => {
println!("error: Memory information is not available.");
println!("maybe you are not running this program on a Linux OS?");
break;}
};
//the new info is becoming the old info, and a new info is requested
mem::swap(&mut cpuinfo_new, &mut cpuinfo_old);
cpuinfo_new = CPUInfo... | let mut cpu_graph = Graph::new();
loop {
match meminfo.update() { //we can just update the meminfo
Ok(_) => {}, | random_line_split |
generics.rs | use super::{EncodeContext, ToHtml};
impl<Type> ToHtml for Option<Type>
where
Type: ToHtml,
{
fn to_html(&self, context: &EncodeContext) -> String {
match self {
Some(value) => value.to_html(context),
None => "".to_string(),
}
}
fn to_attrs(&self, context: &Encod... |
}
| {
self.iter()
.map(|item| item.to_attrs(context))
.flatten()
.collect()
} | identifier_body |
generics.rs | use super::{EncodeContext, ToHtml};
impl<Type> ToHtml for Option<Type>
where
Type: ToHtml,
{
fn to_html(&self, context: &EncodeContext) -> String {
match self {
Some(value) => value.to_html(context),
None => "".to_string(),
}
}
fn | (&self, context: &EncodeContext) -> Vec<String> {
match self {
Some(value) => value.to_attrs(context),
None => Vec::new(),
}
}
}
impl<Type> ToHtml for Box<Type>
where
Type: ToHtml,
{
fn to_html(&self, context: &EncodeContext) -> String {
self.as_ref().to_html... | to_attrs | identifier_name |
generics.rs | use super::{EncodeContext, ToHtml};
impl<Type> ToHtml for Option<Type>
where
Type: ToHtml,
{
fn to_html(&self, context: &EncodeContext) -> String {
match self {
Some(value) => value.to_html(context),
None => "".to_string(),
}
}
fn to_attrs(&self, context: &Encod... | }
}
impl<Type> ToHtml for Vec<Type>
where
Type: ToHtml,
{
fn to_html(&self, context: &EncodeContext) -> String {
self.iter()
.map(|item| item.to_html(context))
.collect::<Vec<String>>()
.concat()
}
fn to_attrs(&self, context: &EncodeContext) -> Vec<String> ... | self.as_ref().to_html(context)
}
fn to_attrs(&self, context: &EncodeContext) -> Vec<String> {
self.as_ref().to_attrs(context) | random_line_split |
string.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/lib/string.rs
//! Dynamically-allocated string type
//!
//! Acts every similarly to the rust std's String type.
use core::{ops,cmp,fmt};
use vec::Vec;
/// String type
#[derive(Clone,PartialOrd,Ord,PartialEq,Eq)]
pub struct String(Vec<u8>);
/// String b... | {
fn extend<T>(&mut self, iterable: T)
where
T: ::core::iter::IntoIterator<Item=char>
{
for c in iterable {
self.push_char(c);
}
}
}
impl<B: AsMut<[u8]>+AsRef<[u8]>> ops::Deref for FixedString<B>
{
type Target = str;
fn deref(&self) -> &str {
let bytes = &self.data.as_ref()[..self.len];
// SAFE: Vali... | }
}
impl<B: AsMut<[u8]>+AsRef<[u8]>> ::core::iter::Extend<char> for FixedString<B> | random_line_split |
string.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/lib/string.rs
//! Dynamically-allocated string type
//!
//! Acts every similarly to the rust std's String type.
use core::{ops,cmp,fmt};
use vec::Vec;
/// String type
#[derive(Clone,PartialOrd,Ord,PartialEq,Eq)]
pub struct String(Vec<u8>);
/// String b... | (args: fmt::Arguments) -> String {
use core::fmt::Write;
let mut ret = String::new();
let _ = write!(&mut ret, "{}", args);
ret
}
pub fn push(&mut self, c: char) {
let mut buf = [0,0,0,0];
let len = c.encode_utf8(&mut buf).expect("Four bytes not enough for utf-8?");
self.0.push_all(&buf[..len]);
}
/... | from_args | identifier_name |
string.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/lib/string.rs
//! Dynamically-allocated string type
//!
//! Acts every similarly to the rust std's String type.
use core::{ops,cmp,fmt};
use vec::Vec;
/// String type
#[derive(Clone,PartialOrd,Ord,PartialEq,Eq)]
pub struct String(Vec<u8>);
/// String b... |
}
impl<'a> PartialEq<&'a str> for String {
fn eq(&self, v: & &'a str) -> bool {
<str as PartialEq>::eq(&self, *v)
}
}
impl<'a> PartialOrd<&'a str> for String {
fn partial_cmp(&self, v: & &'a str) -> Option<cmp::Ordering> {
<str as PartialOrd>::partial_cmp(&self, *v)
}
}
impl<B: AsMut<[u8]>+AsRef<[u8]>> Fixed... | {
<str as PartialOrd>::partial_cmp(&self, v)
} | identifier_body |
align.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Values for CSS Box Alignment properties
//!
//! https://drafts.csswg.org/css-align/
use crate::values::compu... | () -> Self {
Self {
specified: specified::JustifyItems::legacy(),
computed: specified::JustifyItems::normal(),
}
}
}
impl ToComputedValue for specified::JustifyItems {
type ComputedValue = JustifyItems;
/// <https://drafts.csswg.org/css-align/#valdef-justify-items-l... | legacy | identifier_name |
align.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Values for CSS Box Alignment properties
//!
//! https://drafts.csswg.org/css-align/
use crate::values::compu... | ;
JustifyItems {
specified,
computed,
}
}
#[inline]
fn from_computed_value(computed: &JustifyItems) -> Self {
computed.specified
}
}
| {
// If the inherited value of `justify-items` includes the
// `legacy` keyword, `legacy` computes to the inherited value, but
// we assume it computes to `normal`, and handle that special-case
// in StyleAdjuster.
Self::normal()
} | conditional_block |
align.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Values for CSS Box Alignment properties
//!
//! https://drafts.csswg.org/css-align/
use crate::values::compu... | /// Need to carry around both the specified and computed value to handle the
/// special legacy keyword without destroying style sharing.
///
/// In particular, `justify-items` is a reset property, so we ought to be able
/// to share its computed representation across elements as long as they match
/// the same rules. ... |
/// The computed value for the `justify-items` property.
/// | random_line_split |
borrowck-lend-flow-loop.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 borrow_mut(_v: &mut isize) {}
fn cond() -> bool { panic!() }
fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<isize>) {
*v = box() (**v + 1);
//~^ WARN deprecated syntax
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v: Box<_> = box 3... | {} | identifier_body |
borrowck-lend-flow-loop.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() {}
| {
continue; // ...so it is not live as exit (and re-enter) the `while` loop here
} | conditional_block |
borrowck-lend-flow-loop.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 ... | () {
// In this instance, the borrow is carried through the loop.
let mut v: Box<_> = box 3;
let mut w: Box<_> = box 4;
let mut _x = &w;
while cond() {
borrow_mut(&mut *v);
_x = &v;
break;
}
borrow_mut(&mut *v); //~ ERROR cannot borrow
}
fn while_aliased_mut_cond(co... | while_aliased_mut_break | identifier_name |
borrowck-lend-flow-loop.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 ... | //~^ WARN deprecated syntax
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v: Box<_> = box 3;
let mut x = &mut v;
**x += 1;
loop {
borrow(&*v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this i... | fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<isize>) {
*v = box() (**v + 1); | random_line_split |
challenge16.rs | use aes::Aes128;
use aes::{chunks_count, BLOCK_SIZE};
use xor::XOR;
use crate::errors::*;
use crate::prefix_suffix_oracles::{Oracle, Oracle16};
use super::challenge12::prefix_plus_suffix_length;
pub fn | () -> Result<()> {
let oracle = Oracle16::new()?;
// The following input is chosen in such a way that the last block of the cleartext
// in oracle consists entirely of padding bytes.
let (chunks_count, fill_len) = chunks_count(prefix_plus_suffix_length(&oracle)?);
let mut ciphertext = oracle.encryp... | run | identifier_name |
challenge16.rs | use aes::Aes128;
use aes::{chunks_count, BLOCK_SIZE};
use xor::XOR;
use crate::errors::*;
use crate::prefix_suffix_oracles::{Oracle, Oracle16};
use super::challenge12::prefix_plus_suffix_length;
pub fn run() -> Result<()> | }
| {
let oracle = Oracle16::new()?;
// The following input is chosen in such a way that the last block of the cleartext
// in oracle consists entirely of padding bytes.
let (chunks_count, fill_len) = chunks_count(prefix_plus_suffix_length(&oracle)?);
let mut ciphertext = oracle.encrypt(&vec![0; fill_l... | identifier_body |
challenge16.rs | use aes::Aes128;
use aes::{chunks_count, BLOCK_SIZE};
use xor::XOR;
use crate::errors::*;
use crate::prefix_suffix_oracles::{Oracle, Oracle16};
use super::challenge12::prefix_plus_suffix_length;
pub fn run() -> Result<()> {
let oracle = Oracle16::new()?;
| // Sanity check
compare_eq((chunks_count + 1) * BLOCK_SIZE, ciphertext.len())?;
let target_last_block = b";admin=true".pad();
let current_last_block = vec![BLOCK_SIZE as u8; BLOCK_SIZE];
let attack_bitflip = target_last_block.xor(¤t_last_block);
// Flip the next to last block
ciphert... | // The following input is chosen in such a way that the last block of the cleartext
// in oracle consists entirely of padding bytes.
let (chunks_count, fill_len) = chunks_count(prefix_plus_suffix_length(&oracle)?);
let mut ciphertext = oracle.encrypt(&vec![0; fill_len])?;
| random_line_split |
tftp.rs | /* Copyright (C) 2017-2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY... | opcode : u8, filename : String, mode : String) -> TFTPTransaction {
TFTPTransaction {
opcode,
filename,
mode : mode.to_lowercase(),
id : 0,
tx_data: AppLayerTxData::new(),
}
}
pub fn is_mode_ok(&self) -> bool {
match self.mode.a... | ew( | identifier_name |
tftp.rs | /* Copyright (C) 2017-2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY... | let (i, mode) = getstr(i)?;
Ok((i,
TFTPTransaction::new(opcode, String::from(filename), String::from(mode))
)
)
}
fn parse_tftp_request(input: &[u8]) -> Option<TFTPTransaction> {
match tftp_request(input) {
Ok((_, tx)) => {
if!tx.is_mode_ok() {
retur... | let (i, _) = tag([0])(slice)?;
let (i, opcode) = be_u8(i)?;
let (i, filename) = getstr(i)?;
let (i, _) = tag([0])(i)?; | random_line_split |
tftp.rs | /* Copyright (C) 2017-2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY... |
#[no_mangle]
pub extern "C" fn rs_tftp_get_tx_cnt(state: &mut TFTPState) -> u64 {
return state.tx_id as u64;
}
fn getstr(i: &[u8]) -> IResult<&[u8], &str> {
map_res(
take_while(|c| c!= 0),
str::from_utf8
)(i)
}
fn tftp_request<'a>(slice: &'a [u8]) -> IResult<&[u8], TFTPTransaction> {
... |
match state.get_tx_by_id(tx_id) {
Some(tx) => tx as *const _ as *mut _,
None => std::ptr::null_mut(),
}
}
| identifier_body |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use ... | let symbols = Symbols::parse(context, input)?;
// There must be at least two symbols for alphabetic or
// numeric system.
if (symbols_type == SymbolsType::Alphabetic ||
symbols_type == SymbolsType::Numeric) && symbols.0.len() < 2 {
... | .unwrap_or(SymbolsType::Symbolic); | random_line_split |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use ... | <W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match self.0 {
1 => Ok(()),
0 => dest.write_str(" off"),
x => write!(dest, " {}", x)
}
}
}
impl Parse for FontSettingTagInt {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) ... | to_css | identifier_name |
native-always-waits.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 ... | (argc: int, argv: *const *const u8) -> int {
// make sure that native::start always waits for all children to finish
native::start(argc, argv, proc() {
spawn(proc() {
unsafe { set = true; }
});
});
// if we didn't set the global, then return a nonzero code
if unsafe {set... | start | identifier_name |
native-always-waits.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 ... | {
// make sure that native::start always waits for all children to finish
native::start(argc, argv, proc() {
spawn(proc() {
unsafe { set = true; }
});
});
// if we didn't set the global, then return a nonzero code
if unsafe {set} {0} else {1}
} | identifier_body | |
native-always-waits.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-androi... | random_line_split | |
native-always-waits.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 ... |
}
| {1} | conditional_block |
device.rs | use std::marker::PhantomData;
use std::mem;
use libusb::*;
use context::Context;
use device_handle::{self, DeviceHandle};
use device_descriptor::{self, DeviceDescriptor};
use config_descriptor::{self, ConfigDescriptor};
use fields::{self, Speed};
/// A reference to a USB device.
pub struct Device<'a> {
context:... |
/// Returns the device's address on the bus that it's connected to.
pub fn address(&self) -> u8 {
unsafe {
libusb_get_device_address(self.device)
}
}
/// Returns the device's connection speed.
pub fn speed(&self) -> Speed {
fields::speed_from_libusb(unsafe {
... | {
unsafe {
libusb_get_bus_number(self.device)
}
} | identifier_body |
device.rs | use std::marker::PhantomData;
use std::mem;
use libusb::*;
use context::Context;
use device_handle::{self, DeviceHandle};
use device_descriptor::{self, DeviceDescriptor};
use config_descriptor::{self, ConfigDescriptor};
use fields::{self, Speed};
/// A reference to a USB device.
pub struct Device<'a> {
context:... | (&self) -> u8 {
unsafe {
libusb_get_device_address(self.device)
}
}
/// Returns the device's connection speed.
pub fn speed(&self) -> Speed {
fields::speed_from_libusb(unsafe {
libusb_get_device_speed(self.device)
})
}
/// Opens the device.
... | address | identifier_name |
device.rs | use std::marker::PhantomData;
use std::mem;
use libusb::*;
use context::Context;
use device_handle::{self, DeviceHandle};
use device_descriptor::{self, DeviceDescriptor};
use config_descriptor::{self, ConfigDescriptor};
use fields::{self, Speed};
/// A reference to a USB device.
pub struct Device<'a> {
context:... | unsafe impl<'a> Sync for Device<'a> {}
impl<'a> Device<'a> {
/// Reads the device descriptor.
pub fn device_descriptor(&self) -> ::Result<DeviceDescriptor> {
let mut descriptor: libusb_device_descriptor = unsafe { mem::uninitialized() };
// since libusb 1.0.16, this function always succeeds
... | }
}
}
unsafe impl<'a> Send for Device<'a> {} | random_line_split |
ast.rs | //! Definition of Thinkerbell scripts.
//!
//! Typical applications will not interact with script
//! objects. Rather, they will use module `parse` to parse a script
//! and module `run` to execute it.
use foxbox_taxonomy::channel::*;
use foxbox_taxonomy::io::*;
use foxbox_taxonomy::selector::*;
use foxbox_taxonomy::s... | fn parse(path: Path, source: &JSON) -> Result<Self, ParseError> {
let destination = try!(path.push("destination",
|path| ChannelSelector::take_vec(path, source, "destination"))
);
let feature = try!(path.push("feature",
|path| Id::take(path, source, "feature"))
... | "Parser".to_owned()
}
| identifier_body |
ast.rs | //! Definition of Thinkerbell scripts.
//!
//! Typical applications will not interact with script
//! objects. Rather, they will use module `parse` to parse a script
//! and module `run` to execute it.
use foxbox_taxonomy::channel::*;
use foxbox_taxonomy::io::*;
use foxbox_taxonomy::selector::*;
use foxbox_taxonomy::s... | /// An individual match.
///
/// Matchs always take the form: "data received from getter channel
/// enters given range".
///
/// A condition is true if *any* of the corresponding getter channels
/// yielded a value that enters the given range.
///
/// # JSON
///
/// A match is represented as an object with the followi... | })
}
}
| random_line_split |
ast.rs | //! Definition of Thinkerbell scripts.
//!
//! Typical applications will not interact with script
//! objects. Rather, they will use module `parse` to parse a script
//! and module `run` to execute it.
use foxbox_taxonomy::channel::*;
use foxbox_taxonomy::io::*;
use foxbox_taxonomy::selector::*;
use foxbox_taxonomy::s... | h: Path, source: &JSON) -> Result<Self, ParseError> {
let sources = try!(path.push("source",
|path| ChannelSelector::take_vec(path, source, "source"))
);
let feature = try!(path.push("feature",
|path| Id::take(path, source, "feature"))
);
let range = try!(... | e(pat | identifier_name |
summary.rs | use std::path::PathBuf;
use std::fs::File;
use std::io::{Read, Result, Error, ErrorKind};
use book::bookitem::BookItem;
/*
pub enum LineType {
Blank,
Header,
Link(String, PathBuf), // Name, Path
ListItem(String, PathBuf, i32), // Name, Path, Level
Other,
}
*/
pub fn construct_bookitems(path: &Path... | debug!("\t[line]: {}", line);
debug!("[*]: There is an indentation error on this line. Indentation should be {} spaces", spaces_in_tab);
return Err(Error::new(
ErrorKind::Other,
format!("Indentation error on line:\n\n{}", line)
)
)
}
Ok(level)... | {
debug!("[fn]: level");
let mut spaces = 0;
let mut level = 0;
for ch in line.chars() {
match ch {
' ' => spaces += 1,
'\t' => level += 1,
_ => break,
}
if spaces >= spaces_in_tab {
level += 1;
spaces = 0;
}
... | identifier_body |
summary.rs | use std::path::PathBuf;
use std::fs::File;
use std::io::{Read, Result, Error, ErrorKind};
use book::bookitem::BookItem;
/*
pub enum LineType {
Blank,
Header,
Link(String, PathBuf), // Name, Path
ListItem(String, PathBuf, i32), // Name, Path, Level
Other,
}
*/
pub fn construct_bookitems(path: &Path... | (l: &str) -> Option<BookItem> {
debug!("[fn]: parse_line");
let mut name;
let mut path;
// Remove leading and trailing spaces or tabs
let line = l.trim_matches(|c: char| { c =='' || c == '\t' });
if let Some(c) = line.chars().nth(0) {
match c {
// List item
'-' |... | parse_line | identifier_name |
summary.rs | use std::path::PathBuf;
use std::fs::File;
use std::io::{Read, Result, Error, ErrorKind};
use book::bookitem::BookItem;
/*
pub enum LineType {
Blank,
Header,
Link(String, PathBuf), // Name, Path
ListItem(String, PathBuf, i32), // Name, Path, Level
Other,
}
*/
pub fn construct_bookitems(path: &Path... | let mut items: Vec<BookItem> = vec![];
loop {
if summary.len() <= 0 { break }
let level = try!(level(summary[0], 4));
if current_level > level { break }
else if current_level < level {
items.last_mut().unwrap().sub_items = try!(parse_level(summary, level))
... | Ok(top_items)
}
fn parse_level(summary: &mut Vec<&str>, current_level: i32) -> Result<Vec<BookItem>> {
debug!("[fn]: parse_level"); | random_line_split |
lib.rs | //! Assignment operators (`+=`, `-=`, `*=`, etc) traits
//!
//! Note that no operator sugar is provided, i.e. `x += y` won't use these traits.
//!
//! This crate is only a convenience for me, as I've the need of using these traits as bounds in
//! some of my libraries, and I'd rather not duplicate the definitions in e... | /// The `+=` operator (without the sugar)
pub trait AddAssign<Rhs=Self> {
/// `a += b` -> `AddAssign::add_assign(&mut a, b)`
fn add_assign(&mut self, Rhs);
}
/// The `/=` operator (without the sugar)
pub trait DivAssign<Rhs=Self> {
/// `a /= b` -> `DivAssign::div_assign(&mut a, b)`
fn div_assign(&mut s... |
#![deny(missing_docs)]
#![deny(warnings)]
| random_line_split |
explicit-self-objects-box.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 ... | }
impl Foo for S {
fn f(@self) {
assert_eq!(self.x, 3);
}
}
pub fn main() {
let x = @S { x: 3 };
let y = x as @Foo;
y.f();
y.f();
y.f();
y.f();
} | x: int | random_line_split |
explicit-self-objects-box.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 = @S { x: 3 };
let y = x as @Foo;
y.f();
y.f();
y.f();
y.f();
}
| main | identifier_name |
restyle_damage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The restyle damage is a hint that tells layout which kind of operations may
//! be needed in presence of incr... | ) || (new.get_box().display == Display::Inline &&
restyle_damage_rebuild_and_reflow_inline!(
old,
new,
damage,
[
ServoRestyleDamage::REPAINT,
ServoRestyleDamage::REPOSITION,
ServoRestyleDamage::STORE_OVERFLOW,
... | {
let mut damage = ServoRestyleDamage::empty();
// This should check every CSS property, as enumerated in the fields of
// https://doc.servo.org/style/properties/struct.ComputedValues.html
// This uses short-circuiting boolean OR for its side effects and ignores the result.
let _ = restyle_damage_... | identifier_body |
restyle_damage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The restyle damage is a hint that tells layout which kind of operations may
//! be needed in presence of incr... | () -> ServoRestyleDamage {
ServoRestyleDamage::REPAINT |
ServoRestyleDamage::REPOSITION |
ServoRestyleDamage::STORE_OVERFLOW |
ServoRestyleDamage::BUBBLE_ISIZES |
ServoRestyleDamage::REFLOW_OUT_OF_FLOW |
ServoRestyleDamage::REFLOW |
ServoRe... | rebuild_and_reflow | identifier_name |
restyle_damage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The restyle damage is a hint that tells layout which kind of operations may
//! be needed in presence of incr... | /// Repaint the node itself.
///
/// Currently unused; need to decide how this propagates.
const REPAINT = 0x01;
/// The stacking-context-relative position of this node or its
/// descendants has changed.
///
/// Propagates both up and down the flow tree.... |
bitflags! {
/// Individual layout actions that may be necessary after restyling.
pub struct ServoRestyleDamage: u8 { | random_line_split |
restyle_damage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The restyle damage is a hint that tells layout which kind of operations may
//! be needed in presence of incr... |
damage
}
| {
damage.insert(ServoRestyleDamage::rebuild_and_reflow());
} | conditional_block |
mod.rs | // Legato - Statsd Server in Rust
//
// Copyright 2016 TSH Labs
//
// 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 d... | /// Format aggregated timers to be sent to a `MetricSink` backend.
fn fmt_timers(&self, timers: &HashMap<String, TimerStatsBundle>,
now: &time::Timespec) -> T;
/// Format aggregated gauges to be sent to a `MetricSink` backend.
fn fmt_gauges(&self, gauges: &HashMap<String, u64>,
... | pub trait MetricFormatter<T: AsRef<[u8]>> {
/// Format aggregated counters to be sent to a `MetricSink` backend.
fn fmt_counters(&self, counters: &HashMap<String, i64>,
now: &time::Timespec) -> T;
| random_line_split |
notify.rs | use {sys, Evented, EventSet, PollOpt, Selector, Token};
use util::BoundedQueue;
use std::{fmt, cmp, io};
use std::sync::Arc;
use std::sync::atomic::AtomicIsize;
use std::sync::atomic::Ordering::Relaxed;
const SLEEP: isize = -1;
const CLOSED: isize = -2;
/// Send notifications to the event loop, waking it up if necess... |
_ => { cur + 1 }
};
val = self.state.compare_and_swap(cur, nxt, Relaxed);
if val == cur {
break;
}
cur = val;
}
if cur == SLEEP {
if let Err(e) = self.awaken.wakeup() {
return Err... | { 1 } | conditional_block |
notify.rs | use {sys, Evented, EventSet, PollOpt, Selector, Token};
use util::BoundedQueue;
use std::{fmt, cmp, io};
use std::sync::Arc;
use std::sync::atomic::AtomicIsize;
use std::sync::atomic::Ordering::Relaxed;
const SLEEP: isize = -1;
const CLOSED: isize = -2;
/// Send notifications to the event loop, waking it up if necess... | nxt = SLEEP;
} else {
nxt = 0;
}
}
val = self.state.compare_and_swap(cur, nxt, Relaxed);
if val == cur {
break;
}
cur = val;
}
if cur < 0 {
... | {
let max = max as isize;
let mut cur = self.state.load(Relaxed);
let mut nxt;
let mut val;
loop {
// This should be impossible if close() in only called from the event loop destructor
debug_assert!(cur != CLOSED);
// If there are pending mes... | identifier_body |
notify.rs | use {sys, Evented, EventSet, PollOpt, Selector, Token};
use util::BoundedQueue;
use std::{fmt, cmp, io};
use std::sync::Arc;
use std::sync::atomic::AtomicIsize;
use std::sync::atomic::Ordering::Relaxed;
const SLEEP: isize = -1;
const CLOSED: isize = -2;
/// Send notifications to the event loop, waking it up if necess... | // If there are pending messages, then whether or not the event loop
// was planning to sleep does not matter - it will not sleep.
if cur > 0 {
if max >= cur {
nxt = 0;
} else {
nxt = cur - max;
}... | debug_assert!(cur != CLOSED);
| random_line_split |
notify.rs | use {sys, Evented, EventSet, PollOpt, Selector, Token};
use util::BoundedQueue;
use std::{fmt, cmp, io};
use std::sync::Arc;
use std::sync::atomic::AtomicIsize;
use std::sync::atomic::Ordering::Relaxed;
const SLEEP: isize = -1;
const CLOSED: isize = -2;
/// Send notifications to the event loop, waking it up if necess... | <M> {
state: AtomicIsize,
queue: BoundedQueue<M>,
awaken: sys::Awakener
}
impl<M: Send> NotifyInner<M> {
fn with_capacity(capacity: usize) -> io::Result<NotifyInner<M>> {
Ok(NotifyInner {
state: AtomicIsize::new(0),
queue: BoundedQueue::with_capacity(capacity),
... | NotifyInner | identifier_name |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct LayoutCo... |
}
| {
Box::new(LayoutCollection {
current: self.current,
layouts: self.layouts.iter().map(|x| x.copy()).collect(),
})
} | identifier_body |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct LayoutCo... |
_ => self.layouts[self.current].apply_message(message, window_system, stack, config),
}
}
fn description(&self) -> String {
self.layouts[self.current].description()
}
fn copy(&self) -> Box<dyn Layout> {
Box::new(LayoutCollection {
current: self.current,... | {
self.layouts[self.current].unhook(window_system, stack, config);
self.current = (self.current + (self.layouts.len() - 1)) % self.layouts.len();
true
} | conditional_block |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct LayoutCo... | fn description(&self) -> String {
self.layouts[self.current].description()
}
fn copy(&self) -> Box<dyn Layout> {
Box::new(LayoutCollection {
current: self.current,
layouts: self.layouts.iter().map(|x| x.copy()).collect(),
})
}
} | _ => self.layouts[self.current].apply_message(message, window_system, stack, config),
}
}
| random_line_split |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct LayoutCo... | (layouts: Vec<Box<dyn Layout>>) -> Box<dyn Layout> {
Box::new(LayoutCollection {
layouts,
current: 0,
})
}
}
impl Layout for LayoutCollection {
fn apply_layout(
&mut self,
window_system: &dyn WindowSystem,
screen: Rectangle,
config: &Gener... | boxed_new | identifier_name |
regions-infer-paramd-indirect.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> {
f: Box<b<'a>>
}
trait set_f<'a> {
fn set_f_ok(&mut self, b: Box<b<'a>>);
fn set_f_bad(&mut self, b: Box<b>);
}
impl<'a> set_f<'a> for c<'a> {
fn set_f_ok(&mut self, b: Box<b<'a>>) {
self.f = b;
}
fn set_f_bad(&mut self, b: Box<b>) {
self.f = b; //~ ERROR mismatched type... | c | identifier_name |
regions-infer-paramd-indirect.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 ... | }
impl<'a> set_f<'a> for c<'a> {
fn set_f_ok(&mut self, b: Box<b<'a>>) {
self.f = b;
}
fn set_f_bad(&mut self, b: Box<b>) {
self.f = b; //~ ERROR mismatched types: expected `Box<Box<&'a int>>`, found `Box<Box<&int>>`
}
}
fn main() {} | fn set_f_bad(&mut self, b: Box<b>); | random_line_split |
regions-infer-paramd-indirect.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() {}
| {
self.f = b; //~ ERROR mismatched types: expected `Box<Box<&'a int>>`, found `Box<Box<&int>>`
} | identifier_body |
schemes.rs | use valico::json_schema;
use typemap;
use super::super::framework;
pub struct SchemesScope;
impl typemap::Key for SchemesScope {
type Value = json_schema::Scope;
}
fn build_schemes(handlers: &mut framework::ApiHandlers, scope: &mut json_schema::Scope) -> Result<(), json_schema::SchemaError> {
for handler_ i... | (app: &mut framework::Application, mut scope: json_schema::Scope) -> Result<(), json_schema::SchemaError> {
try!(build_schemes(&mut app.root_api.handlers, &mut scope));
app.ext.insert::<SchemesScope>(scope);
Ok(())
} | enable_schemes | identifier_name |
schemes.rs | use valico::json_schema;
use typemap;
| pub struct SchemesScope;
impl typemap::Key for SchemesScope {
type Value = json_schema::Scope;
}
fn build_schemes(handlers: &mut framework::ApiHandlers, scope: &mut json_schema::Scope) -> Result<(), json_schema::SchemaError> {
for handler_ in handlers.iter_mut() {
let mut handler = &mut **handler_ as ... | use super::super::framework;
| random_line_split |
schemes.rs | use valico::json_schema;
use typemap;
use super::super::framework;
pub struct SchemesScope;
impl typemap::Key for SchemesScope {
type Value = json_schema::Scope;
}
fn build_schemes(handlers: &mut framework::ApiHandlers, scope: &mut json_schema::Scope) -> Result<(), json_schema::SchemaError> | }
Ok(())
}
pub fn enable_schemes(app: &mut framework::Application, mut scope: json_schema::Scope) -> Result<(), json_schema::SchemaError> {
try!(build_schemes(&mut app.root_api.handlers, &mut scope));
app.ext.insert::<SchemesScope>(scope);
Ok(())
} | {
for handler_ in handlers.iter_mut() {
let mut handler = &mut **handler_ as &mut framework::ApiHandler;
if handler.is::<framework::Api>() {
let api = handler.downcast_mut::<framework::Api>().unwrap();
try!(build_schemes(&mut api.handlers, scope))
} else if handler.is... | identifier_body |
schemes.rs | use valico::json_schema;
use typemap;
use super::super::framework;
pub struct SchemesScope;
impl typemap::Key for SchemesScope {
type Value = json_schema::Scope;
}
fn build_schemes(handlers: &mut framework::ApiHandlers, scope: &mut json_schema::Scope) -> Result<(), json_schema::SchemaError> {
for handler_ i... |
}
}
Ok(())
}
pub fn enable_schemes(app: &mut framework::Application, mut scope: json_schema::Scope) -> Result<(), json_schema::SchemaError> {
try!(build_schemes(&mut app.root_api.handlers, &mut scope));
app.ext.insert::<SchemesScope>(scope);
Ok(())
} | {
let coercer = endpoint.coercer.as_mut().unwrap();
try!(coercer.build_schemes(scope));
} | conditional_block |
doc-attrib.rs | // rustfmt-wrap_comments: true
// rustfmt-normalize_doc_attributes: true
// Only doc = "" attributes should be normalized
#![doc = " Example doc attribute comment"]
#![doc = " Example doc attribute comment with 10 leading spaces"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v... | // Long `#[doc = "..."]`
struct A { #[doc = " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"] b: i32 }
#[doc = " The `nodes` and `edges` method each return instantiations of `Cow<[T]>` to leave implementers the freedom to create entirely new vectors or to pass back slices into... | random_line_split | |
doc-attrib.rs | // rustfmt-wrap_comments: true
// rustfmt-normalize_doc_attributes: true
// Only doc = "" attributes should be normalized
#![doc = " Example doc attribute comment"]
#![doc = " Example doc attribute comment with 10 leading spaces"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v... | { b: i32 }
#[doc = " Level 1 comment"]
mod tests {
#[doc = " Level 2 comment"]
impl A {
#[doc = " Level 3 comment"]
fn f() {
#[doc = " Level 4 comment"]
fn g() {
}
}
}
}
struct C {
#[doc = " item doc attrib comment"]
// regular item com... | B | identifier_name |
p089.rs | //! [Problem 89](https://projecteuler.net/problem=89) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::{
fs::File,
io::{self, prelude::*, BufReader},
u32,
};
const ROMAN_PAIRS: &[(&str, u32)] = &[
... | s.push_str("C");
}
if n >= 90 {
n -= 90;
s.push_str("XC");
}
if n >= 50 {
n -= 50;
s.push_str("L");
}
if n >= 40 {
n -= 40;
s.push_str("XL");
}
while n >= 10 {
n -= 10;
s.push_str("X");
}
if n >= 9 {
... | {
let mut s = String::new();
while n >= 1000 {
n -= 1000;
s.push_str("M");
}
if n >= 900 {
n -= 900;
s.push_str("CM");
}
if n >= 500 {
n -= 500;
s.push_str("D");
}
if n >= 400 {
n -= 400;
s.push_str("CD");
}
while n ... | identifier_body |
p089.rs | //! [Problem 89](https://projecteuler.net/problem=89) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::{
fs::File,
io::{self, prelude::*, BufReader},
u32,
}; | ("IX", 9),
("XL", 40),
("XC", 90),
("CD", 400),
("CM", 900),
("I", 1),
("V", 5),
("X", 10),
("L", 50),
("C", 100),
("D", 500),
("M", 1000),
];
fn from_roman(mut s: &str) -> Option<u32> {
let mut last_d = u32::MAX;
let mut n = 0;
while!s.is_empty() {
... |
const ROMAN_PAIRS: &[(&str, u32)] = &[
("IV", 4), | random_line_split |
p089.rs | //! [Problem 89](https://projecteuler.net/problem=89) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::{
fs::File,
io::{self, prelude::*, BufReader},
u32,
};
const ROMAN_PAIRS: &[(&str, u32)] = &[
... |
while n >= 100 {
n -= 100;
s.push_str("C");
}
if n >= 90 {
n -= 90;
s.push_str("XC");
}
if n >= 50 {
n -= 50;
s.push_str("L");
}
if n >= 40 {
n -= 40;
s.push_str("XL");
}
while n >= 10 {
n -= 10;
s.push_... | {
n -= 400;
s.push_str("CD");
} | conditional_block |
p089.rs | //! [Problem 89](https://projecteuler.net/problem=89) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::{
fs::File,
io::{self, prelude::*, BufReader},
u32,
};
const ROMAN_PAIRS: &[(&str, u32)] = &[
... | (mut n: u32) -> String {
let mut s = String::new();
while n >= 1000 {
n -= 1000;
s.push_str("M");
}
if n >= 900 {
n -= 900;
s.push_str("CM");
}
if n >= 500 {
n -= 500;
s.push_str("D");
}
if n >= 400 {
n -= 400;
s.push_str("C... | to_roman | identifier_name |
utils.rs | // TODO redo the "Private" traits
use data_type::{DataTypeFetchResp, DataTypeMapEntry, DataTypeMapField, DataTypeValue};
use errors::RiakErr;
use object::{FetchObjectResp, ObjectContent};
use rpb::riak::RpbBucketProps;
use rpb::riak_dt::{DtFetchResp, DtValue, MapEntry, MapField};
use rpb::riak_kv::{RpbContent, RpbGetRe... | } | random_line_split | |
fmt.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
// macro_rules! peel {
// ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
// }
// macro_rules! tuple {
// () => ();
// ( $($name:ident,)+ ) => (
// #[stable(feature = "rust1", since = "1.0.0")]
... | assert_eq!(output, "(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33)".to_string());
}
} | random_line_split | |
fmt.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
// macro_rules! peel {
// ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
// }
// macro_rules! tuple {
// () => ();
// ( $($name:ident,)+ ) => (
// #[stable(feature = "rust1", since = "1.0.0")]
... | () {
let value: (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) = (
b'h' as T0,
b'e' as T1,
b'l' as T2,
b'l' as T3,
b'o' as T4,
b''as T5,
b'w' as T6,
b'o' as T7,
b'r' as T8,
b'l' as T9,
b'd' as T10,
b'!' as T11
);
let output: String = format!("{:?}", val... | fmt_test1 | identifier_name |
fmt.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
// macro_rules! peel {
// ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
// }
// macro_rules! tuple {
// () => ();
// ( $($name:ident,)+ ) => (
// #[stable(feature = "rust1", since = "1.0.0")]
... |
}
| {
let value: (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) = (
b'h' as T0,
b'e' as T1,
b'l' as T2,
b'l' as T3,
b'o' as T4,
b' ' as T5,
b'w' as T6,
b'o' as T7,
b'r' as T8,
b'l' as T9,
b'd' as T10,
b'!' as T11
);
let output: String = format!("{:?}", valu... | identifier_body |
alphabet.rs | use text::letter::Letter;
use graphics::rectangle::Rectangle;
use std::collections::HashMap;
use text::font::Font;
pub struct Alphabet<'r> {
font: &'r Font<'r>,
alphabet: HashMap<char, Letter>,
}
impl<'r> Alphabet<'r> {
pub fn new(font: &'r Font) -> Alphabet<'r> {
let mut alphabet = HashMap::new... | (&self, letter: char) -> Option<&Letter> {
match self.alphabet.get(&letter) {
Some(res) => Some(res),
None => {
println!("Couldn't find - {}", letter);
None
}
}
}
pub fn letter_width(&self) -> f32 {
let (_, v) = self.al... | find | identifier_name |
alphabet.rs | use text::letter::Letter;
use graphics::rectangle::Rectangle;
use std::collections::HashMap;
use text::font::Font;
pub struct Alphabet<'r> {
font: &'r Font<'r>,
alphabet: HashMap<char, Letter>,
}
impl<'r> Alphabet<'r> {
pub fn new(font: &'r Font) -> Alphabet<'r> {
let mut alphabet = HashMap::new... |
pub fn letter_width(&self) -> f32 {
let (_, v) = self.alphabet
.iter()
.next()
.expect("Couldn't get letter width from alphabet.");
v.tex_pos.w
}
}
| {
match self.alphabet.get(&letter) {
Some(res) => Some(res),
None => {
println!("Couldn't find - {}", letter);
None
}
}
} | identifier_body |
alphabet.rs | use text::letter::Letter;
use graphics::rectangle::Rectangle;
use std::collections::HashMap;
use text::font::Font;
pub struct Alphabet<'r> {
font: &'r Font<'r>,
alphabet: HashMap<char, Letter>,
}
impl<'r> Alphabet<'r> {
pub fn new(font: &'r Font) -> Alphabet<'r> {
let mut alphabet = HashMap::new... | .iter()
.next()
.expect("Couldn't get letter width from alphabet.");
v.tex_pos.w
}
} | }
pub fn letter_width(&self) -> f32 {
let (_, v) = self.alphabet | random_line_split |
lib.rs | //! This crate provides native rust implementations of
//! Image encoders and decoders and basic image manipulation
//! functions.
#![crate_name = "image"]
#![crate_type = "rlib"]
#![warn(missing_docs)]
#![warn(unused_qualifications)]
#![warn(unused_typecasts)]
#![feature(macro_rules)]
extern crate flate;
pub use c... | load,
load_from_memory,
save_buffer,
};
pub use dynimage::DynamicImage:: {
ImageRgb8,
ImageRgba8,
ImageLuma8,
ImageLumaA8,
};
//Image Processing Functions
pub mod imageops;
//Image Codecs
pub mod webp;
pub mod ppm;
pub mod png;
pub mod jpeg;
pub mod gif;
pub mod tiff;
pub mod tga;
mod ima... | ///opening and loading images
pub use dynimage:: {
open, | random_line_split |
fs.rs | use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::os::windows::prelude::*;
use std::path::{Path, PathBuf};
use std::{io, ptr};
use winapi::shared::minwindef::*;
use winapi::shared::winerror::*;
use winapi::um::errhandlingapi::*;
use winapi::um::fileapi::*;
use winapi::um::minwinbase::*;
use wina... | <P: AsRef<Path>>(path: P) -> io::Result<()> {
// On Windows it is not enough to just recursively remove the contents of a
// directory and then the directory itself. Deleting does not happen
// instantaneously, but is scheduled.
// To work around this, we move the file or directory to some `base_dir`
... | remove_dir_all | identifier_name |
fs.rs | use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::os::windows::prelude::*;
use std::path::{Path, PathBuf};
use std::{io, ptr};
use winapi::shared::minwindef::*;
use winapi::shared::winerror::*;
use winapi::um::errhandlingapi::*;
use winapi::um::fileapi::*;
use winapi::um::minwinbase::*;
use wina... | (*info).FileNameLength = (size - STRUCT_SIZE) as DWORD;
let result = SetFileInformationByHandle(
file.as_raw_handle(),
FileRenameInfo,
data.as_mut_ptr() as *mut _ as *mut _,
size as DWORD,
);
if result == 0 {
Err(io::Error::las... | random_line_split | |
fs.rs | use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::os::windows::prelude::*;
use std::path::{Path, PathBuf};
use std::{io, ptr};
use winapi::shared::minwindef::*;
use winapi::shared::winerror::*;
use winapi::um::errhandlingapi::*;
use winapi::um::fileapi::*;
use winapi::um::minwinbase::*;
use wina... | else {
let extra = n - heap_buf.len();
heap_buf.reserve(extra);
heap_buf.set_len(n);
&mut heap_buf[..]
};
// This function is typically called on windows API functions which
// will return the correct length of the str... | {
&mut stack_buf[..]
} | conditional_block |
main.rs | // https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/generics.html
#![allow(dead_code, unused_variables)]
fn main() {
////////////////////////////////////////////////////////////////////////////////
// Generics
let x: Option<i32> = Some(5);
// let x: Option<f64> = Some(5); // er... | <T>(x: T) {
// Do something with `x`.
}
fn takes_two_things<T, U>(x: T, y: U) {
//...
}
////////////////////////////////////////////////////////////////////////////////
// Generics structs
struct Point<T> {
x: T,
y: T,
}
let int_origin = Point { x: 0, ... | takes_anything | identifier_name |
main.rs | // https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/generics.html
#![allow(dead_code, unused_variables)]
fn main() {
////////////////////////////////////////////////////////////////////////////////
// Generics
let x: Option<i32> = Some(5);
// let x: Option<f64> = Some(5); // er... | }
fn takes_two_things<T, U>(x: T, y: U) {
//...
}
////////////////////////////////////////////////////////////////////////////////
// Generics structs
struct Point<T> {
x: T,
y: T,
}
let int_origin = Point { x: 0, y: 0 };
let float_origin = Point { x: 0.0,... | fn takes_anything<T>(x: T) {
// Do something with `x`. | random_line_split |
fcmovnb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn fcmovnb_1() {
run_test(&Instruction { mnemonic: Mnemonic::FCMOVNB, operand1: Some(Direct(ST)), operand2: Some(Direct(ST... |
fn fcmovnb_3() {
run_test(&Instruction { mnemonic: Mnemonic::FCMOVNB, operand1: Some(Direct(ST)), operand2: Some(Direct(ST7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[219, 199], OperandSize::Qword)
}
| {
run_test(&Instruction { mnemonic: Mnemonic::FCMOVNB, operand1: Some(Direct(ST)), operand2: Some(Direct(ST1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[219, 193], OperandSize::Dword)
} | identifier_body |
fcmovnb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn fcmovnb_1() {
run_test(&Instruction { mnemonic: Mnemonic::FCMOVNB, operand1: Some(Direct(ST)), operand2: Some(Direct(ST... | fn fcmovnb_3() {
run_test(&Instruction { mnemonic: Mnemonic::FCMOVNB, operand1: Some(Direct(ST)), operand2: Some(Direct(ST7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[219, 199], OperandSize::Qword)
} | }
| random_line_split |
fcmovnb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn fcmovnb_1() {
run_test(&Instruction { mnemonic: Mnemonic::FCMOVNB, operand1: Some(Direct(ST)), operand2: Some(Direct(ST... | () {
run_test(&Instruction { mnemonic: Mnemonic::FCMOVNB, operand1: Some(Direct(ST)), operand2: Some(Direct(ST1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[219, 193], OperandSize::Dword)
}
fn fcmovnb_3() {
run_test(&Instruc... | fcmovnb_2 | identifier_name |
widget.rs | use std::io::{Result, Write};
use analysis;
use env::Env;
use super::{function, general};
use super::general::tabs;
pub fn generate<W: Write>(w: &mut W, env: &Env, analysis: &analysis::object::Info) -> Result<()>{
let type_ = analysis.type_(&env.library);
try!(general::start_comments(w, &env.config));
tr... |
try!(general::impl_static_type(w, &analysis.name, &type_.glib_get_type));
if generate_trait(analysis) {
try!(writeln!(w, ""));
try!(writeln!(w, "pub trait {}Ext {{", analysis.name));
for func_analysis in &analysis.methods() {
try!(function::generate(w, env, func_analysis, t... | {
try!(writeln!(w, ""));
try!(writeln!(w, "impl {} {{", analysis.name));
for func_analysis in &analysis.constructors() {
try!(function::generate(w, env, func_analysis, false, false, 1));
}
if !generate_trait(analysis) {
for func_analysis in &analysis.meth... | conditional_block |
widget.rs | use std::io::{Result, Write};
use analysis;
use env::Env;
use super::{function, general};
use super::general::tabs;
pub fn generate<W: Write>(w: &mut W, env: &Env, analysis: &analysis::object::Info) -> Result<()>{
let type_ = analysis.type_(&env.library);
try!(general::start_comments(w, &env.config));
tr... | (analysis: &analysis::object::Info) -> bool {
analysis.has_children
}
pub fn generate_reexports(env: &Env, analysis: &analysis::object::Info, module_name: &str,
contents: &mut Vec<String>, traits: &mut Vec<String>) {
let version_cfg = general::version_condition_string(&env.config.library_name,
... | generate_trait | identifier_name |
widget.rs | use std::io::{Result, Write};
use analysis;
use env::Env;
use super::{function, general};
use super::general::tabs;
pub fn generate<W: Write>(w: &mut W, env: &Env, analysis: &analysis::object::Info) -> Result<()>{
let type_ = analysis.type_(&env.library);
try!(general::start_comments(w, &env.config));
tr... |
pub fn generate_reexports(env: &Env, analysis: &analysis::object::Info, module_name: &str,
contents: &mut Vec<String>, traits: &mut Vec<String>) {
let version_cfg = general::version_condition_string(&env.config.library_name,
env.config.min_cfg_version, analysis.version, false, 0);
let (cfg, cf... | {
analysis.has_children
} | identifier_body |
widget.rs | use std::io::{Result, Write};
use analysis;
use env::Env;
use super::{function, general};
use super::general::tabs;
pub fn generate<W: Write>(w: &mut W, env: &Env, analysis: &analysis::object::Info) -> Result<()>{
let type_ = analysis.type_(&env.library);
try!(general::start_comments(w, &env.config));
tr... |
pub fn generate_reexports(env: &Env, analysis: &analysis::object::Info, module_name: &str,
contents: &mut Vec<String>, traits: &mut Vec<String>) {
let version_cfg = general::version_condition_string(&env.config.library_name,
env.config.min_cfg_version, analysis.version, false, 0);
let (cfg, cfg... | } | random_line_split |
callee.rs | hise = abis.is_intrinsic()
}
_ => {
must_monomorphise = false;
}
}
} else {
must_monomorphise = false;
}
// Create a monomorphic verison of generic functions
if must_monomorphise {
// Should be either intra-crate or inlined.
... | random_line_split | ||
callee.rs |
ref_id: ast::NodeId) -> FnData |
pub fn trans_fn_ref_with_vtables_to_callee(
bcx: @mut Block,
def_id: ast::DefId,
ref_id: ast::NodeId,
type_params: &[ty::t],
vtables: Option<typeck::vtable_res>)
-> Callee {
Callee {bcx: bcx,
data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id,
... | {
/*!
*
* Translates a reference (with id `ref_id`) to the fn/method
* with id `def_id` into a function pointer. This may require
* monomorphization or inlining. */
let _icx = push_ctxt("trans_fn_ref");
let type_params = node_id_type_params(bcx, ref_id);
let vtables = node_vtables... | identifier_body |
callee.rs | {
Closure(Datum),
Fn(FnData),
Method(MethodData)
}
pub struct Callee {
bcx: @mut Block,
data: CalleeData
}
pub fn trans(bcx: @mut Block, expr: &ast::Expr) -> Callee {
let _icx = push_ctxt("trans_callee");
debug2!("callee::trans(expr={})", expr.repr(bcx.tcx()));
// pick out special ki... | CalleeData | identifier_name | |
var.rs | //! Intermediate representation of variables.
use super::super::codegen::MacroTypeVariation;
use super::context::{BindgenContext, TypeId};
use super::dot::DotAttributes;
use super::function::cursor_mangling;
use super::int::IntKind;
use super::item::Item;
use super::ty::{FloatKind, TypeKind};
use crate::callbacks::Mac... |
fn get_integer_literal_from_cursor(
cursor: &clang::Cursor,
unit: &clang::TranslationUnit,
) -> Option<i64> {
use clang_sys::*;
let mut value = None;
cursor.visit(|c| {
match c.kind() {
CXCursor_IntegerLiteral | CXCursor_UnaryOperator => {
value = parse_int_lite... | {
use cexpr::expr;
use cexpr::expr::EvalResult;
let cexpr_tokens = cursor.cexpr_tokens();
// TODO(emilio): We can try to parse other kinds of literals.
match expr::expr(&cexpr_tokens) {
Ok((_, EvalResult::Int(Wrapping(val)))) => Some(val),
_ => None,
}
} | identifier_body |
var.rs | //! Intermediate representation of variables.
use super::super::codegen::MacroTypeVariation;
use super::context::{BindgenContext, TypeId};
use super::dot::DotAttributes;
use super::function::cursor_mangling;
use super::int::IntKind;
use super::item::Item;
use super::ty::{FloatKind, TypeKind};
use crate::callbacks::Mac... | {
/// A boolean.
Bool(bool),
/// An integer.
Int(i64),
/// A floating point number.
Float(f64),
/// A character.
Char(u8),
/// A string, not necessarily well-formed utf-8.
String(Vec<u8>),
}
/// A `Var` is our intermediate representation of a variable.
#[derive(Debug)]
pub stru... | VarType | identifier_name |
var.rs | //! Intermediate representation of variables.
use super::super::codegen::MacroTypeVariation;
use super::context::{BindgenContext, TypeId};
use super::dot::DotAttributes;
use super::function::cursor_mangling;
use super::int::IntKind;
use super::item::Item;
use super::ty::{FloatKind, TypeKind};
use crate::callbacks::Mac... | let (type_kind, val) = match value {
EvalResult::Invalid => return Err(ParseError::Continue),
EvalResult::Float(f) => {
(TypeKind::Float(FloatKind::Double), VarType::Float(f))
}
EvalResult::Char(c) =>... | let name = String::from_utf8(id).unwrap(); | random_line_split |
database.rs | extern crate rusqlite;
use std::result::Result;
use std::string::String;
// TODO: use rusqlite::Connection
pub struct Database {
conn: rusqlite::Connection,
}
#[derive(Debug)]
pub struct Artist {
pub id: i32,
pub name: String,
pub musicbrainz_id: String,
pub last_checked: i64
}
impl Database {
... |
}
| {
let mut stmt = self.conn.prepare("SELECT id, name, musicbrainzId, lastChecked FROM artists ORDER BY lastChecked ASC LIMIT 1").unwrap();
let mut artist_iter = stmt.query_map(&[], |row| {
Artist {
id: row.get(0),
name: row.get(1),
musicbrainz_i... | identifier_body |
database.rs | extern crate rusqlite;
use std::result::Result;
use std::string::String;
// TODO: use rusqlite::Connection
pub struct Database {
conn: rusqlite::Connection,
}
#[derive(Debug)]
pub struct Artist {
pub id: i32,
pub name: String,
pub musicbrainz_id: String,
pub last_checked: i64
}
impl Database {
... | (filename: String) -> Database {
Database {
conn: rusqlite::Connection::open(filename).unwrap(),
}
}
pub fn create_artists_table(&self) -> Result<(), rusqlite::Error> {
try!(self.conn.execute(
"CREATE TABLE artists (
id INTEGER PRIMARY KEY AUTOINCREM... | new | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.