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 |
|---|---|---|---|---|
cache.rs | on a type, hold impls here while
// folding and add them to the cache later on if we find the trait.
orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
/// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
/// we need the alias element to have an array of... | cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
}
// Cache where all known primitives have their documentation located.
//
// Favor linking to as local extern as possible, so iterate all crates in
// reverse topological order.
... | let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
cache.extern_locations.insert(n, (e.name.clone(), src_root,
extern_location(e, extern_url, &dst)));
let did = DefId { krate: n, index: CRATE_DEF_INDEX }; | random_line_split |
cache.rs | }
// Cache where all known primitives have their documentation located.
//
// Favor linking to as local extern as possible, so iterate all crates in
// reverse topological order.
for &(_, ref e) in krate.externs.iter().rev() {
for &(def_id, prim, _) in &e.primiti... | build_index | identifier_name | |
cache.rs | , index: CRATE_DEF_INDEX };
cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
}
// Cache where all known primitives have their documentation located.
//
// Favor linking to as local extern as possible, so iterate all crates in
// reverse... | {
url.push('/')
} | conditional_block | |
constants.rs | use lazy_static::lazy_static;
use crate::options::ConfigColours;
// Default widget ID
pub const DEFAULT_WIDGET_ID: u64 = 56709;
// How long to store data.
pub const STALE_MAX_MILLISECONDS: u64 = 600 * 1000; // Keep 10 minutes of data.
// How much data is SHOWN
pub const DEFAULT_TIME_MILLISECONDS: u64 = 60 * 1000; /... | // rx_color: None,
// tx_color: None,
// rx_total_color: None,
// tx_total_color: None,
// border_color: None,
// highlighted_border_color: None,
// text_color: None,
// selected_text_color: None,
// selected_bg_color: None,
// widget_title... | // all_cpu_color: None,
// avg_cpu_color: None,
// cpu_core_colors: None,
// ram_color: None,
// swap_color: None, | random_line_split |
shell.rs | request = Request::new_with_str_and_init(url, &opts).map_err(js_err_handler)?;
let window = web_sys::window().unwrap();
// Get the response as a future and await it
let res_value = JsFuture::from(window.fetch_with_request(&request))
.await
.map_err(js_err_handler)?;
// Turn that into a p... |
/// Gets the initial state injected by the server, if there was any. This is used to differentiate initial loads from subsequent ones,
/// which have different log chains to prevent double-trips (a common SPA problem).
pub fn get_initial_state() -> InitialState {
let val_opt = web_sys::window().unwrap().get("__PE... | {
let val_opt = web_sys::window().unwrap().get("__PERSEUS_RENDER_CFG");
let js_obj = match val_opt {
Some(js_obj) => js_obj,
None => return None,
};
// The object should only actually contain the string value that was injected
let cfg_str = match js_obj.as_string() {
Some(cfg... | identifier_body |
shell.rs | request = Request::new_with_str_and_init(url, &opts).map_err(js_err_handler)?;
let window = web_sys::window().unwrap();
// Get the response as a future and await it
let res_value = JsFuture::from(window.fetch_with_request(&request))
.await
.map_err(js_err_handler)?;
// Turn that into a p... | () -> InitialState {
let val_opt = web_sys::window().unwrap().get("__PERSEUS_INITIAL_STATE");
let js_obj = match val_opt {
Some(js_obj) => js_obj,
None => return InitialState::NotPresent,
};
// The object should only actually contain the string value that was injected
let state_str =... | get_initial_state | identifier_name |
shell.rs | let request = Request::new_with_str_and_init(url, &opts).map_err(js_err_handler)?;
let window = web_sys::window().unwrap();
// Get the response as a future and await it
let res_value = JsFuture::from(window.fetch_with_request(&request))
.await
.map_err(js_err_handler)?;
// Turn that into... | /// A representation of whether or not the initial state was present. If it was, it could be `None` (some templates take no state), and
/// if not, then this isn't an initial load, and we need to request the page from the server. It could also be an error that the server
/// has rendered.
pub enum InitialState {
//... | random_line_split | |
lib.rs | //! An Entity Component System for game development.
//!
//! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP.
#![allow(dead_code)]
#![feature(append,drain)]
use std::iter;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use std::collections::hash_map::... | (&mut self, ent: Entity) {
self.clear_family_data_for(ent);
self.components.remove(&ent);
}
fn remove_from_family(&mut self, family: &str, ent: Entity) {
let mut idx: Option<usize> = None;
{
let vec = self.families.get_mut(family).expect("No such family");
... | delete_component_data_for | identifier_name |
lib.rs | //! An Entity Component System for game development.
//!
//! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP.
#![allow(dead_code)]
#![feature(append,drain)]
use std::iter;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use std::collections::hash_map::... |
// Give this EntityDataHolder a list of which families this entity has.
self.data[self.ent].set_families(families);
}
}
/*
fn main() {
println!("Hello, world!");
let mut manager = EntityManager::new();
let ent = manager.new_entity();
manager.add_component_to(ent, Position{x:1, y:2});
println!("p... | {
self.processor.add_processable(self.ent);
} | conditional_block |
lib.rs | //! An Entity Component System for game development.
//!
//! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP.
#![allow(dead_code)]
#![feature(append,drain)]
use std::iter;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use std::collections::hash_map::... | if self.$access.has_it() {
b.field(stringify!($access), &self.$access);
}
)+*/
b.finish()
}
}
impl EntityDataHolder for $data {
fn new() -> Self {
$data::new_empty()
... | /*$( | random_line_split |
lib.rs | //! An Entity Component System for game development.
//!
//! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP.
#![allow(dead_code)]
#![feature(append,drain)]
use std::iter;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use std::collections::hash_map::... |
pub fn set_family_relation(&mut self, family: &'static str, ent: Entity) {
match self.families.entry(family) {
Vacant(entry) => {entry.insert(vec!(ent));},
Occupied(entry) => {
let v = entry.into_mut();
if v.contains(&ent) { return; }
... | {
let mut idx: Option<usize> = None;
{
let vec = self.families.get_mut(family).expect("No such family");
let op = vec.iter().enumerate().find(|&(_,e)| *e == ent);
idx = Some(op.expect("Entity not found in this family").0);
}
if let Some(idx) = idx {
... | identifier_body |
baconian.rs | //! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than
//! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605.
//!
//! Each character of the plaintext message is encoded as a 5-bit binary character.
//! These characters are then "hidden" in a decoy ... |
/// Encrypt a message using the Baconian cipher
///
/// * The message to be encrypted can only be ~18% of the decoy_text as each character
/// of message is encoded by 5 encoding characters `AAAAA`, `AAAAB`, etc.
/// * The italicised ciphertext is then hidden in a decoy text, where, for each '... | {
Baconian {
use_distinct_alphabet: key.0,
decoy_text: key.1.unwrap_or_else(|| lipsum(160)),
}
} | identifier_body |
baconian.rs | //! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than
//! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605.
//!
//! Each character of the plaintext message is encoded as a 5-bit binary character.
//! These characters are then "hidden" in a decoy ... | o";
let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n";
assert_eq!(cipher_text, b.encrypt(message).unwrap());
}
// Need to test that the traditional and use_distinct_alphabet codes give different results
#[test]
fn encrypt_trad_v_dist() {
let b_trad = Baconian::new(... | essage = "Hell | identifier_name |
baconian.rs | //! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than
//! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605.
//!
//! Each character of the plaintext message is encoded as a 5-bit binary character.
//! These characters are then "hidden" in a decoy ... | }
// Need to test that the traditional and use_distinct_alphabet codes give different results
#[test]
fn encrypt_trad_v_dist() {
let b_trad = Baconian::new((false, None));
let b_dist = Baconian::new((true, None));
let message = "I JADE YOU VERVENT UNICORN";
assert_ne!(
... | assert_eq!(cipher_text, b.encrypt(message).unwrap()); | random_line_split |
recv_stream.rs | VarInt,
};
/// A stream that can only be used to receive data
///
/// `stop(0)` is implicitly called on drop unless:
/// - A variant of [`ReadError`] has been yielded by a read call
/// - [`stop()`] was called explicitly
///
/// # Closing a stream
///
/// When a stream is expected to be closed gracefully the sende... | (&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> {
Read {
stream: self,
buf: ReadBuf::new(buf),
}
.await
}
/// Read an exact number of bytes contiguously from the stream.
///
/// See [`read()`] for details.
///
/// [`read()`]: RecvSt... | read | identifier_name |
recv_stream.rs | },
VarInt,
};
/// A stream that can only be used to receive data
///
/// `stop(0)` is implicitly called on drop unless:
/// - A variant of [`ReadError`] has been yielded by a read call
/// - [`stop()`] was called explicitly
///
/// # Closing a stream
///
/// When a stream is expected to be closed gracefully the se... | UnknownStream,
/// Attempted an ordered read following an unordered read
///
/// Performing an unordered read allows discontinuities to arise in the receive buffer of a
/// stream which cannot be recovered, making further ordered reads impossible.
#[error("ordered read after unordered read")]
... | #[error("connection lost")]
ConnectionLost(#[from] ConnectionError),
/// The stream has already been stopped, finished, or reset
#[error("unknown stream")] | random_line_split |
recv_stream.rs | VarInt,
};
/// A stream that can only be used to receive data
///
/// `stop(0)` is implicitly called on drop unless:
/// - A variant of [`ReadError`] has been yielded by a read call
/// - [`stop()`] was called explicitly
///
/// # Closing a stream
///
/// When a stream is expected to be closed gracefully the sende... |
}
/// Future produced by [`RecvStream::read_exact()`].
///
/// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact
#[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"]
struct ReadExact<'a> {
stream: &'a mut RecvStream,
buf: ReadBuf<'a>,
}
impl<'a> Future for ReadExact<'a>... | {
let this = self.get_mut();
ready!(this.stream.poll_read(cx, &mut this.buf))?;
match this.buf.filled().len() {
0 if this.buf.capacity() != 0 => Poll::Ready(Ok(None)),
n => Poll::Ready(Ok(Some(n))),
}
} | identifier_body |
conf.rs | use crate::ecies;
use crate::hash256::Hash256;
use crate::keys::{public_to_slice, sign, slice_to_public};
use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE};
use crate::util::secs_since;
use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey};
use std::str::FromStr;
use std::time::UNIX_EPOCH;
... | (&self) -> u128 {self.value}
fn gas_price(&self) -> u128 {self.gas_price}
fn encryption_conf(&self) -> Option<EncOpt> {
let mut rng = rand::thread_rng();
let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap();
let nonce: Hash256 = Hash256::random();
let secp = Secp25... | value | identifier_name |
conf.rs | use crate::ecies;
use crate::hash256::Hash256;
use crate::keys::{public_to_slice, sign, slice_to_public};
use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE};
use crate::util::secs_since;
use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey};
use std::str::FromStr;
use std::time::UNIX_EPOCH;
... |
fn gas(&self) -> u128 {self.gas}
fn value(&self) -> u128 {self.value}
fn gas_price(&self) -> u128 {self.gas_price}
fn encryption_conf(&self) -> Option<EncOpt> {
let mut rng = rand::thread_rng();
let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap();
let nonce... | fn secret(&self) -> Option<String> {self.secret.clone()}
fn crypto(&self) -> Option<String> {self.crypto.clone()}
fn password(&self) -> String {self.password.clone()}
fn out_address(&self) -> String {self.out_address.clone()} | random_line_split |
conf.rs | use crate::ecies;
use crate::hash256::Hash256;
use crate::keys::{public_to_slice, sign, slice_to_public};
use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE};
use crate::util::secs_since;
use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey};
use std::str::FromStr;
use std::time::UNIX_EPOCH;
... |
fn encryption_conf(&self) -> Option<EncOpt> { None }
fn version(&self, cfg: &Option<EncOpt>) -> Message;
}
impl Sender for Wallet {
fn in_address(&self) -> String {return self.in_address.clone();}
fn out_address(&self) -> String {return self.out_address.clone();}
fn outpoint_hash(&self) -> Hash25... | {0} | identifier_body |
main.rs | use std::cell::Cell;
fn main() {
variable_bindings();
functions();
primitive_types();
comments();
if_();
loops();
ownership();
reference_and_borrowing();
lifetimes();
mutability();
struct_();
enums();
match_();
patterns();
method_syntax();
vectors();
... | () {
// Booleans
let x: bool = false;
println!("x is {}", x);
// char, supports Unicode
let x: char = 'A';
println!("x is {}", x);
// Numeric values
// signed and fixed size
let x: i8 = -12;
println!("x is {}", x);
// unsigned and fixed size
let x: u8 = 12;
println!... | primitive_types | identifier_name |
main.rs | use std::cell::Cell;
fn main() {
variable_bindings();
functions();
primitive_types();
comments();
if_();
loops();
ownership();
reference_and_borrowing();
lifetimes();
mutability();
struct_();
enums();
match_();
patterns();
method_syntax();
vectors();
... |
// Inheritance
trait bar : foo {
fn is_good(&self);
}
// Deriving
#[derive(Debug)]
struct Foo;
println!("{:?}", Foo);
}
fn drop() {
// A special trait from Rust standard library. When things goes out of scope.
struct Firework {
strength: i32,
};
impl Drop... | f.is_valid() }
} | identifier_body |
main.rs | use std::cell::Cell;
fn main() {
variable_bindings();
functions();
primitive_types();
comments();
if_();
loops();
ownership();
reference_and_borrowing();
lifetimes();
mutability();
struct_();
enums();
match_();
patterns();
method_syntax();
vectors();
... | }
}
fn strings() {
// resizable, a sequence of utf-8 characters, not null terminated
// &str is a string slice, has fixed size.
let greeting = "Hello there."; // &'static str
let s = "foo
bar";
let s2 = "foo\
bar";
println!("{}", s);
println!("{}", s2);
let mut s = ... | for i in &v2 {
println!("A reference to {}", i); | random_line_split |
mod.rs | //! Provides structs used to interact with the cypher transaction endpoint
//!
//! The types declared in this module, save for `Statement`, don't need to be instantiated
//! directly, since they can be obtained from the `GraphClient`.
//!
//! # Examples
//!
//! ## Execute a single query
//! ```
//! # use rusted_cypher:... | #[cfg(not(feature = "rustc-serialize"))]
fn check_param_errors_for_rustc_serialize(_: &Vec<Statement>) -> Result<(), GraphError> {
Ok(())
}
fn send_query(client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>)
-> Result<Response, GraphError> {
if cfg!(feature = "rustc-serialize") {... |
Ok(())
}
| random_line_split |
mod.rs | //! Provides structs used to interact with the cypher transaction endpoint
//!
//! The types declared in this module, save for `Statement`, don't need to be instantiated
//! directly, since they can be obtained from the `GraphClient`.
//!
//! # Examples
//!
//! ## Execute a single query
//! ```
//! # use rusted_cypher:... |
}
| {
let cypher = get_cypher();
let statement1 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n");
let statement2 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n");
let query = cypher.query()
.with_statement(statement1)
.with_statement(statement2);
let res... | identifier_body |
mod.rs | //! Provides structs used to interact with the cypher transaction endpoint
//!
//! The types declared in this module, save for `Statement`, don't need to be instantiated
//! directly, since they can be obtained from the `GraphClient`.
//!
//! # Examples
//!
//! ## Execute a single query
//! ```
//! # use rusted_cypher:... | (client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>)
-> Result<Response, GraphError> {
if cfg!(feature = "rustc-serialize") {
try!(check_param_errors_for_rustc_serialize(&statements));
}
let mut json = BTreeMap::new();
json.insert("statements", statements);
... | send_query | identifier_name |
text.rs | //! This protocol is used to handle input and output of
//! text-based information intended for the system user during the operation of code in the boot
//! services environment. Also included here are the definitions of three console devices: one for input
//! and one each for normal output and errors.
use core::fmt;... | // Represents the foreground color black.
Black = 0x00,
/// Represents the foreground color blue.
Blue = 0x01,
/// Represents the foreground color green.
Green = 0x02,
/// Represents the foreground color cyan.
Cyan = 0x03,
/// Represents the foreground color red.
Red = 0x04,
/// ... | ndColor {
/ | identifier_name |
text.rs | //! This protocol is used to handle input and output of
//! text-based information intended for the system user during the operation of code in the boot
//! services environment. Also included here are the definitions of three console devices: one for input
//! and one each for normal output and errors.
use core::fmt;... | Executes the given function with the UTF16-encoded string.
///
/// `function` will get a UTF16-encoded null-terminated string as its argument when its called.
///
/// `function` may be called multiple times. This is because the string is converted
/// to UTF16 in a fixed size buffer to avoid allocations. As a consequen... | self.output_string(s).map_err(|_| fmt::Error).map(|_| ())
}
}
/// | identifier_body |
text.rs | //! This protocol is used to handle input and output of
//! text-based information intended for the system user during the operation of code in the boot
//! services environment. Also included here are the definitions of three console devices: one for input
//! and one each for normal output and errors.
use core::fmt;... | /// Represents the background color blue.
Blue = 0x10,
/// Represents the background color green.
Green = 0x20,
/// Represents the background color cyan.
Cyan = 0x30,
/// Represents the background color red.
Red = 0x40,
/// Represents the background color magenta.
Magenta = 0x50,... | random_line_split | |
text.rs | //! This protocol is used to handle input and output of
//! text-based information intended for the system user during the operation of code in the boot
//! services environment. Also included here are the definitions of three console devices: one for input
//! and one each for normal output and errors.
use core::fmt;... | function(buffer.as_ptr())?;
}
Ok(())
};
for character in string.chars() {
// If there is not enough space in the buffer, flush it
if current_index + character.len_utf16() + 1 >= BUFFER_SIZE {
flush_buffer(&mut buffer, current_index, warning)?;
}
... | *warning = function(buffer.as_ptr())?;
} else {
| conditional_block |
context.rs | use std::{
alloc::Layout,
cell::{Ref, RefMut},
marker::PhantomData,
mem::size_of,
panic::AssertUnwindSafe,
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
};
use anyhow::anyhow;
use bytemuck::{Pod, Zeroable};
use feather_common::Game;
use feather_ecs::EntityBuilder;
use quill_common::Co... | Ok(ptr)
}
/// Writes `data` to `ptr`.
///
/// # Safety
/// **WASM**: No concerns.
/// **NATIVE**: `ptr` must point to a slice
/// of at least `len` valid bytes.
pub unsafe fn write_bytes(&self, ptr: PluginPtrMut<u8>, data: &[u8]) -> anyhow::Result<()> {
let bytes = self.... | random_line_split | |
context.rs | use std::{
alloc::Layout,
cell::{Ref, RefMut},
marker::PhantomData,
mem::size_of,
panic::AssertUnwindSafe,
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
};
use anyhow::anyhow;
use bytemuck::{Pod, Zeroable};
use feather_common::Game;
use feather_ecs::EntityBuilder;
use quill_common::Co... |
pub fn init_with_instance(&self, instance: &Instance) -> anyhow::Result<()> {
match &self.inner {
Inner::Wasm(w) => w.borrow_mut().init_with_instance(instance),
Inner::Native(_) => panic!("cannot initialize native plugin context"),
}
}
/// Enters the plugin context... | {
Self {
inner: Inner::Native(native::NativePluginContext::new()),
invoking_on_main_thread: AtomicBool::new(false),
game: ThreadPinned::new(None),
id,
entity_builders: ThreadPinned::new(Arena::new()),
}
} | identifier_body |
context.rs | use std::{
alloc::Layout,
cell::{Ref, RefMut},
marker::PhantomData,
mem::size_of,
panic::AssertUnwindSafe,
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
};
use anyhow::anyhow;
use bytemuck::{Pod, Zeroable};
use feather_common::Game;
use feather_ecs::EntityBuilder;
use quill_common::Co... | <T: DeserializeOwned>(
&self,
ptr: PluginPtr<u8>,
len: u32,
) -> anyhow::Result<T> {
// SAFETY: we do not return a reference to these
// bytes.
unsafe {
let bytes = self.deref_bytes(ptr.cast(), len)?;
serde_json::from_slice(bytes).map_err(From:... | read_json | identifier_name |
lib.rs | // This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
# Rust bindings library for Sciter engine.
[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rende... |
return ap;
}
/// Getting ISciterAPI reference, can be used for manual API calling.
///
/// Bypasses ABI compatability checks.
#[doc(hidden)]
#[allow(non_snake_case)]
pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI {
let ap = unsafe {
if cfg!(feature="extension") {
EXT_API.expect("Sciter API is not availabl... | {
assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature");
} | conditional_block |
lib.rs | // This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
# Rust bindings library for Sciter engine.
[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rende... |
/// Get a global variable by its path.
///
/// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable).
#[doc(hidden)]
pub fn get_variable(path: &str) -> dom::Result<Value> {
let ws = s2u!(path);
let mut value = Value::new();
let ok = (_API.SciterGetVariable)(std::ptr::null_mut()... | {
let ws = s2u!(path);
let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr());
if ok == dom::SCDOM_RESULT::OK {
Ok(())
} else {
Err(ok)
}
} | identifier_body |
lib.rs | // This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
# Rust bindings library for Sciter engine.
[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rende... | (permanent: bool) -> ::std::result::Result<ApiType, String> {
use std::ffi::CString;
use std::path::Path;
fn try_load(path: &Path) -> Option<LPCVOID> {
let path = CString::new(format!("{}", path.display())).expect("invalid library path");
let dll = unsafe { LoadLibraryA(path.as_ptr()) };
... | try_load_library | identifier_name |
lib.rs | // This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
# Rust bindings library for Sciter engine.
[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rende... | Err(error) => panic!("{}", error),
}
}
}
#[cfg(all(feature = "dynamic", unix))]
mod ext {
#![allow(non_snake_case, non_camel_case_types)]
extern crate libc;
pub static mut CUSTOM_DLL_PATH: Option<String> = None;
#[cfg(target_os = "linux")]
const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ];
//... | match try_load_library(true) {
Ok(api) => api, | random_line_split |
lib.rs | use cpython::{
py_class, py_exception, py_module_initializer, ObjectProtocol, PyClone, PyDrop, PyErr,
PyObject, PyResult, PySequence, PythonObject, exc::{TypeError}
};
use search::Graph;
use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap};
use std::convert::TryInto;
mod search;
#[cfg(feature = "p... | // and there are still errors. Raise with info from all of them.
let mut skip_edges = BTreeSet::new();
let mut errors = Vec::new();
'outer: for _ in 0..10 {
if let Some(edges) = self.graph(py).borrow().search(hash_in, &hash_var_in, hash_out, &hash_var_out, &skip_edges) {
... | }
// Retry a few times, if something breaks along the way.
// Collect errors.
// If we run out of paths to take or run out of reties, | random_line_split |
lib.rs | //! This crate wraps [libkres](https://knot-resolver.cz) from
//! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver,
//! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides
//! a generic interface for pushing/pulling DNS mes... | () {
let context = Context::new();
assert!(context.add_module("iterate").is_ok());
assert!(context.remove_module("iterate").is_ok());
}
#[test]
fn context_trust_anchor() {
let context = Context::new();
let ta = gen::RR::from_string(
". 0 IN DS 20326 8 2 E... | context_with_module | identifier_name |
lib.rs | //! This crate wraps [libkres](https://knot-resolver.cz) from
//! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver,
//! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides
//! a generic interface for pushing/pulling DNS mes... | }
}
/// Request wraps `struct kr_request` and keeps a reference for the context.
/// The request is not automatically executed, it must be driven the caller to completion.
pub struct Request {
context: Arc<Context>,
inner: Mutex<*mut c::lkr_request>,
}
/* Neither request nor context are thread safe.
* Bo... | } | random_line_split |
lib.rs | //! This crate wraps [libkres](https://knot-resolver.cz) from
//! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver,
//! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides
//! a generic interface for pushing/pulling DNS mes... |
/// Generate an outbound query for the request. This should be called when `consume()` returns a `Produce` state.
pub fn produce(&self) -> Option<(Bytes, Vec<SocketAddr>)> {
let mut msg = vec![0; 512];
let mut addresses = Vec::new();
let mut sa_vec: Vec<*mut c::sockaddr> = vec![ptr::nu... | {
let (_context, inner) = self.locked();
let from = socket2::SockAddr::from(from);
let msg_ptr = if !msg.is_empty() { msg.as_ptr() } else { ptr::null() };
unsafe { c::lkr_consume(*inner, from.as_ptr() as *const _, msg_ptr, msg.len()) }
} | identifier_body |
e.rs | use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[... | (
&self,
source: usize,
sink: usize,
dual: &mut [T],
pv: &mut [usize],
pe: &mut [usize],
) -> bool {
let n = self.g.len();
let mut dist = vec![self.cost_sum; n];
let mut vis = vec![false; n];
... | refine_dual | identifier_name |
e.rs | use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[... |
}
}
if!vis[sink] {
return false;
}
for v in 0..n {
if!vis[v] {
continue;
}
dual[v] -= dist[sink] - dist[v];
}
true
}
}
struct _E... | {
dist[e.to] = dist[v] + cost;
pv[e.to] = v;
pe[e.to] = i;
que.push((std::cmp::Reverse(dist[e.to]), e.to));
} | conditional_block |
e.rs | use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[... | }
}
impl BoundedAbove for $ty {
#[inline]
fn max_value() -> Self {
Self::max_value()
}
}
impl Integral for $ty {}
)*
};
}
impl_integral!(i8, i16, i32, i64, i128, isize, ... | Self::min_value() | random_line_split |
e.rs | use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[... | while v!= source {
c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap);
v = prev_v[v];
}
let mut v = sink;
while v!= source {
self.g[prev_v[v]][prev_e[v]].cap -= c;
let rev... | {
let n = self.g.len();
assert!(source < n);
assert!(sink < n);
assert_ne!(source, sink);
let mut dual = vec![T::zero(); n];
let mut prev_v = vec![0; n];
let mut prev_e = vec![0; n];
let mut flow = T::zero();
le... | identifier_body |
api.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
use super::dev_lock::LockReadGuard;
use super::drop_privileges::get_saved_ids;
use super::{AllowedIP, Device, Error, SocketAddr};
use crate::device::Action;
use crate::serialization::KeyBytes;
use crate::x25519;
use he... |
match key {
"private_key" => match val.parse::<KeyBytes>() {
Ok(key_bytes) => {
device.set_key(x25519::StaticSecret::from(key_bytes.0))
}
Err(_) => return EINV... | {
d.try_writeable(
|device| device.trigger_yield(),
|device| {
device.cancel_yield();
let mut cmd = String::new();
while reader.read_line(&mut cmd).is_ok() {
cmd.pop(); // remove newline if any
if cmd.is_empty() {
... | identifier_body |
api.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
use super::dev_lock::LockReadGuard;
use super::drop_privileges::get_saved_ids;
use super::{AllowedIP, Device, Error, SocketAddr};
use crate::device::Action;
use crate::serialization::KeyBytes;
use crate::x25519;
use he... | Ok(mark) => match device.set_fwmark(mark) {
Ok(()) => {}
Err(_) => return EADDRINUSE,
},
Err(_) => return EINVAL,
},
"replac... | target_os = "fuchsia",
target_os = "linux"
))]
"fwmark" => match val.parse::<u32>() { | random_line_split |
api.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
use super::dev_lock::LockReadGuard;
use super::drop_privileges::get_saved_ids;
use super::{AllowedIP, Device, Error, SocketAddr};
use crate::device::Action;
use crate::serialization::KeyBytes;
use crate::x25519;
use he... | (&mut self, fd: i32) -> Result<(), Error> {
let io_file = unsafe { UnixStream::from_raw_fd(fd) };
self.queue.new_event(
io_file.as_raw_fd(),
Box::new(move |d, _| {
// This is the closure that listens on the api file descriptor
let mut reader = Bu... | register_api_fd | identifier_name |
api.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
use super::dev_lock::LockReadGuard;
use super::drop_privileges::get_saved_ids;
use super::{AllowedIP, Device, Error, SocketAddr};
use crate::device::Action;
use crate::serialization::KeyBytes;
use crate::x25519;
use he... |
let (key, val) = (parsed_cmd[0], parsed_cmd[1]);
match key {
"remove" => match val.parse::<bool>() {
Ok(true) => remove = true,
Ok(false) => remove = false,
Err(_) => return EINVAL,
},
"p... | {
return EPROTO;
} | conditional_block |
report.rs | //! Coverage report generation.
//!
//! # Template directory structure
//!
//! The coverage report produce two classes of files:
//!
//! * One summary page
//! * Source file pages, one page per source.
//!
//! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this
... | eport_path: &Path, report_files: &[ReportFileEntry], tera: &Tera, crate_path: &str, config: &FileConfig) -> Result<PathBuf> {
let path = report_path.join(config.output);
let mut context = Context::new();
let files = report_files
.iter()
.map(|entry| {
json!({
"symb... | ite_summary(r | identifier_name |
report.rs | //! Coverage report generation.
//!
//! # Template directory structure
//!
//! The coverage report produce two classes of files:
//!
//! * One summary page
//! * Source file pages, one page per source.
//!
//! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this
... | //! }
//! },
//! ...
//! ]
//! }
//! ```
use error::{Result, ResultExt};
use sourcepath::{SourceType, identify_source_path};
use template::new as new_template;
use utils::{clean_dir, parent_3};
use copy_dir::copy_dir;
use cov::{self, Gcov, Graph, Interner, Report, Symbol};
use serde_jso... | //! "branches_count": 250,
//! "branches_executed": 225,
//! "branches_taken": 219 | random_line_split |
report.rs | //! Coverage report generation.
//!
//! # Template directory structure
//!
//! The coverage report produce two classes of files:
//!
//! * One summary page
//! * Source file pages, one page per source.
//!
//! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this
... | /// Renders the `report` into `report_path` using a template.
///
/// If the template has a summary page, returns the path of the rendered summary.
fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Interner) -> Result<Option<PathBuf>> {
use toml::de::... | let mut graph = Graph::default();
for extension in &["gcno", "gcda"] {
progress!("Parsing", "*.{} files", extension);
for entry in read_dir(cov_build_path.join(extension))? {
let path = entry?.path();
if path.extension() == Some(OsStr::new(extension)) {
t... | identifier_body |
report.rs | //! Coverage report generation.
//!
//! # Template directory structure
//!
//! The coverage report produce two classes of files:
//!
//! * One summary page
//! * Source file pages, one page per source.
//!
//! `cargo cov` uses [Tera templates](https://github.com/Keats/tera#readme). Template files are stored using this
... | }
}
graph.analyze();
Ok(graph)
}
/// Renders the `report` into `report_path` using a template.
///
/// If the template has a summary page, returns the path of the rendered summary.
fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Int... | trace!("merging {} {:?}", extension, path);
graph.merge(Gcov::open(path, interner)?)?;
}
| conditional_block |
main.rs | = 60; // Second:minute scale. Can be changed for debugging purposes.
#[cfg(feature = "tokio")] const COMMAND_DEACTIVATE: u8 = 0;
#[cfg(feature = "tokio")] const COMMAND_ACTIVATE: u8 = 1;
#[cfg(feature = "tokio")] const COMMAND_TRIGGER: u8 = 2;
fn main() {
let success = do_main();
std::process::exit(if s... | else { None };
if active &&
self.notify.map(|notify| (idle.unwrap() + notify) >= self.time).unwrap_or(idle.unwrap() >= self.time) {
let idle = idle.unwrap();
if self.not_when_fullscreen && self.fullscreen.is_none() {
let mut focus = 0u64;
let... | {
Some(match get_idle(self.display, self.info) {
Ok(idle) => idle / 1000, // Convert to seconds
Err(_) => return Some(false)
})
} | conditional_block |
main.rs | 64 = 60; // Second:minute scale. Can be changed for debugging purposes.
#[cfg(feature = "tokio")] const COMMAND_DEACTIVATE: u8 = 0;
#[cfg(feature = "tokio")] const COMMAND_ACTIVATE: u8 = 1;
#[cfg(feature = "tokio")] const COMMAND_TRIGGER: u8 = 2;
fn main() {
let success = do_main();
std::process::exit(if... | }
#[cfg(feature = "tokio")] {
#[cfg(feature = "pulse")]
let not_when_audio = matches.is_present("not-when-audio");
let socket = matches.value_of("socket");
let app = Rc::new(RefCell::new(app));
let mut core = Core::new().unwrap();
let handle = Rc::new(core.hand... |
thread::sleep(app.delay);
} | random_line_split |
main.rs | = 60; // Second:minute scale. Can be changed for debugging purposes.
#[cfg(feature = "tokio")] const COMMAND_DEACTIVATE: u8 = 0;
#[cfg(feature = "tokio")] const COMMAND_ACTIVATE: u8 = 1;
#[cfg(feature = "tokio")] const COMMAND_TRIGGER: u8 = 2;
fn main() {
let success = do_main();
std::process::exit(if s... |
let mut playing = 0;
let app = Rc::clone(&app);
handle.spawn(rx.for_each(move |event| {
match event {
Event::Clear => playing = 0,
Event::New => playing += 1,
Event::Finish => {... | {
unsafe {
let state = pa_context_get_state(ctx);
if state == PA_CONTEXT_READY {
pa_context_set_subscribe_callback(ctx, Some(subscribe_callback), userdata);
pa_context_subscribe(ctx, PA_SUBSCRIPT... | identifier_body |
main.rs | .takes_value(true)
.requires("notify")
.conflicts_with("print")
);
#[cfg(feature = "tokio")]
let mut clap_app = clap_app; // make mutable
#[cfg(feature = "tokio")] {
clap_app = clap_app
.arg(
Arg::with_name("socket")
... | get_idle | identifier_name | |
decoder.rs | use std::cmp;
use std::io::{self, Read};
use encoding_rs::{Decoder, Encoding, UTF_8};
/// A BOM is at least 2 bytes and at most 3 bytes.
///
/// If fewer than 2 bytes are available to be read at the beginning of a
/// reader, then a BOM is `None`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Bom {
bytes: [... | Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(nread)
}
/// A reader that transcodes to UTF-8. The source encoding is determined by
/// inspecting the BOM from the stream read from `R`, if one exists. If a
/// UTF-16 BOM exists, then t... | Ok(n) => {
nread += n;
let tmp = buf;
buf = &mut tmp[n..];
} | random_line_split |
decoder.rs | use std::cmp;
use std::io::{self, Read};
use encoding_rs::{Decoder, Encoding, UTF_8};
/// A BOM is at least 2 bytes and at most 3 bytes.
///
/// If fewer than 2 bytes are available to be read at the beginning of a
/// reader, then a BOM is `None`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Bom {
bytes: [... |
}
Ok(nwrite)
}
#[inline(never)] // impacts perf...
fn detect(&mut self) -> io::Result<()> {
let bom = self.rdr.peek_bom()?;
self.decoder = bom.decoder();
Ok(())
}
}
impl<R: io::Read, B: AsMut<[u8]>> io::Read for DecodeReader<R, B> {
fn read(&mut self, buf: ... | {
self.pos = 0;
self.last = true;
let (_, _, nout, _) =
self.decoder.as_mut().unwrap().decode_to_utf8(
&[], buf, true);
return Ok(nout);
} | conditional_block |
decoder.rs | use std::cmp;
use std::io::{self, Read};
use encoding_rs::{Decoder, Encoding, UTF_8};
/// A BOM is at least 2 bytes and at most 3 bytes.
///
/// If fewer than 2 bytes are available to be read at the beginning of a
/// reader, then a BOM is `None`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Bom {
bytes: [... | () {
let srcbuf = vec![0xFF, 0xFE];
let mut dstbuf = vec![0; 8 * (1<<10)];
let mut rdr = DecodeReader::new(&*srcbuf, vec![0; 8 * (1<<10)], None);
let n = rdr.read(&mut dstbuf).unwrap();
assert_eq!(&*srcbuf, &dstbuf[..n]);
let srcbuf = vec![0xFE, 0xFF];
let mut rd... | trans_utf16_bom | identifier_name |
decoder.rs | use std::cmp;
use std::io::{self, Read};
use encoding_rs::{Decoder, Encoding, UTF_8};
/// A BOM is at least 2 bytes and at most 3 bytes.
///
/// If fewer than 2 bytes are available to be read at the beginning of a
/// reader, then a BOM is `None`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Bom {
bytes: [... |
}
/// `BomPeeker` wraps `R` and satisfies the `io::Read` interface while also
/// providing a peek at the BOM if one exists. Peeking at the BOM does not
/// advance the reader.
struct BomPeeker<R> {
rdr: R,
bom: Option<Bom>,
nread: usize,
}
impl<R: io::Read> BomPeeker<R> {
/// Create a new BomPeeker.... | {
let bom = self.as_slice();
if bom.len() < 3 {
return None;
}
if let Some((enc, _)) = Encoding::for_bom(bom) {
if enc != UTF_8 {
return Some(enc.new_decoder_with_bom_removal());
}
}
None
} | identifier_body |
query.rs | use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;
use serde::de;
use serde::Deserializer;
/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implem... | self.0.insert_or_poison(key.into(), value.into())
}
Ok(self.0)
}
}
let visitor = Visitor(NormalizedParameter::default());
deserializer.deserialize_seq(visitor)
}
}
impl<K, V> FromIterator<(K, V)> for NormalizedParameter
where... | while let Some((key, value)) = access.next_element::<(String, String)>()? { | random_line_split |
query.rs | use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;
use serde::de;
use serde::Deserializer;
/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implem... |
}
/// Return a reference to value in a collection if it is the only one.
///
/// For example, a vector of string like types returns a reference to its first
/// element if there are no other, else it returns `None`.
///
/// If this were done with slices, that would require choosing a particular
/// value type of the ... | {
self.normalize()
} | identifier_body |
query.rs | use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;
use serde::de;
use serde::Deserializer;
/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implem... | else {
self.get(0).and_then(V::get_unique)
}
}
}
mod test {
use super::*;
/// Compilation tests for various possible QueryParameter impls.
#[allow(unused)]
#[allow(dead_code)]
fn test_query_parameter_impls() {
let _ = (&HashMap::<String, String>::new()) as &dyn Que... | {
None
} | conditional_block |
query.rs | use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::hash::{BuildHasher, Hash};
use std::rc::Rc;
use std::sync::Arc;
use serde::de;
use serde::Deserializer;
/// Allows access to the query parameters in an url or a body.
///
/// Use one of the listed implem... | (&self, key: &str) -> Option<Cow<str>> {
self.inner
.get(key)
.and_then(|val| val.as_ref().map(Cow::as_ref).map(Cow::Borrowed))
}
fn normalize(&self) -> NormalizedParameter {
self.clone()
}
}
impl NormalizedParameter {
/// Create an empty map.
pub fn new() -> ... | unique_value | identifier_name |
system.rs | use crate::simulation::agent_shader::ty::PushConstantData;
use crate::simulation::blur_fade_shader;
use crate::simulation::Simulation;
use imgui::{Context, Ui};
use imgui_vulkano_renderer::Renderer;
use imgui_winit_support::{HiDpiMode, WinitPlatform};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vulkano:... | sensor_radius: 1,
// In the range [0 - PI]
sensor_angle_spacing: 0.18,
// Seconds per frame. (60fps)
delta_time: 0.016667,
};
let mut fade_parameters: blur_fade_shader::ty::PushConstantData =
blur_fade_shader::ty::PushConstantData ... | random_line_split | |
system.rs | use crate::simulation::agent_shader::ty::PushConstantData;
use crate::simulation::blur_fade_shader;
use crate::simulation::Simulation;
use imgui::{Context, Ui};
use imgui_vulkano_renderer::Renderer;
use imgui_winit_support::{HiDpiMode, WinitPlatform};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vulkano:... | .build_vk_surface(&event_loop, instance.clone())
.unwrap();
let queue_family = physical
.queue_families()
.find(|&q|
q.supports_graphics() && q.explicitly_supports_transfers()
&& surface.is_supported(q).unwrap_or(false)
)
... | {
// Basic commands taken from the vulkano imgui examples:
// https://github.com/Tenebryo/imgui-vulkano-renderer/blob/master/examples/support/mod.rs
let instance = {
let extensions = vulkano_win::required_extensions();
Instance::new(None, &extensions, None).expect("Faile... | identifier_body |
system.rs | use crate::simulation::agent_shader::ty::PushConstantData;
use crate::simulation::blur_fade_shader;
use crate::simulation::Simulation;
use imgui::{Context, Ui};
use imgui_vulkano_renderer::Renderer;
use imgui_winit_support::{HiDpiMode, WinitPlatform};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vulkano:... | <
F: FnMut(
&mut bool,
&mut PushConstantData,
&mut blur_fade_shader::ty::PushConstantData,
&mut Ui,
) +'static,
>(
self,
simulation: Simulation,
mut run_ui: F,
) {
let System {
event_l... | main_loop | identifier_name |
peers_tests.rs | #[cfg(not(feature = "native"))] use common::call_back;
use common::executor::Timer;
use common::for_tests::wait_for_log_re;
use common::mm_ctx::{MmArc, MmCtxBuilder};
use common::privkey::key_pair_from_seed;
#[cfg(feature = "native")] use common::wio::{drive, CORE};
use common::{block_on, now_float, small_rng};
use crd... | let received = unwrap!(block_on(recv_f));
assert_eq!(received, message);
assert!(now_float() - start < 0.1); // Double-check that we're not waiting for DHT chunks.
block_on(destruction_check(alice));
block_on(destruction_check(bob));
}
/// Check the primitives used to communicate with the HTTP fal... | .direct_chunks
.load(Ordering::Relaxed)
> 0));
let start = now_float(); | random_line_split |
peers_tests.rs | #[cfg(not(feature = "native"))] use common::call_back;
use common::executor::Timer;
use common::for_tests::wait_for_log_re;
use common::mm_ctx::{MmArc, MmCtxBuilder};
use common::privkey::key_pair_from_seed;
#[cfg(feature = "native")] use common::wio::{drive, CORE};
use common::{block_on, now_float, small_rng};
use crd... | /// Using a minimal one second HTTP fallback which should happen before the DHT kicks in.
#[cfg(feature = "native")]
pub fn peers_http_fallback_recv() {
let ctx = MmCtxBuilder::new().into_mm_arc();
let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30204);
let server = unwrap!(super::http_fallback::ne... | use std::ptr::null;
common::executor::spawn(async move {
peers_dht().await;
unsafe { call_back(cb_id, null(), 0) }
})
}
| identifier_body |
peers_tests.rs | #[cfg(not(feature = "native"))] use common::call_back;
use common::executor::Timer;
use common::for_tests::wait_for_log_re;
use common::mm_ctx::{MmArc, MmCtxBuilder};
use common::privkey::key_pair_from_seed;
#[cfg(feature = "native")] use common::wio::{drive, CORE};
use common::{block_on, now_float, small_rng};
use crd... | // NB: Still need the DHT enabled in order for the pings to work.
let alice = block_on(peer(json! ({"dht": "on"}), 2121));
let bob = block_on(peer(json! ({"dht": "on"}), 2122));
let bob_id = unwrap!(bob.public_id());
// Bob isn't a friend yet.
let alice_pctx = unwrap!(super::PeersContext::from_... | return;
}
| conditional_block |
peers_tests.rs | #[cfg(not(feature = "native"))] use common::call_back;
use common::executor::Timer;
use common::for_tests::wait_for_log_re;
use common::mm_ctx::{MmArc, MmCtxBuilder};
use common::privkey::key_pair_from_seed;
#[cfg(feature = "native")] use common::wio::{drive, CORE};
use common::{block_on, now_float, small_rng};
use crd... | (mm: MmArc) {
mm.stop();
if let Err(err) = wait_for_log_re(&mm, 1., "delete_dugout finished!").await {
// NB: We want to know if/when the `peers` destruction doesn't happen, but we don't want to panic about it.
pintln!((err))
}
}
async fn peers_exchange(conf: Json) {
let fallback_on = c... | destruction_check | identifier_name |
lib.rs | OwnerProofSystem, Randomness, LockIdentifier, Filter},
weights::{
Weight, IdentityFee,
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
},
};
// A few exports that help ease life for downstream crates.
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
p... |
}
impl Convert<Balance, u64> for CurrencyToVoteHandler {
fn convert(x: Balance) -> u64 {
(x / Self::factor()) as u64
}
}
impl Convert<u128, Balance> for CurrencyToVoteHandler {
fn convert(x: u128) -> Balance {
x * Self::factor()
}
}
parameter_types! {
pub const SessionsPerEra: sp_staking::SessionIndex = 3;... | {
(Balances::total_issuance() / u64::max_value() as Balance).max(1)
} | identifier_body |
lib.rs | OwnerProofSystem, Randomness, LockIdentifier, Filter},
weights::{
Weight, IdentityFee,
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
},
};
// A few exports that help ease life for downstream crates.
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
p... | (x: Balance) -> u64 {
(x / Self::factor()) as u64
}
}
impl Convert<u128, Balance> for CurrencyToVoteHandler {
fn convert(x: u128) -> Balance {
x * Self::factor()
}
}
parameter_types! {
pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours
pub const BondingDuration: pallet_staking::EraIndex = 4; ... | convert | identifier_name |
lib.rs | ::{KeyOwnerProofSystem, Randomness, LockIdentifier, Filter},
weights::{
Weight, IdentityFee,
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
},
};
// A few exports that help ease life for downstream crates.
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStor... | type WeightInfo = ();
}
parameter_types! {
pub const TransactionByteFee: Balance = 1;
}
/// pallet_transaction_payment origin
impl pallet_transaction_payment::Trait for Runtime {
type Currency = Balances;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = IdentityFee<Balance>;
type OnTransactionPa... | type AccountStore = System; //
type Event = Event; | random_line_split |
event.rs | use crate::mappings::Mappings;
use crate::scheduler::TaskMessage;
use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS};
use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId};
use hashbrown::HashSet;
use lazy_static::lazy_static;
use legion::storage::ComponentType... |
let ptr: *mut E = self
.ctx
.bump
.get_or_default()
.alloc_layout(Layout::for_value(self.queued.as_slice()))
.cast::<E>()
.as_ptr();
self.queued
.drain(..)
.enumerate()
.for_each(|(index, event)| unsafe... | {
return; // Nothing to do
} | conditional_block |
event.rs | use crate::mappings::Mappings;
use crate::scheduler::TaskMessage;
use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS};
use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId};
use hashbrown::HashSet;
use lazy_static::lazy_static;
use legion::storage::ComponentType... | (&mut self, event: E) {
self.queued.push(event);
}
pub fn trigger_batched(&mut self, events: impl IntoIterator<Item = E>) {
self.queued.extend(events);
}
}
impl<'a, E> SystemDataOutput<'a> for &'a mut Trigger<E>
where
E: Send + Sync +'static,
{
type SystemData = Trigger<E>;
}
impl... | trigger | identifier_name |
event.rs | use crate::mappings::Mappings;
use crate::scheduler::TaskMessage;
use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS};
use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId};
use hashbrown::HashSet;
use lazy_static::lazy_static;
use legion::storage::ComponentType... | /// Returns the unique ID of this event handler, as allocated by `system_id_for::<T>()`.
fn id(&self) -> SystemId;
/// Returns the name of this event handler.
fn name(&self) -> &'static str;
/// Returns the ID of the event which is handled by this handler.
fn event_id(&self) -> EventId;
/... | pub unsafe trait RawEventHandler: Send + Sync + 'static { | random_line_split |
mod.rs | pub mod build;
pub mod config;
pub mod dev;
pub mod generate;
pub mod init;
pub mod kv;
pub mod login;
pub mod logout;
pub mod preview;
pub mod publish;
pub mod r2;
pub mod route;
pub mod secret;
pub mod subdomain;
pub mod tail;
pub mod whoami;
pub mod exec {
pub use super::build::build;
pub use super::config:... | {
/// Interact with your Workers KV Namespaces
#[structopt(name = "kv:namespace", setting = AppSettings::SubcommandRequiredElseHelp)]
KvNamespace(kv::KvNamespace),
/// Individually manage Workers KV key-value pairs
#[structopt(name = "kv:key", setting = AppSettings::SubcommandRequiredElseHelp)]
... | Command | identifier_name |
mod.rs | pub mod build;
pub mod config;
pub mod dev;
pub mod generate;
pub mod init;
pub mod kv;
pub mod login;
pub mod logout;
pub mod preview;
pub mod publish;
pub mod r2;
pub mod route;
pub mod secret;
pub mod subdomain;
pub mod tail;
pub mod whoami;
pub mod exec {
pub use super::build::build;
pub use super::config:... |
#[cfg(test)]
mod tests {
use super::*;
fn rename_class(tag: &str) -> RenameClass {
RenameClass {
from: format!("renameFrom{}", tag),
to: format!("renameTo{}", tag),
}
}
fn transfer_class(tag: &str) -> TransferClass {
TransferClass {
from: f... | {
match input {
"self" => Ok(String::from("self")),
address => match IpAddr::from_str(address) {
Ok(_) => Ok(address.to_owned()),
Err(err) => anyhow::bail!("{}: {}", err, input),
},
}
} | identifier_body |
mod.rs | pub mod build;
pub mod config;
pub mod dev;
pub mod generate;
pub mod init;
pub mod kv;
pub mod login;
pub mod logout;
pub mod preview;
pub mod publish;
pub mod r2;
pub mod route;
pub mod secret; | pub mod exec {
pub use super::build::build;
pub use super::config::configure;
pub use super::dev::dev;
pub use super::generate::generate;
pub use super::init::init;
pub use super::kv::kv_bulk;
pub use super::kv::kv_key;
pub use super::kv::kv_namespace;
pub use super::login::login;
... | pub mod subdomain;
pub mod tail;
pub mod whoami;
| random_line_split |
test.rs | // Utilities for creating test cases.
use core::marker::PhantomData;
use std::time::{Duration, Instant};
use std::vec::Vec;
use common::errors::*;
use crate::random::Rng;
/*
To verify no timing leaks:
- Run any many different input sizes.
- Verify compiler optimizations aren't making looping over many iterations to... | });
if length > 1 {
// Last byte set to value #1
out.push({
let mut v = vec![0u8; length];
*v.last_mut().unwrap() = 0x20;
v
});
// Last byte set to value #2
out.push({
let mut v = vec![0u8; length];
*v.last_mut(... | {
let mut out = vec![];
// All zeros.
out.push(vec![0u8; length]);
// All 0xFF.
out.push(vec![0xFFu8; length]);
// First byte set to value #1
out.push({
let mut v = vec![0u8; length];
v[0] = 0xAB;
v
});
// First byte set to value #2
out.push({
l... | identifier_body |
test.rs | // Utilities for creating test cases.
use core::marker::PhantomData;
use std::time::{Duration, Instant};
use std::vec::Vec;
use common::errors::*;
use crate::random::Rng;
/*
To verify no timing leaks:
- Run any many different input sizes.
- Verify compiler optimizations aren't making looping over many iterations to... | /// code being profiled.
///
/// NOTE: This can not track any work performed on other threads.
pub struct TimingLeakTest<R, Gen, Runner> {
test_case_generator: Gen,
test_case_runner: Runner,
options: TimingLeakTestOptions,
r: PhantomData<R>,
}
pub struct TimingLeakTestOptions {
/// Number of separa... | /// 2. A TimingLeakTestCaseRunner which takes a test case as input and runs the | random_line_split |
test.rs | // Utilities for creating test cases.
use core::marker::PhantomData;
use std::time::{Duration, Instant};
use std::vec::Vec;
use common::errors::*;
use crate::random::Rng;
/*
To verify no timing leaks:
- Run any many different input sizes.
- Verify compiler optimizations aren't making looping over many iterations to... | {
sum: u64,
n: usize,
}
| RollingMean | identifier_name |
tags.rs | use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::process::Command;
use std::collections::HashSet;
use std::path::{PathBuf, Path};
use app_result::{AppResult, app_err_msg, app_err_missing_src};
use types::{Tags, TagsKind, SourceKind};
use path_ext::PathExt;
use config::Config;
use dirs::{
rus... | (config: &Config,
source: &SourceKind,
dependencies: &Vec<SourceKind>)
-> AppResult<Tags> {
let lib_tags = try!(update_tags(config, source));
if lib_tags.is_up_to_date(&config.tags_k... | update_tags_and_check_for_reexports | identifier_name |
tags.rs | use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::process::Command;
use std::collections::HashSet;
use std::path::{PathBuf, Path};
use app_result::{AppResult, app_err_msg, app_err_missing_src};
use types::{Tags, TagsKind, SourceKind};
use path_ext::PathExt;
use config::Config;
use dirs::{
rus... |
#[derive(Eq, PartialEq, Hash)]
struct ExternCrate<'a>
{
name: &'a str,
as_name: &'a str
}
let mut extern_crates = HashSet::<ExternCrate>::new();
for line in lines {
let items = line.trim_matches(';').split(' ').collect::<Vec<&str>>();
if items.len() < 3 {
... | {
let mut lib_file = src_dir.to_path_buf();
lib_file.push("src");
lib_file.push("lib.rs");
if ! lib_file.is_file() {
return Ok(Vec::new());
}
let contents = {
let mut file = try!(File::open(&lib_file));
let mut contents = String::new();
try!(file.read_to_string(... | identifier_body |
tags.rs | use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::process::Command;
use std::collections::HashSet;
use std::path::{PathBuf, Path};
use app_result::{AppResult, app_err_msg, app_err_missing_src};
use types::{Tags, TagsKind, SourceKind};
use path_ext::PathExt;
use config::Config;
use dirs::{
rus... | merged_lines.sort();
merged_lines.dedup();
let mut tag_file = try!(
OpenOptions::new()
.create(true)
.truncate(true)
.read(true)
.write(true)
.open(into_tag_file)
);
t... | {
let mut file_contents: Vec<String> = Vec::new();
for file in tag_files.iter() {
let mut file = try!(File::open(file));
let mut contents = String::new();
try!(file.read_to_string(&mut contents));
file_contents.push(contents);
... | conditional_block |
tags.rs | use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::process::Command;
use std::collections::HashSet;
use std::path::{PathBuf, Path};
use app_result::{AppResult, app_err_msg, app_err_missing_src};
use types::{Tags, TagsKind, SourceKind};
use path_ext::PathExt;
use config::Config;
use dirs::{
rus... | let mut cmd = Command::new("git");
cmd.current_dir(git_dir)
.arg("rev-parse")
.arg("HEAD");
let out = try!(cmd.output());
String::from_utf8(out.stdout)
.map(|s| s.trim().to_string())
.map_err(|_| app_err_msg("Couldn't convert 'git rev-parse HEAD' output to utf8!".to_string()... |
/// get the commit hash of the current `HEAD` of the git repository located at `git_dir`
fn get_commit_hash(git_dir: &Path) -> AppResult<String> { | random_line_split |
cubicbez.rs | Mul, Range}; ////
////use std::ops::{Mul, Range};
use introsort; ////
use crate::MAX_EXTREMA;
use arrayvec::ArrayVec;
use crate::common::solve_quadratic;
use crate::common::GAUSS_LEGENDRE_COEFFS_9;
use crate::{
Affine, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv,
ParamCu... | // y = x^2
let c = CubicBez::new(
(0.0, 0.0),
(1.0 / 3.0, 0.0),
(2.0 / 3.0, 1.0 / 3.0),
(1.0, 1.0),
);
let true_arclen = 0.5 * libm::sqrt(5.0f64) + 0.25 * (2.0 + libm::sqrt(5.0f64)).ln();
for i in 0..12 {
let accuracy = 0.... | z_arclen() {
| identifier_name |
cubicbez.rs | ::{Mul, Range}; ////
////use std::ops::{Mul, Range};
use introsort; ////
use crate::MAX_EXTREMA;
use arrayvec::ArrayVec;
use crate::common::solve_quadratic;
use crate::common::GAUSS_LEGENDRE_COEFFS_9;
use crate::{
Affine, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv,
Para... | let p0 = self.eval(t0);
let p3 = self.eval(t1);
let d = self.deriv();
let scale = (t1 - t0) * (1.0 / 3.0);
let p1 = p0 + scale * d.eval(t0).to_vec2();
let p2 = p3 - scale * d.eval(t1).to_vec2();
CubicBez { p0, p1, p2, p3 }
}
/// Subdivide into halves, usi... |
fn subsegment(&self, range: Range<f64>) -> CubicBez {
let (t0, t1) = (range.start, range.end); | random_line_split |
cubicbez.rs | Mul, Range}; ////
////use std::ops::{Mul, Range};
use introsort; ////
use crate::MAX_EXTREMA;
use arrayvec::ArrayVec;
use crate::common::solve_quadratic;
use crate::common::GAUSS_LEGENDRE_COEFFS_9;
use crate::{
Affine, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv,
ParamCu... |
0.999_999 * libm::pow(self.max_hypot2 / err, 1. / 6.0) ////
////0.999_999 * (self.max_hypot2 / err).powf(1. / 6.0)
};
t1 = t0 + shrink * (t1 - t0);
}
}
}
}
#[cfg(test)]
mod tests {
use crate::{
Affine, CubicBez... | 0.5
} else { | conditional_block |
cubicbez.rs | Mul, Range}; ////
////use std::ops::{Mul, Range};
use introsort; ////
use crate::MAX_EXTREMA;
use arrayvec::ArrayVec;
use crate::common::solve_quadratic;
use crate::common::GAUSS_LEGENDRE_COEFFS_9;
use crate::{
Affine, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv,
ParamCu... | l ParamCurveNearest for CubicBez {
/// Find nearest point, using subdivision.
fn nearest(&self, p: Point, accuracy: f64) -> (f64, f64) {
let mut best_r = None;
let mut best_t = 0.0;
for (t0, t1, q) in self.to_quads(accuracy) {
let (t, r) = q.nearest(p, accuracy);
... | (self.p0.x * (6.0 * self.p1.y + 3.0 * self.p2.y + self.p3.y)
+ 3.0
* (self.p1.x * (-2.0 * self.p0.y + self.p2.y + self.p3.y)
- self.p2.x * (self.p0.y + self.p1.y - 2.0 * self.p3.y))
- self.p3.x * (self.p0.y + 3.0 * self.p1.y + 6.0 * self.p2.y))
... | identifier_body |
controller.rs | mod cli;
mod collect;
mod detector;
mod init;
mod reconcile_queue;
mod reconciler;
mod supervisor;
mod validate_api_server;
pub use self::{
collect::Collect,
reconciler::{ReconcileContext, ReconcileStatus},
};
use self::collect::ControllerDescriptionCollector;
use crate::controller::reconcile_queue::QueueConf... |
};
tokio::time::sleep(Duration::from_secs(sleep_timeout)).await;
}
}
};
tokio::task::spawn(version_skew_check_fut);
//tracing::info!("Discovering cluster APIs");
//let discovery = Arc::new(Discovery::new(&client).aw... | {
tracing::warn!("Failed to validate api server version: {:#}", e);
10
} | conditional_block |
controller.rs | mod cli;
mod collect;
mod detector;
mod init;
mod reconcile_queue;
mod reconciler;
mod supervisor;
mod validate_api_server;
pub use self::{
collect::Collect,
reconciler::{ReconcileContext, ReconcileStatus},
};
use self::collect::ControllerDescriptionCollector;
use crate::controller::reconcile_queue::QueueConf... | (&self) {
if let Some(crd) = self.meta.crd.as_ref() {
let res = (self.vtable.api_resource)();
assert_eq!(crd.spec.names.plural, res.plural);
assert_eq!(crd.spec.names.kind, res.kind);
assert_eq!(crd.spec.group, res.group);
let has_version = crd.spec.ve... | validate | identifier_name |
controller.rs | mod cli;
mod collect;
mod detector;
mod init;
mod reconcile_queue;
mod reconciler;
mod supervisor;
mod validate_api_server;
pub use self::{
collect::Collect,
reconciler::{ReconcileContext, ReconcileStatus},
};
use self::collect::ControllerDescriptionCollector;
use crate::controller::reconcile_queue::QueueConf... | }
Ok(())
}
}
/// Description of a controller
#[derive(Clone)]
struct ControllerDescription {
name: String,
crd: Option<CustomResourceDefinition>,
watches: Vec<ApiResource>,
}
#[derive(Clone)]
pub(crate) struct DynController {
meta: ControllerDescription,
vtable: ControllerVtabl... | random_line_split | |
flex.rs | // Copyright 2020 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &AppState,
env: &Env,
) -> Size {
self.inner.layout(ctx, bc, data, env)
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) {
self.inner.paint(ctx, dat... | {
self.inner.update(ctx, old_data, data, env);
} | conditional_block |
flex.rs | // Copyright 2020 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | (
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &AppState,
env: &Env,
) -> Size {
self.inner.layout(ctx, bc, data, env)
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) {
self.inner.paint(ctx, data, env)
}
fn... | layout | identifier_name |
flex.rs | // Copyright 2020 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | const MAIN_AXIS_ALIGNMENT_OPTIONS: [(&str, MainAxisAlignment); 6] = [
("Start", MainAxisAlignment::Start),
("Center", MainAxisAlignment::Center),
("End", MainAxisAlignment::End),
("Between", MainAxisAlignment::SpaceBetween),
("Evenly", MainAxisAlignment::SpaceEvenly),
("Around", MainAxisAlignmen... | ("Fixed:", Spacers::Fixed),
]; | random_line_split |
web.rs | use std::path::PathBuf;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::prelude::*;
use std::ffi::OsStr;
use std::sync::Arc;
use std::time::{Duration as SDuration, Instant};
use crate::utils::{print_error_and_causes, FutureExt as _, ResultExt as ResultExt2};
u... |
use crate::Shared;
use crate::DataLogEntry;
use crate::TSDataLogEntry;
use file_db::{create_intervall_filtermap, TimestampedMethods};
use hyper::StatusCode;
use hyper::server::{Http, NewService, Request, Response, Server, Service};
use hyper::header;
use futures::future::{FutureExt as _, TryFutureExt}; // for conver... | random_line_split | |
web.rs |
use std::path::PathBuf;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::prelude::*;
use std::ffi::OsStr;
use std::sync::Arc;
use std::time::{Duration as SDuration, Instant};
use crate::utils::{print_error_and_causes, FutureExt as _, ResultExt as ResultExt2};
... | <F>(result: F) -> HandlerResult
where
F: Future<Item = Response, Error = Error> + Sized +'static,
{
Box::new(result.then(|result| {
let f = match result {
Ok(response) => response,
Err(err) => {
use std::fmt::Write;
let mut buf = String::with_capac... | box_and_convert_error | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.