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 |
|---|---|---|---|---|
rxcb.rs | //! Objective XCB Wrapper
#![allow(dead_code)]
extern crate univstring; use self::univstring::UnivString;
extern crate xcb;
use self::xcb::ffi::*;
use std::ptr::{null, null_mut};
use std::marker::PhantomData;
use std::io::{Error as IOError, ErrorKind};
#[repr(C)] pub enum WindowIOClass
{
InputOnly = XCB_WINDOW_CLAS... | }
impl<T:?Sized> DerefMut for MallocBox<T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.0 } } }
impl<T:?Sized> Drop for MallocBox<T>
{
fn drop(&mut self) { unsafe { ::libc::free(self.0 as *mut _) } }
}
impl<T:?Sized> Debug for MallocBox<T> where T: Debug
{
fn fmt(&self, fmt: &mut Formatter) -> FmtResult... | { unsafe { &*self.0 } } | identifier_body |
rxcb.rs | //! Objective XCB Wrapper
#![allow(dead_code)]
extern crate univstring; use self::univstring::UnivString;
extern crate xcb;
use self::xcb::ffi::*;
use std::ptr::{null, null_mut};
use std::marker::PhantomData;
use std::io::{Error as IOError, ErrorKind};
#[repr(C)] pub enum WindowIOClass
{
InputOnly = XCB_WINDOW_CLAS... | (&self) -> Window { Window(self.new_id()) }
/*pub fn try_intern(&self, name: &str) -> AtomCookie
{
AtomCookie(unsafe { xcb_intern_atom(self.0, 0, name.len() as _, name.as_ptr()) }, self)
}*/
pub fn intern(&self, name: &str) -> AtomCookie
{
AtomCookie(unsafe { xcb_intern_atom(self.0, 1, name.len() as _, name.a... | new_window_id | identifier_name |
git.rs | //! Getting the Git status of files and directories.
use std::ffi::OsStr;
#[cfg(target_family = "unix")]
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use log::*;
use crate::fs::fields as f;
/// A **Git cache** is assembled based on the user’s input arguments.
///
/// This... | }
/// The character to display if the file has been modified and the change
/// has been staged.
fn index_status(status: git2::Status) -> f::GitStatus {
match status {
s if s.contains(git2::Status::INDEX_NEW) => f::GitStatus::New,
s if s.contains(git2::Status::INDEX_MODIFIED) => f::GitSt... | s if s.contains(git2::Status::WT_TYPECHANGE) => f::GitStatus::TypeChange,
s if s.contains(git2::Status::IGNORED) => f::GitStatus::Ignored,
s if s.contains(git2::Status::CONFLICTED) => f::GitStatus::Conflicted,
_ => f::GitStatus::Not... | random_line_split |
git.rs | //! Getting the Git status of files and directories.
use std::ffi::OsStr;
#[cfg(target_family = "unix")]
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use log::*;
use crate::fs::fields as f;
/// A **Git cache** is assembled based on the user’s input arguments.
///
/// This... | t {
let path = reorient(dir);
let s = self.statuses.iter()
.filter(|p| if p.1 == git2::Status::IGNORED {
path.starts_with(&p.0)
} else {
p.0.starts_with(&path)
})
.fold(git2::Status::empty(), |a, b| a | b.1);
let sta... | ) -> f::Gi | identifier_name |
structure.rs | mod iter;
use super::{
drop_items::DropItem,
dyn_iter::{DynIter, DynIterMut},
items::ItemType,
underground_belt::UnderDirection,
water_well::FluidBox,
FactorishState, Inventory, InventoryTrait, Recipe,
};
use rotate_enum::RotateEnum;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
us... | impl Position {
pub fn new(x: i32, y: i32) -> Self {
Self { x, y }
}
pub(crate) fn div_mod(&self, size: i32) -> (Position, Position) {
let div = Position::new(self.x.div_euclid(size), self.y.div_euclid(size));
let mod_ = Position::new(self.x.rem_euclid(size), self.y.rem_euclid(size)... | }
| random_line_split |
structure.rs | mod iter;
use super::{
drop_items::DropItem,
dyn_iter::{DynIter, DynIterMut},
items::ItemType,
underground_belt::UnderDirection,
water_well::FluidBox,
FactorishState, Inventory, InventoryTrait, Recipe,
};
use rotate_enum::RotateEnum;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
us... |
fn select_recipe(&mut self, _index: usize) -> Result<bool, JsValue> {
Err(JsValue::from_str("recipes not available"))
}
fn get_selected_recipe(&self) -> Option<&Recipe> {
None
}
fn fluid_box(&self) -> Option<Vec<&FluidBox>> {
None
}
fn fluid_box_mut(&mut self) -> Opt... | {
Cow::from(&[][..])
} | identifier_body |
structure.rs | mod iter;
use super::{
drop_items::DropItem,
dyn_iter::{DynIter, DynIterMut},
items::ItemType,
underground_belt::UnderDirection,
water_well::FluidBox,
FactorishState, Inventory, InventoryTrait, Recipe,
};
use rotate_enum::RotateEnum;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
us... |
}
/// Query a set of items that this structure can output. Actual output would not happen until `output()`, thus
/// this method is immutable. It should return empty Inventory if it cannot output anything.
fn can_output(&self, _structures: &StructureDynIter) -> Inventory {
Inventory::new()
... | {
false
} | conditional_block |
structure.rs | mod iter;
use super::{
drop_items::DropItem,
dyn_iter::{DynIter, DynIterMut},
items::ItemType,
underground_belt::UnderDirection,
water_well::FluidBox,
FactorishState, Inventory, InventoryTrait, Recipe,
};
use rotate_enum::RotateEnum;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
us... | (&mut self, _item_type: &ItemType, _amount: isize) -> isize {
0
}
fn burner_energy(&self) -> Option<(f64, f64)> {
None
}
fn inventory(&self, _is_input: bool) -> Option<&Inventory> {
None
}
fn inventory_mut(&mut self, _is_input: bool) -> Option<&mut Inventory> {
No... | add_burner_inventory | identifier_name |
driver.rs | use eventsim::{Process, ProcessState, EventId};
use super::infrastructure::*;
use input::staticinfrastructure::*;
use smallvec::SmallVec;
use super::dynamics::*;
use output::history::TrainLogEvent;
use super::Sim;
enum ModelContainment {
Inside,
Outside,
}
enum Activation {
Wait(EventId),
Activate,
... | {
id :usize,
train: Train,
authority: f64,
step: (DriverAction, f64),
connected_signals: SmallVec<[(ObjectId, f64); 4]>,
logger: Box<Fn(TrainLogEvent)>,
activation: Activation,
timestep: Option<f64>,
}
impl Driver {
pub fn new(sim: &mut Sim,
id :usize,
... | Driver | identifier_name |
driver.rs | use eventsim::{Process, ProcessState, EventId};
use super::infrastructure::*;
use input::staticinfrastructure::*;
use smallvec::SmallVec;
use super::dynamics::*;
use output::history::TrainLogEvent;
use super::Sim;
enum ModelContainment {
Inside,
Outside,
}
enum Activation {
Wait(EventId),
Activate,
... |
}
}
_ => panic!("Not a signal"),
}
}
//println!("Updated authority {}", self.authority);
// Static maximum speed profile ahead from current position
// TODO: other speed limitations
let static_speed_profile = Stat... | {
//println!("Signal red in sight dist{} self.auth{}", dist,dist-20.0);
self.authority = dist - 20.0;
if self.authority < 0.0 { self.authority = 0.0; }
break;
} | conditional_block |
driver.rs | use eventsim::{Process, ProcessState, EventId};
use super::infrastructure::*;
use input::staticinfrastructure::*;
use smallvec::SmallVec;
use super::dynamics::*;
use output::history::TrainLogEvent;
use super::Sim;
enum ModelContainment {
Inside,
Outside,
}
enum Activation {
Wait(EventId),
Activate,
... | }
false
} else {
true
}
});
{
let log = &mut self.logger;
self.connected_signals.retain(|&mut (obj, ref mut dist)| {
*dist -= update.dx;
let lost = *dist < 10.0; // If closer than 10 m, sign... | sim.start_process(p);
} | random_line_split |
lib.rs | /// When sending data, split it into frames whose maximum size is this value
/// (max 1MByte, as per the Mplex spec).
split_send_size: usize,
}
impl MplexConfig {
/// Builds the default configuration.
#[inline]
pub fn new() -> MplexConfig {
Default::default()
}
/// Sets the max... | ,
}
}
}
fn write_substream(&self, substream: &mut Self::Substream, buf: &[u8]) -> Poll<usize, IoError> {
if!substream.local_open {
return Err(IoErrorKind::BrokenPipe.into());
}
let mut inner = self.inner.lock();
let to_write = cmp::min(buf.len()... | {
// There was no data packet in the buffer about this substream; maybe it's
// because it has been closed.
if inner.opened_substreams.contains(&(substream.num, substream.endpoint)) {
return Ok(Async::NotReady)
} els... | conditional_block |
lib.rs | /// When sending data, split it into frames whose maximum size is this value
/// (max 1MByte, as per the Mplex spec).
split_send_size: usize,
}
impl MplexConfig {
/// Builds the default configuration.
#[inline]
pub fn new() -> MplexConfig {
Default::default()
}
/// Sets the max... |
}
/// Behaviour when the maximum length of the buffer is reached.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum MaxBufferBehaviour {
/// Produce an error on all the substreams.
CloseAll,
/// No new message will be read from the underlying connection if the buffer is full.
///
/// This can ... | {
MplexConfig {
max_substreams: 128,
max_buffer_len: 4096,
max_buffer_behaviour: MaxBufferBehaviour::CloseAll,
split_send_size: 1024,
}
} | identifier_body |
lib.rs | /// When sending data, split it into frames whose maximum size is this value
/// (max 1MByte, as per the Mplex spec).
split_send_size: usize,
}
impl MplexConfig {
/// Builds the default configuration.
#[inline]
pub fn new() -> MplexConfig {
Default::default()
}
/// Sets the max... | (&mut self, size: usize) -> &mut Self {
let size = cmp::min(size, codec::MAX_FRAME_SIZE);
self.split_send_size = size;
self
}
#[inline]
fn upgrade<C>(self, i: C) -> Multiplex<C>
where
C: AsyncRead + AsyncWrite
{
let max_buffer_len = self.max_buffer_len;
... | split_send_size | identifier_name |
lib.rs |
/// When sending data, split it into frames whose maximum size is this value
/// (max 1MByte, as per the Mplex spec).
split_send_size: usize,
}
impl MplexConfig {
/// Builds the default configuration.
#[inline]
pub fn new() -> MplexConfig {
Default::default()
}
/// Sets the ma... | // Small convenience function that tries to write `elem` to the stream.
fn poll_send<C>(inner: &mut MultiplexInner<C>, elem: codec::Elem) -> Poll<(), IoError>
where C: AsyncRead + AsyncWrite
{
if inner.is_shutdown {
return Err(IoError::new(IoErrorKind::Other, "connection is shut down"))
}
match inne... | random_line_split | |
lib.rs | //! Data Encryption Standard Rust implementation.
//!
//! The only supported mode is Electronic Codebook (ECB).
//!
//! # Example
//!
//! ```
//! extern crate des_rs_krautcat;
//!
//! let key = [0x13, 0x34, 0x57, 0x79, 0x9B, 0xBC, 0xDF, 0xF1];
//! let message = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF];
//! let ... |
let mut blocks = vec![];
for msg in message {
let permuted = ip(msg, Ip::Direct);
let mut li: u32 = ((permuted & 0xFFFFFFFF00000000) >> 32) as u32;
let mut ri: u32 = ((permuted & 0x00000000FFFFFFFF)) as u32;
for subkey in &subkeys {
let last_li = li;
li... | let message_len = message.len();
let message = message_to_u64s(message); | random_line_split |
lib.rs | //! Data Encryption Standard Rust implementation.
//!
//! The only supported mode is Electronic Codebook (ECB).
//!
//! # Example
//!
//! ```
//! extern crate des_rs_krautcat;
//!
//! let key = [0x13, 0x34, 0x57, 0x79, 0x9B, 0xBC, 0xDF, 0xF1];
//! let message = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF];
//! let ... | 0) as u8,
((num & 0x000000FF00000000) >> 32) as u8,
((num & 0x00000000FF000000) >> 24) as u8,
((num & 0x0000000000FF0000) >> 16) as u8,
((num & 0x000000000000FF00) >> 8) as u8,
((num & 0x00000000000000FF) >> 0) as u8
]
}
/// Процедура создания 16 подключей
fn compute_subke... | 000) >> 4 | identifier_name |
lib.rs | //! Data Encryption Standard Rust implementation.
//!
//! The only supported mode is Electronic Codebook (ECB).
//!
//! # Example
//!
//! ```
//! extern crate des_rs_krautcat;
//!
//! let key = [0x13, 0x34, 0x57, 0x79, 0x9B, 0xBC, 0xDF, 0xF1];
//! let message = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF];
//! let ... | << 16, result);
}
#[test]
fn test_encrypt_decrypt() {
let key = [0x13, 0x34, 0x57, 0x79, 0x9B, 0xBC, 0xDF, 0xF1];
let message = [0x52, 0x75, 0x73, 0x74, 0x20, 0x44, 0x45, 0x53];
let expected_cipher = vec![0x27, 0xC1, 0x4F, 0xA6, 0x9A, 0x04, 0x4E, 0x28];
let cipher = encrypt... | result = pc1(0b00010011_00110100_01010111_01111001_10011011_10111100_11011111_11110001);
assert_eq!(0b1111000_0110011_0010101_0101111_0101010_1011001_1001111_0001111 << 8, result);
}
#[test]
fn test_pc2() {
let result = pc2(0b1110000_1100110_0101010_1011111_1010101_0110011_0011110_0011110 <... | identifier_body |
lib.rs | //! Data Encryption Standard Rust implementation.
//!
//! The only supported mode is Electronic Codebook (ECB).
//!
//! # Example
//!
//! ```
//! extern crate des_rs_krautcat;
//!
//! let key = [0x13, 0x34, 0x57, 0x79, 0x9B, 0xBC, 0xDF, 0xF1];
//! let message = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF];
//! let ... | 1)) & 0x8000000000000000) as u64;
let b2 = ((block_exp >> 1) & 0x7C00000000000000) as u64;;
let b3 = ((block_exp >> 3) & 0x03F0000000000000) as u64;;
let b4 = ((block_exp >> 5) & 0x000FC00000000000) as u64;;
let b5 = ((block_exp >> 7) ... | st RESULT_LEN: usize = 48;
let block_exp = (block as u64) << 32;
let b1 = ((block_exp << (BLOCK_LEN - | conditional_block |
proc_fork.rs | use super::*;
use crate::{
capture_snapshot,
os::task::OwnedTaskStatus,
runtime::task_manager::{TaskWasm, TaskWasmRunProperties},
syscalls::*,
WasiThreadHandle,
};
use serde::{Deserialize, Serialize};
use wasmer::Memory;
#[derive(Serialize, Deserialize)]
pub(crate) struct ForkResult {
pub pid: ... | <M: MemorySize>(
mut ctx: FunctionEnvMut<'_, WasiEnv>,
mut copy_memory: Bool,
pid_ptr: WasmPtr<Pid, M>,
) -> Result<Errno, WasiError> {
wasi_try_ok!(WasiEnv::process_signals_and_exit(&mut ctx)?);
// If we were just restored then we need to return the value instead
if let Some(result) = unsafe {... | proc_fork | identifier_name |
proc_fork.rs | use super::*;
use crate::{
capture_snapshot,
os::task::OwnedTaskStatus,
runtime::task_manager::{TaskWasm, TaskWasmRunProperties},
syscalls::*,
WasiThreadHandle,
};
use serde::{Deserialize, Serialize};
use wasmer::Memory;
#[derive(Serialize, Deserialize)]
pub(crate) struct ForkResult {
pub pid: ... |
}
}
trace!(%pid, %tid, "child exited (code = {})", ret);
// Clean up the environment and return the result
ctx.cleanup((&mut store), Some(ret));
// We drop the handle at the last moment which will close the thread
drop(child_handle);
ret
}
| {} | conditional_block |
proc_fork.rs | use super::*;
use crate::{
capture_snapshot,
os::task::OwnedTaskStatus,
runtime::task_manager::{TaskWasm, TaskWasmRunProperties},
syscalls::*,
WasiThreadHandle,
};
use serde::{Deserialize, Serialize};
use wasmer::Memory;
#[derive(Serialize, Deserialize)]
pub(crate) struct ForkResult {
pub pid: ... | let mut ret: ExitCode = Errno::Success.into();
let err = if ctx.data(&store).thread.is_main() {
trace!(%pid, %tid, "re-invoking main");
let start = unsafe { ctx.data(&store).inner() }.start.clone().unwrap();
start.call(&mut store)
} else {
trace!(%pid, %tid, "re-invoking thre... | {
let env = ctx.data(&store);
let tasks = env.tasks().clone();
let pid = env.pid();
let tid = env.tid();
// If we need to rewind then do so
if let Some((rewind_state, rewind_result)) = rewind_state {
let res = rewind_ext::<M>(
ctx.env.clone().into_mut(&mut store),
... | identifier_body |
proc_fork.rs | use super::*;
use crate::{
capture_snapshot,
os::task::OwnedTaskStatus,
runtime::task_manager::{TaskWasm, TaskWasmRunProperties},
syscalls::*,
WasiThreadHandle,
};
use serde::{Deserialize, Serialize};
use wasmer::Memory;
#[derive(Serialize, Deserialize)]
pub(crate) struct ForkResult {
pub pid: ... | let rewind_state = deep.rewind;
move |ctx, store, rewind_result| {
run::<M>(
ctx,
store,
child_handle,
Some((rewind_state, rewind_result)),
... | // Create the respawn function
let respawn = {
let tasks = tasks.clone(); | random_line_split |
main.rs | #[cfg(test)]
extern crate memsec;
use std::collections::BTreeMap;
use std::env;
use std::fmt::{self, Display, Formatter};
use std::fs;
use std::iter;
use std::process::{Command, Stdio};
use std::str::{self, FromStr};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
u... |
fn table(&self) -> String {
let col1_heading = "Process Name";
let col2_heading = "Max Locked Memory (kb)";
let col1_heading_len = col1_heading.chars().count();
let col2_heading_len = col2_heading.chars().count();
let min_col2_start = col1_heading_len + COLUMN_BUFFER;
... | {
if let Some(pinfo) = self.0.get_mut(&pid) {
if kbs_locked > pinfo.max_locked {
pinfo.max_locked = kbs_locked;
}
}
} | identifier_body |
main.rs | #[cfg(test)]
extern crate memsec;
use std::collections::BTreeMap;
use std::env;
use std::fmt::{self, Display, Formatter};
use std::fs;
use std::iter;
use std::process::{Command, Stdio};
use std::str::{self, FromStr};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
u... | {
soft: Limit,
hard: Limit,
}
fn run_prlimit() -> MlockLimit {
let output = Command::new("prlimit")
.args(&["--memlock", "--output=SOFT,HARD", "--noheadings"])
.output()
.map(|output| String::from_utf8(output.stdout).unwrap())
.unwrap_or_else(|e| panic!("Subprocess failed: `uli... | MlockLimit | identifier_name |
main.rs | #[cfg(test)]
extern crate memsec;
use std::collections::BTreeMap;
use std::env;
use std::fmt::{self, Display, Formatter};
use std::fs;
use std::iter;
use std::process::{Command, Stdio};
use std::str::{self, FromStr};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
u... | cargo_test_pid: Arc<Mutex<Option<Pid>>>,
child_pids: Arc<Mutex<Vec<Pid>>>,
db: Arc<Mutex<Database>>,
done: Arc<AtomicBool>,
) -> JoinHandle<()> {
thread::spawn(move || {
while cargo_test_pid.lock().unwrap().is_none() {
thread::sleep(Duration::from_millis(1));
}
wh... | random_line_split | |
dep_cache.rs |
(Rc<(HashSet<InternedString>, Rc<Vec<DepInfo>>)>, bool),
>,
/// all the cases we ended up using a supplied replacement
used_replacements: HashMap<PackageId, Summary>,
}
impl<'a> RegistryQueryer<'a> {
pub fn new(
registry: &'a mut dyn Registry,
replacements: &'a [(PackageIdSpec,... | impl Requirements<'_> {
fn new(summary: &Summary) -> Requirements<'_> {
Requirements {
summary,
deps: HashMap::new(),
features: HashSet::new(),
}
}
fn into_features(self) -> HashSet<InternedString> {
self.features
}
fn require_dep_feature... | random_line_split | |
dep_cache.rs | pub fn new(
registry: &'a mut dyn Registry,
replacements: &'a [(PackageIdSpec, Dependency)],
version_prefs: &'a VersionPreferences,
minimal_versions: bool,
max_rust_version: Option<PartialVersion>,
) -> Self {
RegistryQueryer {
registry,
repl... | {
match self {
RequirementError::MissingFeature(feat) => {
let deps: Vec<_> = summary
.dependencies()
.iter()
.filter(|dep| dep.name_in_toml() == feat)
.collect();
if deps.is_empty() {
... | identifier_body | |
dep_cache.rs | (Rc<(HashSet<InternedString>, Rc<Vec<DepInfo>>)>, bool),
>,
/// all the cases we ended up using a supplied replacement
used_replacements: HashMap<PackageId, Summary>,
}
impl<'a> RegistryQueryer<'a> {
pub fn new(
registry: &'a mut dyn Registry,
replacements: &'a [(PackageIdSpec, D... | (self) -> HashSet<InternedString> {
self.features
}
fn require_dep_feature(
&mut self,
package: InternedString,
feat: InternedString,
weak: bool,
) -> Result<(), RequirementError> {
// If `package` is indeed an optional dependency then we activate the
... | into_features | identifier_name |
benchmark.rs | #![feature(duration_as_u128)]
//! Executes all mjtests in the /exec/big folder.
use compiler_cli::optimization_arg;
use compiler_shared::timing::{AsciiDisp, CompilerMeasurements, SingleMeasurement};
use humantime::format_duration;
use optimization;
use regex::Regex;
use runner_integration_tests::{compiler_call, Backend... |
Err(msg) => {
log::debug!(
"could not open file for reference benchmark of {}: {:?}",
self.file.display(),
msg
);
}
}
}
fn load_reference_from_disk(&mut self) {
if let Ok(res) = s... | {
if let Err(msg) = serde_json::ser::to_writer(&outfile, &diskformat) {
log::debug!(
"could not write file for reference benchmark of {}: {:?}",
self.file.display(),
msg
);
}
... | conditional_block |
benchmark.rs | #![feature(duration_as_u128)]
//! Executes all mjtests in the /exec/big folder.
use compiler_cli::optimization_arg;
use compiler_shared::timing::{AsciiDisp, CompilerMeasurements, SingleMeasurement};
use humantime::format_duration;
use optimization;
use regex::Regex;
use runner_integration_tests::{compiler_call, Backend... |
}
fn main() {
env_logger::init();
let opts = Opts::from_args();
for big_test in &big_tests() {
if!opts.filter.is_match(&big_test.minijava.to_string_lossy()) {
log::info!("skipping {}", big_test.minijava.display());
continue;
}
let mut bench = Benchmark::ne... | {
Self {
measurements: HashMap::new(),
}
} | identifier_body |
benchmark.rs | #![feature(duration_as_u128)]
//! Executes all mjtests in the /exec/big folder.
use compiler_cli::optimization_arg;
use compiler_shared::timing::{AsciiDisp, CompilerMeasurements, SingleMeasurement};
use humantime::format_duration;
use optimization;
use regex::Regex;
use runner_integration_tests::{compiler_call, Backend... | (file: PathBuf) -> Self {
Self {
measurements: Vec::new(),
reference: None,
file,
}
}
pub fn add(&mut self, measurements: &[SingleMeasurement]) {
if self.measurements.is_empty() {
for measurement in measurements {
self.meas... | new | identifier_name |
benchmark.rs | #![feature(duration_as_u128)]
//! Executes all mjtests in the /exec/big folder.
use compiler_cli::optimization_arg;
use compiler_shared::timing::{AsciiDisp, CompilerMeasurements, SingleMeasurement};
use humantime::format_duration;
use optimization;
use regex::Regex;
use runner_integration_tests::{compiler_call, Backend... | fn main() {
env_logger::init();
let opts = Opts::from_args();
for big_test in &big_tests() {
if!opts.filter.is_match(&big_test.minijava.to_string_lossy()) {
log::info!("skipping {}", big_test.minijava.display());
continue;
}
let mut bench = Benchmark::new(bi... | }
}
}
| random_line_split |
lib.rs | //! Monie-in-the-middle http(s) proxy library
//!
//! Observe and manipulate requests by implementing `monie::Mitm`.
//!
//! Here is a skeleton to help get started:
//!
//! ```
//! use futures::future::Future;
//! use hyper::{Body, Chunk, Request, Response, Server};
//! use monie::{Mitm, MitmProxyService};
//!
//! stru... |
}
impl<T: Mitm + Sync + Send +'static> NewService for MitmProxyService<T> {
type ReqBody = Body;
type ResBody = Body;
type Error = std::io::Error;
type Service = MitmProxyService<T>;
type InitError = std::io::Error;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_servic... | {
MitmProxyService::<T> {
_phantom: std::marker::PhantomData,
}
} | identifier_body |
lib.rs | //! Monie-in-the-middle http(s) proxy library
//!
//! Observe and manipulate requests by implementing `monie::Mitm`.
//!
//! Here is a skeleton to help get started:
//!
//! ```
//! use futures::future::Future;
//! use hyper::{Body, Chunk, Request, Response, Server};
//! use monie::{Mitm, MitmProxyService};
//!
//! stru... | else {
error!("service_inner_requests() serve_connection: {}", e);
};
})
}
| {
info!(
"service_inner_requests() serve_connection: \
client closed connection"
);
} | conditional_block |
lib.rs | //! Monie-in-the-middle http(s) proxy library
//!
//! Observe and manipulate requests by implementing `monie::Mitm`.
//!
//! Here is a skeleton to help get started:
//!
//! ```
//! use futures::future::Future;
//! use hyper::{Body, Chunk, Request, Response, Server};
//! use monie::{Mitm, MitmProxyService};
//!
//! stru... | <T: Mitm + Sync + Send +'static>(
connect_req: Request<Body>,
) -> impl Future<Item = Response<Body>, Error = std::io::Error> {
info!("proxy_connect() impersonating {:?}", connect_req.uri());
let authority =
Authority::from_shared(Bytes::from(connect_req.uri().to_string()))
.unwrap();
... | proxy_connect | identifier_name |
lib.rs | //! Monie-in-the-middle http(s) proxy library
//!
//! Observe and manipulate requests by implementing `monie::Mitm`.
//!
//! Here is a skeleton to help get started:
//!
//! ```
//! use futures::future::Future;
//! use hyper::{Body, Chunk, Request, Response, Server};
//! use monie::{Mitm, MitmProxyService};
//!
//! stru... | /// received "inside" the fake, tapped `CONNECT` tunnel.
fn proxy_request<T: Mitm + Sync + Send +'static>(
req: Request<Body>,
) -> impl Future<Item = Response<Body>, Error = std::io::Error> {
obtain_connection(req.uri().to_owned())
.map(|mut connection| {
let mitm1 = Arc::new(T::new(req.uri(... | ///
/// This function is called for plain http requests, and for https requests | random_line_split |
block.rs | use crate::lookup_table::LookupTable;
use crate::properties::Block;
use Block::*;
impl From<char> for Block {
#[inline]
fn from(c: char) -> Self {
if c < ROW0_LIMIT {
return ROW0_TABLE.get_or(&(c as u8), No_Block);
}
if c < PLANE0_LIMIT {
return PLANE0_TABLE.get... |
const ROW0_TABLE: LookupTable<u8, Block> = lookup_table![
(0x00, 0x7F, Basic),
];
const ROW0_LIMIT: char = '\u{80}';
const PLANE0_TABLE: LookupTable<u16, Block> = lookup_table![
(0x0080, 0x024F, Latin),
(0x0250, 0x02AF, IPA),
(0x02B0, 0x02FF, Spacing),
(0x0300, 0x036F, Combining),
(0x0370, 0x0... | {
use std::convert::TryInto;
ROW0_TABLE.validate();
if let Ok(x) = (ROW0_LIMIT as u32).try_into() { assert!(!ROW0_TABLE.contains(&x)); }
PLANE0_TABLE.validate();
if let Ok(x) = (PLANE0_LIMIT as u32).try_into() { assert!(!PLANE0_TABLE.contains(&x)); }
SUPPLEMENTARY_TABLE.validate();
} | identifier_body |
block.rs | use crate::lookup_table::LookupTable;
use crate::properties::Block;
use Block::*;
impl From<char> for Block {
#[inline]
fn from(c: char) -> Self {
if c < ROW0_LIMIT {
return ROW0_TABLE.get_or(&(c as u8), No_Block);
}
if c < PLANE0_LIMIT {
return PLANE0_TABLE.get... | (0x1CC0, 0x1CCF, Sundanese),
(0x1CD0, 0x1CFF, Vedic),
(0x1D00, 0x1DBF, Phonetic),
(0x1DC0, 0x1DFF, Combining),
(0x1E00, 0x1EFF, Latin),
(0x1F00, 0x1FFF, Greek),
(0x2000, 0x206F, General),
(0x2070, 0x209F, Superscripts),
(0x20A0, 0x20CF, Currency),
(0x20D0, 0x20FF, Combining),
... | (0x1C80, 0x1C8F, Cyrillic),
(0x1C90, 0x1CBF, Georgian), | random_line_split |
block.rs | use crate::lookup_table::LookupTable;
use crate::properties::Block;
use Block::*;
impl From<char> for Block {
#[inline]
fn from(c: char) -> Self {
if c < ROW0_LIMIT {
return ROW0_TABLE.get_or(&(c as u8), No_Block);
}
if c < PLANE0_LIMIT {
return PLANE0_TABLE.get... |
SUPPLEMENTARY_TABLE.validate();
}
const ROW0_TABLE: LookupTable<u8, Block> = lookup_table![
(0x00, 0x7F, Basic),
];
const ROW0_LIMIT: char = '\u{80}';
const PLANE0_TABLE: LookupTable<u16, Block> = lookup_table![
(0x0080, 0x024F, Latin),
(0x0250, 0x02AF, IPA),
(0x02B0, 0x02FF, Spacing),
(0x0300... | { assert!(!PLANE0_TABLE.contains(&x)); } | conditional_block |
block.rs | use crate::lookup_table::LookupTable;
use crate::properties::Block;
use Block::*;
impl From<char> for Block {
#[inline]
fn from(c: char) -> Self {
if c < ROW0_LIMIT {
return ROW0_TABLE.get_or(&(c as u8), No_Block);
}
if c < PLANE0_LIMIT {
return PLANE0_TABLE.get... | () {
use std::convert::TryInto;
ROW0_TABLE.validate();
if let Ok(x) = (ROW0_LIMIT as u32).try_into() { assert!(!ROW0_TABLE.contains(&x)); }
PLANE0_TABLE.validate();
if let Ok(x) = (PLANE0_LIMIT as u32).try_into() { assert!(!PLANE0_TABLE.contains(&x)); }
SUPPLEMENTARY_TABLE.validate();
}
const R... | validate_tables | identifier_name |
mod.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.
use super::*;
mod notification_stream;
use crate::types::PeerError;
use notification_stream::NotificationStream;
/// Processes incoming commands from the... |
/// State observer task around a remote peer. Takes a change stream from the remote peer that wakes
/// the task whenever some state has changed on the peer. Swaps tasks such as making outgoing
/// connections, processing the incoming control messages, and registering for notifications on the
/// remote peer.
pub(supe... | )
.map(|_| ()),
);
handle
} | random_line_split |
mod.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.
use super::*;
mod notification_stream;
use crate::types::PeerError;
use notification_stream::NotificationStream;
/// Processes incoming commands from the... | NotificationEventId::EventTrackChanged => {
let response = TrackChangedNotificationResponse::decode(data)
.map_err(|e| Error::PacketError(e))?;
peer.write().handle_new_controller_notification_event(ControllerEvent::TrackIdChanged(
response.identifier(),
... | {
fx_vlog!(tag: "avrcp", 2, "received notification for {:?} {:?}", notif, data);
let preamble = VendorDependentPreamble::decode(data).map_err(|e| Error::PacketError(e))?;
let data = &data[preamble.encoded_len()..];
if data.len() < preamble.parameter_length as usize {
return Err(Error::Unexpec... | identifier_body |
mod.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.
use super::*;
mod notification_stream;
use crate::types::PeerError;
use notification_stream::NotificationStream;
/// Processes incoming commands from the... | (peer: Arc<RwLock<RemotePeer>>) {
fx_vlog!(tag: "avrcp", 2, "state_watcher starting");
let mut change_stream = peer.read().state_change_listener.take_change_stream();
let peer_weak = Arc::downgrade(&peer);
drop(peer);
let mut channel_processor_abort_handle: Option<AbortHandle> = None;
let mut n... | state_watcher | identifier_name |
global.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... |
/// Set the global NRD feature flag using override.
pub fn set_global_nrd_enabled(enabled: bool) {
GLOBAL_NRD_FEATURE_ENABLED.set(enabled, true)
}
/// Explicitly enable the local NRD feature flag.
pub fn set_local_nrd_enabled(enabled: bool) {
NRD_FEATURE_ENABLED.with(|flag| flag.set(Some(enabled)))
}
/// Is the N... | {
GLOBAL_NRD_FEATURE_ENABLED.init(enabled)
} | identifier_body |
global.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | () -> ChainTypes {
CHAIN_TYPE.with(|chain_type| match chain_type.get() {
None => {
if!GLOBAL_CHAIN_TYPE.is_init() {
panic!("GLOBAL_CHAIN_TYPE and CHAIN_TYPE unset. Consider set_local_chain_type() in tests.");
}
let chain_type = GLOBAL_CHAIN_TYPE.borrow();
set_local_chain_type(chain_type);
chain_ty... | get_chain_type | identifier_name |
global.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | size + proof_size
}
#[cfg(test)]
mod test {
use super::*;
use crate::core::Block;
use crate::genesis::*;
use crate::pow::mine_genesis_block;
use crate::ser::{BinWriter, Writeable};
fn test_header_len(genesis: Block) {
let mut raw = Vec::<u8>::with_capacity(1_024);
let mut writer = BinWriter::new(&mut raw, ... | /// Calculates the size of a header (in bytes) given a number of edge bits in the PoW
#[inline]
pub fn header_size_bytes(edge_bits: u8) -> usize {
let size = 2 + 2 * 8 + 5 * 32 + 32 + 2 * 8;
let proof_size = 8 + 4 + 8 + 1 + Proof::pack_len(edge_bits); | random_line_split |
lib.rs | use http::{
Method,
StatusCode,
Uri,
Version,
};
use http::header::{
HeaderMap,
HeaderName,
HeaderValue,
InvalidHeaderName,
InvalidHeaderValue,
};
use http::method::InvalidMethod;
use http::uri::InvalidUriBytes;
use lazy_static::lazy_static;
use regex::bytes::Regex;
use std::io;
use ... | pub struct RequestHeader {
pub method: Method,
pub uri: Uri,
pub version: Version,
pub fields: HeaderMap,
}
#[derive(Debug)]
pub struct ResponseHeader {
pub status_code: StatusCode,
pub fields: HeaderMap,
}
#[derive(Debug)]
pub enum InvalidRequestHeader {
Format,
RequestLine(InvalidReq... | random_line_split | |
lib.rs | use http::{
Method,
StatusCode,
Uri,
Version,
};
use http::header::{
HeaderMap,
HeaderName,
HeaderValue,
InvalidHeaderName,
InvalidHeaderValue,
};
use http::method::InvalidMethod;
use http::uri::InvalidUriBytes;
use lazy_static::lazy_static;
use regex::bytes::Regex;
use std::io;
use ... |
#[test]
fn test_parse_header_field() {
let s = b"Content-Type: application/json; charset=\"\xAA\xBB\xCC\"";
let (h, v) = parse_header_field(s).unwrap();
assert_eq!(
h,
http::header::CONTENT_TYPE,
);
assert_eq!(
v,
HeaderVa... | {
let s = b"OPTIONS * HTTP/1.1";
let (m, u, v) = parse_request_line(s).unwrap();
assert_eq!(m, Method::OPTIONS);
assert_eq!(u.path(), "*");
assert_eq!(v, Version::HTTP_11);
let s = b"POST http://foo.example.com/bar?qux=19&qux=xyz HTTP/1.0";
let (m, u, v) = parse_... | identifier_body |
lib.rs | use http::{
Method,
StatusCode,
Uri,
Version,
};
use http::header::{
HeaderMap,
HeaderName,
HeaderValue,
InvalidHeaderName,
InvalidHeaderValue,
};
use http::method::InvalidMethod;
use http::uri::InvalidUriBytes;
use lazy_static::lazy_static;
use regex::bytes::Regex;
use std::io;
use ... | (e: InvalidHeaderField) -> Self {
InvalidRequestHeader::HeaderField(e)
}
}
impl From<io::Error> for InvalidRequestHeader {
fn from(e: io::Error) -> Self {
InvalidRequestHeader::Io(e)
}
}
const LINE_CAP: usize = 16384;
pub fn parse_request_header<B: BufRead>(mut stream: B)
-> Result<Re... | from | identifier_name |
custom_widget.rs | that in this case, we use `piston_window` to draw our widget, however in practise you may
//! use any backend you wish.
//!
//! For more information, please see the `Widget` trait documentation.
//!
#[macro_use] extern crate conrod;
extern crate find_folder;
extern crate piston_window;
extern crate vecmath;
/// Th... | //
// Defaults can come from several places. Here, we define how certain defaults take
// precedence over others.
//
// Most commonly, defaults are to be retrieved from the `Theme`, however in some cases
// some other logic may need to be considere... | /// The default implementation is the same as below, but unwraps to an absolute scalar of
/// `0.0` instead of `64.0`.
fn default_x_dimension<C: CharacterCache>(&self, ui: &Ui<C>) -> Dimension {
// If no width was given via the `Sizeable` (a trait implemented for all widgets)
... | random_line_split |
custom_widget.rs | in this case, we use `piston_window` to draw our widget, however in practise you may
//! use any backend you wish.
//!
//! For more information, please see the `Widget` trait documentation.
//!
#[macro_use] extern crate conrod;
extern crate find_folder;
extern crate piston_window;
extern crate vecmath;
/// The mod... |
}
// Here we check to see whether or not our button should capture the mouse.
//
// Widgets can "capture" user input. If the button captures the mouse, then mouse
// events will only be seen by the button. Other widgets will not see mouse events
... | {
react();
} | conditional_block |
custom_widget.rs | in this case, we use `piston_window` to draw our widget, however in practise you may
//! use any backend you wish.
//!
//! For more information, please see the `Widget` trait documentation.
//!
#[macro_use] extern crate conrod;
extern crate find_folder;
extern crate piston_window;
extern crate vecmath;
/// The mod... | (&self) -> &CommonBuilder {
&self.common
}
fn common_mut(&mut self) -> &mut CommonBuilder {
&mut self.common
}
fn unique_kind(&self) -> &'static str {
KIND
}
fn init_state(&self) -> State {
State {
interac... | common | identifier_name |
wire.rs | //! Creating and consuming data in wire format.
use super::name::ToDname;
use super::net::{Ipv4Addr, Ipv6Addr};
use core::fmt;
use octseq::builder::{OctetsBuilder, Truncate};
use octseq::parse::{Parser, ShortInput};
//------------ Composer ------------------------------------------------------
pub trait Composer:
... | pl<'a, Octs: AsRef<[u8]> +?Sized> Parse<'a, Octs> for i32 {
fn parse(parser: &mut Parser<'a, Octs>) -> Result<Self, ParseError> {
parser.parse_i32_be().map_err(Into::into)
}
}
impl<'a, Octs: AsRef<[u8]> +?Sized> Parse<'a, Octs> for u32 {
fn parse(parser: &mut Parser<'a, Octs>) -> Result<Self, Parse... | parser.parse_u16_be().map_err(Into::into)
}
}
im | identifier_body |
wire.rs | //! Creating and consuming data in wire format.
use super::name::ToDname;
use super::net::{Ipv4Addr, Ipv6Addr};
use core::fmt;
use octseq::builder::{OctetsBuilder, Truncate};
use octseq::parse::{Parser, ShortInput};
//------------ Composer ------------------------------------------------------
pub trait Composer:
... | }
}
//--- Display and Error
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParseError::ShortInput => f.write_str("unexpected end of input"),
ParseError::Form(ref err) => err.fmt(f),
}
}
}
#[cfg(feature = "std... | impl From<FormError> for ParseError {
fn from(err: FormError) -> Self {
ParseError::Form(err) | random_line_split |
wire.rs | //! Creating and consuming data in wire format.
use super::name::ToDname;
use super::net::{Ipv4Addr, Ipv6Addr};
use core::fmt;
use octseq::builder::{OctetsBuilder, Truncate};
use octseq::parse::{Parser, ShortInput};
//------------ Composer ------------------------------------------------------
pub trait Composer:
... | self) -> bool {
false
}
}
#[cfg(feature = "std")]
impl Composer for std::vec::Vec<u8> {}
impl<const N: usize> Composer for octseq::array::Array<N> {}
#[cfg(feature = "bytes")]
impl Composer for bytes::BytesMut {}
#[cfg(feature = "smallvec")]
impl<A: smallvec::Array<Item = u8>> Composer for smallvec::Sma... | n_compress(& | identifier_name |
request.rs | extern crate base64;
extern crate md5;
use std::collections::HashMap;
use std::io::{Read, Write};
use bucket::Bucket;
use chrono::{DateTime, Utc};
use command::Command;
use hmac::Mac;
use reqwest::async;
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
use sha2::{Digest, Sha256};
use url::Url;
use fu... | }
fn string_to_sign(&self, request: &str) -> String {
signing::string_to_sign(&self.datetime, &self.bucket.region(), request)
}
fn signing_key(&self) -> S3Result<Vec<u8>> {
Ok(signing::signing_key(
&self.datetime,
&self.bucket.secret_key(),
&self.buc... | self.command.http_verb().as_str(),
&self.url(),
headers,
&self.sha256(),
) | random_line_split |
request.rs | extern crate base64;
extern crate md5;
use std::collections::HashMap;
use std::io::{Read, Write};
use bucket::Bucket;
use chrono::{DateTime, Utc};
use command::Command;
use hmac::Mac;
use reqwest::async;
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
use sha2::{Digest, Sha256};
use url::Url;
use fu... | (&self) -> S3Result<(Vec<u8>, u16)> {
let response_data = self.response_data_future().then(|result| match result {
Ok((response_data, status_code)) => Ok((response_data, status_code)),
Err(e) => Err(e),
});
let mut runtime = Runtime::new().unwrap();
runtime.block_... | response_data | identifier_name |
request.rs | extern crate base64;
extern crate md5;
use std::collections::HashMap;
use std::io::{Read, Write};
use bucket::Bucket;
use chrono::{DateTime, Utc};
use command::Command;
use hmac::Mac;
use reqwest::async;
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
use sha2::{Digest, Sha256};
use url::Url;
use fu... |
fn authorization(&self, headers: &HeaderMap) -> S3Result<String> {
let canonical_request = self.canonical_request(headers);
let string_to_sign = self.string_to_sign(&canonical_request);
let mut hmac = signing::HmacSha256::new_varkey(&self.signing_key()?)?;
hmac.input(string_to_sign... | {
Ok(signing::signing_key(
&self.datetime,
&self.bucket.secret_key(),
&self.bucket.region(),
"s3",
)?)
} | identifier_body |
qutex.rs | //! A queue-backed exclusive data lock.
//!
//
// * It is unclear how many of the unsafe methods within need actually remain
// unsafe.
use crossbeam::queue::SegQueue;
use futures::sync::oneshot::{self, Canceled, Receiver, Sender};
use futures::{Future, Poll};
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMu... | (&self) {
// TODO: Consider using `Ordering::Release`.
self.inner.state.store(0, SeqCst);
self.process_queue()
}
}
impl<T> From<T> for Qutex<T> {
#[inline]
fn from(val: T) -> Qutex<T> {
Qutex::new(val)
}
}
// Avoids needing `T: Clone`.
impl<T> Clone for Qutex<T> {
#... | direct_unlock | identifier_name |
qutex.rs | //! A queue-backed exclusive data lock.
//!
//
// * It is unclear how many of the unsafe methods within need actually remain
// unsafe.
use crossbeam::queue::SegQueue;
use futures::sync::oneshot::{self, Canceled, Receiver, Sender};
use futures::{Future, Poll};
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMu... | else {
panic!("FutureGuard::poll: Task already completed.");
}
}
}
impl<T> Drop for FutureGuard<T> {
/// Gracefully unlock if this guard has a lock acquired but has not yet
/// been polled to completion.
fn drop(&mut self) {
if let Some(qutex) = self.qutex.take() {
... | {
unsafe { self.qutex.as_ref().unwrap().process_queue() }
match self.rx.poll() {
Ok(status) => Ok(status.map(|_| Guard {
qutex: self.qutex.take().unwrap(),
})),
Err(e) => Err(e.into()),
}
} | conditional_block |
qutex.rs | //! A queue-backed exclusive data lock.
//!
//
// * It is unclear how many of the unsafe methods within need actually remain
// unsafe.
use crossbeam::queue::SegQueue;
use futures::sync::oneshot::{self, Canceled, Receiver, Sender};
use futures::{Future, Poll};
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMu... | let (tx, rx) = oneshot::channel();
unsafe {
self.push_request(Request::new(tx));
}
FutureGuard::new(self, rx)
}
/// Pushes a lock request onto the queue.
///
//
// TODO: Evaluate unsafe-ness.
//
#[inline]
pub unsafe fn push_request(&self, req:... |
/// Returns a new `FutureGuard` which can be used as a future and will
/// resolve into a `Guard`.
pub fn lock(self) -> FutureGuard<T> { | random_line_split |
qutex.rs | //! A queue-backed exclusive data lock.
//!
//
// * It is unclear how many of the unsafe methods within need actually remain
// unsafe.
use crossbeam::queue::SegQueue;
use futures::sync::oneshot::{self, Canceled, Receiver, Sender};
use futures::{Future, Poll};
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMu... |
}
#[cfg(test)]
// Woefully incomplete:
mod tests {
use super::*;
use futures::Future;
#[test]
fn simple() {
let val = Qutex::from(999i32);
println!("Reading val...");
{
let future_guard = val.clone().lock();
let guard = future_guard.wait().unwrap();
... | {
Qutex {
inner: self.inner.clone(),
}
} | identifier_body |
entity.rs | use anyhow::{anyhow, Context, Error, Result};
use log::{debug, trace};
use serde::Deserialize;
use shellexpand;
use std::{collections::HashMap, convert::TryFrom, env, fs, path::PathBuf, thread};
use toml;
use crate::output::utils::run_cmd;
const DEFAULT_PAGE_SIZE: usize = 10;
#[derive(Debug, Default, Clone, PartialE... |
pub fn run_notify_cmd<S: AsRef<str>>(&self, subject: S, sender: S) -> Result<()> {
let subject = subject.as_ref();
let sender = sender.as_ref();
let default_cmd = format!(r#"notify-send "📫 {}" "{}""#, sender, subject);
let cmd = self
.notify_cmd
.as_ref()
... | {
let name = account.name.as_ref().unwrap_or(&self.name);
let has_special_chars = "()<>[]:;@.,".contains(|special_char| name.contains(special_char));
if name.is_empty() {
format!("{}", account.email)
} else if has_special_chars {
// so the name has special charac... | identifier_body |
entity.rs | use anyhow::{anyhow, Context, Error, Result};
use log::{debug, trace};
use serde::Deserialize;
use shellexpand;
use std::{collections::HashMap, convert::TryFrom, env, fs, path::PathBuf, thread};
use toml;
use crate::output::utils::run_cmd;
const DEFAULT_PAGE_SIZE: usize = 10;
#[derive(Debug, Default, Clone, PartialE... | // #[cfg(test)]
// mod tests {
// use crate::domain::{account::entity::Account, config::entity::Config};
// // a quick way to get a config instance for testing
// fn get_config() -> Config {
// Config {
// name: String::from("Config Name"),
// ..Config::default()
// }... | }
// FIXME: tests | random_line_split |
entity.rs | use anyhow::{anyhow, Context, Error, Result};
use log::{debug, trace};
use serde::Deserialize;
use shellexpand;
use std::{collections::HashMap, convert::TryFrom, env, fs, path::PathBuf, thread};
use toml;
use crate::output::utils::run_cmd;
const DEFAULT_PAGE_SIZE: usize = 10;
#[derive(Debug, Default, Clone, PartialE... | () -> Result<PathBuf> {
let home_var = if cfg!(target_family = "windows") {
"USERPROFILE"
} else {
"HOME"
};
let mut path: PathBuf = env::var(home_var)
.context(format!("cannot find `{}` env var", home_var))?
.into();
path.push(".hima... | path_from_home | identifier_name |
lib.rs | #![forbid(unsafe_code)]
#![warn(rust_2018_idioms)]
use anyhow::{anyhow, Context as _};
use cargo_metadata as cm;
use duct::cmd;
use indoc::indoc;
use itertools::Itertools as _;
use quote::quote;
use std::{
collections::{BTreeMap, HashMap, HashSet},
env, fs,
ops::Range,
path::{Path, PathBuf},
};
pub fn... | (
&mut self,
path: &[&'cm str],
package: &'cm cm::Package,
target: &'cm cm::Target,
) {
match (self, path) {
(Self::Joint(joint), []) => {
joint.insert(&target.name, Self::Leaf(&package.id, target));
... | insert | identifier_name |
lib.rs | #![forbid(unsafe_code)]
#![warn(rust_2018_idioms)]
use anyhow::{anyhow, Context as _};
use cargo_metadata as cm;
use duct::cmd;
use indoc::indoc;
use itertools::Itertools as _;
use quote::quote;
use std::{
collections::{BTreeMap, HashMap, HashSet},
env, fs,
ops::Range,
path::{Path, PathBuf},
};
pub fn... | env::var_os("CARGO").with_context(|| "missing `$CARGO` environment variable")?,
)
.with_file_name("rustfmt")
.with_extension(env::consts::EXE_EXTENSION);
let tempdir = tempfile::Builder::new()
.prefix("qryxip-competitive-programming-library-xtask-")
.temp... |
fn apply_rustfmt(code: &str) -> anyhow::Result<String> {
let rustfmt_exe = PathBuf::from( | random_line_split |
lib.rs | #![forbid(unsafe_code)]
#![warn(rust_2018_idioms)]
use anyhow::{anyhow, Context as _};
use cargo_metadata as cm;
use duct::cmd;
use indoc::indoc;
use itertools::Itertools as _;
use quote::quote;
use std::{
collections::{BTreeMap, HashMap, HashSet},
env, fs,
ops::Range,
path::{Path, PathBuf},
};
pub fn... |
(Self::Joint(joint), [segment, path @..]) => {
joint
.entry(segment)
.or_default()
.insert(path, package, target);
}
_ => panic!(),
}
}
fn expand(
... | {
joint.insert(&target.name, Self::Leaf(&package.id, target));
} | conditional_block |
lib.rs | #![forbid(unsafe_code)]
#![warn(rust_2018_idioms)]
use anyhow::{anyhow, Context as _};
use cargo_metadata as cm;
use duct::cmd;
use indoc::indoc;
use itertools::Itertools as _;
use quote::quote;
use std::{
collections::{BTreeMap, HashMap, HashSet},
env, fs,
ops::Range,
path::{Path, PathBuf},
};
pub fn... | for (package, target) in library_crates {
let markdown = format!(
"---\n\
title: \"{} (<code>{}</code>)\"\n\
documentation_of: //{}\n\
---\n\
{}",
package.name,
target.name,
target
.src_path
... | {
let metadata = &cargo_metadata(manifest_path)?;
let library_crates = metadata
.workspace_members
.iter()
.flat_map(|ws_member| {
let ws_member = &metadata[ws_member];
let target = ws_member.lib_or_proc_macro()?;
Some((ws_member, target))
})
... | identifier_body |
lib.rs | // use std::borrow::Cow;
use std::cmp::Ordering;
use std::rc::Rc;
use std::result::Result;
use std::vec::Vec;
#[derive(Debug)]
enum MastError {
InvalidNode,
StoreError(std::io::Error),
}
#[derive(Debug,Clone)]
struct Node {
key: Vec<i32>,
value: Vec<i32>,
link: Vec<Option<Link>>,
dirty: bool,
... | else {
while v!= 0 && v % branch_factor as i32 == 0 {
v /= branch_factor as i32;
layer += 1;
}
}
return layer;
}
impl<'a> Mast<'a> {
pub fn newInMemory() -> Mast<'a> {
return Mast {
size: 0,
height: 0,
root_link: Link::Mut... | {
while v != 0 && v & 0xf == 0 {
v >>= 4;
layer += 1
}
} | conditional_block |
lib.rs | // use std::borrow::Cow;
use std::cmp::Ordering;
use std::rc::Rc;
use std::result::Result;
use std::vec::Vec;
#[derive(Debug)]
enum MastError {
InvalidNode,
StoreError(std::io::Error),
}
#[derive(Debug,Clone)]
struct Node {
key: Vec<i32>,
value: Vec<i32>,
link: Vec<Option<Link>>,
dirty: bool,
... | };
return Ok(res);
}
if equal {
if value == self.value[i] {
return Ok(InsertResult::NoChange);
}
self.value[i] = value;
self.dirty = true;
return Ok(InsertResult::Updated);
}
let (left_l... | };
let res = child.insert(key, value, distance - 1, key_order)?;
match res {
InsertResult::NoChange => (),
_ => self.dirty = true, | random_line_split |
lib.rs | // use std::borrow::Cow;
use std::cmp::Ordering;
use std::rc::Rc;
use std::result::Result;
use std::vec::Vec;
#[derive(Debug)]
enum MastError {
InvalidNode,
StoreError(std::io::Error),
}
#[derive(Debug,Clone)]
struct Node {
key: Vec<i32>,
value: Vec<i32>,
link: Vec<Option<Link>>,
dirty: bool,
... | (v: &i32, branch_factor: u16) -> u8 {
let mut layer = 0;
let mut v = *v;
if branch_factor == 16 {
while v!= 0 && v & 0xf == 0 {
v >>= 4;
layer += 1
}
} else {
while v!= 0 && v % branch_factor as i32 == 0 {
v /= branch_factor as i32;
... | default_layer | identifier_name |
lib.rs | // use std::borrow::Cow;
use std::cmp::Ordering;
use std::rc::Rc;
use std::result::Result;
use std::vec::Vec;
#[derive(Debug)]
enum MastError {
InvalidNode,
StoreError(std::io::Error),
}
#[derive(Debug,Clone)]
struct Node {
key: Vec<i32>,
value: Vec<i32>,
link: Vec<Option<Link>>,
dirty: bool,
... |
fn default_layer(v: &i32, branch_factor: u16) -> u8 {
let mut layer = 0;
let mut v = *v;
if branch_factor == 16 {
while v!= 0 && v & 0xf == 0 {
v >>= 4;
layer += 1
}
} else {
while v!= 0 && v % branch_factor as i32 == 0 {
v /= branch_factor a... | {
if *a < *b {
return -1;
} else if *a > *b {
return 1;
} else {
return 0;
}
} | identifier_body |
offset.rs | use std::alloc::{GlobalAlloc, System, Layout};
use std::borrow::Borrow;
use std::cmp;
use std::convert::TryInto;
use std::fmt;
use std::marker::PhantomData;
use std::mem::{self, ManuallyDrop};
use std::num::NonZeroU64;
use std::ptr::NonNull;
use std::hint::unreachable_unchecked;
use thiserror::Error;
use leint::Le;
u... | <T:?Sized>(mut self, value: &T) -> (Vec<u8>, Offset<'p, 'v>)
where T: SavePtr<OffsetMut<'p, 'v>, Offset<'p, 'v>>
{
let mut encoder = value.init_save_ptr();
encoder.save_poll(&mut self).into_ok();
let offset = self.finish_save(&encoder).into_ok();
(self.written, offset)
}
... | save | identifier_name |
offset.rs | use std::alloc::{GlobalAlloc, System, Layout};
use std::borrow::Borrow;
use std::cmp;
use std::convert::TryInto;
use std::fmt;
use std::marker::PhantomData;
use std::mem::{self, ManuallyDrop};
use std::num::NonZeroU64;
use std::ptr::NonNull;
use std::hint::unreachable_unchecked;
use thiserror::Error;
use leint::Le;
u... |
}
/// Gets the `Offset` from a clean `OffsetMut`.
#[inline(always)]
pub fn get_offset(&self) -> Option<Offset<'p, 'v>> {
match self.kind() {
Kind::Offset(offset) => Some(offset),
Kind::Ptr(_) => None,
}
}
/// Gets the pointer from a dirty `OffsetMut`.
... | {
Kind::Ptr(unsafe { mem::transmute(self.inner) })
} | conditional_block |
offset.rs | use std::alloc::{GlobalAlloc, System, Layout};
use std::borrow::Borrow;
use std::cmp;
use std::convert::TryInto;
use std::fmt;
use std::marker::PhantomData;
use std::mem::{self, ManuallyDrop};
use std::num::NonZeroU64;
use std::ptr::NonNull;
use std::hint::unreachable_unchecked;
use thiserror::Error;
use leint::Le;
u... | // SAFETY: #[repr(transparent)]
unsafe { &*(self as *const Self as *const _) }
}
}
*/
impl<'p, 'v> From<Offset<'p, 'v>> for usize {
fn from(offset: Offset<'p, 'v>) -> usize {
offset.get()
}
}
impl<'p, 'v> From<Offset<'p, 'v>> for OffsetMut<'p, 'v> {
fn from(inner: Offset<'p, 'v... | fn as_ref(&self) -> &OffsetMut<'p, 'v, A> { | random_line_split |
offset.rs | use std::alloc::{GlobalAlloc, System, Layout};
use std::borrow::Borrow;
use std::cmp;
use std::convert::TryInto;
use std::fmt;
use std::marker::PhantomData;
use std::mem::{self, ManuallyDrop};
use std::num::NonZeroU64;
use std::ptr::NonNull;
use std::hint::unreachable_unchecked;
use thiserror::Error;
use leint::Le;
u... |
fn decode_blob<'a>(blob: ValidBlob<'a, Self>) -> Self {
blob.as_value().clone()
}
fn try_deref_blob<'a>(blob: ValidBlob<'a, Self>) -> Result<&'a Self, ValidBlob<'a, Self>> {
Ok(blob.as_value())
}
fn encode_blob<W: WriteBlob>(&self, dst: W) -> Result<W::Ok, W::Error> {
tod... | {
let raw = u64::from_le_bytes(blob.as_bytes().try_into().unwrap());
if raw & 0b1 == 0b1 && (raw >> 1) < Offset::MAX as u64 {
unsafe { Ok(blob.assume_valid()) }
} else {
Err(ValidateOffsetBlobError)
}
} | identifier_body |
glyph.rs | use super::math::*;
use crate::config::font::{Font, FontDescription};
use crate::config::ui_config::Delta;
use crate::config::Config;
use crate::cursor;
use alacritty_terminal::ansi::CursorStyle;
use alacritty_terminal::term::CursorKey;
use crossfont::{FontDesc, FontKey, Rasterize, Rasterizer, Size, Slant, Style, Weigh... | else {
rasterizer.load_font(&desc, size).unwrap_or_else(|_| regular)
}
};
// Load bold font.
let bold_desc = Self::make_desc(&font.bold(), Slant::Normal, Weight::Bold);
let bold = load_or_regular(bold_desc);
// Load italic font.
let italic_d... |
regular
} | conditional_block |
glyph.rs | use super::math::*;
use crate::config::font::{Font, FontDescription};
use crate::config::ui_config::Delta;
use crate::config::Config;
use crate::cursor;
use alacritty_terminal::ansi::CursorStyle;
use alacritty_terminal::term::CursorKey;
use crossfont::{FontDesc, FontKey, Rasterize, Rasterizer, Size, Slant, Style, Weigh... | {
pub rasterized: crossfont::RasterizedGlyph,
pub wide: bool,
pub zero_width: bool,
}
/// `LoadGlyph` allows for copying a rasterized glyph into graphics memory.
pub trait LoadGlyph {
/// Load the rasterized glyph into GPU memory.
fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> AtlasGlyp... | RasterizedGlyph | identifier_name |
glyph.rs | use super::math::*;
use crate::config::font::{Font, FontDescription};
use crate::config::ui_config::Delta;
use crate::config::Config;
use crate::cursor;
use alacritty_terminal::ansi::CursorStyle;
use alacritty_terminal::term::CursorKey;
use crossfont::{FontDesc, FontKey, Rasterize, Rasterizer, Size, Slant, Style, Weigh... | size: font_size,
},
};
let glyph =
Self::rasterize_glyph(glyph_key, rasterizer, glyph_offset, metrics);
atlas_cell_size.x = std::cmp::max(
... | key: crossfont::GlyphKey {
font_key: *font,
c: c as char, | random_line_split |
sourcemap.rs | sourcemap::SourceMap;
use swc_common::{comments::SingleThreadedComments, source_map::SourceMapGenConfig};
use swc_ecma_ast::EsVersion;
use swc_ecma_codegen::{self, text_writer::WriteJs, Emitter};
use swc_ecma_parser::{lexer::Lexer, Parser, Syntax};
use swc_ecma_testing::{exec_node_js, JsExecOptions};
static IGNORED_P... | {
true
} | identifier_body | |
sourcemap.rs | string, path::PathBuf};
use rustc_hash::FxHashSet;
use sourcemap::SourceMap;
use swc_common::{comments::SingleThreadedComments, source_map::SourceMapGenConfig};
use swc_ecma_ast::EsVersion;
use swc_ecma_codegen::{self, text_writer::WriteJs, Emitter};
use swc_ecma_parser::{lexer::Lexer, Parser, Syntax};
use swc_ecma_te... | ;
impl SourceMapGenConfig for SourceMapConfigImpl {
fn file_name_to_source(&self, f: &swc_common::FileName) -> String {
f.to_string()
}
fn inline_sources_content(&self, _: &swc_common::FileName | SourceMapConfigImpl | identifier_name |
sourcemap.rs | to_string, path::PathBuf};
use rustc_hash::FxHashSet;
use sourcemap::SourceMap;
use swc_common::{comments::SingleThreadedComments, source_map::SourceMapGenConfig};
use swc_ecma_ast::EsVersion;
use swc_ecma_codegen::{self, text_writer::WriteJs, Emitter};
use swc_ecma_parser::{lexer::Lexer, Parser, Syntax};
use swc_ecma... | "38284ea2d9914d86.js",
"3b57183c81070eec.js",
"3bbd75d597d54fe6.js",
"3c1e2ada0ac2b8e3.js",
"3e1a6f702041b599.js",
"3e3a99768a4a1502.js",
"3e69c5cc1a7ac103.js",
"3eac36e29398cdc5.js",
"3ff52d86c77678bd.js",
"43023cd549deee77.js",
"44af28febe2288cc.js",
"478ede4cfe7906d5.j... | "32b635a9667a9fb1.js",
"36224cf8215ad8e4.js",
"37e4a6eca1ece7e5.js", | random_line_split |
audio.rs | use crate::config::Config;
use crate::test::InputSampleStream;
use failure::Error;
use num::{Complex, Zero};
use portaudio as pa;
use std::sync::mpsc::{Receiver, Sender};
const CHANNELS: i32 = 1;
const FRAMES: u32 = 256;
const INTERLEAVED: bool = true;
fn run<'c, T>(
mut modulator: Modulate<'c, T>,
rx_sender... | /// Stream of samples from an audio device
pub struct AudioSampleStream<'c> {
channel: Receiver<f32>,
demod: Demodulate<'c>,
}
impl<'c> AudioSampleStream<'c> {
fn new(channel: Receiver<f32>, sample_rate: f32, config: &'c Config) -> Self {
Self {
channel,
demod: Demodulate::n... | random_line_split | |
audio.rs | use crate::config::Config;
use crate::test::InputSampleStream;
use failure::Error;
use num::{Complex, Zero};
use portaudio as pa;
use std::sync::mpsc::{Receiver, Sender};
const CHANNELS: i32 = 1;
const FRAMES: u32 = 256;
const INTERLEAVED: bool = true;
fn run<'c, T>(
mut modulator: Modulate<'c, T>,
rx_sender... |
}
}
Ok(())
}
pub fn start_audio<'c>(
tx_receiver: Receiver<Complex<f32>>,
config: &'c Config,
) -> Result<(std::thread::JoinHandle<()>, AudioSampleStream<'c>), Error> {
// For the microphone
let (rx_sender, rx_receiver) = std::sync::mpsc::channel::<f32>();
let sample_rate = config.... | {
break;
} | conditional_block |
audio.rs | use crate::config::Config;
use crate::test::InputSampleStream;
use failure::Error;
use num::{Complex, Zero};
use portaudio as pa;
use std::sync::mpsc::{Receiver, Sender};
const CHANNELS: i32 = 1;
const FRAMES: u32 = 256;
const INTERLEAVED: bool = true;
fn run<'c, T>(
mut modulator: Modulate<'c, T>,
rx_sender... | <'c> {
config: &'c Config,
/// Number of carrier samples to skip per baseband sample
to_skip: usize,
/// Sample rate of the audio signal
sample_rate: f32,
/// Total number of (audio) samples transmitted so far
num_samps: u64,
/// Average of the sample so far
samp_avg: Complex<f32>,
}... | Demodulate | identifier_name |
tests.rs | use quickcheck::{QuickCheck, StdGen, TestResult};
use snap::raw::{decompress_len, Decoder, Encoder};
use snap::Error;
#[cfg(feature = "cpp")]
use snappy_cpp as cpp;
// roundtrip is a macro that compresses the input, then decompresses the result
// and compares it with the original input. If they are not equal, then th... |
TestResult::from_bool(
read_frame_depress(&write_frame_press(&bytes)) == bytes,
)
}
QuickCheck::new()
.gen(StdGen::new(rand::thread_rng(), 10_000))
.tests(1_000)
.quickcheck(p as fn(_) -> _);
}
#[test]
fn test_short_input() {
// Regression test for https://... | {
return TestResult::discard();
} | conditional_block |
tests.rs | use quickcheck::{QuickCheck, StdGen, TestResult};
use snap::raw::{decompress_len, Decoder, Encoder};
use snap::Error;
#[cfg(feature = "cpp")]
use snappy_cpp as cpp;
// roundtrip is a macro that compresses the input, then decompresses the result
// and compares it with the original input. If they are not equal, then th... | (bytes: &[u8]) -> Vec<u8> {
Decoder::new().decompress_vec(bytes).unwrap()
}
fn write_frame_press(bytes: &[u8]) -> Vec<u8> {
use snap::write;
use std::io::Write;
let mut wtr = write::FrameEncoder::new(vec![]);
wtr.write_all(bytes).unwrap();
wtr.into_inner().unwrap()
}
fn read_frame_depress(byt... | depress | identifier_name |
tests.rs | use quickcheck::{QuickCheck, StdGen, TestResult};
use snap::raw::{decompress_len, Decoder, Encoder};
use snap::Error;
#[cfg(feature = "cpp")]
use snappy_cpp as cpp;
// roundtrip is a macro that compresses the input, then decompresses the result
// and compares it with the original input. If they are not equal, then th... |
// Miscellaneous tests.
#[test]
fn small_copy() {
use std::iter::repeat;
for i in 0..32 {
let inner: String = repeat('b').take(i).collect();
roundtrip!(format!("aaaa{}aaaabbbb", inner).into_bytes());
}
}
#[test]
fn small_regular() {
let mut i = 1;
while i < 20_000 {
let m... | {
let data = include_bytes!("../data/Mark.Twain-Tom.Sawyer.txt.rawsnappy");
let data = &data[..];
assert_eq!(data, &*press(&depress(data)));
} | identifier_body |
tests.rs | use quickcheck::{QuickCheck, StdGen, TestResult};
use snap::raw::{decompress_len, Decoder, Encoder};
use snap::Error;
#[cfg(feature = "cpp")]
use snappy_cpp as cpp;
// roundtrip is a macro that compresses the input, then decompresses the result
// and compares it with the original input. If they are not equal, then th... | };
match Decoder::new().decompress(d, &mut buf) {
Err(ref err) if err == &$err => {}
Err(ref err) => panic!(
"expected decompression to fail with {:?}, \
but got {:?}",
$err, err
),
Ok(n) => {
... | vec![0; decompress_len(d).unwrap()] | random_line_split |
learn.rs | use super::events_from_chunks;
use clap::{App, Arg, ArgGroup, ArgMatches, SubCommand};
use futures::{try_join, Stream, StreamExt, TryStreamExt};
use nanoid::nanoid;
use serde::Serialize;
use serde_json;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::io::{stdin, stdout, AsyncWrite};
use tokio::sync::mpsc... |
}
EndpointBody::Response(response_body) => {
let response_id = ids.response();
response_body.commands.push(SpecCommand::from(
EndpointCommand::add_response_by_path_and_method(
response_id.clone(),
response_body.path_id.clone(),
response_body.met... | {
request_body
.commands
.push(SpecCommand::from(EndpointCommand::set_request_body_shape(
request_id,
body_descriptor.root_shape_id.clone(),
body_descriptor.content_type.clone(),
false,
)));
} | conditional_block |
learn.rs | use super::events_from_chunks;
use clap::{App, Arg, ArgGroup, ArgMatches, SubCommand};
use futures::{try_join, Stream, StreamExt, TryStreamExt};
use nanoid::nanoid;
use serde::Serialize;
use serde_json;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::io::{stdin, stdout, AsyncWrite};
use tokio::sync::mpsc... | body_descriptor.content_type.clone(),
false,
)));
}
}
EndpointBody::Response(response_body) => {
let response_id = ids.response();
response_body.commands.push(SpecCommand::from(
EndpointCommand::add_response_by_path_and_method(
... | request_body
.commands
.push(SpecCommand::from(EndpointCommand::set_request_body_shape(
request_id,
body_descriptor.root_shape_id.clone(), | random_line_split |
learn.rs | use super::events_from_chunks;
use clap::{App, Arg, ArgGroup, ArgMatches, SubCommand};
use futures::{try_join, Stream, StreamExt, TryStreamExt};
use nanoid::nanoid;
use serde::Serialize;
use serde_json;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::io::{stdin, stdout, AsyncWrite};
use tokio::sync::mpsc... | {
commands: Vec<SpecCommand>,
status_code: u16,
#[serde(skip)]
path_id: String,
#[serde(skip)]
method: String,
#[serde(flatten)]
body_descriptor: Option<EndpointBodyDescriptor>,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct EndpointBodyDescriptor {
content_type: ... | EndpointResponseBody | identifier_name |
lib.rs | was nonlinear. The problem is that these formats
//! are *non-linear color spaces*, which means that many operations that you may want
//! to perform on colors (addition, subtraction, multiplication, linear interpolation,
//! etc.) will work unexpectedly when performed in such a non-linear color space. As
//! such, th... | (&self, amount: Self::Scalar) -> Self {
self.lighten(-amount)
}
}
/// A trait for colors where a hue may be calculated.
///
/// ```
/// use approx::assert_relative_eq;
///
/// use palette::{GetHue, LinSrgb};
///
/// let red = LinSrgb::new(1.0f32, 0.0, 0.0);
/// let green = LinSrgb::new(0.0f32, 1.0, 0.0);
/... | darken | identifier_name |
lib.rs | electron gun was nonlinear. The problem is that these formats
//! are *non-linear color spaces*, which means that many operations that you may want
//! to perform on colors (addition, subtraction, multiplication, linear interpolation,
//! etc.) will work unexpectedly when performed in such a non-linear color space. As... |
{
print!("checking above limits... ");
$(
let from = $limited_from;
let to = $limited_to;
let diff = to - from;
let $limited = (1..11).map(|i| to + (i as f64 / 10.0) * diff);
)+
... | println!("ok")
} | random_line_split |
lib.rs | //! let whateve_it_becomes = orangeish + blueish;
//!
//! // Encode the result back into sRGB and create a byte array
//! let pixel: [u8; 3] = Srgb::from_linear(whateve_it_becomes)
//! .into_format()
//! .into_raw();
//! ```
//!
//! But, even when colors *are* 'linear', there is yet more to explore.
//!
//! The m... | {
T::from_f64(c)
} | identifier_body | |
list.rs | // 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! Dynamic widgets
use std::iter;
use crate::draw::{Draw... | use kas::geom::Rect;
/// A generic row widget
///
/// See documentation of [`List`] type.
pub type Row<W> = List<Horizontal, W>;
/// A generic column widget
///
/// See documentation of [`List`] type.
pub type Column<W> = List<Vertical, W>;
/// A row of boxed widgets
///
/// This is parameterised over handler messag... | use crate::{AlignHints, Directional, Horizontal, Vertical};
use crate::{CoreData, Layout, TkAction, Widget, WidgetCore, WidgetId}; | random_line_split |
list.rs | // 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! Dynamic widgets
use std::iter;
use crate::draw::{Draw... | (&mut self, mgr: &mut Manager) {
if!self.widgets.is_empty() {
mgr.send_action(TkAction::Reconfigure);
}
self.widgets.clear();
}
/// Append a child widget
///
/// Triggers a [reconfigure action](Manager::send_action).
pub fn push(&mut self, mgr: &mut Manager, widg... | clear | identifier_name |
list.rs | // 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 in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! Dynamic widgets
use std::iter;
use crate::draw::{Draw... |
#[inline]
fn core_data_mut(&mut self) -> &mut CoreData {
&mut self.core
}
#[inline]
fn widget_name(&self) -> &'static str {
"List"
}
#[inline]
fn as_widget(&self) -> &dyn Widget {
self
}
#[inline]
fn as_widget_mut(&mut self) -> &mut dyn Widget {
... | {
&self.core
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.