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
implementation.rs
CODE_LEN as usize, xous::MemoryFlags::R, ).expect("couldn't map in the loader code region"); let kernel = xous::syscall::map_memory( Some(NonZeroUsize::new((xous::KERNEL_LOC + xous::FLASH_PHYS_BASE) as usize).unwrap()), None, xous::KERNEL_LEN as usize, ...
debug_staging
identifier_name
implementation.rs
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } fn purge_sensitive_data(&mut self) { let data = self.sensitive_data.as_slice_mut::<u32>(); for d in data.iter_mut() { *d = 0; } core::sync::atomic::compiler_fence(core::sync::atomic::...
{ // read until we get a buffer that's not fully filled break; }
conditional_block
implementation.rs
or Rust optimizers removing writes sensitive_data: xous::MemoryRange, // this gets purged at least on every suspend, but ideally purged sooner than that pass_cache: xous::MemoryRange, // this can be purged based on a policy, as set below boot_password_policy: PasswordRetentionPolicy, update_password_po...
// generate and store a root key (aka boot key), this is what is unlocked by the "boot password" // ironically, it's a "lower security" key because it just acts as a gatekeeper to further // keys that would have a stronger password applied to them, based upon the importance of the secret ...
update_progress(10, progress_modal, progress_action);
random_line_split
implementation.rs
r Rust optimizers removing writes sensitive_data: xous::MemoryRange, // this gets purged at least on every suspend, but ideally purged sooner than that pass_cache: xous::MemoryRange, // this can be purged based on a policy, as set below boot_password_policy: PasswordRetentionPolicy, update_password_pol...
/// Reads a 128-bit key at a given index offset fn read_key_128(&mut self, index: u8) -> [u8; 16] { let mut key: [u8; 16] = [0; 16]; for (addr, word) in key.chunks_mut(4).into_iter().enumerate() { self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, index as u32 + addr as u32); ...
{ let mut key: [u8; 32] = [0; 32]; for (addr, word) in key.chunks_mut(4).into_iter().enumerate() { self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, index as u32 + addr as u32); let keyword = self.keyrom.rf(utra::keyrom::DATA_DATA); for (&byte, dst) in keyword.to_be_byte...
identifier_body
utils.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Logs an error message if the passed in `result` is an error. #[macro_export] macro_rules! log_if_err { ($result:expr, $log_prefix:expr) => { ...
/// Connects to the driver at `path`, returning a proxy of the specified type. The path is /// guaranteed to exist before the connection is opened. /// /// TODO(fxbug.dev/81378): factor this function out to a common library pub async fn connect_to_driver<T: fidl::endpoints::ProtocolMarker>( ...
{ device_watcher::recursive_wait_and_open_node( &io_util::open_directory_in_namespace( "/dev", OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE, )?, path, ) .await }
identifier_body
utils.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Logs an error message if the passed in `result` is an error. #[macro_export] macro_rules! log_if_err { ($result:expr, $log_prefix:expr) => { ...
// verify the bucketing logic hist.add_data(50); hist.add_data(65); hist.add_data(75); hist.add_data(79); // Verify the values were counted and bucketed properly assert_eq!(hist.count(), 4); assert_eq!( hist.get_data(), vec![ ...
// Add some arbitrary values, making sure some do not land on the bucket boundary to further
random_line_split
utils.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Logs an error message if the passed in `result` is an error. #[macro_export] macro_rules! log_if_err { ($result:expr, $log_prefix:expr) => { ...
(num_buckets: u32) -> Vec<HistogramBucket> { (0..num_buckets + 2).map(|i| HistogramBucket { index: i, count: 0 }).collect() } /// Add a data value to the histogram. pub fn add_data(&mut self, n: i64) { // Add one to index to account for underflow bucket at index 0 let mut index = 1 ...
new_vec
identifier_name
macros.rs
/// Prints to [`stdout`][crate::stdout]. /// /// Equivalent to the [`println!`] macro except that a newline is not printed at /// the end of the message. /// /// Note that stdout is frequently line-buffered by default so it may be /// necessary to use [`std::io::Write::flush()`] to ensure the output is emitted /// imme...
/// print!("on "); /// print!("the "); /// print!("same "); /// print!("line "); /// /// stdout().flush().unwrap(); /// /// print!("this string has a newline, why not choose println! instead?\n"); /// /// stdout().flush().unwrap(); /// # } /// ``` #[cfg(feature = "auto")] #[macro_export] macro_rules! print { ($($ar...
/// /// print!("this "); /// print!("will "); /// print!("be ");
random_line_split
pipe.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) -> io::Result<bool> { let amt = match self.state { State::NotReading => return Ok(true), State::Reading => { self.pipe.overlapped_result(&mut *self.overlapped, true)? } State::Read(amt) => amt, }; self.state = State::Not...
result
identifier_name
pipe.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } impl<'a> Drop for AsyncPipe<'a> { fn drop(&mut self) { match self.state { State::Reading => {} _ => return, } // If we have a pending read operation, then we have to make sure that // it's *done* before we actually drop this type. The kernel requires...
while self.result()? && self.schedule_read()? { // ... } Ok(())
random_line_split
pipe.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn into_handle(self) -> Handle { self.inner } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.inner.read(buf) } pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> { self.inner.read_to_end(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<u...
{ &self.inner }
identifier_body
register.rs
//! Box registers use crate::mir::constant::Constant; use crate::mir::expr::Expr; use crate::serialization::sigma_byte_reader::SigmaByteRead; use crate::serialization::sigma_byte_writer::SigmaByteWrite; use crate::serialization::SigmaParsingError; use crate::serialization::SigmaSerializable; use crate::serialization::...
impl TryFrom<HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>> for NonMandatoryRegisters { type Error = NonMandatoryRegistersError; fn try_from( value: HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>, ) -> Result<Self, Self::Error> { ...
} #[cfg(feature = "json")]
random_line_split
register.rs
//! Box registers use crate::mir::constant::Constant; use crate::mir::expr::Expr; use crate::serialization::sigma_byte_reader::SigmaByteRead; use crate::serialization::sigma_byte_writer::SigmaByteWrite; use crate::serialization::SigmaParsingError; use crate::serialization::SigmaSerializable; use crate::serialization::...
/// Size of non-mandatory registers set pub fn len(&self) -> usize { self.0.len() } /// Return true if non-mandatory registers set is empty pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Get register value (returns None, if there is no value for the given regist...
{ NonMandatoryRegisters::try_from( regs.into_iter() .map(|(k, v)| (k, v.into())) .collect::<HashMap<NonMandatoryRegisterId, RegisterValue>>(), ) }
identifier_body
register.rs
//! Box registers use crate::mir::constant::Constant; use crate::mir::expr::Expr; use crate::serialization::sigma_byte_reader::SigmaByteRead; use crate::serialization::sigma_byte_writer::SigmaByteWrite; use crate::serialization::SigmaParsingError; use crate::serialization::SigmaSerializable; use crate::serialization::...
(&self) -> bool { self.0.is_empty() } /// Get register value (returns None, if there is no value for the given register id) pub fn get(&self, reg_id: NonMandatoryRegisterId) -> Option<&RegisterValue> { self.0.get(reg_id as usize) } /// Get register value as a Constant /// retur...
is_empty
identifier_name
mod.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/gui/input/mod.rs //! GUI input managment #[allow(unused_imports)] use kernel::prelude::*; use self::keyboard::KeyCode; use core::sync::atomic::{Ordering,AtomicUsize,AtomicU8}; use kernel::sync::Mutex; pub mod keyboard; pub mod mouse; #[derive(Debug)] p...
fn set_r(&self) { self.0.fetch_or(2, Ordering::Relaxed); } fn clear_l(&self) { self.0.fetch_and(!1, Ordering::Relaxed); } fn clear_r(&self) { self.0.fetch_and(!2, Ordering::Relaxed); } fn get(&self) -> bool { self.0.load(Ordering::Relaxed)!= 0 } } impl MouseCursor { const fn new() -> MouseCursor { MouseCurso...
{ self.0.fetch_or(1, Ordering::Relaxed); }
identifier_body
mod.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/gui/input/mod.rs //! GUI input managment #[allow(unused_imports)] use kernel::prelude::*; use self::keyboard::KeyCode; use core::sync::atomic::{Ordering,AtomicUsize,AtomicU8}; use kernel::sync::Mutex; pub mod keyboard; pub mod mouse; #[derive(Debug)] p...
KeyCode::Semicolon => shift!(self: ";", ":"), KeyCode::Quote => shift!(self: "'", "\""), KeyCode::Comma => shift!(self: ",", "<"), KeyCode::Period => shift!(self: ".", ">"), KeyCode::Slash => shift!(self: "/", "?"), KeyCode::Kb1 => shift!(self: "1", "!"), KeyCode::Kb2 => shift!(self: "2", "@"), K...
KeyCode::SquareClose => shift!(self: "[", "{"), KeyCode::Backslash => shift!(self: "\\","|"),
random_line_split
mod.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/gui/input/mod.rs //! GUI input managment #[allow(unused_imports)] use kernel::prelude::*; use self::keyboard::KeyCode; use core::sync::atomic::{Ordering,AtomicUsize,AtomicU8}; use kernel::sync::Mutex; pub mod keyboard; pub mod mouse; #[derive(Debug)] p...
(&self) -> bool { self.shift_held.get() } fn upper(&self) -> bool { self.shift() } fn get_input_string(&self, keycode: KeyCode) -> &str { macro_rules! shift { ($s:ident: $lower:expr, $upper:expr) => { if $s.shift() { $upper } else {$lower} }; } macro_rules! alpha { ($s:ident: $lower:expr, $upper:expr) =>...
shift
identifier_name
lib.rs
extern crate unix_socket; pub mod protocol; use protocol::{Command, reply, PortSocket}; use std::collections::HashMap; use std::fs::File; use std::io; use std::io::prelude::*; use std::sync::Arc; use std::sync::{Mutex, MutexGuard, TryLockError}; use std::u8; // TODO Corking reduces latency, as spid adds overhead for...
else { sock.write_command(Command::GpioLow(self.index as u8)) } } } impl Port { pub fn new(path: &str) -> Port { let mut pins = HashMap::new(); for i in 0..8 { pins.insert(i, Mutex::new(())); } // Create and return the port struct Port {...
{ sock.write_command(Command::GpioHigh(self.index as u8)) }
conditional_block
lib.rs
extern crate unix_socket; pub mod protocol; use protocol::{Command, reply, PortSocket}; use std::collections::HashMap; use std::fs::File; use std::io; use std::io::prelude::*; use std::sync::Arc; use std::sync::{Mutex, MutexGuard, TryLockError}; use std::u8; // TODO Corking reduces latency, as spid adds overhead for...
fn tx(&self, sock: &mut MutexGuard<PortSocket>, address: u8, write_buf: &[u8]) { sock.write_command(Command::Start(address<<1)).unwrap(); // Write the command and data sock.write_command(Command::Tx(write_buf)).unwrap(); } fn rx(&self, sock: &mut MutexGuard<PortSocket>, address: u...
{ let mut sock = self.socket.lock().unwrap(); sock.write_command(Command::EnableI2C{ baud: baud }).unwrap(); }
identifier_body
lib.rs
extern crate unix_socket; pub mod protocol; use protocol::{Command, reply, PortSocket}; use std::collections::HashMap; use std::fs::File; use std::io; use std::io::prelude::*; use std::sync::Arc; use std::sync::{Mutex, MutexGuard, TryLockError}; use std::u8; // TODO Corking reduces latency, as spid adds overhead for...
(&mut self) -> Result<(), io::Error> { let new_value =!self.value; self.write(new_value) } // Returns the current state of the LED. pub fn read(&self) -> bool { self.value } // Helper function to write new state to LED filepath. fn write(&mut self, new_value: bool) -> R...
toggle
identifier_name
lib.rs
extern crate unix_socket; pub mod protocol; use protocol::{Command, reply, PortSocket}; use std::collections::HashMap; use std::fs::File; use std::io; use std::io::prelude::*; use std::sync::Arc; use std::sync::{Mutex, MutexGuard, TryLockError}; use std::u8; // TODO Corking reduces latency, as spid adds overhead for...
pub port: PortGroup, // An array of LED structs. pub led: Vec<LED>, } impl Tessel { // new() returns a Tessel struct conforming to the Tessel 2's functionality. pub fn new() -> Tessel { // Create a port group with two ports, one on each domain socket path. let ports = PortGroup { ...
pub struct Tessel { // A group of module ports.
random_line_split
watch.rs
//! Recursively watch paths for changes, in an extensible and //! cross-platform way. use crate::NixFile; use crossbeam_channel as chan; use notify::event::ModifyKind; use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use slog_scope::{debug, info}; use std::collections::HashSet; use std::path::{Path...
let nix = PathBuf::from("/nix/store/njlavpa90laywf22b1myif5101qhln8r-hello-2.10"); match super::Watch::extend_filter(nix.clone()) { Ok(path) => assert!(false, "{:?} should be filtered!", path), Err(super::FilteredOut { path, reason }) => { drop(reason); ...
identifier_body
watch.rs
//! Recursively watch paths for changes, in an extensible and //! cross-platform way. use crate::NixFile; use crossbeam_channel as chan; use notify::event::ModifyKind; use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use slog_scope::{debug, info}; use std::collections::HashSet; use std::path::{Path...
false }; watched_paths.iter().any(|watched| { if matches(watched) { return true; } if let Ok(canonicalized_watch) = watched.canonicalize() { if matches(&canonicalized_watch) { return true; } } false }) } ...
if parent == watched { debug!( "event path parent matches watched path"; "event_path" => event_path.to_str(), "parent_path" => parent.to_str()); return true; } }
conditional_block
watch.rs
//! Recursively watch paths for changes, in an extensible and //! cross-platform way. use crate::NixFile; use crossbeam_channel as chan; use notify::event::ModifyKind; use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use slog_scope::{debug, info}; use std::collections::HashSet; use std::path::{Path...
macos_eat_late_notifications(&mut watcher); // bar is not watched, expect error expect_bash(r#"echo 1 > "$1/bar""#, &[temp.path().as_os_str()]); sleep(upper_watcher_timeout()); assert!(no_changes(&watcher)); // Rename bar to foo, expect a notification expect_bas...
random_line_split
watch.rs
//! Recursively watch paths for changes, in an extensible and //! cross-platform way. use crate::NixFile; use crossbeam_channel as chan; use notify::event::ModifyKind; use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use slog_scope::{debug, info}; use std::collections::HashSet; use std::path::{Path...
ath: PathBuf) -> Result<PathBuf, FilteredOut<'static>> { if path.starts_with(Path::new("/nix/store")) { Err(FilteredOut { path, reason: "starts with /nix/store", }) } else { Ok(path) } } fn log_event(&self, event: &noti...
tend_filter(p
identifier_name
lib.rs
//! *Library for encrypting and decrypting age files* //! //! This crate implements file encryption according to the [age-encryption.org/v1] //! specification. It generates and consumes encrypted files that are compatible with the //! [rage] CLI tool, as well as the reference [Go] implementation. //! //! The encryption...
//! let passphrase = "this is not a good passphrase"; //! //! // Encrypt the plaintext to a ciphertext using the passphrase... //! # fn encrypt(passphrase: &str, plaintext: &[u8]) -> Result<Vec<u8>, age::EncryptError> { //! let encrypted = { //! let encryptor = age::Encryptor::with_user_passphrase(Secret::new(passp...
//! let plaintext = b"Hello world!";
random_line_split
lib.rs
//! *Library for encrypting and decrypting age files* //! //! This crate implements file encryption according to the [age-encryption.org/v1] //! specification. It generates and consumes encrypted files that are compatible with the //! [rage] CLI tool, as well as the reference [Go] implementation. //! //! The encryption...
(data: &[u8]) { if let Ok(header) = format::Header::read(data) { let mut buf = Vec::with_capacity(data.len()); header.write(&mut buf).expect("can write header"); assert_eq!(&buf[..], &data[..buf.len()]); } }
fuzz_header
identifier_name
lib.rs
//! *Library for encrypting and decrypting age files* //! //! This crate implements file encryption according to the [age-encryption.org/v1] //! specification. It generates and consumes encrypted files that are compatible with the //! [rage] CLI tool, as well as the reference [Go] implementation. //! //! The encryption...
}
{ let mut buf = Vec::with_capacity(data.len()); header.write(&mut buf).expect("can write header"); assert_eq!(&buf[..], &data[..buf.len()]); }
conditional_block
lib.rs
//! *Library for encrypting and decrypting age files* //! //! This crate implements file encryption according to the [age-encryption.org/v1] //! specification. It generates and consumes encrypted files that are compatible with the //! [rage] CLI tool, as well as the reference [Go] implementation. //! //! The encryption...
{ if let Ok(header) = format::Header::read(data) { let mut buf = Vec::with_capacity(data.len()); header.write(&mut buf).expect("can write header"); assert_eq!(&buf[..], &data[..buf.len()]); } }
identifier_body
main.rs
::{debug, error, info, warn, Level}; use transfer_syntax::TransferSyntaxIndex; use walkdir::WalkDir; /// DICOM C-STORE SCU #[derive(Debug, Parser)] #[command(version)] struct App { /// socket address to Store SCP, /// optionally with AE title /// (example: "STORE-SCP@127.0.0.1:104") addr: String, /...
( file: &DicomFile, pcs: &[dicom_ul::pdu::PresentationContextResult], ) -> Result<(dicom_ul::pdu::PresentationContextResult, String), Error> { let file_ts = TransferSyntaxRegistry .get(&file.file_transfer_syntax) .whatever_context("Unsupported file transfer syntax")?; // TODO(#106) transfe...
check_presentation_contexts
identifier_name
main.rs
::{debug, error, info, warn, Level}; use transfer_syntax::TransferSyntaxIndex; use walkdir::WalkDir; /// DICOM C-STORE SCU #[derive(Debug, Parser)] #[command(version)] struct App { /// socket address to Store SCP, /// optionally with AE title /// (example: "STORE-SCP@127.0.0.1:104") addr: String, /...
} } if let Some(pb) = progress_bar.as_ref() { pb.inc(1) }; } if let Some(pb) = progress_bar { pb.finish_with_message("done") }; scu.release() .whatever_context("Failed to release SCU association")?; Ok(()) } fn store_req_command( ...
{ error!("Unexpected SCP response: {:?}", pdu); let _ = scu.abort(); std::process::exit(-2); }
conditional_block
main.rs
use tracing::{debug, error, info, warn, Level}; use transfer_syntax::TransferSyntaxIndex; use walkdir::WalkDir; /// DICOM C-STORE SCU #[derive(Debug, Parser)] #[command(version)] struct App { /// socket address to Store SCP, /// optionally with AE title /// (example: "STORE-SCP@127.0.0.1:104") addr: St...
let nbytes = cmd_data.len() + object_data.len(); if verbose { info!( "Sending file {} (~ {} kB), uid={}, sop={}, ts={}", file.file.display(), nbytes / 1_000, &file.sop_instance_uid, ...
.whatever_context("Unsupported file transfer syntax")?; dicom_file .write_dataset_with_ts(&mut object_data, ts_selected) .whatever_context("Could not write object dataset")?;
random_line_split
args.rs
//! Handle `cargo add` arguments use cargo_edit::{find, registry_url, Dependency}; use cargo_edit::{get_latest_dependency, CrateName}; use semver; use std::path::PathBuf; use structopt::StructOpt; use crate::errors::*; #[derive(Debug, StructOpt)] #[structopt(bin_name = "cargo")] pub enum
{ /// Add dependency to a Cargo.toml manifest file. #[structopt(name = "add")] #[structopt( after_help = "This command allows you to add a dependency to a Cargo.toml manifest file. If <crate> is a github or gitlab repository URL, or a local path, `cargo add` will try to automatically get the crate ...
Command
identifier_name
args.rs
//! Handle `cargo add` arguments use cargo_edit::{find, registry_url, Dependency}; use cargo_edit::{get_latest_dependency, CrateName}; use semver; use std::path::PathBuf; use structopt::StructOpt; use crate::errors::*; #[derive(Debug, StructOpt)] #[structopt(bin_name = "cargo")] pub enum Command { /// Add depend...
None }; if self.git.is_none() && self.path.is_none() && self.vers.is_none() { let dep = get_latest_dependency( crate_name.name(), self.allow_prerelease, &find(&self.manifest_path)?, &...
{ assert_eq!(self.git.is_some() && self.vers.is_some(), false); assert_eq!(self.git.is_some() && self.path.is_some(), false); assert_eq!(self.git.is_some() && self.registry.is_some(), false); assert_eq!(self.path.is_some() && self.registry.is_some(), false); ...
conditional_block
args.rs
//! Handle `cargo add` arguments use cargo_edit::{find, registry_url, Dependency}; use cargo_edit::{get_latest_dependency, CrateName}; use semver; use std::path::PathBuf; use structopt::StructOpt; use crate::errors::*; #[derive(Debug, StructOpt)] #[structopt(bin_name = "cargo")] pub enum Command { /// Add depend...
.set_optional(self.optional) .set_features(self.features.clone()) .set_default_features(!self.no_default_features); if let Some(ref rename) = self.rename { x = x.set_rename(rename); } ...
{ if self.crates.len() > 1 && (self.git.is_some() || self.path.is_some() || self.vers.is_some()) { return Err(ErrorKind::MultipleCratesWithGitOrPathOrVers.into()); } if self.crates.len() > 1 && self.rename.is_some() { return Err(ErrorKind::MultipleCra...
identifier_body
args.rs
//! Handle `cargo add` arguments use cargo_edit::{find, registry_url, Dependency}; use cargo_edit::{get_latest_dependency, CrateName}; use semver; use std::path::PathBuf; use structopt::StructOpt; use crate::errors::*; #[derive(Debug, StructOpt)] #[structopt(bin_name = "cargo")] pub enum Command { /// Add depend...
#[structopt(long = "target", conflicts_with = "dev", conflicts_with = "build")] pub target: Option<String>, /// Add as an optional dependency (for use in features). #[structopt(long = "optional", conflicts_with = "dev", conflicts_with = "build")] pub optional: bool, /// Path to the manifest to...
/// Add as dependency to the given target platform.
random_line_split
cache.rs
use crate::address_map::{ModuleAddressMap, ValueLabelsRanges}; use crate::compilation::{Compilation, Relocations}; use crate::module::Module; use crate::module_environ::FunctionBodyData; use core::hash::Hasher; use cranelift_codegen::{ir, isa}; use cranelift_entity::PrimaryMap; use cranelift_wasm::DefinedFuncIndex; use...
(dir: &Path, compression_level: i32) -> Self { // On Windows, if we want long paths, we need '\\?\' prefix, but it doesn't work // with relative paths. One way to get absolute path (the only one?) is to use // fs::canonicalize, but it requires that given path exists. The extra advant...
new_step2
identifier_name
cache.rs
use crate::address_map::{ModuleAddressMap, ValueLabelsRanges}; use crate::compilation::{Compilation, Relocations}; use crate::module::Module; use crate::module_environ::FunctionBodyData; use core::hash::Hasher; use cranelift_codegen::{ir, isa}; use cranelift_entity::PrimaryMap; use cranelift_wasm::DefinedFuncIndex; use...
mod_dbg = if generate_debug_info { ".d" } else { "" }, ); Some( conf::cache_directory() .join(isa.triple().to_string()) .join(compiler_dir) .join(mod_filename), ) } else { Non...
{ let mod_cache_path = if conf::cache_enabled() { let hash = Sha256Hasher::digest(module, function_body_inputs); let compiler_dir = if cfg!(debug_assertions) { format!( "{comp_name}-{comp_ver}-{comp_mtime}", comp_name = compiler_nam...
identifier_body
cache.rs
use crate::address_map::{ModuleAddressMap, ValueLabelsRanges}; use crate::compilation::{Compilation, Relocations}; use crate::module::Module; use crate::module_environ::FunctionBodyData; use core::hash::Hasher; use cranelift_codegen::{ir, isa}; use cranelift_entity::PrimaryMap; use cranelift_wasm::DefinedFuncIndex; use...
} // Private static, so only internal function can access it. static CONFIG: Once<Config> = Once::new(); static INIT_CALLED: AtomicBool = AtomicBool::new(false); static DEFAULT_COMPRESSION_LEVEL: i32 = 0; // 0 for zstd means "use default level" /// Returns true if and only if the cache is enab...
struct Config { pub cache_enabled: bool, pub cache_dir: PathBuf, pub compression_level: i32,
random_line_split
main.rs
// vim:set et sw=4 ts=4 foldmethod=marker: #![warn(clippy::all, clippy::pedantic)] #![warn(missing_docs)] #![recursion_limit="512"] // starting doc {{{ //! ARES: Automatic REcord System. //! //! A Kubernetes-native system to automatically create and manage DNS records //! meant to run in parallel with External DNS....
() -> Result<()> { let opts: cli::Opts = cli::Opts::parse(); let decorator = slog_term::TermDecorator::new().build(); let drain = slog_term::FullFormat::new(decorator).build().fuse(); let drain = slog_async::Async::new(drain).build().fuse(); let root_logger = slog::Logger::root( drain, ...
main
identifier_name
main.rs
// vim:set et sw=4 ts=4 foldmethod=marker: #![warn(clippy::all, clippy::pedantic)] #![warn(missing_docs)] #![recursion_limit="512"] // starting doc {{{ //! ARES: Automatic REcord System. //! //! A Kubernetes-native system to automatically create and manage DNS records //! meant to run in parallel with External DNS....
info!(sub_logger, "Finished syncing"); info!(sub_logger, "Spawning watcher"); let res = collector.watch_values(&record.metadata, &sub_ac.provider, &mut builder).await; ...
{ crit!(sub_logger, "Error! {}", e); break }
conditional_block
main.rs
// vim:set et sw=4 ts=4 foldmethod=marker: #![warn(clippy::all, clippy::pedantic)] #![warn(missing_docs)] #![recursion_limit="512"] // starting doc {{{ //! ARES: Automatic REcord System. //! //! A Kubernetes-native system to automatically create and manage DNS records //! meant to run in parallel with External DNS....
//! ```yaml //! apiVersion: v1 //! kind: Pod //! metadata: //! name: nginx-hello-world //! app: nginx //! spec: //! containers: //! - name: nginx //! image: nginxdemos/hello //! --- //! apiVersion: syntixi.io/v1alpha1 //! kind: Record //! metadata: //! name: example-selector //! spec: //! fqdn: selector...
//! however, useful for making SPF records point to an outbound mail record, //! where the mail can be sent from one of many Nodes. //!
random_line_split
main.rs
// vim:set et sw=4 ts=4 foldmethod=marker: #![warn(clippy::all, clippy::pedantic)] #![warn(missing_docs)] #![recursion_limit="512"] // starting doc {{{ //! ARES: Automatic REcord System. //! //! A Kubernetes-native system to automatically create and manage DNS records //! meant to run in parallel with External DNS....
let config_content = config_data .get(opts.secret_key.as_str()) .ok_or(anyhow!("Unable to get key from Secret"))? .clone().0; debug!(root_logger, "Configuration loaded from Secret"); let config: Vec<Arc<AresConfig>> = serde_yaml::from_str::<Vec<_>>(std::str::from_utf8(&config_c...
{ let opts: cli::Opts = cli::Opts::parse(); let decorator = slog_term::TermDecorator::new().build(); let drain = slog_term::FullFormat::new(decorator).build().fuse(); let drain = slog_async::Async::new(drain).build().fuse(); let root_logger = slog::Logger::root( drain, o!("secret" =>...
identifier_body
core.rs
// Copyright (c) 2016-2021 Fabian Schuiki use crate::lexer::token::*; use crate::parser::rules::{Parser, Recovered, RecoveredResult, Reported, ReportedResult}; use moore_common::errors::*; use moore_common::name::*; use moore_common::source::*; use std; use std::fmt::Display; use std::marker::PhantomData; /// A predi...
<P: Parser>(p: &mut P) -> Option<Spanned<Name>> { let Spanned { value, span } = p.peek(0); match value { Ident(n) => { p.bump(); Some(Spanned::new(n, span)) } _ => None, } } /// Determine the earliest occurring token from a set. Useful to determine which /// ...
try_ident
identifier_name
core.rs
// Copyright (c) 2016-2021 Fabian Schuiki use crate::lexer::token::*; use crate::parser::rules::{Parser, Recovered, RecoveredResult, Reported, ReportedResult}; use moore_common::errors::*; use moore_common::name::*; use moore_common::source::*; use std; use std::fmt::Display; use std::marker::PhantomData; /// A predi...
Ok(x) => v.push(x), Err(_) => { term.recover(p, false); return Err(Recovered); } } } Ok(v) } /// Parse a list of items separated with a specific token, until a terminator /// oktne has been reached. The terminator is not consumed. pub ...
match parse(p) {
random_line_split
core.rs
// Copyright (c) 2016-2021 Fabian Schuiki use crate::lexer::token::*; use crate::parser::rules::{Parser, Recovered, RecoveredResult, Reported, ReportedResult}; use moore_common::errors::*; use moore_common::name::*; use moore_common::source::*; use std; use std::fmt::Display; use std::marker::PhantomData; /// A predi...
} impl<P, T> Predicate<P> for TokenPredicate<P, T> where P: Parser, T: Predicate<P>, { fn matches(&mut self, p: &mut P) -> bool { self.inner.matches(p) || p.peek(0).value == self.token } fn recover(&mut self, p: &mut P, consume: bool) { self.inner.recover(p, consume) } } impl...
{ TokenPredicate { inner: inner, token: token, _marker: PhantomData, } }
identifier_body
core.rs
// Copyright (c) 2016-2021 Fabian Schuiki use crate::lexer::token::*; use crate::parser::rules::{Parser, Recovered, RecoveredResult, Reported, ReportedResult}; use moore_common::errors::*; use moore_common::name::*; use moore_common::source::*; use std; use std::fmt::Display; use std::marker::PhantomData; /// A predi...
} /// Consume a specific token, or emit an error if the next token in the stream /// does not match the expected one. pub fn require<P: Parser>(p: &mut P, expect: Token) -> ReportedResult<()> { let Spanned { value: actual, span, } = p.peek(0); if actual == expect { p.bump(); ...
{ false }
conditional_block
ship_parser.rs
use log::{error, warn, debug, trace}; use serde_json::Value; use serde_json::map::Map; use crate::ballistics::{Ballistics, Dispersion}; use crate::gun::*; use crate::download::{download, download_with_params}; use serde_derive::Deserialize; use std::collections::HashMap; use cgmath::{Matrix4, Point3}; use std::io::pr...
(faces: &Vec<ArmorFace>) -> [f64; 3] { let mins = [ faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.x}).fold(1./0., f64::min), faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.y}).fold(1./0., f64::min), faces.iter().map(|face| { face.vertices.iter...
find_size
identifier_name
ship_parser.rs
use log::{error, warn, debug, trace}; use serde_json::Value; use serde_json::map::Map; use crate::ballistics::{Ballistics, Dispersion}; use crate::gun::*; use crate::download::{download, download_with_params}; use serde_derive::Deserialize; use std::collections::HashMap; use cgmath::{Matrix4, Point3}; use std::io::pr...
} faces } fn find_size(faces: &Vec<ArmorFace>) -> [f64; 3] { let mins = [ faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.x}).fold(1./0., f64::min), faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.y}).fold(1./0., f64::min), faces.iter()....
}
random_line_split
ship_parser.rs
use log::{error, warn, debug, trace}; use serde_json::Value; use serde_json::map::Map; use crate::ballistics::{Ballistics, Dispersion}; use crate::gun::*; use crate::download::{download, download_with_params}; use serde_derive::Deserialize; use std::collections::HashMap; use cgmath::{Matrix4, Point3}; use std::io::pr...
else if ammotype == "AP" { Ammo::new( AmmoType::Ap(ApAmmo::new( ammo["bulletDiametr"].as_f64().expect("Couldn't find bulletDiametr"), ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"), ammo["bulletDetonator"].as_f64().expect("Couldn't f...
{ Ammo::new( AmmoType::He(HeAmmo::new( ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"), ammo["alphaPiercingHE"].as_f64().expect("Couldn't find alphaPiercingHE"), )), ballistics, ) }
conditional_block
ship_parser.rs
use log::{error, warn, debug, trace}; use serde_json::Value; use serde_json::map::Map; use crate::ballistics::{Ballistics, Dispersion}; use crate::gun::*; use crate::download::{download, download_with_params}; use serde_derive::Deserialize; use std::collections::HashMap; use cgmath::{Matrix4, Point3}; use std::io::pr...
ammo, ) }).collect() } #[derive(Deserialize)] struct ArmorMaterial { #[serde(alias = "type")] armor_type: usize, thickness: usize, // mm } #[derive(Deserialize)] struct ArmorGroup { material: String, indices: Vec<usize>, } #[derive(Deserialize)] struct ArmorObject { v...
{ //debug!("{:#?}", artillery_spec); let guns = artillery_spec["guns"].as_object().unwrap(); /*for (key,gun) in guns { debug!("{}: {:?}", key, gun); }*/ let dispersion = Dispersion::new( artillery_spec["minDistH"].as_f64().expect("Couldn't find horizontal"), artillery_spec["minDi...
identifier_body
editor.rs
use rustyline_derive::{Completer, Hinter, Validator}; use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer}; use serde_json::json; use std::{cell::RefCell, collections::HashMap, fmt::Write, ops::Range}; use tree_sitter::{Query, QueryCursor}; use tree_sitter_highlight::{HighlightConfiguration,...
} HighlightEvent::Source { start, end } => { let style = style_stack.last().unwrap(); stylings.insert(*style, start..end, 1); } } } let parsed = hi.parser().parse(line, None); if let Some(parsed)...
style_stack.pop();
random_line_split
editor.rs
ustyline_derive::{Completer, Hinter, Validator}; use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer}; use serde_json::json; use std::{cell::RefCell, collections::HashMap, fmt::Write, ops::Range}; use tree_sitter::{Query, QueryCursor}; use tree_sitter_highlight::{HighlightConfiguration, High...
{ pub ansi: ansi_term::Style, pub css: Option<String>, } #[derive(Debug)] pub struct Theme { pub styles: Vec<Style>, pub highlight_names: Vec<String>, } #[derive(Default, Deserialize, Serialize)] pub struct ThemeConfig { #[serde(default)] pub theme: Theme, } impl Theme { /* pub fn load(p...
Style
identifier_name
editor.rs
rustyline_derive::{Completer, Hinter, Validator}; use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer}; use serde_json::json; use std::{cell::RefCell, collections::HashMap, fmt::Write, ops::Range}; use tree_sitter::{Query, QueryCursor}; use tree_sitter_highlight::{HighlightConfiguration, Hi...
} if len > 0 { let mut start = HashMap::new(); let mut end = HashMap::new(); for (i, r) in self.current.iter().enumerate() { start .entry(r.range.start) .or_insert_with(Vec::new) .push((i, &r.style...
self.backing[0].1 }
identifier_body
lib.rs
//! # docker-bisect //! `docker-bisect` create assumes that the docker daemon is running and that you have a //! docker image with cached layers to probe. extern crate colored; extern crate dockworker; extern crate indicatif; extern crate rand; use std::clone::Clone; use std::fmt; use std::io::{prelude::*, Error, Erro...
<T>(layers: Vec<Layer>, action: &T) -> Result<Vec<Transition>, Error> where T: ContainerAction +'static, { let first_layer = layers.first().expect("no first layer"); let last_layer = layers.last().expect("no last layer"); let first_image_name: String = first_layer.image_name.clone(); let last_image...
get_changes
identifier_name
lib.rs
//! # docker-bisect //! `docker-bisect` create assumes that the docker daemon is running and that you have a //! docker image with cached layers to probe. extern crate colored; extern crate dockworker; extern crate indicatif; extern crate rand; use std::clone::Clone; use std::fmt; use std::io::{prelude::*, Error, Erro...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self.before { Some(be) => write!(f, "({} -> {})", be, self.after), None => write!(f, "-> {}", self.after), } } } /// Starts the bisect operation. Calculates highest and lowest layer result and if they have ///...
impl fmt::Display for Transition {
random_line_split
lib.rs
//! # docker-bisect //! `docker-bisect` create assumes that the docker daemon is running and that you have a //! docker image with cached layers to probe. extern crate colored; extern crate dockworker; extern crate indicatif; extern crate rand; use std::clone::Clone; use std::fmt; use std::io::{prelude::*, Error, Erro...
match r.read(&mut g.buf[g.len..]) { Ok(0) => { break; } Ok(n) => g.len += n, Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(_e) => { break; } } if Syst...
{ g.buf.resize(g.len + reservation_size, 0); }
conditional_block
lib.rs
//! # docker-bisect //! `docker-bisect` create assumes that the docker daemon is running and that you have a //! docker image with cached layers to probe. extern crate colored; extern crate dockworker; extern crate indicatif; extern crate rand; use std::clone::Clone; use std::fmt; use std::io::{prelude::*, Error, Erro...
} fn lay(id: usize) -> Layer { Layer { height: id, image_name: id.to_string(), creation_command: id.to_string(), } } #[test] fn if_output_always_same_return_earliest_command() { let results = get_changes( vec![lay(1), lay(2),...
{}
identifier_body
lib.rs
use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; /// `InputCellID` is a unique identifier for an input cell. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InputCellID(usize); /// `ComputeCellID` is a unique identifier for a compute cell. /// Values of type ...
} // Sets the value of the specified input cell. // // Returns false if the cell does not exist. // // Similarly, you may wonder about `get_mut(&mut self, id: CellID) -> Option<&mut Cell>`, with // a `set_value(&mut self, new_value: T)` method on `Cell`. // // As before, that turned...
}
random_line_split
lib.rs
use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; /// `InputCellID` is a unique identifier for an input cell. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InputCellID(usize); /// `ComputeCellID` is a unique identifier for a compute cell. /// Values of type ...
} struct ComputeCell<'r, T: Debug> { fun: Box<dyn 'r + Fn(&[T]) -> T>, deps: Vec<CellID>, callbacks: HashMap<CallbackID, Callback<'r, T>>, prev_val: Cell<Option<T>>, next_cbid: usize, // increases monotonically; increments on adding a callback clients: HashSet<ComputeCellID>, } impl<'r, T: Co...
{ InputCell { clients: HashSet::new(), value: init, } }
identifier_body
lib.rs
use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; /// `InputCellID` is a unique identifier for an input cell. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InputCellID(usize); /// `ComputeCellID` is a unique identifier for a compute cell. /// Values of type ...
() -> Self { Reactor { input_cells: Vec::new(), compute_cells: Vec::new(), } } // Creates an input cell with the specified initial value, returning its ID. pub fn create_input(&mut self, initial: T) -> InputCellID { let idx = self.input_cells.len(); l...
new
identifier_name
wasitests.rs
//! This file will run at build time to autogenerate the WASI regression tests //! It will compile the files indicated in TESTS, to:executable and.wasm //! - Compile with the native rust target to get the expected output //! - Compile with the latest WASI target to get the wasm //! - Generate the test that will compare...
#[derive(Debug, Clone, PartialEq, Eq)] pub struct NativeOutput { stdout: String, stderr: String, result: i64, } /// Compile and execute the test file as native code, saving the results to be /// compared against later. /// /// This function attempts to clean up its output after it executes it. fn generate_...
use super::util; use super::wasi_version::*;
random_line_split
wasitests.rs
//! This file will run at build time to autogenerate the WASI regression tests //! It will compile the files indicated in TESTS, to:executable and.wasm //! - Compile with the native rust target to get the expected output //! - Compile with the latest WASI target to get the wasm //! - Generate the test that will compare...
} Err(e) => println!("{:?}", e), } } println!("All modules generated."); } /// This is the structure of the `.wast` file #[derive(Debug, Default, Serialize, Deserialize)] pub struct WasiTest { /// The name of the wasm module to run pub wasm_prog_name: String, /// Th...
{ compile(temp_dir.path(), test, wasi_versions); }
conditional_block
wasitests.rs
//! This file will run at build time to autogenerate the WASI regression tests //! It will compile the files indicated in TESTS, to:executable and.wasm //! - Compile with the native rust target to get the expected output //! - Compile with the latest WASI target to get the wasm //! - Generate the test that will compare...
(temp_dir: &Path, file: &str, wasi_versions: &[WasiVersion]) { let src_code: String = fs::read_to_string(file).unwrap(); let options: WasiOptions = extract_args_from_source_file(&src_code).unwrap_or_default(); assert!(file.ends_with(".rs")); let rs_mod_name = { Path::new(&file.to_lowercase()) ...
compile
identifier_name
wasitests.rs
//! This file will run at build time to autogenerate the WASI regression tests //! It will compile the files indicated in TESTS, to:executable and.wasm //! - Compile with the native rust target to get the expected output //! - Compile with the latest WASI target to get the wasm //! - Generate the test that will compare...
.options .args .iter() .map(|v| format!("\"{}\"", v)) .collect::<Vec<String>>() .join(" "); let _ = write!(out, "\n (args {})", args); } if!self.options.dir.is_empty() { let preopens = sel...
{ use std::fmt::Write; let mut out = format!( ";; This file was generated by https://github.com/wasmerio/wasi-tests\n (wasi_test \"{}\"", self.wasm_prog_name ); if !self.options.env.is_empty() { let envs = self .options ...
identifier_body
test.rs
use super::{cmd, Expression}; use std; use std::collections::HashMap; use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::OsString; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Command; use std::str; use std::sync::{Arc, Once}; // Include a cop...
() { // Windows compatible. let output = sh("echo hi").read().unwrap(); assert_eq!("hi", output); } #[test] fn test_start() { let handle1 = cmd!(path_to_exe("echo"), "hi") .stdout_capture() .start() .unwrap(); let handle2 = cmd!(path_to_exe("echo"), "lo") .stdout_capture...
test_sh
identifier_name
test.rs
use super::{cmd, Expression}; use std; use std::collections::HashMap; use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::OsString; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Command; use std::str; use std::sync::{Arc, Once}; // Include a cop...
else { assert_eq!(output1, "abc123"); } } #[test] fn test_broken_pipe() { // If the input writing thread fills up its pipe buffer, writing will block. If the process // on the other end of the pipe exits while writer is waiting, the write will return an // error. We need to swallow that error,...
{ assert_eq!(output1, ""); }
conditional_block
test.rs
use super::{cmd, Expression}; use std; use std::collections::HashMap; use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::OsString; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Command; use std::str; use std::sync::{Arc, Once}; // Include a cop...
let handle2 = cmd!(path_to_exe("echo"), "lo") .stdout_capture() .start() .unwrap(); let output1 = handle1.wait().unwrap(); let output2 = handle2.wait().unwrap(); assert_eq!("hi", str::from_utf8(&output1.stdout).unwrap().trim()); assert_eq!("lo", str::from_utf8(&output2.stdout).u...
.stdout_capture() .start() .unwrap();
random_line_split
test.rs
use super::{cmd, Expression}; use std; use std::collections::HashMap; use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::OsString; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Command; use std::str; use std::sync::{Arc, Once}; // Include a cop...
#[test] fn test_pipe_start() { let nonexistent_cmd = cmd!(path_to_exe("nonexistent!!!")); let sleep_cmd = cmd!(path_to_exe("sleep"), "1000000"); // Errors starting the left side of a pipe are returned immediately, and // the right side is never started. nonexistent_cmd.pipe(&sleep_cmd).start().un...
{ // Make sure both sides get killed. let sleep_cmd = cmd!(path_to_exe("sleep"), "1000000"); // Note that we don't use unchecked() here. This tests that kill suppresses // exit status errors. let handle = sleep_cmd.pipe(sleep_cmd.clone()).start().unwrap(); handle.kill().unwrap(); // But call...
identifier_body
lib.rs
//! Pretty printing for Javascript values from [wasm-bindgen](https://docs.rs/wasm-bindgen). #![forbid(unsafe_code)] use js_sys::{ Array, Date, Error, Function, JsString, Map, Object, Promise, Reflect, RegExp, Set, Symbol, WeakSet, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet}, fmt::{Debug,...
; impl Debug for JsFunction { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "[Function]") } } #[cfg(test)] mod tests { use super::*; use futures::channel::oneshot::channel; use wasm_bindgen::closure::Closure; use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_confi...
JsFunction
identifier_name
lib.rs
//! Pretty printing for Javascript values from [wasm-bindgen](https://docs.rs/wasm-bindgen). #![forbid(unsafe_code)] use js_sys::{ Array, Date, Error, Function, JsString, Map, Object, Promise, Reflect, RegExp, Set, Symbol, WeakSet, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet}, fmt::{Debug,...
where T: AsRef<JsValue>, { fn pretty(&self) -> Prettified { Prettified { value: self.as_ref().to_owned(), seen: WeakSet::new(), skip: Default::default(), } } } /// A pretty-printable value from Javascript. pub struct Prettified { /// The current value...
impl<T> Pretty for T
random_line_split
lib.rs
//! Pretty printing for Javascript values from [wasm-bindgen](https://docs.rs/wasm-bindgen). #![forbid(unsafe_code)] use js_sys::{ Array, Date, Error, Function, JsString, Map, Object, Promise, Reflect, RegExp, Set, Symbol, WeakSet, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet}, fmt::{Debug,...
); } #[wasm_bindgen_test] fn repeated_siblings_are_not_cycles() { let with_siblings = js_sys::Function::new_no_args( r#" let root = { child: { nested: [] } }; let repeated_child = { foo: "bar" }; root.child.nested.push(repeated_child); ...
{ let with_cycles = js_sys::Function::new_no_args( r#" let root = { child: { nested: [] } }; root.child.nested.push(root); return root; "#, ) .call0(&JsValue::null()) .unwrap(); assert_eq!( with_cycles.pretty()....
identifier_body
renderer.rs
use std::f64; use pcg_rand::Pcg32; use rand::{Rng, SeedableRng}; use crate::hitpoint::Hitpoint; use crate::math::{add, brdf, dot, elementwise_mul, intensity_to_color, min, mul, norm, random_from_brdf, sub}; use crate::ray::Ray; use crate::renderershape::RendererShape; use crate::rendereroutputpixel::RendererOutputPix...
(&self, colors: &[[f64; 3]], number_of_batches: usize, batch_size: usize) -> Vec<[f64; 3]> { let mut averages: Vec<[f64; 3]> = vec![[0.0, 0.0, 0.0]; number_of_batches]; for i in 0..colors.len() { averages[i/batch_size] = add(averages[i/batch_size], colors[i]); } for average in &mut averages { *average = m...
averages
identifier_name
renderer.rs
use std::f64; use pcg_rand::Pcg32; use rand::{Rng, SeedableRng}; use crate::hitpoint::Hitpoint; use crate::math::{add, brdf, dot, elementwise_mul, intensity_to_color, min, mul, norm, random_from_brdf, sub}; use crate::ray::Ray; use crate::renderershape::RendererShape; use crate::rendereroutputpixel::RendererOutputPix...
} } let max_r_distance = (largest[0]-smallest[0]).abs(); let max_g_distance = (largest[1]-smallest[1]).abs(); let max_b_distance = (largest[2]-smallest[2]).abs(); max_r_distance+max_g_distance+max_b_distance } fn create_hitpoint_path(&mut self, mut ray: &mut Ray, color: &mut [f64; 3], hitpoint_path: &m...
{ largest[j] = average[j]; }
conditional_block
renderer.rs
use std::f64; use pcg_rand::Pcg32; use rand::{Rng, SeedableRng}; use crate::hitpoint::Hitpoint; use crate::math::{add, brdf, dot, elementwise_mul, intensity_to_color, min, mul, norm, random_from_brdf, sub}; use crate::ray::Ray; use crate::renderershape::RendererShape; use crate::rendereroutputpixel::RendererOutputPix...
} } for (i, sphere) in self.scene.renderer_spheres.iter().enumerate() { if!sphere.active { continue; } let distance = sphere.distance(&ray); if distance < min_distance { min_distance = distance; closest_renderer_shape_index = Some(i); renderer_type = RendererType::Sphere; } } f...
} let distance = cylinder.distance(&ray); if distance < min_distance { min_distance = distance; closest_renderer_shape_index = Some(i);
random_line_split
renderer.rs
use std::f64; use pcg_rand::Pcg32; use rand::{Rng, SeedableRng}; use crate::hitpoint::Hitpoint; use crate::math::{add, brdf, dot, elementwise_mul, intensity_to_color, min, mul, norm, random_from_brdf, sub}; use crate::ray::Ray; use crate::renderershape::RendererShape; use crate::rendereroutputpixel::RendererOutputPix...
// Find the closest hitpoint. fn closest_renderer_shape(&self, ray: &mut Ray) -> Option<Hitpoint> { let mut min_distance = f64::MAX; let mut closest_renderer_shape_index: Option<usize> = None; let mut renderer_type = RendererType::Cylinder; for (i, cylinder) in self.scene.renderer_cylinders.iter().enumerat...
{ self.renderer_output_pixels[last_pos].pixel.color = add(self.renderer_output_pixels[last_pos].pixel.color, color); self.renderer_output_pixels[last_pos].color = add(self.renderer_output_pixels[last_pos].color, color); self.renderer_output_pixels[last_pos].number_of_bin_elements += 1; if self.perform_post_proc...
identifier_body
de.rs
use serde::{ de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}, forward_to_deserialize_any, }; use serde::Deserialize; use std::{cell::Cell, fmt}; #[derive(Debug, PartialEq)] pub enum DeserializeError { UnexpectedEOF, WrongCharacter(u8), End, InfoHashMissing, TooDeep, NoFile, E...
(&self) -> &str { "aa" //self.msg.as_str() } } pub fn from_bytes<'de, T>(s: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut de: Deserializer = Deserializer::new(s); T::deserialize(&mut de) } pub fn from_bytes_with_hash<'de, T>(s: &'de [u8]) -> Result<(T, Vec<u8>)> where ...
description
identifier_name
de.rs
use serde::{ de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}, forward_to_deserialize_any, }; use serde::Deserialize; use std::{cell::Cell, fmt}; #[derive(Debug, PartialEq)] pub enum DeserializeError { UnexpectedEOF, WrongCharacter(u8), End, InfoHashMissing, TooDeep, NoFile, E...
} #[test] fn test_key_no_value() { #[derive(Deserialize, PartialEq, Debug)] struct Dict<'b> { a: i64, b: &'b str, } let res: Result<Dict> = from_bytes(b"d1:ai1e1:be"); println!("{:?}", res); assert_eq!(res, Err(DeserializeError::Wro...
{ #[derive(Deserialize, PartialEq, Debug)] struct Dict<'b> { a: i64, b: &'b str, c: &'b str, X: &'b str, } let bc: Dict = from_bytes(b"d1:ai12453e1:b3:aaa1:c3:bbb1:X10:0123456789e").unwrap(); assert_eq!( bc, ...
identifier_body
de.rs
use serde::{ de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}, forward_to_deserialize_any, }; use serde::Deserialize; use std::{cell::Cell, fmt}; #[derive(Debug, PartialEq)] pub enum DeserializeError { UnexpectedEOF, WrongCharacter(u8), End, InfoHashMissing, TooDeep, NoFile, E...
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { // println!("NEXT: {:?}", self.peek()); match self.peek().ok_or(DeserializeError::UnexpectedEOF)? { b'i' => { // println!("FOUND NUMBER", ); visitor.visit...
#[doc(hidden)] impl<'a, 'de> serde::de::Deserializer<'de> for &'a mut Deserializer<'de> { type Error = DeserializeError;
random_line_split
main.rs
multisample::MultisampleState, rasterization::RasterizationState, vertex_input::{Vertex, VertexDefinition}, viewport::{Viewport, ViewportState}, GraphicsPipelineCreateInfo, }, layout::PipelineDescriptorSetLayoutCreateInfo, GraphicsPipelin...
let device_extensions = DeviceExtensions { khr_swapchain: true, ..DeviceExtensions::empty() }; let (physical_device, queue_family_index) = instance .enumerate_physical_devices() .unwrap() .filter(|p| p.supported_extensions().contains(&device_extensions)) .filter_m...
{ // The start of this example is exactly the same as `triangle`. You should read the `triangle` // example if you haven't done so yet. let event_loop = EventLoop::new(); let library = VulkanLibrary::new().unwrap(); let required_extensions = Surface::required_extensions(&event_loop); let insta...
identifier_body
main.rs
multisample::MultisampleState, rasterization::RasterizationState, vertex_input::{Vertex, VertexDefinition}, viewport::{Viewport, ViewportState}, GraphicsPipelineCreateInfo, }, layout::PipelineDescriptorSetLayoutCreateInfo, GraphicsPipelin...
() { // The start of this example is exactly the same as `triangle`. You should read the `triangle` // example if you haven't done so yet. let event_loop = EventLoop::new(); let library = VulkanLibrary::new().unwrap(); let required_extensions = Surface::required_extensions(&event_loop); let in...
main
identifier_name
main.rs
multisample::MultisampleState, rasterization::RasterizationState, vertex_input::{Vertex, VertexDefinition}, viewport::{Viewport, ViewportState}, GraphicsPipelineCreateInfo, }, layout::PipelineDescriptorSetLayoutCreateInfo, GraphicsPipeli...
event_loop.run(move |event, _, control_flow| { match event { Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { *control_flow = ControlFlow::Exit; } Event::WindowEvent { event: Win...
let descriptor_set_allocator = StandardDescriptorSetAllocator::new(device.clone()); let command_buffer_allocator = StandardCommandBufferAllocator::new(device.clone(), Default::default());
random_line_split
fmlrc2.rs
extern crate clap; extern crate env_logger; extern crate exitcode; extern crate log; extern crate needletail; use clap::{Arg, App, value_t, values_t}; use log::{info, error}; use needletail::parse_fastx_file; use std::fs::File; use std::sync::{Arc, mpsc}; use threadpool::ThreadPool; use fmlrc::bv_bwt::BitVectorBWT; ...
() { //initialize logging for our benefit later env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); //non-cli parameters const JOB_SLOTS: u64 = 10000; const UPDATE_INTERVAL: u64 = 10000; //this is the CLI block, params that get populated appear before let...
main
identifier_name
fmlrc2.rs
extern crate clap; extern crate env_logger; extern crate exitcode; extern crate log; extern crate needletail; use clap::{Arg, App, value_t, values_t}; use log::{info, error}; use needletail::parse_fastx_file; use std::fs::File; use std::sync::{Arc, mpsc}; use threadpool::ThreadPool; use fmlrc::bv_bwt::BitVectorBWT; u...
.help("The FASTA file to write corrected reads to") .required(true) .index(3)) .get_matches(); //pull out required values bwt_fn = matches.value_of("COMP_MSBWT.NPY").unwrap().to_string(); long_read_fn = matches.value_of("LONG_READS.FA").unwrap().to_string(); ...
.index(2)) .arg(Arg::with_name("CORRECTED_READS.FA")
random_line_split
fmlrc2.rs
extern crate clap; extern crate env_logger; extern crate exitcode; extern crate log; extern crate needletail; use clap::{Arg, App, value_t, values_t}; use log::{info, error}; use needletail::parse_fastx_file; use std::fs::File; use std::sync::{Arc, mpsc}; use threadpool::ThreadPool; use fmlrc::bv_bwt::BitVectorBWT; ...
//clone the transmit channel and submit the pool job let tx = tx.clone(); let arc_bwt = arc_bwt.clone(); let arc_params = arc_params.clone(); let read_data: LongReadFA = LongReadFA { read_index:...
{ let rx_value: CorrectionResults = rx.recv().unwrap(); if verbose_mode { info!("Job #{:?}: {:.2} -> {:.2}", rx_value.read_index, rx_value.avg_before, rx_value.avg_after); } match fasta_writer.wri...
conditional_block
fmlrc2.rs
extern crate clap; extern crate env_logger; extern crate exitcode; extern crate log; extern crate needletail; use clap::{Arg, App, value_t, values_t}; use log::{info, error}; use needletail::parse_fastx_file; use std::fs::File; use std::sync::{Arc, mpsc}; use threadpool::ThreadPool; use fmlrc::bv_bwt::BitVectorBWT; ...
let verbose_mode: bool; let matches = App::new("FMLRC2") .version(VERSION.unwrap_or("?")) .author("J. Matthew Holt <jholt@hudsonalpha.org>") .about("FM-index Long Read Corrector - Rust implementation") .arg(Arg::with_name("verbose_mode") .short("v") .long("...
{ //initialize logging for our benefit later env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); //non-cli parameters const JOB_SLOTS: u64 = 10000; const UPDATE_INTERVAL: u64 = 10000; //this is the CLI block, params that get populated appear before let bw...
identifier_body
browser.rs
command_response, CommandMessage}; use crate::conn::Connection; use crate::error::{CdpError, Result}; use crate::handler::browser::BrowserContext; use crate::handler::viewport::Viewport; use crate::handler::{Handler, HandlerConfig, HandlerMessage, REQUEST_TIMEOUT}; use crate::listeners::{EventListenerRequest, EventStre...
} self } pub fn build(self) -> std::result::Result<BrowserConfig, String> { let executable = if let Some(e) = self.executable { e } else { default_executable()? }; Ok(BrowserConfig { headless: self.headless, sandbo...
self.args.push(arg.into());
random_line_split
browser.rs
_response, CommandMessage}; use crate::conn::Connection; use crate::error::{CdpError, Result}; use crate::handler::browser::BrowserContext; use crate::handler::viewport::Viewport; use crate::handler::{Handler, HandlerConfig, HandlerMessage, REQUEST_TIMEOUT}; use crate::listeners::{EventListenerRequest, EventStream}; us...
} } else { line = String::new(); } } } cfg_if::cfg_if! { if #[cfg(feature = "async-std-runtime")] { async_std::task::spawn_blocking(|| read_debug_url(stdout)).await } else if #[cfg(feature = "tokio-runtime")] { ...
{ return ws.trim().to_string(); }
conditional_block
browser.rs
_response, CommandMessage}; use crate::conn::Connection; use crate::error::{CdpError, Result}; use crate::handler::browser::BrowserContext; use crate::handler::viewport::Viewport; use crate::handler::{Handler, HandlerConfig, HandlerMessage, REQUEST_TIMEOUT}; use crate::listeners::{EventListenerRequest, EventStream}; us...
{ let default_paths = &["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"][..]; for path in default_paths { if std::path::Path::new(path).exists() { return Ok(path.into()); } } } #[cfg(windows)] { if let Some(path) = g...
{ if let Ok(path) = std::env::var("CHROME") { if std::path::Path::new(&path).exists() { return Ok(path.into()); } } for app in &[ "google-chrome-stable", "chromium", "chromium-browser", "chrome", "chrome-browser", ] { if let Ok...
identifier_body
browser.rs
_response, CommandMessage}; use crate::conn::Connection; use crate::error::{CdpError, Result}; use crate::handler::browser::BrowserContext; use crate::handler::viewport::Viewport; use crate::handler::{Handler, HandlerConfig, HandlerMessage, REQUEST_TIMEOUT}; use crate::listeners::{EventListenerRequest, EventStream}; us...
(config: BrowserConfig) -> Result<(Self, Handler)> { // launch a new chromium instance let mut child = config.launch()?; // extract the ws: let get_ws_url = ws_url_from_output(&mut child); let dur = Duration::from_secs(20); cfg_if::cfg_if! { if #[cfg(featur...
launch
identifier_name
main.rs
#![feature(plugin, decl_macro, custom_derive, type_ascription)] // Compiler plugins #![plugin(rocket_codegen)] // rocket code generator extern crate rocket; extern crate rabe; extern crate serde; extern crate serde_json; extern crate rustc_serialize; extern crate blake2_rfc; extern crate rocket_simpleauth; exter...
(d:Json<User>) -> Result<(), BadRequest<String>> { let ref username: String = d.username; let ref passwd: String = d.password; let ref random_session_id = d.random_session_id; let salt: i32 = 1234; // TODO use random salt when storing hashed user passwords println!("Adding user {} {} {} {}", &use...
add_user
identifier_name
main.rs
#![feature(plugin, decl_macro, custom_derive, type_ascription)] // Compiler plugins #![plugin(rocket_codegen)] // rocket code generator extern crate rocket; extern crate rabe; extern crate serde; extern crate serde_json; extern crate rustc_serialize; extern crate blake2_rfc; extern crate rocket_simpleauth; exter...
Ok(_usize) => Ok(session_id), Err(_e) => Err("Could not insert into sessions".to_string()) } } Err(_) => Err("Invalid scheme".to_string()) } } fn db_get_session_by_api_key(conn: &MysqlConnection, api_key: &String) -> Result<schema::Session, diesel::result::Error> { use schema::sessions; sessio...
{ use schema::sessions; println!("Got scheme {}", scheme); match scheme.parse::<SCHEMES>() { Ok(_scheme) => { let session_id: String = OsRng::new().unwrap().next_u64().to_string(); let session = schema::NewSession { is_initialized: false, scheme: scheme.to_string(), random_session_id: session_id....
identifier_body
main.rs
#![feature(plugin, decl_macro, custom_derive, type_ascription)] // Compiler plugins #![plugin(rocket_codegen)] // rocket code generator extern crate rocket; extern crate rabe; extern crate serde; extern crate serde_json; extern crate rustc_serialize; extern crate blake2_rfc; extern crate rocket_simpleauth; exter...
} // ----------------------------------------------------- // Message formats follow // ----------------------------------------------------- #[derive(Serialize, Deserialize)] struct Message { contents: String } #[derive(Serialize, Deserialize)] struct SetupMsg { scheme: String, attributes: Vec<S...
return Outcome::Failure((Status::Unauthorized, ())); } return Outcome::Success(ApiKey(key.to_string())); }
random_line_split
server.rs
// Copyright (c) 2019 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not b...
let mut header_buf = [httparse::EMPTY_HEADER; MAX_NUM_HEADERS]; let mut request = httparse::Request::new(&mut header_buf); match request.parse(self.buffer.as_ref()) { Ok(httparse::Status::Complete(_)) => (), Ok(httparse::Status::Partial) => return Err(Error::IncompleteHttpRequest), Err(e) => return Err(...
self.socket } // Decode client handshake request. fn decode_request(&mut self) -> Result<ClientRequest, Error> {
random_line_split
server.rs
// Copyright (c) 2019 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not b...
} let path = request.path.unwrap_or("/"); Ok(ClientRequest { ws_key, protocols, path, headers }) } // Encode server handshake response. fn encode_response(&mut self, response: &Response<'_>) { match response { Response::Accept { key, protocol } => { let accept_value = super::generate_accept_key(&k...
{ protocols.push(p) }
conditional_block
server.rs
// Copyright (c) 2019 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not b...
/// Await an incoming client handshake request. pub async fn receive_request(&mut self) -> Result<ClientRequest<'_>, Error> { self.buffer.clear(); let mut skip = 0; loop { crate::read(&mut self.socket, &mut self.buffer, BLOCK_SIZE).await?; let limit = std::cmp::min(self.buffer.len(), MAX_HEADERS_SIZE...
{ self.extensions.drain(..) }
identifier_body
server.rs
// Copyright (c) 2019 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not b...
<'a, T> { socket: T, /// Protocols the server supports. protocols: Vec<&'a str>, /// Extensions the server supports. extensions: Vec<Box<dyn Extension + Send>>, /// Encoding/decoding buffer. buffer: BytesMut, } impl<'a, T: AsyncRead + AsyncWrite + Unpin> Server<'a, T> { /// Create a new server handshake. pub ...
Server
identifier_name
vga_buffer.rs
use core::fmt; use volatile::Volatile; use spin::Mutex; #[allow(dead_code)] // prevents compiler warnings that some enumerations are never used #[derive(Debug, Clone, Copy, PartialEq, Eq)] // enables copy semantics for the type: makes printable & comparable #[repr(u8)] // makes each enum variant be stor...
LightRed = 12, Pink = 13, Yellow = 14, White = 15, } // used to represent a full VGA color code (foreground & background) #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct ColorCode(u8); // creates a type which is essentially an alias for a single byte impl ColorCode { // creates a single ...
LightGreen = 10, LightCyan = 11,
random_line_split
vga_buffer.rs
use core::fmt; use volatile::Volatile; use spin::Mutex; #[allow(dead_code)] // prevents compiler warnings that some enumerations are never used #[derive(Debug, Clone, Copy, PartialEq, Eq)] // enables copy semantics for the type: makes printable & comparable #[repr(u8)] // makes each enum variant be stor...
else { assert_eq!(screen_char, empty_char()); } } } } }
{ // ensures empty lines are shifted in on a new line and have correct color code assert_eq!(screen_char.ascii_character, b' '); assert_eq!(screen_char.color_code, writer.color_code); }
conditional_block
vga_buffer.rs
use core::fmt; use volatile::Volatile; use spin::Mutex; #[allow(dead_code)] // prevents compiler warnings that some enumerations are never used #[derive(Debug, Clone, Copy, PartialEq, Eq)] // enables copy semantics for the type: makes printable & comparable #[repr(u8)] // makes each enum variant be stor...
{ Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, Pink = 13, Yellow = 14, White = 15, } // used to represent a full VGA color code (for...
Color
identifier_name