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
lz4.rs
use std::fs::File; use std::path::Path; use std::io::Read; let stream = File::open(&Path::new("path/to/file.lz4")).unwrap(); let mut decompressed = Vec::new(); lz4::Decoder::new(stream).read_to_end(&mut decompressed); ``` # Credit This implementation is largely based on Branimir Karadžić's implementation which can b...
# Example ```rust,ignore use compress::lz4;
random_line_split
pools.rs
use crate::*; use serde::{Deserialize, Serialize}; impl BlockFrostApi { endpoints! { /// List of registered stake pools. pools() -> Vec<String> => "/pools"; ("https://docs.blockfrost.io/#tag/Cardano-Pools/paths/~1pools/get"), /// List of already retired pools. pools_ret...
] "# } test_schema! { test_pool_delegators, Vec<PoolDelegator>, r#" [ { "address": "stake1ux4vspfvwuus9uwyp5p3f0ky7a30jq5j80jxse0fr7pa56sgn8kha", "live_stake": "1137959159981411" }, { "address": "stake1uylayej7esmarzd4mk4aru37zh9yz0luj3g9fsvgpfaxulq564r5u", ...
"ipv6": "https://stakenuts.com/mainnet.json", "dns": "relay1.stakenuts.com", "dns_srv": "_relays._tcp.relays.stakenuts.com", "port": 3001 }
random_line_split
pools.rs
use crate::*; use serde::{Deserialize, Serialize}; impl BlockFrostApi { endpoints! { /// List of registered stake pools. pools() -> Vec<String> => "/pools"; ("https://docs.blockfrost.io/#tag/Cardano-Pools/paths/~1pools/get"), /// List of already retired pools. pools_ret...
{ /// Bech32 pool ID. pub pool_id: String, /// Hexadecimal pool ID. pub hex: String, /// VRF key hash. pub vrf_key: String, /// Total minted blocks. pub blocks_minted: Integer, pub live_stake: String, pub live_size: Float, pub live_saturation: Float, pub live_delegators:...
Pool
identifier_name
chain_spec.rs
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) a...
true, true, ) } ChainSpec::from_genesis( "Darwinia IceFrog Testnet", "icefrog_testnet", icefrog_config_genesis, vec![], Some(TelemetryEndpoints::new(vec![(STAGING_TELEMETRY_URL.to_string(), 0)])), Some("DAR"), { let mut properties = Properties::new(); properties.insert("ss58Format".into(...
{ fn icefrog_config_genesis() -> GenesisConfig { darwinia_genesis( vec![ get_authority_keys_from_seed("Alice"), get_authority_keys_from_seed("Bob"), ], hex!["a60837b2782f7ffd23e95cd26d1aa8d493b8badc6636234ccd44db03c41fcc6c"].into(), // 5FpQFHfKd1xQ9HLZLQoG1JAQSCJoUEVBELnKsKNcuRLZejJR vec![ he...
identifier_body
chain_spec.rs
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) a...
; const RING_ENDOWMENT: Balance = 20_000_000 * COIN; const KTON_ENDOWMENT: Balance = 10 * COIN; const STASH: Balance = 1000 * COIN; GenesisConfig { frame_system: Some(SystemConfig { code: WASM_BINARY.to_vec(), changes_trie_config: Default::default(), }), pallet_indices: Some(IndicesConfig { ids: en...
{ vec![initial_authorities[0].clone().1, initial_authorities[1].clone().1] }
conditional_block
chain_spec.rs
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) a...
stakers: initial_authorities .iter() .map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)) .collect(), invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), slash_reward_fraction: Perbill::from_percent(10), ..Default::default() }), } } /// Staging testnet c...
pallet_staking: Some(StakingConfig { current_era: 0, validator_count: initial_authorities.len() as u32 * 2, minimum_validator_count: initial_authorities.len() as u32,
random_line_split
chain_spec.rs
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) a...
() -> GenesisConfig { darwinia_genesis( vec![ get_authority_keys_from_seed("Alice"), get_authority_keys_from_seed("Bob"), ], hex!["a60837b2782f7ffd23e95cd26d1aa8d493b8badc6636234ccd44db03c41fcc6c"].into(), // 5FpQFHfKd1xQ9HLZLQoG1JAQSCJoUEVBELnKsKNcuRLZejJR vec![ hex!["a60837b2782f7ffd23e95cd2...
icefrog_config_genesis
identifier_name
ext.rs
//! Safe wrapper around externalities invokes. use wasm_std::{ self, types::{H256, U256, Address} }; /// Generic wasm error #[derive(Debug)] pub struct Error; mod external { extern "C" { // Various call variants /// Direct/classic call. /// Corresponds to "CALL" opcode in EVM ...
/// Get the block's timestamp /// /// It can be viewed as an output of Unix's `time()` function at /// current block's inception. pub fn timestamp() -> u64 { unsafe { external::timestamp() as u64 } } /// Get the block's number /// /// This value represents number of ancestor blocks. /// The genesis block has a num...
unsafe { fetch_address(|x| external::coinbase(x) ) } }
identifier_body
ext.rs
//! Safe wrapper around externalities invokes. use wasm_std::{ self, types::{H256, U256, Address} }; /// Generic wasm error #[derive(Debug)] pub struct Error; mod external { extern "C" { // Various call variants /// Direct/classic call. /// Corresponds to "CALL" opcode in EVM ...
else { Err(Error) } } } /// Returns hash of the given block or H256::zero() /// /// Only works for 256 most recent blocks excluding current /// Returns H256::zero() in case of failure pub fn block_hash(block_number: u64) -> H256 { let mut res = H256::zero(); unsafe { external::...
{ Ok(()) }
conditional_block
ext.rs
//! Safe wrapper around externalities invokes. use wasm_std::{ self, types::{H256, U256, Address} }; /// Generic wasm error #[derive(Debug)] pub struct Error; mod external { extern "C" { // Various call variants /// Direct/classic call. /// Corresponds to "CALL" opcode in EVM ...
if external::create( endowment_arr.as_ptr(), code.as_ptr(), code.len() as u32, (&mut result).as_mut_ptr() ) == 0 { Ok(result) } else { Err(Error) } } } #[cfg(feature = "kip4")] /// Create a new account with the ...
random_line_split
ext.rs
//! Safe wrapper around externalities invokes. use wasm_std::{ self, types::{H256, U256, Address} }; /// Generic wasm error #[derive(Debug)] pub struct Error; mod external { extern "C" { // Various call variants /// Direct/classic call. /// Corresponds to "CALL" opcode in EVM ...
-> u64 { unsafe { external::blocknumber() as u64 } } /// Get the block's difficulty. pub fn difficulty() -> U256 { unsafe { fetch_u256(|x| external::difficulty(x) ) } } /// Get the block's gas limit. pub fn gas_limit() -> U256 { unsafe { fetch_u256(|x| external::gaslimit(x) ) } } #[cfg(feature = "kip6")...
ock_number()
identifier_name
async_await_basics.rs
use futures::executor::block_on; use std::thread::Thread; use std::sync::mpsc; use futures::join; use { std::{ pin::Pin, task::Waker, thread, }, }; use { futures::{ future::{FutureExt, BoxFuture}, task::{ArcWake, waker_ref}, }, std::{ future::Future, ...
{ shared_state: Arc<Mutex<SharedState>>, } /// Shared state between the future and the waiting thread struct SharedState { /// Whether or not the sleep time has elapsed completed: bool, /// The waker for the task that `TimerFuture` is running on. /// The thread can use this after setting `complet...
TimerFuture
identifier_name
async_await_basics.rs
use futures::executor::block_on; use std::thread::Thread; use std::sync::mpsc; use futures::join; use { std::{ pin::Pin, task::Waker, thread, }, }; use { futures::{ future::{FutureExt, BoxFuture}, task::{ArcWake, waker_ref}, }, std::{ future::Future, ...
// function, but we omit that here to keep things simple. shared_state.waker = Some(cx.waker().clone()); Poll::Pending } } } impl TimerFuture { /// Create a new `TimerFuture` which will complete after the provided /// timeout. pub fn new(duration: Duration) -...
// // N.B. it's possible to check for this using the `Waker::will_wake`
random_line_split
async_await_basics.rs
use futures::executor::block_on; use std::thread::Thread; use std::sync::mpsc; use futures::join; use { std::{ pin::Pin, task::Waker, thread, }, }; use { futures::{ future::{FutureExt, BoxFuture}, task::{ArcWake, waker_ref}, }, std::{ future::Future, ...
async fn learn_and_sing() { let song = learn_song().await; sing_song(song).await; } async fn async_main() { let f2 = dance(); let f1 = learn_and_sing(); futures::join!(f2, f1); } // Each time a future is polled, it is polled as part of a "task". Tasks are the top-level futures // that have been...
{ println!("Dance!!") }
identifier_body
async_await_basics.rs
use futures::executor::block_on; use std::thread::Thread; use std::sync::mpsc; use futures::join; use { std::{ pin::Pin, task::Waker, thread, }, }; use { futures::{ future::{FutureExt, BoxFuture}, task::{ArcWake, waker_ref}, }, std::{ future::Future, ...
} } } } // In practice, this problem is solved through integration with an IO-aware system blocking primitive, // such as epoll on Linux, kqueue on FreeBSD and Mac OS, IOCP on Windows, and ports on Fuchsia (all // of which are exposed through the cross-platform Rust crate mio). These primitive...
{ // We're not done processing the future, so put it // back in its task to be run again in the future. *future_slot = Some(future); }
conditional_block
main.rs
//! # Basic Subclass example //! //! This file creates a `GtkApplication` and a `GtkApplicationWindow` subclass //! and showcases how you can override virtual funcitons such as `startup` //! and `activate` and how to interact with the GObjects and their private //! structs. extern crate gstreamer as gst; extern crate ...
} use std::time::Duration; use std::io::Seek; use std::io::SeekFrom; fn main() { gtk::init().expect("Failed to initialize gtk"); let app = SimpleApplication::new(); let args: Vec<String> = std::env::args().collect(); app.run(&args); }
{ glib::Object::new( Self::static_type(), &[ ("application-id", &"org.gtk-rs.SimpleApplication"), ("flags", &ApplicationFlags::empty()), ], ) .expect("Failed to create SimpleApp") .downcast() .expect("Created sim...
identifier_body
main.rs
//! # Basic Subclass example //! //! This file creates a `GtkApplication` and a `GtkApplicationWindow` subclass //! and showcases how you can override virtual funcitons such as `startup` //! and `activate` and how to interact with the GObjects and their private //! structs. extern crate gstreamer as gst; extern crate ...
audio_player_clone.pause_music(); }); // Connect our method `on_increment_clicked` to be called // when the increment button is clicked. increment.connect_clicked(clone!(@weak self_ => move |_| { let priv_ = SimpleWindowPrivate::from_instance(&self_); ...
pause_button.connect_clicked(move |_| {
random_line_split
main.rs
//! # Basic Subclass example //! //! This file creates a `GtkApplication` and a `GtkApplicationWindow` subclass //! and showcases how you can override virtual funcitons such as `startup` //! and `activate` and how to interact with the GObjects and their private //! structs. extern crate gstreamer as gst; extern crate ...
(&self) { self.counter.set(self.counter.get() + 1); let w = self.widgets.get().unwrap(); w.label .set_text(&format!("Your life has {} meaning", self.counter.get())); } fn on_decrement_clicked(&self) { self.counter.set(self.counter.get().wrapping_sub(1)); let w ...
on_increment_clicked
identifier_name
lib.rs
//! A thread-safe object pool with automatic return and attach/detach semantics //! //! The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects //! //! # Examples //! //! ## Creating a Pool //! //! The general pool creation looks like this //! ``` //! let pool: MemPool<T> =...
elf.run_block.lock(); log::trace!("attach started<<<<<<<<<<<<<<<<"); log::trace!("recyled an item "); let mut wait_list = { self.waiting.lock() }; log::trace!("check waiting list ok :{}", wait_list.len()); if wait_list.len() > 0 && self.len() >= wait_list[0].min_request { ...
_x = s
identifier_name
lib.rs
//! A thread-safe object pool with automatic return and attach/detach semantics //! //! The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects //! //! # Examples //! //! ## Creating a Pool //! //! The general pool creation looks like this //! ``` //! let pool: MemPool<T> =...
waiting.lock().len() * 60 + 2 }; log::trace!("try again :{} with retries backoff:{}", str, to_retry); for i in 0..to_retry { sleep(std::time::Duration::from_secs(1)); if let Ok(item) = self.objects.1.try_recv() { log::trace!("get ok:{}", str); ...
); (Some(Reusable::new(&self, item)), false) /* } else if (self.pending.lock().len() == 0) { log::trace!("get should pend:{}", str); self.pending.lock().push(PendingInfo { id: String::from(str), notif...
conditional_block
lib.rs
//! A thread-safe object pool with automatic return and attach/detach semantics //! //! The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects //! //! # Examples //! //! ## Creating a Pool //! //! The general pool creation looks like this //! ``` //! let pool: MemPool<T> =...
usize { self.objects.1.len() } #[inline] pub fn is_empty(&self) -> bool { self.objects.1.is_empty() } #[inline] pub fn pending(&'static self, str: &str, sender: channel::Sender<Reusable<T>>, releasable: usize) -> (Option<Reusable<T>>, bool) { log::trace!("pending item:{...
{}", cap); log::trace!("mempool remains:{}", cap); let mut objects = channel::unbounded(); for _ in 0..cap { &objects.0.send(init()); } MemoryPool { objects, pending: Arc::new(Mutex::new(Vec::new())), waiting: Arc::new(Mutex::new(Ve...
identifier_body
lib.rs
//! A thread-safe object pool with automatic return and attach/detach semantics //! //! The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects //! //! # Examples //! //! ## Creating a Pool //! //! The general pool creation looks like this //! ``` //! let pool: MemPool<T> =...
//! some_file.read_to_end(reusable_buff); //! // reusable_buff is automatically returned to the pool when it goes out of scope //! ``` //! Pull from pool and `detach()` //! ``` //! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // retu...
//! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // returns None when the pool is saturated //! reusable_buff.clear(); // clear the buff before using
random_line_split
counter.rs
use std::ffi::CString; use std::io; use std::sync::{Mutex, Once}; #[cfg(target_os = "freebsd")] use libc::EDOOFUS; #[cfg(target_os = "freebsd")] use pmc_sys::{ pmc_allocate, pmc_attach, pmc_detach, pmc_id_t, pmc_init, pmc_mode_PMC_MODE_SC, pmc_mode_PMC_MODE_TC, pmc_read, pmc_release, pmc_rw, pmc_start, pmc_sto...
(&mut self) { unsafe { pmc_stop(self.counter.id) }; } } /// An allocated PMC counter. /// /// Counters are initialised using the [`CounterBuilder`] type. /// /// ```no_run /// use std::{thread, time::Duration}; /// /// let instr = CounterConfig::default() /// .attach_to(vec![0]) /// .allocate("inst_r...
drop
identifier_name
counter.rs
use std::ffi::CString; use std::io; use std::sync::{Mutex, Once}; #[cfg(target_os = "freebsd")] use libc::EDOOFUS; #[cfg(target_os = "freebsd")] use pmc_sys::{ pmc_allocate, pmc_attach, pmc_detach, pmc_id_t, pmc_init, pmc_mode_PMC_MODE_SC, pmc_mode_PMC_MODE_TC, pmc_read, pmc_release, pmc_rw, pmc_start, pmc_sto...
handles.push(AttachHandle { id, pid }) } c.attached = Some(handles) } Ok(c) } /// Start this counter. /// /// The counter stops when the returned [`Running`] handle is dropped. #[must_use = "counter only runs until handle is dropped"] ...
{ return match io::Error::raw_os_error(&io::Error::last_os_error()) { Some(libc::EBUSY) => unreachable!(), Some(libc::EEXIST) => Err(new_os_error(ErrorKind::AlreadyAttached)), Some(libc::EPERM) => Err(new_os_error(ErrorKind::For...
conditional_block
counter.rs
use std::ffi::CString; use std::io; use std::sync::{Mutex, Once}; #[cfg(target_os = "freebsd")] use libc::EDOOFUS; #[cfg(target_os = "freebsd")] use pmc_sys::{ pmc_allocate, pmc_attach, pmc_detach, pmc_id_t, pmc_init, pmc_mode_PMC_MODE_SC, pmc_mode_PMC_MODE_TC, pmc_read, pmc_release, pmc_rw, pmc_start, pmc_sto...
// Allocate the PMC let mut id = 0; if unsafe { pmc_allocate( c_spec.as_ptr(), pmc_mode, 0, cpu.unwrap_or(CPU_ANY), &mut id, 0, ) }!= 0 { return mat...
let c_spec = CString::new(event_spec.into()).map_err(|_| new_error(ErrorKind::InvalidEventSpec))?;
random_line_split
mod.rs
use rstd::prelude::*; use codec::{Encode, Decode}; use support::{ StorageValue, StorageMap, decl_event, decl_storage, decl_module, ensure, traits::{ Currency, ReservableCurrency, OnFreeBalanceZero, OnUnbalanced, WithdrawReason, ExistenceRequirement, Imbalance, Get, }, dispatch::Result, }; use sr_primitives...
//! # Activity Module //! #![cfg_attr(not(feature = "std"), no_std)]
random_line_split
mod.rs
//! # Activity Module //! #![cfg_attr(not(feature = "std"), no_std)] use rstd::prelude::*; use codec::{Encode, Decode}; use support::{ StorageValue, StorageMap, decl_event, decl_storage, decl_module, ensure, traits::{ Currency, ReservableCurrency, OnFreeBalanceZero, OnUnbalanced, WithdrawReason, ExistenceReq...
<T: Trait>(#[codec(compact)] BalanceOf<T>); impl<T: Trait> TakeFees<T> { /// utility constructor. Used only in client/factory code. pub fn from(fee: BalanceOf<T>) -> Self { Self(fee) } /// Compute the final fee value for a particular transaction. /// /// The final fee is composed of: /// - _length-fee_: Th...
TakeFees
identifier_name
mod.rs
//! # Activity Module //! #![cfg_attr(not(feature = "std"), no_std)] use rstd::prelude::*; use codec::{Encode, Decode}; use support::{ StorageValue, StorageMap, decl_event, decl_storage, decl_module, ensure, traits::{ Currency, ReservableCurrency, OnFreeBalanceZero, OnUnbalanced, WithdrawReason, ExistenceReq...
// PRIVATE MUTABLES fn charge_for_energy(who: &T::AccountId, value: BalanceOf<T>) -> Result { // ensure reserve if!T::Currency::can_reserve(who, value) { return Err("not enough free funds"); } // check current_charged let current_charged = <Charged<T>>::get(who); let new_charged = current_charged.che...
{ T::EnergyCurrency::available_free_balance(who) }
identifier_body
lib.rs
} } } impl From<StoreError> for ProcessError { fn from(err: StoreError) -> Self { match err { StoreError::MissingDigest(s, d) => Self::MissingDigest(s, d), StoreError::Unclassified(s) => Self::Unclassified(s), } } } impl From<String> for ProcessError { fn from(err: String) -> Self { ...
{ let directory_digests = vec![response.output_directory.clone()]; let file_digests = vec![response.stdout_digest, response.stderr_digest]; in_workunit!( "eager_validate_action_cache", Level::Trace, |_workunit| async move { store .exists_recursive(director...
conditional_block
lib.rs
test)] mod cache_tests; pub mod switched; pub mod children; pub mod docker; #[cfg(test)] mod docker_tests; pub mod local; #[cfg(test)] mod local_tests; pub mod nailgun; pub mod named_caches; pub mod remote; #[cfg(test)] pub mod remote_tests; pub mod remote_cache; #[cfg(test)] mod remote_cache_tests; extern cra...
/// from. Defaults to the `input_files` root. /// pub working_directory: Option<RelativePath>, /// /// All of the input digests for the process. /// pub input_digests: InputDigests, pub output_files: BTreeSet<RelativePath>, pub output_directories: BTreeSet<RelativePath>, pub timeout: Option<std:...
pub env: BTreeMap<String, String>, /// /// A relative path to a directory existing in the `input_files` digest to execute the process
random_line_split
lib.rs
est)] mod cache_tests; pub mod switched; pub mod children; pub mod docker; #[cfg(test)] mod docker_tests; pub mod local; #[cfg(test)] mod local_tests; pub mod nailgun; pub mod named_caches; pub mod remote; #[cfg(test)] pub mod remote_tests; pub mod remote_cache; #[cfg(test)] mod remote_cache_tests; extern crat...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingDigest(s, d) => { write!(f, "{s}: {d:?}") } Self::Unclassified(s) => write!(f, "{s}"), } } } impl From<StoreError> for ProcessError { fn from(err: StoreError) -> Self { match err { StoreError:...
fmt
identifier_name
lib.rs
est)] mod cache_tests; pub mod switched; pub mod children; pub mod docker; #[cfg(test)] mod docker_tests; pub mod local; #[cfg(test)] mod local_tests; pub mod nailgun; pub mod named_caches; pub mod remote; #[cfg(test)] pub mod remote_tests; pub mod remote_cache; #[cfg(test)] mod remote_cache_tests; extern crat...
/// /// Set the execution strategy to Docker, with the specified image. /// pub fn docker(mut self, image: String) -> Process { self.execution_strategy = ProcessExecutionStrategy::Docker(image); self } /// /// Set the execution strategy to remote execution with the provided platform properties....
{ self.append_only_caches = append_only_caches; self }
identifier_body
main.rs
#![no_std] #![no_main] #![feature(global_asm, asm, naked_functions)] #![feature(panic_info_message)] #[macro_use] extern crate bitflags; use volatile::Volatile; use lcd::*; use gpu::FramebufferConfig; use core::ptr::{read_volatile, write_volatile}; use core::{str, fmt, cmp, mem}; use core::fmt::{Write, UpperHex, Bina...
if pad.down_once() { self.decrement(); } } fn set_value(&mut self, value: u32) { self.value = value; } fn value(&self) -> u32 { self.value } } pub unsafe fn init_screens(top_fb: &mut [[u8; 3]]) { let brightness_level = 0xFEFE; (*(0x10141200 a...
{ self.increment(); }
conditional_block
main.rs
#![no_std] #![no_main] #![feature(global_asm, asm, naked_functions)] #![feature(panic_info_message)] #[macro_use] extern crate bitflags; use volatile::Volatile; use lcd::*; use gpu::FramebufferConfig; use core::ptr::{read_volatile, write_volatile}; use core::{str, fmt, cmp, mem}; use core::fmt::{Write, UpperHex, Bina...
// Set up color LUT top_fb_conf.set_color_lut_index(0); for i in 0..= 255 { top_fb_conf.set_color_lut_color(0x10101 * i); } setup_framebuffers(top_fb.as_ptr() as _); } unsafe fn setup_framebuffers(addr: u32) { (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill bla...
top_fb_conf.set_buffer_stride(0x2D0); top_fb_conf.reg(0x9C).write(0);
random_line_split
main.rs
#![no_std] #![no_main] #![feature(global_asm, asm, naked_functions)] #![feature(panic_info_message)] #[macro_use] extern crate bitflags; use volatile::Volatile; use lcd::*; use gpu::FramebufferConfig; use core::ptr::{read_volatile, write_volatile}; use core::{str, fmt, cmp, mem}; use core::fmt::{Write, UpperHex, Bina...
(&mut self, f: impl FnOnce(&mut u32)) { let pos = self.cursor_pos * 4; // Extract digit let mut digit = (self.value >> pos) & 0xF; f(&mut digit); digit &= 0xF; // Clear digit self.value &=!(0xF << pos); // Insert digit self.value |= digit << po...
modify
identifier_name
main.rs
#![no_std] #![no_main] #![feature(global_asm, asm, naked_functions)] #![feature(panic_info_message)] #[macro_use] extern crate bitflags; use volatile::Volatile; use lcd::*; use gpu::FramebufferConfig; use core::ptr::{read_volatile, write_volatile}; use core::{str, fmt, cmp, mem}; use core::fmt::{Write, UpperHex, Bina...
{ let c = n.to_be_bytes(); [c[0], c[1], c[2]] }
identifier_body
call.rs
use super::arch::*; use super::data::{Map, SigAction, Stat, StatVfs, TimeSpec}; use super::error::Result; use super::flag::*; use super::number::*; use core::{mem, ptr}; // Signal restorer extern "C" fn restorer() ->! { sigreturn().unwrap(); unreachable!(); } /// Close a file pub fn
(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_CLOSE, fd) } } /// Get the current system time pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result<usize> { unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) } } /// Copy and transform a file descriptor pub fn dup(fd: usi...
close
identifier_name
call.rs
use super::arch::*; use super::data::{Map, SigAction, Stat, StatVfs, TimeSpec}; use super::error::Result; use super::flag::*; use super::number::*; use core::{mem, ptr}; // Signal restorer extern "C" fn restorer() ->! { sigreturn().unwrap(); unreachable!(); } /// Close a file pub fn close(fd: usize) -> Resul...
/// Set the current process user IDs pub fn setreuid(ruid: usize, euid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREUID, ruid, euid) } } /// Set up a signal handler pub fn sigaction(sig: usize, act: Option<&SigAction>, oldact: Option<&mut SigAction>) -> Result<usize> { unsafe { syscall4(SYS_SIGACTIO...
{ unsafe { syscall2(SYS_SETRENS, rns, ens) } }
identifier_body
call.rs
use super::arch::*; use super::data::{Map, SigAction, Stat, StatVfs, TimeSpec}; use super::error::Result; use super::flag::*; use super::number::*; use core::{mem, ptr}; // Signal restorer extern "C" fn restorer() ->! { sigreturn().unwrap(); unreachable!(); } /// Close a file pub fn close(fd: usize) -> Resul...
unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) } } /// Copy and transform a file descriptor pub fn dup(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_DUP, fd, buf.as_ptr() as usize, buf.len()) } } /// Copy and transform a file descriptor pub fn dup2(fd: usize, newfd...
} /// Get the current system time pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result<usize> {
random_line_split
frame_info.rs
//! This module is used for having backtraces in the Wasm runtime. //! Once the Compiler has compiled the ModuleInfo, and we have a set of //! compiled functions (addresses and function index) and a module, //! then we can use this to set a backtrace for that module. //! //! # Example //! ```ignore //! use wasmer_vm::{...
} }; // In debug mode for now assert that we found a mapping for `pc` within // the function, because otherwise something is buggy along the way and // not accounting for all the instructions. This isn't super critical // though so we can omit this check in release ...
{ None }
conditional_block
frame_info.rs
//! This module is used for having backtraces in the Wasm runtime. //! Once the Compiler has compiled the ModuleInfo, and we have a set of //! compiled functions (addresses and function index) and a module, //! then we can use this to set a backtrace for that module. //! //! # Example //! ```ignore //! use wasmer_vm::{...
/// Process the frame info in case is not yet processed pub fn maybe_process_frame(&mut self, pc: usize) -> Option<()> { let module = self.module_info_mut(pc)?; let func = module.function_info(pc)?; let func_local_index = func.local_index; module.process_function_debug_info(fun...
{ let module = self.module_info(pc)?; let func = module.function_info(pc)?; let extra_func_info = module.function_debug_info(func.local_index); Some(extra_func_info.is_unprocessed()) }
identifier_body
frame_info.rs
//! This module is used for having backtraces in the Wasm runtime. //! Once the Compiler has compiled the ModuleInfo, and we have a set of //! compiled functions (addresses and function index) and a module, //! then we can use this to set a backtrace for that module. //! //! # Example //! ```ignore //! use wasmer_vm::{...
/// /// The offset here is the offset from the beginning of the original wasm /// module to the instruction that this frame points to. pub fn module_offset(&self) -> usize { self.instr.bits() as usize } /// Returns the offset from the original wasm module's function to this /// fram...
random_line_split
frame_info.rs
//! This module is used for having backtraces in the Wasm runtime. //! Once the Compiler has compiled the ModuleInfo, and we have a set of //! compiled functions (addresses and function index) and a module, //! then we can use this to set a backtrace for that module. //! //! # Example //! ```ignore //! use wasmer_vm::{...
{ /// An internal map that keeps track of backtrace frame information for /// each module. /// /// This map is morally a map of ranges to a map of information for that /// module. Each module is expected to reside in a disjoint section of /// contiguous memory. No modules can overlap. /// ...
GlobalFrameInfo
identifier_name
lib.rs
# struct UserCreatedData { //! # user_id: String, //! # } //! # //! fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { //! match (t, v) { //! (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), //! _ => None, //! }...
} /// Additional metadata associated with a message #[derive(Clone, Debug, PartialEq, serde::Serialize)] struct Metadata { /// The timestamp when message was created in the publishing service timestamp: u128, /// Name of the publishing service publisher: String, /// Custom headers /// //...
{ Ok(ValidatedMessage { id: self.id.unwrap_or_else(Uuid::new_v4), metadata: Metadata { timestamp: self.timestamp.as_millis(), publisher: publisher_name, headers: self.headers.unwrap_or_else(HashMap::new), }, schema, ...
identifier_body
lib.rs
# struct UserCreatedData { //! # user_id: String, //! # } //! # //! fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { //! match (t, v) { //! (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), //! _ => None, //! }...
else { let mut map = HashMap::new(); map.insert(header.into(), value.into()); self.headers = Some(map); } self } /// Add custom id to the message /// /// If not called, a random UUID is generated for this message. pub fn id(mut self, id: Uuid) ->...
{ hdrs.insert(header.into(), value.into()); }
conditional_block
lib.rs
# struct UserCreatedData { //! # user_id: String, //! # } //! # //! fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { //! match (t, v) { //! (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), //! _ => None, //! ...
/// A message builder #[derive(Clone, Debug, PartialEq)] pub struct Message<D, T> { /// Message identifier id: Option<Uuid>, /// Creation timestamp timestamp: std::time::Duration, /// Message headers headers: Option<Headers>, /// Message data data: D, /// Message type data_type: ...
} } }
random_line_split
lib.rs
# struct UserCreatedData { //! # user_id: String, //! # } //! # //! fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { //! match (t, v) { //! (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), //! _ => None, //! }...
(data_type: T, data_schema_version: Version, data: D) -> Self { Message { id: None, timestamp: SystemTime::now() .duration_since(UNIX_EPOCH) .expect("time is before the unix epoch"), headers: None, data, data_type, ...
new
identifier_name
lib.rs
//! A Rust wrapper around [Zathura's] plugin API, allowing plugin development in //! Rust. //! //! This library wraps the plugin interface and exposes the [`ZathuraPlugin`] //! trait and the [`plugin_entry!`] macro as the primary way to implement a Rust //! plugin for Zathura. //! //! # Examples //! //! ``` //! # use z...
<P: ZathuraPlugin>( document: *mut zathura_document_t, _data: *mut c_void, ) -> zathura_error_t { wrap(|| { let doc = DocumentRef::from_raw(document); let doc_data = &mut *(doc.plugin_data() as *mut P::DocumentData); let result = P::document_free(doc, doc_...
document_free
identifier_name
lib.rs
//! A Rust wrapper around [Zathura's] plugin API, allowing plugin development in //! Rust. //! //! This library wraps the plugin interface and exposes the [`ZathuraPlugin`] //! trait and the [`plugin_entry!`] macro as the primary way to implement a Rust //! plugin for Zathura. //! //! # Examples //! //! ``` //! # use z...
/// Render a page to a Cairo context. pub unsafe extern "C" fn page_render_cairo<P: ZathuraPlugin>( page: *mut zathura_page_t, _data: *mut c_void, cairo: *mut sys::cairo_t, printing: bool, ) -> zathura_error_t { wrap(|| { let mut p = PageRef::from_raw(pa...
{ wrap(|| { let result = { let mut p = PageRef::from_raw(page); let doc_data = &mut *(p.document().plugin_data() as *mut P::DocumentData); let page_data = &mut *(p.plugin_data() as *mut P::PageData); P::page_free(p, doc_data, page_data)...
identifier_body
lib.rs
//! A Rust wrapper around [Zathura's] plugin API, allowing plugin development in //! Rust. //! //! This library wraps the plugin interface and exposes the [`ZathuraPlugin`] //! trait and the [`plugin_entry!`] macro as the primary way to implement a Rust //! plugin for Zathura.
//! # use zathura_plugin::*; //! struct PluginType {} //! //! impl ZathuraPlugin for PluginType { //! type DocumentData = (); //! type PageData = (); //! //! fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError> { //! unimplemented!() //! } //! //! fn page_init(pa...
//! //! # Examples //! //! ```
random_line_split
utxo_scanner_task.rs
static { async fn finalize( &self, total_scanned: u64, final_utxo_pos: u64, elapsed: Duration, ) -> Result<(), UtxoScannerError> { let metadata = self.get_metadata().await?.unwrap_or_default(); self.publish_event(UtxoScannerEvent::Progress { current_in...
(&self, client: &mut BaseNodeSyncRpcClient) -> Result<BlockHeader, UtxoScannerError> { let chain_metadata = client.get_chain_metadata().await?; let chain_height = chain_metadata.height_of_longest_chain(); let end_header = client.get_header_by_height(chain_height).await?; let end_header =...
get_chain_tip_header
identifier_name
utxo_scanner_task.rs
} }; let _ = time::sleep(Duration::from_secs(30)); } Err(e.into()) }, } } async fn attempt_sync(&mut self, peer: NodeId) -> Result<(u64, u64, Duration), UtxoScannerError> { let mut connection = self.con...
{ let peer = self.peer_seeds.get(self.peer_index).map(NodeId::from_public_key); self.peer_index += 1; peer }
identifier_body
utxo_scanner_task.rs
// peer. In the common case, we wait for start index. if start_index >= output_mmr_size - 1 { debug!( target: LOG_TARGET, "Scanning complete UTXO #{} in {:.2?}", start_index, timer.elapsed() ...
let current_utxo_index = response // Assumes correct ordering which is otherwise not required for this protocol .last() .ok_or_else(|| {
random_line_split
cli.rs
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. 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 a...
else { return; } } // fall back to stderr if no path given or if write failed eprintln!("fatal: {}", error); } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_reload() { assert_eq!("once".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Once)); as...
{ info!("Failed to write error to {:?}: {}", p, e); }
conditional_block
cli.rs
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. 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 a...
} /// Exit code for failure of [`DynLogdir::new`]. // Keep in sync with docs on `Opts::logdir`. const EXIT_BAD_LOGDIR: i32 = 8; const EXIT_FAILED_TO_BIND: i32 = 9; #[tokio::main] pub async fn main() -> Result<(), Box<dyn std::error::Error>> { let opts = Opts::parse(); init_logging(match opts.verbosity { ...
{ if s == "once" { Ok(ReloadStrategy::Once) } else { Ok(ReloadStrategy::Loop { delay: Duration::from_secs(s.parse()?), }) } }
identifier_body
cli.rs
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. 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 a...
delay: Duration::from_secs(s.parse()?), }) } } } /// Exit code for failure of [`DynLogdir::new`]. // Keep in sync with docs on `Opts::logdir`. const EXIT_BAD_LOGDIR: i32 = 8; const EXIT_FAILED_TO_BIND: i32 = 9; #[tokio::main] pub async fn main() -> Result<(), Box<dyn std::error...
random_line_split
cli.rs
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. 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 a...
(default_log_level: LevelFilter) { use env_logger::{Builder, Env}; Builder::from_env(Env::default().default_filter_or(default_log_level.to_string())).init(); } /// Locks stdin and reads it to EOF, then exits the process. fn die_after_stdin() { let stdin = std::io::stdin(); let stdin_lock = stdin.lock()...
init_logging
identifier_name
runner.rs
use diesel::prelude::*; #[cfg(feature = "r2d2")] use diesel::r2d2; use std::any::Any; use std::error::Error; use std::panic::{catch_unwind, AssertUnwindSafe, PanicInfo, RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use std::time::Duration; use threadpool::ThreadPool; use crate::db::*; use crate::errors::*; use crate...
<Env:'static, ConnectionPool> { connection_pool: ConnectionPool, thread_pool: ThreadPool, environment: Arc<Env>, registry: Arc<Registry<Env>>, job_start_timeout: Duration, } impl<Env> Runner<Env, NoConnectionPoolGiven> { /// Create a builder for a job runner /// /// This method takes th...
Runner
identifier_name
runner.rs
use diesel::prelude::*; #[cfg(feature = "r2d2")] use diesel::r2d2; use std::any::Any; use std::error::Error; use std::panic::{catch_unwind, AssertUnwindSafe, PanicInfo, RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use std::time::Duration; use threadpool::ThreadPool; use crate::db::*; use crate::errors::*; use crate...
} Ok(()) }); match job_run_result { Ok(_) | Err(RollbackTransaction) => {} Err(e) => { panic!("Failed to update job: {:?}", e); } } }) } fn connection(&self) -> Resu...
{ eprintln!("Job {} failed to run: {}", job_id, e); storage::update_failed_job(&conn, job_id); }
conditional_block
runner.rs
use diesel::prelude::*; #[cfg(feature = "r2d2")] use diesel::r2d2; use std::any::Any; use std::error::Error; use std::panic::{catch_unwind, AssertUnwindSafe, PanicInfo, RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use std::time::Duration; use threadpool::ThreadPool; use crate::db::*; use crate::errors::*; use crate...
/// The amount of time to wait for a job to start before assuming an error /// has occurred. /// /// Defaults to 10 seconds. pub fn job_start_timeout(mut self, timeout: Duration) -> Self { self.job_start_timeout = Some(timeout); self } /// Provide a connection pool to be u...
{ self.thread_count.unwrap_or(5) }
identifier_body
runner.rs
use diesel::prelude::*; #[cfg(feature = "r2d2")] use diesel::r2d2; use std::any::Any; use std::error::Error; use std::panic::{catch_unwind, AssertUnwindSafe, PanicInfo, RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use std::time::Duration; use threadpool::ThreadPool; use crate::db::*; use crate::errors::*; use crate...
environment: Arc<Env>, registry: Arc<Registry<Env>>, job_start_timeout: Duration, } impl<Env> Runner<Env, NoConnectionPoolGiven> { /// Create a builder for a job runner /// /// This method takes the two required configurations, the database /// connection pool, and the environment to pass t...
random_line_split
lib.rs
//! The Pikelet Compiler //! //! # Compiler Architecture //! //! In order to create a separation of concerns, we break up our compiler into many //! small stages, beginning with a source string, and ultimately ending up with //! compiled machine code. //! //! Below is a rough flow chart showing how source strings are c...
() -> Driver { let context = Context::default(); let desugar_env = DesugarEnv::new(context.mappings()); Driver { context, desugar_env, code_map: CodeMap::new(), } } /// Create a new Pikelet environment, with the prelude loaded as well pub...
new
identifier_name
lib.rs
//! The Pikelet Compiler //! //! # Compiler Architecture //! //! In order to create a separation of concerns, we break up our compiler into many //! small stages, beginning with a source string, and ultimately ending up with //! compiled machine code. //! //! Below is a rough flow chart showing how source strings are c...
let raw_term = self.desugar(&concrete_term)?; self.infer_term(&raw_term) } /// Normalize the contents of a file pub fn normalize_file( &mut self, name: FileName, src: String, ) -> Result<domain::RcValue, Vec<Diagnostic>> { use pikelet_concrete::elaborate...
{ return Err(errors.iter().map(|error| error.to_diagnostic()).collect()); }
conditional_block
lib.rs
//! The Pikelet Compiler //! //! # Compiler Architecture //! //! In order to create a separation of concerns, we break up our compiler into many //! small stages, beginning with a source string, and ultimately ending up with //! compiled machine code. //! //! Below is a rough flow chart showing how source strings are c...
pub fn infer_file( &mut self, name: FileName, src: String, ) -> Result<(core::RcTerm, domain::RcType), Vec<Diagnostic>> { let file_map = self.code_map.add_filemap(name, src); // TODO: follow import paths let (concrete_term, _import_paths, errors) = pikelet_concret...
/// Infer the type of a file
random_line_split
ws.rs
// Copyright 2021, The Tremor Team // // 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 t...
let after_close = self.stream.next().await; debug_assert!( after_close.is_none(), "WS reader not behaving as expected after receiving a close message" ); return Ok(Sour...
Message::Close(_) => { // read from the stream once again to drive the closing handshake
random_line_split
ws.rs
// Copyright 2021, The Tremor Team // // 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 t...
; Ok(SourceReply::Data { origin_uri: self.origin_uri.clone(), stream: Some(stream), meta: Some(meta), data, port: None, codec_overwrite: None, }) } ...
{ meta.insert("binary", Value::const_true())?; }
conditional_block
ws.rs
// Copyright 2021, The Tremor Team // // 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 t...
(sink: SplitSink<WebSocketStream<TcpStream>, Message>) -> Self { Self { sink } } } impl WsWriter<TlsStream<TcpStream>> { fn new_tls_server(sink: SplitSink<WebSocketStream<TlsStream<TcpStream>>, Message>) -> Self { Self { sink } } } impl WsWriter<TcpStream> { fn new_tungstenite_client(s...
new
identifier_name
ws.rs
// Copyright 2021, The Tremor Team // // 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 t...
} impl WsWriter<TcpStream> { fn new_tungstenite_client(sink: SplitSink<WebSocketStream<TcpStream>, Message>) -> Self { Self { sink } } } impl WsWriter<tokio_rustls::client::TlsStream<TcpStream>> { fn new_tls_client( sink: SplitSink<WebSocketStream<tokio_rustls::client::TlsStream<TcpStream...
{ Self { sink } }
identifier_body
cabi.rs
use std::ptr; use std::mem; use std::slice; use std::panic; use std::ffi::{CStr, OsStr}; use std::borrow::Cow; use std::os::raw::{c_int, c_uint, c_char}; use std::os::unix::ffi::OsStrExt; use proguard::MappingView; use sourcemap::Error as SourceMapError; use errors::{Error, ErrorKind, Result}; use unified::{View, Toke...
format!("{}\x00", path) }; Ok(Box::into_raw(s.into_boxed_str()) as *mut u8) });
} else {
random_line_split
cabi.rs
use std::ptr; use std::mem; use std::slice; use std::panic; use std::ffi::{CStr, OsStr}; use std::borrow::Cow; use std::os::raw::{c_int, c_uint, c_char}; use std::os::unix::ffi::OsStrExt; use proguard::MappingView; use sourcemap::Error as SourceMapError; use errors::{Error, ErrorKind, Result}; use unified::{View, Toke...
<'a>(out: *mut Token, tm: &'a TokenMatch<'a>) { (*out).dst_line = tm.dst_line; (*out).dst_col = tm.dst_col; (*out).src_line = tm.src_line; (*out).src_col = tm.src_col; (*out).name = match tm.name { Some(name) => name.as_ptr(), None => ptr::null() }; (*out).name_len = tm.name....
set_token
identifier_name
main.rs
/** * Rust's module/package system is *very* fully-featured and rich. * It's worth revisiting the rust book chapter, which is chock full of * special-case details, synonyms, tricks and tips. * * https://doc.rust-lang.org/book/ch07-00-packages-crates-and-modules.html * * * Here are a few of the highest-le...
(msg: &str) { println!("Blort says: {}", msg); } } // next, the series of *declarations*, each of which points to one of the // module implementations discussed above. The declaration phase is easy to // forget, because the implementations are all part of the project, and so // their source files are ver...
blort
identifier_name
main.rs
/** * Rust's module/package system is *very* fully-featured and rich. * It's worth revisiting the rust book chapter, which is chock full of * special-case details, synonyms, tricks and tips. * * https://doc.rust-lang.org/book/ch07-00-packages-crates-and-modules.html * * * Here are a few of the highest-le...
} // next, the series of *declarations*, each of which points to one of the // module implementations discussed above. The declaration phase is easy to // forget, because the implementations are all part of the project, and so // their source files are very close by. But you are *required* to make an // explicit dec...
{ println!("Blort says: {}", msg); }
identifier_body
main.rs
/** * Rust's module/package system is *very* fully-featured and rich. * It's worth revisiting the rust book chapter, which is chock full of * special-case details, synonyms, tricks and tips. * * https://doc.rust-lang.org/book/ch07-00-packages-crates-and-modules.html * * * Here are a few of the highest-le...
// module implementations discussed above. The declaration phase is easy to // forget, because the implementations are all part of the project, and so // their source files are very close by. But you are *required* to make an // explicit declaration nontheless. If you throw in references to `crate::x::y` // without h...
println!("Blort says: {}", msg); } } // next, the series of *declarations*, each of which points to one of the
random_line_split
validate.rs
use crate::{ config::{self, Config, ConfigDiff}, topology::{self, builder::Pieces}, }; use colored::*; use exitcode::ExitCode; use std::collections::HashMap; use std::{fmt, fs::remove_dir_all, path::PathBuf}; use structopt::StructOpt; const TEMPORARY_DIRECTORY: &str = "validate_tmp"; #[derive(StructOpt, Debug...
} /// Performs topology, component, and health checks. pub async fn validate(opts: &Opts, color: bool) -> ExitCode { let mut fmt = Formatter::new(color); let mut validated = true; let mut config = match validate_config(opts, &mut fmt) { Some(config) => config, None => return exitcode::CO...
{ config::merge_path_lists(vec![ (&self.paths, None), (&self.paths_toml, Some(config::Format::Toml)), (&self.paths_json, Some(config::Format::Json)), (&self.paths_yaml, Some(config::Format::Yaml)), ]) .map(|(path, hint)| config::ConfigPath::File(pa...
identifier_body
validate.rs
use crate::{ config::{self, Config, ConfigDiff}, topology::{self, builder::Pieces}, }; use colored::*; use exitcode::ExitCode; use std::collections::HashMap; use std::{fmt, fs::remove_dir_all, path::PathBuf}; use structopt::StructOpt; const TEMPORARY_DIRECTORY: &str = "validate_tmp"; #[derive(StructOpt, Debug...
t self) { if self.print_space { self.print_space = false; println!(); } } fn print(&mut self, print: impl AsRef<str>) { let width = print .as_ref() .lines() .map(|line| { String::from_utf8_lossy(&strip_ansi_escapes...
e(&mu
identifier_name
validate.rs
use crate::{ config::{self, Config, ConfigDiff}, topology::{self, builder::Pieces}, }; use colored::*; use exitcode::ExitCode; use std::collections::HashMap; use std::{fmt, fs::remove_dir_all, path::PathBuf}; use structopt::StructOpt; const TEMPORARY_DIRECTORY: &str = "validate_tmp"; #[derive(StructOpt, Debug...
} /// Standalone line fn success(&mut self, msg: impl AsRef<str>) { self.print(format!("{} {}\n", self.success_intro, msg.as_ref())) } /// Standalone line fn warning(&mut self, warning: impl AsRef<str>) { self.print(format!("{} {}\n", self.warning_intro, warning.as_ref())) ...
} else { println!("{:>width$}", "Validated", width = self.max_line_width) }
random_line_split
mod.rs
#![allow(clippy::pub_enum_variant_names)] use std::collections::HashMap; use serde::{Serialize, Serializer}; extern crate snowflake; pub use std::sync::Arc; use crate::ast::*; use crate::externals::{External, ArgumentType, EXTERNALS}; mod intexp; mod opexp; mod recordexp; mod seqexp; mod assignexp; mod ifexp; mod whi...
(ast : AST) -> Result<AST, TypeError> { let typed_ast = type_exp(ast, &initial_type_env(), &initial_value_env())?; if *typed_ast.typ == TigerType::TInt(R::RW) { Ok(typed_ast) } else { Err(TypeError::NonIntegerProgram(typed_ast.pos)) } }
typecheck
identifier_name
mod.rs
#![allow(clippy::pub_enum_variant_names)] use std::collections::HashMap; use serde::{Serialize, Serializer}; extern crate snowflake; pub use std::sync::Arc; use crate::ast::*; use crate::externals::{External, ArgumentType, EXTERNALS}; mod intexp; mod opexp; mod recordexp; mod seqexp; mod assignexp; mod ifexp; mod whi...
} else { false } } /// An entry in our `TypeEnviroment` table. #[derive(Clone, Debug)] pub enum EnvEntry { /// A declared varaible Var { /// The type of the variable ty: Arc<TigerType>, }, /// A declared function Func { /// The types of the arguments of the function ...
/// Returns true iif the type is an Int pub fn es_int(t: &TigerType) -> bool { if let TigerType::TInt(_) = *t { true
random_line_split
main.rs
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>);...
let mut prover_transcript = Transcript::new(b"test"); let mut prover = Prover::new( &bp_gens, &pc_gens, &mut prover_transcript, ); let (in1_pt, in1_var) = prover.commit(x1.into(), Scalar::random(&mut rng)); l...
0u64 };
conditional_block
main.rs
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>);...
brackets: &TaxBrackets, total: u64) -> u64 { (0..brackets.0.len()) .map(|i| { let last_cutoff = if i == 0 { 0u64 } else { brackets.0[i-1].0 }; let (next_cutoff, rate) = brackets.0[i]; let amount = if total > next_cutoff { next_cutoff - last_cutoff ...
ompute_taxes(
identifier_name
main.rs
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>);...
) -> Result<LinearCombination, R1CSError> { let lhs_bits = scalar_to_bits_le(cs, n_bits, lhs)?; let rhs_bits = scalar_to_bits_le(cs, n_bits, rhs)?; let zero = LinearCombination::default(); // Iterate through bits from most significant to least, comparing each pair. let (lt, _) = lhs_bits.into_iter...
rhs: LinearCombination
random_line_split
main.rs
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>);...
let (_, _, bit_lt) = cs.multiply(negate_bit(l_bit), r_bit.into()); let (_, _, bit_gt) = cs.multiply(l_bit.into(), negate_bit(r_bit)); // new_lt = lt + eq && bit_lt // -> lt_diff = new_lt - lt = eq * bit_lt // new_gt = gt + eq && bit_gt // -> g...
{ let lhs_bits = scalar_to_bits_le(cs, n_bits, lhs)?; let rhs_bits = scalar_to_bits_le(cs, n_bits, rhs)?; let zero = LinearCombination::default(); // Iterate through bits from most significant to least, comparing each pair. let (lt, _) = lhs_bits.into_iter().zip(rhs_bits.into_iter()) .rev(...
identifier_body
main.rs
extern crate rand; extern crate palette; use std::fs::File; use std::io::prelude::*; use std::path::Path; extern crate clap; use std::thread; use std::sync::mpsc; extern crate rayon; use rayon::prelude::*; mod kohonen_neuron; //use kohonen_neuron::rgb_vector_neuron; mod kohonen; use kohonen::Kohonen; mod sphere_of_inf...
<T>( net: &Kohonen<T>, samples: &std::vec::Vec<T>, its: u32, associate: sphere_of_influence::AssociationKind) -> Kohonen<T> where T: kohonen_neuron::KohonenNeuron + Send + Sync +'static { let mut rv = net.clone(); let width = net.cols as f64; // training with a large fixed radius for a bit s...
iter_train
identifier_name
main.rs
extern crate rand; extern crate palette; use std::fs::File; use std::io::prelude::*; use std::path::Path; extern crate clap; use std::thread; use std::sync::mpsc; extern crate rayon; use rayon::prelude::*; mod kohonen_neuron; //use kohonen_neuron::rgb_vector_neuron; mod kohonen; use kohonen::Kohonen; mod sphere_of_inf...
} let nets: Vec<Kohonen<T>> = descs .par_iter() .map(|(my_net, sample)| { let associate = associate.clone(); let mut net = my_net.clone(); feed_sample(&mut net, &sample, rate, radius, associate); net }) ...
Kohonen<T>: Send + Sync { let mut descs = Vec::new(); for i in 0..samples.len() { descs.push((net.clone(), samples[i].clone())); //feed_sample(net, &samples[i], rate, radius);
random_line_split
main.rs
extern crate rand; extern crate palette; use std::fs::File; use std::io::prelude::*; use std::path::Path; extern crate clap; use std::thread; use std::sync::mpsc; extern crate rayon; use rayon::prelude::*; mod kohonen_neuron; //use kohonen_neuron::rgb_vector_neuron; mod kohonen; use kohonen::Kohonen; mod sphere_of_inf...
rv = train(net2, samples, rate, radius.ceil() as i32, associate.clone()) } rv } pub fn show<T: kohonen_neuron::KohonenNeuron>(net: &Kohonen<T>, path: &str) { let rows = net.rows; let cols = net.cols; let path = Path::new(path); let mut os = match File::create(&path) { Err(why) ...
{ let mut rv = net.clone(); let width = net.cols as f64; // training with a large fixed radius for a bit should help things get into // the right general places /*for _i in 0..(its / 2) { let radius = width / 2.0; let rate = 0.5; rv = train(rv.clone(), samples, rate, radius a...
identifier_body
mod.rs
//! A stateless, layered, multithread video system with OpenGL backends. //! //! # Overview and Goals //! //! The management of video effects has become an important topic and key feature of //! rendering engines. With the increasing number of effects it is not sufficient anymore //! to only support them, but also to i...
drop(Box::from_raw(CTX as *mut VideoSystem)); CTX = std::ptr::null(); } pub(crate) unsafe fn frames() -> Arc<DoubleBuf<Frame>> { ctx().frames() } /// Creates an surface with `SurfaceParams`. #[inline] pub fn create_surface(params: SurfaceParams) -> Result<SurfaceHandle> { ctx().create_surface(params...
{ return; }
conditional_block
mod.rs
//! A stateless, layered, multithread video system with OpenGL backends. //! //! # Overview and Goals //! //! The management of video effects has become an important topic and key feature of //! rendering engines. With the increasing number of effects it is not sufficient anymore //! to only support them, but also to i...
/// Gets the `ShaderParams` if available. #[inline] pub fn shader(handle: ShaderHandle) -> Option<ShaderParams> { ctx().shader(handle) } /// Get the resource state of specified shader. #[inline] pub fn shader_state(handle: ShaderHandle) -> ResourceState { ctx().shader_state(handle) } /// Delete shader state ...
#[inline] pub fn create_shader(params: ShaderParams, vs: String, fs: String) -> Result<ShaderHandle> { ctx().create_shader(params, vs, fs) }
random_line_split
mod.rs
//! A stateless, layered, multithread video system with OpenGL backends. //! //! # Overview and Goals //! //! The management of video effects has become an important topic and key feature of //! rendering engines. With the increasing number of effects it is not sufficient anymore //! to only support them, but also to i...
(params: SurfaceParams) -> Result<SurfaceHandle> { ctx().create_surface(params) } /// Gets the `SurfaceParams` if available. #[inline] pub fn surface(handle: SurfaceHandle) -> Option<SurfaceParams> { ctx().surface(handle) } /// Get the resource state of specified surface. #[inline] pub fn surface_state(handle...
create_surface
identifier_name
mod.rs
//! A stateless, layered, multithread video system with OpenGL backends. //! //! # Overview and Goals //! //! The management of video effects has become an important topic and key feature of //! rendering engines. With the increasing number of effects it is not sufficient anymore //! to only support them, but also to i...
mod ins { use super::system::VideoSystem; pub static mut CTX: *const VideoSystem = std::ptr::null(); #[inline] pub fn ctx() -> &'static VideoSystem { unsafe { debug_assert!( !CTX.is_null(), "video system has not been initialized properly." ...
{ ctx().delete_render_texture(handle) }
identifier_body
rt_threaded.rs
#![warn(rust_2018_idioms)] #![cfg(all(feature = "full", not(tokio_wasi)))] use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use tokio::runtime; use tokio::sync::oneshot; use tokio_test::{assert_err, assert_ok}; use futures::future::poll_fn; use std::future::Future; use std::pin:...
}); } rx.recv().unwrap(); // Wait for the pool to shutdown block.wait(); } } #[test] fn multi_threadpool() { use tokio::sync::oneshot; let rt1 = rt(); let rt2 = rt(); let (tx, rx) = oneshot::channel(); let (done_tx, done_rx) = mpsc::channel(); ...
{ tx.send(()).unwrap(); }
conditional_block
rt_threaded.rs
#![warn(rust_2018_idioms)] #![cfg(all(feature = "full", not(tokio_wasi)))] use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use tokio::runtime; use tokio::sync::oneshot; use tokio_test::{assert_err, assert_ok}; use futures::future::poll_fn; use std::future::Future; use std::pin:...
const TRACKS: usize = 50; for _ in 0..50 { let rt = rt(); let mut start_txs = Vec::with_capacity(TRACKS); let mut final_rxs = Vec::with_capacity(TRACKS); for _ in 0..TRACKS { let (start_tx, mut chain_rx) = tokio::sync::mpsc::channel(10); for _ in 0..CHA...
const CHAIN: usize = 200; const CYCLES: usize = 5;
random_line_split
rt_threaded.rs
#![warn(rust_2018_idioms)] #![cfg(all(feature = "full", not(tokio_wasi)))] use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use tokio::runtime; use tokio::sync::oneshot; use tokio_test::{assert_err, assert_ok}; use futures::future::poll_fn; use std::future::Future; use std::pin:...
() { struct Shared { waker: Option<Waker>, } struct MyFuture { shared: Arc<Mutex<Shared>>, put_waker: bool, } impl MyFuture { fn new() -> (Self, Self) { let shared = Arc::new(Mutex::new(Shared { waker: None })); let f1 = MyFuture { ...
wake_during_shutdown
identifier_name
d3cap.rs
use std::thread::{self, JoinHandle}; use std::hash::{Hash}; use std::collections::hash_map::{Entry, HashMap}; use std::fs::File; use std::io::{self, Read}; use std::sync::{Arc,RwLock}; use std::sync::mpsc::{channel, Sender, SendError}; use toml; use multicast::Multicast; use json_serve::uiserver::UIServer; use util:...
} } Err(LoadMacError::TomlError(None)) } fn start_websocket(port: u16, mac_map: &MacMap, pg_ctl: &ProtoGraphController) -> io::Result<()> { let ui = UIServer::spawn(port, mac_map)?; pg_ctl.register_mac_listener(ui.create_sender()?); pg_ctl.register_ip4_listener(ui.create_sender()?); pg_...
.collect())
random_line_split
d3cap.rs
use std::thread::{self, JoinHandle}; use std::hash::{Hash}; use std::collections::hash_map::{Entry, HashMap}; use std::fs::File; use std::io::{self, Read}; use std::sync::{Arc,RwLock}; use std::sync::mpsc::{channel, Sender, SendError}; use toml; use multicast::Multicast; use json_serve::uiserver::UIServer; use util:...
let tap_hdr = unsafe { &*(pkt.pkt_ptr() as *const tap::RadiotapHeader) }; let base: &dot11::Dot11BaseHeader = magic(tap_hdr); let fc = &base.fr_ctrl; if fc.protocol_version()!= 0 { // bogus packet, bail return Err(ParseErr::UnknownPacket); } ma...
{ unsafe { skip_bytes_cast(pkt, pkt.it_len as isize) } }
identifier_body
d3cap.rs
use std::thread::{self, JoinHandle}; use std::hash::{Hash}; use std::collections::hash_map::{Entry, HashMap}; use std::fs::File; use std::io::{self, Read}; use std::sync::{Arc,RwLock}; use std::sync::mpsc::{channel, Sender, SendError}; use toml; use multicast::Multicast; use json_serve::uiserver::UIServer; use util:...
(conf: D3capConf, pkt_sender: Sender<Pkt>, pd_sender: Sender<PhysData>) -> io::Result<JoinHandle<()>> { thread::Builder::new().name("packet_capture".to_owned()).spawn(move || { let mut cap = init_capture(&conf, pkt_sender, pd_sender); loop { cap....
start_capture
identifier_name
d3cap.rs
use std::thread::{self, JoinHandle}; use std::hash::{Hash}; use std::collections::hash_map::{Entry, HashMap}; use std::fs::File; use std::io::{self, Read}; use std::sync::{Arc,RwLock}; use std::sync::mpsc::{channel, Sender, SendError}; use toml; use multicast::Multicast; use json_serve::uiserver::UIServer; use util:...
match pkt.unwrap() { Pkt::Mac(ref p) => phctl.mac.update(p), Pkt::IP4(ref p) => phctl.ip4.update(p), Pkt::IP6(ref p) => phctl.ip6.update(p), } } })?; Ok(ctl) } fn sender(&self) -> Sender<Pk...
{ break }
conditional_block
mod.rs
//! This module implements the global `Function` object as well as creates Native Functions. //! //! Objects wrap `Function`s and expose them via call/construct slots. //! //! `The `Function` object is used for matching text with a pattern. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN docum...
} #[derive(Debug, Trace, Finalize, PartialEq, Clone)] pub enum ConstructorKind { Base, Derived, } impl ConstructorKind { /// Returns `true` if the constructor kind is `Base`. pub fn is_base(&self) -> bool { matches!(self, Self::Base) } /// Returns `true` if the constructor kind is `D...
{ matches!(self, Self::Global) }
identifier_body
mod.rs
//! This module implements the global `Function` object as well as creates Native Functions. //! //! Objects wrap `Function`s and expose them via call/construct slots. //! //! `The `Function` object is used for matching text with a pattern. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN docum...
(_: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> { Ok(JsValue::undefined()) } /// `Function.prototype.call` /// /// The call() method invokes self with the first argument as the `this` value. /// /// More information: /// - [MDN documentation][mdn] /// - [ECM...
prototype
identifier_name
mod.rs
//! This module implements the global `Function` object as well as creates Native Functions. //! //! Objects wrap `Function`s and expose them via call/construct slots. //! //! `The `Function` object is used for matching text with a pattern. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN docum...
} /// Boa representation of a Function Object. /// /// FunctionBody is specific to this interpreter, it will either be Rust code or JavaScript code (AST Node) /// /// <https://tc39.es/ecma262/#sec-ecmascript-function-objects> #[derive(Clone, Trace, Finalize)] pub enum Function { Native { #[unsafe_ignore_tr...
.deref_mut() .as_mut_any() .downcast_mut::<T>() .ok_or_else(|| context.construct_type_error("cannot downcast `Captures` to given type")) }
random_line_split
mod.rs
//! This module implements the global `Function` object as well as creates Native Functions. //! //! Objects wrap `Function`s and expose them via call/construct slots. //! //! `The `Function` object is used for matching text with a pattern. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN docum...
}; match (&function, name) { ( Function::Native { function: _, constructable: _, }, Some(name), ) => Ok(format!("function {}() {{\n [native Code]\n}}", &name).into()), (Function...
{ return context.throw_type_error("Not a function"); }
conditional_block