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
lambda.rs
use dotenv; use fastspring_keygen_integration::fastspring; use fastspring_keygen_integration::keygen; use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license}; use fastspring_keygen_integration::util; use fastspring_keygen_integration::patreon; use http::header::CONTENT_TYPE; use lambda_http::{la...
Ok(Response::builder() .status(http::StatusCode::OK) .body(Body::default()) .unwrap()) } /// Patreon pledge create trigger fn patreon_handle_pledge_create( client: &reqwest::Client, body: &serde_json::Value, ) -> Result<Response<Body>, HandlerError> { debug!("handle_pledge_create {...
} else if trigger == "pledges:delete" { patreon_handle_pledge_delete(client, &body)?; }
random_line_split
lambda.rs
use dotenv; use fastspring_keygen_integration::fastspring; use fastspring_keygen_integration::keygen; use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license}; use fastspring_keygen_integration::util; use fastspring_keygen_integration::patreon; use http::header::CONTENT_TYPE; use lambda_http::{la...
fn handle_patreon_webhook( client: &reqwest::Client, req: Request, _c: Context, ) -> Result<Response<Body>, HandlerError> { if!patreon::authentify_web_hook(&req) { return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unw...
{ code.split('.').nth(1) }
identifier_body
lambda.rs
use dotenv; use fastspring_keygen_integration::fastspring; use fastspring_keygen_integration::keygen; use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license}; use fastspring_keygen_integration::util; use fastspring_keygen_integration::patreon; use http::header::CONTENT_TYPE; use lambda_http::{la...
(req: Request, c: Context) -> Result<Response<Body>, HandlerError> { debug!("router request={:?}", req); debug!("path={:?}", req.uri().path()); debug!("query={:?}", req.query_string_parameters()); let client = reqwest::Client::new(); match req.uri().path() { "/fastspring-keygen-integration...
router
identifier_name
lambda.rs
use dotenv; use fastspring_keygen_integration::fastspring; use fastspring_keygen_integration::keygen; use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license}; use fastspring_keygen_integration::util; use fastspring_keygen_integration::patreon; use http::header::CONTENT_TYPE; use lambda_http::{la...
let events_json = util::body_to_json(req.body())?; let events_json = events_json["events"].as_array().ok_or("invalid format")?; // TODO do not reply OK every time: check each event for e in events_json { let ty = e["type"].as_str().ok_or("invalid format")?; let data = &e["data"]; ...
{ return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); }
conditional_block
state.rs
use std::cmp::min; use std::collections::BTreeMap; use chrono::Utc; use tako::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use tako::ItemId; use tako::{define_wrapped_type, TaskId}; use crate::server::autoalloc...
pub fn new_job_id(&mut self) -> JobId { let id = self.job_id_counter; self.job_id_counter += 1; id.into() } pub fn revert_to_job_id(&mut self, id: JobId) { self.job_id_counter = id.as_num(); } pub fn last_n_ids(&self, n: u32) -> impl Iterator<Item = JobId> { ...
{ let job_id: JobId = *self.base_task_id_to_job_id.range(..=task_id).next_back()?.1; let job = self.jobs.get_mut(&job_id)?; if task_id < TakoTaskId::new( job.base_task_id.as_num() + job.n_tasks() as <TaskId as ItemId>::IdType, ) { Some(...
identifier_body
state.rs
use std::cmp::min; use std::collections::BTreeMap; use chrono::Utc; use tako::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use tako::ItemId; use tako::{define_wrapped_type, TaskId}; use crate::server::autoalloc...
(&mut self, msg: TaskUpdate, backend: &Backend) { log::debug!("Task id={} updated {:?}", msg.id, msg.state); let (mut job_id, mut is_job_terminated): (Option<JobId>, bool) = (None, false); match msg.state { TaskState::Running { worker_ids, context, ...
process_task_update
identifier_name
state.rs
use std::cmp::min; use std::collections::BTreeMap; use chrono::Utc; use tako::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use tako::ItemId; use tako::{define_wrapped_type, TaskId}; use crate::server::autoalloc...
self.event_storage .on_worker_added(msg.worker_id, msg.configuration); } pub fn process_worker_lost( &mut self, _state_ref: &StateRef, _tako_ref: &Backend, msg: LostWorkerMessage, ) { log::debug!("Worker lost id={}", msg.worker_id); let w...
{ autoalloc.on_worker_connected(msg.worker_id, &msg.configuration); }
conditional_block
state.rs
use std::cmp::min; use std::collections::BTreeMap; use chrono::Utc; use tako::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use tako::ItemId; use tako::{define_wrapped_type, TaskId}; use crate::server::autoalloc...
assert_eq!( state .get_job_mut_by_tako_task_id(task_id.into()) .map(|j| j.job_id.as_num()), expected ); } #[test] fn test_find_job_id_by_task_id() { let state_ref = create_hq_state(); let mut state = state_ref.get_mut(); ...
random_line_split
parse.rs
use crate::{ parse_utils::*, substitute::{substitute, Substitution}, SubstitutionGroup, }; use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree}; use std::{collections::HashSet, iter::Peekable}; /// Parses the attribute part of an invocation of duplicate, returning /// all the substitutions ...
( tree: TokenTree, existing: &Option<HashSet<String>>, ) -> Result<SubstitutionGroup, (Span, String)> { // Must get span now, before it's corrupted. let tree_span = tree.span(); let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n...
extract_verbose_substitutions
identifier_name
parse.rs
use crate::{ parse_utils::*, substitute::{substitute, Substitution}, SubstitutionGroup, }; use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree}; use std::{collections::HashSet, iter::Peekable}; /// Parses the attribute part of an invocation of duplicate, returning /// all the substitutions ...
if let Some(ident) = next_token(&mut stream, "Epected substitution identifier.")? { if let TokenTree::Ident(ident) = ident { let sub = parse_group( &mut stream, ident.span(), "Hint: A substitution identifier should be followed by a group containing the \ code to be inserted instead of...
{ // Must get span now, before it's corrupted. let tree_span = tree.span(); let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \ ]\n]", )?; if group.stream().into...
identifier_body
parse.rs
use crate::{ parse_utils::*, substitute::{substitute, Substitution}, SubstitutionGroup, }; use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree}; use std::{collections::HashSet, iter::Peekable}; /// Parses the attribute part of an invocation of duplicate, returning /// all the substitutions ...
let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \ ]\n]", )?; if group.stream().into_iter().count() == 0 { return Err((group.span(), "No substitution groups fo...
) -> Result<SubstitutionGroup, (Span, String)> { // Must get span now, before it's corrupted. let tree_span = tree.span();
random_line_split
imp.rs
use std::mem; use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder}; use memchr::{memchr, memchr2, memchr3, memmem}; use regex_syntax::hir::literal::{Literal, Literals}; /// A prefix extracted from a compiled regular expression. /// /// A regex prefix is a set of literal strings that *must* be matched at ...
let pats = lits.literals().to_owned(); let is_aho_corasick_fast = sset.dense.len() <= 1 && sset.all_ascii; if lits.literals().len() <= 100 &&!is_aho_corasick_fast { let mut builder = packed::Config::new() .match_kind(packed::MatchKind::LeftmostFirst) .bu...
{ if lits.literals().is_empty() { return Matcher::Empty; } if sset.dense.len() >= 26 { // Avoid trying to match a large number of single bytes. // This is *very* sensitive to a frequency analysis comparison // between the bytes in sset and the comp...
identifier_body
imp.rs
use std::mem; use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder}; use memchr::{memchr, memchr2, memchr3, memmem}; use regex_syntax::hir::literal::{Literal, Literals}; /// A prefix extracted from a compiled regular expression. /// /// A regex prefix is a set of literal strings that *must* be matched at ...
(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[0..lit.len()] { return Some((0, lit.len())); } } None } /// Like ...
find_start
identifier_name
imp.rs
use std::mem; use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder}; use memchr::{memchr, memchr2, memchr3, memmem}; use regex_syntax::hir::literal::{Literal, Literals}; /// A prefix extracted from a compiled regular expression. /// /// A regex prefix is a set of literal strings that *must* be matched at ...
} } fn prefixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() == 1; if let Some(&b) = lit.get(0) { if!sset.sparse[b as usize] { ...
complete: true, all_ascii: true,
random_line_split
imp.rs
use std::mem; use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder}; use memchr::{memchr, memchr2, memchr3, memmem}; use regex_syntax::hir::literal::{Literal, Literals}; /// A prefix extracted from a compiled regular expression. /// /// A regex prefix is a set of literal strings that *must* be matched at ...
else { let next = &one[..]; *one = &[]; Some(next) } } LiteralIter::AC(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; ...
{ None }
conditional_block
synchronizer.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::committee::*; use super::error::*; use super::messages::*; use super::types::*; use bincode::Error; use crypto::Digest; use futures::future::{Fuse, FutureExt}; use futures::select; use futures::stream::futures_unordered::FuturesUnordered; use futures::strea...
warn!("Exiting DagSynchronizer::start()."); break; } } res = rollback_fut => { if let Err(e) = res{ error!("rollback_headers returns error: {:?}", e); } else{ ...
random_line_split
synchronizer.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::committee::*; use super::error::*; use super::messages::*; use super::types::*; use bincode::Error; use crypto::Digest; use futures::future::{Fuse, FutureExt}; use futures::select; use futures::stream::futures_unordered::FuturesUnordered; use futures::strea...
( mut dag_synchronizer: DagSynchronizer, digest: Digest, rollback_stop_round: RoundNumber, sq: SyncNumber, ) -> Result<Option<Vec<Digest>>, DagError> { //TODO: issue: should we try the processor first? we need concurrent access to it... if let Ok(dbvalue) = dag_synchronizer.store.read(digest.to...
handle_header_digest
identifier_name
synchronizer.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::committee::*; use super::error::*; use super::messages::*; use super::types::*; use bincode::Error; use crypto::Digest; use futures::future::{Fuse, FutureExt}; use futures::select; use futures::stream::futures_unordered::FuturesUnordered; use futures::strea...
}); } } debug!( "[DEP] GOT H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); Ok(signed_header) } pub async fn dag_synchronizer_process( mut get_from_dag: Receiver<SyncMessage>, dag_synchronizer: DagSynchronizer, ) { ...
{ debug!( "[DEP] ASK H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); //Note: we now store different digests for header and certificates to avoid false positive. for (other_primary_id, digest) in &header.parents { let digest_in_store = ...
identifier_body
lib.rs
(mut start_chars, mut end_chars) = (a.chars(), b.chars()); // We need to keep track of this, because: // In the case of `a` == `"a"` and `b` == `"aab"`, // we actually need to compare `""` to `"b"` later on, not `""` to `"a"`. let mut last_start_char = '\0'; ...
SymbolTable::from_str("ab").unwrap(); let result = table.mudder_one("a", "b").unwrap(); assert_eq!(result, "ab"); let table = SymbolTable::from_str("0123456789").unwrap(); let result = table.mudder_one("1", "2").unwrap(); assert_eq!(result, "15"); } #[test] fn o
identifier_body
lib.rs
// SymbolTable::mudder() returns a Vec containing `amount` Strings. let result = table.mudder_one("a", "z").unwrap(); // These strings are always lexicographically placed between `start` and `end`. let one_str = result.as_str(); assert!(one_str > "a"); assert!(one_str < "z"); // You can also define your own symbol tab...
// so you cannot pass in an invalid value. use std::num::NonZeroUsize; // You can use the included alphabet table let table = SymbolTable::alphabet();
random_line_split
lib.rs
..., "r", "t"] /// ``` pub fn mudder( &self, a: &str, b: &str, amount: NonZeroUsize, ) -> Result<Vec<String>, GenerationError> { use error::InternalError::*; use GenerationError::*; ensure! { all_chars_ascii(a), NonAsciiError::NonAsciiU8 } ensu...
comp_amount = computed_amount(), b_factor = branching_factor, depth = depth, pool = pool, pool_len = pool.len(), ) } Ok(if amount.get() == 1 { pool.get(pool.len() / 2) .map(|item| vec!...
// We still don't have enough items, so bail panic!( "Internal error: Failed to calculate the correct tree depth! This is a bug. Please report it at: https://github.com/Follpvosten/mudders/issues and make sure to include the following information: Symbols in table: {symbols:?} G...
conditional_block
lib.rs
-> Self { Self::new(&('a' as u8..='z' as u8).collect::<Box<[_]>>()).unwrap() } /// Generate `amount` strings that lexicographically sort between `start` and `end`. /// The algorithm will try to make them as evenly-spaced as possible. /// /// When both parameters are empty strings, `amount`...
phabet()
identifier_name
session.rs
use crypto::digest::Digest; use crypto::sha1::Sha1; use crypto::hmac::Hmac; use crypto::mac::Mac; use eventual; use eventual::Future; use eventual::Async; use protobuf::{self, Message}; use rand::thread_rng; use rand::Rng; use std::io::{Read, Write, Cursor}; use std::result::Result; use std::sync::{Mutex, RwLock, Arc, ...
pub struct Session(pub Arc<SessionInternal>); impl Session { pub fn new(config: Config, cache: Box<Cache + Send + Sync>) -> Session { let device_id = { let mut h = Sha1::new(); h.input_str(&config.device_name); h.result_str() }; Session(Arc::new(SessionI...
} #[derive(Clone)]
random_line_split
session.rs
use crypto::digest::Digest; use crypto::sha1::Sha1; use crypto::hmac::Hmac; use crypto::mac::Mac; use eventual; use eventual::Future; use eventual::Async; use protobuf::{self, Message}; use rand::thread_rng; use rand::Rng; use std::io::{Read, Write, Cursor}; use std::result::Result; use std::sync::{Mutex, RwLock, Arc, ...
{ config: Config, device_id: String, data: RwLock<SessionData>, cache: Box<Cache + Send + Sync>, mercury: Mutex<MercuryManager>, metadata: Mutex<MetadataManager>, stream: Mutex<StreamManager>, audio_key: Mutex<AudioKeyManager>, rx_connection: Mutex<Option<CipherConnection>>, tx...
SessionInternal
identifier_name
session.rs
use crypto::digest::Digest; use crypto::sha1::Sha1; use crypto::hmac::Hmac; use crypto::mac::Mac; use eventual; use eventual::Future; use eventual::Async; use protobuf::{self, Message}; use rand::thread_rng; use rand::Rng; use std::io::{Read, Write, Cursor}; use std::result::Result; use std::sync::{Mutex, RwLock, Arc, ...
pub fn cache(&self) -> &Cache { self.0.cache.as_ref() } pub fn config(&self) -> &Config { &self.0.config } pub fn username(&self) -> String { self.0.data.read().unwrap().canonical_username.clone() } pub fn country(&self) -> String { self.0.data.read().unw...
{ self.0.mercury.lock().unwrap().subscribe(self, uri) }
identifier_body
option.rs
//! Enumeration of RS2 sensor options. //! //! Not all options apply to every sensor. In order to retrieve the correct options, //! one must iterate over the `sensor` object for option compatibility. //! //! Notice that this option refers to the `sensor`, not the device. However, the device //! used also matters; senso...
assert!( Rs2Option::from_i32(i).is_some(), "Rs2Option variant for ordinal {} does not exist.", i, ); } } }
{ continue; }
conditional_block
option.rs
//! Enumeration of RS2 sensor options. //! //! Not all options apply to every sensor. In order to retrieve the correct options, //! one must iterate over the `sensor` object for option compatibility. //! //! Notice that this option refers to the `sensor`, not the device. However, the device //! used also matters; senso...
{ /// The requested option is not supported by this sensor. #[error("Option not supported on this sensor.")] OptionNotSupported, /// The requested option is read-only and cannot be set. #[error("Option is read only.")] OptionIsReadOnly, /// The requested option could not be set. Reason is r...
OptionSetError
identifier_name
option.rs
//! Enumeration of RS2 sensor options. //! //! Not all options apply to every sensor. In order to retrieve the correct options, //! one must iterate over the `sensor` object for option compatibility. //! //! Notice that this option refers to the `sensor`, not the device. However, the device //! used also matters; senso...
NoiseEstimation = sys::rs2_option_RS2_OPTION_NOISE_ESTIMATION as i32, /// Enable/disable data collection for calculating IR pixel reflectivity. EnableIrReflectivity = sys::rs2_option_RS2_OPTION_ENABLE_IR_REFLECTIVITY as i32, /// Auto exposure limit in microseconds. /// /// Default is 0 which mea...
/// Enable/disable the maximum usable depth sensor range given the amount of ambient light in the scene. EnableMaxUsableRange = sys::rs2_option_RS2_OPTION_ENABLE_MAX_USABLE_RANGE as i32, /// Enable/disable the alternate IR, When enabling alternate IR, the IR image is holding the amplitude of the depth corre...
random_line_split
option.rs
//! Enumeration of RS2 sensor options. //! //! Not all options apply to every sensor. In order to retrieve the correct options, //! one must iterate over the `sensor` object for option compatibility. //! //! Notice that this option refers to the `sensor`, not the device. However, the device //! used also matters; senso...
} } }
{ let deprecated_options = vec![ sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_X as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_Y as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_ENABLED as i32, sys::rs2_option_RS2_OPTION_AMBIENT_LIGHT as i32, sys::rs2...
identifier_body
mixture.rs
use itertools::{ Either, EitherOrBoth::{Both, Left, Right}, Itertools, }; use std::{ cell::Cell, sync::atomic::{AtomicU64, Ordering::Relaxed}, }; use tinyvec::TinyVec; use crate::reaction::ReactionIdentifier; use super::{ constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasI...
reactions .iter() .filter_map(|r| r.check_conditions(self).then(|| r.get_id())) .collect() }) } /// Returns a tuple with oxidation power and fuel amount of this gas mixture. pub fn get_burnability(&self) -> (f32, f32) { use crate::types::FireInfo; super::with_gas_info(|gas_info| { self.moles ...
} /// Gets all of the reactions this mix should do. pub fn all_reactable(&self) -> Vec<ReactionIdentifier> { with_reactions(|reactions| {
random_line_split
mixture.rs
use itertools::{ Either, EitherOrBoth::{Both, Left, Right}, Itertools, }; use std::{ cell::Cell, sync::atomic::{AtomicU64, Ordering::Relaxed}, }; use tinyvec::TinyVec; use crate::reaction::ReactionIdentifier; use super::{ constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasI...
FireInfo::Fuel(fire) => { if self.temperature > fire.temperature() { let amount = amt * (1.0 - fire.temperature() / self.temperature).max(0.0); acc.1 += amount / fire.burn_rate(); } } FireInfo::None => (), } } acc }) }) } /// Retu...
{ if self.temperature > oxidation.temperature() { let amount = amt * (1.0 - oxidation.temperature() / self.temperature) .max(0.0); acc.0 += amount * oxidation.power(); } }
conditional_block
mixture.rs
use itertools::{ Either, EitherOrBoth::{Both, Left, Right}, Itertools, }; use std::{ cell::Cell, sync::atomic::{AtomicU64, Ordering::Relaxed}, }; use tinyvec::TinyVec; use crate::reaction::ReactionIdentifier; use super::{ constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasI...
/// Merges one gas mixture into another. pub fn merge(&mut self, giver: &Self) { if self.immutable { return; } let our_heat_capacity = self.heat_capacity(); let other_heat_capacity = giver.heat_capacity(); self.maybe_expand(giver.moles.len()); for (a, b) in self.moles.iter_mut().zip(giver.moles.iter()...
{ self.heat_capacity() * self.temperature }
identifier_body
mixture.rs
use itertools::{ Either, EitherOrBoth::{Both, Left, Right}, Itertools, }; use std::{ cell::Cell, sync::atomic::{AtomicU64, Ordering::Relaxed}, }; use tinyvec::TinyVec; use crate::reaction::ReactionIdentifier; use super::{ constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasI...
(&mut self, heat: f32) { let cap = self.heat_capacity(); self.set_temperature(((cap * self.temperature) + heat) / cap); } /// Returns true if there's a visible gas in this mix. pub fn is_visible(&self) -> bool { self.enumerate() .any(|(i, gas)| gas_visibility(i as usize).map_or(false, |amt| gas >= amt)) } ...
adjust_heat
identifier_name
object.rs
//! Represents an object in PHP. Allows for overriding the internal object used //! by classes, allowing users to store Rust data inside a PHP object. use std::{convert::TryInto, fmt::Debug, ops::DerefMut}; use crate::{ boxed::{ZBox, ZBoxable}, class::RegisteredClass, convert::{FromZendObject, FromZval, F...
(zval: &'a Zval) -> Option<Self> { zval.object() } } impl<'a> FromZvalMut<'a> for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> { zval.object_mut() } } impl IntoZval for ZBox<ZendObject> { const TYPE: DataT...
from_zval
identifier_name
object.rs
//! Represents an object in PHP. Allows for overriding the internal object used //! by classes, allowing users to store Rust data inside a PHP object. use std::{convert::TryInto, fmt::Debug, ops::DerefMut}; use crate::{ boxed::{ZBox, ZBoxable}, class::RegisteredClass, convert::{FromZendObject, FromZval, F...
.as_ref() } .ok_or(Error::InvalidScope)?; T::from_zval(zv).ok_or_else(|| Error::ZvalConversion(zv.get_type())) } /// Attempts to set a property on the object. /// /// # Parameters /// /// * `name` - The name of the property. /// * `value` - The value to se...
&mut rv, )
random_line_split
object.rs
//! Represents an object in PHP. Allows for overriding the internal object used //! by classes, allowing users to store Rust data inside a PHP object. use std::{convert::TryInto, fmt::Debug, ops::DerefMut}; use crate::{ boxed::{ZBox, ZBoxable}, class::RegisteredClass, convert::{FromZendObject, FromZval, F...
} } impl<T: RegisteredClass> From<ZBox<ZendClassObject<T>>> for ZBox<ZendObject> { #[inline] fn from(obj: ZBox<ZendClassObject<T>>) -> Self { ZendObject::from_class_object(obj) } } /// Different ways to query if a property exists. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[repr(...
{ // TODO: become an error let class_name = obj.get_class_name(); panic!( "{}::__toString() must return a string", class_name.expect("unable to determine class name"), ); }
conditional_block
object.rs
//! Represents an object in PHP. Allows for overriding the internal object used //! by classes, allowing users to store Rust data inside a PHP object. use std::{convert::TryInto, fmt::Debug, ops::DerefMut}; use crate::{ boxed::{ZBox, ZBoxable}, class::RegisteredClass, convert::{FromZendObject, FromZval, F...
} impl FromZendObject<'_> for String { fn from_zend_object(obj: &ZendObject) -> Result<Self> { let mut ret = Zval::new(); unsafe { zend_call_known_function( (*obj.ce).__tostring, obj as *const _ as *mut _, obj.ce, &mut ret...
{ zv.set_object(self); Ok(()) }
identifier_body
public_key.rs
use crate::key::{KeyError, PublicKey}; use crate::ssh::decode::SshComplexTypeDecode; use crate::ssh::encode::SshComplexTypeEncode; use std::str::FromStr; use std::{io, string}; use thiserror::Error; #[derive(Debug, Error)] pub enum SshPublicKeyError { #[error(transparent)] IoError(#[from] io::Error), #[er...
pub struct SshPublicKey { pub inner_key: SshBasePublicKey, pub comment: String, } impl SshPublicKey { pub fn to_string(&self) -> Result<String, SshPublicKeyError> { let mut buffer = Vec::with_capacity(1024); self.encode(&mut buffer)?; Ok(String::from_utf8(buffer)?) } } impl Fro...
random_line_split
public_key.rs
use crate::key::{KeyError, PublicKey}; use crate::ssh::decode::SshComplexTypeDecode; use crate::ssh::encode::SshComplexTypeEncode; use std::str::FromStr; use std::{io, string}; use thiserror::Error; #[derive(Debug, Error)] pub enum SshPublicKeyError { #[error(transparent)] IoError(#[from] io::Error), #[er...
() { // ssh-keygen -t rsa -b 2048 -C "test2@picky.com" let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI9ht2g2qOPgSG5huVYjFUouyaw59/6QuQqUVGwgnITlhRbM+bkvJQfcuiqcv+vD9/86Dfugk79sSfg/aVK+V/plqAAZoujz/wALDjEphSxAUcAR+t4i2F39Pa71MSc37I9L30z31tcba1X7od7hzrVMl9iurkOyBC4xcIWa1H8h0mDyoXyWPTqoTONDU...
decode_ssh_rsa_2048_public_key
identifier_name
public_key.rs
use crate::key::{KeyError, PublicKey}; use crate::ssh::decode::SshComplexTypeDecode; use crate::ssh::encode::SshComplexTypeEncode; use std::str::FromStr; use std::{io, string}; use thiserror::Error; #[derive(Debug, Error)] pub enum SshPublicKeyError { #[error(transparent)] IoError(#[from] io::Error), #[er...
#[test] fn ed25519_roundtrip() { let public_key = SshPublicKey::from_str(test_files::SSH_PUBLIC_KEY_ED25519).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(test_files::SSH_PUBLIC_KEY_ED25519, ssh_public_key_after.as_str()); } }
{ let public_key = SshPublicKey::from_str(key_str).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(key_str, ssh_public_key_after.as_str()); }
identifier_body
exception.rs
// Copyright 2020 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
impl ErrorCode { pub fn from_std_error<T: std::error::Error>(error: T) -> Self { ErrorCode { code: 1002, display_text: format!("{}", error), cause: None, backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))), } } pub fn crea...
error )) } }
random_line_split
exception.rs
// Copyright 2020 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
(error: std::num::ParseIntError) -> Self { ErrorCode::from_std_error(error) } } impl From<std::num::ParseFloatError> for ErrorCode { fn from(error: std::num::ParseFloatError) -> Self { ErrorCode::from_std_error(error) } } impl From<common_arrow::arrow::error::ArrowError> for ErrorCode { ...
from
identifier_name
exception.rs
// Copyright 2020 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
} impl From<std::num::ParseFloatError> for ErrorCode { fn from(error: std::num::ParseFloatError) -> Self { ErrorCode::from_std_error(error) } } impl From<common_arrow::arrow::error::ArrowError> for ErrorCode { fn from(error: common_arrow::arrow::error::ArrowError) -> Self { ErrorCode::fro...
{ ErrorCode::from_std_error(error) }
identifier_body
mailbox.rs
// use byteorder::{ByteOrder, NativeEndian}; use core::{ convert::TryInto, fmt, mem, ops, slice, sync::atomic::{fence, Ordering}, }; use field_offset::offset_of; use super::mmu::align_up; const MAIL_BASE: usize = 0xB880; const MAIL_FULL: u32 = 0x8000_0000; const MAIL_EMPTY: u32 = 0x4000_0000; // const M...
(base: usize, offset: u8, value: u32) { ((MAPPED_REGISTERS_BASE + base + offset as usize) as *mut u32).write_volatile(value) } unsafe fn read_mailbox(channel: u8) -> u32 { // 1. Read the status register until the empty flag is not set. // 2. Read data from the read register. // 3. If the lower four bit...
write_reg
identifier_name
mailbox.rs
// use byteorder::{ByteOrder, NativeEndian}; use core::{ convert::TryInto, fmt, mem, ops, slice, sync::atomic::{fence, Ordering}, }; use field_offset::offset_of; use super::mmu::align_up; const MAIL_BASE: usize = 0xB880; const MAIL_FULL: u32 = 0x8000_0000; const MAIL_EMPTY: u32 = 0x4000_0000; // const M...
limit -= 1; } write_reg(MAIL_BASE, MAILBOX_OFFFSETS.write, data | (channel as u32)); fence(Ordering::SeqCst); // println!("Finished writing to mailbox"); } pub trait PropertyTagList: Sized { fn prepare(self) -> PropertyMessageWrapper<Self> { PropertyMessageWrapper::new(self) } ...
{ panic!( "Gave up waiting for space to write to mailbox (channel {}, data: 0x{:08x})", channel, data ); }
conditional_block
mailbox.rs
// use byteorder::{ByteOrder, NativeEndian}; use core::{ convert::TryInto, fmt, mem, ops, slice, sync::atomic::{fence, Ordering}, }; use field_offset::offset_of; use super::mmu::align_up; const MAIL_BASE: usize = 0xB880; const MAIL_FULL: u32 = 0x8000_0000; const MAIL_EMPTY: u32 = 0x4000_0000; // const M...
#[repr(u8)] #[derive(Copy, Clone, Debug)] pub enum Channel { Power = 0, Framebuffer = 1, VirtualUART = 2, VCHIQ = 3, LEDs = 4, Buttons = 5, TouchScreen = 6, Unknown7 = 7, PropertyTagsSend = 8, PropertyTagsReceive = 9, }
{ let resp: u32; let msg_ptr = msg as *mut T; let msg_addr_usize = msg_ptr as usize; let msg_addr_u32 = msg_addr_usize.try_into().map_err(|_| ())?; unsafe { write_mailbox(channel as u8, msg_addr_u32); resp = read_mailbox(channel as u8); } // println!( // "Got response...
identifier_body
mailbox.rs
// use byteorder::{ByteOrder, NativeEndian}; use core::{ convert::TryInto, fmt, mem, ops, slice, sync::atomic::{fence, Ordering}, }; use field_offset::offset_of; use super::mmu::align_up; const MAIL_BASE: usize = 0xB880; const MAIL_FULL: u32 = 0x8000_0000; const MAIL_EMPTY: u32 = 0x4000_0000; // const M...
// Check the channel (lowest 4 bits) of the read value for the correct channel // If the channel is not the one we wish to read from (i.e: 1), go to step 1 // Return the data (i.e: the read value >> 4) // println!("Reading mailbox (want channel {})", channel); let mut limit = 10; loop { ...
// Execute a memory barrier // Read from MAIL0_READ
random_line_split
internal.rs
extern crate proc_macro; use ink_lang_ir::Callable; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, }; use std::{ collections::HashMap, convert::TryFrom, }; use syn::{ ext::IdentExt, parenthesized, parse::{ Parse, ...
let external_ink_methods_iter = ink_methods.iter_mut().map(|(_, value)| { value.sig.ident = format_ident!("{}_{}{}", BRUSH_PREFIX, value.sig.ident, EXTERNAL_METHOD_SUFFIX); value }); let external_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, EXTERNAL_TRAIT_SUFFIX); /...
{ let name = format!("{}", trait_name.unwrap()); metadata_name_attr = quote! { #[ink(metadata_name = #name)] } }
conditional_block
internal.rs
extern crate proc_macro; use ink_lang_ir::Callable; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, }; use std::{ collections::HashMap, convert::TryFrom, }; use syn::{ ext::IdentExt, parenthesized,
Parse, ParseStream, }, ItemImpl, }; use crate::{ metadata::Metadata, trait_definition::{ EXTERNAL_METHOD_SUFFIX, EXTERNAL_TRAIT_SUFFIX, WRAPPER_TRAIT_SUFFIX, }, }; pub(crate) const BRUSH_PREFIX: &'static str = "__brush"; pub(crate) struct MetaList { pub...
parse::{
random_line_split
internal.rs
extern crate proc_macro; use ink_lang_ir::Callable; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, }; use std::{ collections::HashMap, convert::TryFrom, }; use syn::{ ext::IdentExt, parenthesized, parse::{ Parse, ...
(input: ParseStream) -> syn::Result<Self> { let path = input.call(parse_meta_path)?; parse_meta_list_after_path(path, input) } } pub(crate) enum NestedMeta { Path(syn::Path), List(MetaList), } impl Parse for NestedMeta { fn parse(input: ParseStream) -> syn::Result<Self> { let p...
parse
identifier_name
internal.rs
extern crate proc_macro; use ink_lang_ir::Callable; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, }; use std::{ collections::HashMap, convert::TryFrom, }; use syn::{ ext::IdentExt, parenthesized, parse::{ Parse, ...
}, }) } fn parse_meta_list_after_path(path: syn::Path, input: ParseStream) -> syn::Result<MetaList> { let content; Ok(MetaList { path, _paren_token: parenthesized!(content in input), nested: content.parse_terminated(TokenStream2::parse)?, }) } fn parse_meta_after_path(...
{ Ok(syn::Path { leading_colon: input.parse()?, segments: { let mut segments = syn::punctuated::Punctuated::new(); while input.peek(syn::Ident::peek_any) { let ident = syn::Ident::parse_any(input)?; segments.push_value(syn::PathSegment::from(id...
identifier_body
main.rs
extern crate ginseng; use ginseng::guest::Guest; use ginseng::guest::Range; use std::cmp::min; use std::cmp::Ordering; use std:collections::HashMap; use std::vec::Vec; fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64 { let mut total_welfare: u64 = 0; for (guest, allocation) in proposed_al...
(proposed_allocations: &Vec<(&Guest, u64)>) -> Vec<(usize, Range)> { let mut violations: Vec<(usize, Range)> = Vec::new(); let mut index: usize = 0; for &(guest, amount) in proposed_allocations.iter() { // we want to get the guest's forbidden range with the greatest // min value that is...
invalid_allocations
identifier_name
main.rs
extern crate ginseng; use ginseng::guest::Guest; use ginseng::guest::Range; use std::cmp::min; use std::cmp::Ordering; use std:collections::HashMap; use std::vec::Vec; fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64 { let mut total_welfare: u64 = 0; for (guest, allocation) in proposed_al...
.forbidden_ranges .last() .filter(|range| {range.max == u64::max_value()}) .map(|range| {range.min}) .unwrap_or(u64::max_value()); let mem_to_alloc = min(remaining_memory, upper_bound); ...
{ let mut remaining_memory: u64 = available_memory; guest_list.iter().map ( |guest| { // if there's no memory left to hand out our job is simple if remaining_memory == 0 { 0 } // otherwise get the maximum amount mem...
identifier_body
main.rs
extern crate ginseng; use ginseng::guest::Guest; use ginseng::guest::Range; use std::cmp::min; use std::cmp::Ordering; use std:collections::HashMap; use std::vec::Vec; fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64 { let mut total_welfare: u64 = 0; for (guest, allocation) in proposed_al...
// which should be checked after getting the result of this // function // I think what I really want to return from this is a vector of allocation amounts // it'll even take up less space than (reference, allocation) pairs and will be much // less problematic fn naive_allocation ( guest_list: &Vec<&Guest>, av...
random_line_split
map.rs
use super::BareDoomMap; use super::geom::{Coord, Point, Rect, Size}; use std::collections::HashMap; use std::marker::PhantomData; use std; // TODO // map diagnostics // - error: // - info: unused vertex // - info: unused side // - info: sector with no sides // - info: thing not in the map (polyobjs excluded) /// A...
(&self) -> (Handle<Vertex>, Handle<Vertex>) { self.0.vertex_indices() } pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) { self.0.side_indices() } pub fn has_special(&self) -> bool { self.0.has_special() } pub fn blocks_player(&self) -> bool {...
vertex_indices
identifier_name
map.rs
use super::BareDoomMap; use super::geom::{Coord, Point, Rect, Size}; use std::collections::HashMap; use std::marker::PhantomData; use std; // TODO // map diagnostics // - error: // - info: unused vertex // - info: unused side // - info: sector with no sides // - info: thing not in the map (polyobjs excluded) /// A...
} } impl<T> From<usize> for Handle<T> { fn from(index: usize) -> Self { Handle(index, PhantomData) } } trait MapComponent {} pub struct Thing { point: Point, doomednum: u32, } impl Thing { pub fn point(&self) -> Point { self.point } pub fn doomednum(&self) -> u32 { ...
random_line_split
map.rs
use super::BareDoomMap; use super::geom::{Coord, Point, Rect, Size}; use std::collections::HashMap; use std::marker::PhantomData; use std; // TODO // map diagnostics // - error: // - info: unused vertex // - info: unused side // - info: sector with no sides // - info: thing not in the map (polyobjs excluded) /// A...
pub fn iter_things(&self) -> std::slice::Iter<Thing> { self.things.iter() } pub fn vertex(&self, handle: Handle<Vertex>) -> &Vertex { &self.vertices[handle.0] } pub fn side(&self, handle: Handle<Side>) -> &Side { &self.sides[handle.0] } pub fn sector(&self, handle...
{ self.sectors.iter() }
identifier_body
syncmgr.rs
PeerId, BlockHash), /// Syncing headers. Syncing { /// Current block header height. current: Height, /// Best known block header height. best: Height, }, /// Synced up to the specified hash and height. Synced(BlockHash, Height), /// Potential stale tip detected on...
pub fn new(config: Config, rng: fastrand::Rng, upstream: U, clock: C) -> Self { let peers = AddressBook::new(rng.clone()); let last_tip_update = None; let last_peer_sample = None; let last_idle = None; let inflight = HashMap::with_hasher(rng.into()); Self { ...
impl<U: SetTimer + Disconnect + Wire<Event>, C: Clock> SyncManager<U, C> { /// Create a new sync manager.
random_line_split
syncmgr.rs
{ /// A block was added to the main chain. BlockConnected { /// Block height. height: Height, /// Block header. header: BlockHeader, }, /// A block was removed from the main chain. BlockDisconnected { /// Block height. height: Height, /// Bloc...
Event
identifier_name
syncmgr.rs
, BlockHash), /// Syncing headers. Syncing { /// Current block header height. current: Height, /// Best known block header height. best: Height, }, /// Synced up to the specified hash and height. Synced(BlockHash, Height), /// Potential stale tip detected on the a...
/// Called when a peer disconnected. pub fn peer_disconnected(&mut self, id: &PeerId) { self.unregister(id); } /// Called when we received a `getheaders` message from a peer. pub fn received_getheaders<T: BlockReader>( &mut self, addr: &PeerId, (locator_hashes, sto...
{ if link.is_outbound() && !services.has(REQUIRED_SERVICES) { return; } if height > self.best_height().unwrap_or_else(|| tree.height()) { self.upstream.event(Event::PeerHeightUpdated { height }); } self.register(socket, height, preferred, link); ...
identifier_body
syncmgr.rs
, BlockHash), /// Syncing headers. Syncing { /// Current block header height. current: Height, /// Best known block header height. best: Height, }, /// Synced up to the specified hash and height. Synced(BlockHash, Height), /// Potential stale tip detected on the a...
None
{ return Some(time); }
conditional_block
smt.rs
use std::sync::Arc; use anyhow::Result; use criterion::{criterion_group, BenchmarkId, Criterion, Throughput}; use gw_builtin_binaries::{file_checksum, Resource}; use gw_common::{ blake2b::new_blake2b, builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID}, registry_address::RegistryAddress, state::St...
(c: &mut Criterion) { let config = StoreConfig { path: "./smt_data/db".parse().unwrap(), options_file: Some("./smt_data/db.toml".parse().unwrap()), cache_size: Some(1073741824), }; let store = Store::open(&config, COLUMNS).unwrap(); let ee = BenchExecutionEnvironment::new_with_ac...
bench_ckb_transfer
identifier_name
smt.rs
use std::sync::Arc; use anyhow::Result; use criterion::{criterion_group, BenchmarkId, Criterion, Throughput}; use gw_builtin_binaries::{file_checksum, Resource}; use gw_common::{ blake2b::new_blake2b, builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID}, registry_address::RegistryAddress, state::St...
// meta contract const META_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/meta-contract-generator"; const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32]; // sudt contract const SUDT_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generat...
random_line_split
smt.rs
use std::sync::Arc; use anyhow::Result; use criterion::{criterion_group, BenchmarkId, Criterion, Throughput}; use gw_builtin_binaries::{file_checksum, Resource}; use gw_common::{ blake2b::new_blake2b, builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID}, registry_address::RegistryAddress, state::St...
} struct BenchExecutionEnvironment { generator: Generator, chain: BenchChain, mem_pool_state: MemPoolState, } impl BenchExecutionEnvironment { fn new_with_accounts(store: Store, accounts: u32) -> Self { let genesis_config = GenesisConfig { meta_contract_validator_type_hash: META_V...
{ unreachable!("bench chain store") }
identifier_body
smt.rs
use std::sync::Arc; use anyhow::Result; use criterion::{criterion_group, BenchmarkId, Criterion, Throughput}; use gw_builtin_binaries::{file_checksum, Resource}; use gw_common::{ blake2b::new_blake2b, builtins::{CKB_SUDT_ACCOUNT_ID, ETH_REGISTRY_ACCOUNT_ID}, registry_address::RegistryAddress, state::St...
} let mut db = store.begin_transaction(); db.setup_chain_id(ROLLUP_TYPE_HASH).unwrap(); let (mut db, genesis_state) = build_genesis_from_store(db, config, Default::default()).unwrap(); let smt = db .state_smt_with_merkle_state(genesis_state.genesis.raw()...
{ panic!("store genesis already initialized"); }
conditional_block
stream.rs
// Copyright 2016 Jeffrey Burdges. //! Sphinx header symmetric cryptographic routines //! //!... use std::fmt; use std::ops::Range; use std::marker::PhantomData; // use clear_on_drop::ClearOnDrop; use crypto::mac::Mac; use crypto::poly1305::Poly1305; use chacha::ChaCha as ChaCha20; use keystream::{KeyStream,Seeka...
(&self, beta: &[u8]) -> SphinxResult<Gamma> { if beta.len()!= P::BETA_LENGTH as usize { return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") ); } // According to the current API gamma_out lies in a buffer supplied // by our caller, so no need for ...
create_gamma
identifier_name
stream.rs
// Copyright 2016 Jeffrey Burdges. //! Sphinx header symmetric cryptographic routines //! //!... use std::fmt; use std::ops::Range; use std::marker::PhantomData; // use clear_on_drop::ClearOnDrop; use crypto::mac::Mac; use crypto::poly1305::Poly1305; use chacha::ChaCha as ChaCha20; use keystream::{KeyStream,Seeka...
self.stream.seek_to(self.chunks.surb_log.start as u64).unwrap(); self.stream.xor_read(surb_log).unwrap(); Ok(()) } /// Sender's sugested delay for this packet. pub fn delay(&mut self) -> ::std::time::Duration { use rand::{ChaChaRng, SeedableRng}; // Rng, Rand let mu...
{ return Err( SphinxError::InternalError("SURB log too long!") ); }
conditional_block
stream.rs
// Copyright 2016 Jeffrey Burdges. //! Sphinx header symmetric cryptographic routines //! //!... use std::fmt; use std::ops::Range; use std::marker::PhantomData; // use clear_on_drop::ClearOnDrop; use crypto::mac::Mac; use crypto::poly1305::Poly1305; use chacha::ChaCha as ChaCha20; use keystream::{KeyStream,Seeka...
/// Verify the poly1305 MAC `Gamma` given in a Sphinx packet. /// /// Returns an InvalidMac error if the check fails. Does not /// verify the lengths of Beta or the SURB. pub fn verify_gamma(&self, beta: &[u8], gamma_given: &Gamma) -> SphinxResult<()> { let gamma_found = self.create...
{ if beta.len() != P::BETA_LENGTH as usize { return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") ); } // According to the current API gamma_out lies in a buffer supplied // by our caller, so no need for games to zero it here. let mut gamm...
identifier_body
stream.rs
// Copyright 2016 Jeffrey Burdges. //! Sphinx header symmetric cryptographic routines //! //!... use std::fmt; use std::ops::Range; use std::marker::PhantomData; // use clear_on_drop::ClearOnDrop; use crypto::mac::Mac; use crypto::poly1305::Poly1305; use chacha::ChaCha as ChaCha20; use keystream::{KeyStream,Seeka...
/// Initalize our IETF ChaCha20 stream cipher by invoking /// `ChaChaKnN::header_cipher` with our paramaters `P: Params`. pub fn header_cipher(&self) -> SphinxResult<HeaderCipher<P>> { self.chacha.header_cipher::<P>() } } /// Amount of key stream consumed by `hop()` itself const HOP_EATS : usi...
} }
random_line_split
main.rs
use crate::avro_encode::encode; use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema}; use avro_rs::types::Value; use avro_rs::{from_value, types::Record, Codec, Reader, Writer}; use clap::{App, Arg}; use failure::bail; use failure::Error; use futures::StreamExt; use futures_util::future::FutureExt...
]))), ), ]); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let mut body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); encode(&record, &schema, &mut body); Ok(body) } fn deserialize(bytes: &Ve...
{ let schema = get_schema(); let mut writer = Writer::new(&schema, Vec::new()); let record = Value::Record(vec![ ( "before".to_string(), Value::Union(Box::new(Value::Record(vec![ ("FirstName".to_string(), Value::String("Greg".to_string())), ("...
identifier_body
main.rs
use crate::avro_encode::encode; use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema}; use avro_rs::types::Value; use avro_rs::{from_value, types::Record, Codec, Reader, Writer}; use clap::{App, Arg}; use failure::bail; use failure::Error; use futures::StreamExt; use futures_util::future::FutureExt...
() { let matches = App::new("consumer example") .version(option_env!("CARGO_PKG_VERSION").unwrap_or("")) .about("Simple command line consumer") .arg( Arg::with_name("brokers") .short("b") .long("brokers") .help("Broker list in kafka forma...
main
identifier_name
main.rs
use crate::avro_encode::encode; use avro_rs::schema::{RecordField, Schema, SchemaFingerprint, UnionSchema}; use avro_rs::types::Value; use avro_rs::{from_value, types::Record, Codec, Reader, Writer}; use clap::{App, Arg}; use failure::bail; use failure::Error; use futures::StreamExt; use futures_util::future::FutureExt...
let input = writer.into_inner(); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); let output = [&body[..], &input[..]].concat(); Ok(output) } fn serialize2() -...
random_line_split
cogroup.rs
//! Group records by a key, and apply a reduction function. //! //! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records //! with the same key, and apply user supplied functions to the key and a list of values, which are //! expected to populate a list of output values. //! //!...
} // we may need to produce output at index let mut session = output.session(&index); // 2b. We must now determine for each interesting key at this time, how does the // currently reported output match up with what we need as ou...
{ for key in &compact.keys { stash.push(index.clone()); source2.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clon...
conditional_block
cogroup.rs
//! Group records by a key, and apply a reduction function. //! //! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records //! with the same key, and apply user supplied functions to the key and a list of values, which are //! expected to populate a list of output values. //! //!...
if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source2.interesting_times(key, &index, &mut stash); for time in &stash { ...
vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) };
random_line_split
cogroup.rs
//! Group records by a key, and apply a reduction function. //! //! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records //! with the same key, and apply user supplied functions to the key and a list of values, which are //! expected to populate a list of output values. //! //!...
< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)...
cogroup_by_inner
identifier_name
cogroup.rs
//! Group records by a key, and apply a reduction function. //! //! The `group` operators act on data that can be viewed as pairs `(key, val)`. They group records //! with the same key, and apply user supplied functions to the key and a list of values, which are //! expected to populate a list of output values. //! //!...
// create an exchange channel based on the supplied Fn(&D1)->u64. let exch1 = Exchange::new(move |&((ref k, _),_)| key_1(k).as_u64()); let exch2 = Exchange::new(move |&((ref k, _),_)| key_2(k).as_u64()); let mut sorter1 = LSBRadixSorter::new(); let mut sorter2 = LSBRadixSorter::...
{ let mut source1 = Trace::new(look(0)); let mut source2 = Trace::new(look(0)); let mut result = Trace::new(look(0)); // A map from times to received (key, val, wgt) triples. let mut inputs1 = Vec::new(); let mut inputs2 = Vec::new(); // A map from times to a l...
identifier_body
mod.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::io; #...
(&self) -> *const kvm_cpuid2 { &self.kvm_cpuid[0] } /// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_mut_ptr(&mut self) -> *mut kvm_cpuid2 { &mut self.kvm_cpuid[0] } } /// Safe wrapper over the `kvm_run` struct. /// /// The wr...
as_ptr
identifier_name
mod.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::io; #...
Ok(KvmRunWrapper { kvm_run_ptr: addr as *mut u8, mmap_size: size, }) } /// Returns a mutable reference to `kvm_run`. /// #[allow(clippy::mut_from_ref)] pub fn as_mut_ref(&self) -> &mut kvm_run { // Safe because we know we mapped enough memory to hol...
{ return Err(io::Error::last_os_error()); }
conditional_block
mod.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::io; #...
/// Get a pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_ptr(&self) -> *const kvm_cpuid2 { &self.kvm_cpuid[0] } /// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_mut_ptr(&mut self) -> *...
{ // Mapping the unsized array to a slice is unsafe because the length isn't known. Using // the length we originally allocated with eliminates the possibility of overflow. if self.kvm_cpuid[0].nent as usize > self.allocated_len { self.kvm_cpuid[0].nent = self.allocated_len as u32; ...
identifier_body
mod.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use std::io; #...
CpuId { kvm_cpuid, allocated_len: entries.len(), } } /// Returns the mutable entries slice so they can be modified before passing to the VCPU. /// /// # Example /// ```rust /// use kvm_ioctls::{CpuId, Kvm, MAX_KVM_CPUID_ENTRIES}; /// let kvm = Kvm::n...
random_line_split
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileSer...
( &self, path: &PathBuf, buffer: &mut Vec<u8>, ) -> Option<FileFingerprint> { let i = self.ignored_header_bytes as u64; let b = self.fingerprint_bytes; buffer.resize(b, 0u8); if let Ok(mut fp) = fs::File::open(path) { if fp.seek(SeekFrom::Start(i))...
get_fingerprint_of_file
identifier_name
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileSer...
.exclude .iter() .map(|e| Pattern::new(e.to_str().expect("no ability to glob")).unwrap()) .collect::<Vec<_>>(); for (_file_id, watcher) in &mut fp_map { watcher.set_file_findable(false); // assume not findable until found ...
{ let mut line_buffer = Vec::new(); let mut fingerprint_buffer = Vec::new(); let mut fp_map: HashMap<FileFingerprint, FileWatcher> = Default::default(); let mut backoff_cap: usize = 1; let mut lines = Vec::new(); let mut start_of_run = true; // Alright friends, ...
identifier_body
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileSer...
if old_modified_time < new_modified_time { info!( message = "Switching to watch most recently modified file.", new_modified_...
{ // matches a file with a different path if !was_found_this_cycle { info!( message = "Watched file has been renamed.", ...
conditional_block
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileSer...
let mut start_of_run = true; // Alright friends, how does this work? // // We want to avoid burning up users' CPUs. To do this we sleep after // reading lines out of files. But! We want to be responsive as well. We // keep track of a 'backoff_cap' to decide how long we'll...
let mut backoff_cap: usize = 1; let mut lines = Vec::new();
random_line_split
debug.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
; let typed_value = TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema); let (value, _) = typed_value.to_edn_value_pair(); let tx: i64 = row.get(4)?; let added: bool = row.get(5)?; Ok(Datom { e: Ent...
{ ValueType::Long.value_type_tag() }
conditional_block
debug.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
<I>( &mut self, terms: I, tempid_set: InternSet<TempId>, ) -> Result<TxReport> where I: IntoIterator<Item = TermWithTempIds>, { let details = { // The block scopes the borrow of self.sqlite. // We're about to write, so go straight ahead and get...
transact_simple_terms
identifier_name
debug.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
params: &[&dyn ToSql], ) -> Result<String> { let mut stmt: rusqlite::Statement = conn.prepare(sql)?; let mut tw = TabWriter::new(Vec::new()).padding(2); writeln!(&mut tw, "{}", sql).unwrap(); for column_name in stmt.column_names() { write!(&mut tw, "{}\t", column_name).unwrap(); } ...
sql: &str,
random_line_split
hkdf.rs
// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
34007208d5b887185865 "), }, Test { // Test Case 2 ikm: &hex!(" 000102030405060708090a0b0c0d0e0f 101112131415161718191a1b1c1d1e1f 202122232425262728292a2b2c2d2e2f ...
random_line_split
hkdf.rs
// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {} const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160 /// pub struct Test<'a> { ikm: &'a [u8], salt: &'a [u8], info: &'a [u8], okm: &'a [u8], } /// data taken from sample code in Readme of crates.io page pub fn basic_test_hkdf<C...
hkdf_test_cases
identifier_name
hkdf.rs
// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
} } } fn run_test<K: Hkdf>(ikm: &[u8], salt: &[u8], info: &[u8], okm: &[u8]) -> Option<&'static str> { let prk = K::new(Some(salt), ikm); let mut got_okm = vec![0; okm.len()]; if prk.expand(info, &mut got_okm).is_err() { return Some("prk expand"); } if got_okm!= okm { ...
{ panic!( "\n\ Failed test {tc_id}: {desc}\n\ ikm:\t{ikm:?}\n\ salt:\t{salt:?}\n\ info:\t{info:?}\n\ okm:\t{okm:?}\n" ); }
conditional_block
msg.rs
use super::{nlmsg_length, nlmsg_header_length}; use std::fmt; use std::mem::size_of; use std::slice::from_raw_parts; use std::io::{self, ErrorKind, Cursor}; use byteorder::{NativeEndian, ReadBytesExt}; #[derive(Clone, Copy, Debug)] pub enum MsgType { /// Request Request, /// No op Noop, /// Error ...
(&mut self) -> &mut NlMsgHeader { self.flags |= GetFlags::Dump.into(); self } } /* http://linux.die.net/include/linux/netlink.h /* Flags values */ #define NLM_F_REQUEST 1 /* It is request message. */ #define NLM_F_MULTI 2 /* Multipart message, terminated by NLMSG_DONE */ #define NL...
dump
identifier_name
msg.rs
use super::{nlmsg_length, nlmsg_header_length}; use std::fmt; use std::mem::size_of; use std::slice::from_raw_parts; use std::io::{self, ErrorKind, Cursor}; use byteorder::{NativeEndian, ReadBytesExt}; #[derive(Clone, Copy, Debug)] pub enum MsgType { /// Request Request, /// No op Noop, /// Error ...
nl_type: u16, flags: u16, seq: u32, pid: u32, } impl fmt::Debug for NlMsgHeader { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "<NlMsgHeader len={} {:?} flags=[ ", self.msg_length, MsgType::from(self.nl_typ...
random_line_split
msg.rs
use super::{nlmsg_length, nlmsg_header_length}; use std::fmt; use std::mem::size_of; use std::slice::from_raw_parts; use std::io::{self, ErrorKind, Cursor}; use byteorder::{NativeEndian, ReadBytesExt}; #[derive(Clone, Copy, Debug)] pub enum MsgType { /// Request Request, /// No op Noop, /// Error ...
pub fn done() -> NlMsgHeader { NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Done.into(), flags: Flags::Multi.into(), seq: 0, pid: 0, } } pub fn error() -> NlMsgHeader { NlMsgHeader { ...
{ NlMsgHeader { msg_length: nlmsg_header_length() as u32, nl_type: MsgType::Request.into(), flags: Flags::Request.into(), seq: 0, pid: 0, } }
identifier_body
main.rs
error::Error; use std::fs; use std::path::{Path,PathBuf}; use metadata::MetaObject; use history::Restorable; macro_rules! err_write { ($s: tt) => { writeln!(std::io::stderr(), $s).ok().unwrap_or(())}; ($s: tt, $($e: expr),*) => { writeln!(std::io::stderr(), $s, $($e,)*).ok().unwrap_or(())} } ...
(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_clean(args: &clap::ArgMatches, opts: &GlobalOptions) { unimplemented!() } fn do_snap(args: &clap::ArgMatches, opts: &GlobalOptions) { let remote = args.value_of("remote").unwrap().to_owned(); let snap_paths: Vec<&str> = args.va...
do_stat
identifier_name
main.rs
quiet: bool } fn fail_error<E: Error>(msg: &str, err: E) { writeln!(std::io::stderr(), "bkp: {}: {}", msg, err).unwrap(); std::process::exit(1); } trait UnwrapOrFail<T> { /// Unwrap the result or fail with the given error message fn unwrap_or_fail(self, msg: &str) -> T; } impl<T, E: Error> Unwra...
random_line_split
main.rs
error::Error; use std::fs; use std::path::{Path,PathBuf}; use metadata::MetaObject; use history::Restorable; macro_rules! err_write { ($s: tt) => { writeln!(std::io::stderr(), $s).ok().unwrap_or(())}; ($s: tt, $($e: expr),*) => { writeln!(std::io::stderr(), $s, $($e,)*).ok().unwrap_or(())} } ...
(@arg password: -p --password +takes_value "Set the associated password")) (@subcommand list => (about: "List the available destinations") (@arg no_groups: -n --("no-groups") "Don't show grouped destinations")) (@subcommand remove => (about...
{ let opt_matches = clap_app!(bkp => (version: "0.1") (author: "Noah Zentzis <nzentzis@gmail.com>") (about: "Automated system backup utility") (@arg CONFIG: -c --config +takes_value "Specifies a config file to use") (@arg DATADIR: -D --data-dir +takes_value "Specify the local...
identifier_body
indexed_set.rs
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(domain_size: usize) -> Self { HybridIdxSet::Sparse(SparseIdxSet::new(), domain_size) } pub fn clear(&mut self) { let domain_size = match *self { HybridIdxSet::Sparse(_, size) => size, HybridIdxSet::Dense(_, size) => size, }; *self = HybridIdxSet::new_emp...
new_empty
identifier_name
indexed_set.rs
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
#[test] fn test_new_filled() { for i in 0..128 { let idx_buf = IdxSet::new_filled(i); let elems: Vec<usize> = idx_buf.iter().collect(); let expected: Vec<usize> = (0..i).collect(); assert_eq!(elems, expected); } }
assert_eq!(elems, expected); } } }
random_line_split
source_contributions.rs
extern crate clap; extern crate csv; extern crate reqwest; extern crate serde; extern crate failure; #[macro_use] extern crate failure_derive; use clap::{App, Arg}; use csv::StringRecord; use reqwest::{Client, Url}; use serde::de::DeserializeOwned; use serde::Deserialize; use std::{thread, time}; use std::collection...
(repo_url: &str) -> Result<(&str, &str), AppError> { match repo_url.split('/').collect::<Vec<&str>>().as_slice() { [_, "", "github.com", owner, repo] => Ok((owner, repo)), _ => Err(AppError::MetadataExtractionFailed { repo_url: repo_url.to_string(), }), } } // Extract the co...
extract_github_owner_and_repo
identifier_name
source_contributions.rs
extern crate clap; extern crate csv; extern crate reqwest; extern crate serde; extern crate failure; #[macro_use] extern crate failure_derive; use clap::{App, Arg}; use csv::StringRecord; use reqwest::{Client, Url}; use serde::de::DeserializeOwned; use serde::Deserialize; use std::{thread, time}; use std::collection...
// We retry. reqwest::StatusCode::ACCEPTED => { println!("Retrying, only {} retries left...", retries_left); thread::sleep(time::Duration::from_secs(1)); call_github( http_client, ...
{ let retries_left = retries.retries_num; if retries_left == 0 { Err(AppError::NoRetriesLeft) } else { let bearer = format!("Bearer {}", token); match http_method { HttpMethod::Get => { let url: Url = format!("{}{}", GITHUB_BASE_URL, url_path) ...
identifier_body