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 |
|---|---|---|---|---|
rss.rs | use std::error::Error;
use async_trait::async_trait;
use futures::{StreamExt, TryFutureExt};
use rss::Channel;
use bytes::Bytes;
use chrono::DateTime;
use itertools::Itertools;
use super::Provider;
use crate::utils::{Json, Map, hash, IteratorEx};
use crate::config::ConfigFeedEntry;
use crate::feeds::{Feed, Entry}; |
pub struct RssProvider;
impl RssProvider {
pub fn new(_config: Json) -> Result<Self, Box<dyn Error>> {
Ok(RssProvider)
}
}
#[async_trait(?Send)]
impl Provider for RssProvider {
async fn fetch(&mut self, config: Map<&ConfigFeedEntry>) -> Map<Feed> {
// Url -> Feed
let data = config.values()
... |
const MAX_CON_REQUESTS: usize = 10; | random_line_split |
rss.rs | use std::error::Error;
use async_trait::async_trait;
use futures::{StreamExt, TryFutureExt};
use rss::Channel;
use bytes::Bytes;
use chrono::DateTime;
use itertools::Itertools;
use super::Provider;
use crate::utils::{Json, Map, hash, IteratorEx};
use crate::config::ConfigFeedEntry;
use crate::feeds::{Feed, Entry};
co... | (_config: Json) -> Result<Self, Box<dyn Error>> {
Ok(RssProvider)
}
}
#[async_trait(?Send)]
impl Provider for RssProvider {
async fn fetch(&mut self, config: Map<&ConfigFeedEntry>) -> Map<Feed> {
// Url -> Feed
let data = config.values()
.map(|entry| entry.provider_data.as_str())
... | new | identifier_name |
rss.rs | use std::error::Error;
use async_trait::async_trait;
use futures::{StreamExt, TryFutureExt};
use rss::Channel;
use bytes::Bytes;
use chrono::DateTime;
use itertools::Itertools;
use super::Provider;
use crate::utils::{Json, Map, hash, IteratorEx};
use crate::config::ConfigFeedEntry;
use crate::feeds::{Feed, Entry};
co... | feed.notifications.push(entry);
}
feed
},
Ok(Err(err)) => Feed::from_err(&format!("Unable to parse {}", url), &err.to_string()),
Err(err) => Feed::from_err(&format!("Unable to fetch {}", url), &err.to_string()),
}
}
| {
let parsed = response.map(|content| Channel::read_from(&*content));
match parsed {
Ok(Ok(chan)) => {
let mut feed = Feed::new();
for item in chan.items() {
let title = item.title().clone().unwrap_or("<No Title>");
let timestamp = item.pub_date()
.and_then(|time| DateTim... | identifier_body |
error.rs | //! Error types and conversion functions.
use std::error::Error;
use std::fmt;
use std::sync::Arc;
use rodio::decoder::DecoderError;
use rodio::PlayError;
/// An enum containing all kinds of game framework errors.
#[derive(Debug, Clone)]
pub enum GameError {
/// An error in the filesystem layout
FilesystemErr... |
}
impl From<DecoderError> for GameError {
fn from(e: DecoderError) -> GameError {
let errstr = format!("Audio decoder error: {:?}", e);
GameError::AudioError(errstr)
}
}
impl From<PlayError> for GameError {
fn from(e: PlayError) -> GameError {
let errstr = format!("Audio playing e... | {
let errstr = format!("Zip error: {}", e.to_string());
GameError::ResourceLoadError(errstr)
} | identifier_body |
error.rs | //! Error types and conversion functions.
use std::error::Error;
use std::fmt;
use std::sync::Arc;
use rodio::decoder::DecoderError;
use rodio::PlayError;
/// An enum containing all kinds of game framework errors.
#[derive(Debug, Clone)]
pub enum GameError {
/// An error in the filesystem layout
FilesystemErr... | (e: zip::result::ZipError) -> GameError {
let errstr = format!("Zip error: {}", e.to_string());
GameError::ResourceLoadError(errstr)
}
}
impl From<DecoderError> for GameError {
fn from(e: DecoderError) -> GameError {
let errstr = format!("Audio decoder error: {:?}", e);
GameErro... | from | identifier_name |
error.rs | //! Error types and conversion functions.
use std::error::Error;
use std::fmt;
use std::sync::Arc;
use rodio::decoder::DecoderError;
use rodio::PlayError;
/// An enum containing all kinds of game framework errors.
#[derive(Debug, Clone)]
pub enum GameError {
/// An error in the filesystem layout
FilesystemErr... | "Resource not found: {}, searched in paths {:?}",
s, paths
),
GameError::WindowError(ref e) => write!(f, "Window creation error: {}", e),
GameError::CustomError(ref s) => write!(f, "Custom error: {}", s),
GameError::CanvasMSAAError => write... | GameError::ResourceLoadError(ref s) => write!(f, "Error loading resource: {}", s),
GameError::ResourceNotFound(ref s, ref paths) => write!(
f, | random_line_split |
main.rs | #[macro_use]
extern crate diesel;
| #[macro_use]
extern crate log;
mod database;
pub mod models;
pub mod routes;
mod schema;
pub mod util;
use crate::routes::rest;
use crate::routes::rest::izettle::IZettleNotifier;
use crate::util::{catchers, FileResponder};
use clap::Parser;
use dotenv::dotenv;
use rocket::routes;
#[derive(Default, Parser)]
pub stru... | random_line_split | |
main.rs | #[macro_use]
extern crate diesel;
#[macro_use]
extern crate log;
mod database;
pub mod models;
pub mod routes;
mod schema;
pub mod util;
use crate::routes::rest;
use crate::routes::rest::izettle::IZettleNotifier;
use crate::util::{catchers, FileResponder};
use clap::Parser;
use dotenv::dotenv;
use rocket::routes;
... | {
/// Database url specified as a postgres:// uri
#[clap(long, short, env = "DATABASE_URL")]
database: String,
/// Run database migrations on startup
#[clap(long, short ='m', env = "RUN_MIGRATIONS")]
run_migrations: bool,
/// Enable HTTP cache control of statically served files
#[clap... | Opt | identifier_name |
main.rs | #[macro_use]
extern crate diesel;
#[macro_use]
extern crate log;
mod database;
pub mod models;
pub mod routes;
mod schema;
pub mod util;
use crate::routes::rest;
use crate::routes::rest::izettle::IZettleNotifier;
use crate::util::{catchers, FileResponder};
use clap::Parser;
use dotenv::dotenv;
use rocket::routes;
... |
let rocket = rocket::build()
.manage(db_pool)
.manage(IZettleNotifier::default())
.register("/", catchers())
.attach(FileResponder {
folder: "www",
enable_cache: opt.static_file_cache,
max_age: opt.max_age,
})
.mount(
"/api... | {
database::run_migrations(&db_pool);
} | conditional_block |
mod.rs | use std::sync::Arc;
use crate::AppState;
mod actions;
mod devices;
mod ws;
use actions::*;
use devices::*;
use anyhow::Result;
use warp::Filter;
use self::ws::ws;
pub fn with_state(
app_state: &Arc<AppState>,
) -> impl Filter<Extract = (Arc<AppState>,), Error = std::convert::Infallible> + Clone |
// Example of warp usage: https://github.com/seanmonstar/warp/blob/master/examples/todos.rs
pub fn init_api(app_state: &Arc<AppState>) -> Result<()> {
let api = warp::path("api")
.and(warp::path("v1"))
.and(devices(app_state).or(actions(app_state)));
let ws = ws(app_state);
tokio::spawn(as... | {
let app_state = app_state.clone();
warp::any().map(move || app_state.clone())
} | identifier_body |
mod.rs | use std::sync::Arc;
use crate::AppState;
mod actions;
mod devices;
mod ws;
use actions::*;
use devices::*;
use anyhow::Result;
use warp::Filter;
use self::ws::ws;
pub fn with_state(
app_state: &Arc<AppState>,
) -> impl Filter<Extract = (Arc<AppState>,), Error = std::convert::Infallible> + Clone {
let app_... | (app_state: &Arc<AppState>) -> Result<()> {
let api = warp::path("api")
.and(warp::path("v1"))
.and(devices(app_state).or(actions(app_state)));
let ws = ws(app_state);
tokio::spawn(async move {
warp::serve(ws.or(api)).run(([127, 0, 0, 1], 45289)).await;
});
Ok(())
}
| init_api | identifier_name |
mod.rs | use std::sync::Arc;
use crate::AppState;
mod actions;
mod devices;
mod ws;
use actions::*;
use devices::*;
use anyhow::Result;
use warp::Filter;
use self::ws::ws;
pub fn with_state(
app_state: &Arc<AppState>,
) -> impl Filter<Extract = (Arc<AppState>,), Error = std::convert::Infallible> + Clone {
let app_... | } | random_line_split | |
nrvo.rs | // run-pass
// When the NRVO is applied, the return place (`_0`) gets treated like a normal local. For example,
// its address may be taken and it may be written to indirectly. Ensure that MIRI can handle this.
#![feature(const_mut_refs)]
#[inline(never)] // Try to ensure that MIR optimizations don't optimize this a... |
const fn nrvo() -> [u8; 1024] {
let mut buf = [0; 1024];
init(&mut buf);
buf
}
const BUF: [u8; 1024] = nrvo();
fn main() {
assert_eq!(BUF[33], 3);
assert_eq!(BUF[19], 0);
assert_eq!(BUF[444], 4);
}
| {
buf[33] = 3;
buf[444] = 4;
} | identifier_body |
nrvo.rs | // run-pass
// When the NRVO is applied, the return place (`_0`) gets treated like a normal local. For example,
// its address may be taken and it may be written to indirectly. Ensure that MIRI can handle this.
#![feature(const_mut_refs)]
#[inline(never)] // Try to ensure that MIR optimizations don't optimize this a... | (buf: &mut [u8; 1024]) {
buf[33] = 3;
buf[444] = 4;
}
const fn nrvo() -> [u8; 1024] {
let mut buf = [0; 1024];
init(&mut buf);
buf
}
const BUF: [u8; 1024] = nrvo();
fn main() {
assert_eq!(BUF[33], 3);
assert_eq!(BUF[19], 0);
assert_eq!(BUF[444], 4);
}
| init | identifier_name |
nrvo.rs | // run-pass |
#![feature(const_mut_refs)]
#[inline(never)] // Try to ensure that MIR optimizations don't optimize this away.
const fn init(buf: &mut [u8; 1024]) {
buf[33] = 3;
buf[444] = 4;
}
const fn nrvo() -> [u8; 1024] {
let mut buf = [0; 1024];
init(&mut buf);
buf
}
const BUF: [u8; 1024] = nrvo();
fn mai... |
// When the NRVO is applied, the return place (`_0`) gets treated like a normal local. For example,
// its address may be taken and it may be written to indirectly. Ensure that MIRI can handle this. | random_line_split |
lint-plugin-forbid-cmdline.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 ... | () { } //~ ERROR item is named 'lintme'
#[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint)
pub fn main() {
lintme();
}
| lintme | identifier_name |
lint-plugin-forbid-cmdline.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 ... | //~ ERROR item is named 'lintme'
#[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint)
pub fn main() {
lintme();
}
| { } | identifier_body |
lint-plugin-forbid-cmdline.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 ... |
#[plugin] #[no_link]
extern crate lint_plugin_test;
fn lintme() { } //~ ERROR item is named 'lintme'
#[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint)
pub fn main() {
lintme();
} | // ignore-stage1
// compile-flags: -F test-lint
#![feature(plugin)] | random_line_split |
info_test_case.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::super::*;
use alloc::string::String;
use alloc::vec::Vec;
#[derive(Default)]
pub(super) struct InstrInfoTestCase {
pub(super) line_number: u32,
pub(super) bitness: u32,
pub(super) hex_bytes: String,
pu... | pub(super) stack_pointer_increment: i32,
pub(super) is_privileged: bool,
pub(super) is_stack_instruction: bool,
pub(super) is_save_restore_instruction: bool,
pub(super) is_special: bool,
pub(super) used_registers: Vec<UsedRegister>,
pub(super) used_memory: Vec<UsedMemory>,
pub(super) flow_control: FlowControl,
... | pub(super) rflags_undefined: u32,
pub(super) rflags_written: u32,
pub(super) rflags_cleared: u32,
pub(super) rflags_set: u32, | random_line_split |
info_test_case.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::super::*;
use alloc::string::String;
use alloc::vec::Vec;
#[derive(Default)]
pub(super) struct | {
pub(super) line_number: u32,
pub(super) bitness: u32,
pub(super) hex_bytes: String,
pub(super) code: Code,
pub(super) decoder_options: u32,
pub(super) encoding: EncodingKind,
pub(super) cpuid_features: Vec<CpuidFeature>,
pub(super) rflags_read: u32,
pub(super) rflags_undefined: u32,
pub(super) rflags_writt... | InstrInfoTestCase | identifier_name |
main.rs | extern crate wire;
extern crate ctfcommon;
extern crate rustc_serialize;
extern crate docopt;
use ctfcommon::request::CTFRequest;
use ctfcommon::response::CTFResponse;
use ctfcommon::constants::{SERVER_WRITE_LIMIT, SERVER_READ_LIMIT, PORT, ADDRESS};
use docopt::Docopt;
use wire::SizeLimit;
mod formatting;
static USA... | ";
#[derive(RustcDecodable, Debug)]
struct Args {
flag_p: Option<u16>,
arg_flag_id: String,
arg_flag_number: usize,
arg_username: String,
arg_start: usize,
arg_end: usize,
cmd_claim: bool,
cmd_leaderboard: bool,
}
fn main() {
highscores_request(0, 5, PORT);
let args: Args = Do... | Options:
-p <port> TCP port to connect to (optional). The default port is the right one. | random_line_split |
main.rs | extern crate wire;
extern crate ctfcommon;
extern crate rustc_serialize;
extern crate docopt;
use ctfcommon::request::CTFRequest;
use ctfcommon::response::CTFResponse;
use ctfcommon::constants::{SERVER_WRITE_LIMIT, SERVER_READ_LIMIT, PORT, ADDRESS};
use docopt::Docopt;
use wire::SizeLimit;
mod formatting;
static USA... | (id: usize, flag: String, user: String, port: u16) {
// Create a request to check a flag
// TODO: Get rid of this cloning
let flag_offer = CTFRequest::verify_flag(id, flag, user.clone());
// Print statuses!
if let Some(CTFResponse::FlagVerified(_, verified, taken)) = send(&flag_offer, port) {
... | flag_verify_request | identifier_name |
main.rs | extern crate wire;
extern crate ctfcommon;
extern crate rustc_serialize;
extern crate docopt;
use ctfcommon::request::CTFRequest;
use ctfcommon::response::CTFResponse;
use ctfcommon::constants::{SERVER_WRITE_LIMIT, SERVER_READ_LIMIT, PORT, ADDRESS};
use docopt::Docopt;
use wire::SizeLimit;
mod formatting;
static USA... | i.into_blocking_iter().next()
}
| {
// Control max size of incoming and outgoing messages.
// Values are flipped beacuse we are on the client side.
let read_limit = SizeLimit::Bounded(SERVER_WRITE_LIMIT);
let write_limit = SizeLimit::Bounded(SERVER_READ_LIMIT);
// Try to connect to the flag server...
let (i, mut o) = match wir... | identifier_body |
mod.rs | //! Parsing and interpretation for unoptimized Brainfuck abstract syntax trees.
//!
//! In `bfi` by default, this pass runs before run-length encoding and peephole optimization. To
//! run the unoptimized AST directly and skip all optimization, pass `--ast` flag.
//!
//! In this module, BF programs are represented by t... | } | random_line_split | |
mod.rs | //! Parsing and interpretation for unoptimized Brainfuck abstract syntax trees.
//!
//! In `bfi` by default, this pass runs before run-length encoding and peephole optimization. To
//! run the unoptimized AST directly and skip all optimization, pass `--ast` flag.
//!
//! In this module, BF programs are represented by t... | {
/// A non-loop command.
///
/// # Invariants
///
/// The `Command` cannot be `Begin` or `End`.
Cmd(Command),
/// A loop surrounding a sequence of instructions.
Loop(Box<[Statement]>),
}
| Statement | identifier_name |
overloaded-deref.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
(*(*p).borrow_mut()).x = 3;
(*(*p).borrow_mut()).y += 3;
assert_eq!(*(*p).borrow(), Point {x: 3, y: 5});
let v = Rc::new(RefCell::new(vec!(1, 2, 3)));
(*(*v).borrow_mut())[0] = 3;
(*(*v).borrow_mut())[1] += 3;
assert_eq!(((*(*v).borrow... | random_line_split | |
overloaded-deref.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 ... | () {
assert_eq!(*Rc::new(5), 5);
assert_eq!(***Rc::new(Box::new(Box::new(5))), 5);
assert_eq!(*Rc::new(Point {x: 2, y: 4}), Point {x: 2, y: 4});
let i = Rc::new(RefCell::new(2));
let i_value = *(*i).borrow();
*(*i).borrow_mut() = 5;
assert_eq!((i_value, *(*i).borrow()), (2, 5));
let s ... | main | identifier_name |
bfs.rs | use std::collections::VecDeque;
pub fn | <F, GT: ::graph::GraphTraversal>(g: >, s: usize, mapped_function: &mut Box<F>,marker: &mut ::mark::Marker) where F: FnMut(usize) {
let mut q: VecDeque<usize> = VecDeque::new();
q.push_back(s);
marker.mark(s);
loop {
if let Some(u) = q.pop_front() {
mapped_function(u);
q... | bfs | identifier_name |
bfs.rs | use std::collections::VecDeque;
pub fn bfs<F, GT: ::graph::GraphTraversal>(g: >, s: usize, mapped_function: &mut Box<F>,marker: &mut ::mark::Marker) where F: FnMut(usize) {
let mut q: VecDeque<usize> = VecDeque::new();
q.push_back(s);
marker.mark(s);
loop {
if let Some(u) = q.pop_front() {
... | {
for v in g.sources() {
bfs(g, v, mapped_function, marker);
}
} | identifier_body | |
bfs.rs | use std::collections::VecDeque;
pub fn bfs<F, GT: ::graph::GraphTraversal>(g: >, s: usize, mapped_function: &mut Box<F>,marker: &mut ::mark::Marker) where F: FnMut(usize) {
let mut q: VecDeque<usize> = VecDeque::new();
q.push_back(s);
marker.mark(s);
loop {
if let Some(u) = q.pop_front() {
... | bfs(g, v, mapped_function, marker);
}
} | random_line_split | |
bfs.rs | use std::collections::VecDeque;
pub fn bfs<F, GT: ::graph::GraphTraversal>(g: >, s: usize, mapped_function: &mut Box<F>,marker: &mut ::mark::Marker) where F: FnMut(usize) {
let mut q: VecDeque<usize> = VecDeque::new();
q.push_back(s);
marker.mark(s);
loop {
if let Some(u) = q.pop_front() {
... |
}));
} else {
break;
}
}
}
pub fn full_bfs<F, GT: ::graph::GraphTraversal>(g: >, mapped_function: &mut Box<F>, marker: &mut ::mark::Marker) where F: FnMut(usize) {
for v in g.sources() {
bfs(g, v, mapped_function, marker);
}
}
| {
None
} | conditional_block |
day_1.rs | pub use tdd_kata::map_kata::day_1::Map;
describe! map_tests {
before_each {
let mut map = Map::new();
}
it "should create a new empty map" {
assert_eq!(map.size(), 0);
assert!(map.is_empty()); | }
it "should increase size when put into map" {
let old_size = map.size();
map.put(1, 1);
assert_eq!(map.size(), old_size + 1);
assert!(!map.is_empty());
}
it "should not increase size when put the same key into the map" {
map.put(1, 1);
let old_size = ... | random_line_split | |
wizard.rs | use std::io::Result as IoResult;
use std::process::{Command, Stdio, ChildStdin};
use std::path::Path;
use std::iter::Iterator;
use libudev::{Result as UdevResult, Context, Enumerator};
use common::config::{Config, SetupConfig, PciId};
use common::pci_device::PciDevice;
use driver;
use ask;
use iommu;
use usb;
use vf... | {
Wizard.run(cfg, target, workdir, datadir);
} | identifier_body | |
wizard.rs | use std::io::Result as IoResult;
use std::process::{Command, Stdio, ChildStdin};
use std::path::Path;
use std::iter::Iterator;
use libudev::{Result as UdevResult, Context, Enumerator};
use common::config::{Config, SetupConfig, PciId};
use common::pci_device::PciDevice;
use driver;
use ask;
use iommu;
use usb;
use vf... | () -> UdevResult<Vec<PciId>> {
let udev = Context::new().expect("Failed to create udev context");
let mut iter = Enumerator::new(&udev)?;
iter.match_property("DRIVER", "vfio-pci")?;
Ok(iter.scan_devices()?.map(PciDevice::new).map(|x| x.id).collect())
}
pub fn sudo_write_file<P: AsRef<Path>, F: FnOnce... | get_passthrough_devs | identifier_name |
wizard.rs | use std::io::Result as IoResult;
use std::process::{Command, Stdio, ChildStdin};
use std::path::Path;
use std::iter::Iterator;
use libudev::{Result as UdevResult, Context, Enumerator};
use common::config::{Config, SetupConfig, PciId};
use common::pci_device::PciDevice;
use driver;
use ask;
use iommu;
use usb;
use vf... |
config.save(cfg_path);
if!vfio::setup(&mut config.machine) {
return;
}
config.save(cfg_path);
let passthrough_devs = get_passthrough_devs().expect("Failed to check gpu passthrough with udev");
if passthrough_devs.is_empty() {
if!initramfs::rebui... | {
return;
} | conditional_block |
wizard.rs | use std::io::Result as IoResult;
use std::process::{Command, Stdio, ChildStdin};
use std::path::Path;
use std::iter::Iterator;
use libudev::{Result as UdevResult, Context, Enumerator};
use common::config::{Config, SetupConfig, PciId};
use common::pci_device::PciDevice;
use driver;
use ask;
use iommu;
use usb;
use vf... |
println!("Your VM is going to boot now.");
println!("Just install Windows and shut it down cleanly as soon as that's done so we can continue.");
println!();
println!("Note: Windows probably won't pick up the virtio-scsi storage device right away. You can load the drivers... | config.save(cfg_path); | random_line_split |
value.rs | //! Deserialization of a `Value<T>` type which tracks where it was deserialized
//! from.
//!
//! Often Cargo wants to report semantic error information or other sorts of
//! error information about configuration keys but it also may wish to indicate
//! as an error context where the key was defined as well (to help us... |
}
impl<'de> de::Deserialize<'de> for Definition {
fn deserialize<D>(deserializer: D) -> Result<Definition, D::Error>
where
D: de::Deserializer<'de>,
{
let (discr, value) = <(u32, String)>::deserialize(deserializer)?;
match discr {
0 => Ok(Definition::Path(value.into()))... | {
deserializer.deserialize_identifier(FieldVisitor {
expected: DEFINITION_FIELD,
})?;
Ok(DefinitionKey)
} | identifier_body |
value.rs | //! Deserialization of a `Value<T>` type which tracks where it was deserialized
//! from.
//!
//! Often Cargo wants to report semantic error information or other sorts of
//! error information about configuration keys but it also may wish to indicate
//! as an error context where the key was defined as well (to help us... | D: de::Deserializer<'de>,
{
deserializer.deserialize_identifier(FieldVisitor {
expected: VALUE_FIELD,
})?;
Ok(ValueKey)
}
}
struct DefinitionKey;
impl<'de> de::Deserialize<'de> for DefinitionKey {
fn deserialize<D>(deserializer: D) -> Result<DefinitionKey, D::Er... | fn deserialize<D>(deserializer: D) -> Result<ValueKey, D::Error>
where | random_line_split |
value.rs | //! Deserialization of a `Value<T>` type which tracks where it was deserialized
//! from.
//!
//! Often Cargo wants to report semantic error information or other sorts of
//! error information about configuration keys but it also may wish to indicate
//! as an error context where the key was defined as well (to help us... | (&self, other: &Definition) -> bool {
match (self, other) {
(Definition::Cli, Definition::Environment(_)) => true,
(Definition::Cli, Definition::Path(_)) => true,
(Definition::Environment(_), Definition::Path(_)) => true,
_ => false,
}
}
}
impl Partia... | is_higher_priority | identifier_name |
plane.rs | extern crate tray_rust;
extern crate rand;
extern crate image;
use std::sync::Arc;
use rand::StdRng;
use tray_rust::linalg::{AnimatedTransform, Transform, Point, Vector};
use tray_rust::film::{Colorf, RenderTarget, Camera, ImageSample};
use tray_rust::film::filter::MitchellNetravali;
use tray_rust::geometry::{Rectang... | () {
let width = 800usize;
let height = 600usize;
let filter =
Box::new(MitchellNetravali::new(2.0, 2.0, 0.333333333333333333, 0.333333333333333333));
let rt = RenderTarget::new((width, height), (20, 20), filter);
let transform =
AnimatedTransform::unanimated(&Transform::look_at(&Poi... | main | identifier_name |
plane.rs | extern crate tray_rust;
extern crate rand;
extern crate image;
use std::sync::Arc;
use rand::StdRng;
use tray_rust::linalg::{AnimatedTransform, Transform, Point, Vector};
use tray_rust::film::{Colorf, RenderTarget, Camera, ImageSample};
use tray_rust::film::filter::MitchellNetravali;
use tray_rust::geometry::{Rectang... | let dim = rt.dimensions();
// A block queue is how work is distributed among threads, it's a list of tiles
// of the image that have yet to be rendered. Each thread will pull a block from
// this queue and render it.
let block_queue = BlockQueue::new((dim.0 as u32, dim.1 as u32), (8, 8), (0, 0));
... | random_line_split | |
plane.rs | extern crate tray_rust;
extern crate rand;
extern crate image;
use std::sync::Arc;
use rand::StdRng;
use tray_rust::linalg::{AnimatedTransform, Transform, Point, Vector};
use tray_rust::film::{Colorf, RenderTarget, Camera, ImageSample};
use tray_rust::film::filter::MitchellNetravali;
use tray_rust::geometry::{Rectang... | AnimatedTransform::unanimated(&Transform::translate(&Vector::new(0.0, 2.0, 0.0)));
let instance = Instance::receiver(geometry_lock,
material_lock,
position_transform,
"single_plane".to_string())... | {
let width = 800usize;
let height = 600usize;
let filter =
Box::new(MitchellNetravali::new(2.0, 2.0, 0.333333333333333333, 0.333333333333333333));
let rt = RenderTarget::new((width, height), (20, 20), filter);
let transform =
AnimatedTransform::unanimated(&Transform::look_at(&Point:... | identifier_body |
api_handler.rs | use typeable::Typeable;
use traitobject;
use std::any::TypeId;
use std::mem;
use backend;
use super::{CallInfo};
use json::{JsonValue};
pub trait ApiHandler: Typeable {
fn api_call<'a, 'b>(&'a self, &str, &mut JsonValue, &'b mut (backend::Request + 'b), &mut CallInfo<'a>) -> backend::HandleResult<backend::Respons... | pub type ApiHandlers = Vec<Box<ApiHandler + Send + Sync>>; | random_line_split | |
api_handler.rs | use typeable::Typeable;
use traitobject;
use std::any::TypeId;
use std::mem;
use backend;
use super::{CallInfo};
use json::{JsonValue};
pub trait ApiHandler: Typeable {
fn api_call<'a, 'b>(&'a self, &str, &mut JsonValue, &'b mut (backend::Request + 'b), &mut CallInfo<'a>) -> backend::HandleResult<backend::Respons... |
}
pub type ApiHandlers = Vec<Box<ApiHandler + Send + Sync>>; | {
mem::transmute(traitobject::data(self))
} | identifier_body |
api_handler.rs | use typeable::Typeable;
use traitobject;
use std::any::TypeId;
use std::mem;
use backend;
use super::{CallInfo};
use json::{JsonValue};
pub trait ApiHandler: Typeable {
fn api_call<'a, 'b>(&'a self, &str, &mut JsonValue, &'b mut (backend::Request + 'b), &mut CallInfo<'a>) -> backend::HandleResult<backend::Respons... | <T: ApiHandler>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
unsafe {
Some(self.downcast_mut_unchecked())
}
} else {
None
}
}
/// Returns a mutable reference to the boxed value, blindly assuming it to be of type `T`.
/// If y... | downcast_mut | identifier_name |
api_handler.rs | use typeable::Typeable;
use traitobject;
use std::any::TypeId;
use std::mem;
use backend;
use super::{CallInfo};
use json::{JsonValue};
pub trait ApiHandler: Typeable {
fn api_call<'a, 'b>(&'a self, &str, &mut JsonValue, &'b mut (backend::Request + 'b), &mut CallInfo<'a>) -> backend::HandleResult<backend::Respons... |
}
/// Returns a mutable reference to the boxed value, blindly assuming it to be of type `T`.
/// If you are not *absolutely certain* of `T`, you *must not* call this.
#[inline]
pub unsafe fn downcast_mut_unchecked<T: ApiHandler>
(&mut self) -> &mut T {
... | {
None
} | conditional_block |
foo.rs | #![crate_name = "test"]
#![feature(box_syntax)]
#![feature(rustc_private)]
extern crate rustc_graphviz;
// A simple rust project
extern crate krate2;
extern crate krate2 as krate3;
use rustc_graphviz::RenderOption;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::io::Write;
use sub::sub2 a... | 99 {
Rls699 { fs }
}
fn invalid_tuple_struct_access() {
bar.0;
struct S;
S.0;
}
| ls6 | identifier_name |
foo.rs | #![crate_name = "test"]
#![feature(box_syntax)]
#![feature(rustc_private)]
extern crate rustc_graphviz;
// A simple rust project
extern crate krate2;
extern crate krate2 as krate3;
use rustc_graphviz::RenderOption;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::io::Write;
use sub::sub2 a... | for nofields {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
panic!()
}
fn size_hint(&self) -> (usize, Option<usize>) {
panic!()
}
}
trait Pattern<'a> {
type Searcher;
}
struct CharEqPattern;
impl<'a> Pattern<'a> for CharEqPattern {
type Sear... | r | identifier_body |
foo.rs | #![crate_name = "test"]
#![feature(box_syntax)]
#![feature(rustc_private)]
extern crate rustc_graphviz;
// A simple rust project
extern crate krate2;
extern crate krate2 as krate3;
use rustc_graphviz::RenderOption;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::io::Write;
use sub::sub2 a... |
#[path = "SameDir3.rs"]
pub mod SameDir2;
struct nofields;
#[derive(Clone)]
struct some_fields {
field1: u32,
}
type SF = some_fields;
trait SuperTrait {
fn qux(&self) {
panic!();
}
}
trait SomeTrait: SuperTrait {
fn Method(&self, x: u32) -> u32;
fn prov(&self, x: u32) -> u32 {
... | }
}
pub mod SameDir;
pub mod SubDir; | random_line_split |
id3v1.rs | extern crate byteorder;
use std::io::{self, Read, Write, Seek, SeekFrom};
use num::Bounded;
use std::fmt;
use self::byteorder::{BigEndian, ReadBytesExt};
/// The fields in an ID3v1 tag, including the "1.1" track number field.
#[derive(Copy, Clone)]
#[allow(missing_docs)]
pub enum Fields {
Title,
Artist,
A... | else {
Some(Year {value: year})
}
}
}
impl Bounded for Year {
#![allow(deprecated)]
fn min_value() -> Year {
Year {value: 0}
}
fn max_value() -> Year {
Year {value: 9999}
}
}
/// ID3v1 extended time tags--encoded in the format "mmm:ss", a valid value can be... | {
None
} | conditional_block |
id3v1.rs | extern crate byteorder;
use std::io::{self, Read, Write, Seek, SeekFrom};
use num::Bounded;
use std::fmt;
use self::byteorder::{BigEndian, ReadBytesExt};
/// The fields in an ID3v1 tag, including the "1.1" track number field.
#[derive(Copy, Clone)]
#[allow(missing_docs)]
pub enum Fields {
Title,
Artist,
A... | <W: Write>(&self, writer: &mut W, write_track_number: bool) -> Result<(), io::Error> {
use self::Fields::*;
try!(writer.write(TAG));
try!(write_zero_padded(writer, &*self.title, 0, Title.length()));
try!(write_zero_padded(writer, &*self.artist, 0, Artist.length()));
try!(write_ze... | write | identifier_name |
id3v1.rs | extern crate byteorder;
use std::io::{self, Read, Write, Seek, SeekFrom};
use num::Bounded;
use std::fmt;
use self::byteorder::{BigEndian, ReadBytesExt};
/// The fields in an ID3v1 tag, including the "1.1" track number field.
#[derive(Copy, Clone)]
#[allow(missing_docs)]
pub enum Fields {
Title,
Artist,
A... | }
impl Bounded for Time {
#![allow(deprecated)]
fn min_value() -> Time {
Time {value: 0}
}
fn max_value() -> Time {
Time {value: 60039}
}
}
impl fmt::Display for Time {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:03}:{:02}", self.seconds()/60, se... | } else {
Some(Time {value: seconds})
}
} | random_line_split |
id3v1.rs | extern crate byteorder;
use std::io::{self, Read, Write, Seek, SeekFrom};
use num::Bounded;
use std::fmt;
use self::byteorder::{BigEndian, ReadBytesExt};
/// The fields in an ID3v1 tag, including the "1.1" track number field.
#[derive(Copy, Clone)]
#[allow(missing_docs)]
pub enum Fields {
Title,
Artist,
A... |
impl Tag {
/// Create a new ID3v1 tag with no information.
pub fn new() -> Tag {
Tag {
title: vec![], artist: vec![], album: vec![], year: Year::new(0).unwrap(), comment: vec![], track: 0,
genre: 0, speed: 0, genre_str: vec![], start_time: Time::new(0).unwrap(), end_time: Time:... | {
let start = ::std::cmp::min(offset, data.len());
let actual_len = ::std::cmp::min(offset+len, data.len());
try!(writer.write(&data[start..actual_len]));
for _ in 0..(len-(actual_len-start)) {
try!(writer.write(&[0]));
}
Ok(())
} | identifier_body |
atomic.rs | use byteorder::{ReadBytesExt, LittleEndian};
use super::{Section, Struct, Result, Error, ReadExt, Stream};
use super::{FrameList, Frame, FrameObjectValue, FrameObject};
use super::{GeometryList, Geometry, Extension};
use std::cell::RefCell;
use std::rc::{Rc, Weak};
bitflags! {
/// Specifies the options available ... |
}
impl FrameObject for Rc<Atomic> {
fn to_frame_object(&self) -> FrameObjectValue {
FrameObjectValue::Atomic(self.clone())
}
fn frame_refcell(&self) -> &RefCell<Option<Weak<Frame>>> {
&self.parent
}
}
impl Atomic {
/// Constructs an atomic containing the specified geometry.
p... | { 0x0014 } | identifier_body |
atomic.rs | use byteorder::{ReadBytesExt, LittleEndian};
use super::{Section, Struct, Result, Error, ReadExt, Stream};
use super::{FrameList, Frame, FrameObjectValue, FrameObject};
use super::{GeometryList, Geometry, Extension};
use std::cell::RefCell;
use std::rc::{Rc, Weak};
bitflags! {
/// Specifies the options available ... | (frame: Option<Rc<Frame>>,
flags: AtomicFlags, geometry: Rc<Geometry>)
-> Rc<Atomic> {
let atomic = Rc::new(Atomic::new(flags, geometry));
atomic.set_frame(frame);
atomic
}
/// Gets the frame attached to this Atomic.
pub fn frame(&self) ->... | with_frame | identifier_name |
atomic.rs | use byteorder::{ReadBytesExt, LittleEndian};
use super::{Section, Struct, Result, Error, ReadExt, Stream};
use super::{FrameList, Frame, FrameObjectValue, FrameObject};
use super::{GeometryList, Geometry, Extension};
use std::cell::RefCell;
use std::rc::{Rc, Weak};
bitflags! {
/// Specifies the options available ... |
let (frame_index, geo_index, flags, _) = try!(Struct::read_up(rws, |rws| {
Ok((try!(rws.read_u32::<LittleEndian>()),
try!(rws.read_u32::<LittleEndian>()),
try!(rws.read_u32::<LittleEndian>()),
try!(rws.read_u32::<LittleEndian>()))) // unused
... | /// The previosly read geometry and frames from the same clump object in the stream must
/// be passed to this read procedure.
pub fn read<R: ReadExt>(rws: &mut Stream<R>, framelist: &FrameList, geolist: &GeometryList)
-> Result<Rc<A... | random_line_split |
bin.rs | use super::{RmpWrite};
use crate::encode::{write_marker, ValueWriteError};
use crate::Marker;
/// Encodes and attempts to write the most efficient binary array length implementation to the given
/// write, returning the marker used.
///
/// This function is useful when you want to get full control for writing the data... | {
write_bin_len(wr, data.len() as u32)?;
wr.write_bytes(data)
.map_err(ValueWriteError::InvalidDataWrite)
} | identifier_body | |
bin.rs | use super::{RmpWrite};
use crate::encode::{write_marker, ValueWriteError};
use crate::Marker;
/// Encodes and attempts to write the most efficient binary array length implementation to the given
/// write, returning the marker used.
///
/// This function is useful when you want to get full control for writing the data... | <W: RmpWrite>(wr: &mut W, len: u32) -> Result<Marker, ValueWriteError<W::Error>> {
if len < 256 {
write_marker(&mut *wr, Marker::Bin8)?;
wr.write_data_u8(len as u8)?;
Ok(Marker::Bin8)
} else if len <= u16::MAX as u32 {
write_marker(&mut *wr, Marker::Bin16)?;
wr.write_data... | write_bin_len | identifier_name |
bin.rs | use super::{RmpWrite};
use crate::encode::{write_marker, ValueWriteError};
use crate::Marker;
/// Encodes and attempts to write the most efficient binary array length implementation to the given
/// write, returning the marker used.
///
/// This function is useful when you want to get full control for writing the data... | .map_err(ValueWriteError::InvalidDataWrite)
} | wr.write_bytes(data) | random_line_split |
pwm.rs | // Zinc, the bare metal stack for rust.
// Copyright 2015 Paul Osborne <osbpau@gmail.com>
//
// 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-... | ,
Channel1 => { reg::PWM1().mr[1].set_value(value); },
Channel2 => { reg::PWM1().mr[2].set_value(value); },
Channel3 => { reg::PWM1().mr[3].set_value(value); },
Channel4 => { reg::PWM1().mr2[0].set_value(value); },
Channel5 => { reg::PWM1().mr2[1].set_value(value); },
Channel6 => { r... | { reg::PWM1().mr[0].set_value(value); } | conditional_block |
pwm.rs | // Zinc, the bare metal stack for rust.
// Copyright 2015 Paul Osborne <osbpau@gmail.com>
//
// 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-... | channel: channel,
period_us: period_us, // 20ms is pretty common
pulsewidth_us: 0,
};
pwm.update_period();
pwm.update_pulsewidth();
pwm
}
/// Update the PWM Signal based on the current state
fn update_period(&self) {
// Put the counter into reset and disable the counter
... | {
PWM1Clock.enable();
PWM1Clock.set_divisor(PWM_CLOCK_DIVISOR);
reg::PWM1().pr.set_value(0); // no prescaler
// single PWM mode (reset TC on match 0 for Ch0)
reg::PWM1().mcr.set_pwmmr0r(true);
// enable PWM output on this channel
match channel {
Channel0PeriodReserved => { unsafe { ... | identifier_body |
pwm.rs | // Zinc, the bare metal stack for rust.
// Copyright 2015 Paul Osborne <osbpau@gmail.com>
//
// 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-... | (&self) -> u32 {
self.pulsewidth_us
}
}
/// LPC17xx PWM Register Definitions (User Manual: 24.6)
mod reg {
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(PWM1@0x40018000 = {
/// Interrupt Register. The IR can be written to clear
/// interrupts. The IR can be read to identify which ... | get_pulsewidth_us | identifier_name |
pwm.rs | // Zinc, the bare metal stack for rust.
// Copyright 2015 Paul Osborne <osbpau@gmail.com>
//
// 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-... | self.pulsewidth_us = pulsewidth_us;
self.update_pulsewidth();
}
fn get_pulsewidth_us(&self) -> u32 {
self.pulsewidth_us
}
}
/// LPC17xx PWM Register Definitions (User Manual: 24.6)
mod reg {
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(PWM1@0x40018000 = {
/// Interrupt R... | }
fn set_pulsewidth_us(&mut self, pulsewidth_us: u32) { | random_line_split |
mod.rs | use std::thread::JoinHandle;
use std::sync::mpsc::SyncSender;
use search;
use timer::Timer;
use types::options;
pub use self::mode::Mode;
mod mode;
pub struct State {
pub search_state: Option<search::State>,
pub search_guard: Option<JoinHandle<search::BestMove>>,
pub search_tx: Option<SyncSender<search:... | (&mut self) {
*self = State {
mode: Mode::NewGame,
ucinewgame_support: true,
options: self.options.clone(),
..State::new()
}
}
}
| reset_new_game | identifier_name |
mod.rs | use std::thread::JoinHandle;
use std::sync::mpsc::SyncSender;
| use types::options;
pub use self::mode::Mode;
mod mode;
pub struct State {
pub search_state: Option<search::State>,
pub search_guard: Option<JoinHandle<search::BestMove>>,
pub search_tx: Option<SyncSender<search::Cmd>>,
pub mode: Mode,
pub start_search_time: Option<u64>,
pub start_move_time: ... | use search;
use timer::Timer; | random_line_split |
epoch_fetch.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (&self, hash: H256, engine: Arc<EthEngine>, checker: Arc<StateDependentProof<EthereumMachine>>)
-> Self::Transition
{
self.request(request::Signal {
hash: hash,
engine: engine,
proof_check: checker,
})
}
}
| epoch_transition | identifier_name |
epoch_fetch.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | // GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::{Arc, Weak};
use ethcore::encoded;
use ethcore::engines::{EthEngine, StateDependentProof};
use ethcore::header::Header... | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | random_line_split |
epoch_fetch.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
impl ChainDataFetcher for EpochFetch {
type Error = &'static str;
type Body = BoxFuture<encoded::Block, &'static str>;
type Receipts = BoxFuture<Vec<Receipt>, &'static str>;
type Transition = BoxFuture<Vec<u8>, &'static str>;
fn block_body(&self, header: &Header) -> Self::Body {
self.request(request::Body(... | {
Box::new(match self.sync.read().upgrade() {
Some(sync) => {
let on_demand = &self.on_demand;
let maybe_future = sync.with_context(move |ctx| {
on_demand.request(ctx, req).expect(ALL_VALID_BACKREFS)
});
match maybe_future {
Some(x) => Either::A(x.map_err(|_| "Request canceled")),
N... | identifier_body |
cast-rfc0401.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 ... | assert_eq!(Simple::A as u8, 0);
assert_eq!(Simple::B as u8, 1);
assert_eq!(Valued::H8 as i8, -93);
assert_eq!(Valued::H7 as i8, 67);
assert_eq!(Valued::Z as i8, 0);
assert_eq!(Valued::H8 as u8, 163);
assert_eq!(Valued::H7 as u8, 67);
assert_eq!(Valued::Z as u8, 0);
assert_eq!(Valu... | random_line_split | |
cast-rfc0401.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 ... | identifier_name | ||
lib.rs | extern "C" {
fn call_closure(closure_id: i32, arg1: f64, arg2: f64, arg3: f64) -> f64;
}
#[no_mangle]
pub unsafe extern "C" fn with_closure_example(closure_id: i32, arg1: f64, arg2: f64, arg3: f64) -> f64 {
call_closure(closure_id, arg1, arg2, arg3)
}
static mut DATA: &mut [f64; 1000000] = &mut [0f64; 1000000... | () {
for i in 0..DATA.len() {
DATA[i] = (i + 1) as f64;
}
}
#[no_mangle]
pub unsafe extern "C" fn fold(closure_id: i32, init: f64) -> f64 {
DATA.iter().fold(init, |left, right| call_closure(closure_id, left, *right, 0f64))
}
static ADD_FUNC: fn(f64, &f64) -> f64 = |left: f64, right: &f64| left + ... | init_data | identifier_name |
lib.rs | extern "C" {
fn call_closure(closure_id: i32, arg1: f64, arg2: f64, arg3: f64) -> f64;
}
#[no_mangle]
pub unsafe extern "C" fn with_closure_example(closure_id: i32, arg1: f64, arg2: f64, arg3: f64) -> f64 {
call_closure(closure_id, arg1, arg2, arg3)
}
static mut DATA: &mut [f64; 1000000] = &mut [0f64; 1000000... |
#[no_mangle]
pub unsafe extern "C" fn fold(closure_id: i32, init: f64) -> f64 {
DATA.iter().fold(init, |left, right| call_closure(closure_id, left, *right, 0f64))
}
static ADD_FUNC: fn(f64, &f64) -> f64 = |left: f64, right: &f64| left + *right;
#[no_mangle]
pub unsafe extern "C" fn fold_as_sum_in_rust(init: f6... | {
for i in 0..DATA.len() {
DATA[i] = (i + 1) as f64;
}
} | identifier_body |
log.rs | /* Copyright (C) 2018 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 WARR... | };
let encryption = match tx.etype {
Some(ref x) => format!("{:?}", x),
None => "<none>".to_owned(),
};
jsb.set_string("cname", &cname)?;
jsb.set_string("realm", &realm)?;
jsb.set_string("sname", &sname)?;
jsb.set_string("encryption", &encryption)?;
jsb.set_bool("w... | {
match tx.error_code {
Some(c) => {
jsb.set_string("msg_type", "KRB_ERROR")?;
jsb.set_string("failed_request", &format!("{:?}", tx.msg_type))?;
jsb.set_string("error_code", &format!("{:?}", c))?;
},
None => { jsb.set_string("msg_type", &format!("{:?}",... | identifier_body |
log.rs | /* Copyright (C) 2018 Open Information Security Foundation | * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
*... | *
* 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.
* | random_line_split |
log.rs | /* Copyright (C) 2018 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 WARR... | (jsb: &mut JsonBuilder, tx: &mut KRB5Transaction) -> Result<(), JsonError>
{
match tx.error_code {
Some(c) => {
jsb.set_string("msg_type", "KRB_ERROR")?;
jsb.set_string("failed_request", &format!("{:?}", tx.msg_type))?;
jsb.set_string("error_code", &format!("{:?}", c))?;
... | krb5_log_response | identifier_name |
borrowck-vec-pattern-nesting.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 ... | }
impl<T> Fake for T { }
| { } | identifier_body |
borrowck-vec-pattern-nesting.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 ... | () {}
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } }
impl<T> Fake for T { }
| main | identifier_name |
borrowck-vec-pattern-nesting.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 ... | ] => {
// Note: `_a` is *moved* here, but `b` is borrowing,
// hence illegal.
//
// See comment in middle/borrowck/gather_loans/mod.rs
// in the case covering these sorts of vectors.
}
_ => {}
}
let a = vec[0]; //~ ERROR cannot ... | //~| cannot move out
//~| to prevent move
.. | random_line_split |
log.rs | //! Allocator logging.
//!
//! This allows for detailed logging for `ralloc`.
/// Log to the appropriate source.
///
/// The first argument defines the log level, the rest of the arguments are just `write!`-like
/// formatters.
#[macro_export]
macro_rules! log {
(INTERNAL, $( $x:tt )*) => {
log!(@["INTERNA... | lv >= config::MIN_LOG_LEVEL
}
} | identifier_body | |
log.rs | //! Allocator logging.
//!
//! This allows for detailed logging for `ralloc`.
/// Log to the appropriate source.
///
/// The first argument defines the log level, the rest of the arguments are just `write!`-like
/// formatters.
#[macro_export]
macro_rules! log {
(INTERNAL, $( $x:tt )*) => {
log!(@["INTERNA... | self, _: &mut fmt::Formatter, _: usize) -> fmt::Result {
Ok(())
}
fn after(&self, _: &mut fmt::Formatter) -> fmt::Result {
Ok(())
}
}
impl IntoCursor for () {
type Cursor = ();
fn into_cursor(self) -> () {
()
}
}
///... | (& | identifier_name |
log.rs | //! Allocator logging.
//!
//! This allows for detailed logging for `ralloc`.
/// Log to the appropriate source.
///
/// The first argument defines the log level, the rest of the arguments are just `write!`-like
/// formatters.
#[macro_export]
macro_rules! log {
(INTERNAL, $( $x:tt )*) => {
log!(@["INTERNA... | }
}
}
impl Cursor for () {
fn at(&self, _: &mut fmt::Formatter, _: usize) -> fmt::Result {
Ok(())
}
fn after(&self, _: &mut fmt::Formatter) -> fmt::Result {
Ok(())
}
}
impl IntoCursor for () {
type Cursor = ();
... |
fn into_cursor(self) -> UniCursor {
UniCursor {
pos: self,
is_printed: Cell::new(false), | random_line_split |
log.rs | //! Allocator logging.
//!
//! This allows for detailed logging for `ralloc`.
/// Log to the appropriate source.
///
/// The first argument defines the log level, the rest of the arguments are just `write!`-like
/// formatters.
#[macro_export]
macro_rules! log {
(INTERNAL, $( $x:tt )*) => {
log!(@["INTERNA... | }
self.cur.after(f)?;
Ok(())
}
}
/// Check if this log level is enabled.
#[inline]
pub fn level(lv: u8) -> bool {
lv >= config::MIN_LOG_LEVEL
}
}
| // Non-empty block.
write!(f, "x")?;
}
| conditional_block |
number.rs |
use ::runtime::parse::ExprParseError;
use ::utils::*;
enum NumberCheckState
{
FloatLiteral,
Semicolon,
Trailing,
}
struct NumberCheck<'a>
{
token: &'a String,
valid: bool,
state: NumberCheckState,
}
impl<'a> NumberCheck<'a>
{
fn new(tok: &'a String) -> NumberCheck
{
NumberChe... |
fn is_comment(&self, ch: char) -> bool
{
ch == '#'
}
fn is_delim(&self, ch: char) -> bool
{
ch == ';'
}
fn is_preserved_delim(&self, ch: char) -> bool
{
false
}
fn esc_char(&self) -> char
{
'\\' // dummy. actually no esc sequence.
}
... | {
false // no escape sequences allowed for numbers
} | identifier_body |
number.rs |
use ::runtime::parse::ExprParseError;
use ::utils::*;
enum NumberCheckState
{
FloatLiteral,
Semicolon,
Trailing,
}
struct NumberCheck<'a>
{
token: &'a String,
valid: bool,
state: NumberCheckState,
}
impl<'a> NumberCheck<'a>
{
fn new(tok: &'a String) -> NumberCheck
{
NumberChe... |
Ok(())
}
fn esc_set(&self) -> bool
{
false
}
fn set_esc(&mut self, set: bool)
{
}
fn reset(&mut self)
{
self.valid = true;
self.state = NumberCheckState::FloatLiteral;
}
}
pub struct NumberExpr
{
pub value: f64,
pub recall: bool,
}
... | {
match self.state
{
NumberCheckState::Trailing => {
return Err(SyntaxError::Expected(index, "nothing after value expression".to_string()));
},
_ => (),
};
} | conditional_block |
number.rs | use ::runtime::parse::ExprParseError;
use ::utils::*;
enum NumberCheckState
{
FloatLiteral,
Semicolon,
Trailing,
}
struct NumberCheck<'a>
{
token: &'a String,
valid: bool,
state: NumberCheckState,
}
impl<'a> NumberCheck<'a>
{
fn new(tok: &'a String) -> NumberCheck
{
NumberChec... | value_expr.recall = true;
}
else
{
unreachable!("illegal value recall character after syntax check");
}
},
};
}
Ok(value_expr)
} | random_line_split | |
number.rs |
use ::runtime::parse::ExprParseError;
use ::utils::*;
enum NumberCheckState
{
FloatLiteral,
Semicolon,
Trailing,
}
struct NumberCheck<'a>
{
token: &'a String,
valid: bool,
state: NumberCheckState,
}
impl<'a> NumberCheck<'a>
{
fn new(tok: &'a String) -> NumberCheck
{
NumberChe... | (&self, ch: char) -> bool
{
false // no escape sequences allowed for numbers
}
fn is_comment(&self, ch: char) -> bool
{
ch == '#'
}
fn is_delim(&self, ch: char) -> bool
{
ch == ';'
}
fn is_preserved_delim(&self, ch: char) -> bool
{
false
}
... | is_esc | identifier_name |
build.rs | use crowbook_intl::{Extractor, Localizer};
use std::env;
use std::path::Path;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=lang/fr.po");
// Extract and localize src/lib
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat... | let dest_path = Path::new(&env::var("OUT_DIR").unwrap()).join("localize_macros.rs");
localizer.write_macro_file(dest_path).unwrap();
// Extract and localize src/bin
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src/bin"))
... | .add_lang(
"fr",
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/lang/lib/fr.po")),
)
.unwrap(); | random_line_split |
build.rs | use crowbook_intl::{Extractor, Localizer};
use std::env;
use std::path::Path;
fn main() |
// Extract and localize src/bin
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src/bin"))
.unwrap();
// Uncomment to update crowbook.pot
//extractor.write_pot_file(concat!(env!("CARGO_MANIFEST_DIR"), "/lang/bin/crowbook.pot... | {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=lang/fr.po");
// Extract and localize src/lib
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src/lib"))
.unwrap();
// Uncomment to update ... | identifier_body |
build.rs | use crowbook_intl::{Extractor, Localizer};
use std::env;
use std::path::Path;
fn | () {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=lang/fr.po");
// Extract and localize src/lib
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src/lib"))
.unwrap();
// Uncomment to update... | main | identifier_name |
mod.rs | /* Copyright (C) 2022 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 WARR... | pub mod pgsql; | pub mod logger;
pub mod parser; | random_line_split |
lib.rs | use std::char;
use std::collections::HashMap;
#[derive(PartialEq)]
enum Cell {
Empty,
Mine,
}
fn neighbors(x1: usize, y1: usize, x2: usize, y2: usize) -> bool {
let x1 = x1 as isize;
let x2 = x2 as isize;
let y1 = y1 as isize;
let y2 = y2 as isize;
x1 - 1 == x2 && y1 - 1 == y2 || x1 == x... | (board: &Vec<&str>) -> Vec<String> {
let mut cells: HashMap<(usize, usize), Cell> = HashMap::new();
let height = board.len();
let width = board[0].len();
for (y, row) in board.iter().enumerate() {
for (x, cell) in row.chars().enumerate() {
let c = match cell {
'' => C... | annotate | identifier_name |
lib.rs | use std::char;
use std::collections::HashMap;
#[derive(PartialEq)]
enum Cell {
Empty,
Mine,
}
fn neighbors(x1: usize, y1: usize, x2: usize, y2: usize) -> bool {
let x1 = x1 as isize;
let x2 = x2 as isize; | x1 - 1 == x2 && y1 + 1 == y2 ||
x1 == x2 && y1 + 1 == y2 || x1 + 1 == x2 && y1 + 1 == y2 || x1 - 1 == x2 && y1 == y2 ||
x1 + 1 == x2 && y1 == y2
}
fn calc_value(x: usize, y: usize, cells: &HashMap<(usize, usize), Cell>) -> char {
let mut n = 0;
for (&(cx, cy), cell) in cells.iter() {
if nei... | let y1 = y1 as isize;
let y2 = y2 as isize;
x1 - 1 == x2 && y1 - 1 == y2 || x1 == x2 && y1 - 1 == y2 || x1 + 1 == x2 && y1 - 1 == y2 || | random_line_split |
options.rs | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#![deny(missing_docs)]
use {std::collections::HashMap, std::collections::HashSet, std::hash::Hash, std::hash::Hasher};
/// Options that can be applied to specif... |
}
impl Eq for PathOption {}
impl Hash for PathOption {
fn hash<H: Hasher>(&self, state: &mut H) {
use PathOption::*;
state.write_u32(match self {
TrailingCommas(..) => 1,
CollapseContainersOfOne(..) => 2,
SortArrayItems(..) => 3,
PropertyNameOrder(.... | {
use PathOption::*;
match (self, other) {
(&TrailingCommas(..), &TrailingCommas(..)) => true,
(&CollapseContainersOfOne(..), &CollapseContainersOfOne(..)) => true,
(&SortArrayItems(..), &SortArrayItems(..)) => true,
(&PropertyNameOrder(..), &PropertyNameO... | identifier_body |
options.rs | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#![deny(missing_docs)]
use {std::collections::HashMap, std::collections::HashSet, std::hash::Hash, std::hash::Hasher};
/// Options that can be applied to specif... | fn eq(&self, other: &Self) -> bool {
use PathOption::*;
match (self, other) {
(&TrailingCommas(..), &TrailingCommas(..)) => true,
(&CollapseContainersOfOne(..), &CollapseContainersOfOne(..)) => true,
(&SortArrayItems(..), &SortArrayItems(..)) => true,
... | /// and placed after the sorted properties.
PropertyNameOrder(Vec<&'static str>),
}
impl PartialEq for PathOption { | random_line_split |
options.rs | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#![deny(missing_docs)]
use {std::collections::HashMap, std::collections::HashSet, std::hash::Hash, std::hash::Hasher};
/// Options that can be applied to specif... | () -> Self {
FormatOptions {
indent_by: 4,
trailing_commas: true,
collapse_containers_of_one: false,
sort_array_items: false,
options_by_path: HashMap::new(),
}
}
}
| default | identifier_name |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Lines;
use std::io::prelude::*;
use std::collections::HashMap;
use std::path::Path;
type Grid = HashMap<(usize, usize), bool>;
fn turn_on(g: &mut Grid, i: usize, ... |
fn answer1(lines: &[String]) -> usize {
let mut g = Grid::new();
for line in lines.iter() {
parse_and_run(&mut g, line.as_str());
}
g.values().filter(|i| **i).count()
}
type Grid2 = HashMap<(usize, usize), usize>;
fn on(g: &mut Grid2, i: usize, j: usize) {
let e = g.entry((i, j)).or_inse... | {
let p = Path::new("data/input.txt");
match File::open(&p) {
Err(e) => panic!("Couldn't open {}: {}", p.display(), e.description()),
Ok(f) => BufReader::new(f).lines(),
}
} | identifier_body |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Lines;
use std::io::prelude::*;
use std::collections::HashMap;
use std::path::Path;
type Grid = HashMap<(usize, usize), bool>;
fn turn_on(g: &mut Grid, i: usize, ... | (g: &mut Grid2, i: usize, j: usize) {
let e = g.entry((i, j)).or_insert(0);
*e = e.saturating_add(2);
}
fn pnr(g: &mut Grid2, s: &str) {
let f = if s.starts_with("turn on") {
on
} else if s.starts_with("turn off") {
off
} else {
tog
};
let (i0, j0, i1, j1) = parse_pa... | tog | identifier_name |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Lines;
use std::io::prelude::*;
use std::collections::HashMap;
use std::path::Path;
type Grid = HashMap<(usize, usize), bool>;
fn turn_on(g: &mut Grid, i: usize, ... |
fn toggle(g: &mut Grid, i: usize, j: usize) {
let e = g.entry((i, j)).or_insert(false);
*e =!*e;
}
fn parse_pairs(s: &str) -> (usize, usize, usize, usize) {
lazy_static! {
static ref RE: Regex = Regex::new(
"([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)"
).unwrap();
}
... | random_line_split | |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Lines;
use std::io::prelude::*;
use std::collections::HashMap;
use std::path::Path;
type Grid = HashMap<(usize, usize), bool>;
fn turn_on(g: &mut Grid, i: usize, ... | else {
toggle
};
let (i0, j0, i1, j1) = parse_pairs(s);
for i in i0..i1 + 1 {
for j in j0..j1 + 1 {
f(g, i, j);
}
}
}
#[test]
fn _t() {
let mut g = Grid::new();
parse_and_run(&mut g, "turn on 0,0 through 999,999");
for i in 0..999 {
for j in 0..9... | {
turn_off
} | conditional_block |
random_seed.rs | use chapter2::dungeon::{Dungeon};
use chapter2::genotype::{Genotype};
use chapter2::phenotype::{Seed};
use rand::{Rng, thread_rng};
#[derive(Clone, Debug)]
pub struct RandomSeed {
seed: Seed,
}
impl RandomSeed {
pub fn new(seed: &Seed) -> RandomSeed {
RandomSeed {
seed: seed.clone(),
... |
dungeon.set_tile(i, j, &tile);
}
}
dungeon.clone()
}
}
| {
dungeon.set_occupant(i, j, &occupant);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.