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
main.rs
use maplit::btreeset; use reduce::Reduce; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned}; use std::{ collections::{BTreeMap, BTreeSet}, ops::{BitAnd, BitOr}, }; /// a compact index #[derive(Debug, Clone, PartialEq, Eq)] pub struct Index { /// the strings table strin...
} fn main() { let strings = (0..5000).map(|i| { let fizz = i % 3 == 0; let buzz = i % 5 == 0; if fizz && buzz { btreeset!{"fizzbuzz".to_owned(), "com.somecompany.somenamespace.someapp.sometype".to_owned()} } else if fizz { btreeset!{"fizz".to_owned(), "org.sc...
Ok(serde_cbor::from_slice(&decompressed)?) } fn borrow_inner(elements: &[BTreeSet<String>]) -> Vec<BTreeSet<&str>> { elements.iter().map(|x| x.iter().map(|e| e.as_ref()).collect()).collect()
random_line_split
main.rs
use maplit::btreeset; use reduce::Reduce; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned}; use std::{ collections::{BTreeMap, BTreeSet}, ops::{BitAnd, BitOr}, }; /// a compact index #[derive(Debug, Clone, PartialEq, Eq)] pub struct Index { /// the strings table strin...
fn and(e: Vec<Expression>) -> Self { Self::And( e.into_iter() .flat_map(|c| match c { Self::And(es) => es, x => vec![x], }) .collect(), ) } /// convert the expression into disjunctive normal ...
{ Self::Or( e.into_iter() .flat_map(|c| match c { Self::Or(es) => es, x => vec![x], }) .collect(), ) }
identifier_body
main.rs
use maplit::btreeset; use reduce::Reduce; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned}; use std::{ collections::{BTreeMap, BTreeSet}, ops::{BitAnd, BitOr}, }; /// a compact index #[derive(Debug, Clone, PartialEq, Eq)] pub struct Index { /// the strings table strin...
(e: Vec<Expression>) -> Self { Self::Or( e.into_iter() .flat_map(|c| match c { Self::Or(es) => es, x => vec![x], }) .collect(), ) } fn and(e: Vec<Expression>) -> Self { Self::And( ...
or
identifier_name
main.rs
use maplit::btreeset; use reduce::Reduce; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned}; use std::{ collections::{BTreeMap, BTreeSet}, ops::{BitAnd, BitOr}, }; /// a compact index #[derive(Debug, Clone, PartialEq, Eq)] pub struct Index { /// the strings table strin...
} } Ok(Index { strings: strings.into_iter().collect(), elements, }) } } impl Index { /// given a query expression in Dnf form, returns all matching indices pub fn matching(&self, query: Dnf) -> Vec<usize> { // lookup all strings and trans...
{ return Err(serde::de::Error::custom("invalid string index")); }
conditional_block
xterm.rs
use with [`OwoColorize::color`](OwoColorize::color) /// or [`OwoColorize::on_color`](OwoColorize::on_color) #[derive(Copy, Clone, Debug, PartialEq)] pub enum XtermColors { $( #[allow(missing_docs)] $name, )* ...
fn from(color: XtermColors) -> Self { match color { $( XtermColors::$name => $xterm_num, )* } } } } $( #[allow(missing_docs)] ...
impl From<XtermColors> for u8 {
random_line_split
base.rs
use std::marker::PhantomData; use std::rc::Rc; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use ::serial::SerialGen; use ::traits::ReteIntrospection; use ::builder::{AlphaTest, ConditionInfo, KnowledgeBuilder}; use ::network::ids::*; use ::builders::ids::{StatementId, RuleId}; use runtime::memory...
t: PhantomData<T> } impl<T: ReteIntrospection> KnowledgeBase<T> { pub fn compile(builder: KnowledgeBuilder<T>) -> KnowledgeBase<T> { let (string_repo, rules, condition_map) = builder.explode(); let (hash_eq_nodes, alpha_network, statement_memories) = Self::compile_alpha_network(condition_map...
} } pub struct KnowledgeBase<T: ReteIntrospection> {
random_line_split
base.rs
use std::marker::PhantomData; use std::rc::Rc; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use ::serial::SerialGen; use ::traits::ReteIntrospection; use ::builder::{AlphaTest, ConditionInfo, KnowledgeBuilder}; use ::network::ids::*; use ::builders::ids::{StatementId, RuleId}; use runtime::memory...
else { unreachable!("Unexpected comparison. HashEq must be set"); } }); let mut node_id_gen = LayoutIdGenerator::new(); let mut hash_eq_nodes = HashMap::new(); let mut statement_memories: HashMap<StatementId, MemoryId> = HashMap::new(); let mut al...
{ hash1.dependents.len().cmp(&hash2.dependents.len()).then(tests1.len().cmp(&tests2.len())) }
conditional_block
base.rs
use std::marker::PhantomData; use std::rc::Rc; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use ::serial::SerialGen; use ::traits::ReteIntrospection; use ::builder::{AlphaTest, ConditionInfo, KnowledgeBuilder}; use ::network::ids::*; use ::builders::ids::{StatementId, RuleId}; use runtime::memory...
<I: Into<MemoryId> + AlphaMemoryId>(&mut self, id: I, val: Rc<T>) { let mem_id = id.into(); self.mem.entry(mem_id) .or_insert_with(Default::default) .insert(val); } } pub struct AlphaNetwork<T: ReteIntrospection> { hash_eq_node: HashMap<T::HashEq, HashEqNode>, alpha_ne...
insert
identifier_name
base.rs
use std::marker::PhantomData; use std::rc::Rc; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use ::serial::SerialGen; use ::traits::ReteIntrospection; use ::builder::{AlphaTest, ConditionInfo, KnowledgeBuilder}; use ::network::ids::*; use ::builders::ids::{StatementId, RuleId}; use runtime::memory...
} pub enum BetaNodeType { And(MemoryId, MemoryId) } pub struct BetaNode { id: BetaId, b_type: BetaNodeType, destinations: Vec<DestinationNode> } pub struct BetaNetwork { b_network: Vec<BetaNode> } pub struct BetaMemory { tripwire: Vec<bool>, }
{ let rc = Rc::new(val); if !self.store.insert(rc.clone()) { self.store.get(&rc).unwrap().clone() } else { rc } }
identifier_body
lib.rs
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy_pedantic", warn(clippy_pedantic))] // Clippy doesn't like this pattern, but I do. I may consider changing my mind // on this in the future, just to make clippy happy. #![cfg_attr(all(feature="cli...
} } impl<'a> fmt::Debug for HashlifeCache<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Hashlife instance>") } } impl<'a> Node<'a> { pub fn to_raw(&self) -> RawNode<'a> { self.raw } pub fn hashlife_instance(&self) -> Hashlife<'a> { self.hl ...
{ self.node_block(make_2x2(|_,_| self.random_block(rng, lg_size-1))) }
conditional_block
lib.rs
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy_pedantic", warn(clippy_pedantic))] // Clippy doesn't like this pattern, but I do. I may consider changing my mind // on this in the future, just to make clippy happy. #![cfg_attr(all(feature="cli...
/// Hashlife algorithm. /// /// This is the raw version of big stepping. pub fn raw_evolve(&self, node: RawNode<'a>) -> RawBlock<'a> { evolve::evolve(self, node, node.lg_size() - LG_LEAF_SIZE - 1) } /// Given 2^(n+1)x2^(n+1) node `node`, progress it 2^(n-1) generations and /// retur...
/// Given 2^(n+1)x2^(n+1) node `node`, progress it 2^(n-1) generations and /// return 2^nx2^n block in the center. This is the main component of the
random_line_split
lib.rs
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy_pedantic", warn(clippy_pedantic))] // Clippy doesn't like this pattern, but I do. I may consider changing my mind // on this in the future, just to make clippy happy. #![cfg_attr(all(feature="cli...
pub fn unwrap_node(self) -> Node<'a> { self.destruct().unwrap() } pub fn lg_size(&self) -> usize { self.lg_size } pub fn lg_size_verified(&self) -> Result<usize, ()> { Ok(self.lg_size()) } pub fn is_blank(&self) -> bool { self.raw.is_blank() } } impl...
{ self.destruct().unwrap_err() }
identifier_body
lib.rs
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy_pedantic", warn(clippy_pedantic))] // Clippy doesn't like this pattern, but I do. I may consider changing my mind // on this in the future, just to make clippy happy. #![cfg_attr(all(feature="cli...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Hashlife instance>") } } impl<'a> Node<'a> { pub fn to_raw(&self) -> RawNode<'a> { self.raw } pub fn hashlife_instance(&self) -> Hashlife<'a> { self.hl } pub fn evolve(&self) -> Block<'a> { self.hl.bl...
fmt
identifier_name
easy.rs
use super::*; use crate::utils::over; pub fn init<B: Backend>( window: &crate::windowing::window::Window, name: &str, version: u32, ) -> Result< ( B::Instance, B::Surface, Format, Adapter<B>, B::Device, QueueGroup<B>, B::CommandPool, ), &...
.find(|format| format.base_format().1 == ChannelType::Srgb) .unwrap_or(default_format) }; let (device, queue_group) = { let queue_family = adapter .queue_families .iter() .find(|family| { surface.supports_queue_family(family) && fam...
{ let instance = B::Instance::create(name, version).map_err(|_| "unsupported backend")?; let surface = unsafe { instance .create_surface(window) .map_err(|_| "create_surface failed")? }; let adapter = instance.enumerate_adapters().remove(0); let surface_color_format ...
identifier_body
easy.rs
use super::*; use crate::utils::over; pub fn init<B: Backend>( window: &crate::windowing::window::Window, name: &str, version: u32, ) -> Result< ( B::Instance, B::Surface, Format, Adapter<B>, B::Device, QueueGroup<B>, B::CommandPool, ), &...
mask: ColorMask::ALL, blend: Some(BlendState::ALPHA), }); if depth_format.is_some() { pipeline_desc.depth_stencil = DepthStencilDesc { depth: Some(DepthTest { fun: Comparison::LessEqual, write: true, }), depth_bounds: f...
}, ); pipeline_desc.blender.targets.push(ColorBlendDesc {
random_line_split
easy.rs
use super::*; use crate::utils::over; pub fn init<B: Backend>( window: &crate::windowing::window::Window, name: &str, version: u32, ) -> Result< ( B::Instance, B::Surface, Format, Adapter<B>, B::Device, QueueGroup<B>, B::CommandPool, ), &...
; let pipeline_layout = unsafe { device .create_pipeline_layout(desc_layout.into_iter(), push.into_iter()) .expect("out of memory") }; let shader_modules = [(vs_bytes, false), (fs_bytes, true)] .iter() .map(|&(bytes, is_frag)| unsafe { B::make_shader_module(devi...
{ vec![] }
conditional_block
easy.rs
use super::*; use crate::utils::over; pub fn
<B: Backend>( window: &crate::windowing::window::Window, name: &str, version: u32, ) -> Result< ( B::Instance, B::Surface, Format, Adapter<B>, B::Device, QueueGroup<B>, B::CommandPool, ), &'static str, > { let instance = B::Instance::cr...
init
identifier_name
client.rs
// #[macro_use] extern crate actix; // extern crate byteorder; // extern crate bytes; extern crate futures; extern crate serde; extern crate serde_json; // extern crate tokio_io; // extern crate tokio_tcp; extern crate awc; extern crate rustls; extern crate structopt; #[macro_use] extern crate log; extern crate env_log...
// str::FromStr, // time::Duration, sync::Arc, thread, // net, process, thread, }; // use tokio_io::{AsyncRead, io::WriteHalf}; // use tokio_tcp::TcpStream; use awc::{ error::WsProtocolError, http::StatusCode, ws::{Codec, Frame, Message}, Client, Connector, }; use rustls::ClientConfi...
}; use std::{ io,
random_line_split
client.rs
// #[macro_use] extern crate actix; // extern crate byteorder; // extern crate bytes; extern crate futures; extern crate serde; extern crate serde_json; // extern crate tokio_io; // extern crate tokio_tcp; extern crate awc; extern crate rustls; extern crate structopt; #[macro_use] extern crate log; extern crate env_log...
<T>(SinkWrite<SplitSink<Framed<T, Codec>>>) where T: AsyncRead + AsyncWrite; #[derive(Message)] struct ClientCommand(String); impl<T:'static> Actor for WsClient<T> where T: AsyncRead + AsyncWrite, { type Context = Context<Self>; fn started(&mut self, ctx: &mut Context<Self>) { // start heartb...
WsClient
identifier_name
client.rs
// #[macro_use] extern crate actix; // extern crate byteorder; // extern crate bytes; extern crate futures; extern crate serde; extern crate serde_json; // extern crate tokio_io; // extern crate tokio_tcp; extern crate awc; extern crate rustls; extern crate structopt; #[macro_use] extern crate log; extern crate env_log...
else { addr.do_send(ClientCommand(opt.msg)); sys.stop(); } }) })); }) // ).unwrap(); // sys.block_on( // ).unwrap(); // Arbiter::spawn( // TcpStream::connect(&addr) // .and_then(|stream| { ...
{ addr.do_send(ClientCommand(read_stdin())); sys.stop(); }
conditional_block
main.rs
extern crate sdl2; extern crate ears; mod chart; mod guitarplaythrough; use std::time::{Duration, Instant}; use sdl2::event::Event; use sdl2::pixels; use sdl2::keyboard::Keycode; use sdl2::gfx::primitives::DrawRenderer; use ears::{AudioController}; use guitarplaythrough::*; const SCREEN_WIDTH: u32 = 800; const S...
.map(|e| GameInputEffect::GuitarEffect(e)) .map(|effect: GameInputEffect| { match effect { GameInputEffect::Quit => run = false, GameInputEffect::GuitarEffect(effect) => match effect { Hit => (), ...
} } }); playthrough.update_time(song_time_ms)
random_line_split
main.rs
extern crate sdl2; extern crate ears; mod chart; mod guitarplaythrough; use std::time::{Duration, Instant}; use sdl2::event::Event; use sdl2::pixels; use sdl2::keyboard::Keycode; use sdl2::gfx::primitives::DrawRenderer; use ears::{AudioController}; use guitarplaythrough::*; const SCREEN_WIDTH: u32 = 800; const S...
{ Quit, GuitarEffect(GuitarGameEffect), } fn draw_fret<T: sdl2::render::RenderTarget>(canvas: &sdl2::render::Canvas<T>, enabled: bool, x: i16, y: i16, radius: i16, color: pixels::Color) -> Result<(), String> { if enabled { canvas.filled_circle(x, y, radius, color) } else { canvas.circl...
GameInputEffect
identifier_name
main.rs
extern crate sdl2; extern crate ears; mod chart; mod guitarplaythrough; use std::time::{Duration, Instant}; use sdl2::event::Event; use sdl2::pixels; use sdl2::keyboard::Keycode; use sdl2::gfx::primitives::DrawRenderer; use ears::{AudioController}; use guitarplaythrough::*; const SCREEN_WIDTH: u32 = 800; const S...
enum FrameLimit { Vsync, Cap(u32), } fn main() -> Result<(), String> { let sdl_context = sdl2::init()?; /* joystick initialization */ let joystick_subsystem = sdl_context.joystick()?; let available = joystick_subsystem.num_joysticks() .map_err(|e| format!("can't enumerate joysticks:...
{ if enabled { canvas.filled_circle(x, y, radius, color) } else { canvas.circle(x, y, radius, color) } }
identifier_body
elasticsearch.rs
use crate::{ buffers::Acker, event::Event, sinks::util::{ http::{HttpRetryLogic, HttpService}, retries::FixedRetryPolicy, BatchServiceSink, Buffer, Compression, SinkExt, }, template::Template, topology::config::{DataType, SinkConfig}, }; use futures::{stream::iter_ok, Fut...
}) } }
{ Err(format!("Unexpected status: {}", response.status())) }
conditional_block
elasticsearch.rs
use crate::{ buffers::Acker, event::Event, sinks::util::{ http::{HttpRetryLogic, HttpService}, retries::FixedRetryPolicy, BatchServiceSink, Buffer, Compression, SinkExt, }, template::Template, topology::config::{DataType, SinkConfig}, }; use futures::{stream::iter_ok, Fut...
maybe_set_id(id_key, &mut action, &event); assert_eq!(json!({}), action); } #[test] fn doesnt_set_id_when_not_configured() { let id_key: Option<&str> = None; let mut event = Event::from("butts"); event .as_mut_log() .insert_explicit("foo".into(...
.insert_explicit("not_foo".into(), "bar".into()); let mut action = json!({});
random_line_split
elasticsearch.rs
use crate::{ buffers::Acker, event::Event, sinks::util::{ http::{HttpRetryLogic, HttpService}, retries::FixedRetryPolicy, BatchServiceSink, Buffer, Compression, SinkExt, }, template::Template, topology::config::{DataType, SinkConfig}, }; use futures::{stream::iter_ok, Fut...
#[test] fn doesnt_set_id_when_field_missing() { let id_key = Some("foo"); let mut event = Event::from("butts"); event .as_mut_log() .insert_explicit("not_foo".into(), "bar".into()); let mut action = json!({}); maybe_set_id(id_key, &mut action, &ev...
{ let id_key = Some("foo"); let mut event = Event::from("butts"); event .as_mut_log() .insert_explicit("foo".into(), "bar".into()); let mut action = json!({}); maybe_set_id(id_key, &mut action, &event); assert_eq!(json!({"_id": "bar"}), action); ...
identifier_body
elasticsearch.rs
use crate::{ buffers::Acker, event::Event, sinks::util::{ http::{HttpRetryLogic, HttpService}, retries::FixedRetryPolicy, BatchServiceSink, Buffer, Compression, SinkExt, }, template::Template, topology::config::{DataType, SinkConfig}, }; use futures::{stream::iter_ok, Fut...
(host: String) -> impl Future<Item = (), Error = String> { let uri = format!("{}/_flush", host); let request = Request::post(uri).body(Body::empty()).unwrap(); let https = HttpsConnector::new(4).expect("TLS initialization failed"); let client = Client::builder().build(https); cl...
flush
identifier_name
lib.rs
mod pixel; mod y4m; use self::pixel::*; use ::y4m::{Colorspace, Decoder}; use std::cmp; use std::collections::{BTreeMap, BTreeSet}; use std::io::Read; /// Options determining how to run scene change detection. pub struct DetectionOptions { /// Whether or not to analyze the chroma planes. /// Enabling this is ...
let mut keyframes = BTreeSet::new(); let mut frameno = 0; loop { let mut next_input_frameno = frame_queue .keys() .last() .copied() .map(|key| key + 1) .unwrap_or(0); while next_input_frameno < frameno + opts.lookahead_distance { ...
let mut detector = SceneChangeDetector::new(bit_depth, chroma_sampling, &opts); let mut frame_queue = BTreeMap::new();
random_line_split
lib.rs
mod pixel; mod y4m; use self::pixel::*; use ::y4m::{Colorspace, Decoder}; use std::cmp; use std::collections::{BTreeMap, BTreeSet}; use std::io::Read; /// Options determining how to run scene change detection. pub struct DetectionOptions { /// Whether or not to analyze the chroma planes. /// Enabling this is ...
else { frame_queue.get(&(frameno - 1)) }, &frame_set, frameno, &mut keyframes, ); if frameno > 0 { frame_queue.remove(&(frameno - 1)); } frameno += 1; if let Some(ref progress_fn) = opts.progress_callb...
{ None }
conditional_block
lib.rs
mod pixel; mod y4m; use self::pixel::*; use ::y4m::{Colorspace, Decoder}; use std::cmp; use std::collections::{BTreeMap, BTreeSet}; use std::io::Read; /// Options determining how to run scene change detection. pub struct DetectionOptions { /// Whether or not to analyze the chroma planes. /// Enabling this is ...
// If the video ends before F, no frame becomes a scenecut. for i in 1..lookahead_distance { if self.has_scenecut(&frame_subset[i], &frame_subset[lookahead_distance]) { // If the current frame is the frame before a scenecut, it cannot also be the frame of a scenecut. ...
{ let lookahead_distance = cmp::min(self.opts.lookahead_distance, frame_subset.len() - 1); // Where A and B are scenes: AAAAAABBBAAAAAA // If BBB is shorter than lookahead_distance, it is detected as a flash // and not considered a scenecut. for j in 1..=lookahead_distance { ...
identifier_body
lib.rs
mod pixel; mod y4m; use self::pixel::*; use ::y4m::{Colorspace, Decoder}; use std::cmp; use std::collections::{BTreeMap, BTreeSet}; use std::io::Read; /// Options determining how to run scene change detection. pub struct DetectionOptions { /// Whether or not to analyze the chroma planes. /// Enabling this is ...
<'a> { /// Minimum average difference between YUV deltas that will trigger a scene change. threshold: u8, opts: &'a DetectionOptions, /// Frames that cannot be marked as keyframes due to the algorithm excluding them. /// Storing the frame numbers allows us to avoid looking back more than one frame. ...
SceneChangeDetector
identifier_name
debugger.rs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. use std::collections::BTreeMap; use std::io::Read; use std::process::{Child, Command}; use anyhow::{bail, format_err, Result}; use debuggable_module::path::FilePath; use debuggable_module::Address; use pete::{Ptracer, Restart, Signal, Stop, Tr...
pub fn spawn(&mut self, cmd: Command) -> Result<Child> { Ok(self.context.tracer.spawn(cmd)?) } pub fn wait(self, mut child: Child) -> Result<Output> { if let Err(err) = self.wait_on_stops() { // Ignore error if child already exited. let _ = child.kill(); ...
{ let context = DebuggerContext::new(); Self { context, event_handler, } }
identifier_body
debugger.rs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. use std::collections::BTreeMap; use std::io::Read; use std::process::{Child, Command}; use anyhow::{bail, format_err, Result}; use debuggable_module::path::FilePath; use debuggable_module::Address; use pete::{Ptracer, Restart, Signal, Stop, Tr...
#[cfg(target_arch = "aarch64")] let instruction_pointer = &mut regs.pc; // Compute what the last PC would have been _if_ we stopped due to a soft breakpoint. // // If we don't have a registered breakpoint, then we will not use this value. let pc = Address(instruction_po...
#[cfg(target_arch = "x86_64")] let instruction_pointer = &mut regs.rip;
random_line_split
debugger.rs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. use std::collections::BTreeMap; use std::io::Read; use std::process::{Child, Command}; use anyhow::{bail, format_err, Result}; use debuggable_module::path::FilePath; use debuggable_module::Address; use pete::{Ptracer, Restart, Signal, Stop, Tr...
(self, mut child: Child) -> Result<Output> { if let Err(err) = self.wait_on_stops() { // Ignore error if child already exited. let _ = child.kill(); return Err(err); } // Currently unavailable on Linux. let status = None; let stdout = if let...
wait
identifier_name
debugger.rs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. use std::collections::BTreeMap; use std::io::Read; use std::process::{Child, Command}; use anyhow::{bail, format_err, Result}; use debuggable_module::path::FilePath; use debuggable_module::Address; use pete::{Ptracer, Restart, Signal, Stop, Tr...
// Cannot panic due to initial length check. let first = &maps[0]; let path = if let MMapPath::Path(path) = &first.pathname { FilePath::new(path.to_string_lossy())? } else { bail!("module image mappings must be file-backed"); }; for map in &map...
{ bail!("no executable mapping for module image"); }
conditional_block
lib.rs
//! [![license:MIT/Apache-2.0][1]](https://github.com/uazu/stakker)&nbsp; //! [![github:uazu/stakker][2]](https://github.com/uazu/stakker)&nbsp; //! [![crates.io:stakker][3]](https://crates.io/crates/stakker)&nbsp; //! [![docs.rs:stakker][4]](https://docs.rs/stakker)&nbsp; //! [![uazu.github.io:stakker][5]](https://uaz...
//! //! If no inter-thread operations are active, then **Stakker** will //! never do locking or any atomic operations, nor block for any //! reason. So the code can execute at full speed without triggering //! any CPU memory fences or whatever. Usually the only thing that //! blocks would be the external I/O poller w...
//! provided with arguments. These are also efficient due to //! inlining. In this case two chunks of inlined code are generated //! for each by the compiler: the first which accepts arguments and //! pushes the second one onto the queue.
random_line_split
decisiontree.rs
//! llvm/decisiontree.rs - Defines how to codegen a decision tree //! via `codegen_tree`. This decisiontree is the result of compiling //! a match expression into a decisiontree during type inference. use crate::llvm::{ Generator, CodeGen }; use crate::types::pattern::{ DecisionTree, Case, VariantTag }; use crate::type...
cases.last().unwrap().tag == None } /// codegen an else/match-all case of a particular constructor in a DecisionTree. /// If there is no MatchAll case (represented by a None value for case.tag) then /// a block is created with an llvm unreachable assertion. fn codegen_match_else_block<'c>(&...
} } /// When creating a decision tree, any match all case is always last in the case list. fn has_match_all_case(&self, cases: &[Case]) -> bool {
random_line_split
decisiontree.rs
//! llvm/decisiontree.rs - Defines how to codegen a decision tree //! via `codegen_tree`. This decisiontree is the result of compiling //! a match expression into a decisiontree during type inference. use crate::llvm::{ Generator, CodeGen }; use crate::types::pattern::{ DecisionTree, Case, VariantTag }; use crate::type...
<'c>(&mut self, tag: &VariantTag, cache: &mut ModuleCache<'c>) -> Option<BasicValueEnum<'g>> { match tag { VariantTag::True => Some(self.bool_value(true)), VariantTag::False => Some(self.bool_value(false)), VariantTag::Unit => Some(self.unit_value()), // TODO: Re...
get_constructor_tag
identifier_name
decisiontree.rs
//! llvm/decisiontree.rs - Defines how to codegen a decision tree //! via `codegen_tree`. This decisiontree is the result of compiling //! a match expression into a decisiontree during type inference. use crate::llvm::{ Generator, CodeGen }; use crate::types::pattern::{ DecisionTree, Case, VariantTag }; use crate::type...
/// Performs the union downcast, binding each field of the downcasted variant /// the the appropriate DefinitionInfoIds held within the given Case. fn bind_pattern_fields<'c>(&mut self, case: &Case, matched_value: BasicValueEnum<'g>, cache: &mut ModuleCache<'c>) { let variant = self.cast_to_varian...
{ for id in field { let typ = self.follow_bindings(cache.definition_infos[id.0].typ.as_ref().unwrap(), cache); self.definitions.insert((*id, typ), value); } }
identifier_body
main.rs
// -- SymSpell -- // Explanation at // https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f // TL;DR, HashTable keys are generated // from all words + all possible // permutations of those words with up // to two deletes, and the data held // in each key is the correctly spelled /...
new_set.insert(word.to_string(), ()); x.clear(); for j in new_set.keys() { x.push(j.to_string()); } } else { self.error_map .insert( i.clone(), vec![word...
{ // Vec<String> // Must only contain inserts of // correct words let permuted_keys = self.permutations_of(word); for i in permuted_keys { // if error key exists if let Some(x) = self.error_map.get_mut(&i) { let mut new_set: HashMap<String,...
identifier_body
main.rs
// -- SymSpell -- // Explanation at // https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f // TL;DR, HashTable keys are generated // from all words + all possible // permutations of those words with up // to two deletes, and the data held // in each key is the correctly spelled /...
match d.check(&cmd.trim()) { Some(x) => println!("Did you mean {}?", x), _ => println!("Not found :(") }; } } }
io::stdin().read_line(&mut word).expect("no work... >:("); println!("value? "); io::stdin().read_line(&mut value).expect("no work... >:("); d.insert_with_permutations_and_count(word.trim().as_ref(), value.trim().parse().expect("not a number")); } else {
random_line_split
main.rs
// -- SymSpell -- // Explanation at // https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f // TL;DR, HashTable keys are generated // from all words + all possible // permutations of those words with up // to two deletes, and the data held // in each key is the correctly spelled /...
() -> Dictionary { Dictionary { word_map: HashMap::new(), error_map: HashMap::new(), error_distance: 2 } } fn insert(&mut self, word: &str) { if let Some(x) = self.word_map.get_mut(word) { x.score += 1; } else { self.wo...
new
identifier_name
main.rs
// -- SymSpell -- // Explanation at // https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f // TL;DR, HashTable keys are generated // from all words + all possible // permutations of those words with up // to two deletes, and the data held // in each key is the correctly spelled /...
else if let Some(x) = self.error_map.get(word) { if x.len() > 1 { Some(self.find_best_match(x.to_vec())) } else { Some(x[0].clone()) } } else { None } }; if let Some(x) = fin...
{ Some(x.word.clone()) }
conditional_block
consumer.rs
use super::{ delegate::DelegateMut, observer::{DelegateObserver, Observer}, utils::modulus, }; use crate::utils::{slice_assume_init_mut, slice_assume_init_ref, write_uninit_slice}; use core::{iter::Chain, mem::MaybeUninit, ptr, slice}; #[cfg(feature = "std")] use std::io::{self, Write}; /// Consumer part o...
<'a, C: Consumer> { target: &'a C, slices: (&'a [MaybeUninit<C::Item>], &'a [MaybeUninit<C::Item>]), len: usize, } impl<'a, C: Consumer> PopIter<'a, C> { pub fn new(target: &'a mut C) -> Self { let slices = target.occupied_slices(); Self { len: slices.0.len() + slices.1.len()...
PopIter
identifier_name
consumer.rs
use super::{ delegate::DelegateMut, observer::{DelegateObserver, Observer}, utils::modulus, }; use crate::utils::{slice_assume_init_mut, slice_assume_init_ref, write_uninit_slice}; use core::{iter::Chain, mem::MaybeUninit, ptr, slice}; #[cfg(feature = "std")] use std::io::{self, Write}; /// Consumer part o...
#[inline] fn try_pop(&mut self) -> Option<Self::Item> { self.base_mut().try_pop() } #[inline] fn pop_slice(&mut self, elems: &mut [Self::Item]) -> usize where Self::Item: Copy, { self.base_mut().pop_slice(elems) } #[inline] fn iter(&self) -> Iter<'_, Se...
self.base_mut().as_mut_slices() }
random_line_split
consumer.rs
use super::{ delegate::DelegateMut, observer::{DelegateObserver, Observer}, utils::modulus, }; use crate::utils::{slice_assume_init_mut, slice_assume_init_ref, write_uninit_slice}; use core::{iter::Chain, mem::MaybeUninit, ptr, slice}; #[cfg(feature = "std")] use std::io::{self, Write}; /// Consumer part o...
}; unsafe { self.advance_read_index(count) }; count } fn into_iter(self) -> IntoIter<Self> { IntoIter::new(self) } /// Returns an iterator that removes items one by one from the ring buffer. fn pop_iter(&mut self) -> PopIter<'_, Self> { PopIter::new(self) ...
{ unsafe { write_uninit_slice(elems.get_unchecked_mut(..right.len()), right) }; right.len() }
conditional_block
v4.rs
//---------------------------------------------------------------------------// // Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved. // // This file is part of the Rusted PackFile Manager (RPFM) project, // which can be found here: https://github.com/Frodo45127/rpfm. // // This file is licensed un...
egacy_table_definition: &DefinitionV4) -> Self { let mut definition = Self::new(legacy_table_definition.version, None); let fields = legacy_table_definition.fields.iter().map(From::from).collect::<Vec<FieldV5>>(); definition.set_fields(fields); let fields = legacy_table_definition.loca...
om(l
identifier_name
v4.rs
//---------------------------------------------------------------------------// // Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved. // // This file is part of the Rusted PackFile Manager (RPFM) project, // which can be found here: https://github.com/Frodo45127/rpfm. // // This file is licensed un...
lse { None }) .for_each(|(name, definitions)| { definitions.iter().for_each(|definition| { schema.add_definition(name, &From::from(definition)); }) }); schema } } impl From<&DefinitionV4> for DefinitionV5 { fn from(legacy_table_...
Some((name, definitions)) } e
conditional_block
v4.rs
//---------------------------------------------------------------------------// // Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved. // // This file is part of the Rusted PackFile Manager (RPFM) project, // which can be found here: https://github.com/Frodo45127/rpfm. // // This file is licensed un...
FieldTypeV4::I16 => Self::I16, FieldTypeV4::I32 => Self::I32, FieldTypeV4::I64 => Self::I64, FieldTypeV4::F32 => Self::F32, FieldTypeV4::F64 => Self::F64, FieldTypeV4::ColourRGB => Self::ColourRGB, FieldTypeV4::StringU8 => Self::StringU...
random_line_split
traits.rs
thing. Clearly, this could lead to naming conflicts! But since Rust makes you import the /// traits you plan to use, crates are free to take advantage of this superpower, and conflicts are /// rare in practice. /// /// The reason Clone and Iterator methods work without any special imports is that they’re always /// in...
fn name(&self) -> &'static str { "Dave" } fn noise(&self) -> &'static str { "Moo" } } pub fn random_animal(random_number: f64) -> Box<dyn Animal> { if random_number < 0.5 { Box::new(Sheep { name: "Bob", naked: true, }) } else { Bo...
pub struct Cow {} impl Animal for Cow {
random_line_split
traits.rs
. Clearly, this could lead to naming conflicts! But since Rust makes you import the /// traits you plan to use, crates are free to take advantage of this superpower, and conflicts are /// rare in practice. /// /// The reason Clone and Iterator methods work without any special imports is that they’re always /// in scope...
f.state.take() { self.state = Some(s.reject()); } } pub fn approve(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.approve()); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_min() { assert_eq!(min(3, 5...
= sel
identifier_name
traits.rs
Clearly, this could lead to naming conflicts! But since Rust makes you import the /// traits you plan to use, crates are free to take advantage of this superpower, and conflicts are /// rare in practice. /// /// The reason Clone and Iterator methods work without any special imports is that they’re always /// in scope ...
ent any trait on any type, as long as either the trait or the type is /// introduced in the current crate. This means that any time you want to add a method to any type, /// you can use a trait to do it. This is called an "extension trait". pub trait IsEmoji { fn is_emoji(&self) -> bool; } impl IsEmoji for char { ...
t lets you implem
conditional_block
traits.rs
. Clearly, this could lead to naming conflicts! But since Rust makes you import the /// traits you plan to use, crates are free to take advantage of this superpower, and conflicts are /// rare in practice. /// /// The reason Clone and Iterator methods work without any special imports is that they’re always /// in scope...
State for Published { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { self } fn reject(self: Box<Self>) -> Box<dyn State> { self } fn content<'a>(&self, post: &'a Post) -> &'a str { post.content.as_...
} } struct Published {} impl
identifier_body
message.rs
//! Definitions of network messages. use std::error::Error; use std::{net, sync::Arc}; use chrono::{DateTime, Utc}; use zebra_chain::block::{Block, BlockHeader, BlockHeaderHash}; use zebra_chain::{transaction::Transaction, types::BlockHeight}; use super::inv::InventoryHash; use super::types::*; use crate::meta_addr...
(e: E) -> Self { Message::Reject { message: e.to_string(), // The generic case, impls for specific error types should // use specific varieties of `RejectReason`. ccode: RejectReason::Other, reason: e.source().unwrap().to_string(), // Al...
from
identifier_name
message.rs
//! Definitions of network messages. use std::error::Error; use std::{net, sync::Arc}; use chrono::{DateTime, Utc}; use zebra_chain::block::{Block, BlockHeader, BlockHeaderHash}; use zebra_chain::{transaction::Transaction, types::BlockHeight}; use super::inv::InventoryHash; use super::types::*; use crate::meta_addr...
}, /// A `headers` message. /// /// Returns block headers in response to a getheaders packet. /// /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#headers) // Note that the block headers in this packet include a // transaction count (a var_int, so there can be m...
/// /// Set to zero to get as many blocks as possible (500). hash_stop: BlockHeaderHash,
random_line_split
main.rs
use random_fast_rng::{FastRng, Random}; use rusqlite::{params, Connection, DropBehavior}; use std::fs; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc, RwLock}; use std::thread; use std::time::{Duration, Instant}; const ITER_SECS: u64 = 5; const USE_RWLOCK: bool = false; c...
else { "!" } } perf_vec.push(PerfRecord { config: format!("{}wal, {}shared_cache", not_str(options.wal), not_str(options.shared_cache)), readers: 1, writers, reads_per_sec: total_reads as f64 / ITER_SECS as f64, wr...
{ "" }
conditional_block
main.rs
use random_fast_rng::{FastRng, Random}; use rusqlite::{params, Connection, DropBehavior}; use std::fs; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc, RwLock}; use std::thread; use std::time::{Duration, Instant}; const ITER_SECS: u64 = 5; const USE_RWLOCK: bool = false; c...
pub fn seed(&mut self) -> std::io::Result<Vec<u16>> { let mut transaction = self .conn .transaction() .expect("Could not open DB transaction"); transaction.set_drop_behavior(DropBehavior::Commit); let mut query = transaction .prepare( ...
{ if options.wal { self.conn .pragma_update(None, "journal_mode", &"WAL".to_owned()) .expect("Error applying WAL journal_mode"); } self.conn .execute( r#" CREATE TABLE "kv" ( "key" INTEGER NOT NULL, "value" BLOB NOT NULL,...
identifier_body
main.rs
use random_fast_rng::{FastRng, Random}; use rusqlite::{params, Connection, DropBehavior}; use std::fs; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc, RwLock}; use std::thread; use std::time::{Duration, Instant}; const ITER_SECS: u64 = 5; const USE_RWLOCK: bool = false; c...
{ conn: rusqlite::Connection, } #[derive(Copy, Clone, Debug)] struct DbOptions { wal: bool, shared_cache: bool, } impl DbOptions { fn db_flags(&self) -> rusqlite::OpenFlags { use rusqlite::OpenFlags; let mut flags = OpenFlags::empty(); flags.set(OpenFlags::SQLITE_OPEN_CREATE,...
Database
identifier_name
main.rs
use random_fast_rng::{FastRng, Random}; use rusqlite::{params, Connection, DropBehavior}; use std::fs; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc, RwLock}; use std::thread; use std::time::{Duration, Instant}; const ITER_SECS: u64 = 5; const USE_RWLOCK: bool = false; c...
let key = rng.get_u16(); let timer = Instant::now(); let _guard; if USE_RWLOCK { _guard = rwlock.write().expect("Cannot unlock for read!"); } let rows_updated = query .execute(params![key, value]) .expect("Failed to issue update query!")...
rng.fill_bytes(&mut value); while !stop.load(Ordering::Relaxed) {
random_line_split
lib.rs
//! Extensions for [glutin](https://crates.io/crates/glutin) to initialize & update old school //! [gfx](https://crates.io/crates/gfx). _An alternative to gfx_window_glutin_. //! //! # Example //! ```no_run //! type ColorFormat = gfx::format::Srgba8; //! type DepthFormat = gfx::format::DepthStencil; //! //! # fn main()...
} /// Recreate and replace gfx views if the dimensions have changed. pub fn resize_views<Color: RenderFormat, Depth: DepthFormat>( new_size: winit::dpi::PhysicalSize<u32>, color_view: &mut RenderTargetView<R, Color>, depth_view: &mut DepthStencilView<R, Depth>, ) { if let Some((cv, dv)) = resized_view...
{ Init { window: self.window, gl_config: self.gl_config, gl_surface: self.gl_surface, gl_context: self.gl_context, device: self.device, factory: self.factory, color_view: Typed::new(self.color_view), depth_view: Type...
identifier_body
lib.rs
//! Extensions for [glutin](https://crates.io/crates/glutin) to initialize & update old school //! [gfx](https://crates.io/crates/gfx). _An alternative to gfx_window_glutin_. //! //! # Example //! ```no_run //! type ColorFormat = gfx::format::Srgba8; //! type DepthFormat = gfx::format::DepthStencil; //! //! # fn main()...
() -> Self { Self::Specific(0) } } impl From<u8> for NumberOfSamples { fn from(val: u8) -> Self { Self::Specific(val) } } impl NumberOfSamples { fn find<'a>( self, mut configs: impl Iterator<Item = (usize, &'a glutin::config::Config)>, ) -> Option<(usize, &'a glutin...
default
identifier_name
lib.rs
//! Extensions for [glutin](https://crates.io/crates/glutin) to initialize & update old school //! [gfx](https://crates.io/crates/gfx). _An alternative to gfx_window_glutin_. //! //! # Example //! ```no_run //! type ColorFormat = gfx::format::Srgba8; //! type DepthFormat = gfx::format::DepthStencil; //! //! # fn main()...
.with_stencil_size(stencil_bits); let mut no_suitable_config = false; let (window, gl_config) = glutin_winit::DisplayBuilder::new() .with_window_builder(Some(self.winit)) .build(self.event_loop, config_attrs, |configs| { let mut configs: Vec<_> = configs...
.config_attrs .with_alpha_size(alpha_bits) .with_depth_size(depth_total_bits - stencil_bits)
random_line_split
ply_loader.rs
use std::io::{Read, Seek, BufReader, BufRead, SeekFrom}; use std::error; use std::fmt; use crate::model::ply::{PlyFileHeader, PlyElementDescriptor, standard_formats, PlyPropertyDescriptor, PlyScalar, PlyDatatype}; use std::str::{SplitAsciiWhitespace, FromStr}; use byteorder::{LittleEndian, ByteOrder}; use num::{self, N...
a.unwrap() }; // Make new descriptor let elem_index = element_vec.len() as u32; current_element = Some(PlyElementDescriptor::new(elem_index, elem_name, num_entries)); } // Property descriptor else if line.starts_with("property") { // Check that we are actually in an elem...
let a = a.parse::<u32>(); if a.is_err() { return ply_err("Invalid element descriptor"); }
random_line_split
ply_loader.rs
use std::io::{Read, Seek, BufReader, BufRead, SeekFrom}; use std::error; use std::fmt; use crate::model::ply::{PlyFileHeader, PlyElementDescriptor, standard_formats, PlyPropertyDescriptor, PlyScalar, PlyDatatype}; use std::str::{SplitAsciiWhitespace, FromStr}; use byteorder::{LittleEndian, ByteOrder}; use num::{self, N...
(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "PlyError: {}", self.message) } } impl fmt::Debug for PlyError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { <Self as fmt::Display>::fmt(self, f) } } pub fn dump_ply_header(header: &PlyFileHeader) { for element...
fmt
identifier_name
ply_loader.rs
use std::io::{Read, Seek, BufReader, BufRead, SeekFrom}; use std::error; use std::fmt; use crate::model::ply::{PlyFileHeader, PlyElementDescriptor, standard_formats, PlyPropertyDescriptor, PlyScalar, PlyDatatype}; use std::str::{SplitAsciiWhitespace, FromStr}; use byteorder::{LittleEndian, ByteOrder}; use num::{self, N...
else { return Err(PlyReadError::Other(Box::new(PlyError::new("Invalid entry line: Missing property value")))); }; let val: T = match value_str.parse::<T>() { Ok(val) => val, Err(_err) => return Err(PlyReadError::Other(Box::new(PlyError::new("Invalid entry line: Failed to parse value")))), ...
{ s }
conditional_block
main.rs
mod xcb_util; use log::debug; use crate::xcb_util::{ geometry::*, window::WindowExt, }; use std::str; use anyhow::{ anyhow, Error, }; use structopt::StructOpt; use xcb::{ base as xbase, randr as xrandr, xproto, }; #[derive(StructOpt)] struct GlobalOptions {} #[derive(StructOpt)] struct Fract { num...
let pct = DisplayPercentageSpaceRect::new( DisplayPercentageSpacePoint::new(self.x.value(), self.y.value()), DisplayPercentageSpaceSize::new(self.w.value(), self.h.value()), ); let new_rect = pct .to_rect(display_frame) .inner_rect(geom.active_window_insets); dbg!(&new_rect); ...
let display_frame = get_output_available_rect(&conn)?; let geom = get_geometry(&conn)?;
random_line_split
main.rs
mod xcb_util; use log::debug; use crate::xcb_util::{ geometry::*, window::WindowExt, }; use std::str; use anyhow::{ anyhow, Error, }; use structopt::StructOpt; use xcb::{ base as xbase, randr as xrandr, xproto, }; #[derive(StructOpt)] struct GlobalOptions {} #[derive(StructOpt)] struct
{ num: f32, denom: f32, } impl Fract { fn value(&self) -> f32 { self.num / self.denom } } impl std::str::FromStr for Fract { type Err = Error; fn from_str(s: &str) -> Result<Fract, Error> { let parts = s.split('/').collect::<Vec<_>>(); Ok(Fract { num: f32::from_str(parts[0])?, denom: f3...
Fract
identifier_name
lib.rs
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT pub mod bitvec_serde; pub mod rleplus; pub use bitvec; use bitvec::prelude::*; use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not}; use fnv::FnvHashSet; use std::iter::FromIterator; type BitVec = bitvec::prelude::BitVec<Lsb0, ...
BitField::Decoded(bv) => { if let Some(true) = bv.get(index as usize) { Ok(true) } else { Ok(false) } } } } /// Retrieves the index of the first set bit, and error if invalid encoding or no ...
{ if set.contains(&index) { return Ok(true); } if unset.contains(&index) { return Ok(false); } // Check in encoded for the given bit // This can be changed to not flush changes ...
conditional_block
lib.rs
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT pub mod bitvec_serde; pub mod rleplus; pub use bitvec; use bitvec::prelude::*; use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not}; use fnv::FnvHashSet; use std::iter::FromIterator; type BitVec = bitvec::prelude::BitVec<Lsb0, ...
() -> Self { Self::Decoded(BitVec::new()) } } impl BitField { pub fn new() -> Self { Self::default() } /// Generates a new bitfield with a slice of all indexes to set. pub fn new_from_set(set_bits: &[u64]) -> Self { let mut vec = match set_bits.iter().max() { So...
default
identifier_name
lib.rs
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT pub mod bitvec_serde; pub mod rleplus; pub use bitvec; use bitvec::prelude::*; use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not}; use fnv::FnvHashSet; use std::iter::FromIterator; type BitVec = bitvec::prelude::BitVec<Lsb0, ...
// TODO this probably should not require mut self and RLE decode bits pub fn get(&mut self, index: u64) -> Result<bool> { match self { BitField::Encoded { set, unset,.. } => { if set.contains(&index) { return Ok(true); } if...
random_line_split
lib.rs
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT pub mod bitvec_serde; pub mod rleplus; pub use bitvec; use bitvec::prelude::*; use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not}; use fnv::FnvHashSet; use std::iter::FromIterator; type BitVec = bitvec::prelude::BitVec<Lsb0, ...
/// Intersection of two bitfields and assigns to self (equivalent of bit AND `&`) pub fn intersect_assign(&mut self, other: &Self) -> Result<()> { match other { BitField::Encoded { bv, set, unset } => { *self.as_mut_flushed()? &= decode_and_apply_cache(bv, set, unset)? ...
{ self.intersect_assign(other)?; Ok(self) }
identifier_body
nfa.rs
//! The structure for defining non-deterministic finite automata. use crate::automata::alphabet; use crate::automata::dfa::DFA; use crate::automata::dfa::RuleExecutable; use crate::automata::pattern::Pattern; use crate::automata::state::State; use crate::automata::state::Transition; use crate::automata::state; use cra...
for (state_ix, source) in self.states.iter().enumerate() { let targets = source.targets(&self.alphabet_segmentation); for (voc_ix, &target) in targets.iter().enumerate() { matrix[(state_ix,voc_ix)] = target; } } matrix } } // === Trait Impls ===...
;
identifier_name
nfa.rs
//! The structure for defining non-deterministic finite automata. use crate::automata::alphabet; use crate::automata::dfa::DFA; use crate::automata::dfa::RuleExecutable; use crate::automata::pattern::Pattern; use crate::automata::state::State; use crate::automata::state::Transition; use crate::automata::state; use cra...
#[test] fn test_to_dfa _letter() { assert_eq!(DFA::from(&letter()),dfa::tests::letter()); } #[test] fn test_to_dfa_spaces() { assert_eq!(DFA::from(&spaces()),dfa::tests::spaces()); } #[test] fn test_to_dfa_letter_and_spaces() { assert_eq!(DFA::from(&letter_and_s...
tate::from(vec![11]).named("group_0_rule_0"), State::from(vec![4]), State::from(vec![(32..=32,5)]), State::from(vec![6]), State::from(vec![7,10]), State::from(vec![8]), State::from(vec![(32..=32,9)]), State::...
identifier_body
nfa.rs
//! The structure for defining non-deterministic finite automata. use crate::automata::alphabet; use crate::automata::dfa::DFA; use crate::automata::dfa::RuleExecutable; use crate::automata::pattern::Pattern; use crate::automata::state::State; use crate::automata::state::Transition; use crate::automata::state; use cra...
DFA{alphabet_segmentation,links,callbacks} } } // =========== // == Tests == // =========== #[cfg(test)] pub mod tests { extern crate test; use crate::automata::dfa; use super::*; use test::Bencher; /// NFA that accepts a newline '\n'. pub fn newline() -> NFA { NFA { ...
} } let alphabet_segmentation = nfa.alphabet_segmentation.clone(); let links = dfa_mat;
random_line_split
warming.rs
use std::collections::HashSet; use std::ops::Deref; use std::sync::{Arc, Mutex, Weak}; use std::thread::JoinHandle; use std::time::Duration; use crate::{Executor, Inventory, Searcher, SearcherGeneration, TantivyError}; pub const GC_INTERVAL: Duration = Duration::from_secs(1); /// `Warmer` can be used to maintain seg...
/// Start tracking a new generation of [Searcher], and [Warmer::warm] it if there are active /// warmers. /// /// A background GC thread for [Warmer::garbage_collect] calls is uniquely created if there are /// active warmers. pub fn warm_new_searcher_generation(&self, searcher: &Searcher) -> cr...
})))) }
random_line_split
warming.rs
use std::collections::HashSet; use std::ops::Deref; use std::sync::{Arc, Mutex, Weak}; use std::thread::JoinHandle; use std::time::Duration; use crate::{Executor, Inventory, Searcher, SearcherGeneration, TantivyError}; pub const GC_INTERVAL: Duration = Duration::from_secs(1); /// `Warmer` can be used to maintain seg...
( &mut self, searcher: &Searcher, this: &Arc<Mutex<Self>>, ) -> crate::Result<()> { let warmers = self.pruned_warmers(); // Avoid threads (warming as well as background GC) if there are no warmers if warmers.is_empty() { return Ok(()); } se...
warm_new_searcher_generation
identifier_name
warming.rs
use std::collections::HashSet; use std::ops::Deref; use std::sync::{Arc, Mutex, Weak}; use std::thread::JoinHandle; use std::time::Duration; use crate::{Executor, Inventory, Searcher, SearcherGeneration, TantivyError}; pub const GC_INTERVAL: Duration = Duration::from_secs(1); /// `Warmer` can be used to maintain seg...
else { Executor::multi_thread(num_threads, "tantivy-warm-") } } #[cfg(test)] mod tests { use std::collections::HashSet; use std::sync::atomic::{self, AtomicUsize}; use std::sync::{Arc, RwLock, Weak}; use super::Warmer; use crate::core::searcher::SearcherGeneration; use crate::dire...
{ Ok(Executor::single_thread()) }
conditional_block
main.rs
#![feature(test)] #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate gfx_device_gl; extern crate glutin; extern crate rand; extern crate failure; #[macro_use] extern crate failure_derive; extern crate image; extern crate rusttype; extern crate specs; extern crate rayon; #[macro_use] extern cra...
} // Update & paint the world { dispatcher.dispatch_seq(&mut world.res); // Get the player position let player_pos = world.read_storage::<Pos>().get(player).unwrap().clone(); let player_pos = [player_pos.pos.x, player_pos.z, player_pos.pos.y]; ...
{ println!("Resizing window viewport"); renderer.update_window_size(&window); }
conditional_block
main.rs
#![feature(test)] #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate gfx_device_gl; extern crate glutin; extern crate rand; extern crate failure; #[macro_use] extern crate failure_derive; extern crate image; extern crate rusttype; extern crate specs; extern crate rayon; #[macro_use] extern cra...
.with(PlayerControlled::new()) .with(FollowCamera) .with(Health::new(8, Hitmask(HITMASK_PLAYER))) .with(Collector { magnet_radius: 64.0 }) .with(Equipment { .. Default::default() }) .with(CollCircle { r: 8.0, off: Vec32::zero(), fla...
.with(Vel { vel: Vec32::zero() }) .with(Alliance::good())
random_line_split
main.rs
#![feature(test)] #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate gfx_device_gl; extern crate glutin; extern crate rand; extern crate failure; #[macro_use] extern crate failure_derive; extern crate image; extern crate rusttype; extern crate specs; extern crate rayon; #[macro_use] extern cra...
(renderer::VertexBuffer); /// Entities that have been 'killed' and need to produce on-death effects. This /// doesn't mean all deleted entities - it means alive characters have been /// killed by combat or other effects. pub struct KilledEntities(Vec<Entity>); /// Empty specs::System to use in the dispatcher as a com...
UIVertexBuffer
identifier_name
main.rs
#![feature(test)] #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate gfx_device_gl; extern crate glutin; extern crate rand; extern crate failure; #[macro_use] extern crate failure_derive; extern crate image; extern crate rusttype; extern crate specs; extern crate rayon; #[macro_use] extern cra...
} /// Create the world and register all the components fn create_world() -> specs::World { let mut world = specs::World::new(); world.register::<Pos>(); world.register::<Vel>(); world.register::<PlayerControlled>(); world.register::<Tilemap>(); world.register::<AnimSprite>(); world.registe...
{}
identifier_body
mod.rs
.name) pub const SHA256_NAME: &str = "SHA256"; /// The name of the sha2-512 algorithm returned by [`FingerprintHash::name()`](enum.FingerprintHash.html#method.name) pub const SHA512_NAME: &str = "SHA512"; /// An enum representing the hash function used to generate fingerprint /// /// Used with [`PublicPart::fingerprin...
/// Serialize the keypair to the OpenSSL PKCS#8 PEM format /// /// If the passphrase is given (set to `Some(...)`), then the generated PKCS#8 key will be encrypted. pub fn serialize_pkcs8(&self, passphrase: Option<&str>) -> OsshResult<String> { serialize_pkcs8_privkey(self, passphrase) } ...
{ stringify_pem_privkey(self, passphrase) }
identifier_body
mod.rs
method.name) pub const SHA256_NAME: &str = "SHA256"; /// The name of the sha2-512 algorithm returned by [`FingerprintHash::name()`](enum.FingerprintHash.html#method.name) pub const SHA512_NAME: &str = "SHA512"; /// An enum representing the hash function used to generate fingerprint /// /// Used with [`PublicPart::fing...
SHA512, } impl FingerprintHash { fn hash(self, data: &[u8]) -> Vec<u8> { fn digest_hash<D>(hasher: &mut D, data: &[u8]) -> Vec<u8> where D: Digest + FixedOutputReset, { // Fix error[E0034]: multiple applicable items in scope Digest::update(hasher, dat...
SHA256,
random_line_split
mod.rs
.name) pub const SHA256_NAME: &str = "SHA256"; /// The name of the sha2-512 algorithm returned by [`FingerprintHash::name()`](enum.FingerprintHash.html#method.name) pub const SHA512_NAME: &str = "SHA512"; /// An enum representing the hash function used to generate fingerprint /// /// Used with [`PublicPart::fingerprin...
(inner: rsa::RsaPublicKey) -> PublicKey { PublicKey { key: PublicKeyType::RSA(inner), comment: String::new(), } } } impl From<dsa::DsaPublicKey> for PublicKey { fn from(inner: dsa::DsaPublicKey) -> PublicKey { PublicKey { key: PublicKeyType::DSA(inner...
from
identifier_name
mod.rs
(Construct, PlainText)] pub struct TextElem { /// A prioritized sequence of font families. /// /// When processing text, Typst tries all specified font families in order /// until it finds a font that has the necessary glyphs. In the example /// below, the font `Inria Serif` is preferred, but since ...
ngth) => length.resolve(styles), } } } cast! { TopEdge, self => match self { Self::Metric(metric) => metric.into_value(), Self::Length(length) => length.into_value(), }, v: TopEdgeMetric => Self::Metric(v), v: Length => Self::Length(v), } /// Metrics that describe the t...
ric) = metric.try_into() { font.metrics().vertical(metric).resolve(styles) } else { bbox.map(|bbox| (font.to_em(bbox.y_max)).resolve(styles)) .unwrap_or_default() } } TopEdge::Length(le
conditional_block
mod.rs
#[element(Construct, PlainText)] pub struct TextElem { /// A prioritized sequence of font families. /// /// When processing text, Typst tries all specified font families in order /// until it finds a font that has the necessary glyphs. In the example /// below, the font `Inria Serif` is preferred, b...
self => match self { Self::Metric(metric) => metric.into_value(), Self::Length(length) => length.into_value(), }, v: BottomEdgeMetric => Self::Metric(v), v: Length => Self::Length(v), } /// Metrics that describe the bottom edge of text. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, ...
} } cast! { BottomEdge,
random_line_split
mod.rs
(global: &mut Scope) { global.define("text", TextElem::func()); global.define("linebreak", LinebreakElem::func()); global.define("smartquote", SmartQuoteElem::func()); global.define("strong", StrongElem::func()); global.define("emph", EmphElem::func()); global.define("lower", lower_func()); ...
define
identifier_name
rust_gtest_interop.rs
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::pin::Pin; /// Use `prelude:::*` to get access to all macros defined in this crate. pub mod prelude { // The #[extern_test_suite("cplusplus::Type") macro. pub ...
pub use crate::expect_ge; pub use crate::expect_gt; pub use crate::expect_le; pub use crate::expect_lt; pub use crate::expect_ne; pub use crate::expect_true; } // The gtest_attribute proc-macro crate makes use of small_ctor, with a path // through this crate here to ensure it's available. #[doc...
random_line_split
rust_gtest_interop.rs
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::pin::Pin; /// Use `prelude:::*` to get access to all macros defined in this crate. pub mod prelude { // The #[extern_test_suite("cplusplus::Type") macro. pub ...
{ data: [u8; 0], marker: std::marker::PhantomData<(*mut u8, std::marker::PhantomPinned)>, } #[doc(hidden)] pub trait TestResult { fn into_error_message(self) -> Option<String>; } impl TestResult for () { fn into_error_message(self) -> Option<String> { None } } // This impl requires an `Err...
OpaqueTestingTest
identifier_name
rust_gtest_interop.rs
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::pin::Pin; /// Use `prelude:::*` to get access to all macros defined in this crate. pub mod prelude { // The #[extern_test_suite("cplusplus::Type") macro. pub ...
} // Internals used by code generated from the gtest-attriute proc-macro. Should // not be used by human-written code. #[doc(hidden)] pub mod __private { use super::{GtestFactoryFunction, OpaqueTestingTest, Pin}; /// Rust wrapper around the same C++ method. /// /// We have a wrapper to convert the fi...
{ match self { Ok(_) => None, Err(e) => Some(format!("Test returned error: {}", e.into())), } }
identifier_body
main.rs
//This project was inspired by https://github.com/jkusner/CACBarcode/blob/master/cacbarcode.py extern crate base_custom; use base_custom::BaseCustom; extern crate chrono; use chrono::prelude::*; extern crate time; use time::Duration; fn main() { if std::env::args().count() > 1 { println!("For security, the bar...
//Electronic Data Interchange Person Identifier (base 32) let edipi = data_chars.by_ref().take(7).collect::<String>(); out.push(("Electronic Data Interchange Person Identifier", base32.decimal(edipi).to_string())); //Personnel Category Code out.push(("Personnel Category Code", lookup_ppc(data_chars.next().un...
random_line_split
main.rs
//This project was inspired by https://github.com/jkusner/CACBarcode/blob/master/cacbarcode.py extern crate base_custom; use base_custom::BaseCustom; extern crate chrono; use chrono::prelude::*; extern crate time; use time::Duration; fn main() { if std::env::args().count() > 1 { println!("For security, the bar...
(data: String) -> String { let mut data_chars = data.chars(); let base32 = BaseCustom::<String>::new("0123456789ABCDEFGHIJKLMNOPQRSTUV", None); let mut out = Vec::new(); //(Key, Value) out.push(("Barcode type", "Code39".to_string())); //Version let version = data_chars.next().unwrap(); match version {...
decode_code39
identifier_name
main.rs
//This project was inspired by https://github.com/jkusner/CACBarcode/blob/master/cacbarcode.py extern crate base_custom; use base_custom::BaseCustom; extern crate chrono; use chrono::prelude::*; extern crate time; use time::Duration; fn main() { if std::env::args().count() > 1 { println!("For security, the bar...
fn decode_pdf217(data: String) -> String { let base32 = BaseCustom::<String>::new("0123456789ABCDEFGHIJKLMNOPQRSTUV", None); let base_time = Utc.ymd(1000, 1, 1); let mut data_chars = data.chars(); let mut out = Vec::new(); //(Key, Value) out.push(("Barcode type", "PDF217".to_string())); //Version l...
{ match data.len() { 18 => return decode_code39(data), 88 | 89 => return decode_pdf217(data), _ => return format!("Incorrect barcode length: {}. Make sure to include all spaces.", data.len()), } }
identifier_body
mod.rs
use crate::domain; use crate::ops; use crate::prelude::*; use petgraph; use std::collections::{HashMap, HashSet}; use std::ops::{Deref, DerefMut}; mod process; #[cfg(test)] pub(crate) use self::process::materialize; pub mod special; mod ntype; pub use self::ntype::NodeType; // crate viz for tests mod debug; // NOT...
ool { if let NodeType::Base(..) = self.inner { true } else { false } } pub fn is_union(&self) -> bool { if let NodeType::Internal(NodeOperator::Union(_)) = self.inner { true } else { false } } pub fn is_sha...
f) -> b
identifier_name
mod.rs
use crate::domain; use crate::ops; use crate::prelude::*; use petgraph; use std::collections::{HashMap, HashSet}; use std::ops::{Deref, DerefMut}; mod process; #[cfg(test)] pub(crate) use self::process::materialize; pub mod special; mod ntype; pub use self::ntype::NodeType; // crate viz for tests mod debug; // NOT...
is_shard_merger(&self) -> bool { if let NodeType::Internal(NodeOperator::Union(ref u)) = self.inner { u.is_shard_merger() } else { false } } }
let NodeType::Internal(NodeOperator::Union(_)) = self.inner { true } else { false } } pub fn
identifier_body
mod.rs
use crate::domain; use crate::ops; use crate::prelude::*; use petgraph; use std::collections::{HashMap, HashSet}; use std::ops::{Deref, DerefMut}; mod process; #[cfg(test)] pub(crate) use self::process::materialize; pub mod special; mod ntype; pub use self::ntype::NodeType; // crate viz for tests mod debug; // NOT...
children: Vec::new(), inner: inner.into(), taken: false, purge: false, sharded_by: Sharding::None, } } pub fn mirror<NT: Into<NodeType>>(&self, n: NT) -> Node { Self::new(&*self.name, &self.fields, n) } pub fn named_mirror<N...
index: None, domain: None, fields: fields.into_iter().map(|s| s.to_string()).collect(), parents: Vec::new(),
random_line_split
gdb_stub.rs
, &mut self.gba); if self.run_state == RunState::Running { let deadline = Instant::now() + Duration::from_millis(15); while Instant::now() < deadline { self.step_gba(); if let Some(stop_reason) = self.bus_snooper.stop_reason.take() { ...
WriteWatchpoint(u32), AccessWatchpoint(u32), Breakpoint(u32), Step, } impl StopReason { fn to_command(&self) -> Vec<u8> { let mut result = Vec::new(); match self { StopReason::ReadWatchpoint(addr) => write!(result, "T{:02}rwatch:{}", SIGTRAP, std::str::from_utf8(&int_to_...
#[derive(Debug)] enum StopReason { ReadWatchpoint(u32),
random_line_split
gdb_stub.rs
note!(GDB, "TcpListener accepted a connection from {}", addr); stream.set_nonblocking(!self.blocking)?; self.no_ack_mode = false; self.stream = Some(stream); } // Unwrapping because we ensured it's Some above let stream = self.stream.as_mut().unwrap(); ...
read16
identifier_name
gdb_stub.rs
self.no_ack_mode = false; self.stream = Some(stream); } // Unwrapping because we ensured it's Some above let stream = self.stream.as_mut().unwrap(); let mut bytes = [0u8; 1200]; let mut msg: &[u8]; if let Some(amount) = transpose_would_block(stream.read(&mu...
{ self.check_read(addr); self.delegate.read16(addr) }
identifier_body
declare.rs
/*! Functionality for declaring Objective-C classes. Classes can be declared using the `ClassDecl` struct. Instance variables and methods can then be added before the class is ultimately registered. # Example The following example demonstrates declaring a class named `MyNumber` that has one ivar, a `u32` named `_num...
/// Adds a requirement on another protocol. pub fn add_protocol(&mut self, proto: &Protocol) { unsafe { runtime::protocol_addProtocol(self.proto, proto); } } /// Registers self, consuming it and returning a reference to the /// newly registered `Protocol`. pub fn r...
{ self.add_method_description_common::<Args, Ret>(sel, is_required, false) }
identifier_body