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
app.rs
use audio; use audio::cpal; use find_folder; use glium::glutin; use state; use std; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::marker::PhantomData; use std::path::PathBuf; use std::sync::{mpsc, Arc}; use std::thread; use std::time::Duration; use window::{self, Window}; use ui; /// An **App...
else { self.process_fn_tx.borrow().as_ref().unwrap().clone() }; audio::stream::Builder { event_loop: self.event_loop.clone(), process_fn_tx: process_fn_tx, model, sample_rate: None, channels: None, frames_per_buffer: N...
{ let event_loop = self.event_loop.clone(); let (tx, rx) = mpsc::channel(); let mut loop_context = audio::stream::LoopContext::new(rx); thread::Builder::new() .name("cpal::EventLoop::run thread".into()) .spawn(move || event_loop.run(move |i...
conditional_block
unlinked_file.rs
//! Diagnostic emitted for files that aren't part of any crate. use std::iter; use hir::{db::DefDatabase, DefMap, InFile, ModuleSource}; use ide_db::{ base_db::{FileId, FileLoader, SourceDatabase, SourceDatabaseExt}, source_change::SourceChange, RootDatabase, }; use syntax::{ ast::{self, edit::IndentL...
() { cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists); check_no_fix( r#" //- /main.rs #[cfg(never)] mod foo; //- /foo.rs $0 "#, ); } #[test] fn unlinked_file_with_cfg_on() { check_diagnostics( r#" //- /main.rs #[cfg(not(never))] mod f...
unlinked_file_with_cfg_off
identifier_name
unlinked_file.rs
//! Diagnostic emitted for files that aren't part of any crate. use std::iter; use hir::{db::DefDatabase, DefMap, InFile, ModuleSource}; use ide_db::{ base_db::{FileId, FileLoader, SourceDatabase, SourceDatabaseExt}, source_change::SourceChange, RootDatabase, }; use syntax::{ ast::{self, edit::IndentL...
}
{ check_fix( r#" //- /main.rs mod bar { } //- /bar/foo/mod.rs $0 "#, r#" mod bar { mod foo; } "#, ); }
identifier_body
unlinked_file.rs
//! Diagnostic emitted for files that aren't part of any crate. use std::iter; use hir::{db::DefDatabase, DefMap, InFile, ModuleSource}; use ide_db::{ base_db::{FileId, FileLoader, SourceDatabase, SourceDatabaseExt}, source_change::SourceChange, RootDatabase, }; use syntax::{ ast::{self, edit::IndentL...
mod foo; "#, ); } #[test] fn unlinked_file_insert_in_empty_file_mod_file() { check_fix( r#" //- /main.rs //- /foo/mod.rs $0 "#, r#" mod foo; "#, ); check_fix( r#" //- /main.rs mod bar; //- /bar.rs // bar module //- /bar/foo/mod.rs $0 "#, ...
"#, r#"
random_line_split
lib.rs
NODELAY` (defaults to `true`). //! //! - `pool_min` - Lower bound of opened connections for `Pool` (defaults to `10`). //! - `pool_max` - Upper bound of opened connections for `Pool` (defaults to `20`). //! //! - `ping_before_query` - Ping server every time before execute any query. (defaults to `true`). //! - `send_re...
tokio::time::timeout(timeout, future).await? } #[cf
identifier_body
lib.rs
@host[:port]/database?param1=value1&...&paramN=valueN //! ``` //! //! parameters: //! //! - `compression` - Whether or not use compression (defaults to `none`). Possible choices: //! * `none` //! * `lz4` //! //! - `readonly` - Restricts permissions for read data, write data and change settings queries. (default...
} Ok(Packet::Exception(e)) => return Err(Error::Server(e)), Err(e) => return Err(Error::Io(e)), _ => return Err(Error::Driver(DriverError::UnexpectedPacket)), } } self.inner = h; self.context.server_info = info.unwrap()...
match packet { Ok(Packet::Hello(inner, server_info)) => { info!("[hello] <- {:?}", &server_info); h = Some(inner); info = Some(server_info);
random_line_split
lib.rs
port]/database?param1=value1&...&paramN=valueN //! ``` //! //! parameters: //! //! - `compression` - Whether or not use compression (defaults to `none`). Possible choices: //! * `none` //! * `lz4` //! //! - `readonly` - Restricts permissions for read data, write data and change settings queries. (defaults to `n...
ns: Options) -> Result<ClientHandle> { let source = options.into_options_src(); Self::open(source, None).await } pub(crate) async fn open(source: OptionsSource, pool: Option<Pool>) -> Result<ClientHandle> { let options = try_opt!(source.get()); let compress = options.compression...
t(optio
identifier_name
lib.rs
host[:port]/database?param1=value1&...&paramN=valueN //! ``` //! //! parameters: //! //! - `compression` - Whether or not use compression (defaults to `none`). Possible choices: //! * `none` //! * `lz4` //! //! - `readonly` - Restricts permissions for read data, write data and change settings queries. (defaults...
/// Check connection and try to reconnect if necessary. pub async fn check_connection(&mut self) -> Result<()> { self.pool.detach(); let source = self.context.options.clone(); let pool = self.pool.clone(); let (send_retries, retry_timeout) = { let options = try_op...
Box::pin(f(self)) } }
conditional_block
main.rs
//! A cargo subcommand for displaying line counts of source code in projects, //! including a niave `unsafe` counter for Rust source files. This subcommand //! was originally based off and inspired by the project //! [tokei](https://github.com/aaronepower/tokei) by //! [Aaronepower](https://github.com/aaronepower) //! ...
counts.fill_from(); cli_try!(counts.count()); cli_try!(counts.write_results()); Ok(()) } fn single_char(s: String) -> Result<(), String> { if s.len() == 1 { Ok(()) } else { Err(format!( "the --separator argument option only accepts a single character but found '{}'"...
{ debugln!("executing; cmd=execute;"); verboseln!(cfg, "{}: {:?}", Format::Warning("Excluding"), cfg.exclude); verbose!( cfg, "{}", if cfg.exts.is_some() { format!( "{} including files with extension: {}\n", Format::Warning("Only"), ...
identifier_body
main.rs
//! A cargo subcommand for displaying line counts of source code in projects, //! including a niave `unsafe` counter for Rust source files. This subcommand //! was originally based off and inspired by the project //! [tokei](https://github.com/aaronepower/tokei) by //! [Aaronepower](https://github.com/aaronepower) //! ...
extern crate clap; #[cfg(feature = "color")] extern crate ansi_term; extern crate gitignore; extern crate glob; extern crate regex; extern crate tabwriter; #[cfg(feature = "debug")] use std::env; use clap::{App, AppSettings, Arg, SubCommand}; use config::Config; use count::Counts; use error::{CliError, CliResult}; u...
)] #[macro_use]
random_line_split
main.rs
//! A cargo subcommand for displaying line counts of source code in projects, //! including a niave `unsafe` counter for Rust source files. This subcommand //! was originally based off and inspired by the project //! [tokei](https://github.com/aaronepower/tokei) by //! [Aaronepower](https://github.com/aaronepower) //! ...
else { Err(format!( "the --separator argument option only accepts a single character but found '{}'", Format::Warning(s) )) } }
{ Ok(()) }
conditional_block
main.rs
//! A cargo subcommand for displaying line counts of source code in projects, //! including a niave `unsafe` counter for Rust source files. This subcommand //! was originally based off and inspired by the project //! [tokei](https://github.com/aaronepower/tokei) by //! [Aaronepower](https://github.com/aaronepower) //! ...
(s: String) -> Result<(), String> { if s.len() == 1 { Ok(()) } else { Err(format!( "the --separator argument option only accepts a single character but found '{}'", Format::Warning(s) )) } }
single_char
identifier_name
route.rs
Lit}; use crate::syn_ext::{syn_to_diag, IdentExt}; use self::syn::{Attribute, parse::Parser}; use crate::http_codegen::{Method, MediaType, RoutePath, DataSegment, Optional}; use crate::attribute::segments::{Source, Kind, Segment}; use crate::{ROUTE_FN_PREFIX, ROUTE_STRUCT_PREFIX, URI_MACRO_PREFIX, ROCKET_PARAM_PREFIX}...
#[allow(non_snake_case, unreachable_patterns, unreachable_code)] let #ident: #ty = #expr; } } fn data_expr(ident: &syn::Ident, ty: &syn::Type) -> TokenStream2 { define_vars_and_mods!(req, data, FromData, Outcome, Transform); let span = ident.span().unstable().join(ty.span()).unwrap().into()...
}; quote! {
random_line_split
route.rs
}; use crate::syn_ext::{syn_to_diag, IdentExt}; use self::syn::{Attribute, parse::Parser}; use crate::http_codegen::{Method, MediaType, RoutePath, DataSegment, Optional}; use crate::attribute::segments::{Source, Kind, Segment}; use crate::{ROUTE_FN_PREFIX, ROUTE_STRUCT_PREFIX, URI_MACRO_PREFIX, ROCKET_PARAM_PREFIX}; ...
{ #[meta(naked)] method: SpanWrapped<Method>, path: RoutePath, data: Option<SpanWrapped<DataSegment>>, format: Option<MediaType>, rank: Option<isize>, } /// The raw, parsed `#[method]` (e.g, `get`, `put`, `post`, etc.) attribute. #[derive(Debug, FromMeta)] struct MethodRouteAttribute { #[m...
RouteAttribute
identifier_name
route.rs
}; use crate::syn_ext::{syn_to_diag, IdentExt}; use self::syn::{Attribute, parse::Parser}; use crate::http_codegen::{Method, MediaType, RoutePath, DataSegment, Optional}; use crate::attribute::segments::{Source, Kind, Segment}; use crate::{ROUTE_FN_PREFIX, ROUTE_STRUCT_PREFIX, URI_MACRO_PREFIX, ROCKET_PARAM_PREFIX}; ...
dup_check(&mut segments, attr.path.path.iter().cloned(), &mut diags); attr.path.query.as_ref().map(|q| dup_check(&mut segments, q.iter().cloned(), &mut diags)); dup_check(&mut segments, attr.data.clone().map(|s| s.value.0).into_iter(), &mut diags); // Check the validity of function arguments. let...
{ for segment in iter.filter(|s| s.kind != Kind::Static) { let span = segment.span; if let Some(previous) = set.replace(segment) { diags.push(span.error(format!("duplicate parameter: `{}`", previous.name)) .span_note(previous.span, "previous parameter ...
identifier_body
sendmail.rs
c_char) ->!; //char FAST_FUNC *parse_url(char *url, char **user, char **pass); #[no_mangle] fn launch_helper(argv: *mut *const libc::c_char); #[no_mangle] fn get_cred_or_die(fd: libc::c_int); #[no_mangle] fn send_mail_command(fmt: *const libc::c_char, param: *const libc::c_char) -> *mut libc::c_char; #[...
); } if strlen(answer) <= 3i32 as libc::c_ulong || '-' as i32!= *answer.offset(3) as libc::c_int { break; } free(answer as *mut libc::c_void); } if!answer.is_null() { let mut n: libc::c_int = atoi(answer); if (*ptr_to_globals).timeout!= 0 { alarm(0i32 as libc::c_uint); ...
{ let mut answer: *mut libc::c_char = 0 as *mut libc::c_char; let mut msg: *mut libc::c_char = send_mail_command(fmt, param); loop // read stdin // if the string has a form NNN- -- read next string. E.g. EHLO response // parse first bytes to a number // if code = -1 then just return this number // if co...
identifier_body
sendmail.rs
c_char) ->!; //char FAST_FUNC *parse_url(char *url, char **user, char **pass); #[no_mangle] fn launch_helper(argv: *mut *const libc::c_char); #[no_mangle] fn get_cred_or_die(fd: libc::c_int); #[no_mangle] fn send_mail_command(fmt: *const libc::c_char, param: *const libc::c_char) -> *mut libc::c_char; #[...
else { current_block = 228501038991332163; } loop { match current_block { 228501038991332163 => // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop // N.B. after reenter code will be > 0 { if!(code == 0) { ...
{ current_block = 16252544171633782868; }
conditional_block
sendmail.rs
c_char) ->!; //char FAST_FUNC *parse_url(char *url, char **user, char **pass); #[no_mangle] fn launch_helper(argv: *mut *const libc::c_char); #[no_mangle] fn get_cred_or_die(fd: libc::c_int); #[no_mangle] fn send_mail_command(fmt: *const libc::c_char, param: *const libc::c_char) -> *mut libc::c_char; #[...
(mut list: *const libc::c_char) { let mut free_me: *mut libc::c_char = xstrdup(list); let mut str: *mut libc::c_char = free_me; let mut s: *mut libc::c_char = free_me; let mut prev: libc::c_char = 0i32 as libc::c_char; let mut in_quote: libc::c_int = 0i32; while *s!= 0 { let fresh0 = s; s = s.offset...
rcptto_list
identifier_name
sendmail.rs
fmt: *const libc::c_char, param: *const libc::c_char) -> *mut libc::c_char; #[no_mangle] fn printbuf_base64(buf: *const libc::c_char, len: libc::c_uint); #[no_mangle] fn printstr_base64(buf: *const libc::c_char); } use crate::librb::size_t; use libc::pid_t; use libc::uid_t; #[derive(Copy, Clone)] #[repr(C)] pu...
b"Bcc:\x00" as *const u8 as *const libc::c_char, s, 4i32 as libc::c_ulong, )
random_line_split
game_tree.rs
//! This file contains code that represents the GameState at any point //! during the game, in a lazily-evaluated tree structure. use crate::common::gamestate::GameState; use crate::common::action::Move; use std::collections::HashMap; /// Represents an entire game of Fish, starting from the given GameState /// passed ...
(&self) -> &GameState { match self { GameTree::Turn { state,.. } => state, GameTree::End(state) => state, } } /// Returns a mutable reference to the GameState of the current node of the GameTree pub fn get_state_mut(&mut self) -> &mut GameState { match self {...
get_state
identifier_name
game_tree.rs
//! This file contains code that represents the GameState at any point //! during the game, in a lazily-evaluated tree structure. use crate::common::gamestate::GameState; use crate::common::action::Move; use std::collections::HashMap; /// Represents an entire game of Fish, starting from the given GameState /// passed ...
GameTree::Turn { valid_moves,.. } => { valid_moves.get_mut(&move_).map(|lazy_game| lazy_game.get_evaluated()) }, GameTree::End(_) => None, } } /// Returns the `GameTree` that would be produced as a result of taking the given Move. /// If the move ...
/// If the move is invalid (not in valid_moves or self is `End`) then None is returned pub fn get_game_after_move(&mut self, move_: Move) -> Option<&mut GameTree> { match self {
random_line_split
game_tree.rs
//! This file contains code that represents the GameState at any point //! during the game, in a lazily-evaluated tree structure. use crate::common::gamestate::GameState; use crate::common::action::Move; use std::collections::HashMap; /// Represents an entire game of Fish, starting from the given GameState /// passed ...
#[test] fn test_new() { // valid_moves generated correctly // - have expected moves, check if same as generated // starting gamestate is same as one passed to new let game = start_game(); let mut valid_moves = game.get_state().get_valid_moves(); let mut expec...
{ let mut expected_valid_moves = vec![]; let state = game.get_state(); let occupied_tiles = state.get_occupied_tiles(); for penguin in state.current_player().penguins.iter() { let current_tile = state.get_tile(penguin.tile_id.unwrap()).unwrap(); for tile in curre...
identifier_body
bigrand.rs
//! Randomization of big integers use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler}; use rand::prelude::*; use rand::Rng; use crate::BigInt; use crate::BigUint; use crate::Sign::*; use crate::big_digit::BigDigit; use crate::bigint::{into_magnitude, magnitude}; use crate::integer::Intege...
<R: Rng +?Sized>(&self, rng: &mut R) -> Self::X { &self.base + BigInt::from(rng.gen_biguint_below(&self.len)) } #[inline] fn sample_single<R: Rng +?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + ...
sample
identifier_name
bigrand.rs
//! Randomization of big integers use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler}; use rand::prelude::*; use rand::Rng; use crate::BigInt; use crate::BigUint; use crate::Sign::*; use crate::big_digit::BigDigit; use crate::bigint::{into_magnitude, magnitude}; use crate::integer::Intege...
// means that when two of these values are multiplied together, // the result isn't ever one bit short. if b >= 2 { bytes[0] |= 3u8.wrapping_shl(b as u32 - 2); } else { // Here b==1, because b cannot be zero. bytes[0] |= 1; ...
{ if bit_size < 2 { panic!("prime size must be at least 2-bit"); } let mut b = bit_size % 8; if b == 0 { b = 8; } let bytes_len = (bit_size + 7) / 8; let mut bytes = vec![0u8; bytes_len]; loop { self.fill_bytes(&mut b...
identifier_body
bigrand.rs
//! Randomization of big integers use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler}; use rand::prelude::*; use rand::Rng; use crate::BigInt; use crate::BigUint; use crate::Sign::*; use crate::big_digit::BigDigit; use crate::bigint::{into_magnitude, magnitude}; use crate::integer::Intege...
lazy_static! { /// The product of the values in SMALL_PRIMES and allows us /// to reduce a candidate prime by this number and then determine whether it's /// coprime to all the elements of SMALL_PRIMES without further BigUint /// operations. static ref SMALL_PRIMES_PRODUCT: BigUint = BigUint::from_u...
/// odd by construction. #[cfg(feature = "prime")] const SMALL_PRIMES: [u8; 15] = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53]; #[cfg(feature = "prime")]
random_line_split
bigrand.rs
//! Randomization of big integers use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler}; use rand::prelude::*; use rand::Rng; use crate::BigInt; use crate::BigUint; use crate::Sign::*; use crate::big_digit::BigDigit; use crate::bigint::{into_magnitude, magnitude}; use crate::integer::Intege...
else { // Here b==1, because b cannot be zero. bytes[0] |= 1; if bytes_len > 1 { bytes[1] |= 0x80; } } // Make the value odd since an even number this large certainly isn't prime. bytes[bytes_len - ...
{ bytes[0] |= 3u8.wrapping_shl(b as u32 - 2); }
conditional_block
lib.rs
//! //! Dynamic, plugin-based [Symbol](https://en.wikipedia.org/wiki/Symbol_(programming)) abstraction. //! //! A [Symbol] can be used as an _identifier_ in place of the more primitive workhorse [String]. //! There could be multiple reasons to do so: //! //! 1. Mixing of different domains in the same runtime code //! 2...
f, "{}::{}", instance.namespace_name(), instance.symbol_name() ) } } } } impl PartialEq for Symbol { fn eq(&self, rhs: &Symbol) -> bool { match (self, rhs) { (Self::Static(thi...
Self::Static(ns, id) => { write!(f, "{}::{}", ns.namespace_name(), ns.symbol_name(*id)) } Self::Dynamic(instance) => { write!(
random_line_split
lib.rs
//! //! Dynamic, plugin-based [Symbol](https://en.wikipedia.org/wiki/Symbol_(programming)) abstraction. //! //! A [Symbol] can be used as an _identifier_ in place of the more primitive workhorse [String]. //! There could be multiple reasons to do so: //! //! 1. Mixing of different domains in the same runtime code //! 2...
#[test] fn test_inequality() { let test_state = TestState::new(); test_state.assert_full_ne(&STATIC_A_0, &STATIC_A_1); test_state.assert_full_ne(&STATIC_A_0, &STATIC_B_0); test_state.assert_full_ne(&dynamic::sym0("foo"), &dynamic::sym0("bar")); test_state.assert_full_...
{ let test_state = TestState::new(); test_state.assert_full_eq(&STATIC_A_0, &STATIC_A_0); test_state.assert_full_eq(&STATIC_A_1, &STATIC_A_1); test_state.assert_full_eq(&STATIC_B_0, &STATIC_B_0); test_state.assert_full_ne(&STATIC_A_0, &STATIC_A_1); test_state.assert_ful...
identifier_body
lib.rs
//! //! Dynamic, plugin-based [Symbol](https://en.wikipedia.org/wiki/Symbol_(programming)) abstraction. //! //! A [Symbol] can be used as an _identifier_ in place of the more primitive workhorse [String]. //! There could be multiple reasons to do so: //! //! 1. Mixing of different domains in the same runtime code //! 2...
() { let test_state = TestState::new(); test_state.assert_full_eq(&STATIC_A_0, &STATIC_A_0); test_state.assert_full_eq(&STATIC_A_1, &STATIC_A_1); test_state.assert_full_eq(&STATIC_B_0, &STATIC_B_0); test_state.assert_full_ne(&STATIC_A_0, &STATIC_A_1); test_state.assert_...
test_equality
identifier_name
mod.rs
use futures::{select, StreamExt}; use log::{debug, error, info, warn}; use std::collections::HashMap; use std::sync::RwLock; use tokio::signal::unix::{signal, SignalKind}; use tokio::sync::mpsc::{self, UnboundedSender}; mod trace; use crate::protocol::{Message, MessageBody, TryIntoMessage}; use crate::{Broker, Error,...
}, }; } if pending_tasks > 0 { // Warm shutdown loop. When there are still pendings tasks we wait for them // to finish. We get updates about pending tasks through the `event_rx` channel. // We also watch for a second SIGINT, in which case...
TaskStatus::Pending => pending_tasks += 1, TaskStatus::Finished => pending_tasks -= 1, }; }
random_line_split
mod.rs
use futures::{select, StreamExt}; use log::{debug, error, info, warn}; use std::collections::HashMap; use std::sync::RwLock; use tokio::signal::unix::{signal, SignalKind}; use tokio::sync::mpsc::{self, UnboundedSender}; mod trace; use crate::protocol::{Message, MessageBody, TryIntoMessage}; use crate::{Broker, Error,...
Ok(()) } /// Wraps `try_handle_delivery` to catch any and all errors that might occur. async fn handle_delivery( &self, delivery_result: Result<B::Delivery, B::DeliveryError>, event_tx: UnboundedSender<TaskEvent>, ) { if let Err(e) = self.try_handle_delivery(de...
{ self.broker.decrease_prefetch_count().await?; }
conditional_block
mod.rs
use futures::{select, StreamExt}; use log::{debug, error, info, warn}; use std::collections::HashMap; use std::sync::RwLock; use tokio::signal::unix::{signal, SignalKind}; use tokio::sync::mpsc::{self, UnboundedSender}; mod trace; use crate::protocol::{Message, MessageBody, TryIntoMessage}; use crate::{Broker, Error,...
<T: Task>(&self, task: &T) -> Self { Self { timeout: task.timeout().or(self.timeout), max_retries: task.max_retries().or(self.max_retries), min_retry_delay: task.min_retry_delay().unwrap_or(self.min_retry_delay), max_retry_delay: task.max_retry_delay().unwrap_or(s...
overrides
identifier_name
test.rs
//! Contains helpers for Gotham applications to use during testing. //! //! See the [`TestServer`] and [`AsyncTestServer`] types for example usage. use std::convert::TryFrom; use std::future::Future; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use std::...
#[test] fn test_server_supports_multiple_servers() { test::common_tests::supports_multiple_servers(TestServer::new, TestServer::client) } #[test] fn test_server_spawns_and_runs_futures() { let server = TestServer::new(TestHandler::default()).unwrap(); let (sender, spawn_r...
{ test::common_tests::async_echo(TestServer::new, TestServer::client) }
identifier_body
test.rs
//! Contains helpers for Gotham applications to use during testing. //! //! See the [`TestServer`] and [`AsyncTestServer`] types for example usage. use std::convert::TryFrom; use std::future::Future; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use std::...
() { async_test::common_tests::adds_client_address_to_state( AsyncTestServer::new, AsyncTestServer::client, ) .await; } }
async_test_server_adds_client_address_to_state
identifier_name
test.rs
//! Contains helpers for Gotham applications to use during testing. //! //! See the [`TestServer`] and [`AsyncTestServer`] types for example usage. use std::convert::TryFrom; use std::future::Future; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use std::...
else { tcp.connected() } } } impl<IO> AsyncRead for TlsConnectionStream<IO> where IO: AsyncRead + AsyncWrite + Unpin, { #[inline] fn poll_read( self: Pin<&mut Self>, cx: &mut Context, buf: &mut ReadBuf, ) -> Poll<Result<(), io::Error>> { self.pro...
{ tcp.connected().negotiated_h2() }
conditional_block
test.rs
//! Contains helpers for Gotham applications to use during testing. //! //! See the [`TestServer`] and [`AsyncTestServer`] types for example usage. use std::convert::TryFrom; use std::future::Future; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use std::...
Ok(stream) => { let domain = ServerName::try_from(req.host().unwrap()).unwrap(); match tls.connect(domain, stream).await { Ok(tls_stream) => { info!("Client TcpStream connected: {:?}", tls_stream); ...
async move { match TcpStream::connect(address).await {
random_line_split
viewer.rs
use std::f32::consts::PI; use std::os::raw::c_void; use std::path::Path; use std::process; use std::time::Instant; use cgmath::{ Deg, Point3 }; use collision::Aabb; use gl; use gltf; use glutin; use glutin::{ Api, MouseScrollDelta, MouseButton, GlContext, GlRequest, GlProfile, VirtualKeyCod...
}, WindowEvent::MouseInput { button, state: Released,..} => { match (button, orbit_controls.state.clone()) { (MouseButton::Left, NavState::Rotating) | (MouseButton::Right, NavState::Panning) => { orbit_controls.state...
_ => () }
random_line_split
viewer.rs
use std::f32::consts::PI; use std::os::raw::c_void; use std::path::Path; use std::process; use std::time::Instant; use cgmath::{ Deg, Point3 }; use collision::Aabb; use gl; use gltf; use glutin; use glutin::{ Api, MouseScrollDelta, MouseButton, GlContext, GlRequest, GlProfile, VirtualKeyCod...
(source: &str, scene_index: usize) -> (Root, Scene) { let mut start_time = Instant::now(); // TODO!: http source // let gltf = if source.starts_with("http") { panic!("not implemented: HTTP support temporarily removed.") // let http_source = HttpSource::new(source)...
load
identifier_name
viewer.rs
use std::f32::consts::PI; use std::os::raw::c_void; use std::path::Path; use std::process; use std::time::Instant; use cgmath::{ Deg, Point3 }; use collision::Aabb; use gl; use gltf; use glutin; use glutin::{ Api, MouseScrollDelta, MouseButton, GlContext, GlRequest, GlProfile, VirtualKeyCod...
; self.orbit_controls.position = cam_pos; self.orbit_controls.target = center; self.orbit_controls.camera.znear = size / 100.0; self.orbit_controls.camera.zfar = Some(size * 20.0); self.orbit_controls.camera.update_projection_matrix(); } pub fn start_render_loop(&mut se...
{ Point3::new( center.x + size / 2.0, center.y + size / 5.0, center.z + size / 2.0, ) }
conditional_block
viewer.rs
use std::f32::consts::PI; use std::os::raw::c_void; use std::path::Path; use std::process; use std::time::Instant; use cgmath::{ Deg, Point3 }; use collision::Aabb; use gl; use gltf; use glutin; use glutin::{ Api, MouseScrollDelta, MouseButton, GlContext, GlRequest, GlProfile, VirtualKeyCod...
WindowEvent::HiDpiFactorChanged(f) => { *dpi_factor = f; }, WindowEvent::DroppedFile(_path_buf) => { () // TODO: drag file in } WindowEvent::MouseInput { button, state: Pressed,..} => { ...
{ let mut keep_running = true; #[allow(single_match)] events_loop.poll_events(|event| { match event { glutin::Event::WindowEvent{ event, .. } => match event { WindowEvent::CloseRequested => { keep_running = false; }, Win...
identifier_body
cq_reactor.rs
//! The Completion Queue Reactor. Functions like any other async/await reactor, but is driven by //! IRQs triggering wakeups in order to poll NVME completion queues (see `CompletionFuture`). //! //! While the reactor is primarily intended to wait for IRQs and then poll completion queues, it //! can also be used for not...
use super::{CmdId, CqId, InterruptSources, Nvme, NvmeComp, NvmeCmd, SqId}; /// A notification request, sent by the future in order to tell the completion thread that the /// current task wants a notification when a matching completion queue entry has been seen. #[derive(Debug)] pub enum NotifReq { RequestCompletio...
random_line_split
cq_reactor.rs
//! The Completion Queue Reactor. Functions like any other async/await reactor, but is driven by //! IRQs triggering wakeups in order to poll NVME completion queues (see `CompletionFuture`). //! //! While the reactor is primarily intended to wait for IRQs and then poll completion queues, it //! can also be used for not...
( nvme: Arc<Nvme>, interrupt_sources: InterruptSources, receiver: Receiver<NotifReq>, ) -> thread::JoinHandle<()> { // Actually, nothing prevents us from spawning additional threads. the channel is MPMC and // everything is properly synchronized. I'm not saying this is strictly required, but with ...
start_cq_reactor_thread
identifier_name
cq_reactor.rs
//! The Completion Queue Reactor. Functions like any other async/await reactor, but is driven by //! IRQs triggering wakeups in order to poll NVME completion queues (see `CompletionFuture`). //! //! While the reactor is primarily intended to wait for IRQs and then poll completion queues, it //! can also be used for not...
fn new( nvme: Arc<Nvme>, mut int_sources: InterruptSources, receiver: Receiver<NotifReq>, ) -> Result<Self> { Ok(Self { event_queue: Self::create_event_queue(&mut int_sources)?, int_sources, nvme, pending_reqs: Vec::new(), ...
{ use syscall::flag::*; let fd = syscall::open("event:", O_CLOEXEC | O_RDWR)?; let mut file = unsafe { File::from_raw_fd(fd as RawFd) }; for (num, irq_handle) in int_sources.iter_mut() { if file .write(&Event { id: irq_handle.as_raw_fd() a...
identifier_body
xcbwin.rs
use std::sync::Arc; use std::sync::Mutex; use std::ops::Drop; use std::thread; use window::Dock; use cairo; use cairo::XCBSurface; use cairo_sys; use xcb; use xcb::*; fn get_visualid_from_depth(scr: Screen, depth: u8) -> (Visualid, u8) { for d in scr.allowed_depths() { if depth == d.depth()
} // If no depth matches return root visual return (scr.root_visual(), scr.root_depth()); } pub struct XCB { conn: Arc<Connection>, scr_num: i32, win: Window, root: Window, bufpix: Pixmap, gc: Gcontext, colour: Colormap, visual: Visualid, de...
{ for v in d.visuals() { return (v.visual_id(), depth); } }
conditional_block
xcbwin.rs
use std::sync::Arc; use std::sync::Mutex; use std::ops::Drop; use std::thread; use window::Dock; use cairo; use cairo::XCBSurface; use cairo_sys; use xcb; use xcb::*; fn get_visualid_from_depth(scr: Screen, depth: u8) -> (Visualid, u8) { for d in scr.allowed_depths() { if depth == d.depth() { ...
impl Dock for XCB { fn create_surface(&self) -> cairo::Surface { // Prepare cairo variables let cr_conn = unsafe { cairo::XCBConnection::from_raw_none( self.conn.get_raw_conn() as *mut cairo_sys::xcb_connection_t) }; let cr_draw = cairo::XCBDrawable(self...
self.pos = (x as i16, y as i16); } }
random_line_split
xcbwin.rs
use std::sync::Arc; use std::sync::Mutex; use std::ops::Drop; use std::thread; use window::Dock; use cairo; use cairo::XCBSurface; use cairo_sys; use xcb; use xcb::*; fn get_visualid_from_depth(scr: Screen, depth: u8) -> (Visualid, u8) { for d in scr.allowed_depths() { if depth == d.depth() { ...
(&self, name: &str) -> Atom { let atom = intern_atom(&self.conn, false, name); atom.get_reply().unwrap().atom() } fn get_screen(&self) -> Screen { let setup = self.conn.get_setup(); let screen = setup.roots().nth(self.scr_num as usize).unwrap(); return screen; } ...
get_atom
identifier_name
xcbwin.rs
use std::sync::Arc; use std::sync::Mutex; use std::ops::Drop; use std::thread; use window::Dock; use cairo; use cairo::XCBSurface; use cairo_sys; use xcb; use xcb::*; fn get_visualid_from_depth(scr: Screen, depth: u8) -> (Visualid, u8) { for d in scr.allowed_depths() { if depth == d.depth() { ...
}
{ free_pixmap(&*self.conn, self.win); free_pixmap(&*self.conn, self.bufpix); free_gc(&*self.conn, self.gc); free_colormap(&*self.conn, self.colour); }
identifier_body
lib.rs
that frame has //! been dropped. The frame is created when `Julia::scope(_with_slots)` is called and dropped //! when that method returns. //! //! Because you can use both a `Global` and a mutable reference to a `GcFrame` inside the closure, //! it's possible to access the contents of modules and create new values tha...
scope
identifier_name
lib.rs
.z/lib/julia` must also be //! added to `LD_LIBRARY_PATH`. //! //! #### Windows //! //! If you want to use jlrs on Windows you must use WSL. An installation guide to install WSL on //! Windows can be found [on Microsoft's website]. After installing a Linux distribution, follow //! the installation instructions for Linu...
/// results. The frame will preallocate `slots` slots. /// /// Example: /// /// ``` /// # use jlrs::prelude::*; /// # use jlrs::util::JULIA; /// # fn main() { /// # JULIA.with(|j| { /// # let mut julia = j.borrow_mut(); /// julia.scope_with_slots(1, |_global, frame| { /...
random_line_split
lib.rs
z/lib/julia` must also be //! added to `LD_LIBRARY_PATH`. //! //! #### Windows //! //! If you want to use jlrs on Windows you must use WSL. An installation guide to install WSL on //! Windows can be found [on Microsoft's website]. After installing a Linux distribution, follow //! the installation instructions for Linux...
if!image_path.as_ref().exists() { let io_err = IOError::new(ErrorKind::NotFound, image_path_str); return Err(JlrsError::other(io_err))?; } let bindir = CString::new(julia_bindir_str).unwrap(); let im_rel_path = CString::new(image_path_str).unwrap(); jl...
{ let io_err = IOError::new(ErrorKind::NotFound, julia_bindir_str); return Err(JlrsError::other(io_err))?; }
conditional_block
lib.rs
`GcFrame` is used to root local values. Rooting a //! value in a frame prevents it from being freed by the garbage collector until that frame has //! been dropped. The frame is created when `Julia::scope(_with_slots)` is called and dropped //! when that method returns. //! //! Because you can use both a `Global` and a...
{ uv_async_send(handle.cast()) == 0 }
identifier_body
round_trip.rs
use std::fmt::Debug; use tree_buf::prelude::*; mod common; use common::*; use std::collections::HashMap; use tree_buf::encode_options; use tree_buf::options; // Create this namespace to hide the prelude. This is a check that the hygenics do not require any types from tree_buf to be imported mod hide_namespace { us...
#[test] fn map_1_root() { let mut data = HashMap::new(); data.insert("test".to_owned(), 5u32); round_trip(&data, 10, 22); } #[test] fn map_n_root() { let mut data = HashMap::new(); data.insert("test3".to_owned(), 5u32); data.insert("test2".to_owned(), 5); data.insert("test1".to_owned(), 0...
{ // See also: 84d15459-35e4-4f04-896f-0f4ea9ce52a9 let data = HashMap::<u32, u32>::new(); round_trip(&data, 2, 8); }
identifier_body
round_trip.rs
use std::fmt::Debug; use tree_buf::prelude::*; mod common; use common::*; use std::collections::HashMap; use tree_buf::encode_options; use tree_buf::options; // Create this namespace to hide the prelude. This is a check that the hygenics do not require any types from tree_buf to be imported mod hide_namespace { us...
() { let mut data = HashMap::new(); data.insert("test3".to_owned(), 5u32); data.insert("test2".to_owned(), 5); data.insert("test1".to_owned(), 0); round_trip(&data, None, None); } #[test] fn maps_array() { let mut data = Vec::new(); for i in 0..5u32 { let mut h = HashMap::new(); ...
map_n_root
identifier_name
round_trip.rs
use std::fmt::Debug; use tree_buf::prelude::*; mod common; use common::*; use std::collections::HashMap; use tree_buf::encode_options; use tree_buf::options; // Create this namespace to hide the prelude. This is a check that the hygenics do not require any types from tree_buf to be imported mod hide_namespace { us...
// Show that this is much better than fixed, since this would be a minimum for exactly 0 schema overhead. assert_eq!(std::mem::size_of::<f64>() * data.len(), 400); } #[test] fn nested_float_vec() { round_trip(&vec![vec![10.0, 11.0], vec![], vec![99.0]], 24, 32); } #[test] fn array_tuple() { round_trip...
let options = encode_options! { options::LosslessFloat }; let binary = tree_buf::write_with_options(&data, &options); assert_eq!(binary.len(), 376);
random_line_split
chip8.rs
use rand::{Rng, thread_rng}; pub const PIXEL_W: u16 = 64; // width of CHIP-8 screen pub const PIXEL_H: u16 = 32; // height of CHIP-8 screen pub const FONT_LOCATION: u16 = 0x80; // location of font set in system RAM pub const CARTRIDGE_LOCATION: u16 = 0x200; // location in system RAM where game data should be l...
{ pub memory: [u8; 4096], // RAM pub reg: [u8; 16], // registers pub gfx: [u8; (PIXEL_W * PIXEL_H) as usize], // pixels stack: [u16; 16], // subroutine stack pub key: [u8; 16], // keypad idx: u16, // index register pc: u16, // program counter sp: u16, // s...
Chip8
identifier_name
chip8.rs
use rand::{Rng, thread_rng}; pub const PIXEL_W: u16 = 64; // width of CHIP-8 screen pub const PIXEL_H: u16 = 32; // height of CHIP-8 screen pub const FONT_LOCATION: u16 = 0x80; // location of font set in system RAM pub const CARTRIDGE_LOCATION: u16 = 0x200; // location in system RAM where game data should be l...
, // draw sprites at coordinate reg x, reg y (NOT X AND Y AS I ORIGINALLY DID) a width of 8 and height of z. // get z sprites from memory starting at location idx. (0xD, _, _, _) => { self.draw_flag = true; let mut pixel_unset = false; let sprites = &self.memory[self.idx as usize.. (self.idx + (z ...
{ let rand_val: u8 = thread_rng().gen(); self.reg[_x] = yz & rand_val; self.pc += 2; }
conditional_block
chip8.rs
use rand::{Rng, thread_rng}; pub const PIXEL_W: u16 = 64; // width of CHIP-8 screen pub const PIXEL_H: u16 = 32; // height of CHIP-8 screen pub const FONT_LOCATION: u16 = 0x80; // location of font set in system RAM pub const CARTRIDGE_LOCATION: u16 = 0x200; // location in system RAM where game data should be lo...
current_sprite_bit, current_coordinate % PIXEL_W as usize, current_coordinate / PIXEL_W as usize ); } if self.gfx[current_coordinate % self.gfx.len()] & current_sprite_bit!= 0 { // if the current byte/pixel is 1, and the sprite bit is 1, pixel_unset = true; // then th...
if super::DEBUG { println!("drawing pixel 0b{:b} at {}, {}",
random_line_split
mod.rs
//! Boa's implementation of ECMAScript's global `BigInt` object. //! //! `BigInt` is a built-in object that provides a way to represent whole numbers larger //! than the largest number JavaScript can reliably represent with the Number primitive //! and represented by the `Number.MAX_SAFE_INTEGER` constant. //! `BigInt`...
impl IntrinsicObject for BigInt { fn init(realm: &Realm) { let _timer = Profiler::global().start_event(Self::NAME, "init"); BuiltInBuilder::from_standard_constructor::<Self>(realm) .method(Self::to_string, "toString", 0) .method(Self::value_of, "valueOf", 0) .static...
random_line_split
mod.rs
//! Boa's implementation of ECMAScript's global `BigInt` object. //! //! `BigInt` is a built-in object that provides a way to represent whole numbers larger //! than the largest number JavaScript can reliably represent with the Number primitive //! and represented by the `Number.MAX_SAFE_INTEGER` constant. //! `BigInt`...
(realm: &Realm) { let _timer = Profiler::global().start_event(Self::NAME, "init"); BuiltInBuilder::from_standard_constructor::<Self>(realm) .method(Self::to_string, "toString", 0) .method(Self::value_of, "valueOf", 0) .static_method(Self::as_int_n, "asIntN", 2) ...
init
identifier_name
mod.rs
//! Boa's implementation of ECMAScript's global `BigInt` object. //! //! `BigInt` is a built-in object that provides a way to represent whole numbers larger //! than the largest number JavaScript can reliably represent with the Number primitive //! and represented by the `Number.MAX_SAFE_INTEGER` constant. //! `BigInt`...
{ Ok(JsValue::new(modulo)) } } /// `BigInt.asUintN()` /// /// The `BigInt.asUintN()` method wraps the value of a `BigInt` to an unsigned integer between `0` and `2**(width) - 1`. /// /// [spec]: https://tc39.es/ecma262/#sec-bigint.asuintn /// [mdn]: https://developer.moz...
Ok(JsValue::new(JsBigInt::sub( &modulo, &JsBigInt::pow(&JsBigInt::new(2), &JsBigInt::new(i64::from(bits)))?, ))) } else
conditional_block
thread_pool.rs
use std::marker::PhantomData; use std::sync::Arc; use std::thread::JoinHandle; use std::{iter, mem}; use crossbeam::atomic::AtomicCell; use crossbeam::deque::{Injector, Steal, Stealer, Worker}; use crossbeam::sync::{Parker, Unparker, WaitGroup}; use futures::task::{Context, Poll, Waker}; use futures::Future; use std::...
/// Compute a task in the `ThreadPool` pub fn compute<F>(&self, task: F) where F: StaticTaskFn, { self.thread_pool .compute(Task::new(self.task_group_id, task)); } /// Execute a bunch of tasks in a scope that blocks until all tasks are finished. /// Provides a l...
{ self.thread_pool.target_thread_count }
identifier_body
thread_pool.rs
use std::marker::PhantomData; use std::sync::Arc; use std::thread::JoinHandle; use std::{iter, mem}; use crossbeam::atomic::AtomicCell; use crossbeam::deque::{Injector, Steal, Stealer, Worker}; use crossbeam::sync::{Parker, Unparker, WaitGroup}; use futures::task::{Context, Poll, Waker}; use futures::Future; use std::...
(&self) -> usize { self.thread_pool.target_thread_count } /// Compute a task in the `ThreadPool` pub fn compute<F>(&self, task: F) where F: StaticTaskFn, { self.thread_pool .compute(Task::new(self.task_group_id, task)); } /// Execute a bunch of tasks in a...
degree_of_parallelism
identifier_name
thread_pool.rs
use std::marker::PhantomData; use std::sync::Arc; use std::thread::JoinHandle; use std::{iter, mem}; use crossbeam::atomic::AtomicCell; use crossbeam::deque::{Injector, Steal, Stealer, Worker}; use crossbeam::sync::{Parker, Unparker, WaitGroup}; use futures::task::{Context, Poll, Waker}; use futures::Future; use std::...
else { parked_threads.push(unparker.clone()); parker.park(); } } } pub fn create_context(&self) -> ThreadPoolContext { ThreadPoolContext::new(self, self.next_group_id.fetch_add(1)) } fn compute(&self, task: Task) { self.global_queue....
{ // TODO: recover panics task.call_once(); }
conditional_block
thread_pool.rs
use std::marker::PhantomData; use std::sync::Arc; use std::thread::JoinHandle; use std::{iter, mem}; use crossbeam::atomic::AtomicCell; use crossbeam::deque::{Injector, Steal, Stealer, Worker}; use crossbeam::sync::{Parker, Unparker, WaitGroup}; use futures::task::{Context, Poll, Waker}; use futures::Future; use std::...
#[test] fn scoped_vec() { const NUMBER_OF_TASKS: usize = 42; let thread_pool = ThreadPool::new(2); let context = thread_pool.create_context(); let mut result = vec![0; NUMBER_OF_TASKS]; context.scope(|scope| { for (chunk, i) in result.chunks_exact_mut(1).z...
} }); assert_eq!(result.load(Ordering::SeqCst), NUMBER_OF_TASKS); }
random_line_split
main.rs
extern crate gl; extern crate imgui; extern crate imgui_opengl_renderer; extern crate imgui_sdl2; extern crate sdl2; /* @TODO: - Show line numbers! - Use traits to Send, Parse and Draw - Create a checkbox to enable debugging the parser, queries, etc; - Write a logger to use a imgui window */ use imgu...
let _gl_context = window .gl_create_context() .expect("Couldn't create GL context"); gl::load_with(|s| video_subsystem.gl_get_proc_address(s) as _); let mut imgui = imgui::Context::create(); imgui.io_mut().config_flags |= imgui::ConfigFlags::DOCKING_ENABLE; let mut path = std::path::...
{ let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let ttf_context = sdl2::ttf::init().unwrap(); { let gl_attr = video_subsystem.gl_attr(); gl_attr.set_context_profile(sdl2::video::GLProfile::Core); gl_attr.set_context_version(3, 0); ...
identifier_body
main.rs
extern crate gl; extern crate imgui; extern crate imgui_opengl_renderer; extern crate imgui_sdl2; extern crate sdl2; /* @TODO: - Show line numbers! - Use traits to Send, Parse and Draw - Create a checkbox to enable debugging the parser, queries, etc; - Write a logger to use a imgui window */ use imgu...
else { imgui::sys::ImGuiDockNode_IsSplitNode(node) } } } const STEP_COMMANDS: [&str; 5] = [ "step\n", "-data-list-register-values x 0 1 2 3 4 5 6 7 8 9 10\n", "-stack-list-locals 1\n", r#" -data-disassemble -s $pc -e "$pc + 20" -- 0 "#, r#" -data-read-memor...
{ false }
conditional_block
main.rs
extern crate gl; extern crate imgui; extern crate imgui_opengl_renderer; extern crate imgui_sdl2; extern crate sdl2; /* @TODO: - Show line numbers! - Use traits to Send, Parse and Draw - Create a checkbox to enable debugging the parser, queries, etc; - Write a logger to use a imgui window */ use imgu...
ui::docked_window(&ui, &mut gdb, "Vars", right_down, |ui, gdb| { ui.columns(2, im_str!("A"), true); for (k, v) in &gdb.variables { ui.text(k); ui.next_column(); ui.text(v); ui.next_column(); } }); ...
} else { ui.text_colored([x, x, x, 1.0f32], &l); } } });
random_line_split
main.rs
extern crate gl; extern crate imgui; extern crate imgui_opengl_renderer; extern crate imgui_sdl2; extern crate sdl2; /* @TODO: - Show line numbers! - Use traits to Send, Parse and Draw - Create a checkbox to enable debugging the parser, queries, etc; - Write a logger to use a imgui window */ use imgu...
() -> Result<(), Error> { let (tx, rx) = channel(); let gdb_mutex = Arc::new(Mutex::new(debugger::DebuggerState::new())); let mut child = start_process(rx, Arc::clone(&gdb_mutex)); send_commands(&tx, &STARTUP_COMMANDS, 100); start_graphics(Arc::clone(&gdb_mutex), move || {}, &tx); child.kil...
main
identifier_name
zhtta.rs
return true; } } return false; } } impl std::cmp::Ord for HTTP_Request { fn lt(&self, other: &HTTP_Request) -> bool { //First get the file sizes for the Http_Request let sizeSelf = fs::stat(self.path).size; let sizeOther = fs::stat(other.path).size; ...
} // TODO: Smarter Scheduling. fn dequeue_static_file_request(&mut self) { let req_queue_get = self.request_queue_arc.clone(); let stream_map_get = self.stream_map_arc.clone(); let cacheArc = self.cache.clone(); //Semaphore for counting tasks let s = Semaphore:...
}); notify_chan.send(()); // Send incoming notification to responder task.
random_line_split
zhtta.rs
return true; } } return false; } } impl std::cmp::Ord for HTTP_Request { fn lt(&self, other: &HTTP_Request) -> bool { //First get the file sizes for the Http_Request let sizeSelf = fs::stat(self.path).size; let sizeOther = fs::stat(other.path).size; ...
req_queue_arc.access(|local_req_queue| { debug!("Got queue mutex lock."); let req: HTTP_Request = req_port.recv(); local_req_queue.push(req); //debug!("Priority of new request is {:d}", getPriority(name.clone())); debug!("A new request enqueued, now th...
{ // Save stream in hashmap for later response. let mut stream = stream; let peer_name = WebServer::get_peer_name(&mut stream); let (stream_port, stream_chan) = Chan::new(); stream_chan.send(stream); unsafe { // Use an unsafe method, because TcpStream in Rust ...
identifier_body
zhtta.rs
return true; } } return false; } } impl std::cmp::Ord for HTTP_Request { fn lt(&self, other: &HTTP_Request) -> bool { //First get the file sizes for the Http_Request let sizeSelf = fs::stat(self.path).size; let sizeOther = fs::stat(other.path).size; ...
(stream: Option<std::io::net::tcp::TcpStream>, path: &Path) { let mut stream = stream; let msg: ~str = format!("Cannot open: {:s}", path.as_str().expect("invalid path").to_owned()); stream.write(HTTP_BAD.as_bytes()); stream.write(msg.as_bytes()); } // TODO: Safe visitor counter...
respond_with_error_page
identifier_name
zhtta.rs
notify_chan: SharedChan<()> } impl WebServer { fn new(ip: &str, port: uint, www_dir: &str) -> WebServer { let (notify_port, shared_notify_chan) = SharedChan::new(); let www_dir_path = ~Path::new(www_dir); os::change_dir(www_dir_path.clone()); WebServer { ip: ip.to_owned...
{ let semaphore = s.clone(); semaphore.acquire(); // TODO: Spawning more tasks to respond the dequeued requests concurrently. You may need a semophore to control the concurrency. semaphore.access( || { //Sending ...
conditional_block
mesh_generator.rs
* copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS ...
let minimum = Vec3::new( extent.minimum.0[0] as f32, extent.minimum.0[1] as f32, extent.minimum.0[2] as f32, ); let maximum = Vec3::new( extent.max().0[0] as f32, extent.ma...
{ let mut render_mesh = Mesh::new(PrimitiveTopology::TriangleList); let MeshBuf { positions, normals, tex_coords, layer, indices, extent, } = mesh_buf;...
conditional_block
mesh_generator.rs
* copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS ...
(&mut self, commands: &mut Commands, meshes: &mut Assets<Mesh>) { self.entities.retain(|_, (entity, mesh)| { clear_up_entity(entity, mesh, commands, meshes); false }); self.remove_queue.retain(|_, (entity, mesh)| { clear_up_entity(entity, mesh, commands, meshe...
clear_entities
identifier_name
mesh_generator.rs
* copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS ...
pub fn is_empty(&self) -> bool { self.commands.is_empty() } pub fn len(&self) -> usize { self.commands.len() } pub fn clear(&mut self) { self.commands.clear(); } } // PERF: try to eliminate the use of multiple Vecs #[derive(Clone, Debug, Eq, PartialEq)] pub enum Mesh...
{ self.commands.push_front(command); }
identifier_body
mesh_generator.rs
all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLD...
) }); } } } LodChunkUpdate3::Merge(merge) => { for lod_key in merge.old_chunks.iter() { ...
create_mesh_for_chunk( lod_key, voxel_map, local_mesh_buffers, ),
random_line_split
mod.rs
use crate::audio::*; use crate::format; use id3; use lazy_static::lazy_static; use liblame_sys::*; use log::*; use regex::bytes; use sample; use std::*; mod index; use self::index::FrameIndex; /// This is the absolute maximum number of samples that can be contained in a single frame. const MAX_FRAME_SIZE: usize = 115...
(err: io::Error) -> Error { Error::IO(err) } } impl From<id3::Error> for Error { fn from(err: id3::Error) -> Error { Error::ID3(err) } } impl From<index::Error> for Error { fn from(err: index::Error) -> Error { Error::Index(err) } } #[cfg(all(test, feature = "unstable"))] ...
from
identifier_name
mod.rs
use crate::audio::*; use crate::format; use id3; use lazy_static::lazy_static; use liblame_sys::*; use log::*; use regex::bytes; use sample; use std::*; mod index; use self::index::FrameIndex; /// This is the absolute maximum number of samples that can be contained in a single frame. const MAX_FRAME_SIZE: usize = 115...
} impl<F, R> Seekable for Decoder<F, R> where F: sample::Frame<Sample = i16>, R: io::Read + io::Seek +'static, { fn seek(&mut self, position: u64) -> Result<(), SeekError> { let i = self .frame_index .frame_for_sample(position) .ok_or(SeekError::OutofRange { ...
{ self.sample_rate }
identifier_body
mod.rs
use crate::audio::*; use crate::format; use id3; use lazy_static::lazy_static; use liblame_sys::*; use log::*; use regex::bytes; use sample; use std::*; mod index; use self::index::FrameIndex; /// This is the absolute maximum number of samples that can be contained in a single frame. const MAX_FRAME_SIZE: usize = 115...
$dyn(Box::from(Decoder { input, input_buf: [0; MAX_FRAME_BYTES], hip: init.hip, frame_index, sample_rate, buffers: init.buffers, next_frame: 0, ...
num_samples: Some(frame_index.num_samples()), tag: init.tag, }; macro_rules! dyn_type { ($dyn:path) => {
random_line_split
day3.rs
use { aoc_runner_derive::aoc, re_parse::{Error as ReParseError, ReParse, Regex}, serde_derive::Deserialize, std::{ cmp::max, mem::replace, ops::{Index, IndexMut}, slice::Iter as SliceIter, str::{FromStr, Split}, }, }; struct ClaimIterator<'s> { input: Spl...
} } let uncontested = claims .into_iter() .filter_map(|(c, uncontested)| if uncontested { Some(c) } else { None }) .collect::<Vec<_>>(); if uncontested.len()!= 1 { panic!("Expected single remaining claim, got {:?}", uncontested); } uncontested[0].id } #[test] ...
{ (&mut claims[i]).1 = false; (&mut claims[j]).1 = false; }
conditional_block
day3.rs
use { aoc_runner_derive::aoc, re_parse::{Error as ReParseError, ReParse, Regex}, serde_derive::Deserialize, std::{ cmp::max, mem::replace, ops::{Index, IndexMut}, slice::Iter as SliceIter, str::{FromStr, Split}, }, }; struct ClaimIterator<'s> { input: Spl...
() { const CLAIM_TO_COMPARE_TO: &'static str = "#0 @ 2,2: 3x3"; let claim: Claim = CLAIM_TO_COMPARE_TO.parse().unwrap(); for other in &[ // Close but not touching "#0 @ 1,1: 1x1", "#0 @ 2,1: 1x1", "#0 @ 3,1: 1x1", "#0 @ 4,1: 1x1", "#0 @ 5,1: 1x1", "#0...
test_intersection
identifier_name
day3.rs
use { aoc_runner_derive::aoc, re_parse::{Error as ReParseError, ReParse, Regex}, serde_derive::Deserialize, std::{ cmp::max, mem::replace, ops::{Index, IndexMut}, slice::Iter as SliceIter, str::{FromStr, Split}, }, }; struct ClaimIterator<'s> { input: Spl...
let count = grid[(x, y)]; assert!(count!= 0); if count > 1 { return false; } } } true }, ) .collect::<Vec<_>>(); ...
right, .. }| { for y in *top..*bottom { for x in *left..*right {
random_line_split
day3.rs
use { aoc_runner_derive::aoc, re_parse::{Error as ReParseError, ReParse, Regex}, serde_derive::Deserialize, std::{ cmp::max, mem::replace, ops::{Index, IndexMut}, slice::Iter as SliceIter, str::{FromStr, Split}, }, }; struct ClaimIterator<'s> { input: Spl...
#[aoc(day3, part2, square_iteration)] pub fn day3_part2_square_iteration(input: &str) -> usize { // OPT: Use ArrayVec for even more performance? Depends on max size. // OR OPT: Pre-allocating might be beneficial here, not sure how `size_hint` works for char // splits. let mut claims = ClaimIterator::n...
{ assert_eq!(day3_part1(HINT_INPUT), HINT_EXPECTED_PART1_OUTPUT); }
identifier_body
livestream.rs
use std::collections::{HashMap, BTreeMap}; use tokio::sync::mpsc::*; use std::{thread, fs}; use crate::camera::CameraProvider; use std::sync::Arc; use std::cell::RefCell; use tokio::sync::mpsc::error::TrySendError; use tokio::sync::mpsc::error::ErrorKind; use std::io::Write; use std::sync::mpsc as bchan; pu...
()->Self{ LiveStream{ next_client_id: 0, clients: BTreeMap::new(), cached_frames: RingBuffer::new(20), channel: channel(5), first_frame: None } } pub fn get_sender(&self)->Sender<IncomingMessage>{ self.channel.0.clone(...
new
identifier_name
livestream.rs
use std::collections::{HashMap, BTreeMap}; use tokio::sync::mpsc::*; use std::{thread, fs}; use crate::camera::CameraProvider; use std::sync::Arc; use std::cell::RefCell; use tokio::sync::mpsc::error::TrySendError; use tokio::sync::mpsc::error::ErrorKind; use std::io::Write; use std::sync::mpsc as bchan; pu...
data: v, size, start: 0, end: 0, offset: 0, next_index: 0 } } pub fn info(&self){ println!("<RingBuffer size={}, start={}, end={}, offset={}, next_index={}>", self.size, self.start, self.end, self.offset, self.next_...
v.push(None); } RingBuffer{
random_line_split
mod.rs
mod expr; mod static_init; mod stmt; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass}; use cranelift::codegen::{ self, ir::{ entities::StackSlot, function::Function, stackslot::{St...
( &mut self, params: Vec<Symbol>, func_start: Block, location: &Location, builder: &mut FunctionBuilder, ) -> CompileResult<()> { // Cranelift requires that all block params are declared up front let ir_vals: Vec<_> = params .iter() .map(...
store_stack_params
identifier_name
mod.rs
mod expr; mod static_init; mod stmt; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass}; use cranelift::codegen::{ self, ir::{ entities::StackSlot, function::Function, stackslot::{St...
location, })) }; let data = StackSlotData { kind, size, offset: None, }; let stack_slot = builder.create_stack_slot(data); self.scope.insert(decl.symbol.id, Id::Local(stack_slot)); if let Some(init) = decl.in...
data: "cannot store items on the stack that are more than 4 GB, it will overflow the stack".into(),
random_line_split
mod.rs
mod expr; mod static_init; mod stmt; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass}; use cranelift::codegen::{ self, ir::{ entities::StackSlot, function::Function, stackslot::{St...
} self.scope.exit(); builder.seal_all_blocks(); builder.finalize(); let flags = settings::Flags::new(settings::builder()); if self.debug { println!("{}", func); } if let Err(err) = codegen::verify_function(&func, &flags) { panic...
{ // void function, return nothing builder.ins().return_(&[]); }
conditional_block
mod.rs
mod expr; mod static_init; mod stmt; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass}; use cranelift::codegen::{ self, ir::{ entities::StackSlot, function::Function, stackslot::{St...
*location ), Ok(size) => size, }; let stack_data = StackSlotData { kind: StackSlotKind::ExplicitSlot, size: u32_size, offset: None, }; let slot = builder.create_stack_slot(...
{ // Cranelift requires that all block params are declared up front let ir_vals: Vec<_> = params .iter() .map(|param| { let ir_type = param.ctype.as_ir_type(); Ok(builder.append_block_param(func_start, ir_type)) }) .collect:...
identifier_body
fork_resolver.rs
/* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
// Delete states for all blocks not in chain let chain_len_to_delete = chain_head.block_num - cache_block.block_num; delete_states_upto( cache_block.block_id, chain_head.clone().block_id, ...
// Mark all blocks upto common ancestor // in the chain as invalid.
random_line_split
fork_resolver.rs
/* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
else { fork_won = if fork_cc < chain_cc { true } else { false }; } } } if fork_won { info!("Discarding the block in progress."); service.cancel_block(); pu...
{ fork_won = if get_cert_from(&block).duration_id < get_cert_from(&chain_head).duration_id { true } else { false ...
conditional_block
fork_resolver.rs
/* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
( ancestor: BlockId, head: BlockId, delete_len: u64, service: &mut Poet2Service, state_store: &mut ConsensusStateStore, ) -> () { let mut next = head; let mut count = 0_u64; loop { if ancestor == next || count >= delete_len { break; } count += 1; ...
delete_states_upto
identifier_name
fork_resolver.rs
/* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
state_store.delete(next.clone()); next = BlockId::from( state_ .unwrap() .estimate_info .previous_block_id .as_bytes() .to_vec(), ); } } } fn get_cert_from(blo...
{ let mut next = head; let mut count = 0_u64; loop { if ancestor == next || count >= delete_len { break; } count += 1; let state_ = state_store.get(next.clone()); if state_.is_err() { debug!("State not found. Getting block via service."); ...
identifier_body
actions.rs
use crate::{ dkg_contract::{DKG as DKGContract, DKG_ABI}, opts::*, }; use rand::{CryptoRng, RngCore}; use std::{fs::File, io::Write, sync::Arc}; use dkg_core::{ primitives::{joint_feldman::*, resharing::RDKG, *}, DKGPhase, Phase2Result, }; use anyhow::Result; use ethers::prelude::*; use ethers::provid...
Err(err) => Err(anyhow::anyhow!("DKG error: {}", err)), } } #[derive(serde::Serialize, Debug)] struct OutputJson { #[serde(rename = "publicKey")] public_key: String, #[serde(rename = "publicPolynomial")] public_polynomial: String, #[serde(rename = "share")] share: String, } async ...
{ println!("Success. Your share and threshold pubkey are ready."); if let Some(path) = output_path { let file = File::create(path)?; write_output(&file, &output)?; } else { write_output(std::io::stdout(), &output)?; } ...
conditional_block
actions.rs
use crate::{ dkg_contract::{DKG as DKGContract, DKG_ABI}, opts::*, }; use rand::{CryptoRng, RngCore}; use std::{fs::File, io::Write, sync::Arc}; use dkg_core::{ primitives::{joint_feldman::*, resharing::RDKG, *}, DKGPhase, Phase2Result, }; use anyhow::Result; use ethers::prelude::*; use ethers::provid...
let contract = DKGContract::new(opts.contract_address, client); for addr in opts.address { let tx = contract.allowlist(addr).block(BlockNumber::Pending); let tx = tx.send().await?.await?; println!("Sent `allow` tx for {:?} (hash: {:?})", addr, tx); } Ok(()) } pub async fn sta...
let client = Arc::new(client);
random_line_split
actions.rs
use crate::{ dkg_contract::{DKG as DKGContract, DKG_ABI}, opts::*, }; use rand::{CryptoRng, RngCore}; use std::{fs::File, io::Write, sync::Arc}; use dkg_core::{ primitives::{joint_feldman::*, resharing::RDKG, *}, DKGPhase, Phase2Result, }; use anyhow::Result; use ethers::prelude::*; use ethers::provid...
<P, C, R, M: Middleware +'static>( mut dkg: DKGContract<M>, phase0: P, rng: &mut R, output_path: Option<String>, ) -> Result<()> where C: Curve, // We need to bind the Curve's Point and Scalars to the Scheme // S: Scheme<Public = <C as Curve>::Point, Private = <C as Curve>::Scalar>, P: P...
run_dkg
identifier_name
transaction_verify_centre.rs
//! The `tvu` module implements the Transaction Validation Unit, a //! multi-stage transaction validation pipeline in software. //! //! 1. BlobFetchStage //! - Incoming blobs are picked up from the TVU sockets and repair socket. //! 2. RetransmitStage //! - Blobs are windowed until a contiguous chunk is available. Thi...
.skip_while(|line| line.starts_with("#!")) .skip_while(|line| line.is_empty()) .take(2) .map(|s| s.trim_start_matches("# ")); !LICENSE_HEADER.lines().eq(maybe_license) } }; if missing_header { return Err("missing a license h...
random_line_split
transaction_verify_centre.rs
//! The `tvu` module implements the Transaction Validation Unit, a //! multi-stage transaction validation pipeline in software. //! //! 1. BlobFetchStage //! - Incoming blobs are picked up from the TVU sockets and repair socket. //! 2. RetransmitStage //! - Blobs are windowed until a contiguous chunk is available. Thi...
{ pub fetch: Vec<UdpSocket>, pub repair: UdpSocket, pub retransmit: UdpSocket, } impl Tvu { /// This service receives messages from a leader in the network and processes the transactions /// on the bank state. /// # Arguments /// * `node_group_info` - The node_group_info state. /// * `...
Sockets
identifier_name
transaction_verify_centre.rs
//! The `tvu` module implements the Transaction Validation Unit, a //! multi-stage transaction validation pipeline in software. //! //! 1. BlobFetchStage //! - Incoming blobs are picked up from the TVU sockets and repair socket. //! 2. RetransmitStage //! - Blobs are windowed until a contiguous chunk is available. Thi...
//TODO //the packets coming out of blob_receiver need to be sent to the GPU and verified //then sent to the window, which does the erasure coding reconstruction let retransmit_stage = RetransmitStage::new( bank_forks.clone(), leader_schedule_cache, bl...
{ let keypair: Arc<Keypair> = node_group_info .read() .expect("Unable to read from node_group_info during Tvu creation") .keypair .clone(); let Sockets { repair: repair_socket, fetch: fetch_sockets, retransmit: retransm...
identifier_body
transaction_verify_centre.rs
//! The `tvu` module implements the Transaction Validation Unit, a //! multi-stage transaction validation pipeline in software. //! //! 1. BlobFetchStage //! - Incoming blobs are picked up from the TVU sockets and repair socket. //! 2. RetransmitStage //! - Blobs are windowed until a contiguous chunk is available. Thi...
}; if missing_header { return Err("missing a license header".into()); } Ok(()) } #[cfg(test)] pub mod tests { use super::*; use crate::treasury_stage::create_test_recorder; use crate::block_buffer_pool::get_tmp_ledger_path; use crate::node_group_info::{NodeGroupInfo, Node}; ...
{ let maybe_license = contents .lines() .skip_while(|line| line.starts_with("#!")) .skip_while(|line| line.is_empty()) .take(2) .map(|s| s.trim_start_matches("# ")); !LICENSE_HEADER.lines().eq(maybe_license) ...
conditional_block