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
nvg.rs
//! NanoVG is small antialiased vector graphics rendering library with a lean //! API modeled after the HTML5 Canvas API. It can be used to draw gauge //! instruments in MSFS. See `Gauge::create_nanovg`. use crate::sys; type Result = std::result::Result<(), Box<dyn std::error::Error>>; /// A NanoVG render context. p...
pub fn stroke<T: Into<PaintOrColor>>(mut self, stroke: T) -> Self { self.stroke = Some(stroke.into()); self } /// Set the fill of this style. pub fn fill<T: Into<PaintOrColor>>(mut self, fill: T) -> Self { self.fill = Some(fill.into()); self } } /// Colors in NanoVG...
} impl Style { /// Set the stroke of this style.
random_line_split
actix.rs
. // See the License for the specific language governing permissions and // limitations under the License. //! Actix-web API backend. //! //! [Actix-web](https://github.com/actix/actix-web) is an asynchronous backend //! for HTTP API, based on the [Actix](https://github.com/actix/actix) framework. pub use actix_web::...
} } } /// Creates `actix_web::App` for the given aggregator and runtime configuration. pub(crate) fn create_app(aggregator: &ApiAggregator, runtime_config: ApiRuntimeConfig) -> App { let app_config = runtime_config.app_config; let access = runtime_config.access; let mut app = App::new(); a...
{ let handler = f.inner.handler; let actuality = f.inner.actuality; let mutability = f.mutability; let index = move |request: HttpRequest| -> FutureResponse { let handler = handler.clone(); let actuality = actuality.clone(); extract_query(request, muta...
identifier_body
actix.rs
. // See the License for the specific language governing permissions and // limitations under the License. //! Actix-web API backend. //! //! [Actix-web](https://github.com/actix/actix-web) is an asynchronous backend //! for HTTP API, based on the [Actix](https://github.com/actix/actix) framework. pub use actix_web::...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SystemRuntime").finish() } } /// CORS header specification. #[derive(Debug, Clone, PartialEq, Eq)] pub enum AllowOrigin { /// Allows access from any host. Any, /// Allows access only from the specified hosts. Whitelist(Vec...
fmt
identifier_name
actix.rs
implied. // See the License for the specific language governing permissions and // limitations under the License. //! Actix-web API backend. //! //! [Actix-web](https://github.com/actix/actix-web) is an asynchronous backend //! for HTTP API, based on the [Actix](https://github.com/actix/actix) framework. pub use act...
"*" => Ok(AllowOrigin::Any), _ => Ok(AllowOrigin::Whitelist(vec![value.to_string()])), } } fn visit_seq<A>(self, seq: A) -> result::Result<AllowOrigin, A::Error> where A: de::SeqAccess<'de>, { ...
match value {
random_line_split
mock.rs
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Creating mock Runtime here use crate::{AssetConfig, Config, NetworkConfig}; use codec::{Codec, Decode, Encode}; use common::mock::ExistentialDeposits; use common::prelude::Balance; use common::{ Amount, AssetId32, AssetName, AssetSymb...
else { Extra::pre_dispatch_unsigned(&self.call, info, len)?; None }; Ok(self.call.dispatch(maybe_who.into())) } } impl<Call, Extra> Serialize for MyTestXt<Call, Extra> where MyTestXt<Call, Extra>: Encode, { fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> ...
{ Extra::pre_dispatch(extra, &who, &self.call, info, len)?; Some(who) }
conditional_block
mock.rs
THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Creating mock Runtime here use crate::{AssetConfig, Config, NetworkConfig}; use codec::{Codec, Decode, Encode}; use common::mock::ExistentialDeposits; use common::prelude::Balance; use common::{ Amount, AssetId32, AssetName, Asset...
impl sp_runtime::traits::ExtrinsicMetadata for TestExtrinsic { const VERSION: u8 = 1; type SignedExtensions = (); } construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system::{Module, Call,...
type GetEthNetworkId = EthNetworkId; type WeightInfo = (); }
random_line_split
mock.rs
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Creating mock Runtime here use crate::{AssetConfig, Config, NetworkConfig}; use codec::{Codec, Decode, Encode}; use common::mock::ExistentialDeposits; use common::prelude::Balance; use common::{ Amount, AssetId32, AssetName, AssetSymb...
; pub type TestExtrinsic = MyTestXt<Call, MyExtra>; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); pub const ExistentialDeposit: u1...
MyExtra
identifier_name
mock.rs
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Creating mock Runtime here use crate::{AssetConfig, Config, NetworkConfig}; use codec::{Codec, Decode, Encode}; use common::mock::ExistentialDeposits; use common::prelude::Balance; use common::{ Amount, AssetId32, AssetName, AssetSymb...
); self.last_network_id += 1; net_id } pub fn build(self) -> (TestExternalities, State) { let (offchain, offchain_state) = TestOffchainExt::new(); let (pool, pool_state) = TestTransactionPoolExt::new(); let authority_account_id = bridge_multisig::Mod...
{ let net_id = self.last_network_id; let multisig_account_id = bridge_multisig::Module::<Runtime>::multi_account_id( &self.root_account_id, 1, net_id as u64 + 10, ); let peers_keys = gen_peers_keys(&format!("OCW{}", net_id), peers_num.unwrap_or(4)); ...
identifier_body
js_lua_state.rs
use std::sync::Arc; use std::{fs, thread}; use crate::js_traits::{FromJs, ToJs}; use crate::lua_execution; use crate::value::Value; use mlua::{Lua, StdLib}; use neon::context::Context; use neon::handle::Handle; use neon::prelude::*; use neon::declare_types; fn lua_version() -> &'static str { if cfg!(feature = "...
} fn flag_into_std_lib(flag: u32) -> Option<StdLib> { const ALL_SAFE: u32 = u32::MAX - 1; match flag { #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))] 0x1 => Some(StdLib::COROUTINE), 0x2 => Some(StdLib::TABLE), 0x4 => Some(StdLib::IO), 0x8 => Some(S...
{ LuaState { libraries: StdLib::ALL_SAFE, lua: Arc::new(Lua::new_with(StdLib::ALL_SAFE).unwrap()), } }
identifier_body
js_lua_state.rs
use std::sync::Arc; use std::{fs, thread}; use crate::js_traits::{FromJs, ToJs}; use crate::lua_execution; use crate::value::Value; use mlua::{Lua, StdLib}; use neon::context::Context; use neon::handle::Handle; use neon::prelude::*; use neon::declare_types; fn lua_version() -> &'static str { if cfg!(feature = "...
let libraries = build_libraries_option(cx, libs)?; // Because we're allowing the end user to dynamically choose their libraries, // we're using the unsafe call in case they include `debug`. We need to notify // the end user in the documentation about the caveats of `debug`. let lua = unsafe { ...
let libs = options.get(&mut cx, libraries_key)?;
random_line_split
js_lua_state.rs
use std::sync::Arc; use std::{fs, thread}; use crate::js_traits::{FromJs, ToJs}; use crate::lua_execution; use crate::value::Value; use mlua::{Lua, StdLib}; use neon::context::Context; use neon::handle::Handle; use neon::prelude::*; use neon::declare_types; fn lua_version() -> &'static str { if cfg!(feature = "...
( mut cx: MethodContext<JsLuaState>, code: String, name: Option<String>, ) -> JsResult<JsValue> { let this = cx.this(); let lua: &Lua = { let guard = cx.lock(); let state = this.borrow(&guard); &state.lua.clone() }; match lua_execution::do_string_sync(lua, code, name...
do_string_sync
identifier_name
main.rs
use std::{fs, net::ToSocketAddrs, path::PathBuf, sync::Arc}; use structopt::StructOpt; use url::Url; use tracing::{Level, info}; use bevy::{ input::{ keyboard::ElementState as PressState, mouse::{MouseButtonInput, MouseScrollUnit, MouseWheel}, }, prelude::*, render::mesh::{Mesh, VertexAt...
#[tokio::main] async fn run(options: Opt) -> Result<(), Box<dyn std::error::Error>> { let path = std::env::current_dir().unwrap(); println!("The current directory is {}", path.display()); tracing::subscriber::set_global_default( tracing_subscriber::FmtSubscriber::builder() .with_max_le...
{ let opt = Opt::from_args(); run(opt) }
identifier_body
main.rs
use std::{fs, net::ToSocketAddrs, path::PathBuf, sync::Arc}; use structopt::StructOpt; use url::Url; use tracing::{Level, info}; use bevy::{ input::{ keyboard::ElementState as PressState, mouse::{MouseButtonInput, MouseScrollUnit, MouseWheel}, }, prelude::*, render::mesh::{Mesh, VertexAt...
( mut state: ResMut<RequestTileOnConnectedState>, mut sender: ResMut<Events<SendEvent>>, receiver: ResMut<Events<ReceiveEvent>> ) { for evt in state.event_reader.iter(&receiver) { if let ReceiveEvent::Connected(connection, _) = evt { info!("Requesting tile because connected to server...
request_tile_on_connected
identifier_name
main.rs
use std::{fs, net::ToSocketAddrs, path::PathBuf, sync::Arc}; use structopt::StructOpt; use url::Url; use tracing::{Level, info}; use bevy::{ input::{ keyboard::ElementState as PressState, mouse::{MouseButtonInput, MouseScrollUnit, MouseWheel}, }, prelude::*, render::mesh::{Mesh, VertexAt...
mcam.right = None; mcam.forward = None; } } } /// Pushes camera actions based upon scroll wheel movement. fn act_on_scroll_wheel( mouse_wheel: Res<Events<MouseWheel>>, mut acts: ResMut<Events<CameraBPAction>>, ) { for mw in mouse_wheel.get_reader().iter(&mouse_wheel) { ...
if !in_rect && ax.is_finite() && ay.is_finite() { mcam.right = Some(ax); mcam.forward = Some(ay); } else {
random_line_split
main.rs
use std::{fs, net::ToSocketAddrs, path::PathBuf, sync::Arc}; use structopt::StructOpt; use url::Url; use tracing::{Level, info}; use bevy::{ input::{ keyboard::ElementState as PressState, mouse::{MouseButtonInput, MouseScrollUnit, MouseWheel}, }, prelude::*, render::mesh::{Mesh, VertexAt...
if let Some(w) = mcam.forward { acts.send(CameraBPAction::MoveForward(Some(w))) } } fn play_every_sound_on_mb1( mev: Res<Events<MouseButtonInput>>, fxs: Res<Assets<AudioSource>>, output: Res<AudioOutput>, ) { for mev in mev.get_reader().iter(&mev) { if mev.button == MouseButto...
{ acts.send(CameraBPAction::MoveRight(Some(w))) }
conditional_block
mod.rs
mod searcher; use self::searcher::{SearchEngine, SearchWorker}; use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages}; use crate::stdio_server::handler::CachedPreviewImpl; use crate::stdio_server::job; use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context}; use cr...
.get_preview() .await?; let current_input = ctx.vim.input_get().await?; let current_lnum = ctx.vim.display_getcurlnum().await?; // Only send back the result if the request is not out-dated. if input == current_input && lnum == current_lnum { ctx...
rent_lines = self .current_usages .as_ref() .unwrap_or(&self.cached_results.usages); if current_lines.is_empty() { return Ok(()); } let input = ctx.vim.input_get().await?; let lnum = ctx.vim.display_getcurlnum().await?; // lnum i...
identifier_body
mod.rs
mod searcher; use self::searcher::{SearchEngine, SearchWorker}; use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages}; use crate::stdio_server::handler::CachedPreviewImpl; use crate::stdio_server::job; use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context}; use cr...
// otherwise restore the fuzzy query as the keyword we are going to search. let (keyword, query_type, usage_matcher) = if fuzzy_terms.is_empty() { if exact_terms.is_empty() { (query.into(), QueryType::StartWith, UsageMatcher::default()) } else { ( exact_te...
random_line_split
mod.rs
mod searcher; use self::searcher::{SearchEngine, SearchWorker}; use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages}; use crate::stdio_server::handler::CachedPreviewImpl; use crate::stdio_server::job; use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context}; use cr...
else { ( exact_terms[0].text.clone(), QueryType::Exact, UsageMatcher::new(exact_terms, inverse_terms), ) } } else { ( fuzzy_terms.iter().map(|term| &term.text).join(" "), QueryType::StartWith, ...
{ (query.into(), QueryType::StartWith, UsageMatcher::default()) }
conditional_block
mod.rs
mod searcher; use self::searcher::{SearchEngine, SearchWorker}; use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages}; use crate::stdio_server::handler::CachedPreviewImpl; use crate::stdio_server::job; use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context}; use cr...
&mut Context) -> Result<()> { let current_lines = self .current_usages .as_ref() .unwrap_or(&self.cached_results.usages); if current_lines.is_empty() { return Ok(()); } let input = ctx.vim.input_get().await?; let lnum = ctx.vim.displ...
, ctx:
identifier_name
command_server.rs
//! Internal server that accepts raw commands, queues them up, and transmits //! them to the Tick Processor asynchronously. Commands are re-transmitted //! if a response isn't received in a timout period. //! //! Responses from the Tick Processor are sent back over the commands channel //! and are sent to worker proce...
( &mut self, command: Command, commands_channel: String ) -> Receiver<Result<Response, String>> { let temp_lock_res = self.conn_queue.lock().unwrap().is_empty(); // Force the guard locking conn_queue to go out of scope // this prevents the lock from being held through the entire if/e...
execute
identifier_name
command_server.rs
//! Internal server that accepts raw commands, queues them up, and transmits //! them to the Tick Processor asynchronously. Commands are re-transmitted //! if a response isn't received in a timout period. //! //! Responses from the Tick Processor are sent back over the commands channel //! and are sent to worker proce...
for task in cmd_rx.wait() { let res = dispatch_worker( task.unwrap(), al, &mut client, &mut sleeper_tx, command_queue.clone() ); // exit if we're in the process of collapse if res.is_none() { break; } } } impl CommandServer { pub fn new(insta...
random_line_split
command_server.rs
//! Internal server that accepts raw commands, queues them up, and transmits //! them to the Tick Processor asynchronously. Commands are re-transmitted //! if a response isn't received in a timout period. //! //! Responses from the Tick Processor are sent back over the commands channel //! and are sent to worker proce...
} Ok(sleeper_tx) }).wait().ok().unwrap(); // block until a response is received or the command times out } /// Manually loop over the converted Stream of commands fn dispatch_worker( work: WorkerTask, al: &Mutex<AlertList>, mut client: &mut redis::Client, mut sleeper_tx: &mut UnboundedSend...
{ // timed out { al.lock().expect("Couldn't lock al in Err(_)") .deregister(&wr_cmd.uuid); } attempts += 1; if attempts >= CONF.cs_max_retries { // Let the main thread know it's safe to use th...
conditional_block
lib.rs
//! Securely zero memory with a simple trait ([Zeroize]) built on stable Rust //! primitives which guarantee the operation will not be 'optimized away'. //! //! ## Usage //! //! ``` //! use zeroize::Zeroize; //! //! fn main() { //! // Protip: don't embed secrets in your source code. //! // This is just an examp...
//! 2. Ensure all subsequent reads to the memory following the zeroing operation //! will always see zeroes. //! //! This crate guarantees #1 is true: LLVM's volatile semantics ensure it. //! //! The story around #2 is much more complicated. In brief, it should be true that //! LLVM's current implementation does not...
//! ## What guarantees does this crate provide? //! //! Ideally a secure memory-zeroing function would guarantee the following: //! //! 1. Ensure the zeroing operation can't be "optimized away" by the compiler.
random_line_split
lib.rs
//! Securely zero memory with a simple trait ([Zeroize]) built on stable Rust //! primitives which guarantee the operation will not be 'optimized away'. //! //! ## Usage //! //! ``` //! use zeroize::Zeroize; //! //! fn main() { //! // Protip: don't embed secrets in your source code. //! // This is just an examp...
() { atomic::fence(atomic::Ordering::SeqCst); atomic::compiler_fence(atomic::Ordering::SeqCst); } /// Set a mutable reference to a value to the given replacement #[inline] fn volatile_set<T: Copy + Sized>(dst: &mut T, src: T) { unsafe { ptr::write_volatile(dst, src) } } #[cfg(feature = "nightly")] #[inlin...
atomic_fence
identifier_name
lib.rs
//! Securely zero memory with a simple trait ([Zeroize]) built on stable Rust //! primitives which guarantee the operation will not be 'optimized away'. //! //! ## Usage //! //! ``` //! use zeroize::Zeroize; //! //! fn main() { //! // Protip: don't embed secrets in your source code. //! // This is just an examp...
/// Set a mutable reference to a value to the given replacement #[inline] fn volatile_set<T: Copy + Sized>(dst: &mut T, src: T) { unsafe { ptr::write_volatile(dst, src) } } #[cfg(feature = "nightly")] #[inline] fn volatile_zero_bytes(dst: &mut [u8]) { unsafe { core::intrinsics::volatile_set_memory(dst.as_mut...
{ atomic::fence(atomic::Ordering::SeqCst); atomic::compiler_fence(atomic::Ordering::SeqCst); }
identifier_body
fakes.rs
// Copyright 2021 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. #![cfg(test)] use { crate::{ client::{bss_selection::SignalData, scan, types as client_types}, config_management::{ Credent...
pub fn get_recorded_connect_reslts(&self) -> Vec<ConnectResultRecord> { self.connect_results_recorded .try_lock() .expect("expect locking self.connect_results_recorded to succeed") .clone() } /// Manually change the hidden network probabiltiy of a saved network. ...
{ self.connections_recorded .try_lock() .expect("expect locking self.connections_recorded to succeed") .clone() }
identifier_body
fakes.rs
// Copyright 2021 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. #![cfg(test)] use { crate::{ client::{bss_selection::SignalData, scan, types as client_types}, config_management::{ Credent...
#[derive(Clone)] pub struct FakeScanRequester { // A type alias for this complex type would be needless indirection, so allow the complex type #[allow(clippy::type_complexity)] pub scan_results: Arc<Mutex<VecDeque<Result<Vec<client_types::ScanResult>, client_types::ScanError>>>>, #[allow(clippy:...
rng.gen::<u8>().into(), ) }
random_line_split
fakes.rs
// Copyright 2021 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. #![cfg(test)] use { crate::{ client::{bss_selection::SignalData, scan, types as client_types}, config_management::{ Credent...
() -> (mpsc::Sender<String>, mpsc::Receiver<String>) { const DEFAULT_BUFFER_SIZE: usize = 100; // arbitrary value mpsc::channel(DEFAULT_BUFFER_SIZE) } /// Create past connection data with all random values. Tests can set the values they care about. pub fn random_connection_data() -> PastConnectionData { le...
create_inspect_persistence_channel
identifier_name
fakes.rs
// Copyright 2021 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. #![cfg(test)] use { crate::{ client::{bss_selection::SignalData, scan, types as client_types}, config_management::{ Credent...
else { None }, ) .flatten() .collect() } } } /// Note that the configs-per-NetworkIdentifier limit is set to 1 in /// this mock struct. If a NetworkIdentifier is already stored, writing /// a config to it will evict the prev...
{ Some(config.clone()) }
conditional_block
render_global.rs
use std::error; use std::rc::Rc; use std::cell::RefCell; use std::ops::Deref; use std::sync::Mutex; use gl_bindings::gl; use cgmath::{Matrix4, SquareMatrix, vec3, Point3, Rad}; use crate::demo; use crate::utils::lazy_option::Lazy; use crate::render::{Framebuffer, FramebufferAttachment, AttachmentPoint, ImageFormat, Ren...
// let mut program = RefCell::borrow_mut(&program); // program.delete(); // } // if let Some(program) = self.program_post_resolve.take() { // let mut program = RefCell::borrow_mut(&program); // program.delete(); // } // Reload shader from assets // // Load shaders // self.program_ehaa_scene = So...
// if let Some(program) = self.program_ehaa_scene.take() {
random_line_split
render_global.rs
use std::error; use std::rc::Rc; use std::cell::RefCell; use std::ops::Deref; use std::sync::Mutex; use gl_bindings::gl; use cgmath::{Matrix4, SquareMatrix, vec3, Point3, Rad}; use crate::demo; use crate::utils::lazy_option::Lazy; use crate::render::{Framebuffer, FramebufferAttachment, AttachmentPoint, ImageFormat, Ren...
else { // Create fbo self.framebuffer_scene_hdr_ehaa = Some(Rc::new(RefCell::new({ let mut fbo = Framebuffer::new(event.resolution.0, event.resolution.1); fbo.add_attachment(FramebufferAttachment::from_new_texture(AttachmentPoint::Depth, ImageFormat::get(gl::DEPTH_COMPONENT32F))); fbo.add_atta...
{ let mut fbo = RefCell::borrow_mut(t); fbo.resize(event.resolution.0, event.resolution.1); }
conditional_block
render_global.rs
use std::error; use std::rc::Rc; use std::cell::RefCell; use std::ops::Deref; use std::sync::Mutex; use gl_bindings::gl; use cgmath::{Matrix4, SquareMatrix, vec3, Point3, Rad}; use crate::demo; use crate::utils::lazy_option::Lazy; use crate::render::{Framebuffer, FramebufferAttachment, AttachmentPoint, ImageFormat, Ren...
(&mut self) { // let asset_folder = demo::demo_instance().asset_folder.as_mut().unwrap(); // Log println!("Reloading shaders!"); // Reload shaders from asset self.program_ehaa_scene.reload_from_asset().expect("Failed to reload scene shader from asset"); self.program_post_composite.reload_from_asset().e...
reload_shaders
identifier_name
hslcolor.rs
//! This file implements what I refer to as HSL but which would precisely be called sHSL: a simple //! transformation of sRGB that creates a cylindrical space. HSL has the same problems with //! perceptual uniformity and general unsuitability for exact psychophysically-accurate //! representation as color as sRGB does,...
#[test] fn test_hsl_rgb_conversion() { let red_rgb = RGBColor { r: 1., g: 0., b: 0., }; let red_hsl: HSLColor = red_rgb.convert(); assert!(red_hsl.h.abs() <= 0.0001); assert!((red_hsl.s - 1.0) <= 0.0001); assert!((red_hsl.l - 0...
random_line_split
hslcolor.rs
//! This file implements what I refer to as HSL but which would precisely be called sHSL: a simple //! transformation of sRGB that creates a cylindrical space. HSL has the same problems with //! perceptual uniformity and general unsuitability for exact psychophysically-accurate //! representation as color as sRGB does,...
} impl From<HSLColor> for Coord { fn from(val: HSLColor) -> Self { Coord { x: val.h, y: val.s, z: val.l, } } } impl Bound for HSLColor { fn bounds() -> [(f64, f64); 3] { [(0., 360.), (0., 1.), (0., 1.)] } } impl FromStr for HSLColor { t...
{ HSLColor { h: c.x, s: c.y, l: c.z, } }
identifier_body
hslcolor.rs
//! This file implements what I refer to as HSL but which would precisely be called sHSL: a simple //! transformation of sRGB that creates a cylindrical space. HSL has the same problems with //! perceptual uniformity and general unsuitability for exact psychophysically-accurate //! representation as color as sRGB does,...
else if self.h <= 180.0 { (0.0, chroma, x) } else if self.h <= 240.0 { (0.0, x, chroma) } else if self.h <= 300.0 { (x, 0.0, chroma) } else { (chroma, 0.0, x) }; // now we add the right value to each component to get the correct li...
{ (x, chroma, 0.0) }
conditional_block
hslcolor.rs
//! This file implements what I refer to as HSL but which would precisely be called sHSL: a simple //! transformation of sRGB that creates a cylindrical space. HSL has the same problems with //! perceptual uniformity and general unsuitability for exact psychophysically-accurate //! representation as color as sRGB does,...
() { let red_rgb = RGBColor { r: 1., g: 0., b: 0., }; let red_hsl: HSLColor = red_rgb.convert(); assert!(red_hsl.h.abs() <= 0.0001); assert!((red_hsl.s - 1.0) <= 0.0001); assert!((red_hsl.l - 0.5) <= 0.0001); assert!(red_hsl.dis...
test_hsl_rgb_conversion
identifier_name
channel_layout.rs
use std::{array, ffi::CString, fmt, mem, ptr, slice}; use crate::{ ffi::{AVChannel, AVChannelOrder, *}, Error, }; // new channel layout since 5.1 #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(i32)] pub enum Channel { None = AVChannel::AV_CHAN_NONE.0, FrontLeft = AVChannel::AV_CHAN_FRONT_LEFT.0, FrontRight...
{ order: u32, mask: Option<u64>, map: Option<Vec<CustomChannel>>, } #[derive(Deserialize)] #[serde(untagged, crate = "serde_")] enum VersionedLayout { Old(OldLayout), New(NewLayout), } let (order, u, nb_channels); match VersionedLayout::deserialize(deserializer)? { Vers...
NewLayout
identifier_name
channel_layout.rs
use std::{array, ffi::CString, fmt, mem, ptr, slice}; use crate::{ ffi::{AVChannel, AVChannelOrder, *}, Error, }; // new channel layout since 5.1 #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(i32)] pub enum Channel { None = AVChannel::AV_CHAN_NONE.0, FrontLeft = AVChannel::AV_CHAN_FRONT_LEFT.0, FrontRight...
#[test] fn old_format() { let x: ChannelLayout = serde_json::from_str(r#"{ "bits": 31 }"#).unwrap(); assert_eq!(x.0.order, AVChannelOrder::AV_CHANNEL_ORDER_NATIVE); assert_eq!(x.0.nb_channels, 5); assert_eq!(unsafe { x.0.u.mask }, 31); } } }
{ round_trip_debug(ChannelLayout::native(&[Channel::StereoRight, Channel::LowFrequency])); round_trip_debug(ChannelLayout::custom(&[ CustomChannel::new(Channel::LowFrequency, Some("low-freq")), CustomChannel::new(Channel::BackCenter, None), ])); }
identifier_body
channel_layout.rs
use std::{array, ffi::CString, fmt, mem, ptr, slice}; use crate::{ ffi::{AVChannel, AVChannelOrder, *}, Error, }; // new channel layout since 5.1 #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(i32)] pub enum Channel { None = AVChannel::AV_CHAN_NONE.0, FrontLeft = AVChannel::AV_CHAN_FRONT_LEFT.0, FrontRight...
} d.field("opaque", &self.0.opaque); d.finish() } } impl PartialEq for ChannelLayout { fn eq(&self, other: &ChannelLayout) -> bool { unsafe { let ord = av_channel_layout_compare(self.as_ptr(), other.as_ptr()); match ord { // negative return values for invalid layouts ..=-1 => false, 0 =>...
}
random_line_split
main.rs
log::warn!("{}", log_line); } } }); } })) }; #[cfg(unix)] for socketpath in &ARGS.sockets { let arc = mimetypes.clone(); ...
// correct host if let Some(domain) = url.domain() { // because the gemini scheme is not special enough for WHATWG, normalize // it ourselves let host = Host::parse( &percent_decode_str(domain) .decode_utf8() .or(...
// no userinfo and no fragment if url.password().is_some() || !url.username().is_empty() || url.fragment().is_some() { return Err((BAD_REQUEST, "URL contains fragment or userinfo")); }
random_line_split
main.rs
else { // already listening on the other unspecified address log::warn!("Could not start listener on {}, but already listening on another unspecified address. Probably your system automatically listens in dual stack?", addr); continue;...
{ panic!("Failed to listen on {addr}: {e}") }
conditional_block
main.rs
log::warn!("{}", log_line); } } }); } })) }; #[cfg(unix)] for socketpath in &ARGS.sockets { let arc = mimetypes.clone(); ...
<T> { stream: TlsStream<T>, local_port_check: Option<u16>, log_line: String, metadata: Arc<Mutex<FileOptions>>, } impl RequestHandle<TcpStream> { /// Creates a new request handle for the given stream. If establishing the TLS /// session fails, returns a corresponding log line. async fn new(...
RequestHandle
identifier_name
certificate_manager.rs
// Copyright (c) Microsoft. All rights reserved. use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; use futures::future::Either; #[cfg(unix)] use openssl::pkcs12::Pkcs12; #[cfg(unix)] use openssl::pkey::PKey; #[cfg(unix)] use openssl::stack::Stack; #[cfg(unix)] use openssl::x509::X509; use tokio::prelu...
use edgelet_core::CertificateProperties; use failure::ResultExt; pub use crate::error::{Error, ErrorKind}; pub struct CertificateManager<C: CreateCertificate + Clone> { certificate: Arc<RwLock<Option<Certificate>>>, crypto: C, props: CertificateProperties, creation_time: Instant, } #[derive(Clone)] s...
use edgelet_core::crypto::{ Certificate as CryptoCertificate, CreateCertificate, KeyBytes, PrivateKey, Signature, };
random_line_split
certificate_manager.rs
// Copyright (c) Microsoft. All rights reserved. use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; use futures::future::Either; #[cfg(unix)] use openssl::pkcs12::Pkcs12; #[cfg(unix)] use openssl::pkey::PKey; #[cfg(unix)] use openssl::stack::Stack; #[cfg(unix)] use openssl::x509::X509; use tokio::prelu...
} } #[derive(Clone)] struct TestCrypto { created: bool, } impl TestCrypto { pub fn new() -> Result<Self, CoreError> { Ok(Self { created: true }) } } impl CoreCreateCertificate for TestCrypto { type Certificate = TestCertificate; ...
{ if let ErrorKind::CertificateTimerCreationError = err.kind() { assert_eq!(true, true); } else { panic!( "Expected a CertificteTimerCreationError type, but got {:?}", err ); ...
conditional_block
certificate_manager.rs
// Copyright (c) Microsoft. All rights reserved. use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; use futures::future::Either; #[cfg(unix)] use openssl::pkcs12::Pkcs12; #[cfg(unix)] use openssl::pkey::PKey; #[cfg(unix)] use openssl::stack::Stack; #[cfg(unix)] use openssl::x509::X509; use tokio::prelu...
{} impl CoreCertificate for TestCertificate { type Buffer = String; type KeyBuffer = Vec<u8>; fn pem(&self) -> Result<Self::Buffer, CoreError> { Ok("test".to_string()) } fn get_private_key(&self) -> Result<Option<CorePrivateKey<Self::KeyBuffer>>, CoreError> { ...
TestCertificate
identifier_name
certificate_manager.rs
// Copyright (c) Microsoft. All rights reserved. use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; use futures::future::Either; #[cfg(unix)] use openssl::pkcs12::Pkcs12; #[cfg(unix)] use openssl::pkey::PKey; #[cfg(unix)] use openssl::stack::Stack; #[cfg(unix)] use openssl::x509::X509; use tokio::prelu...
fn get_private_key(&self) -> Result<Option<CorePrivateKey<Self::KeyBuffer>>, CoreError> { Ok(Some(PrivateKey::Key(KeyBytes::Pem( "akey".to_string().as_bytes().to_vec(), )))) } fn get_valid_to(&self) -> Result<DateTime<Utc>, CoreError> { Ok(D...
{ Ok("test".to_string()) }
identifier_body
main.rs
use anyhow::{Context, Result}; use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::path::Path; use std::rc::{Rc, Weak}; use structopt::StructOpt; use xml::{ attribute::OwnedAttribute, name::OwnedName, reader::{EventReader, XmlEvent}, }; #[derive(Debug, StructOpt)] #[structopt(name ...
self.cur.replace(element); } } /// 当前元素解析完成 fn fish_feed_element(&mut self) { self.depth -= 1; // 当前父节点指向上一层的节点 let mut parent = None; if let Some(cur) = &self.cur { if let Some(p) = &cur.borrow().parent { parent = p.upgrade();...
// cur parent 变更为 最新节点 self.cur.replace(element); } else { // 第一个节点 self.root.replace(Rc::clone(&element));
random_line_split
main.rs
use anyhow::{Context, Result}; use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::path::Path; use std::rc::{Rc, Weak}; use structopt::StructOpt; use xml::{ attribute::OwnedAttribute, name::OwnedName, reader::{EventReader, XmlEvent}, }; #[derive(Debug, StructOpt)] #[structopt(name ...
fn print_elements(root: &Option<Rc<RefCell<Element>>>, verbose: bool) { if verbose { println!("{}", Element::display(root)); } if let Some(root_rc) = root { if root_rc.borrow(). element_type.is_text() { let run_property = Element::find_run_property(&root); let color...
pth -= 1; // 当前父节点指向上一层的节点 let mut parent = None; if let Some(cur) = &self.cur { if let Some(p) = &cur.borrow().parent { parent = p.upgrade(); } } self.cur = parent; } /// 向当前的 element 中添加text, 目前只有 w:t 类型会有 fn feed_character...
identifier_body
main.rs
use anyhow::{Context, Result}; use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::path::Path; use std::rc::{Rc, Weak}; use structopt::StructOpt; use xml::{ attribute::OwnedAttribute, name::OwnedName, reader::{EventReader, XmlEvent}, }; #[derive(Debug, StructOpt)] #[structopt(name ...
l的 OwnedName 中构建 ElementType fn from_name(name: &OwnedName) -> Self { let raw = format!( "{}:{}", name.prefix.as_ref().unwrap_or(&String::new()), name.local_name ); // 目前 只识别 `w:xxx` 格式, 且只是部分标签 if name.prefix.is_none() || name.prefix.as_ref().unw...
/// 从 xm
identifier_name
main.rs
use anyhow::{Context, Result}; use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::path::Path; use std::rc::{Rc, Weak}; use structopt::StructOpt; use xml::{ attribute::OwnedAttribute, name::OwnedName, reader::{EventReader, XmlEvent}, }; #[derive(Debug, StructOpt)] #[structopt(name ...
// 调试信息 if opt.verbose { println!(r#"{}Characters("{}")"#, " ".repeat(depth), data,); } // 当前元素添加 text data doc_parsing.feed_characters(data); } XmlEvent::Whitespace(_) => {} _ => { ...
nt_xml_owned_name(&name, depth, false); } // 当前元素解析完成 doc_parsing.fish_feed_element(); } XmlEvent::Comment(_) => {} XmlEvent::CData(_) => {} XmlEvent::Characters(data) => {
conditional_block
lib.rs
//! # mio-serial - A mio-compatable serial port implementation for *nix //! //! This crate provides a SerialPort implementation compatable with mio. //! //! ** This crate ONLY provides a unix implementation ** //! //! Some basic helper methods are provided for setting a few serial port //! parameters such as the baud ...
B150 => 150, B200 => 200, B300 => 300, B600 => 600, B1200 => 1200, B1800 => 1800, B2400 => 2400, _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Unknown baud bitmask: {}", baud))), }; ...
{ use termios::{B0, B50, B75, B110, B134, B150, B200, B300, B600, B1200, B1800, B2400, B4800, B9600, B19200, B38400}; let s = self.termios()?; // And the original rate let baud = termios::cfgetospeed(&s); let b = match baud { B4800 => 4800, ...
identifier_body
lib.rs
//! # mio-serial - A mio-compatable serial port implementation for *nix //! //! This crate provides a SerialPort implementation compatable with mio. //! //! ** This crate ONLY provides a unix implementation ** //! //! Some basic helper methods are provided for setting a few serial port //! parameters such as the baud ...
{ fd: RawFd, orig_settings: termios::Termios, is_raw: bool, } impl SerialPort { /// Construct a new SerialPort /// /// Opens the a serial port at the location provided by `path` with the following /// default settings: /// /// - 9600,8N1 (9600 Baud, 8-bit data, no parity, 1 st...
SerialPort
identifier_name
lib.rs
//! # mio-serial - A mio-compatable serial port implementation for *nix //! //! This crate provides a SerialPort implementation compatable with mio. //! //! ** This crate ONLY provides a unix implementation ** //! //! Some basic helper methods are provided for setting a few serial port //! parameters such as the baud ...
/// - `Err(e)` for all other IO errors pub fn maybe_read(&mut self, buf: &mut [u8]) -> io::Result<Option<usize>> { match self.read(buf) { Ok(s) => Ok(Some(s)), Err(e) => { if let io::ErrorKind::WouldBlock = e.kind() { Ok(None) ...
/// # Returns /// /// - `Ok(Some(size))` on successful reads /// - `Ok(None)` if calling read would block.
random_line_split
psd_channel.rs
use crate::sections::image_data_section::ChannelBytes; use crate::sections::PsdCursor; use thiserror::Error; pub trait IntoRgba { /// Given an index of a pixel in the current rectangle /// (top left is 0.. to the right of that is 1.. etc) return the index of that pixel in the /// RGBA image that will be ge...
( &self, rgba: &mut Vec<u8>, channel_kind: PsdChannelKind, channel_bytes: &[u8], ) { let mut cursor = PsdCursor::new(&channel_bytes[..]); let mut idx = 0; let offset = channel_kind.rgba_offset().unwrap(); let len = cursor.get_ref().len() as u64; ...
insert_rle_channel
identifier_name
psd_channel.rs
use crate::sections::image_data_section::ChannelBytes; use crate::sections::PsdCursor; use thiserror::Error; pub trait IntoRgba { /// Given an index of a pixel in the current rectangle /// (top left is 0.. to the right of that is 1.. etc) return the index of that pixel in the /// RGBA image that will be ge...
sixteen_to_eight_rgba(red, green) } }, ChannelBytes::RleCompressed(red) => { let red = &rle_decompress(red); match self.green().unwrap() { ChannelBytes::RawData(green) => sixteen_to_eight_rgba(red, green), ...
ChannelBytes::RawData(red) => match self.green().unwrap() { ChannelBytes::RawData(green) => sixteen_to_eight_rgba(red, green), ChannelBytes::RleCompressed(green) => { let green = &rle_decompress(green);
random_line_split
psd_channel.rs
use crate::sections::image_data_section::ChannelBytes; use crate::sections::PsdCursor; use thiserror::Error; pub trait IntoRgba { /// Given an index of a pixel in the current rectangle /// (top left is 0.. to the right of that is 1.. etc) return the index of that pixel in the /// RGBA image that will be ge...
let byte = cursor.read_1()[0]; for _ in 0..repeat as usize { let rgba_idx = self.rgba_idx(idx); rgba[rgba_idx * 4 + offset] = byte; idx += 1; } }; } } } /// Rle decompress a channel fn ...
{ break; }
conditional_block
prime_field.rs
At a minimum `UInt` should implement [`Clone`], [`PartialEq`], /// [`PartialOrd`], [`Zero`], [`One`], [`AddInline`]`<&Self>`, /// [`SubInline`]`<&Self>` and [`Montgomery`]. /// /// For [`Root`] it should also implment [`Binary`] and [`DivRem`]. For /// [`SquareRoot`] it requires [`Binary`] and [`Shr`]`<usize>`. For r...
pub struct PrimeField<P: Parameters> { // TODO: un-pub. They are pub so FieldElement can have const-fn constructors. pub uint: P::UInt, pub _parameters: PhantomData<P>, } /// Required constant parameters for the prime field // TODO: Fix naming #[allow(clippy::module_name_repetitions)] // UInt can no...
// Derive fails for Clone, PartialEq, Eq, Hash
random_line_split
prime_field.rs
minimum `UInt` should implement [`Clone`], [`PartialEq`], /// [`PartialOrd`], [`Zero`], [`One`], [`AddInline`]`<&Self>`, /// [`SubInline`]`<&Self>` and [`Montgomery`]. /// /// For [`Root`] it should also implment [`Binary`] and [`DivRem`]. For /// [`SquareRoot`] it requires [`Binary`] and [`Shr`]`<usize>`. For rand /...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "field_element!(\"{:?}\")", self.to_uint()) } } impl<P: Parameters> Zero for PrimeField<P> { #[inline(always)] fn zero() -> Self { Self::from_montgomery(P::UInt::zero()) } #[inline(always)] fn is_zero(&self) -> bool...
fmt
identifier_name
prime_field.rs
minimum `UInt` should implement [`Clone`], [`PartialEq`], /// [`PartialOrd`], [`Zero`], [`One`], [`AddInline`]`<&Self>`, /// [`SubInline`]`<&Self>` and [`Montgomery`]. /// /// For [`Root`] it should also implment [`Binary`] and [`DivRem`]. For /// [`SquareRoot`] it requires [`Binary`] and [`Shr`]`<usize>`. For rand /...
else { None } } else { Some(Self::one()) } } } // TODO: Generalize over order type // Lint has a false positive here #[allow(single_use_lifetimes)] impl<U, P> Root<&U> for PrimeField<P> where U: FieldUInt + Binary + for<'a> DivRem<&'a U, Quotient = U, Re...
{ Some(Self::generator().pow(&q)) }
conditional_block
prime_field.rs
: FieldUInt; /// The modulus to implement in Montgomery form const MODULUS: Self::UInt; /// M64 = -MODULUS^(-1) mod 2^64 const M64: u64; // R1 = 2^256 mod MODULUS const R1: Self::UInt; // R2 = 2^512 mod MODULUS const R2: Self::UInt; // R3 = 2^768 mod MODULUS const R3: Self::...
{ let powers_of_two = (0..193).map(|n| U256::ONE << n); let roots_of_unity: Vec<_> = powers_of_two .map(|n| FieldElement::root(&n).unwrap()) .collect(); for (smaller_root, larger_root) in roots_of_unity[1..].iter().zip(roots_of_unity.as_slice()) { ass...
identifier_body
mod.rs
// See https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3 mod bitmap; mod decoder; mod encoder; pub use bitmap::{encode_bool as bitpacked_encode, BitmapIter}; pub use decoder::Decoder; pub use encoder::{encode_bool, encode_u32}; use super::bitpacking; #[de...
() { let data = vec![3]; let num_bits = 0; let decoder = HybridRleDecoder::new(&data, num_bits as u32, 2); let result = decoder.collect::<Vec<_>>(); assert_eq!(result, &[0, 0]); } }
zero_bit_width
identifier_name
mod.rs
// See https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3 mod bitmap; mod decoder; mod encoder; pub use bitmap::{encode_bool as bitpacked_encode, BitmapIter}; pub use decoder::Decoder; pub use encoder::{encode_bool, encode_u32}; use super::bitpacking; #[de...
} enum State<'a> { None, Bitpacked(bitpacking::Decoder<'a>), Rle(std::iter::Take<std::iter::Repeat<u32>>), } // Decoder of Hybrid-RLE encoded values. pub struct HybridRleDecoder<'a> { decoder: Decoder<'a>, state: State<'a>, remaining: usize, } #[inline] fn read_next<'a, 'b>(decoder: &'b mut D...
Bitpacked(&'a [u8]), /// A RLE-encoded slice. The first attribute corresponds to the slice (that can be interpreted) /// the second attribute corresponds to the number of repetitions. Rle(&'a [u8], usize),
random_line_split
mod.rs
// See https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3 mod bitmap; mod decoder; mod encoder; pub use bitmap::{encode_bool as bitpacked_encode, BitmapIter}; pub use decoder::Decoder; pub use encoder::{encode_bool, encode_u32}; use super::bitpacking; #[de...
208, 64, 4, 21, 100, 208, 65, 8, 37, 164, 208, 66, 12, 53, 228, 208, 67, 16, 69, 36, 209, 68, 20, 85, 100, 209, 69, 24, 101, 164, 209, 70, 28, 117, 228, 209, 71, 32, 133, 36, 210, 72, 36, 149, 100, 210, 73, 40, 165, 164, 210, 74, 44, 181, 228, 210, 75, 48, 197, 36, 211, 7...
{ // data encoded from pyarrow representing (0..1000) let data = vec![ 127, 0, 4, 32, 192, 0, 4, 20, 96, 192, 1, 8, 36, 160, 192, 2, 12, 52, 224, 192, 3, 16, 68, 32, 193, 4, 20, 84, 96, 193, 5, 24, 100, 160, 193, 6, 28, 116, 224, 193, 7, 32, 132, 32, 194, 8, 36, 148, ...
identifier_body
mod.rs
// See https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3 mod bitmap; mod decoder; mod encoder; pub use bitmap::{encode_bool as bitpacked_encode, BitmapIter}; pub use decoder::Decoder; pub use encoder::{encode_bool, encode_u32}; use super::bitpacking; #[de...
else { self.state = read_next(&mut self.decoder, self.remaining); self.next() } } fn size_hint(&self) -> (usize, Option<usize>) { (self.remaining, Some(self.remaining)) } } impl<'a> ExactSizeIterator for HybridRleDecoder<'a> {} #[cfg(test)] mod tests { use sup...
{ self.remaining -= 1; Some(result) }
conditional_block
framebuffer_server.rs
// Copyright 2022 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. //! This file contains for creating and serving a `Flatland` view using a `Framebuffer`. //! //! A lot of the code in this file is temporary to enable deve...
let sysmem_buffer_collection_token = executor.run_singlethreaded(buffer_allocator.duplicate_token())?; // Notify the async code that the sysmem buffer collection token is available. collection_sender.send(sysmem_buffer_collection_token).expect("Failed to send collection"); ...
{ let (collection_sender, collection_receiver) = channel(); let (allocation_sender, allocation_receiver) = channel(); // This thread is spawned to deal with the mix of asynchronous and synchronous proxies. // In particular, we want to keep Framebuffer creation synchronous, while still making use of ...
identifier_body
framebuffer_server.rs
// Copyright 2022 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. //! This file contains for creating and serving a `Flatland` view using a `Framebuffer`. //! //! A lot of the code in this file is temporary to enable deve...
{ /// The Flatland proxy associated with this server. flatland: fuicomposition::FlatlandSynchronousProxy, /// The buffer collection that is registered with Flatland. collection: fsysmem::BufferCollectionInfo2, } impl FramebufferServer { /// Returns a `FramebufferServer` that has created a scene a...
FramebufferServer
identifier_name
framebuffer_server.rs
// Copyright 2022 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. //! This file contains for creating and serving a `Flatland` view using a `Framebuffer`. //! //! A lot of the code in this file is temporary to enable deve...
.present(fuicomposition::PresentArgs { requested_presentation_time: Some( present_parameters.requested_presentation_time.into_nanos(), ), acquire_fences: None, release_fences: None, ...
random_line_split
lib.rs
//! [![github]](https://github.com/dtolnay/paste)&ensp;[![crates-io]](https://crates.io/crates/paste)&ensp;[![docs-rs]](https://docs.rs/paste) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?sty...
if string.value.contains(&['#', '\\', '.', '+'][..]) || string.value.starts_with("b'") || string.value.starts_with("b\"") || string.value.starts_with("br\"") { return Err(Error::new(string.span, "unsupported literal")); ...
continue; } } }
random_line_split
lib.rs
//! [![github]](https://github.com/dtolnay/paste)&ensp;[![crates-io]](https://crates.io/crates/paste)&ensp;[![docs-rs]](https://docs.rs/paste) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?sty...
} } if pasted.starts_with('\'') { let mut apostrophe = TokenTree::Punct(Punct::new('\'', Spacing::Joint)); apostrophe.set_span(span); tokens.extend(iter::once(apostrophe)); pasted.remove(0); } let ident = match panic::catch_unwind(|| Ident::new(&pasted, span)) {...
{ let mut tokens = TokenStream::new(); #[cfg(not(no_literal_fromstr))] { use proc_macro::{LexError, Literal}; use std::str::FromStr; if pasted.starts_with(|ch: char| ch.is_ascii_digit()) { let literal = match panic::catch_unwind(|| Literal::from_str(&pasted)) { ...
identifier_body
lib.rs
//! [![github]](https://github.com/dtolnay/paste)&ensp;[![crates-io]](https://crates.io/crates/paste)&ensp;[![docs-rs]](https://docs.rs/paste) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?sty...
{ Init, Ident, Literal, Apostrophe, Lifetime, Colon1, Colon2, } let mut state = State::Init; for tt in input.clone() { state = match (state, &tt) { (State::Init, TokenTree::Ident(_)) => State::Ident, (State::Init, Toke...
State
identifier_name
schedule.rs
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. use futures::{Async, Future, Poll}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::sync::atomic; use std::sync::mpsc as std_mpsc; use super::{FiberState, Sp...
let is_runnable = { CURRENT_CONTEXT.with(|context| { let mut context = context.borrow_mut(); if context .scheduler .as_ref() .map_or(true, |s| s.id!= self.scheduler_id) { cont...
let finished;
random_line_split
schedule.rs
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. use futures::{Async, Future, Poll}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::sync::atomic; use std::sync::mpsc as std_mpsc; use super::{FiberState, Sp...
Err(std_mpsc::TryRecvError::Disconnected) => unreachable!(), Ok(request) => { did_something = true; self.handle_request(request); } } // Task if let Some(fiber_id) = self.next_runnable() { ...
{}
conditional_block
schedule.rs
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. use futures::{Async, Future, Poll}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::sync::atomic; use std::sync::mpsc as std_mpsc; use super::{FiberState, Sp...
<'a> { scheduler: &'a mut CurrentScheduler, fiber: &'a mut FiberState, } impl<'a> Context<'a> { /// Returns the identifier of the current exeuction context. pub fn context_id(&self) -> super::ContextId { (self.scheduler.id, self.fiber.fiber_id) } /// Parks the current fiber. pub fn ...
Context
identifier_name
schedule.rs
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. use futures::{Async, Future, Poll}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::sync::atomic; use std::sync::mpsc as std_mpsc; use super::{FiberState, Sp...
fn next_runnable(&mut self) -> Option<fiber::FiberId> { while let Some(fiber_id) = self.run_queue.pop_front() { if let Some(fiber) = self.fibers.get_mut(&fiber_id) { fiber.in_run_queue = false; return Some(fiber_id); } } None } } ...
{ let fiber = assert_some!(self.fibers.get_mut(&fiber_id)); if !fiber.in_run_queue { self.run_queue.push_back(fiber_id); fiber.in_run_queue = true; } }
identifier_body
mod.rs
//! Inter-Integrated Circuit driver for Tegra210. //! //! # Description //! //! The I²C controller (I2C) implements an I²C 3.0 specification-compliant //! I²C master and slave controller. The I²C controller supports multiple //! masters and slaves. It supports Standard mode (up to 100 Kbits/s), //! Fast mode (up to 400...
evice over I²C and writes the result to the buffer. pub fn read(&self, device: u32, register: u8, buffer: &mut [u8]) -> Result<(), Error> { // Limit output size to 32-bits. if buffer.len() > 4 { return Err(Error::BufferBoundariesBlown); } // Write single byte register ID...
device. self.write(device, register, &byte.to_le_bytes()) } /// Reads a register of a d
identifier_body
mod.rs
//! Inter-Integrated Circuit driver for Tegra210. //! //! # Description //! //! The I²C controller (I2C) implements an I²C 3.0 specification-compliant //! I²C master and slave controller. The I²C controller supports multiple //! masters and slaves. It supports Standard mode (up to 100 Kbits/s), //! Fast mode (up to 400...
pub I2C_CMD_DATA2: Mmio<u32>, _0x14: Mmio<u32>, _0x18: Mmio<u32>, pub I2C_STATUS: Mmio<u32>, pub I2C_SL_CNFG: Mmio<u32>, pub I2C_SL_RCVD: Mmio<u32>, pub I2C_SL_STATUS: Mmio<u32>, pub I2C_SL_ADDR1: Mmio<u32>, pub I2C_SL_ADDR2: Mmio<u32>, pub I2C_TLOW_SEXT: Mmio<u32>, _0x38: Mm...
pub struct Registers { pub I2C_CNFG: Mmio<u32>, pub I2C_CMD_ADDR0: Mmio<u32>, pub I2C_CMD_ADDR1: Mmio<u32>, pub I2C_CMD_DATA1: Mmio<u32>,
random_line_split
mod.rs
//! Inter-Integrated Circuit driver for Tegra210. //! //! # Description //! //! The I²C controller (I2C) implements an I²C 3.0 specification-compliant //! I²C master and slave controller. The I²C controller supports multiple //! masters and slaves. It supports Standard mode (up to 100 Kbits/s), //! Fast mode (up to 400...
buffer: &mut [u8]) -> Result<(), Error> { // Limit output size to 32-bits. if buffer.len() > 4 { return Err(Error::BufferBoundariesBlown); } // Write single byte register ID to device. self.send(device, &[register])?; // Receive data and write these to the ...
u8,
identifier_name
mod.rs
//! Inter-Integrated Circuit driver for Tegra210. //! //! # Description //! //! The I²C controller (I2C) implements an I²C 3.0 specification-compliant //! I²C master and slave controller. The I²C controller supports multiple //! masters and slaves. It supports Standard mode (up to 100 Kbits/s), //! Fast mode (up to 400...
opy it back. let result = register_base.I2C_CMD_DATA1.read().to_le_bytes(); buffer.copy_from_slice(&result[..buffer.len()]); Ok(()) } /// Initializes the I²C controller. pub fn init(&self) { let register_base = unsafe { &*self.registers }; // Enable device clock. ...
::QueryFailed); } // Read result and c
conditional_block
get_block_template.rs
//! Support functions for the `get_block_template()` RPC. use std::{collections::HashMap, iter, sync::Arc}; use jsonrpc_core::{Error, ErrorCode, Result}; use tower::{Service, ServiceExt}; use zebra_chain::{ amount::{self, Amount, NegativeOrZero, NonNegative}, block::{ self, merkle::{self, Aut...
( funding_streams: HashMap<FundingStreamReceiver, (Amount<NonNegative>, transparent::Address)>, miner_address: transparent::Address, miner_reward: Amount<NonNegative>, like_zcashd: bool, ) -> Vec<(Amount<NonNegative>, transparent::Script)> { // Combine all the funding streams with the miner reward. ...
combine_coinbase_outputs
identifier_name
get_block_template.rs
//! Support functions for the `get_block_template()` RPC. use std::{collections::HashMap, iter, sync::Arc}; use jsonrpc_core::{Error, ErrorCode, Result}; use tower::{Service, ServiceExt}; use zebra_chain::{ amount::{self, Amount, NegativeOrZero, NonNegative}, block::{ self, merkle::{self, Aut...
/// Returns the transactions that are currently in `mempool`, or None if the /// `last_seen_tip_hash` from the mempool response doesn't match the tip hash from the state. /// /// You should call `check_synced_to_tip()` before calling this function. /// If the mempool is inactive because Zebra is not synced to the tip...
{ let request = zebra_state::ReadRequest::ChainInfo; let response = state .oneshot(request.clone()) .await .map_err(|error| Error { code: ErrorCode::ServerError(0), message: error.to_string(), data: None, })?; let chain_info = match respon...
identifier_body
get_block_template.rs
//! Support functions for the `get_block_template()` RPC. use std::{collections::HashMap, iter, sync::Arc}; use jsonrpc_core::{Error, ErrorCode, Result}; use tower::{Service, ServiceExt}; use zebra_chain::{ amount::{self, Amount, NegativeOrZero, NonNegative}, block::{ self, merkle::{self, Aut...
transparent, }; use zebra_consensus::{ funding_stream_address, funding_stream_values, miner_subsidy, FundingStreamReceiver, }; use zebra_node_services::mempool; use zebra_state::GetBlockTemplateChainInfo; use crate::methods::get_block_template_rpcs::{ constants::{MAX_ESTIMATED_DISTANCE_TO_NETWORK_CHAIN_TIP...
parameters::Network, serialization::ZcashDeserializeInto, transaction::{Transaction, UnminedTx, VerifiedUnminedTx},
random_line_split
server.rs
// // Copyright (c) Pirmin Kalberer. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // use core::config::ApplicationCfg; use datasource_type::Datasources; use datasource::DatasourceInput; use core::grid::Grid; use core::layer::Layer; use servi...
layerinfos: format!("{}", layerinfos.join(", ")), hasviewer: hasviewer, } } } struct StaticFiles { files: HashMap<&'static str, (&'static [u8], MediaType)>, } impl StaticFiles { fn init() -> StaticFiles { let mut static_files = StaticFiles { files: Hash...
{ let mut hasviewer = true; let layerinfos: Vec<String> = set.layers .iter() .map(|l| { let geom_type = l.geometry_type.clone().unwrap_or("UNKNOWN".to_string()); hasviewer = hasviewer && [ "POINT", ...
identifier_body
server.rs
// // Copyright (c) Pirmin Kalberer. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // use core::config::ApplicationCfg; use datasource_type::Datasources; use datasource::DatasourceInput; use core::grid::Grid; use core::layer::Layer; use servi...
} else { None } } None => None, }; } pub fn service_from_args(args: &ArgMatches) -> (MvtService, ApplicationCfg) { if let Some(cfgpath) = args.value_of("config") { info!("Reading configuration from '{}'", cfgpath); for argname in vec!["db...
{ Some(0) }
conditional_block
server.rs
// // Copyright (c) Pirmin Kalberer. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // use core::config::ApplicationCfg; use datasource_type::Datasources; use datasource::DatasourceInput; use core::grid::Grid; use core::layer::Layer; use servi...
() -> StaticFiles { let mut static_files = StaticFiles { files: HashMap::new(), }; static_files.add( "favicon.ico", include_bytes!("static/favicon.ico"), MediaType::Ico, ); static_files.add( "index.html", inc...
init
identifier_name
server.rs
// // Copyright (c) Pirmin Kalberer. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // use core::config::ApplicationCfg; use datasource_type::Datasources; use datasource::DatasourceInput; use core::grid::Grid; use core::layer::Layer; use servi...
serde_json::to_vec(&json).unwrap() }, ); server.get( "/:tileset/:z/:x/:y.pbf", middleware! { |req, mut res| let service: &MvtService = res.server_data(); let tileset = req.param("tileset").unwrap(); let z = req.param("z").unwrap().parse::...
let json = service.get_mbtiles_metadata(&tileset).unwrap();
random_line_split
mod.rs
pub mod dir_diff_list; use crate::cli_opt::{ApplyOpts, CliOpts, Command, TestSamplesOpts}; use crate::path_pattern::PathPattern; use crate::{error::*, SourceLoc}; use clap::Parser; use dir_diff_list::Difference; use dir_diff_list::EntryDiff; use std::fs; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}...
else if crate::ui::ask_to_update_sample("Accept to add into sample?")? { let path = self.actual_base_path.join(&self.relative_path); let is_dir = std::fs::metadata(&path)?.is_dir(); if is_dir { std::fs::create_dir_all(self.expect_base_...
{ let path = self.expect_base_path.join(&self.relative_path); let is_dir = std::fs::metadata(&path)?.is_dir(); if crate::ui::ask_to_update_sample("Accept to remove from sample ?")? { if is_dir { std::fs::remo...
conditional_block
mod.rs
pub mod dir_diff_list; use crate::cli_opt::{ApplyOpts, CliOpts, Command, TestSamplesOpts}; use crate::path_pattern::PathPattern; use crate::{error::*, SourceLoc}; use clap::Parser; use dir_diff_list::Difference; use dir_diff_list::EntryDiff; use std::fs; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}...
pub fn is_success(&self) -> bool { self.diffs.is_empty() } } impl std::fmt::Display for SampleRun { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Differences: {:#?}", self.diffs) } } /// recursively copy a directory /// based on https://stackoverflow...
{ // ALTERNATIVE: fork a sub-process to run current ffizer in apply mode let destination = &sample.args.dst_folder; if sample.existing.exists() { copy(&sample.existing, destination)?; } let ctx = crate::Ctx { cmd_opt: sample.args.clone(), }; ...
identifier_body
mod.rs
pub mod dir_diff_list; use crate::cli_opt::{ApplyOpts, CliOpts, Command, TestSamplesOpts}; use crate::path_pattern::PathPattern; use crate::{error::*, SourceLoc}; use clap::Parser; use dir_diff_list::Difference; use dir_diff_list::EntryDiff; use std::fs; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}...
samples_folder: B, tmp_dir: &TempDir, ) -> Result<Vec<Sample>> { let mut out = vec![]; for e in fs::read_dir(&samples_folder).map_err(|source| Error::ListFolder { path: samples_folder.as_ref().into(), source, })? { let path = e?.path(); ...
fn find_from_folder<B: AsRef<Path>>( template_loc: &SourceLoc,
random_line_split
mod.rs
pub mod dir_diff_list; use crate::cli_opt::{ApplyOpts, CliOpts, Command, TestSamplesOpts}; use crate::path_pattern::PathPattern; use crate::{error::*, SourceLoc}; use clap::Parser; use dir_diff_list::Difference; use dir_diff_list::EntryDiff; use std::fs; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}...
<P: AsRef<Path>>(file: P) -> Result<Self> { let v = if file.as_ref().exists() { let cfg_str = fs::read_to_string(file.as_ref()).map_err(|source| Error::ReadFile { path: file.as_ref().into(), source, })?; serde_yaml::from_str::<SampleCfg>(&cfg_s...
from_file
identifier_name
mod.rs
//! [RFC 7230](https://tools.ietf.org/html/rfc723) compliant HTTP 1.1 request parser mod util; use std::io::prelude::*; use std::net::TcpStream; use std::collections::HashMap; use std::sync::Arc; use self::util::*; pub use self::util::ParseError; use self::util::TokenType::{TChar, Invalid}; /// A container for the ...
) -> &HashMap<String, String> { &self.headers } /// Convert this request builder into a full request pub fn into_request(self) -> Option<Request> { match self { RequestBuilder { version: Some(version), method: Some(method), target:...
aders(&self
identifier_name
mod.rs
//! [RFC 7230](https://tools.ietf.org/html/rfc723) compliant HTTP 1.1 request parser mod util; use std::io::prelude::*; use std::net::TcpStream; use std::collections::HashMap; use std::sync::Arc; use self::util::*; pub use self::util::ParseError; use self::util::TokenType::{TChar, Invalid}; /// A container for the ...
match it.get_inner().read_to_end(builder.get_body()) { Ok(0) => Ok(()), Ok(_) => { println!("Body read complete"); Ok(()) }, Err(e) => Err(ParseError::new_server_error(e)), }*/ } } unsafe impl Send for Request {} // nb...
random_line_split
spacing.rs
extern crate std as ruststd ; use core :: hash :: { self , Hash } ; use core ::intrinsics:: {arith_offset,assume} ; use core::iter::FromIterator; use core :: mem; use core::ops::{ Index,IndexMut }; const CAPACITY :usize = 2*B-1; fn foo ( a : ...
pub fn capacity( & self ) -> usize { self . buf . cap ( ) } pub fn reserve(& mut self, additional: usize) { self. buf.reserve(self. len,additional) ; } pub fn into_boxed_slice( mut self ) -> Box < [ T ] > { unsafe{ self . shrink_to_fit ( ) ;...
{ Vec{ buf :RawVec::from_raw_parts(ptr, capacity) , len :length , } }
identifier_body
spacing.rs
extern crate std as ruststd ; use core :: hash :: { self , Hash } ; use core ::intrinsics:: {arith_offset,assume} ; use core::iter::FromIterator; use core :: mem; use core::ops::{ Index,IndexMut }; const CAPACITY :usize = 2*B-1; fn foo ( a : ...
<R>(&mut self,range:R)->Drain<T>where R:RangeArgument <usize>{ let len = self.len(); let start = * range.start() .unwrap_or( & 0 ) ; let end = * range. end().unwrap_or( & len ) ; assert!(start <= end); assert!(end <= len); } } impl<T:Clone>Vec<T>{ pub f...
drain
identifier_name
spacing.rs
extern crate std as ruststd ; use core :: hash :: { self , Hash } ; use core ::intrinsics:: {arith_offset,assume} ; use core::iter::FromIterator; use core :: mem; use core::ops::{ Index,IndexMut }; const CAPACITY :usize = 2*B-1; fn foo ( a : ...
} } pub fn capacity( & self ) -> usize { self . buf . cap ( ) } pub fn reserve(& mut self, additional: usize) { self. buf.reserve(self. len,additional) ; } pub fn into_boxed_slice( mut self ) -> Box < [ T ] > { unsafe{ self . shrink...
random_line_split
spacing.rs
extern crate std as ruststd ; use core :: hash :: { self , Hash } ; use core ::intrinsics:: {arith_offset,assume} ; use core::iter::FromIterator; use core :: mem; use core::ops::{ Index,IndexMut }; const CAPACITY :usize = 2*B-1; fn foo ( a : ...
r+=1 ; } self.truncate(w); } } } pub fn from_elem < T : Clone > ( elem :T,n:usize) -> Vec <T>{ } impl < T :Clone >Clone for Vec <T>{ fn clone(&self) -> Vec<T> { < [ T ] > :: to_vec ( & * * self ) } ...
{ if r!=w{ let p_w = p_wm1.offset(1); mem::swap( & mut * p_r , & mut * p_w ); } w += 1; }
conditional_block
xcode.rs
bundle_id: String, #[serde(rename = "CFBundleShortVersionString")] version: String, #[serde(rename = "CFBundleVersion")] build: String, } #[derive(Deserialize, Debug)] pub struct XcodeProjectInfo { targets: Vec<String>, configurations: Vec<String>, #[serde(default = "PathBuf::new")] ...
Ok(()) } } /// Returns true if we were invoked from xcode #[cfg(target_os = "macos")] pub fn launched_from_xcode() -> bool { if env::var("XCODE_VERSION_ACTUAL").is_err() { return false; } let mut pid = unsafe { getpid() as u32 }; while let Some(parent) = mac_process_info::get_pare...
{ show_notification("Sentry", &format!("{} finished", self.task_name))?; }
conditional_block
xcode.rs
if let Some(filename_os) = path.file_name(); if let Some(filename) = filename_os.to_str(); if filename.ends_with(".xcodeproj"); then { return match XcodeProjectInfo::from_path(path) { Ok(info) => Ok(Some(info)), _ => Ok(None), }; ...
{ let mut vars = HashMap::new(); vars.insert("FOO_BAR".to_string(), "foo bar baz / blah".to_string()); assert_eq!( expand_xcodevars("A$(FOO_BAR:rfc1034identifier)B", &vars), "Afoo-bar-baz-blahB" ); assert_eq!( expand_xcodevars("A$(FOO_BAR:identifier)B", &vars), "Afoo...
identifier_body
xcode.rs
bundle_id: String, #[serde(rename = "CFBundleShortVersionString")] version: String, #[serde(rename = "CFBundleVersion")] build: String, } #[derive(Deserialize, Debug)] pub struct XcodeProjectInfo { targets: Vec<String>, configurations: Vec<String>, #[serde(default = "PathBuf::new")] ...
<'a> { output_file: Option<TempFile>, #[allow(dead_code)] task_name: &'a str, } impl<'a> MayDetach<'a> { fn new(task_name: &'a str) -> MayDetach<'a> { MayDetach { output_file: None, task_name, } } /// Returns true if we are deteached from xcode pub f...
MayDetach
identifier_name
xcode.rs
bundle_id: String, #[serde(rename = "CFBundleShortVersionString")] version: String, #[serde(rename = "CFBundleVersion")] build: String, } #[derive(Deserialize, Debug)] pub struct XcodeProjectInfo { targets: Vec<String>, configurations: Vec<String>, #[serde(default = "PathBuf::new")] ...
/// Shows a dialog in xcode and blocks. The dialog will have a title and a /// message as well as the buttons "Show details" and "Ignore". Returns /// `true` if the `show details` button has been pressed. #[cfg(target_os = "macos")] pub fn show_critical_info(title: &str, message: &str) -> Result<bool> { use serd...
random_line_split
elf.rs
use std::convert::TryInto; use std::ffi::CStr; use std::mem; use std::ptr; use std::slice; use failure::{bail, format_err, Error, Fail, ResultExt}; use goblin::elf::{ header::{EM_BPF, ET_REL}, section_header::{SectionHeader, SHT_PROGBITS, SHT_REL}, sym::{Sym, STB_GLOBAL}, }; use ebpf_core::{ ffi, prog...
buf.get(sec.file_range()).ok_or_else(|| { format_err!( "`{}` section data {:?} out of bound", name, sec.file_range() ) }) }; match name { ...
{ if self.obj.header.e_type != ET_REL || self.obj.header.e_machine != EM_BPF { bail!("not an eBPF object file"); } if self.obj.header.endianness()? != scroll::NATIVE { bail!("endianness mismatch.") } let mut license = None; let mut version = None...
identifier_body