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
circuit.rs
use ff::{Field, PrimeField, PrimeFieldRepr, BitIterator}; use bellman::{Circuit, ConstraintSystem, SynthesisError}; use zcash_primitives::jubjub::{FixedGenerators, JubjubEngine, edwards, PrimeOrder, JubjubParams}; use zcash_primitives::constants; use zcash_primitives::primitives::{PaymentAddress, ProofGenerationKey...
use zcash_primitives::pedersen_hash; use zcash_primitives::jubjub::{JubjubBls12, fs, edwards,}; use rand_core::{RngCore, SeedableRng,}; use rand_xorshift::XorShiftRng; let params = &JubjubBls12::new(); let rng = &mut XorShiftRng::from_seed([ 0x58, 0x62, 0xbe, 0x3d, 0x76, 0x3d, 0x31, 0x...
#[test] fn test_ring() { use bellman::gadgets::test::TestConstraintSystem; use pairing::bls12_381::{Bls12, Fr,};
random_line_split
cli.rs
#[macro_use] extern crate bma_benchmark; #[macro_use] extern crate prettytable; use clap::Clap; use log::info; use num_format::{Locale, ToFormattedString}; use prettytable::Table; use rand::prelude::*; use std::collections::BTreeMap; use std::sync::{atomic, Arc}; use std::time::{Duration, Instant}; use tokio::signal::u...
if let Some(ref msg) = opts.message { let topic = opts.topic.expect(ERR_TOPIC_NOT_SPECIFIED); if let Some(message_size) = msg.strip_prefix("==") { let mut m = Vec::new(); let size = byte_unit::Byte::from_str(&message_size) .unwrap() ...
let mut client = client::Client::connect(&config).await.unwrap();
random_line_split
cli.rs
#[macro_use] extern crate bma_benchmark; #[macro_use] extern crate prettytable; use clap::Clap; use log::info; use num_format::{Locale, ToFormattedString}; use prettytable::Table; use rand::prelude::*; use std::collections::BTreeMap; use std::sync::{atomic, Arc}; use std::time::{Duration, Instant}; use tokio::signal::u...
(topic: Option<&String>) -> Vec<String> { topic .expect(ERR_TOPIC_NOT_SPECIFIED) .split(',') .into_iter() .map(ToOwned::to_owned) .collect::<Vec<String>>() } #[tokio::main(worker_threads = 1)] async fn main() { let opts = Opts::parse(); env_logger::Builder::new() ....
parse_topics
identifier_name
cli.rs
#[macro_use] extern crate bma_benchmark; #[macro_use] extern crate prettytable; use clap::Clap; use log::info; use num_format::{Locale, ToFormattedString}; use prettytable::Table; use rand::prelude::*; use std::collections::BTreeMap; use std::sync::{atomic, Arc}; use std::time::{Duration, Instant}; use tokio::signal::u...
.set_queue_size(queue_size) .set_timeout(Duration::from_secs_f64(opts.timeout)) .set_tls(opts.tls) .set_tls_ca(tls_ca) .build(); if opts.benchmark { benchmark( &config, opts.benchmark_workers, opts.benchmark_iterations, opts....
{ let opts = Opts::parse(); env_logger::Builder::new() .target(env_logger::Target::Stdout) .filter_level(if opts.benchmark || opts.top { log::LevelFilter::Info } else { log::LevelFilter::Trace }) .init(); let queue_size = if opts.benchmark { 25...
identifier_body
cli.rs
#[macro_use] extern crate bma_benchmark; #[macro_use] extern crate prettytable; use clap::Clap; use log::info; use num_format::{Locale, ToFormattedString}; use prettytable::Table; use rand::prelude::*; use std::collections::BTreeMap; use std::sync::{atomic, Arc}; use std::time::{Duration, Instant}; use tokio::signal::u...
; assert!(client.is_connected()); let bi: u32 = rng.gen(); workers.push(Arc::new(BenchmarkWorker::new( format!("{}/{}", bi, i), client, r_client, data_channel, ))); } let mut futures = Vec::new(); staged_benchmark_start!("subscr...
{ (client.take_data_channel().unwrap(), None) }
conditional_block
queueing_honey_badger.rs
#![deny(unused_must_use)] //! Network tests for Queueing Honey Badger. use std::collections::BTreeSet; use std::sync::Arc; use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan}; use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger}; use hbbft::sender_queue::{Message, SenderQueu...
(node_info: NewNodeInfo<SQ>, seed: TestRngSeed) -> (SQ, Step<QHB>) { let mut rng: TestRng = TestRng::from_seed(seed); let peer_ids = node_info.netinfo.other_ids().cloned(); let netinfo = node_info.netinfo.clone(); let dhb = DynamicHoneyBadger::builder().build(netinfo, node_info.secret_key, node_...
new_queueing_hb
identifier_name
queueing_honey_badger.rs
#![deny(unused_must_use)] //! Network tests for Queueing Honey Badger. use std::collections::BTreeSet; use std::sync::Arc; use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan}; use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger}; use hbbft::sender_queue::{Message, SenderQueu...
info!( "{:?} has finished waiting for node removal; still waiting: {:?}", stepped_id, awaiting_removal ); if awaiting_removal.is_empty() { info!("Removing first correct node from the test network"); saved_first_correct ...
random_line_split
queueing_honey_badger.rs
#![deny(unused_must_use)] //! Network tests for Queueing Honey Badger. use std::collections::BTreeSet; use std::sync::Arc; use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan}; use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger}; use hbbft::sender_queue::{Message, SenderQueu...
fn do_test_queueing_honey_badger_first_delivery_silent(seed: TestRngSeed) { test_queueing_honey_badger_different_sizes(NodeOrderAdversary::new, 30, seed); }
{ test_queueing_honey_badger_different_sizes(ReorderingAdversary::new, 30, seed); }
identifier_body
queueing_honey_badger.rs
#![deny(unused_must_use)] //! Network tests for Queueing Honey Badger. use std::collections::BTreeSet; use std::sync::Arc; use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan}; use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger}; use hbbft::sender_queue::{Message, SenderQueu...
stepped_id, awaiting_addition ); if awaiting_addition.is_empty() &&!rejoined_first_correct { let node = saved_first_correct .take() .expect("first correct node wasn't saved"); let st...
{ // If the stepped node started voting to add the first correct node back, // take a note of that and rejoin it. if let Some(join_plan) = net.get(stepped_id) .unwrap() .outputs() .iter() ...
conditional_block
lru_cache.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) { unsafe { let _: ~LruEntry<K, V> = cast::transmute(self.head); let _: ~LruEntry<K, V> = cast::transmute(self.tail); } } } #[cfg(test)] mod tests { use super::LruCache; fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) { assert!(opt.is_some()); ...
drop
identifier_name
lru_cache.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 ...
unsafe { cur = (*cur).next; match (*cur).key { // should never print nil None => try!(write!(f.buf, "nil")), Some(ref k) => try!(write!(f.buf, "{}", *k)), } } try!(write!(f.bu...
{ try!(write!(f.buf, ", ")) }
conditional_block
lru_cache.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 ...
write!(f.buf, r"\}") } } impl<K: Hash + TotalEq, V> Container for LruCache<K, V> { /// Return the number of key-value pairs in the cache. fn len(&self) -> uint { self.map.len() } } impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> { /// Clear the cache of all key-value pairs. ...
random_line_split
lru_cache.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 ...
#[inline] fn detach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*(*node).prev).next = (*node).next; (*(*node).next).prev = (*node).prev; } } #[inline] fn attach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*node).next = (*self...
{ if self.len() > 0 { let lru = unsafe { (*self.tail).prev }; self.detach(lru); unsafe { match (*lru).key { None => (), Some(ref k) => { self.map.pop(&KeyRef{k: k}); } } } } }
identifier_body
fetch_places.rs
use crate::models::{Coord, Place}; use crate::DbOpt; use diesel; use diesel::prelude::*; use diesel::result::{DatabaseErrorKind, Error as DieselError}; use log::{debug, info, warn}; use reqwest::{self, Client, Response}; use serde_json::Value; use slug::slugify; use structopt::StructOpt; #[derive(StructOpt)] #[structo...
Some("station") => Some(18), _ => None, }) .or_else(|| match tag_str(tags, "amenity") { Some("bus_station") => Some(16), Some("exhibition_center") => Some(20), Some("kindergarten") => Some(15), Some("p...
Some("pedestrian") => Some(15), // torg Some("rest_area") => Some(16), _ => None, }) .or_else(|| match tag_str(tags, "public_transport") {
random_line_split
fetch_places.rs
use crate::models::{Coord, Place}; use crate::DbOpt; use diesel; use diesel::prelude::*; use diesel::result::{DatabaseErrorKind, Error as DieselError}; use log::{debug, info, warn}; use reqwest::{self, Client, Response}; use serde_json::Value; use slug::slugify; use structopt::StructOpt; #[derive(StructOpt)] #[structo...
Some("attraction") => Some(16), Some("theme_park") | Some("zoo") => Some(14), _ => None, }) .or_else(|| match tag_str(tags, "boundary") { Some("national_park") => Some(14), Some("historic") => Some(7), // Seems to be ...
{ if let Some(tags) = obj.get("tags") { let name = tags .get("name:sv") //.or_else(|| tags.get("name:en")) .or_else(|| tags.get("name")) .and_then(Value::as_str); let level = tags .get("admin_level") .and_then(Value::as_str) ...
identifier_body
fetch_places.rs
use crate::models::{Coord, Place}; use crate::DbOpt; use diesel; use diesel::prelude::*; use diesel::result::{DatabaseErrorKind, Error as DieselError}; use log::{debug, info, warn}; use reqwest::{self, Client, Response}; use serde_json::Value; use slug::slugify; use structopt::StructOpt; #[derive(StructOpt)] #[structo...
<'a>(tags: &'a Value, name: &str) -> Option<&'a str> { tags.get(name).and_then(Value::as_str) } fn get_or_create_place( c: &PgConnection, t_osm_id: i64, name: &str, level: i16, ) -> Result<Place, diesel::result::Error> { use crate::schema::places::dsl::*; places .filter( ...
tag_str
identifier_name
inbound.rs
//! The inbound thread. //! //! This module handles all the inbound SWIM messages. use super::AckSender; use crate::{member::Health, server::{outbound, Server}, swim::{Ack, Ping, PingReq, Swim, Swim...
(server: &Server, socket: &UdpSocket, tx_outbound: &AckSender, addr: SocketAddr, mut msg: Ack) { trace!("Ack from {}@{}", msg.from.id, addr); if msg.forward_to.is_some() && *server.member_id!= msg.forward...
process_ack_mlw_smw_rhw
identifier_name
inbound.rs
//! The inbound thread. //! //! This module handles all the inbound SWIM messages. use super::AckSender; use crate::{member::Health, server::{outbound, Server}, swim::{Ack, Ping, PingReq, Swim, Swim...
match socket.recv_from(&mut recv_buffer[..]) { Ok((length, addr)) => { let swim_payload = match server.unwrap_wire(&recv_buffer[0..length]) { Ok(swim_payload) => swim_payload, Err(e) => { // NOTE: In the future, we mig...
{ thread::sleep(Duration::from_millis(100)); continue; }
conditional_block
inbound.rs
//! The inbound thread. //! //! This module handles all the inbound SWIM messages. use super::AckSender; use crate::{member::Health, server::{outbound, Server}, swim::{Ack, Ping, PingReq, Swim, Swim...
addr: SocketAddr, mut msg: Ack) { trace!("Ack from {}@{}", msg.from.id, addr); if msg.forward_to.is_some() && *server.member_id!= msg.forward_to.as_ref().unwrap().id { let (forward_to_addr, from_addr) = { let forward_to = msg.forward_to.a...
fn process_ack_mlw_smw_rhw(server: &Server, socket: &UdpSocket, tx_outbound: &AckSender,
random_line_split
inbound.rs
//! The inbound thread. //! //! This module handles all the inbound SWIM messages. use super::AckSender; use crate::{member::Health, server::{outbound, Server}, swim::{Ack, Ping, PingReq, Swim, Swim...
{ outbound::ack_mlr_smr_rhw(server, socket, &msg.from, addr, msg.forward_to); // Populate the member for this sender with its remote address msg.from.address = addr.ip().to_string(); trace!("Ping from {}@{}", msg.from.id, addr); if msg.from.departed { server.insert_member_mlw_rhw(msg.from, H...
identifier_body
compressor_params.rs
use super::*; use crate::{BasisTextureFormat, UserData}; use basis_universal_sys as sys; pub use basis_universal_sys::ColorU8; /// The color space the image to be compressed is encoded in. Using the correct color space will #[derive(Debug, Copy, Clone)] pub enum ColorSpace { /// Used for normal maps or other "data...
// The default options that are applied when creating a new compressor or calling reset() on it fn set_default_options(&mut self) { // Set a default quality level. Leaving this unset results in undefined behavior, so we set // it to a working value by default self.set_etc1s_quality_lev...
{ unsafe { sys::compressor_params_clear(self.0); self.set_default_options(); self.clear_source_image_list(); } }
identifier_body
compressor_params.rs
use super::*; use crate::{BasisTextureFormat, UserData}; use basis_universal_sys as sys; pub use basis_universal_sys::ColorU8; /// The color space the image to be compressed is encoded in. Using the correct color space will #[derive(Debug, Copy, Clone)] pub enum ColorSpace { /// Used for normal maps or other "data...
( &mut self, print_status_to_stdout: bool, ) { unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) } } /// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN) /// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALIT...
set_print_status_to_stdout
identifier_name
compressor_params.rs
use super::*; use crate::{BasisTextureFormat, UserData}; use basis_universal_sys as sys; pub use basis_universal_sys::ColorU8; /// The color space the image to be compressed is encoded in. Using the correct color space will #[derive(Debug, Copy, Clone)] pub enum ColorSpace { /// Used for normal maps or other "data...
} /// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN) /// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALITY_MAX). pub fn set_etc1s_quality_level( &mut self, quality_level: u32, ) { assert!(quality_level >= crate::ETC1S_QUALITY_MIN); ...
print_status_to_stdout: bool, ) { unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) }
random_line_split
manual_map.rs
use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF}; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::higher::IfLetOrMatch; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable}; use ...
f(cx, pat, 0, ctxt) } // Checks for an expression wrapped by the `Some` constructor. Returns the contained expression. fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> { // TODO: Allow more complex expressions. match expr.kind { ExprKi...
{ match pat.kind { PatKind::Wild => Some(OptionPat::Wild), PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt), PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None), PatKind::TupleStruct(ref qpath, [pattern], _) ...
identifier_body
manual_map.rs
use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF}; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::higher::IfLetOrMatch; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable}; use ...
(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> { match pat.kind { PatKind::Wild => Some(OptionPat::Wild), PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt), PatKind::Path(ref qpath) if is_lang_ctor(cx, qpat...
f
identifier_name
manual_map.rs
use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF}; use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::higher::IfLetOrMatch; use clippy_utils::source::{snippet_with_applicability, snippet_with_context}; use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable}; use ...
use rustc_hir::{ def::Res, Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{sym, SyntaxConte...
}; use rustc_ast::util::parser::PREC_POSTFIX; use rustc_errors::Applicability; use rustc_hir::LangItem::{OptionNone, OptionSome};
random_line_split
util.rs
use std::path::{Path,PathBuf}; use std::process::{Command,Stdio}; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::os::unix::fs as unixfs; use std::env; use std::fs::{self, File, DirEntry}; use std::ffi::CString; use std::io::{self, Seek, Read, BufReader, SeekFrom}; use ...
} Ok(()) } pub fn chown_tree(base: &Path, chown_to: (u32,u32), include_base: bool) -> Result<()> { for entry in WalkDir::new(base) { let entry = entry.map_err(|e| format_err!("Error reading directory entry: {}", e))?; if entry.path()!= base || include_base { chown(entry.path(),...
{ copy_path(path, &to, chown_to) .map_err(context!("failed to copy {:?} to {:?}", path, to))?; }
conditional_block
util.rs
use std::path::{Path,PathBuf}; use std::process::{Command,Stdio}; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::os::unix::fs as unixfs; use std::env; use std::fs::{self, File, DirEntry}; use std::ffi::CString; use std::io::{self, Seek, Read, BufReader, SeekFrom}; use ...
<P: AsRef<Path>>(path: P) -> Result<()> { let path = path.as_ref(); cmd!("/usr/bin/xz", "-d {}", path.display()) .map_err(context!("failed to decompress {:?}", path)) } pub fn mount<P: AsRef<Path>>(source: impl AsRef<str>, target: P, options: Option<&str>) -> Result<()> { let source = source.as_ref(...
xz_decompress
identifier_name
util.rs
use std::path::{Path,PathBuf}; use std::process::{Command,Stdio}; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::os::unix::fs as unixfs; use std::env; use std::fs::{self, File, DirEntry}; use std::ffi::CString; use std::io::{self, Seek, Read, BufReader, SeekFrom}; use ...
} pub fn copy_tree(from_base: &Path, to_base: &Path) -> Result<()> { _copy_tree(from_base, to_base, None) } pub fn copy_tree_with_chown(from_base: &Path, to_base: &Path, chown_to: (u32,u32)) -> Result<()> { _copy_tree(from_base, to_base, Some(chown_to)) } fn _copy_tree(from_base: &Path, to_base: &Path, cho...
{ if to.exists() { bail!("destination path {} already exists which is not expected", to.display()); } let meta = from.metadata() .map_err(context!("failed to read metadata from source file {:?}", from))?; if from.is_dir() { util::create_dir(to)?; } else { util::copy...
identifier_body
util.rs
use std::path::{Path,PathBuf}; use std::process::{Command,Stdio}; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::os::unix::fs as unixfs; use std::env; use std::fs::{self, File, DirEntry}; use std::ffi::CString; use std::io::{self, Seek, Read, BufReader, SeekFrom}; use ...
is_ascii(c) && (c.is_alphanumeric() || c == '-') } fn is_ascii(c: char) -> bool { c as u32 <= 0x7F } pub fn is_first_char_alphabetic(s: &str) -> bool { if let Some(c) = s.chars().next() { return is_ascii(c) && c.is_alphabetic() } false } fn search_path(filename: &str) -> Result<PathBuf> {...
fn is_alphanum_or_dash(c: char) -> bool {
random_line_split
lib.rs
//! A proportional-integral-derivative (PID) controller library. //! //! See [Pid] for the adjustable controller itself, as well as [ControlOutput] for the outputs and weights which you can use after setting up your controller. Follow the complete example below to setup your first controller! //! //! # Example //! //! ...
let mut pid_i32 = Pid::new(10i32, 100); pid_i32.p(0, 100).i(0, 100).d(0, 100); for _ in 0..5 { assert_eq!( pid_i32.next_control_output(0).output, pid_i8.next_control_output(0i8).output as i32 ); } } /// See if the controll...
fn signed_integers_zeros() { let mut pid_i8 = Pid::new(10i8, 100); pid_i8.p(0, 100).i(0, 100).d(0, 100);
random_line_split
lib.rs
//! A proportional-integral-derivative (PID) controller library. //! //! See [Pid] for the adjustable controller itself, as well as [ControlOutput] for the outputs and weights which you can use after setting up your controller. Follow the complete example below to setup your first controller! //! //! # Example //! //! ...
(&mut self, setpoint: impl Into<T>) -> &mut Self { self.setpoint = setpoint.into(); self } /// Given a new measurement, calculates the next [control output](ControlOutput). /// /// # Panics /// /// - If a setpoint has not been set via `update_setpoint()`. pub fn next_control...
setpoint
identifier_name
mod.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. //! This module contains the actions that will drive a raft state machine. //! //! # Raft Ready //! //! Every messages or ticks may have side affect. Handling all those side //! affect immediately is not efficient. Instead, tikv uses `Ready` to batch u...
/// Callback for fetching logs asynchronously. pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) { let FetchedLogs { context, logs } = fetched_logs; let low = logs.low; if!self.is_leader() { self.entry_storage_mut().clean_async_fetch_res(low); return;...
{ self.raft_group_mut().tick() }
identifier_body
mod.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. //! This module contains the actions that will drive a raft state machine. //! //! # Raft Ready //! //! Every messages or ticks may have side affect. Handling all those side //! affect immediately is not efficient. Instead, tikv uses `Ready` to batch u...
_take_committed_entries: Vec<raft::prelude::Entry>, ) { unimplemented!() } /// Processing the ready of raft. A detail description of how it's handled /// can be found at https://docs.rs/raft/latest/raft/#processing-the-ready-state. /// /// It's should be called at the end of eve...
random_line_split
mod.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. //! This module contains the actions that will drive a raft state machine. //! //! # Raft Ready //! //! Every messages or ticks may have side affect. Handling all those side //! affect immediately is not efficient. Instead, tikv uses `Ready` to batch u...
(&mut self) -> bool { self.raft_group_mut().tick() } /// Callback for fetching logs asynchronously. pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) { let FetchedLogs { context, logs } = fetched_logs; let low = logs.low; if!self.is_leader() { self.ent...
tick
identifier_name
driver.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![feature(rustc_private)] #![feature(str_strip)] // FIXME: switch to something more ergonomic here, once available. // (Currently there is no way to opt into sysroot crates without `extern crate`.) #[allow(unused_extern_crates)] extern crate rustc; #[allow(unuse...
.or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN")) .ok(); toolchain_path(home, toolchain) }) .or_else(|| { Command::new("rustc") .arg("--print") .arg("sysroo...
.or_else(|_| std::env::var("MULTIRUST_HOME")) .ok(); let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
random_line_split
driver.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![feature(rustc_private)] #![feature(str_strip)] // FIXME: switch to something more ergonomic here, once available. // (Currently there is no way to opt into sysroot crates without `extern crate`.) #[allow(unused_extern_crates)] extern crate rustc; #[allow(unuse...
})); } } let mut clippy = ClippyCallbacks; let mut default = DefaultCallbacks; let callbacks: &mut (dyn rustc_driver::Callbacks + Send) = if clippy_enabled { &mut clippy } else { &mut default }; rustc_driver...
{ Some(s.to_string()) }
conditional_block
driver.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![feature(rustc_private)] #![feature(str_strip)] // FIXME: switch to something more ergonomic here, once available. // (Currently there is no way to opt into sysroot crates without `extern crate`.) #[allow(unused_extern_crates)] extern crate rustc; #[allow(unuse...
() { let args = &["--bar=bar", "--foobar", "123", "--foo"]; assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None); assert_eq!(arg_value(args, "--bar", |_| false), None); assert_eq!(arg_value(args, "--bar", |_| true), Some("bar")); assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Som...
test_arg_value
identifier_name
matrix_invert.rs
use std::error::Error; use std::ffi::CString; use std::time::Instant; use crate::utils::matrix_utils::print_matrix; use rustacuda::prelude::*; use std::fmt; pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> { // Initialize the CUDA API rustacuda::init(CudaFlags::empty())?; // Get the first device...
// calculate the inverse and compare with expected result let inv = matrix_invert_cpu(&m).unwrap(); assert_eq!(expected, inv); println!("orignal: {}", m); println!("inverted: {}", inv); } #[derive(Debug, PartialEq, Clone)] pub struct Matrix { data: Vec<f32>, rows: usize, cols: usize, } ...
expected.set(2, 2, 1.0);
random_line_split
matrix_invert.rs
use std::error::Error; use std::ffi::CString; use std::time::Instant; use crate::utils::matrix_utils::print_matrix; use rustacuda::prelude::*; use std::fmt; pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> { // Initialize the CUDA API rustacuda::init(CudaFlags::empty())?; // Get the first device...
(rows: usize, cols: usize) -> Matrix { Matrix { rows: rows, cols: cols, data: vec![0.0; cols * rows], } } pub fn identiy(rows: usize) -> Matrix { let mut m = Matrix::zero(rows, rows); for i in 0..rows { m.set(i, i, 1.0); } ...
zero
identifier_name
matrix_invert.rs
use std::error::Error; use std::ffi::CString; use std::time::Instant; use crate::utils::matrix_utils::print_matrix; use rustacuda::prelude::*; use std::fmt; pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> { // Initialize the CUDA API rustacuda::init(CudaFlags::empty())?; // Get the first device...
// apply all transformations to the identiy matrix as well cols = 2 * mat_a.cols; let mut tmp: f32 = 0.0; for row in 0..rows { // transform to an upper triangle matrix // element in main diagonal is used to divide the current row let mut elem = dummy.get(row, row); if el...
{ if mat_a.rows != mat_a.cols { return Err(MathError::MatrixNotInvertableNotSquare); } let rows = mat_a.rows; let mut cols = mat_a.cols; // helper matrix for inverting let mut dummy = Matrix::zero(rows, 2 * cols); // copy matrix a to dummy (left half of dummy) for row in 0..row...
identifier_body
upb.rs
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
// SAFETY: // - `upb_Arena_Realloc` promises that if the return pointer is non-null, it is // dereferencable for the new `size` in bytes until the arena is destroyed. // - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a // `UPB_MALLOC_ALIGN` boun...
{ alloc::handle_alloc_error(new); }
conditional_block
upb.rs
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
pub fn copy_bytes_in_arena_if_needed_by_runtime<'a>( msg_ref: MutatorMessageRef<'a>, val: &'a [u8], ) -> &'a [u8] { // SAFETY: the alignment of `[u8]` is less than `UPB_MALLOC_ALIGN`. let new_alloc = unsafe { msg_ref.arena.alloc(Layout::for_value(val)) }; debug_assert_eq!(new_alloc.len(), val.len())...
self.msg } }
random_line_split
upb.rs
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
(_private: Private, msg: &'msg mut MessageInner) -> Self { MutatorMessageRef { msg: msg.msg, arena: &msg.arena } } pub fn msg(&self) -> RawMessage { self.msg } } pub fn copy_bytes_in_arena_if_needed_by_runtime<'a>( msg_ref: MutatorMessageRef<'a>, val: &'a [u8], ) -> &'a [u8] { ...
new
identifier_name
upb.rs
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
} impl Drop for Arena { #[inline] fn drop(&mut self) { unsafe { upb_Arena_Free(self.raw); } } } /// Serialized Protobuf wire format data. /// /// It's typically produced by `<Message>::serialize()`. pub struct SerializedData { data: NonNull<u8>, len: usize, // The...
{ debug_assert!(new.align() <= UPB_MALLOC_ALIGN); // SAFETY: // - `self.raw` is a valid UPB arena // - `ptr` was allocated by a previous call to `alloc` or `realloc` as promised // by the caller. let ptr = unsafe { upb_Arena_Realloc(self.raw, ptr, old.size(), new.size()...
identifier_body
more.rs
use crate::librb::uoff_t; use libc; use libc::fclose; use libc::fstat; use libc::isatty; use libc::off64_t; use libc::off_t; use libc::printf; use libc::putchar_unlocked; use libc::stat; use libc::termios; use libc::FILE; extern "C" { #[no_mangle] fn _exit(_: libc::c_int) ->!; #[no_mangle] static mut optind:...
) -> libc::c_int; #[no_mangle] fn set_termios_to_raw(fd: libc::c_int, oldterm: *mut termios, flags: libc::c_int) -> libc::c_int; #[no_mangle] static mut bb_common_bufsiz1: [libc::c_char; 0]; } pub type C2RustUnnamed = libc::c_uint; pub const BB_FATAL_SIGS: C2RustUnnamed = 117503054; #[derive(Copy, Clone)] ...
fn get_terminal_width_height( fd: libc::c_int, width: *mut libc::c_uint, height: *mut libc::c_uint,
random_line_split
more.rs
use crate::librb::uoff_t; use libc; use libc::fclose; use libc::fstat; use libc::isatty; use libc::off64_t; use libc::off_t; use libc::printf; use libc::putchar_unlocked; use libc::stat; use libc::termios; use libc::FILE; extern "C" { #[no_mangle] fn _exit(_: libc::c_int) ->!; #[no_mangle] static mut optind:...
unsafe extern "C" fn gotsig(mut _sig: libc::c_int) { /* bb_putchar_stderr doesn't use stdio buffering, * therefore it is safe in signal handler */ bb_putchar_stderr('\n' as i32 as libc::c_char); /* for compiler */ tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings)...
{ tcsetattr( (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno, 0i32, settings, ); }
identifier_body
more.rs
use crate::librb::uoff_t; use libc; use libc::fclose; use libc::fstat; use libc::isatty; use libc::off64_t; use libc::off_t; use libc::printf; use libc::putchar_unlocked; use libc::stat; use libc::termios; use libc::FILE; extern "C" { #[no_mangle] fn _exit(_: libc::c_int) ->!; #[no_mangle] static mut optind:...
(mut settings: *mut termios) { tcsetattr( (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno, 0i32, settings, ); } unsafe extern "C" fn gotsig(mut _sig: libc::c_int) { /* bb_putchar_stderr doesn't use stdio buffering, * therefore it is safe in signal handler */ bb_putchar_stderr('\n' ...
tcsetattr_tty_TCSANOW
identifier_name
point_cloud.rs
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ //! The actual point cloud use indexmap::IndexMap; use std::collections::HashMap; use std::fs::File; use std::path::Path; u...
} fn get_file_list(files_reg: &str) -> Vec<PathBuf> { let options = MatchOptions { case_sensitive: false, ..Default::default() }; let mut paths = Vec::new(); let glob_paths = match glob_with(files_reg, &options) { Ok(expr) => expr, Err(e) => panic!("Pattern reading error...
{ if let Some(schema_map) = schema_yaml.as_hash() { for (k, v) in schema_map.iter() { let key = k.as_str().unwrap().to_string(); match v.as_str().unwrap() { "u32" => label_scheme.add_u32(key), "f32" => label_scheme.add_f32(key), "i32" =...
identifier_body
point_cloud.rs
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ //! The actual point cloud use indexmap::IndexMap; use std::collections::HashMap; use std::fs::File; use std::path::Path; u...
(&self) -> usize { self.data_sources.iter().fold(0, |acc, mm| acc + mm.len()) } /// Dimension of the data in the point cloud pub fn dim(&self) -> usize { self.data_dim } /// The names of the data are currently a shallow wrapper around a usize. pub fn reference_indexes(&self) ->...
len
identifier_name
point_cloud.rs
path::PathBuf; use std::sync::{Arc, Mutex}; use std::fmt; use glob::{glob_with, MatchOptions}; use std::io::Read; use yaml_rust::{Yaml, YamlLoader}; use std::marker::PhantomData; use std::cmp::min; use rayon::prelude::*; use super::*; use super::errors::*; use super::labels::*; use super::labels::values::*; use crate...
random_line_split
day_15.rs
mod point; mod astar; use { crate::{ astar::Pathfinder, point::{ Point, Neighbors, }, }, std::{ fmt, cmp::Ordering, collections::{ HashSet, HashMap, }, time::Instant, usize, }, ra...
let b_dest = *b.last().unwrap(); // sort first by shortest paths... match a.len().cmp(&b.len()) { // then by origin pos in reading order Ordering::Equal => Point::cmp_reading_order(a_dest, b_dest), dest_order => ...
{ let mut paths = Vec::new(); let origin_points = fighter.pos.neighbors_reading_order() .filter(|p| self.is_free_space(*p)); let mut path = Vec::new(); for origin in origin_points { for &dest in &dests { let free_tile_...
conditional_block
day_15.rs
mod point; mod astar; use { crate::{ astar::Pathfinder, point::{ Point, Neighbors, }, }, std::{ fmt, cmp::Ordering, collections::{ HashSet, HashMap, }, time::Instant, usize, }, ra...
match a.hp.cmp(&b.hp) { Ordering::Equal => Point::cmp_reading_order(a.pos, b.pos), hp_order => hp_order, } }); if let Some(j) = target_index { let attack_power = match self.fighters[i].team { Team::E...
{ let neighbors = self.fighters[i].pos.neighbors_reading_order(); let target_index = neighbors .filter_map(|neighbor| { self.fighters.iter().enumerate() .filter_map(|(j, f)| { if f.pos == neighbor && f.h...
identifier_body
day_15.rs
mod point; mod astar; use { crate::{ astar::Pathfinder, point::{ Point, Neighbors, }, }, std::{ fmt, cmp::Ordering, collections::{ HashSet, HashMap, }, time::Instant, usize, }, ra...
(&self, i: usize, targets: &mut Vec<usize>) { targets.clear(); let fighter = &self.fighters[i]; targets.extend(self.fighters.iter().enumerate() .filter(|(_, other)| other.hp > 0) .filter_map(|(j, other)| if other.team!= fighter.team { Some(j) } ...
find_targets
identifier_name
day_15.rs
mod point; mod astar; use { crate::{ astar::Pathfinder, point::{ Point, Neighbors, }, }, std::{ fmt, cmp::Ordering, collections::{ HashSet, HashMap, }, time::Instant, usize, }, ra...
for (y, line) in s.lines().enumerate() { height += 1; width = line.len(); // assume all lines are the same length for (x, char) in line.chars().enumerate() { let point = Point::new(x as isize, y as isize); match char { '#' ...
let mut fighters = Vec::new(); let mut tiles = Vec::new();
random_line_split
install.rs
// * This file is part of the uutils coreutils package. // * // * (c) Ben Eills <ben@beneills.com> // * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. // spell-checker:ignore (ToDO) rwxr sourcepath targetpath extern crate clap; ...
Copy one file to a new location, changing metadata. /// /// # Parameters /// /// _from_ must exist as a non-directory. /// _to_ must be a non-existent file, whose parent directory exists. /// /// # Errors /// /// If the copy system call fails, we print a verbose error and return an empty error value. /// fn copy(from: ...
0 } } ///
conditional_block
install.rs
// * This file is part of the uutils coreutils package. // * // * (c) Ben Eills <ben@beneills.com> // * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. // spell-checker:ignore (ToDO) rwxr sourcepath targetpath extern crate clap; ...
py one file to a new location, changing metadata. /// /// # Parameters /// /// _from_ must exist as a non-directory. /// _to_ must be a non-existent file, whose parent directory exists. /// /// # Errors /// /// If the copy system call fails, we print a verbose error and return an empty error value. /// fn copy(from: &P...
copy(file, &target, b).is_err() { 1 } else { 0 } } /// Co
identifier_body
install.rs
// * This file is part of the uutils coreutils package. // * // * (c) Ben Eills <ben@beneills.com> // * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. // spell-checker:ignore (ToDO) rwxr sourcepath targetpath extern crate clap; ...
(matches: &ArgMatches) -> Result<Behavior, i32> { let main_function = if matches.is_present("directory") { MainFunction::Directory } else { MainFunction::Standard }; let considering_dir: bool = MainFunction::Directory == main_function; let specified_mode: Option<u32> = if matches.i...
behavior
identifier_name
install.rs
// * This file is part of the uutils coreutils package. // * // * (c) Ben Eills <ben@beneills.com> // * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. // spell-checker:ignore (ToDO) rwxr sourcepath targetpath extern crate clap; ...
/// Create directories Directory, /// Install files to locations (primary functionality) Standard, } impl Behavior { /// Determine the mode for chmod after copy. pub fn mode(&self) -> u32 { match self.specified_mode { Some(x) => x, None => DEFAULT_MODE, }...
random_line_split
asset.rs
/* * This file is part of the UnityPack rust package. * (c) Istvan Fehervari <gooksl@gmail.com> * * All rights reserved 2017 */ use assetbundle::AssetBundle; use assetbundle::Signature; use assetbundle::FSDescriptor; use typetree::{TypeMetadata, TypeNode}; use resources::default_type_metadata; use binaryreader::*...
{ asset_path: String, guid: Uuid, asset_type: i32, pub file_path: String, // probably want to add a reference to the calling Asset itself } impl AssetRef { pub fn new<R: Read + Seek + Teller>( buffer: &mut R, endianness: &Endianness, ) -> Result<AssetRef> { let asse...
AssetRef
identifier_name
asset.rs
/* * This file is part of the UnityPack rust package. * (c) Istvan Fehervari <gooksl@gmail.com> * * All rights reserved 2017 */ use assetbundle::AssetBundle; use assetbundle::Signature; use assetbundle::FSDescriptor; use typetree::{TypeMetadata, TypeNode}; use resources::default_type_metadata; use binaryreader::*...
} self.objects.insert(obj.path_id, obj); Ok(()) } pub fn read_id<R: Read + Seek + Teller>(&self, buffer: &mut R) -> io::Result<i64> { if self.format >= 14 { return buffer.read_i64(&self.endianness); } let result = buffer.read_i32(&self.endianness)? ...
{}
conditional_block
asset.rs
/* * This file is part of the UnityPack rust package. * (c) Istvan Fehervari <gooksl@gmail.com> * * All rights reserved 2017 */ use assetbundle::AssetBundle; use assetbundle::Signature; use assetbundle::FSDescriptor; use typetree::{TypeMetadata, TypeNode}; use resources::default_type_metadata; use binaryreader::*...
}
pub enum AssetOrRef { Asset, AssetRef(AssetRef),
random_line_split
mod.rs
// Copyright 2020-2023 - Nym Technologies SA <contact@nymtech.net> // SPDX-License-Identifier: Apache-2.0 use crate::config::persistence::paths::MixNodePaths; use crate::config::template::CONFIG_TEMPLATE; use nym_bin_common::logging::LoggingSettings; use nym_config::defaults::{ mainnet, DEFAULT_HTTP_API_LISTENING_...
} }
random_line_split
mod.rs
// Copyright 2020-2023 - Nym Technologies SA <contact@nymtech.net> // SPDX-License-Identifier: Apache-2.0 use crate::config::persistence::paths::MixNodePaths; use crate::config::template::CONFIG_TEMPLATE; use nym_bin_common::logging::LoggingSettings; use nym_config::defaults::{ mainnet, DEFAULT_HTTP_API_LISTENING_...
(mut self, port: u16) -> Self { self.mixnode.mix_port = port; self } pub fn with_verloc_port(mut self, port: u16) -> Self { self.mixnode.verloc_port = port; self } pub fn with_http_api_port(mut self, port: u16) -> Self { self.mixnode.http_api_port = port; ...
with_mix_port
identifier_name
interpreter.rs
use super::{environment::Environment, primitives}; use calyx::{errors::FutilResult, ir}; use std::collections::HashMap; /// Evaluates a group, given an environment. pub fn eval_group( group: ir::RRC<ir::Group>, env: &Environment, ) -> FutilResult<Environment> { eval_assigns(&(group.borrow()).assignments, &...
Ok(write_env) } /// Evaluate guard implementation #[allow(clippy::borrowed_box)] // XXX: Allow for this warning. It would make sense to use a reference when we // have the `box` match pattern available in Rust. fn eval_guard(guard: &Box<ir::Guard>, env: &Environment) -> u64 { (match &**guard { ir::Guar...
write_env.map.get(&done_cell) );*/
random_line_split
interpreter.rs
use super::{environment::Environment, primitives}; use calyx::{errors::FutilResult, ir}; use std::collections::HashMap; /// Evaluates a group, given an environment. pub fn eval_group( group: ir::RRC<ir::Group>, env: &Environment, ) -> FutilResult<Environment> { eval_assigns(&(group.borrow()).assignments, &...
(assigns: &[ir::Assignment]) -> &ir::Assignment { assigns .iter() .find(|assign| { let dst = assign.dst.borrow(); dst.is_hole() && dst.name == "done" }) .expect("Group does not have a done signal") } /// Determines if writing a particular cell and cell port is c...
get_done_signal
identifier_name
interpreter.rs
use super::{environment::Environment, primitives}; use calyx::{errors::FutilResult, ir}; use std::collections::HashMap; /// Evaluates a group, given an environment. pub fn eval_group( group: ir::RRC<ir::Group>, env: &Environment, ) -> FutilResult<Environment> { eval_assigns(&(group.borrow()).assignments, &...
// queue any required updates. //determine if dst_cell is a combinational cell or not if is_combinational(&dst_cell, &assign.dst.borrow().name, env) { // write to assign.dst to e2 immediately, if combinational write_env.put( ...
{ // check if the cells are constants? // cell of assign.src let src_cell = get_cell_from_port(&assign.src); // cell of assign.dst let dst_cell = get_cell_from_port(&assign.dst); /*println!( "src cell {:...
conditional_block
interpreter.rs
use super::{environment::Environment, primitives}; use calyx::{errors::FutilResult, ir}; use std::collections::HashMap; /// Evaluates a group, given an environment. pub fn eval_group( group: ir::RRC<ir::Group>, env: &Environment, ) -> FutilResult<Environment> { eval_assigns(&(group.borrow()).assignments, &...
} ir::Guard::Geq(g1, g2) => { env.get_from_port(&g1.borrow()) >= env.get_from_port(&g2.borrow()) } ir::Guard::Leq(g1, g2) => { env.get_from_port(&g1.borrow()) <= env.get_from_port(&g2.borrow()) } ir::Guard::Port(p) => env.get_from_port(&p.borrow())...
{ (match &**guard { ir::Guard::Or(g1, g2) => { (eval_guard(g1, env) == 1) || (eval_guard(g2, env) == 1) } ir::Guard::And(g1, g2) => { (eval_guard(g1, env) == 1) && (eval_guard(g2, env) == 1) } ir::Guard::Not(g) => eval_guard(g, &env) != 0, ir::...
identifier_body
lib.rs
#![warn(clippy::all, clippy::pedantic, clippy::nursery)] #![allow( clippy::default_trait_access, clippy::use_self, clippy::wildcard_imports )] use arr_macro::arr; use derivative::Derivative; use enr::*; use ethereum_types::*; use futures::{Sink, SinkExt}; use heapless::{ consts::{U16, U4096}, FnvIn...
if *current_bucket == *max_bucket { return None; } *current_bucket += 1; *current_bucket_remaining = None; } } } pub enum DiscoveryRequest { Ping, } pub enum DiscoveryResponse { Pong, } pub enum DiscoveryPacket { WhoAreYou, ...
{ // Safety: we have exclusive access to underlying node table return Some(unsafe { &mut *ptr.as_ptr() }); }
conditional_block
lib.rs
#![warn(clippy::all, clippy::pedantic, clippy::nursery)] #![allow( clippy::default_trait_access, clippy::use_self, clippy::wildcard_imports )] use arr_macro::arr; use derivative::Derivative; use enr::*; use ethereum_types::*; use futures::{Sink, SinkExt}; use heapless::{ consts::{U16, U4096}, FnvIn...
} pub struct BucketNodes<'a, K: EnrKey>(NodeEntries<'a, K>); impl<'a, K: EnrKey> Iterator for BucketNodes<'a, K> { type Item = &'a mut NodeEntry<K>; fn next(&mut self) -> Option<Self::Item> { self.0.next() } } pub struct Closest<'a, K: EnrKey>(NodeEntries<'a, K>); impl<'a, K: EnrKey> Iterator ...
{ Closest(NodeEntries { node_table: self, current_bucket: 0, max_bucket: 255, current_bucket_remaining: None, }) }
identifier_body
lib.rs
#![warn(clippy::all, clippy::pedantic, clippy::nursery)] #![allow( clippy::default_trait_access, clippy::use_self, clippy::wildcard_imports )] use arr_macro::arr; use derivative::Derivative; use enr::*; use ethereum_types::*; use futures::{Sink, SinkExt}; use heapless::{ consts::{U16, U4096}, FnvIn...
() { let _ = env_logger::try_init(); let host_id = H256::random(); let mut table = NodeTable::<SecretKey>::new(host_id); for _ in 0..9000 { table.add_node( EnrBuilder::new("v4") .build(&SecretKey::random(&mut rand::thread_rng())) ...
test_iterator
identifier_name
lib.rs
#![warn(clippy::all, clippy::pedantic, clippy::nursery)] #![allow( clippy::default_trait_access, clippy::use_self, clippy::wildcard_imports )] use arr_macro::arr; use derivative::Derivative; use enr::*; use ethereum_types::*; use futures::{Sink, SinkExt}; use heapless::{ consts::{U16, U4096}, FnvIn...
ptr::NonNull, sync::{Arc, Mutex}, time::{Duration, Instant}, }; use tokio::{ net::UdpSocket, prelude::*, stream::{StreamExt, *}, }; use tokio_util::{codec::*, udp::*}; pub mod proto; pub mod topic; pub type RawNodeId = [u8; 32]; #[must_use] pub fn distance(a: H256, b: H256) -> U256 { U256...
ops::BitXor,
random_line_split
bytesearch.rs
use crate::insn::MAX_CHAR_SET_LENGTH; use core::fmt; extern crate memchr; #[cfg(not(feature = "std"))] use alloc::vec::Vec; /// Facilities for searching bytes. pub trait ByteSearcher { /// Search for ourselves in a slice of bytes. /// The length of the slice is unspecified and may be 0. /// \return the nex...
} None } } // CharSet helper. Avoid branching in the loop to get good unrolling. #[allow(unused_parens)] #[inline(always)] pub fn charset_contains(set: &[u32; MAX_CHAR_SET_LENGTH], c: u32) -> bool { let mut result = false; for &v in set.iter() { result |= (v == c); } result...
{ return Some(idx); }
conditional_block
bytesearch.rs
use crate::insn::MAX_CHAR_SET_LENGTH; use core::fmt; extern crate memchr; #[cfg(not(feature = "std"))] use alloc::vec::Vec; /// Facilities for searching bytes. pub trait ByteSearcher { /// Search for ourselves in a slice of bytes. /// The length of the slice is unspecified and may be 0. /// \return the nex...
(&self, rhs: &[u8]) -> bool { debug_assert!(rhs.len() == Self::LENGTH, "Slice has wrong length"); if cfg!(feature = "prohibit-unsafe") { // Here's what we would like to do. However this will emit an unnecessary length compare, and an unnecessary pointer compare. self == rhs ...
equals_known_len
identifier_name
bytesearch.rs
use crate::insn::MAX_CHAR_SET_LENGTH; use core::fmt; extern crate memchr; #[cfg(not(feature = "std"))] use alloc::vec::Vec; /// Facilities for searching bytes. pub trait ByteSearcher { /// Search for ourselves in a slice of bytes. /// The length of the slice is unspecified and may be 0. /// \return the nex...
format_bitmap("ByteBitmap", f, |v| self.contains(v)) } } /// A trivial ByteSearcher corresponding to the empty string. #[derive(Debug, Copy, Clone)] pub struct EmptyString {} impl ByteSearcher for EmptyString { #[inline(always)] fn find_in(&self, _bytes: &[u8]) -> Option<usize> { Some(0) ...
impl fmt::Debug for ByteBitmap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
random_line_split
bytesearch.rs
use crate::insn::MAX_CHAR_SET_LENGTH; use core::fmt; extern crate memchr; #[cfg(not(feature = "std"))] use alloc::vec::Vec; /// Facilities for searching bytes. pub trait ByteSearcher { /// Search for ourselves in a slice of bytes. /// The length of the slice is unspecified and may be 0. /// \return the nex...
/// Set a bit in this bitmap. #[inline(always)] pub fn set(&mut self, val: u8) { let byte = val >> 4; let bit = val & 0xF; self.0[byte as usize] |= 1 << bit; } /// Update ourselves from another bitmap, in place. pub fn bitor(&mut self, rhs: &ByteBitmap) { for i...
{ let byte = val >> 4; let bit = val & 0xF; (self.0[byte as usize] & (1 << bit)) != 0 }
identifier_body
texel.rs
` developers #![allow(unsafe_code)] use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use core::marker::PhantomData; use core::{fmt, hash, mem, num, ptr, slice}; use crate::buf::buf; /// Marker struct to denote a texel type. /// /// Can be constructed only for types that have expected alignment and no byte ...
() -> Texel<[T; 6]> { T::texel().array::<6>() } } impl<T: AsTexel> AsTexel for [T; 7] { fn texel() -> Texel<[T; 7]> { T::texel().array::<7>() } } impl<T: AsTexel> AsTexel for [T; 8] { fn texel() -> Texel<[T; 8]> { T::texel().array::<8...
texel
identifier_name
texel.rs
rs` developers #![allow(unsafe_code)] use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use core::marker::PhantomData; use core::{fmt, hash, mem, num, ptr, slice}; use crate::buf::buf; /// Marker struct to denote a texel type. /// /// Can be constructed only for types that have expected alignment and no byt...
pub(crate) fn cast_buf<'buf>(self, buffer: &'buf buf) -> &'buf [P] { debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0); debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0); // Safety: // * data is valid for reads as memory size is not enlarg...
self.cast_mut_bytes(texel) }
identifier_body
texel.rs
rs` developers #![allow(unsafe_code)] use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use core::marker::PhantomData; use core::{fmt, hash, mem, num, ptr, slice}; use crate::buf::buf; /// Marker struct to denote a texel type. /// /// Can be constructed only for types that have expected alignment and no byt...
} /// Try to reinterpret a slice of bytes as a slice of the texel. /// /// This returns `Some` if the buffer is suitably aligned, and `None` otherwise. pub fn try_to_slice_mut<'buf>(self, bytes: &'buf mut [u8]) -> Option<&'buf mut [P]> { if let Some(slice) = self.try_to_slice(bytes) { ...
None }
conditional_block
texel.rs
rs` developers
#![allow(unsafe_code)] use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use core::marker::PhantomData; use core::{fmt, hash, mem, num, ptr, slice}; use crate::buf::buf; /// Marker struct to denote a texel type. /// /// Can be constructed only for types that have expected alignment and no byte invariants. I...
random_line_split
lib.rs
#![warn( clippy::doc_markdown, clippy::redundant_closure, clippy::explicit_iter_loop, clippy::match_same_arms, clippy::needless_borrow, clippy::print_stdout, clippy::integer_arithmetic, clippy::cast_possible_truncation, clippy::map_unwrap_or, clippy::unseparated_literal_suffix, ...
( _: &PyType, py: Python, pyschema: &PyAny, draft: Option<u8>, with_meta_schemas: Option<bool>, ) -> PyResult<Self> { let obj_ptr = pyschema.as_ptr(); let object_type = unsafe { pyo3::ffi::Py_TYPE(obj_ptr) }; if unsafe { object_type!= types::STR_TYPE }...
from_str
identifier_name
lib.rs
#![warn( clippy::doc_markdown, clippy::redundant_closure, clippy::explicit_iter_loop, clippy::match_same_arms, clippy::needless_borrow, clippy::print_stdout, clippy::integer_arithmetic, clippy::cast_possible_truncation, clippy::map_unwrap_or, clippy::unseparated_literal_suffix, ...
message.push(']'); } message.push(':'); message.push_str("\n "); message.push_str(&error.instance.to_string()); message } /// is_valid(schema, instance, draft=None, with_meta_schemas=False) /// /// A shortcut for validating the input instance against the schema. /// /// >>> is_valid(...
jsonschema::paths::PathChunk::Index(index) => message.push_str(&index.to_string()), // Keywords are not used for instances jsonschema::paths::PathChunk::Keyword(_) => unreachable!("Internal error"), };
random_line_split
lib.rs
#![warn( clippy::doc_markdown, clippy::redundant_closure, clippy::explicit_iter_loop, clippy::match_same_arms, clippy::needless_borrow, clippy::print_stdout, clippy::integer_arithmetic, clippy::cast_possible_truncation, clippy::map_unwrap_or, clippy::unseparated_literal_suffix, ...
} const SCHEMA_LENGTH_LIMIT: usize = 32; #[pyproto] impl<'p> PyObjectProtocol<'p> for JSONSchema { fn __repr__(&self) -> PyResult<String> { Ok(format!("<JSONSchema: {}>", self.repr)) } } #[allow(dead_code)] mod build { include!(concat!(env!("OUT_DIR"), "/built.rs")); } /// JSON Schema validatio...
{ iter_on_error(py, &self.schema, instance) }
identifier_body
form_input.rs
use super::error_message::get_error_message; use crate::styles::{get_palette, get_size, Palette, Size}; use wasm_bindgen_test::*; use yew::prelude::*; use yew::{utils, App}; /// # Form Input /// /// ## Features required /// /// forms /// /// ## Example /// /// ```rust /// use yew::prelude::*; /// use yew_styles::forms...
/// type Properties = (); /// fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { /// FormInputExample { /// link, /// value: "".to_string(), /// } /// } /// fn update(&mut self, msg: Self::Message) -> ShouldRender { /// match msg { /// ...
random_line_split
form_input.rs
use super::error_message::get_error_message; use crate::styles::{get_palette, get_size, Palette, Size}; use wasm_bindgen_test::*; use yew::prelude::*; use yew::{utils, App}; /// # Form Input /// /// ## Features required /// /// forms /// /// ## Example /// /// ```rust /// use yew::prelude::*; /// use yew_styles::forms...
(&mut self, props: Self::Properties) -> ShouldRender { if self.props!= props { self.props = props; true } else { false } } fn view(&self) -> Html { html! { <> <input id=self.props.id.clone() ...
change
identifier_name
form_input.rs
use super::error_message::get_error_message; use crate::styles::{get_palette, get_size, Palette, Size}; use wasm_bindgen_test::*; use yew::prelude::*; use yew::{utils, App}; /// # Form Input /// /// ## Features required /// /// forms /// /// ## Example /// /// ```rust /// use yew::prelude::*; /// use yew_styles::forms...
InputType::Time => "time".to_string(), InputType::Url => "url".to_string(), InputType::Week => "week".to_string(), } } #[wasm_bindgen_test] fn should_create_form_input() { let props = Props { key: "".to_string(), code_ref: NodeRef::default(), id: "form-input-id-...
{ match input_type { InputType::Button => "button".to_string(), InputType::Checkbox => "checkbox".to_string(), InputType::Color => "color".to_string(), InputType::Date => "date".to_string(), InputType::Datetime => "datetime".to_string(), InputType::DatetimeLocal => "d...
identifier_body
main.rs
extern crate clap; use clap::{App, Arg}; use std::io::{stderr, stdin, stdout, Write, Read}; use std::time::{Duration, Instant}; use std::net::{SocketAddr, TcpListener, IpAddr}; const DEFAULT_BUFFER_SIZE: usize = 4096; const DEFAULT_ITERATION_COUNT: usize = 1; const DEFAULT_ADDRESS: &'static str = "127.0.0.1"; macro_...
fn byte_to_mem_units(bytes: f64) -> (f64, &'static str) { const KB: f64 = 1024.0; const MB: f64 = KB * 1024.0; const GB: f64 = MB * 1024.0; const TB: f64 = GB * 1024.0; if bytes >= TB { (bytes / TB, "TB") } else if bytes >= GB { (bytes / GB, "GB") } else if bytes >= MB { (bytes / MB, "MB"...
{ write!(output, "\x1b[{}A", lines)?; Ok(()) }
identifier_body
main.rs
extern crate clap; use clap::{App, Arg}; use std::io::{stderr, stdin, stdout, Write, Read}; use std::time::{Duration, Instant}; use std::net::{SocketAddr, TcpListener, IpAddr}; const DEFAULT_BUFFER_SIZE: usize = 4096; const DEFAULT_ITERATION_COUNT: usize = 1; const DEFAULT_ADDRESS: &'static str = "127.0.0.1"; macro_...
} else { measure_stdin(buffer_size, iterations, passthrough); } } fn measure_tcp_stream(address: &str, port: u16, buffer_size: usize, iterations: usize, passthrough: bool) { let parsed_addr: IpAddr = match address.parse() { Ok(parsed) => parsed, Err(_) => { print_err!("B...
}
random_line_split
main.rs
extern crate clap; use clap::{App, Arg}; use std::io::{stderr, stdin, stdout, Write, Read}; use std::time::{Duration, Instant}; use std::net::{SocketAddr, TcpListener, IpAddr}; const DEFAULT_BUFFER_SIZE: usize = 4096; const DEFAULT_ITERATION_COUNT: usize = 1; const DEFAULT_ADDRESS: &'static str = "127.0.0.1"; macro_...
(bytes: f64) -> (f64, &'static str) { const KB: f64 = 1024.0; const MB: f64 = KB * 1024.0; const GB: f64 = MB * 1024.0; const TB: f64 = GB * 1024.0; if bytes >= TB { (bytes / TB, "TB") } else if bytes >= GB { (bytes / GB, "GB") } else if bytes >= MB { (bytes / MB, "MB") } else if bytes ...
byte_to_mem_units
identifier_name
lib.rs
use itertools::Itertools; use std::convert::TryFrom; use std::fmt; use std::fs; pub const N_ROUNDS: usize = 6; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Debug, Clone, PartialEq)] pub struct Position { coords: Vec<i32>, } impl Position { /// Return linear index of position...
#[test] fn test_grid_indexing() { let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap(); let pos = Position::from(&[1, 0, 1]); assert_eq!(ConwayCube::Active, grid.cube_at(&pos)); let pos = Position::from(&[1, 1, 0]); assert_eq!(ConwayCube::Inactive, grid.cube_at(...
{ let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap(); assert_eq!(3, grid.edge); assert_eq!(5, grid.active_cubes()); }
identifier_body
lib.rs
use itertools::Itertools; use std::convert::TryFrom; use std::fmt; use std::fs; pub const N_ROUNDS: usize = 6; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Debug, Clone, PartialEq)] pub struct Position { coords: Vec<i32>, } impl Position { /// Return linear index of position...
// create empty nD grid, and copy initial 2D grid plane to it // (in the middle of each dimension beyond the first two): let max_i = InfiniteGrid::index_size(edge, dim); let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i]; for y in 0..edge { for x in 0..edg...
.lines() .flat_map(|line| line.trim().chars().map(ConwayCube::from_char)) .collect();
random_line_split
lib.rs
use itertools::Itertools; use std::convert::TryFrom; use std::fmt; use std::fs; pub const N_ROUNDS: usize = 6; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Debug, Clone, PartialEq)] pub struct Position { coords: Vec<i32>, } impl Position { /// Return linear index of position...
() { // the full N_ROUNDS takes a while so: let n_rounds = 1; // = N_ROUNDS; let grid = InfiniteGrid::from_input(TINY_LAYOUT, 4).unwrap(); let mut n_active: usize = 0; for (i, g) in grid.iter().enumerate() { if i >= n_rounds - 1 { n_active = g.active_...
test_6_rounds_4d
identifier_name
lib.rs
use itertools::Itertools; use std::convert::TryFrom; use std::fmt; use std::fs; pub const N_ROUNDS: usize = 6; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Debug, Clone, PartialEq)] pub struct Position { coords: Vec<i32>, } impl Position { /// Return linear index of position...
else { 848 }; assert_eq!(expect, n_active); } }
{ 3*4 + 5 + 3*4 }
conditional_block
encoder.rs
common::AOMCodec; use crate::ffi::*; use std::mem::{self, MaybeUninit}; use std::ptr; use av_data::frame::{Frame, FrameBufferConv, MediaKind}; use av_data::packet::Packet; use av_data::pixel::formats::YUV420; use av_data::pixel::Formaton; #[derive(Clone, Debug, PartialEq)] pub struct PSNR { pub samples: [u32; 4]...
(&mut self) -> Result<()> { if self.enc.is_none() { self.cfg .get_encoder() .map(|enc| { self.enc = Some(enc); }) .map_err(|_err| Error::ConfigurationIncomplete) } else { ...
configure
identifier_name
encoder.rs
common::AOMCodec; use crate::ffi::*; use std::mem::{self, MaybeUninit}; use std::ptr; use av_data::frame::{Frame, FrameBufferConv, MediaKind}; use av_data::packet::Packet; use av_data::pixel::formats::YUV420; use av_data::pixel::Formaton; #[derive(Clone, Debug, PartialEq)] pub struct PSNR { pub samples: [u32; 4]...
dts: Some(0), duration: Some(1), timebase: Some(Rational64::new(1, 1000)), user_private: None, }; ctx.configure().unwrap(); let mut f = Arc::new(setup_frame(w, h, &t)); let mut out = 0; for i in 0..100 { Arc::get_mut(&m...
{ use super::AV1_DESCR; use av_codec::common::CodecList; use av_codec::encoder::*; use av_codec::error::*; use std::sync::Arc; let encoders = Codecs::from_list(&[AV1_DESCR]); let mut ctx = Context::by_name(&encoders, "av1").unwrap(); let w = 200; ...
identifier_body
encoder.rs
::common::AOMCodec; use crate::ffi::*; use std::mem::{self, MaybeUninit}; use std::ptr; use av_data::frame::{Frame, FrameBufferConv, MediaKind}; use av_data::packet::Packet; use av_data::pixel::formats::YUV420; use av_data::pixel::Formaton; #[derive(Clone, Debug, PartialEq)] pub struct PSNR { pub samples: [u32; ...
let mut e = setup(w, h, &t); let mut f = setup_frame(w, h, &t); let mut out = 0; // TODO write some pattern for i in 0..100 { e.encode(&f).unwrap(); f.t.pts = Some(i); // println!("{:#?}", f); loop { let p = e.get_...
random_line_split
main.rs
Find a better way. let temporary_process = unsafe { KObject::new(megaton_hammer::kernel::svc::CURRENT_PROCESS) }; let ret = cb(0x30000, &temporary_process, transfer_mem.as_ref()); unsafe { std::mem::forget(temporary_process); } ret })?; println!("Open /dev/nvhost-as-gpu"); ...
GpuBuffer { nvmap_handle: create.handle, size: mem.len() * std::mem::size_of::<BufferMemory>(), alignment: 0x1000, kind: 0 } }; let buffers = { let mut alloc = NvMapIocAllocArgs { handle: gpu_buffer.nvmap_handle, h...
{ return Err(MyError::IoctlError(ret)); }
conditional_block
main.rs
Find a better way. let temporary_process = unsafe { KObject::new(megaton_hammer::kernel::svc::CURRENT_PROCESS) }; let ret = cb(0x30000, &temporary_process, transfer_mem.as_ref()); unsafe { std::mem::forget(temporary_process); } ret })?; println!("Open /dev/nvhost-as-gpu"); ...
(&self) -> &[u32] { &self.0[..] } } impl std::ops::DerefMut for BufferMemory { fn deref_mut(&mut self) -> &mut [u32] { &mut self.0[..] } } const NVMAP_IOC_CREATE: u32 = 0xC0080101; const NVMAP_IOC_FROM_ID: u32 = 0xC0080103; const NVMAP_IOC_ALLOC: u32 = 0xC0200104; const NVMAP_IOC_FREE: u32...
deref
identifier_name
main.rs
: Find a better way. let temporary_process = unsafe { KObject::new(megaton_hammer::kernel::svc::CURRENT_PROCESS) }; let ret = cb(0x30000, &temporary_process, transfer_mem.as_ref()); unsafe { std::mem::forget(temporary_process); } ret })?; println!("Open /dev/nvhost-as-gpu"); ...
parcel.write_u32(0x54); parcel.write_u32(0); // unknown, but always those values parcel.write_u32(0x588bbba9); parcel.write_u32(0); // Timestamp, u64 parcel.write_u32(1); // unknown, but always those values parcel.write_u32(0); parcel.write_u32(0); ...
random_line_split
main.rs
} impl From<megaton_hammer::error::Error> for MyError { fn from(err: megaton_hammer::error::Error) -> MyError { MyError::MegatonError(err) } } fn main() -> std::result::Result<(), MyError> { // Let's get ferris to show up on my switch. println!("Initialize NV"); let nvdrv = nns::nvdrv::I...
{ MyError::ImageError(err) }
identifier_body