file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
main.rs
extern crate serenity; use serenity::prelude::*; use serenity::model::*; use std::env; // Serenity implements transparent sharding in a way that you do not need to // manually handle separate processes or connections manually. // // Transparent sharding is useful for a shared cache. Instead of having caches // with d...
} fn main() { // Configure the client with your Discord bot token in the environment. let token = env::var("DISCORD_TOKEN") .expect("Expected a token in the environment"); let mut client = Client::new(&token, Handler); // The total number of shards to use. The "current shard number" of a ...
{ println!("{} is connected!", ready.user.name); }
identifier_body
main.rs
extern crate serenity; use serenity::prelude::*; use serenity::model::*; use std::env; // Serenity implements transparent sharding in a way that you do not need to // manually handle separate processes or connections manually. // // Transparent sharding is useful for a shared cache. Instead of having caches // with d...
}
{ println!("Client error: {:?}", why); }
conditional_block
main.rs
extern crate serenity; use serenity::prelude::*; use serenity::model::*; use std::env; // Serenity implements transparent sharding in a way that you do not need to // manually handle separate processes or connections manually. // // Transparent sharding is useful for a shared cache. Instead of having caches // with d...
if msg.content == "!ping" { // The current shard needs to be unlocked so it can be read from, as // multiple threads may otherwise attempt to read from or mutate it // concurrently. { let shard = ctx.shard.lock(); let shard_info = sh...
fn on_message(&self, ctx: Context, msg: Message) {
random_line_split
std-smallintmap.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 args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { ~[~"", ~"100000", ~"100"] } else if args.len() <= 1u { ~[~"", ~"10000", ~"50"] } else { args }; let max = from_str::<uint>(args[1]).unwrap(); let rep = from_str::<uint>(args[2]).unwrap(); ...
main
identifier_name
std-smallintmap.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() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { ~[~"", ~"100000", ~"100"] } else if args.len() <= 1u { ~[~"", ~"10000", ~"50"] } else { args }; let max = from_str::<uint>(args[1]).unwrap(); let rep = from_str::<uint>(args[2]).un...
{ for i in range(min, max) { assert_eq!(*map.get(&i), i + 22u); } }
identifier_body
std-smallintmap.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 max = from_str::<uint>(args[1]).unwrap(); let rep = from_str::<uint>(args[2]).unwrap(); let mut checkf = 0.0; let mut appendf = 0.0; for _ in range(0u, rep) { let mut map = SmallIntMap::new(); let start = extra::time::precise_time_s(); append_sequential(0u, max, &mut ...
{ args }
conditional_block
std-smallintmap.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 ...
append_sequential(0u, max, &mut map); let mid = extra::time::precise_time_s(); check_sequential(0u, max, &map); let end = extra::time::precise_time_s(); checkf += (end - mid) as f64; appendf += (mid - start) as f64; } let maxf = max as f64; println!("insert...
let mut appendf = 0.0; for _ in range(0u, rep) { let mut map = SmallIntMap::new(); let start = extra::time::precise_time_s();
random_line_split
wallet.rs
use indy::IndyError; use indy::wallet; use indy::future::Future; pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#; pub fn create_wallet(config: &str) -> Result<(), IndyError> { wallet::create_wallet(config, DEFAULT_WALL...
{ wallet::close_wallet(wallet_handle).wait() }
identifier_body
wallet.rs
use indy::IndyError; use indy::wallet;
pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#; pub fn create_wallet(config: &str) -> Result<(), IndyError> { wallet::create_wallet(config, DEFAULT_WALLET_CREDENTIALS).wait() } pub fn open_wallet(config: &str) -> Res...
use indy::future::Future;
random_line_split
wallet.rs
use indy::IndyError; use indy::wallet; use indy::future::Future; pub const DEFAULT_WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#; pub fn create_wallet(config: &str) -> Result<(), IndyError> { wallet::create_wallet(config, DEFAULT_WALL...
() -> Result<i32, IndyError> { let wallet_name = format!("default-wallet-name-{}", super::sequence::get_next_id()); let config = format!(r#"{{"id":"{}"}}"#, wallet_name); create_wallet(&config)?; open_wallet(&config) } pub fn close_wallet(wallet_handle: i32) -> Result<(), IndyError> { wallet::clos...
create_and_open_wallet
identifier_name
architecture.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2015, 2017 Panopticon authors * * 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 opti...
(&self) -> usize { match self { &Mode::Real => 32, &Mode::Protected => 16, &Mode::Long => 16, } } pub fn bits(&self) -> usize { match self { &Mode::Real => 16, &Mode::Protected => 32, &Mode::Long => 64, } ...
alt_bits
identifier_name
architecture.rs
/* * Panopticon - A libre disassembler * Copyright (C) 2015, 2017 Panopticon authors * * 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 opti...
let ret = crate::disassembler::read(*cfg, &buf, p).and_then( |(len, mne, mut jmp)| { Ok( Match::<Amd64> { tokens: buf[0..len as usize].to_vec(), mnemonics: vec![mne], jumps: jmp.drain(..).map...
} debug!("disass @ {:#x}: {:?}", p, buf);
random_line_split
uievent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
can_bubble: bool, cancelable: bool, view: Option<JSRef<Window>>, detail: i32) -> Temporary<UIEvent> { let ev = UIEvent::new_uninitialized(window).root(); ev.deref().InitUIEvent(type_, can_bubble, cancelable, view, detail); Temporary::fr...
pub fn new(window: JSRef<Window>, type_: DOMString,
random_line_split
uievent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
{ pub event: Event, view: Cell<Option<JS<Window>>>, detail: Traceable<Cell<i32>> } impl UIEventDerived for Event { fn is_uievent(&self) -> bool { self.type_id == UIEventTypeId } } impl UIEvent { pub fn new_inherited(type_id: EventTypeId) -> UIEvent { UIEvent { even...
UIEvent
identifier_name
uievent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
pub fn new_uninitialized(window: JSRef<Window>) -> Temporary<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId), &Window(window), UIEventBinding::Wrap) } pub fn new(window: JSRef<Window>, type_: DOMString, ...
{ UIEvent { event: Event::new_inherited(type_id), view: Cell::new(None), detail: Traceable::new(Cell::new(0)), } }
identifier_body
regions-steal-closure.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() { let cl_box = { let mut i = 3i; box_it(box || i += 1) //~ ERROR cannot infer }; cl_box.cl.call_mut(()); }
fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> { closure_box {cl: x} }
random_line_split
regions-steal-closure.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> { cl: Box<FnMut() + 'a>, } fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> { closure_box {cl: x} } fn main() { let cl_box = { let mut i = 3i; box_it(box || i += 1) //~ ERROR cannot infer }; cl_box.cl.call_mut(()); }
closure_box
identifier_name
regions-steal-closure.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 cl_box = { let mut i = 3i; box_it(box || i += 1) //~ ERROR cannot infer }; cl_box.cl.call_mut(()); }
identifier_body
options.rs
// The MIT License (MIT) // Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the righ...
() -> Options { Options { stack_size: rt::min_stack(), name: None, } } pub fn stack_size(mut self, size: usize) -> Options { self.stack_size = size; self } pub fn name(mut self, name: Option<String>) -> Options { self.name = name; ...
new
identifier_name
options.rs
// The MIT License (MIT) // Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the righ...
pub name: Option<String>, } impl Options { pub fn new() -> Options { Options { stack_size: rt::min_stack(), name: None, } } pub fn stack_size(mut self, size: usize) -> Options { self.stack_size = size; self } pub fn name(mut self, name: ...
/// Coroutine options pub struct Options { pub stack_size: usize,
random_line_split
map_clone.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_trait_method; use clippy_utils::remove_blocks; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_...
applicability, ); } }
random_line_split
map_clone.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_trait_method; use clippy_utils::remove_blocks; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_...
(cx: &LateContext<'_>, replace: Span, root: Span, copied: bool) { let mut applicability = Applicability::MachineApplicable; if copied { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for copying elements", "consi...
lint
identifier_name
map_clone.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_trait_method; use clippy_utils::remove_blocks; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_...
}
{ span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for cloning elements", "consider calling the dedicated `cloned` method", format!( "{}.cloned()", snippet_with_applicability(cx,...
conditional_block
map_clone.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::is_trait_method; use clippy_utils::remove_blocks; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_copy, is_type_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_...
"you are using an explicit closure for cloning elements", "consider calling the dedicated `cloned` method", format!( "{}.cloned()", snippet_with_applicability(cx, root, "..", &mut applicability) ), applicability, ); ...
{ let mut applicability = Applicability::MachineApplicable; if copied { span_lint_and_sugg( cx, MAP_CLONE, replace, "you are using an explicit closure for copying elements", "consider calling the dedicated `copied` method", format!(...
identifier_body
gamma.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaSmallShape { inv_shape: f64, large_shape: GammaLargeShape } /// Gamma distribution where the shape parameter is larger than 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape ...
random_line_split
gamma.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
) { let gamma = Gamma::new(10., 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in 0..::RAND_BENCH_N { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } #[bench] fn bench_gamma_s...
e_shape(b: &mut Bencher
identifier_name
gamma.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
l Sample<f64> for GammaSmallShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaLargeShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Gamma { fn ind_sample<R: Rng>(&self, rng: &mut R...
.ind_sample(rng) } } imp
identifier_body
get_state_events_for_empty_key.rs
//! [GET /_matrix/client/r0/rooms/{roomId}/state/{eventType}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-rooms-roomid-state-eventtype) use ruma_api::ruma_api; use ruma_events::EventType; use ruma_identifiers::RoomId; use serde_json::value::RawValue as RawJsonValue; ruma_api! { metadata...
response { /// The content of the state event. /// /// To create a `Box<RawJsonValue>`, use `serde_json::value::to_raw_value`. #[ruma_api(body)] pub content: Box<RawJsonValue>, } error: crate::Error }
#[ruma_api(path)] pub event_type: EventType, }
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::path::Path; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use stack_config::StackConfig; use tracing::{even...
else { event!(Level::DEBUG, "System RC configurations loaded"); } if let Some(home) = home_dir { if let Err(e) = load_user(&mut loader, &home) { event!(Level::INFO, home =?home, "Unable to load user configuration, skipped: {:?}", e); } else { event!(Level::DEBUG...
{ event!( Level::INFO, etc_eden_dir = ?etc_eden_dir, "Unable to load system RC configurations, skipped: {:?}", e ); }
conditional_block
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::path::Path; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use stack_config::StackConfig; use tracing::{even...
(loader: &mut EdenFsConfigLoader, etc_dir: &Path) -> Result<()> { let rcs_dir = etc_dir.join("config.d"); let entries = std::fs::read_dir(&rcs_dir) .with_context(|| format!("Unable to read configuration from {:?}", rcs_dir))?; for rc in entries { let rc = match rc { Ok(rc) => rc,...
load_system_rcs
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::path::Path; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use stack_config::StackConfig; use tracing::{even...
continue; } }; let name = rc.file_name(); let name = if let Some(name) = name.to_str() { name } else { continue; }; if name.starts_with('.') ||!name.ends_with(".toml") { continue; } if let E...
event!( Level::INFO, "Unable to read configuration, skipped: {:?}", e );
random_line_split
sectors.rs
use rand::{seq, ChaChaRng, SeedableRng}; use rayon::prelude::*; use std::{ collections::HashMap, sync::atomic::{AtomicBool, Ordering}, time::Instant, usize::MAX, }; use config::GameConfig; use entities::Faction; use entities::Sector; use utils::Point; /// Used for generating sectors. pub struct Sector...
.into_iter() .map(|point| (point, 0)) .collect(); // Run K means until convergence, i.e until no reassignments let mut has_assigned = true; while has_assigned { let wrapped_assigned = AtomicBool::new(false); // Assign to closest centroid...
.cloned() .collect::<Vec<_>>(); // System to cluster_id mapping let mut cluster_map: HashMap<Point, usize> = system_locations
random_line_split
sectors.rs
use rand::{seq, ChaChaRng, SeedableRng}; use rayon::prelude::*; use std::{ collections::HashMap, sync::atomic::{AtomicBool, Ordering}, time::Instant, usize::MAX, }; use config::GameConfig; use entities::Faction; use entities::Sector; use utils::Point; /// Used for generating sectors. pub struct Sector...
(&self, config: &GameConfig, system_locations: Vec<Point>) -> Vec<Sector> { // Measure time for generation. let now = Instant::now(); info!("Simulating expansion for initial sectors..."); let seed: &[_] = &[config.map_seed as u32]; let mut rng: ChaChaRng = ChaChaRng::from_seed(s...
generate
identifier_name
sectors.rs
use rand::{seq, ChaChaRng, SeedableRng}; use rayon::prelude::*; use std::{ collections::HashMap, sync::atomic::{AtomicBool, Ordering}, time::Instant, usize::MAX, }; use config::GameConfig; use entities::Faction; use entities::Sector; use utils::Point; /// Used for generating sectors. pub struct Sector...
/// Split the systems in to a set number of clusters using K-means. pub fn generate(&self, config: &GameConfig, system_locations: Vec<Point>) -> Vec<Sector> { // Measure time for generation. let now = Instant::now(); info!("Simulating expansion for initial sectors..."); let se...
{ SectorGen {} }
identifier_body
sectors.rs
use rand::{seq, ChaChaRng, SeedableRng}; use rayon::prelude::*; use std::{ collections::HashMap, sync::atomic::{AtomicBool, Ordering}, time::Instant, usize::MAX, }; use config::GameConfig; use entities::Faction; use entities::Sector; use utils::Point; /// Used for generating sectors. pub struct Sector...
} *cluster_id = closest_cluster; }); has_assigned = wrapped_assigned.load(Ordering::Relaxed); // Calculate new centroids centroids //.par_iter_mut() .iter_mut() .enumerate() ...
{ wrapped_assigned.store(true, Ordering::Relaxed); closest_cluster = i; closest_distance = distance; }
conditional_block
custom_build.rs
use std::collections::{HashMap, BTreeSet}; use std::fs; use std::io::prelude::*; use std::path::PathBuf; use std::str; use std::sync::{Mutex, Arc}; use core::{PackageId, PackageSet}; use util::{CargoResult, human, Human}; use util::{internal, ChainError, profile, paths}; use util::Freshness; use super::job::Work; use...
to_link.extend(dep_scripts.to_link.iter().cloned()); } } let prev = out.entry(*unit).or_insert(BuildScripts::default()); prev.to_link.extend(to_link); prev.plugins.extend(plugins); return prev } }
{ // Do a quick pre-flight check to see if we've already calculated the // set of dependencies. if out.contains_key(unit) { return &out[unit] } let mut to_link = BTreeSet::new(); let mut plugins = BTreeSet::new(); if !unit.target.is_custom_build() &&...
identifier_body
custom_build.rs
use std::collections::{HashMap, BTreeSet}; use std::fs; use std::io::prelude::*; use std::path::PathBuf; use std::str; use std::sync::{Mutex, Arc}; use core::{PackageId, PackageSet}; use util::{CargoResult, human, Human}; use util::{internal, ChainError, profile, paths}; use util::Freshness; use super::job::Work; use...
let data = match iter.next() { Some(val) => val, None => continue }; // getting the `key=value` part of the line let mut iter = data.splitn(2, '='); let key = iter.next(); let value = iter.next(); let (...
{ // skip this line since it doesn't start with "cargo:" continue; }
conditional_block
custom_build.rs
use std::collections::{HashMap, BTreeSet}; use std::fs; use std::io::prelude::*; use std::path::PathBuf; use std::str; use std::sync::{Mutex, Arc}; use core::{PackageId, PackageSet}; use util::{CargoResult, human, Human}; use util::{internal, ChainError, profile, paths}; use util::Freshness; use super::job::Work; use...
(config: &super::BuildConfig, packages: &PackageSet) -> BuildState { let mut sources = HashMap::new(); for package in packages.iter() { match package.manifest().links() { Some(links) => { sources.insert(links.to_string(), ...
new
identifier_name
custom_build.rs
use std::collections::{HashMap, BTreeSet}; use std::fs; use std::io::prelude::*; use std::path::PathBuf; use std::str; use std::sync::{Mutex, Arc}; use core::{PackageId, PackageSet}; use util::{CargoResult, human, Human}; use util::{internal, ChainError, profile, paths}; use util::Freshness; use super::job::Work; use...
// line started with `cargo:` but didn't match `key=value` _ => bail!("Wrong output in {}: `{}`", whence, line), }; match key { "rustc-flags" => { let (libs, links) = try!( BuildOutput::parse_rustc_flags...
let key = iter.next(); let value = iter.next(); let (key, value) = match (key, value) { (Some(a), Some(b)) => (a, b.trim_right()),
random_line_split
time.rs
//! Utilities for mapping between human-usable time units and BAPS3's //! preferred time units. /// Enum of available time units. /// /// This does not contain every possible time unit anyone may want to use with /// a BAPS3 client, but covers the main possibilities. /// /// Each unit specified in terms of its equival...
{ /// Hours (1 hour = 60 minutes) Hours, /// Minutes (1 minute = 60 seconds). Minutes, /// Seconds (1 second = 1,000 milliseconds). Seconds, /// Milliseconds (1 millisecond = 1,000 microseconds). Milliseconds, /// Microseconds (the BAPS3 base unit). Microseconds } impl TimeUnit...
TimeUnit
identifier_name
time.rs
//! Utilities for mapping between human-usable time units and BAPS3's //! preferred time units. /// Enum of available time units. /// /// This does not contain every possible time unit anyone may want to use with /// a BAPS3 client, but covers the main possibilities. /// /// Each unit specified in terms of its equival...
/// Multiplexes a series of unit flags into a TimeUnit. /// Larger units take precedence. pub fn from_flags(h: bool, m: bool, s: bool, ms: bool) -> TimeUnit { if h { TimeUnit::Hours } else if m { TimeUnit::Minutes } else if s { TimeUnit::Seconds } el...
random_line_split
time.rs
//! Utilities for mapping between human-usable time units and BAPS3's //! preferred time units. /// Enum of available time units. /// /// This does not contain every possible time unit anyone may want to use with /// a BAPS3 client, but covers the main possibilities. /// /// Each unit specified in terms of its equival...
}
{ if h { TimeUnit::Hours } else if m { TimeUnit::Minutes } else if s { TimeUnit::Seconds } else if ms { TimeUnit::Milliseconds } else { TimeUnit::Microseconds } }
identifier_body
time.rs
//! Utilities for mapping between human-usable time units and BAPS3's //! preferred time units. /// Enum of available time units. /// /// This does not contain every possible time unit anyone may want to use with /// a BAPS3 client, but covers the main possibilities. /// /// Each unit specified in terms of its equival...
else { TimeUnit::Microseconds } } }
{ TimeUnit::Milliseconds }
conditional_block
mem.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::encryptionpb::EncryptedContent; use super::metadata::*; use crate::crypter::*; use crate::{AesGcmCrypter, Error, Iv, Result}; /// An in-memory backend, it saves master key in memory. pub(crate) struct MemAesGcmBackend { pub key: Vec<...
let key = &self.key; let iv_value = content .get_metadata() .get(MetadataKey::Iv.as_str()) .ok_or_else(|| { // IV is missing. The metadata of the encrypted content is invalid or corrupted. Error::Other(box_err!("metadata {} not found", Me...
{ // Currently we only support aes256-gcm. A different method could mean the encrypted // content is written by a future version of TiKV, and we don't know how to handle it. // Fail immediately instead of fallback to previous key. return Err(Error::Other(box_err!( ...
conditional_block
mem.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::encryptionpb::EncryptedContent; use super::metadata::*; use crate::crypter::*; use crate::{AesGcmCrypter, Error, Iv, Result}; /// An in-memory backend, it saves master key in memory. pub(crate) struct MemAesGcmBackend { pub key: Vec<...
#[test] fn test_mem_backend_authenticate() { let pt = vec![1u8, 2, 3]; let key = Vec::from_hex("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4") .unwrap(); let backend = MemAesGcmBackend::new(key).unwrap(); let encrypted_content = backend.encrypt_c...
{ // See more http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip let pt = Vec::from_hex("25431587e9ecffc7c37f8d6d52a9bc3310651d46fb0e3bad2726c8f2db653749") .unwrap(); let ct = Vec::from_hex("84e5f23f95648fa247cb28eef53abec947dbf05ac953734618111583840bd980") ...
identifier_body
mem.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::encryptionpb::EncryptedContent; use super::metadata::*; use crate::crypter::*; use crate::{AesGcmCrypter, Error, Iv, Result}; /// An in-memory backend, it saves master key in memory. pub(crate) struct MemAesGcmBackend { pub key: Vec<...
let gcm_tag = AesGcmTag::from(tag.as_slice()); let ciphertext = content.get_content(); let plaintext = AesGcmCrypter::new(key, iv) .decrypt(ciphertext, gcm_tag) .map_err(|e| // Decryption error, likely caused by mismatched tag. It could be the tag is ...
// Tag is missing. The metadata of the encrypted content is invalid or corrupted. Error::Other(box_err!("gcm tag not found")) })?;
random_line_split
mem.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::encryptionpb::EncryptedContent; use super::metadata::*; use crate::crypter::*; use crate::{AesGcmCrypter, Error, Iv, Result}; /// An in-memory backend, it saves master key in memory. pub(crate) struct MemAesGcmBackend { pub key: Vec<...
(&self, plaintext: &[u8], iv: Iv) -> Result<EncryptedContent> { let mut content = EncryptedContent::default(); content.mut_metadata().insert( MetadataKey::Method.as_str().to_owned(), MetadataMethod::Aes256Gcm.as_slice().to_vec(), ); let iv_value = iv.as_slice().to...
encrypt_content
identifier_name
003.rs
#![feature(slicing_syntax)] extern crate test; extern crate time;
use std::os; fn solution() -> u64 { let mut n = 600_851_475_143; for factor in iter::count(3, 2) { while n % factor == 0 { n /= factor; } if factor * factor > n { return n; } else if n == 1 { return factor; } } unreachable!(...
use std::io::stdio; use std::iter;
random_line_split
003.rs
#![feature(slicing_syntax)] extern crate test; extern crate time; use std::io::stdio; use std::iter; use std::os; fn solution() -> u64 { let mut n = 600_851_475_143; for factor in iter::count(3, 2) { while n % factor == 0 { n /= factor; } if factor * factor > n { ...
{ match os::args()[] { [_, ref flag] if flag[] == "-a" => return println!("{}", solution()), _ => {}, } for line in stdio::stdin().lock().lines() { let iters: u64 = line.unwrap()[].trim().parse().unwrap(); let start = time::precise_time_ns(); for _ in range(0, iters...
identifier_body
003.rs
#![feature(slicing_syntax)] extern crate test; extern crate time; use std::io::stdio; use std::iter; use std::os; fn solution() -> u64 { let mut n = 600_851_475_143; for factor in iter::count(3, 2) { while n % factor == 0 { n /= factor; } if factor * factor > n { ...
, } for line in stdio::stdin().lock().lines() { let iters: u64 = line.unwrap()[].trim().parse().unwrap(); let start = time::precise_time_ns(); for _ in range(0, iters) { test::black_box(solution()); } let end = time::precise_time_ns(); println!("{}"...
{}
conditional_block
003.rs
#![feature(slicing_syntax)] extern crate test; extern crate time; use std::io::stdio; use std::iter; use std::os; fn solution() -> u64 { let mut n = 600_851_475_143; for factor in iter::count(3, 2) { while n % factor == 0 { n /= factor; } if factor * factor > n { ...
() { match os::args()[] { [_, ref flag] if flag[] == "-a" => return println!("{}", solution()), _ => {}, } for line in stdio::stdin().lock().lines() { let iters: u64 = line.unwrap()[].trim().parse().unwrap(); let start = time::precise_time_ns(); for _ in range(0, it...
main
identifier_name
bpf_base.rs
use crate::abi::Endian; use crate::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, TargetOptions}; pub fn opts(endian: Endian) -> TargetOptions
..Default::default() } }
{ TargetOptions { allow_asm: true, endian, linker_flavor: LinkerFlavor::BpfLinker, atomic_cas: false, executables: true, dynamic_linking: true, no_builtins: true, panic_strategy: PanicStrategy::Abort, position_independent_executables: true, ...
identifier_body
bpf_base.rs
use crate::abi::Endian; use crate::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, TargetOptions}; pub fn opts(endian: Endian) -> TargetOptions { TargetOptions { allow_asm: true, endian, linker_flavor: LinkerFlavor::BpfLinker, atomic_cas: false, executables: true,
no_builtins: true, panic_strategy: PanicStrategy::Abort, position_independent_executables: true, // Disable MergeFunctions since: // - older kernels don't support bpf-to-bpf calls // - on newer kernels, userspace still needs to relocate before calling // BPF_PRO...
dynamic_linking: true,
random_line_split
bpf_base.rs
use crate::abi::Endian; use crate::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, TargetOptions}; pub fn
(endian: Endian) -> TargetOptions { TargetOptions { allow_asm: true, endian, linker_flavor: LinkerFlavor::BpfLinker, atomic_cas: false, executables: true, dynamic_linking: true, no_builtins: true, panic_strategy: PanicStrategy::Abort, position_...
opts
identifier_name
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
#[macro_use] extern crate libimagstore; extern crate libimagerror; extern crate libimagutil; module_entry_path_mod!("links"); pub mod iter; pub mod linkable; pub mod link; pub mod storecheck;
#[cfg(test)] extern crate env_logger;
random_line_split
types.pre.rs
use std::{fmt, str}; #[derive(Debug)] pub struct Machine<'a> { pub memory: CambridgeArray<'a, u8>, pub output: UTF8Wrapper<'a>, #ifdef PROFILE pub trace: ProfileShim, #endif } pub struct CambridgeArray<'a, T: 'a>(pub &'a [T]); // Cambridge is Oxford's rival pub struct UTF8Wrapper<'a>(pub &'a [u8]); #ifde...
(pub fn() -> Profile); #endif impl<'a, T: fmt::Display> fmt::Debug for CambridgeArray<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "[")); if self.0.len() > 0 { for e in &self.0[..] { try!(write!(f, " {}", e)); } } ...
ProfileShim
identifier_name
types.pre.rs
use std::{fmt, str}; #[derive(Debug)] pub struct Machine<'a> { pub memory: CambridgeArray<'a, u8>, pub output: UTF8Wrapper<'a>, #ifdef PROFILE pub trace: ProfileShim, #endif } pub struct CambridgeArray<'a, T: 'a>(pub &'a [T]); // Cambridge is Oxford's rival pub struct UTF8Wrapper<'a>(pub &'a [u8]); #ifde...
write!(f, " ]") } } impl<'a> fmt::Debug for UTF8Wrapper<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "\n{}", try!(str::from_utf8(self.0).map_err(|_| fmt::Error))) } } #ifdef PROFILE #[derive(Debug, Default)] pub struct Profile { pub instructions: u32, pub ...
{ for e in &self.0[..] { try!(write!(f, " {}", e)); } }
conditional_block
types.pre.rs
use std::{fmt, str}; #[derive(Debug)] pub struct Machine<'a> { pub memory: CambridgeArray<'a, u8>, pub output: UTF8Wrapper<'a>, #ifdef PROFILE pub trace: ProfileShim, #endif } pub struct CambridgeArray<'a, T: 'a>(pub &'a [T]); // Cambridge is Oxford's rival pub struct UTF8Wrapper<'a>(pub &'a [u8]); #ifde...
} #ifdef PROFILE #[derive(Debug, Default)] pub struct Profile { pub instructions: u32, pub increments: u32, pub decrements: u32, pub overflows: u32, pub underflows: u32, pub lefts: u32, pub rights: u32, pub left_grows: u32, pub right_grows: u32, pub ins: u32, pub in_revconvs: u32, pub in_unaries: u32,...
{ write!(f, "\n{}", try!(str::from_utf8(self.0).map_err(|_| fmt::Error))) }
identifier_body
types.pre.rs
use std::{fmt, str}; #[derive(Debug)] pub struct Machine<'a> { pub memory: CambridgeArray<'a, u8>, pub output: UTF8Wrapper<'a>, #ifdef PROFILE pub trace: ProfileShim, #endif }
#ifdef PROFILE pub struct ProfileShim(pub fn() -> Profile); #endif impl<'a, T: fmt::Display> fmt::Debug for CambridgeArray<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "[")); if self.0.len() > 0 { for e in &self.0[..] { try!(write!(f, " ...
pub struct CambridgeArray<'a, T: 'a>(pub &'a [T]); // Cambridge is Oxford's rival pub struct UTF8Wrapper<'a>(pub &'a [u8]);
random_line_split
interface.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
} #[derive(PartialEq, Eq, Debug)] pub enum Token { DoctypeToken(Doctype), TagToken(Tag), CommentToken(StrTendril), CharacterTokens(StrTendril), NullCharacterToken, EOFToken, ParseError(Cow<'static, str>), } // FIXME: rust-lang/rust#22629 unsafe impl Send for Token { } /// Types which can...
{ if (self.kind != other.kind) || (self.name != other.name) { return false; } let mut self_attrs = self.attrs.clone(); let mut other_attrs = other.attrs.clone(); self_attrs.sort(); other_attrs.sort(); self_attrs == other_attrs }
identifier_body
interface.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
(&self, other: &Tag) -> bool { if (self.kind!= other.kind) || (self.name!= other.name) { return false; } let mut self_attrs = self.attrs.clone(); let mut other_attrs = other.attrs.clone(); self_attrs.sort(); other_attrs.sort(); self_attrs == other_at...
equiv_modulo_attr_order
identifier_name
interface.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
None } }
/// The tokenizer will call this after emitting any tag. /// This allows the tree builder to change the tokenizer's state. /// By default no state changes occur. fn query_state_change(&mut self) -> Option<states::State> {
random_line_split
interface.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
let mut self_attrs = self.attrs.clone(); let mut other_attrs = other.attrs.clone(); self_attrs.sort(); other_attrs.sort(); self_attrs == other_attrs } } #[derive(PartialEq, Eq, Debug)] pub enum Token { DoctypeToken(Doctype), TagToken(Tag), CommentToken(StrTend...
{ return false; }
conditional_block
filemanager.rs
use std::path::Path; use crate::channel::*; use crate::threadpool::*; use crossbeam_channel::*; pub enum FileManagerRequests { ReadAll { file: String, sender: Sender<Message>, }, } pub struct ReadAllResult {} pub enum FileManagerRequestsResponses { Ok, ReadAllResult(ReadAllResult), }...
} }); Ok(future) } } impl<'a> Drop for FileManager<'a> { fn drop(&mut self) { if self.epoll > 0 { unsafe { libc::close(self.epoll) }; } } } #[cfg(test)] mod tests { use crate::threadpool::Threadpool; use crossbeam_channel::*; #[t...
} else { panic!("unexpected result")
random_line_split
filemanager.rs
use std::path::Path; use crate::channel::*; use crate::threadpool::*; use crossbeam_channel::*; pub enum FileManagerRequests { ReadAll { file: String, sender: Sender<Message>, }, } pub struct ReadAllResult {} pub enum
{ Ok, ReadAllResult(ReadAllResult), } pub struct FileManager<'a> { epoll: libc::c_int, dispatcher: TypedThreadDispatcher<'a, FileManagerRequests, FileManagerRequestsResponses>, } pub struct TempFile { pub path: std::path::PathBuf, } impl TempFile { pub fn all_equal(path: &str, data: u8) -> s...
FileManagerRequestsResponses
identifier_name
filemanager.rs
use std::path::Path; use crate::channel::*; use crate::threadpool::*; use crossbeam_channel::*; pub enum FileManagerRequests { ReadAll { file: String, sender: Sender<Message>, }, } pub struct ReadAllResult {} pub enum FileManagerRequestsResponses { Ok, ReadAllResult(ReadAllResult), }...
else { panic!("unexpected result") } }); Ok(future) } } impl<'a> Drop for FileManager<'a> { fn drop(&mut self) { if self.epoll > 0 { unsafe { libc::close(self.epoll) }; } } } #[cfg(test)] mod tests { use crate::thread...
{ r }
conditional_block
filemanager.rs
use std::path::Path; use crate::channel::*; use crate::threadpool::*; use crossbeam_channel::*; pub enum FileManagerRequests { ReadAll { file: String, sender: Sender<Message>, }, } pub struct ReadAllResult {} pub enum FileManagerRequestsResponses { Ok, ReadAllResult(ReadAllResult), }...
pub fn random(path: &str, mut size: usize) -> std::io::Result<Self> { use std::io::*; let _ = std::fs::remove_file(&path); let mut file = std::fs::File::create(&path)?; let mut data = vec![0u8; 4 * 1024]; while size > 0 { for v in (4 * 1024).min(0) { ...
{ use std::io::*; let _ = std::fs::remove_file(&path); let mut file = std::fs::File::create(&path)?; let mut data = vec![0u8; 16 * 1024]; for (i, v) in data.iter_mut().enumerate() { *v = f(i); } file.write_all(&data)?; file.sync_all()?; ...
identifier_body
macros.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 ...
=> ( ::syscall::syscall0( ::syscall::nr::$nr) ); ($nr:ident, $a1:expr) => ( ::syscall::syscall1( ::syscall::nr::$nr, $a1 as usize) ); ($nr:ident, $a1:expr, $a2:expr) => ( ::syscall::syscall2( ::syscall::nr::$nr, ...
#[macro_export] macro_rules! syscall { ($nr:ident)
random_line_split
default_impl.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use futures::future::BoxFuture;...
( this: &(impl DagAlgorithm +?Sized), set: NameSet, ) -> Result<NameSet> { let mut to_visit: Vec<VertexName> = { let mut list = Vec::with_capacity(set.count().await?); let mut iter = set.iter().await?; while let Some(next) = iter.next().await { let vertex = next?; ...
first_ancestors
identifier_name
default_impl.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use futures::future::BoxFuture;...
} } let hints = Hints::new_inherit_idmap_dag(set.hints()); let set = NameSet::from_iter(visited.into_iter().map(Ok), hints); this.sort(&set).await } pub(crate) async fn heads(this: &(impl DagAlgorithm +?Sized), set: NameSet) -> Result<NameSet> { Ok(set.clone() - this.parents(set).await?) }...
{ to_visit.push(parent); }
conditional_block
default_impl.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use futures::future::BoxFuture;...
pub(crate) async fn gca_all(this: &(impl DagAlgorithm +?Sized), set: NameSet) -> Result<NameSet> { this.heads_ancestors(this.common_ancestors(set).await?) .await } pub(crate) async fn common_ancestors( this: &(impl DagAlgorithm +?Sized), set: NameSet, ) -> Result<NameSet> { let result = match ...
{ this.gca_all(set) .await? .iter() .await? .next() .await .transpose() }
identifier_body
default_impl.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use futures::future::BoxFuture;...
} async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> { // No need to use such a hint (to avoid infinite recursion). // Pending names should exist in the graph without using remote fetching. Ok(MemNameDag::new()) } } ...
} } Ok(filtered_parents)
random_line_split
mouse.rs
//! Back-end agnostic mouse buttons. use num::{ FromPrimitive, ToPrimitive }; /// Represent a mouse button. #[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq, Eq, Ord, PartialOrd, Hash, Debug)] pub enum MouseButton { /// Unknown mouse button. Unknown, /// Left mouse button. Left, ...
} impl ToPrimitive for MouseButton { fn to_u64(&self) -> Option<u64> { match self { &MouseButton::Unknown => Some(0), &MouseButton::Left => Some(1), &MouseButton::Right => Some(2), &MouseButton::Middle => Some(3), &MouseButton::X1 => Some(4), ...
{ FromPrimitive::from_u64(n as u64) }
identifier_body
mouse.rs
//! Back-end agnostic mouse buttons. use num::{ FromPrimitive, ToPrimitive };
#[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq, Eq, Ord, PartialOrd, Hash, Debug)] pub enum MouseButton { /// Unknown mouse button. Unknown, /// Left mouse button. Left, /// Right mouse button. Right, /// Middle mouse button. Middle, /// Extra mouse button number...
/// Represent a mouse button.
random_line_split
mouse.rs
//! Back-end agnostic mouse buttons. use num::{ FromPrimitive, ToPrimitive }; /// Represent a mouse button. #[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq, Eq, Ord, PartialOrd, Hash, Debug)] pub enum MouseButton { /// Unknown mouse button. Unknown, /// Left mouse button. Left, ...
(&self) -> Option<u64> { match self { &MouseButton::Unknown => Some(0), &MouseButton::Left => Some(1), &MouseButton::Right => Some(2), &MouseButton::Middle => Some(3), &MouseButton::X1 => Some(4), &MouseButton::X2 => Some(5), &M...
to_u64
identifier_name
log.rs
/* Copyright (C) 2021 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...
(tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> { js.open_object("modbus")?; js.set_uint("id", tx.id)?; if let Some(req) = &tx.request { js.open_object("request")?; log_message(&req, js)?; js.close()?; } if let Some(resp) = &tx.response { js....
log
identifier_name
log.rs
/* Copyright (C) 2021 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...
} js.close()?; Ok(()) } fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> { js.set_uint("transaction_id", msg.transaction_id.into())?; js.set_uint("protocol_id", msg.protocol_id.into())?; js.set_uint("unit_id", msg.unit_id.into())?; js.set_uint("function_raw", ms...
if let Some(resp) = &tx.response { js.open_object("response")?; log_message(&resp, js)?; js.close()?;
random_line_split
log.rs
/* Copyright (C) 2021 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...
/// populate a json object with transactional information, for logging fn log(tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> { js.open_object("modbus")?; js.set_uint("id", tx.id)?; if let Some(req) = &tx.request { js.open_object("request")?; log_message(&req, js)?;...
{ log(tx, js).is_ok() }
identifier_body
quiz_error.rs
extern crate diesel; use self::diesel::result::Error as DatabaseError; use std::error; use std::fmt; use std::convert::From; #[derive(Debug)] pub enum QuizError { DatabaseError(DatabaseError), JokerUnavailable, GameAlreadyFinished, NoGameInProgress, GameStillInProgress, StateError, OutOfR...
(err: DatabaseError) -> Self { QuizError::DatabaseError(err) } }
from
identifier_name
quiz_error.rs
extern crate diesel; use self::diesel::result::Error as DatabaseError; use std::error; use std::fmt; use std::convert::From; #[derive(Debug)] pub enum QuizError { DatabaseError(DatabaseError), JokerUnavailable, GameAlreadyFinished, NoGameInProgress, GameStillInProgress, StateError, OutOfR...
write!(f, "Game already finished error: Tried to interact with a game that has already been finished") } QuizError::NoGameInProgress => { write!(f, "No game in progress error: Tried to play without starting a game firs...
random_line_split
quiz_error.rs
extern crate diesel; use self::diesel::result::Error as DatabaseError; use std::error; use std::fmt; use std::convert::From; #[derive(Debug)] pub enum QuizError { DatabaseError(DatabaseError), JokerUnavailable, GameAlreadyFinished, NoGameInProgress, GameStillInProgress, StateError, OutOfR...
QuizError::OutOfResources => { write!(f, "Out of resources error: Answered all possible questions") } } } } impl error::Error for QuizError { fn description(&self) -> &str { match *self { QuizError::DatabaseError(ref err) => err.description()...
{ match *self { QuizError::DatabaseError(ref err) => write!(f, "Database error: {}", err), QuizError::JokerUnavailable => write!(f, "Joker error: Tried to use unavailable Joker"), QuizError::GameAlreadyFinished => { write!(f, "Game alrea...
identifier_body
lib.rs
//! # `peeking_take_while` //! //! Provides the `peeking_take_while` iterator adaptor method. //! //! The `peeking_take_while` method is very similar to `take_while`, but behaves //! differently when used with a borrowed iterator (perhaps returned by //! `Iterator::by_ref`). //! //! `peeking_take_while` peeks at the ne...
//! // or equal to 10. //! //! //...except, when using plain old `take_while` we lost 10! //! assert_eq!(iter_xs.next(), Some(11)); //! //! // However, when using `peeking_take_while` we did not! Great! //! assert_eq!(iter_ys.next(), Some(10)); //! # } //! ``` use std::iter::Peekable; /// The iterator returned by `pe...
//! // And now we will do some other thing with the items that are greater than
random_line_split
lib.rs
//! # `peeking_take_while` //! //! Provides the `peeking_take_while` iterator adaptor method. //! //! The `peeking_take_while` method is very similar to `take_while`, but behaves //! differently when used with a borrowed iterator (perhaps returned by //! `Iterator::by_ref`). //! //! `peeking_take_while` peeks at the ne...
<P>(&'a mut self, predicate: P) -> PeekingTakeWhile<I, P> where P: FnMut(&<Self as Iterator>::Item) -> bool { PeekingTakeWhile { iter: self, predicate: predicate, } } }
peeking_take_while
identifier_name
lib.rs
//! # `peeking_take_while` //! //! Provides the `peeking_take_while` iterator adaptor method. //! //! The `peeking_take_while` method is very similar to `take_while`, but behaves //! differently when used with a borrowed iterator (perhaps returned by //! `Iterator::by_ref`). //! //! `peeking_take_while` peeks at the ne...
} } /// The `Iterator` extension trait that provides the `peeking_take_while` /// method. /// /// See the [module documentation](./index.html) for details. pub trait PeekableExt<'a, I>: Iterator where I: 'a + Iterator { /// The `Iterator` extension trait that provides the `peeking_take_while` /// meth...
{ self.iter.next() }
conditional_block
month.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
let (year, month) = if now.month() == 12 { (now.year() + 1, 1) } else { (now.year(), now.month() + 1) }; NaiveDate::from_ymd(year, month, 1).and_hms(0, 0, 0) }, Some(s) => s?, }; ...
{ let cmd = rt.cli().subcommand().1.unwrap(); // checked in main let filter = { use chrono::offset::Local; use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now(); let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) ...
identifier_body
month.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
(rt: &Runtime) -> Result<()> { let cmd = rt.cli().subcommand().1.unwrap(); // checked in main let filter = { use chrono::offset::Local; use chrono::naive::NaiveDate; use chrono::Datelike; let now = Local::now(); let start = match cmd.value_of("start").map(::chrono::nai...
month
identifier_name
month.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
debug!(" -> tag = {:?}", tag); let start = e.get_start_datetime()?; debug!(" -> start = {:?}", start); let end = e.get_end_datetime()?; debug!(" -> end = {:?}", end); rt.report_touched(e.get_location()) .map_err(Error::from) ...
debug!("Processing {:?}", e.get_location()); let tag = e.get_timetrack_tag()?;
random_line_split
move_.rs
use crate::direction::Direction; /// This structure contains everything needed to do or undo a Sokoban move. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Move { /// Was a crate moved? pub moves_crate: bool, /// Where was the move directed? pub direction: Direction, } impl Mo...
use std::convert::TryFrom; use std::fmt;
random_line_split
move_.rs
use std::convert::TryFrom; use std::fmt; use crate::direction::Direction; /// This structure contains everything needed to do or undo a Sokoban move. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Move { /// Was a crate moved? pub moves_crate: bool, /// Where was the move directed?...
c } } /// Parse a string representation of moves. pub fn parse(s: &str) -> Result<Vec<Move>, char> { s.chars().map(Move::try_from).collect::<Result<Vec<_>, _>>() } impl fmt::Display for Move { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_char()) }...
{ c.make_ascii_uppercase(); }
conditional_block
move_.rs
use std::convert::TryFrom; use std::fmt; use crate::direction::Direction; /// This structure contains everything needed to do or undo a Sokoban move. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Move { /// Was a crate moved? pub moves_crate: bool, /// Where was the move directed?...
(&self) -> char { let mut c = match self.direction { Direction::Left => 'l', Direction::Right => 'r', Direction::Up => 'u', Direction::Down => 'd', }; if self.moves_crate { c.make_ascii_uppercase(); } c } } /// Pars...
to_char
identifier_name
move_.rs
use std::convert::TryFrom; use std::fmt; use crate::direction::Direction; /// This structure contains everything needed to do or undo a Sokoban move. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Move { /// Was a crate moved? pub moves_crate: bool, /// Where was the move directed?...
} impl TryFrom<char> for Move { type Error = char; fn try_from(c: char) -> Result<Move, char> { use crate::Direction::*; let dir = match c { 'l' | 'L' => Left, 'r' | 'R' => Right, 'u' | 'U' => Up, 'd' | 'D' => Down, _ => return Err(c...
{ write!(f, "{}", self.to_char()) }
identifier_body
100_doors.rs
// Implements http://rosettacode.org/wiki/100_doors use std::num::Float; use std::iter::Map; use std::ops::Range; type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>; #[derive(Debug, PartialEq)] enum DoorState { Open, Closed, } // This is an example of returning an iterator, this allows the caller to // choose if ...
{ let doors = calculate_doors().collect::<Vec<DoorState>>(); // test that the doors with index corresponding to // a perfect square are now open for i in 1..11 { assert_eq!(doors[i*i - 1], DoorState::Open); } }
identifier_body
100_doors.rs
// Implements http://rosettacode.org/wiki/100_doors use std::num::Float; use std::iter::Map; use std::ops::Range; type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>; #[derive(Debug, PartialEq)] enum DoorState { Open, Closed, } // This is an example of returning an iterator, this allows the caller to // choose if ...
} (1u32..101).map(door_status as fn(u32) -> DoorState) } #[cfg(not(test))] fn main() { let doors = calculate_doors(); for (i, x) in doors.enumerate() { println!("Door {} is {:?}", i + 1, x); } } #[test] fn solution() { let doors = calculate_doors().collect::<Vec<DoorState>>(); // test that ...
{ DoorState::Closed }
conditional_block
100_doors.rs
// Implements http://rosettacode.org/wiki/100_doors use std::num::Float; use std::iter::Map; use std::ops::Range; type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>; #[derive(Debug, PartialEq)] enum DoorState { Open, Closed, } // This is an example of returning an iterator, this allows the caller to // choose if ...
() -> DoorIter { fn door_status(door_number: u32) -> DoorState { let x = (door_number as f64).sqrt(); if x == x.round() { DoorState::Open } else { DoorState::Closed } } (1u32..101).map(door_status as fn(u32) -> DoorState) } #[cfg(not(test))] fn main() { let doors = calculate_doors(); ...
calculate_doors
identifier_name
100_doors.rs
// Implements http://rosettacode.org/wiki/100_doors
#[derive(Debug, PartialEq)] enum DoorState { Open, Closed, } // This is an example of returning an iterator, this allows the caller to // choose if they want to allocate or just process as a stream. fn calculate_doors() -> DoorIter { fn door_status(door_number: u32) -> DoorState { let x = (door_number as ...
use std::num::Float; use std::iter::Map; use std::ops::Range; type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>;
random_line_split
attr-stmt-expr.rs
// Copyright 2018 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 ...
(string: &'static str) { // macros are handled a bit differently #[expect_print_expr] //~^ ERROR attributes on expressions are experimental //~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable println!("{}", string) } fn main() { #[expect_let] let string = "Hell...
print_str
identifier_name
attr-stmt-expr.rs
// Copyright 2018 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() { #[expect_let] let string = "Hello, world!"; #[expect_print_stmt] println!("{}", string); #[expect_expr] //~^ ERROR attributes on expressions are experimental //~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable print_str("string") }
#[expect_print_expr] //~^ ERROR attributes on expressions are experimental //~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable println!("{}", string)
random_line_split
attr-stmt-expr.rs
// Copyright 2018 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 ...
{ #[expect_let] let string = "Hello, world!"; #[expect_print_stmt] println!("{}", string); #[expect_expr] //~^ ERROR attributes on expressions are experimental //~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable print_str("string") }
identifier_body
buttons-input.rs
/* * Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy,...
, // To be listened to by the user. DataAvailable(_) | DataCleared => (), LeftChanged(text) => self.model.left_text = text, RightChanged(text) => self.model.right_text = text, Quit => gtk::main_quit(), } } view! { #[name="window"] ...
{ self.model.text = format!("{}{}", self.model.left_text, self.model.right_text); self.model.relm.stream().emit(DataAvailable(self.model.text.clone())); }
conditional_block
buttons-input.rs
/* * Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy,...
() { let (component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let cancel_button = &widgets.cancel_button; let concat_button = &widgets.concat_button; let label = &widgets.label; let left_entry = &widgets.left_entry; let right_entry = &widgets.r...
label_change
identifier_name