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
stream.rs
use crate::{JsonRpcClient, Middleware, PinBoxFut, Provider, ProviderError}; use ethers_core::types::{Transaction, TxHash, U256}; use futures_core::stream::Stream; use futures_core::Future; use futures_util::stream::FuturesUnordered; use futures_util::{stream, FutureExt, StreamExt}; use pin_project::pin_project; use s...
<'a, P, R> { /// The filter's installed id on the ethereum node pub id: U256, provider: &'a Provider<P>, // The polling interval interval: Box<dyn Stream<Item = ()> + Send + Unpin>, state: FilterWatcherState<'a, R>, } impl<'a, P, R> FilterWatcher<'a, P, R> where P: JsonRpcClient, R: ...
FilterWatcher
identifier_name
lib.rs
//! This is an implementation the test factory pattern made to work with [Diesel][]. //! //! [Diesel]: https://diesel.rs //! //! Example usage: //! //! ``` //! #[macro_use] //! extern crate diesel; //! //! use diesel_factories::{Association, Factory}; //! use diesel::{pg::PgConnection, prelude::*}; //! //! // Tell Dies...
/// The primary key type your model uses. /// /// This will normally be i32 or i64 but can be whatever you need. type Id: Clone; /// The database connection type you use such as `diesel::pg::PgConnection`. type Connection; /// Insert the factory into the database. /// /// # Panics ...
type Model;
random_line_split
lib.rs
//! This is an implementation the test factory pattern made to work with [Diesel][]. //! //! [Diesel]: https://diesel.rs //! //! Example usage: //! //! ``` //! #[macro_use] //! extern crate diesel; //! //! use diesel_factories::{Association, Factory}; //! use diesel::{pg::PgConnection, prelude::*}; //! //! // Tell Dies...
} } } /// A generic factory trait. /// /// You shouldn't ever have to implement this trait yourself. It can be derived using /// `#[derive(Factory)]` /// /// See the [root module docs](/) for info on how to use `#[derive(Factory)]`. pub trait Factory: Clone { /// The model type the factory inserts. ...
{ let model = factory.clone().insert(con); F::id_for_model(&model).clone() }
conditional_block
lib.rs
//! This is an implementation the test factory pattern made to work with [Diesel][]. //! //! [Diesel]: https://diesel.rs //! //! Example usage: //! //! ``` //! #[macro_use] //! extern crate diesel; //! //! use diesel_factories::{Association, Factory}; //! use diesel::{pg::PgConnection, prelude::*}; //! //! // Tell Dies...
#[doc(hidden)] pub fn new_factory(inner: Factory) -> Self { Association::Factory(inner) } } impl<M, F> Association<'_, M, F> where F: Factory<Model = M> + Clone, { #[doc(hidden)] pub fn insert_returning_id(&self, con: &F::Connection) -> F::Id { match self { Associa...
{ Association::Model(inner) }
identifier_body
lib.rs
//! This is an implementation the test factory pattern made to work with [Diesel][]. //! //! [Diesel]: https://diesel.rs //! //! Example usage: //! //! ``` //! #[macro_use] //! extern crate diesel; //! //! use diesel_factories::{Association, Factory}; //! use diesel::{pg::PgConnection, prelude::*}; //! //! // Tell Dies...
(&self, con: &F::Connection) -> F::Id { match self { Association::Model(model) => F::id_for_model(&model).clone(), Association::Factory(factory) => { let model = factory.clone().insert(con); F::id_for_model(&model).clone() } } } } ...
insert_returning_id
identifier_name
test_util.rs
use crate::runtime::Runtime; use crate::{event::LogEvent, Event}; use futures::{compat::Stream01CompatExt, stream, SinkExt, Stream, StreamExt, TryStreamExt}; use futures01::{ future, stream as stream01, sync::mpsc, try_ready, Async, Future, Poll, Stream as Stream01, }; use openssl::ssl::{SslConnector, SslMethod, S...
async fn receive_lines_stream<S, T>( stream: S, count: Arc<AtomicUsize>, tripwire: oneshot::Receiver<()>, ) -> Vec<String> where S: Stream<Item = IoResult<T>>, T: AsyncWrite + AsyncRead, { stream .take_until(tripwire) .map_ok(|socke...
{ CountReceiver::new(|count, tripwire| async move { let mut listener = tokio::net::UnixListener::bind(path).unwrap(); CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await }) }
identifier_body
test_util.rs
use crate::runtime::Runtime; use crate::{event::LogEvent, Event}; use futures::{compat::Stream01CompatExt, stream, SinkExt, Stream, StreamExt, TryStreamExt}; use futures01::{ future, stream as stream01, sync::mpsc, try_ready, Async, Future, Poll, Stream as Stream01, }; use openssl::ssl::{SslConnector, SslMethod, S...
pub fn wait_for_tcp(addr: SocketAddr) { wait_for(|| std::net::TcpStream::connect(addr).is_ok()) } pub fn wait_for_atomic_usize<T, F>(val: T, unblock: F) where T: AsRef<AtomicUsize>, F: Fn(usize) -> bool, { let val = val.as_ref(); wait_for(|| unblock(val.load(Ordering::SeqCst))) } pub fn shutdown_o...
pub fn runtime() -> Runtime { Runtime::single_threaded().unwrap() }
random_line_split
test_util.rs
use crate::runtime::Runtime; use crate::{event::LogEvent, Event}; use futures::{compat::Stream01CompatExt, stream, SinkExt, Stream, StreamExt, TryStreamExt}; use futures01::{ future, stream as stream01, sync::mpsc, try_ready, Async, Future, Poll, Stream as Stream01, }; use openssl::ssl::{SslConnector, SslMethod, S...
( len: usize, breadth: usize, depth: usize, count: usize, ) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) { random_events_with_stream_generic(count, move || { let mut log = LogEvent::default(); let tree = random_pseudonested_map(len, breadth, depth); for (k, v) in...
random_nested_events_with_stream
identifier_name
test_util.rs
use crate::runtime::Runtime; use crate::{event::LogEvent, Event}; use futures::{compat::Stream01CompatExt, stream, SinkExt, Stream, StreamExt, TryStreamExt}; use futures01::{ future, stream as stream01, sync::mpsc, try_ready, Async, Future, Poll, Stream as Stream01, }; use openssl::ssl::{SslConnector, SslMethod, S...
} } pub struct CountReceiver<T> { count: Arc<AtomicUsize>, trigger: oneshot::Sender<()>, handle: JoinHandle<Vec<T>>, } impl<T: Send +'static> CountReceiver<T> { pub fn count(&self) -> usize { self.count.load(Ordering::Relaxed) } pub async fn wait(self) -> Vec<T> { let _ =...
{ panic!("Future already completed"); }
conditional_block
model.rs
use chrono::{DateTime, Utc}; use failure::{format_err, Error}; use serde::{Deserialize, Serialize}; use std::{borrow::Borrow, convert::TryFrom, fmt}; #[derive(Debug, Default)] pub struct Root { pub channel_url: Option<String>, pub cache_url: Option<String>, pub git_revision: Option<String>, pub fetch_t...
(&self) -> StorePathHash { StorePathHash( <[u8; StorePathHash::LEN]>::try_from( self.path[Self::STORE_PREFIX.len()..Self::SEP_POS].as_bytes(), ) .unwrap(), ) } pub fn name(&self) -> &str { &self.path[Self::SEP_POS + 1..] } } impl T...
hash
identifier_name
model.rs
use chrono::{DateTime, Utc}; use failure::{format_err, Error}; use serde::{Deserialize, Serialize}; use std::{borrow::Borrow, convert::TryFrom, fmt}; #[derive(Debug, Default)] pub struct Root { pub channel_url: Option<String>, pub cache_url: Option<String>, pub git_revision: Option<String>, pub fetch_t...
pub fn root(&self) -> &str { &Self::STORE_PREFIX[..Self::STORE_PREFIX.len() - 1] } pub fn hash_str(&self) -> &str { &self.path[Self::STORE_PREFIX.len()..Self::SEP_POS] } pub fn hash(&self) -> StorePathHash { StorePathHash( <[u8; StorePathHash::LEN]>::try_from(...
{ &self.path }
identifier_body
model.rs
use chrono::{DateTime, Utc}; use failure::{format_err, Error}; use serde::{Deserialize, Serialize}; use std::{borrow::Borrow, convert::TryFrom, fmt}; #[derive(Debug, Default)] pub struct Root { pub channel_url: Option<String>, pub cache_url: Option<String>, pub git_revision: Option<String>, pub fetch_t...
} } impl TryFrom<String> for StorePath { type Error = Error; // https://github.com/NixOS/nix/blob/abb8ef619ba2fab3ae16fb5b5430215905bac723/src/libstore/store-api.cc#L85 fn try_from(path: String) -> Result<Self, Self::Error> { use failure::ensure; fn is_valid_hash(s: &[u8]) -> bool { ...
} pub fn name(&self) -> &str { &self.path[Self::SEP_POS + 1..]
random_line_split
main.rs
, ObjectSymbol, SymbolKind, SymbolScope}; use std::env; use std::fs::File; use std::io::Cursor; use std::io::Read; use std::mem; #[derive(Debug)] struct ArtifactSummary<'a> { buffer: &'a Vec<u8>, obj: &'a object::File<'a>, symbols: StandardSymbols<'a>, data_segments: Option<DataSegments>, serialize...
} if!imported_symbols.is_empty() { println!(); println!(" Other imported symbols (from ELF headers):"); for import in &imported_symbols { println!(" {}", import); } } } fn print_summary(summary: ArtifactSummary<'_>) { println!("Required Symbols:"); ...
{ imported_symbols.remove(idx); }
conditional_block
main.rs
Section, ObjectSymbol, SymbolKind, SymbolScope}; use std::env; use std::fs::File; use std::io::Cursor; use std::io::Read; use std::mem; #[derive(Debug)] struct ArtifactSummary<'a> { buffer: &'a Vec<u8>, obj: &'a object::File<'a>, symbols: StandardSymbols<'a>, data_segments: Option<DataSegments>, se...
Some(name) => { println!(" ELF header name: {}", name); } None => { println!(" No corresponding ELF symbol."); } }; break; } let colorize_name = |x: Option<&str>| match ...
" Function {} {}", i, "is missing the module data part of its declaration".red() ); match header_name {
random_line_split
main.rs
, ObjectSymbol, SymbolKind, SymbolScope}; use std::env; use std::fs::File; use std::io::Cursor; use std::io::Read; use std::mem; #[derive(Debug)] struct ArtifactSummary<'a> { buffer: &'a Vec<u8>, obj: &'a object::File<'a>, symbols: StandardSymbols<'a>, data_segments: Option<DataSegments>, serialize...
<'a> { lucet_module: Option<object::read::Symbol<'a, 'a>>, } #[derive(Debug)] struct DataSegments { segments: Vec<DataSegment>, } #[derive(Debug)] struct DataSegment { offset: u32, len: u32, data: Vec<u8>, } impl<'a> ArtifactSummary<'a> { fn new(buffer: &'a Vec<u8>, obj: &'a object::File<'_>)...
StandardSymbols
identifier_name
vm.rs
8 { /// The current opcode. opcode: u16, /// The chip's 4096 bytes of memory. pub memory: [u8; 4096], // TEMPORARY pub for debug purposes /// The chip's 16 registers, from V0 to VF. /// VF is used for the 'carry flag'. v: [u8; 16], /// Index register. i: usize, /// Program counte...
fn subn_vx_vy(&mut self, x: u8, y: u8) { let new_vx_i8 = self.v[y as usize] as i8 - self.v[x as usize] as i8; self.v[x as usize] = new_vx_i8 as u8; self.v[FLAG] = if new_vx_i8 < 0 { 0x1 } else { 0x0 }; self.pc += 2; } /// Store the value of the register VY shifted right one ...
/// store the (wrapped) result in register VX. /// Set V_FLAG to 0x1 if a borrow occurs, and to 0x0 otherwise.
random_line_split
vm.rs
{ /// The current opcode. opcode: u16, /// The chip's 4096 bytes of memory. pub memory: [u8; 4096], // TEMPORARY pub for debug purposes /// The chip's 16 registers, from V0 to VF. /// VF is used for the 'carry flag'. v: [u8; 16], /// Index register. i: usize, /// Program counter...
(0x4, x, _, _) => self.sne_vx_nn(x, (op & 0x00FF) as u8), (0x5, x, y, 0x0) => self.se_vx_vy(x, y), (0x6, x, _, _) => self.ld_vx_nn(x, (op & 0x00FF) as u8), (0x7, x, _, _) => self.add_vx_nn(x, (op & 0x00FF) as u8), (0x8, x, y, 0x0) => self.ld_vx_vy(x, y), ...
{ // For easier matching, get the values (nibbles) A, B, C, D // if the opcode is 0xABCD. let opcode_tuple = ( ((op & 0xF000) >> 12) as u8, ((op & 0x0F00) >> 8) as u8, ((op & 0x00F0) >> 4) as u8, (op & 0x000F) as u8, ); //println!(...
identifier_body
vm.rs
{ /// The current opcode. opcode: u16, /// The chip's 4096 bytes of memory. pub memory: [u8; 4096], // TEMPORARY pub for debug purposes /// The chip's 16 registers, from V0 to VF. /// VF is used for the 'carry flag'. v: [u8; 16], /// Index register. i: usize, /// Program counter...
(&mut self, b: bool) { self.shift_op_use_vy = b; } /// Is the CPU waiting for a key press? pub fn is_waiting_for_key(&self) -> bool { self.wait_for_key.0 } /// Called by the emulator application to inform the virtual machine /// waiting for a key pressed that a key has been pre...
should_shift_op_use_vy
identifier_name
mod.rs
use md5; use rustc_serialize::hex::ToHex; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] enum Dir { Up, Down, Left, Right, } impl Dir { fn as_char(&self) -> char { match *self { Dir::Up => 'U', Dir::Down => 'D', Dir::Le...
(passcode: String) -> Maze { Maze { width: 4, height: 4, destination: Point { x: 3, y: 3 }, calculated: HashMap::new(), passcode: passcode, } } /// have we visited this room and had this set of doors before? fn have_visited(&mut se...
new
identifier_name
mod.rs
use md5; use rustc_serialize::hex::ToHex; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] enum Dir { Up, Down, Left, Right, } impl Dir { fn as_char(&self) -> char { match *self { Dir::Up => 'U', Dir::Down => 'D', Dir::Le...
// println!("Previous doors here {:?}", previous_door_sets_here); previous_door_sets_here.into_iter().any(|d| d.clone() == doors) } None => false, }; result } fn get_doors_for(&mut self, room: Point, path: Vec<Dir>) -> Vec<Dir> { i...
random_line_split
mod.rs
use md5; use rustc_serialize::hex::ToHex; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] enum Dir { Up, Down, Left, Right, } impl Dir { fn as_char(&self) -> char { match *self { Dir::Up => 'U', Dir::Down => 'D', Dir::Le...
fn find_longest_route(&self, pos: Point, path: &Vec<Dir>, steps: usize) -> usize { // based on the nicely elegant C solution by GitHub user rhardih let doors = open_doors_here(&self.passcode, path); let mut longest = 0; let can_up = doors.contains(&Dir::Up) &&!self.is_wall(pos.clo...
{ let room = self.calculated.get(&self.destination); match room { None => Vec::new(), Some(r) => r.keys().cloned().collect(), } }
identifier_body
main.rs
<<<<<<< HEAD /* * word correction * * Reads text from the corpus text and * Count the frequency of each word, then correct the candidate word in input text, output with the most frequetly * used one * * Background * * The purpose of correct is to find possible corrections for misspelled words. It consists of two pha...
if let Some(currtrie) = trie.children.get(&curchar){ let counter = 0; cur.push(curchar); <<<<<<< HEAD ======= >>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0728eca04f0 temp = find(currtrie,path,&mut temppath,cur,counter)...
temppath = pathclone.clone(); temppath.remove(0); curchar = temppath.remove(0); if let Some(currtrie) = trie.children.get(&curchar){ let counter = op-1; cur.push(curchar); <<<<<<< HEAD ======= >>>>>>> 7a6cdabd1d54f8ce2e0980b7aae2d0...
conditional_block
main.rs
<<<<<<< HEAD /* * word correction * * Reads text from the corpus text and * Count the frequency of each word, then correct the candidate word in input text, output with the most frequetly * used one * * Background * * The purpose of correct is to find possible corrections for misspelled words. It consists of two pha...
* * Input : trie: The trie made from corpus.txt, contains all the word * path: The misspelled word * pathclone: The remained string need to match * cur: The trie path * op: The edit times left for current matching * * The stop condition is that current trie path consist a word and match...
* This is the main search function for this program. We implement the DFS(Depth-First-Search)+Regression * Algorithm to travel the whole trie and find all the candidate word, then pick the most frequently one.
random_line_split
main.rs
<<<<<<< HEAD /* * word correction * * Reads text from the corpus text and * Count the frequency of each word, then correct the candidate word in input text, output with the most frequetly * used one * * Background * * The purpose of correct is to find possible corrections for misspelled words. It consists of two pha...
} cur.pop(); } //deletion //if we can get a word after deleting current character if op > 0{ if pathclone.len()==1 && trie.value>0{ temp= Result{ value: trie.value, ...
n()==0 && trie.value>0 { return Result{ value: trie.value, key: cur.clone(), } } else{ let mut max= Result::new(); let mut temp: Result; let mut temppath =pathclone.clone(); let mut currtrie :&Trie; if pathclone.len()>0{ let mut curchar = tempp...
identifier_body
main.rs
<<<<<<< HEAD /* * word correction * * Reads text from the corpus text and * Count the frequency of each word, then correct the candidate word in input text, output with the most frequetly * used one * * Background * * The purpose of correct is to find possible corrections for misspelled words. It consists of two pha...
h: & String,pathclone: & mut String,cur: & mut String, op: i64)-> Result{ if pathclone.len()==0 && trie.value>0 { return Result{ value: trie.value, key: cur.clone(), } } else{ let mut max= Result::new(); let mut temp: Result; let mut temppath =pathclone.clone(); let mut c...
pat
identifier_name
lisplike.rs
extern mod std; use std::hashmap::HashMap; use std::to_str::ToStr; use std::rc::Rc; use std::io::stdio::{print, println}; use sexpr; // A very simple LISP-like language // Globally scoped, no closures /// Our value types #[deriving(Clone)] pub enum LispValue { List(~[LispValue]), Atom(~str), Str(~str), Num(f64), ...
#[test] fn test_eval_fn() { let mut symt = Rc::new(new_symt()); init_std(symt); assert_eq!(eval(symt, read("(eval 1)")), ~Num(1.0)); assert_eq!(eval(symt, read("(eval \"hi\")")), ~Str(~"hi")); assert_eq!(eval(symt, read("(eval (quote (+ 1 2)))")), ~Num(3.0)); assert_eq!(eval(symt, read("(eval (quote ( (...
{ let mut symt = Rc::new(new_symt()); init_std(symt); eval(symt, read("(def fac (fn (n) (cond ((= n 0) 1) (true (* n (fac (- n 1)))))))")); assert_eq!(eval(symt, read("(fac 10)")), ~Num(3628800.0)); }
identifier_body
lisplike.rs
extern mod std; use std::hashmap::HashMap; use std::to_str::ToStr; use std::rc::Rc; use std::io::stdio::{print, println}; use sexpr; // A very simple LISP-like language // Globally scoped, no closures /// Our value types #[deriving(Clone)] pub enum LispValue { List(~[LispValue]), Atom(~str), Str(~str), Num(f64), ...
() -> SymbolTable { HashMap::new() } /// Binds a symbol in the symbol table. Replaces if it already exists. pub fn bind(symt: Rc<SymbolTable>, name: ~str, value: ~LispValue) { symt.borrow().insert(name, value); } /// Look up a symbol in the symbol table. Fails if not found. pub fn lookup(symt: Rc<SymbolTable>, name...
new_symt
identifier_name
lisplike.rs
extern mod std; use std::hashmap::HashMap; use std::to_str::ToStr; use std::rc::Rc; use std::io::stdio::{print, println}; use sexpr; // A very simple LISP-like language // Globally scoped, no closures /// Our value types #[deriving(Clone)] pub enum LispValue { List(~[LispValue]), Atom(~str), Str(~str), Num(f64), ...
// XXX: this is ugly but it won't automatically derive Eq because of the extern fn impl Eq for LispValue { fn eq(&self, other: &LispValue) -> bool { match (self.clone(), other.clone()) { (BIF(ref x, _, _, _), BIF(ref y, _, _, _)) if *x == *y => true, (Str(ref x), Str(ref y)) if *x == *y => true, (Num(ref x...
}
random_line_split
apply.rs
use crate::{ patch::{Hunk, Line, Patch}, utils::LineIter, }; use std::collections::VecDeque; use std::{fmt, iter}; /// An error returned when [`apply`]ing a `Patch` fails /// /// [`apply`]: fn.apply.html #[derive(Debug)] pub struct ApplyError(usize); impl fmt::Display for ApplyError { fn fmt(&self, f: &mu...
; // If any of these lines have already been patched then we can't match at this position if image.iter().any(ImageLine::is_patched) { return false; } pre_image(lines).eq(image.iter().map(ImageLine::inner)) } #[derive(Debug)] struct Interleave<I, J> { a: iter::Fuse<I>, b: iter::Fuse<J...
{ return false; }
conditional_block
apply.rs
use crate::{ patch::{Hunk, Line, Patch}, utils::LineIter, }; use std::collections::VecDeque; use std::{fmt, iter}; /// An error returned when [`apply`]ing a `Patch` fails /// /// [`apply`]: fn.apply.html #[derive(Debug)] pub struct ApplyError(usize); impl fmt::Display for ApplyError { fn fmt(&self, f: &mu...
(&mut self) -> Option<I::Item> { self.flag =!self.flag; if self.flag { match self.a.next() { None => self.b.next(), item => item, } } else { match self.b.next() { None => self.a.next(), item => it...
next
identifier_name
apply.rs
use crate::{ patch::{Hunk, Line, Patch}, utils::LineIter, }; use std::collections::VecDeque; use std::{fmt, iter}; /// An error returned when [`apply`]ing a `Patch` fails /// /// [`apply`]: fn.apply.html #[derive(Debug)] pub struct ApplyError(usize); impl fmt::Display for ApplyError { fn fmt(&self, f: &mu...
fn into_inner(self) -> &'a T { self.inner() } fn is_patched(&self) -> bool { match self { ImageLine::Unpatched(_) => false, ImageLine::Patched(_) => true, } } } impl<T:?Sized> Copy for ImageLine<'_, T> {} impl<T:?Sized> Clone for ImageLine<'_, T> { ...
{ match self { ImageLine::Unpatched(inner) | ImageLine::Patched(inner) => inner, } }
identifier_body
apply.rs
use crate::{ patch::{Hunk, Line, Patch}, utils::LineIter, }; use std::collections::VecDeque; use std::{fmt, iter}; /// An error returned when [`apply`]ing a `Patch` fails /// /// [`apply`]: fn.apply.html #[derive(Debug)] pub struct ApplyError(usize); impl fmt::Display for ApplyError { fn fmt(&self, f: &mu...
} /// Apply a non-utf8 `Patch` to a base image pub fn apply_bytes(base_image: &[u8], patch: &Patch<'_, [u8]>) -> Result<Vec<u8>, ApplyError> { let mut image: Vec<_> = LineIter::new(base_image) .map(ImageLine::Unpatched) .collect(); for (i, hunk) in patch.hunks().iter().enumerate() { appl...
random_line_split
memory.rs
//! Interface with Screeps' `Memory` global variable //! //! Screeps' memory lives in the javascript `Memory` global variable and is //! encoded as a javascript object. This object's reference is tracked within //! rust as a `MemoryReference`. The [`root`] function gives access to a //! reference to the `Memory` global...
return _.get(@{self.as_ref()}, @{path}); }) .try_into() } /// Get a dictionary value or create it if it does not exist. /// /// If the value exists but is a different type, this will return `None`. pub fn dict_or_create(&self, key: &str) -> Result<MemoryReference, Unexpec...
random_line_split
memory.rs
//! Interface with Screeps' `Memory` global variable //! //! Screeps' memory lives in the javascript `Memory` global variable and is //! encoded as a javascript object. This object's reference is tracked within //! rust as a `MemoryReference`. The [`root`] function gives access to a //! reference to the `Memory` global...
else { Some(val.try_into()).transpose() } } pub fn set<T>(&self, key: &str, value: T) where T: JsSerialize, { js! { @(no_return) (@{self.as_ref()})[@{key}] = @{value}; } } pub fn path_set<T>(&self, path: &str, value: T) where ...
{ Ok(None) }
conditional_block
memory.rs
//! Interface with Screeps' `Memory` global variable //! //! Screeps' memory lives in the javascript `Memory` global variable and is //! encoded as a javascript object. This object's reference is tracked within //! rust as a `MemoryReference`. The [`root`] function gives access to a //! reference to the `Memory` global...
(&self, key: &str) -> Result<Option<f64>, ConversionError> { (js! { return (@{self.as_ref()})[@{key}]; }) .try_into() } pub fn path_f64(&self, path: &str) -> Result<Option<f64>, ConversionError> { (js! { return _.get(@{self.as_ref()}, @{path}); }) ...
f64
identifier_name
memory.rs
//! Interface with Screeps' `Memory` global variable //! //! Screeps' memory lives in the javascript `Memory` global variable and is //! encoded as a javascript object. This object's reference is tracked within //! rust as a `MemoryReference`. The [`root`] function gives access to a //! reference to the `Memory` global...
pub fn path_arr<T>(&self, path: &str) -> Result<Option<Vec<T>>, ConversionError> where T: TryFrom<Value, Error = ConversionError>, { (js! { return _.get(@{self.as_ref()}, @{path}); }) .try_into() } } impl TryFrom<Value> for MemoryReference { type Error =...
{ (js! { return (@{self.as_ref()})[@{key}]; }) .try_into() }
identifier_body
rsa-fdh-vrf.rs
// This crate implements RSA-FDH-VRF based on section 4 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/ // The ciphersuite is RSA-FDH-VRF-SHA256, suite string can be changed if other hash function is desired // The step comments refer to the corresponding steps in the IETF pseudocode for comparison with hacspe...
// STEP 1 and 2 let hash_string = SUITE_STRING.concat(&TWO.concat(pi_string)); // STEP 3 ByteSeqResult::Ok(sha256(&hash_string).slice(0,32)) } // Based on section 4.3 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/ pub fn verify(pk: PK, alpha: &ByteSeq, pi_string: &ByteSeq) -> ByteSeqResult {...
} // Based on section 4.2 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/ pub fn proof_to_hash(pi_string: &ByteSeq) -> ByteSeqResult {
random_line_split
rsa-fdh-vrf.rs
// This crate implements RSA-FDH-VRF based on section 4 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/ // The ciphersuite is RSA-FDH-VRF-SHA256, suite string can be changed if other hash function is desired // The step comments refer to the corresponding steps in the IETF pseudocode for comparison with hacspe...
(sk: SK, alpha: &ByteSeq) -> ByteSeqResult { let (n, _d) = sk.clone(); // STEP 1 and 2 let em = vrf_mgf1(n, alpha)?; // STEP 3 let m = os2ip(&em); // STEP 4 let s = rsasp1(sk, m)?; // STEP 5 and 6 i2osp(s, BYTE_SIZE) } // Based on section 4.2 of https://datatracker.ietf.org/doc/...
prove
identifier_name
rsa-fdh-vrf.rs
// This crate implements RSA-FDH-VRF based on section 4 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/ // The ciphersuite is RSA-FDH-VRF-SHA256, suite string can be changed if other hash function is desired // The step comments refer to the corresponding steps in the IETF pseudocode for comparison with hacspe...
// Based on section 4.3 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/ pub fn verify(pk: PK, alpha: &ByteSeq, pi_string: &ByteSeq) -> ByteSeqResult { let (n, _e) = pk.clone(); // STEP 1 let s = os2ip(pi_string); // STEP 2 let m = rsavp1(pk, s)?; // STEP 3 and 4 let em_prime = ...
{ // STEP 1 and 2 let hash_string = SUITE_STRING.concat(&TWO.concat(pi_string)); // STEP 3 ByteSeqResult::Ok(sha256(&hash_string).slice(0,32)) }
identifier_body
rsa-fdh-vrf.rs
// This crate implements RSA-FDH-VRF based on section 4 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-vrf/ // The ciphersuite is RSA-FDH-VRF-SHA256, suite string can be changed if other hash function is desired // The step comments refer to the corresponding steps in the IETF pseudocode for comparison with hacspe...
else { ByteSeqResult::Err(Error::VerificationFailed) } } #[cfg(test)] mod tests { use super::*; use num_bigint::{BigInt,Sign}; use glass_pumpkin::prime; use quickcheck::*; // RSA key generation // Taken from https://asecuritysite.com/rust/rsa01/ fn modinv(a0: BigInt, m0: Big...
{ proof_to_hash(pi_string) }
conditional_block
game.rs
#[cfg(feature = "hot-reload")] use crate::assets::HotReloader; use crate::config::AudioConfig; use crate::core::audio::AudioSystem; use crate::core::camera::{Camera, ProjectionMatrix}; use crate::core::input::{Input, InputAction}; use crate::core::random::{RandomGenerator, Seed}; use crate::core::scene::{Scene, SceneSt...
(mut self) -> Game<'a, A> { let renderer = Renderer::new(self.surface, &self.gui_context); // Need some input :D let input: Input<A> = { let (key_mapping, btn_mapping) = self .input_config .unwrap_or((A::get_default_key_mapping(), A::get_default_mouse_ma...
build
identifier_name
game.rs
#[cfg(feature = "hot-reload")] use crate::assets::HotReloader; use crate::config::AudioConfig; use crate::core::audio::AudioSystem; use crate::core::camera::{Camera, ProjectionMatrix}; use crate::core::input::{Input, InputAction}; use crate::core::random::{RandomGenerator, Seed}; use crate::core::scene::{Scene, SceneSt...
let scene_result = if let Some(scene) = self.scene_stack.current_mut() { let scene_res = scene.update(dt, &mut self.world, &self.resources); { let chan = self.resources.fetch::<EventChannel<GameEvent>>().unwrap(); for ev in chan.read(&...
random_line_split
game.rs
#[cfg(feature = "hot-reload")] use crate::assets::HotReloader; use crate::config::AudioConfig; use crate::core::audio::AudioSystem; use crate::core::camera::{Camera, ProjectionMatrix}; use crate::core::input::{Input, InputAction}; use crate::core::random::{RandomGenerator, Seed}; use crate::core::scene::{Scene, SceneSt...
pub fn build(mut self) -> Game<'a, A> { let renderer = Renderer::new(self.surface, &self.gui_context); // Need some input :D let input: Input<A> = { let (key_mapping, btn_mapping) = self .input_config .unwrap_or((A::get_default_key_mapping(), A::ge...
{ self.seed = Some(seed); self }
identifier_body
mod.rs
//! Utilities for handling shell surfaces with the `wl_shell` protocol //! //! This module provides automatic handling of shell surfaces objects, by being registered //! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`, //! thus this module is provided as a compatibility layer wit...
/// Send a ping request to this shell surface /// /// You'll receive the reply as a [`ShellRequest::Pong`] request /// /// A typical use is to start a timer at the same time you send this ping /// request, and cancel it when you receive the pong. If the timer runs /// down to 0 before a po...
{ if self.alive() { Some(&self.wl_surface) } else { None } }
identifier_body
mod.rs
//! Utilities for handling shell surfaces with the `wl_shell` protocol //! //! This module provides automatic handling of shell surfaces objects, by being registered //! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`, //! thus this module is provided as a compatibility layer wit...
<R> { wl_surface: wl_surface::WlSurface, shell_surface: wl_shell_surface::WlShellSurface, token: CompositorToken<R>, } impl<R> ShellSurface<R> where R: Role<ShellSurfaceRole> +'static, { /// Is the shell surface referred by this handle still alive? pub fn alive(&self) -> bool { self.she...
ShellSurface
identifier_name
mod.rs
//! Utilities for handling shell surfaces with the `wl_shell` protocol //! //! This module provides automatic handling of shell surfaces objects, by being registered //! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`, //! thus this module is provided as a compatibility layer wit...
else { Err(()) } } /// Send a configure event to this toplevel surface to suggest it a new configuration pub fn send_configure(&self, size: (u32, u32), edges: wl_shell_surface::Resize) { self.shell_surface.configure(edges, size.0 as i32, size.1 as i32) } /// Signal a p...
{ self.shell_surface.ping(serial); Ok(()) }
conditional_block
mod.rs
//! Utilities for handling shell surfaces with the `wl_shell` protocol //! //! This module provides automatic handling of shell surfaces objects, by being registered //! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`, //! thus this module is provided as a compatibility layer wit...
/// /// You'll receive the reply as a [`ShellRequest::Pong`] request /// /// A typical use is to start a timer at the same time you send this ping /// request, and cancel it when you receive the pong. If the timer runs /// down to 0 before a pong is received, mark the client as unresponsive. ...
} /// Send a ping request to this shell surface
random_line_split
edid.rs
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Implementation of the EDID specification provided by software. //! EDID spec: <https://glenwing.github.io/docs/VESA-EEDID-A2.pdf> use std::fmt; use std::fmt::Debug; use...
fn calculate_checksum(edid: &mut [u8]) { let mut checksum: u8 = 0; for byte in edid.iter().take(EDID_DATA_LENGTH - 1) { checksum = checksum.wrapping_add(*byte); } if checksum!= 0 { checksum = 255 - checksum + 1; } edid[127] = checksum; }
{ edid[18] = 1; edid[19] = 4; }
identifier_body
edid.rs
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Implementation of the EDID specification provided by software. //! EDID spec: <https://glenwing.github.io/docs/VESA-EEDID-A2.pdf> use std::fmt; use std::fmt::Debug; use...
(width: u32, height: u32) -> Resolution { Resolution { width, height } } fn get_aspect_ratio(&self) -> (u32, u32) { let divisor = gcd(self.width, self.height); (self.width / divisor, self.height / divisor) } } fn gcd(x: u32, y: u32) -> u32 { match y { 0 => x, _ ...
new
identifier_name
edid.rs
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Implementation of the EDID specification provided by software. //! EDID spec: <https://glenwing.github.io/docs/VESA-EEDID-A2.pdf> use std::fmt; use std::fmt::Debug; use...
} } fn populate_display_name(edid_block: &mut [u8]) { // Display Product Name String Descriptor Tag edid_block[0..5].clone_from_slice(&[0x00, 0x00, 0x00, 0xFC, 0x00]); edid_block[5..].clone_from_slice("CrosvmDisplay".as_bytes()); } fn populate_detailed_timing(edid_block: &mut [u8], info: &DisplayInfo)...
calculate_checksum(&mut edid); Ok(OkEdid(Self { bytes: edid }))
random_line_split
edid.rs
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Implementation of the EDID specification provided by software. //! EDID spec: <https://glenwing.github.io/docs/VESA-EEDID-A2.pdf> use std::fmt; use std::fmt::Debug; use...
edid[127] = checksum; }
{ checksum = 255 - checksum + 1; }
conditional_block
off.rs
use petgraph::{graph::NodeIndex, visit::Dfs, Graph}; use std::{collections::HashMap, io::Result, path::Path, str::FromStr}; use super::{Abstract, Concrete, Element, ElementList, Point, Polytope, RankVec}; /// Gets the name for an element with a given rank. fn element_name(rank: isize) -> String { match super::ELE...
a>( num: usize, dim: usize, toks: &mut impl Iterator<Item = &'a str>, ) -> Vec<Point> { // Reads all vertices. let mut vertices = Vec::with_capacity(num); // Add each vertex to the vector. for _ in 0..num { let mut vert = Vec::with_capacity(dim); for _ in 0..dim { ...
rse_vertices<'
identifier_name
off.rs
use petgraph::{graph::NodeIndex, visit::Dfs, Graph}; use std::{collections::HashMap, io::Result, path::Path, str::FromStr}; use super::{Abstract, Concrete, Element, ElementList, Point, Polytope, RankVec}; /// Gets the name for an element with a given rank. fn element_name(rank: isize) -> String { match super::ELE...
/// A set of options to be used when saving the OFF file. #[derive(Clone, Copy)] pub struct OffOptions { /// Whether the OFF file should have comments specifying each face type. pub comments: bool, } impl Default for OffOptions { fn default() -> Self { OffOptions { comments: true } } } fn writ...
Ok(from_src(String::from_utf8(std::fs::read(fp)?).unwrap())) }
identifier_body
off.rs
use petgraph::{graph::NodeIndex, visit::Dfs, Graph}; use std::{collections::HashMap, io::Result, path::Path, str::FromStr}; use super::{Abstract, Concrete, Element, ElementList, Point, Polytope, RankVec}; /// Gets the name for an element with a given rank. fn element_name(rank: isize) -> String { match super::ELE...
else if c == '\n' { comment = false; } comment || c.is_whitespace() }) .filter(|s|!s.is_empty()) } /// Reads the next integer or float from the OFF file. fn next_tok<'a, T>(toks: &mut impl Iterator<Item = &'a str>) -> T where T: FromStr, <T as FromStr>::Err: std::fmt::Debug,...
{ comment = true; }
conditional_block
off.rs
use petgraph::{graph::NodeIndex, visit::Dfs, Graph}; use std::{collections::HashMap, io::Result, path::Path, str::FromStr}; use super::{Abstract, Concrete, Element, ElementList, Point, Polytope, RankVec}; /// Gets the name for an element with a given rank. fn element_name(rank: isize) -> String { match super::ELE...
// Reads all sub-elements of the d-element. for _ in 0..el_sub_num { let el_sub = toks.next().expect("OFF file ended unexpectedly."); subs.push(el_sub.parse().expect("Integer parsing failed!")); } els_subs.push(Element { subs }); } els_subs } /// Build...
let el_sub_num = next_tok(toks); let mut subs = Vec::with_capacity(el_sub_num);
random_line_split
lib.rs
/*! # Strip MapMaking library Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur facilisis consectetur arcu. Etiam semper, sem sit amet lacinia dignissim, mauris eros rutrum massa, a imperdiet orci urna vel elit. Nulla at sagittis lacus. Curabitur eu gravida turpis. Mauris blandit porta orci. Aliquam f...
pub fn get_pix(&self) -> &Vec<Vec<i32>> { &self.pix } pub fn get_tod(&self) -> &Vec<Vec<f32>> { &self.tod } } // Mitigation of the systematic effects // Starting from the binning, to the // implementation of a de_noise model impl <'a> Obs <'a>{ pub fn binning(&self) -> (Vec<f32>, ...
{ &self.mc_id }
identifier_body
lib.rs
/*! # Strip MapMaking library Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur facilisis consectetur arcu. Etiam semper, sem sit amet lacinia dignissim, mauris eros rutrum massa, a imperdiet orci urna vel elit. Nulla at sagittis lacus. Curabitur eu gravida turpis. Mauris blandit porta orci. Aliquam f...
(&self) -> &Vec<Vec<i32>> { &self.pix } pub fn get_tod(&self) -> &Vec<Vec<f32>> { &self.tod } } // Mitigation of the systematic effects // Starting from the binning, to the // implementation of a de_noise model impl <'a> Obs <'a>{ pub fn binning(&self) -> (Vec<f32>, Vec<i32>) { ...
get_pix
identifier_name
lib.rs
/*! # Strip MapMaking library Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur facilisis consectetur arcu. Etiam semper, sem sit amet lacinia dignissim, mauris eros rutrum massa, a imperdiet orci urna vel elit. Nulla at sagittis lacus. Curabitur eu gravida turpis. Mauris blandit porta orci. Aliquam f...
} return Obs { start, stop, detector, mc_id, alpha, f_knee, pix, tod: tod_final, sky_t: sky, phantom: PhantomData, ...
tod_final.push(tmp);
random_line_split
bindings.rs
//! Setting up and responding to user defined key/mouse bindings use crate::{ core::{State, Xid}, pure::geometry::Point, x::XConn, Error, Result, }; #[cfg(feature = "keysyms")] use penrose_keysyms::XKeySym; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::{collections::HashMap, co...
} /// The types of mouse events represented by a MouseEvent #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum MouseEventKind { /// A button was pressed Press, /// A button was released Release, /// The mouse was moved while a...
{ self.button.into() }
identifier_body
bindings.rs
//! Setting up and responding to user defined key/mouse bindings use crate::{ core::{State, Xid}, pure::geometry::Point, x::XConn, Error, Result, }; #[cfg(feature = "keysyms")] use penrose_keysyms::XKeySym; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::{collections::HashMap, co...
self.button.into() } } /// The types of mouse events represented by a MouseEvent #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum MouseEventKind { /// A button was pressed Press, /// A button was released Release, ...
random_line_split
bindings.rs
//! Setting up and responding to user defined key/mouse bindings use crate::{ core::{State, Xid}, pure::geometry::Point, x::XConn, Error, Result, }; #[cfg(feature = "keysyms")] use penrose_keysyms::XKeySym; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::{collections::HashMap, co...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("KeyEventHandler").finish() } } impl<F, X> MouseEventHandler<X> for F where F: FnMut(&MouseEvent, &mut State<X>, &X) -> Result<()>, X: XConn, { fn call(&mut self, evt: &MouseEvent, state: &mut State<X>, x: &X) -> Result<()> { ...
fmt
identifier_name
pack.rs
.map(|s| PackId::Pack(s.to_owned())) } fn is_valid(s: &str) -> bool { s.chars() .all(|c| c.is_ascii_alphanumeric() || EXTRA_ID_CHARS.contains(&c)) } } impl FromStr for PackId { type Err = IdError; fn from_str(s: &str) -> Result<Self, Self::Err> { if!PackId::is_v...
Ok(()) } /// Writes the object to the specified path, taking care /// of adjusting file permissions. fn write_object(buf: &[u8], path: &Path) -> Result<(), Error> { fs::create_dir_all(path.parent().unwrap())?; let mut f = File::create(path)?; f.write_all(buf)?; Ok(()) } /// Returns a list of the ...
{ return Err(PackError::ChecksumMismatch(*exp_checksum, checksum).into()); }
conditional_block
pack.rs
.map(|s| PackId::Pack(s.to_owned())) } fn is_valid(s: &str) -> bool { s.chars() .all(|c| c.is_ascii_alphanumeric() || EXTRA_ID_CHARS.contains(&c)) } } impl FromStr for PackId { type Err = IdError; fn from_str(s: &str) -> Result<Self, Self::Err> { if!PackId::is_v...
(frames: &[PackFrame]) -> Vec<u64> { let mut frame_offsets: Vec<_> = vec![0; frames.len()]; for i in 1..frame_offsets.len() { frame_offsets[i] = frames[i - 1].frame_size + frame_offsets[i - 1]; } frame_offsets } /// Returns a list of the data offsets, computed using the order and /// decompress...
compute_frame_offsets
identifier_name
pack.rs
Result<Self, Self::Err> { if let Some((pack, snapshot)) = s.trim_end().rsplit_once(':') { if pack.is_empty() { return Err(IdError::InvalidPack(pack.to_owned())); } if snapshot.is_empty() { return Err(IdError::InvalidSnapshot(snapshot.to_owned(...
assert!(!PackId::is_valid("Some Text")); // non-latin alphabets assert!(!PackId::is_valid("това-е-тест"));
random_line_split
mod.rs
//! This module is an attempt to provide a friendly, rust-esque interface to Apple's Audio Unit API. //! //! Learn more about the Audio Unit API [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40003278-CH1-...
EffectType, FormatConverterType, GeneratorType, IOType, MixerType, MusicDeviceType, Type, }; #[cfg(target_os = "macos")] pub mod macos_helpers; pub mod audio_format; pub mod render_callback; pub mod sample_format; pub mod stream_format; pub mod types; /// The input and output **Scope**s. /// /// More info [here]...
pub use self::audio_format::AudioFormat; pub use self::sample_format::{Sample, SampleFormat}; pub use self::stream_format::StreamFormat; pub use self::types::{
random_line_split
mod.rs
//! This module is an attempt to provide a friendly, rust-esque interface to Apple's Audio Unit API. //! //! Learn more about the Audio Unit API [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40003278-CH1-...
{ // The audio buffer list to which input data is rendered. buffer_list: *mut sys::AudioBufferList, callback: *mut render_callback::InputProcFnWrapper, } macro_rules! try_os_status { ($expr:expr) => { Error::from_os_status($expr)? }; } impl AudioUnit { /// Construct a new AudioUnit wi...
InputCallback
identifier_name
mod.rs
//! This module is an attempt to provide a friendly, rust-esque interface to Apple's Audio Unit API. //! //! Learn more about the Audio Unit API [here](https://developer.apple.com/library/mac/documentation/MusicAudio/Conceptual/AudioUnitProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40003278-CH1-...
/// Return the current input Stream Format for the AudioUnit. pub fn input_stream_format(&self) -> Result<StreamFormat, Error> { self.stream_format(Scope::Input) } } unsafe impl Send for AudioUnit {} impl Drop for AudioUnit { fn drop(&mut self) { unsafe { use crate::error; ...
self.stream_format(Scope::Output) }
identifier_body
diagnostics.rs
#![warn( clippy::print_stdout, clippy::unimplemented, clippy::doc_markdown, clippy::items_after_statements, clippy::match_same_arms, clippy::similar_names, clippy::single_match_else, clippy::use_self, clippy::use_debug )] //! The diagnostics object controls the output of warnings an...
let (start_term_pos, end_term_pos) = line_fmt.actual_columns(&faulty_part_of_line).unwrap(); let term_width = end_term_pos - start_term_pos; num_fmt.spaces(output.writer())?; { let mut output = ColorOutput::new(ou...
// - unwrap(.): both positions are guranteed to exist in the line since we just // got them from the faulty line, which is a subset of the whole error line
random_line_split
diagnostics.rs
#![warn( clippy::print_stdout, clippy::unimplemented, clippy::doc_markdown, clippy::items_after_statements, clippy::match_same_arms, clippy::similar_names, clippy::single_match_else, clippy::use_self, clippy::use_debug )] //! The diagnostics object controls the output of warnings an...
(line: &'span Span<'file>) -> Self { Self { line } } fn render(&self, writer: &mut dyn WriteColor) -> Result<(), Error> { let mut output = ColorOutput::new(writer); // TODO: implement an iterator let chars = self.line.start_position().iter(); for position in chars { ...
new
identifier_name
diagnostics.rs
#![warn( clippy::print_stdout, clippy::unimplemented, clippy::doc_markdown, clippy::items_after_statements, clippy::match_same_arms, clippy::similar_names, clippy::single_match_else, clippy::use_self, clippy::use_debug )] //! The diagnostics object controls the output of warnings an...
let mut actual_column = 0; for position in chars { if position.column() == col { break; } actual_column += self.render_char(position.chr()).0.len(); } Some(actual_column) } fn render_char(&self, chr: char) -> (String, Optio...
{ // TODO: get rid of this nonsense // NOTE: it would actually be nice to condition the Position on the Line // instead of AsciiFile. Thinking of this, we could actually just do // `AsciiFile::new((span.as_str().as_bytes()))`. Meaning AsciiFile is // not a file, but a View ...
identifier_body
tags.rs
//! Constants for commonly used tags in TIFF files, baseline //! or extended. //! //! Check the [Tiff Tag Reference](https://www.awaresystems.be/imaging/tiff/tifftags.html) //! for more information on each tag. #![allow(non_upper_case_globals)] /// 16-bit identifier of a field entry. pub type FieldTag = u16; // pub c...
pub const FocalPlaneResolutionUnit: u16 = 0xa210; //Type.Short pub const FocalLengthIn35mmFilm: u16 = 0xa405; //Type.Short pub const EXIFPhotoBodySerialNumber: u16 = 0xa431; //Type.Ascii pub const EXIFPhotoLensModel: u16 = 0xa434; //Type.Ascii pub const DNGVersion: u16 = 0xc612; //Type.Byte pub const DNGBackwardVersion...
pub const SubsecTimeOriginal: u16 = 0x9291; //Type.Ascii pub const FocalPlaneXResolution: u16 = 0xa20e; //Type.Rational pub const FocalPlaneYResolution: u16 = 0xa20f; //Type.Rational
random_line_split
root_mod_trait.rs
use super::*; use crate::{prefix_type::PrefixRefTrait, utils::leak_value}; /// The root module of a dynamic library, /// which may contain other modules,function pointers,and static references. /// /// /// # Examples /// /// For a more in-context example of a type implementing this trait you can look /// at either th...
fn root_module_statics() -> &'static RootModuleStatics<Self>; /// Gets the root module,returning None if the module is not yet loaded. #[inline] fn get_module() -> Option<Self> { Self::root_module_statics().root_mod.get() } /// Gets the RawLibrary of the module, /// returning None ...
random_line_split
root_mod_trait.rs
use super::*; use crate::{prefix_type::PrefixRefTrait, utils::leak_value}; /// The root module of a dynamic library, /// which may contain other modules,function pointers,and static references. /// /// /// # Examples /// /// For a more in-context example of a type implementing this trait you can look /// at either th...
/// Gets the LibHeader of a library. /// /// # Errors /// /// This will return these errors: /// /// - `LibraryError::GetSymbolError`: /// If the root module was not exported. /// /// - `LibraryError::InvalidAbiHeader`: /// If the abi_stable used by the library is not compatible. /// /// # Safety /// /// The LibHeade...
{ let path = match where_ { LibraryPath::Directory(directory) => M::get_library_path(directory), LibraryPath::FullPath(full_path) => full_path.to_owned(), }; RawLibrary::load_at(&path) }
identifier_body
root_mod_trait.rs
use super::*; use crate::{prefix_type::PrefixRefTrait, utils::leak_value}; /// The root module of a dynamic library, /// which may contain other modules,function pointers,and static references. /// /// /// # Examples /// /// For a more in-context example of a type implementing this trait you can look /// at either th...
( raw_library: &RawLibrary, ) -> Result<AbiHeaderRef, LibraryError> { let mangled = ROOT_MODULE_LOADER_NAME_WITH_NUL; let header: AbiHeaderRef = unsafe { *raw_library.get::<AbiHeaderRef>(mangled.as_bytes())? }; Ok(header) } /// Gets the LibHeader of the library at the path. /// /// This leaks the unde...
abi_header_from_raw_library
identifier_name
server.rs
//! Processes requests from clients & peer nodes //! //! # Overview //! //! The MinDB server is a peer in the MiniDB cluster. It is initialized with a //! port to bind to and a list of peers to replicate to. The server then //! processes requests send from both clients and peers. //! //! # Peers //! //! On process star...
(&self) { // Iterate all the peers sending a clone of the data. This operation // performs a deep clone for each peer, which is not going to be super // efficient as the data set grows, but improving this is out of scope // for MiniDB. for peer in &self.peers { peer.s...
replicate
identifier_name
server.rs
//! Processes requests from clients & peer nodes //! //! # Overview //! //! The MinDB server is a peer in the MiniDB cluster. It is initialized with a //! port to bind to and a list of peers to replicate to. The server then //! processes requests send from both clients and peers. //! //! # Peers //! //! On process star...
// let mut state = self.server_state.borrow_mut(); let actor_id = state.actor_id; state.data.insert(actor_id, cmd.value()); // Replicate the new state to all peers state.replicate(); let resp = Response::Su...
// and respond with Success
random_line_split
server.rs
//! Processes requests from clients & peer nodes //! //! # Overview //! //! The MinDB server is a peer in the MiniDB cluster. It is initialized with a //! port to bind to and a list of peers to replicate to. The server then //! processes requests send from both clients and peers. //! //! # Peers //! //! On process star...
Request::Join(other) => { info!("[COMMAND] Join"); // A Join request is issued by a peer during replication and // provides the peer's latest state. // // The join request is handled by joining the provided state ...
{ info!("[COMMAND] Clear"); let mut state = self.server_state.borrow_mut(); let actor_id = state.actor_id; state.data.clear(actor_id); state.replicate(); let resp = Response::Success(proto::Success); Box:...
conditional_block
server.rs
//! Processes requests from clients & peer nodes //! //! # Overview //! //! The MinDB server is a peer in the MiniDB cluster. It is initialized with a //! port to bind to and a list of peers to replicate to. The server then //! processes requests send from both clients and peers. //! //! # Peers //! //! On process star...
state.data.insert(actor_id, cmd.value()); // Replicate the new state to all peers state.replicate(); let resp = Response::Success(proto::Success); Box::new(futures::done(Ok(resp))) } Request::Remove(cmd) => { ...
{ match request { Request::Get(_) => { info!("[COMMAND] Get"); // Clone the current state and respond with the set // let data = self.server_state.borrow().data.clone(); let resp = Response::Value(data); ...
identifier_body
heap.rs
/// Implements a heap data structure (a.k.a. a priority queue). /// /// In this implementation, heap is "top-heavy" meaning that the root node is /// the node with the highest value in the heap. The relative priority of /// two nodes is determined via the `cmp` function defined over type of the /// heap's elements (i.e...
}
{ let label = format!("{:?}", self.store[*n]); graphviz::LabelText::LabelStr(label.into_cow()) }
identifier_body
heap.rs
/// Implements a heap data structure (a.k.a. a priority queue). /// /// In this implementation, heap is "top-heavy" meaning that the root node is /// the node with the highest value in the heap. The relative priority of /// two nodes is determined via the `cmp` function defined over type of the /// heap's elements (i.e...
store: Vec<T>, } #[derive(Debug)] enum ChildType { Left, Right } fn left_child(i: NodeIdx) -> NodeIdx { 2 * i + 1 } fn right_child(i: NodeIdx) -> NodeIdx { 2 * i + 2 } impl<T: Ord> Heap<T> { /// Creates a new empty heap. pub fn new() -> Heap<T> { Heap { store: Vec::new() } } ...
use self::core::borrow::IntoCow; pub type NodeIdx = usize; pub struct Heap<T: Ord> {
random_line_split
heap.rs
/// Implements a heap data structure (a.k.a. a priority queue). /// /// In this implementation, heap is "top-heavy" meaning that the root node is /// the node with the highest value in the heap. The relative priority of /// two nodes is determined via the `cmp` function defined over type of the /// heap's elements (i.e...
else { Some((idx - 1) / 2) } } else { panic!("Heap.parent({}): given `idx` not in the heap.", idx) } } fn left_child(&self, parent: NodeIdx) -> Option<NodeIdx> { self.child(ChildType::Left, parent) } fn right_child(&self, parent: NodeIdx) -> Option<NodeIdx> { ...
{ None }
conditional_block
heap.rs
/// Implements a heap data structure (a.k.a. a priority queue). /// /// In this implementation, heap is "top-heavy" meaning that the root node is /// the node with the highest value in the heap. The relative priority of /// two nodes is determined via the `cmp` function defined over type of the /// heap's elements (i.e...
(&self) -> bool { self.len() == 0 } /// Takes the index of a node and returns the index of its parent. Returns /// `None` if the given node has no such parent (i.e. the given node is /// the root. /// /// The function panics if the given index is not valid. fn parent(&self, idx: No...
empty
identifier_name
pit.rs
//! Periodic interrupt timer (PIT) driver and futures //! //! The PIT timer channels are the most precise timers in the HAL. PIT timers run on the periodic clock //! frequency. //! //! A single hardware PIT instance has four PIT channels. Use [`new`](PIT::new()) to acquire these four //! channels. //! //! # Example //!...
//! let (_, _, _, mut pit) = ral::pit::PIT::take() //! .map(PIT::new) //! .unwrap(); //! //! # async { //! pit.delay(250_000).await; //! # }; //! ``` use crate::ral; use core::{ future::Future, marker::PhantomPinned, pin::Pin, sync::atomic, task::{Context, Poll, Waker}, }; /// Periodic inte...
//! // Select 24MHz crystal oscillator, divide by 24 == 1MHz clock //! ral::modify_reg!(ral::ccm, ccm, CSCMR1, PERCLK_PODF: DIVIDE_24, PERCLK_CLK_SEL: 1); //! // Enable PIT clock gate //! ral::modify_reg!(ral::ccm, ccm, CCGR1, CG6: 0b11);
random_line_split
pit.rs
//! Periodic interrupt timer (PIT) driver and futures //! //! The PIT timer channels are the most precise timers in the HAL. PIT timers run on the periodic clock //! frequency. //! //! A single hardware PIT instance has four PIT channels. Use [`new`](PIT::new()) to acquire these four //! channels. //! //! # Example //!...
() -> Self { Self::new(PIT_CHANNEL_3_ADDRESS, 3) } } /// Timer Load Value Register pub mod LDVAL { /// Timer Start Value pub mod TSV { /// Offset (0 bits) pub const offset: u32 = 0; /// Mask (32 bits: 0xffffffff << 0) pub ...
three
identifier_name
pit.rs
//! Periodic interrupt timer (PIT) driver and futures //! //! The PIT timer channels are the most precise timers in the HAL. PIT timers run on the periodic clock //! frequency. //! //! A single hardware PIT instance has four PIT channels. Use [`new`](PIT::new()) to acquire these four //! channels. //! //! # Example //!...
else { // Neither complete nor active; prepare to run ral::write_reg!(register, channel, LDVAL, count); unsafe { WAKERS[channel.index()] = Some(cx.waker().clone()); } atomic::compiler_fence(atomic::Ordering::SeqCst); ral::modify_reg!(register, channel, TCTRL,...
{ // We're active; do nothing Poll::Pending }
conditional_block
pit.rs
//! Periodic interrupt timer (PIT) driver and futures //! //! The PIT timer channels are the most precise timers in the HAL. PIT timers run on the periodic clock //! frequency. //! //! A single hardware PIT instance has four PIT channels. Use [`new`](PIT::new()) to acquire these four //! channels. //! //! # Example //!...
} static mut WAKERS: [Option<Waker>; 4] = [None, None, None, None]; /// A future that yields once the PIT timer elapses pub struct Delay<'a> { channel: &'a mut register::ChannelInstance, _pin: PhantomPinned, count: u32, } impl<'a> Future for Delay<'a> { type Output = (); fn poll(self: Pin<&mut ...
{ Delay { channel: &mut self.channel, count, _pin: PhantomPinned, } }
identifier_body
transactions_reader.rs
/// Reads transactions from a CSV file /// Make it a separate file in case we want to add new methods /// such as reading from a non-CSV file and so on use std::{ collections::HashMap, io::{BufRead, BufReader}, path::Path, }; use anyhow::Context; use crossbeam_channel::{Receiver, Sender}; use csv::{ByteRec...
while let Ok(true) = csv_reader.read_byte_record(&mut raw_record) { let record = raw_record.deserialize::<TransactionRecord>(Some(&headers)); if let Ok(record) = record { transactions.push(record); } ...
{ for _ in 0..num_threads { let block_rx = block_rx.clone(); let parsed_tx = parsed_tx.clone(); // For now consider that the headers if read then they're OK and equal to below let headers = ByteRecord::from(vec!["type", "client", "tx", "amount"]); std:...
identifier_body
transactions_reader.rs
/// Reads transactions from a CSV file /// Make it a separate file in case we want to add new methods /// such as reading from a non-CSV file and so on use std::{ collections::HashMap, io::{BufRead, BufReader}, path::Path, }; use anyhow::Context; use crossbeam_channel::{Receiver, Sender}; use csv::{ByteRec...
; } waiting_for += 1; } } else if block.0 > waiting_for { queue.insert(block.0, block.1); } } }); } // Reads a big block until new line alignment fn read_block(&mut se...
{ return; }
conditional_block
transactions_reader.rs
/// Reads transactions from a CSV file /// Make it a separate file in case we want to add new methods /// such as reading from a non-CSV file and so on use std::{ collections::HashMap, io::{BufRead, BufReader}, path::Path, }; use anyhow::Context; use crossbeam_channel::{Receiver, Sender}; use csv::{ByteRec...
/// Tests that we can read and parse all transactions #[test] fn test_st_bulk_transaction_reader_serde() { let reader = STBulkReader::new(); test_transaction_reader(reader, "tests/data/test_serde.csv"); } #[test] fn test_mt_reader_transaction_reader_serde() { let reader ...
random_line_split
transactions_reader.rs
/// Reads transactions from a CSV file /// Make it a separate file in case we want to add new methods /// such as reading from a non-CSV file and so on use std::{ collections::HashMap, io::{BufRead, BufReader}, path::Path, }; use anyhow::Context; use crossbeam_channel::{Receiver, Sender}; use csv::{ByteRec...
{} impl STBulkReader { pub fn new() -> Self { Self {} } } impl TransactionCSVReader for STBulkReader { fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream> { let start_time = std::time::Instant::now(); info!("STBulkReader reading the transactions"); ...
STBulkReader
identifier_name
dir.rs
use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; use std::ffi::OsStr; use std::fmt; use std::io; use std::str; use traits::{self, Dir as DirTrait, Entry as EntryTrait}; use util::VecExt; use vfat::{Attributes, Date, Metadata, Time, Timestamp}; use vfat::{Cluster, Entry, File, Shared, VFat}; #[derive(Debug)] pub ...
}).filter_map(|entry| match entry.lfn() { Some(lfn) if lfn.seqno!= 0xE5 => Some(*lfn), _ => None, }).collect(); entries.sort_by_key(|lfn| lfn.seqno); let mut name: Vec<u16> = vec![]; for &lfn in entries.iter() { name.extend(l...
{ false }
conditional_block
dir.rs
use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; use std::ffi::OsStr; use std::fmt; use std::io; use std::str; use traits::{self, Dir as DirTrait, Entry as EntryTrait}; use util::VecExt; use vfat::{Attributes, Date, Metadata, Time, Timestamp}; use vfat::{Cluster, Entry, File, Shared, VFat}; #[derive(Debug)] pub ...
#[repr(C, packed)] #[derive(Copy, Clone, Debug)] pub struct VFatLfnDirEntry { seqno: u8, name_1: [u16; 5], attributes: u8, _reserved_1: u8, dos_checksum: u8, name_2: [u16; 6], _reserved_2: [u8; 2], name_3: [u16; 2], } #[repr(C, packed)] #[derive(Copy, Clone)] pub struct VFatUnknownDirEn...
} }
random_line_split
dir.rs
use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; use std::ffi::OsStr; use std::fmt; use std::io; use std::str; use traits::{self, Dir as DirTrait, Entry as EntryTrait}; use util::VecExt; use vfat::{Attributes, Date, Metadata, Time, Timestamp}; use vfat::{Cluster, Entry, File, Shared, VFat}; #[derive(Debug)] pub ...
(&mut self) -> Option<Self::Item> { if self.current >= self.buf.len() { return None; } let (regular_index, regular, name) = (&self.buf)[self.current..] .iter() .enumerate() .filter_map(|(i, union_entry)| { let index = self.current + i...
next
identifier_name
dir.rs
use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; use std::ffi::OsStr; use std::fmt; use std::io; use std::str; use traits::{self, Dir as DirTrait, Entry as EntryTrait}; use util::VecExt; use vfat::{Attributes, Date, Metadata, Time, Timestamp}; use vfat::{Cluster, Entry, File, Shared, VFat}; #[derive(Debug)] pub ...
fn cluster(&self) -> Cluster { Cluster::from(((self.cluster_high as u32) << 16) | (self.cluster_low as u32)) } fn created(&self) -> Timestamp { let date = Date::from_raw(self.created_date); let time = Time::from_raw(self.created_time); Timestamp::new(date, time) } ...
{ self.name[0] == 0x05 || self.name[0] == 0xE5 }
identifier_body
mod.rs
use amethyst::{ animation::{AnimationBundle, VertexSkinningBundle}, assets::{ AssetStorage, Handle, Loader, PrefabLoader, PrefabLoaderSystemDesc, RonFormat, }, controls::{ControlTagPrefab, FlyControlBundle}, core::{ HideHierarchySystemDesc, ...
let parent_ent: Entity = parents.get(entity)?.entity; get_root_cloned( parents, components, parent_ent, ) } } pub fn get_root_mut<'s, 'a, T, P, C>( parents: &P, components: &'a mut C, entity: Entity, ) -> Option<(&'a mut T, Entity)> where T: Component, P:...
random_line_split
mod.rs
use amethyst::{ animation::{AnimationBundle, VertexSkinningBundle}, assets::{ AssetStorage, Handle, Loader, PrefabLoader, PrefabLoaderSystemDesc, RonFormat, }, controls::{ControlTagPrefab, FlyControlBundle}, core::{ HideHierarchySystemDesc, ...
else { let parent_ent: Entity = parents.get(entity)?.entity; get_root_cloned( parents, components, parent_ent, ) } } pub fn get_root_mut<'s, 'a, T, P, C>( parents: &P, components: &'a mut C, entity: Entity, ) -> Option<(&'a mut T, Entity)> where T: Compo...
{ Some((component.clone(), entity)) }
conditional_block
mod.rs
use amethyst::{ animation::{AnimationBundle, VertexSkinningBundle}, assets::{ AssetStorage, Handle, Loader, PrefabLoader, PrefabLoaderSystemDesc, RonFormat, }, controls::{ControlTagPrefab, FlyControlBundle}, core::{ HideHierarchySystemDesc, ...
pub fn get_root_mut<'s, 'a, T, P, C>( parents: &P, components: &'a mut C, entity: Entity, ) -> Option<(&'a mut T, Entity)> where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericWriteStorage<Component=T> { if components.get_mut(entity).is_some() { Some((components.get_mut(entit...
{ if let Some(component) = components.get(entity) { Some((component.clone(), entity)) } else { let parent_ent: Entity = parents.get(entity)?.entity; get_root_cloned( parents, components, parent_ent, ) } }
identifier_body
mod.rs
use amethyst::{ animation::{AnimationBundle, VertexSkinningBundle}, assets::{ AssetStorage, Handle, Loader, PrefabLoader, PrefabLoaderSystemDesc, RonFormat, }, controls::{ControlTagPrefab, FlyControlBundle}, core::{ HideHierarchySystemDesc, ...
<'s, 'a, T, P, C>( parents: &P, components: &'a C, entity: Entity, ) -> Option<(T, Entity)> where T: Component + Clone, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> { if let Some(component) = components.get(entity) { Some((component.clone(), entity)) } else { ...
get_root_cloned
identifier_name
revaultd.rs
bitcoin::{ secp256k1, util::bip32::{ChildNumber, ExtendedPubKey}, Address, BlockHash, PublicKey as BitcoinPublicKey, Script, TxOut, }, miniscript::descriptor::{DescriptorPublicKey, DescriptorTrait}, scripts::{ CpfpDescriptor, DepositDescriptor, DerivedCpfpDescriptor, Deriv...
(&self) -> Address { self.vault_address(self.current_unused_index) } pub fn last_deposit_address(&self) -> Address { let raw_index: u32 = self.current_unused_index.into(); // FIXME: this should fail instead of creating a hardened index self.vault_address(ChildNumber::from(raw_in...
deposit_address
identifier_name
revaultd.rs
bitcoin::{ secp256k1, util::bip32::{ChildNumber, ExtendedPubKey}, Address, BlockHash, PublicKey as BitcoinPublicKey, Script, TxOut, }, miniscript::descriptor::{DescriptorPublicKey, DescriptorTrait}, scripts::{ CpfpDescriptor, DepositDescriptor, DerivedCpfpDescriptor, Deri...
e.to_string() )))); } } data_dir = fs::canonicalize(data_dir)?; let data_dir_str = data_dir .to_str() .expect("Impossible: the datadir path is valid unicode"); let noise_secret_file = [data_dir_str, "noise_secret"].it...
random_line_split