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 |
|---|---|---|---|---|
multi.rs | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! The multi-threaded worker, which is used when there are multiple worker
//! threads configured. This worker parses buffers to produce requests, sends
//! the requests to the storage worke... | _storage: PhantomData<Storage>,
_request: PhantomData<Request>,
_response: PhantomData<Response>,
}
impl<Storage, Parser, Request, Response> MultiWorkerBuilder<Storage, Parser, Request, Response> {
/// Create a new builder from the provided config and parser.
pub fn new<T: WorkerConfig>(config: &T,... | poll: Poll,
timeout: Duration, | random_line_split |
multi.rs | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! The multi-threaded worker, which is used when there are multiple worker
//! threads configured. This worker parses buffers to produce requests, sends
//! the requests to the storage worke... |
// handle write events before read events to reduce write buffer
// growth if there is also a readable event
if event.is_writable() {
WORKER_EVENT_WRITE.increment();
self.do_write(token);
}
// read events are handled last
if event.is_readable() ... | {
WORKER_EVENT_ERROR.increment();
self.handle_error(token);
} | conditional_block |
multi.rs | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! The multi-threaded worker, which is used when there are multiple worker
//! threads configured. This worker parses buffers to produce requests, sends
//! the requests to the storage worke... |
}
/// Represents a finalized request/response worker which is ready to be run.
pub struct MultiWorker<Storage, Parser, Request, Response> {
nevent: usize,
parser: Parser,
poll: Poll,
timeout: Duration,
session_queue: Queues<(), Session>,
signal_queue: Queues<(), Signal>,
_storage: PhantomD... | {
MultiWorker {
nevent: self.nevent,
parser: self.parser,
poll: self.poll,
timeout: self.timeout,
signal_queue,
_storage: PhantomData,
storage_queue,
session_queue,
}
} | identifier_body |
multi.rs | // Copyright 2021 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! The multi-threaded worker, which is used when there are multiple worker
//! threads configured. This worker parses buffers to produce requests, sends
//! the requests to the storage worke... | (&mut self, sessions: &mut Vec<TrackedItem<Session>>) {
self.session_queue.try_recv_all(sessions);
for session in sessions.drain(..).map(|v| v.into_inner()) {
let pending = session.read_pending();
trace!(
"new session: {:?} with {} bytes pending in read buffer",
... | handle_new_sessions | identifier_name |
wasm.rs | gui_wasm";
pub const DEFAULT_TARGET_CRATE: &str = "app/gui";
#[derive(
clap::ArgEnum,
Clone,
Copy,
Debug,
Default,
strum::Display,
strum::EnumString,
PartialEq,
Eq
)]
#[strum(serialize_all = "kebab-case")]
pub enum ProfilingLevel {
#[default]
Objective,
Task,
Detail... | log_level,
uncollapsed_log_level,
wasm_size_limit: _wasm_size_limit,
system_shader_tools,
} = &inner;
// NOTE: We cannot trust locally installed version of shader tools to be correct.
// Those binaries have no reliable ... | {
let Context { octocrab: _, cache, upload_artifacts: _, repo_root } = context;
let WithDestination { inner, destination } = job;
let span = info_span!("Building WASM.",
repo = %repo_root.display(),
crate = %inner.crate_path.display(),
cargo_opts = ?inner.extr... | identifier_body |
wasm.rs | "gui_wasm";
pub const DEFAULT_TARGET_CRATE: &str = "app/gui";
#[derive(
clap::ArgEnum,
Clone,
Copy,
Debug,
Default,
strum::Display,
strum::EnumString,
PartialEq,
Eq
)]
#[strum(serialize_all = "kebab-case")]
pub enum ProfilingLevel {
#[default]
Objective,
Task,
Deta... | if!self.profile.should_check_size() {
warn!("Skipping size check because profile is '{}'.", self.profile,);
} else if self.profiling_level.unwrap_or_default()!= ProfilingLevel::Objective {
// TODO? additional leeway as sanity check
warn!(
... | info!("Compressed size of {} is {}.", wasm_path.as_ref().display(), compressed_size);
if let Some(wasm_size_limit) = self.wasm_size_limit {
let wasm_size_limit = wasm_size_limit.get_appropriate_unit(true); | random_line_split |
wasm.rs | gui_wasm";
pub const DEFAULT_TARGET_CRATE: &str = "app/gui";
#[derive(
clap::ArgEnum,
Clone,
Copy,
Debug,
Default,
strum::Display,
strum::EnumString,
PartialEq,
Eq
)]
#[strum(serialize_all = "kebab-case")]
pub enum ProfilingLevel {
#[default]
Objective,
Task,
Detail... | (&self) -> Result {
Cargo
.cmd()?
.apply(&cargo::Command::Check)
.apply(&cargo::Options::Workspace)
.apply(&cargo::Options::Package(INTEGRATION_TESTS_CRATE_NAME.into()))
.apply(&cargo::Options::AllTargets)
.run_ok()
.await
}
p... | check | identifier_name |
wasm.rs | #[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct BuildInput {
/// Path to the crate to be compiled to WAM. Relative to the repository root.
pub crate_path: PathBuf,
pub wasm_opt_options: Vec<String>,
pub skip_wasm_opt: bool,
pub extra_cargo_options: Vec<String>,... | {
let mut wasm_opt_command = WasmOpt.cmd()?;
let has_custom_opt_level = wasm_opt_options.iter().any(|opt| {
wasm_opt::OptimizationLevel::from_str(opt.trim_start_matches('-')).is_ok()
});
if !has_custom_opt_level {
wasm_opt_command.apply(&pr... | conditional_block | |
server.rs | use std::thread;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::collections::VecDeque;
use std::io::BufReader;
// MIO
use mio::tcp::{listen, TcpListener, TcpStream};
use mio::util::Slab;
use mio::Socket;
use mio::buf::{RingBuf};
use mio::{Interest, PollOpt, NonBlock, Token, EventLoop, Handler, ReadH... | <S, M>(&mut self, event_loop: &mut EventLoop<Server<S, M>>, replica: &mut Replica<S,M>)
-> Result<()>
where S: Store, M: StateMachine {
// Attempt to write data.
// The `current_write` buffer will be advanced based on how much we wrote.
match self.stream.write(self.curr... | writable | identifier_name |
server.rs | use std::thread;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::collections::VecDeque;
use std::io::BufReader;
// MIO
use mio::tcp::{listen, TcpListener, TcpStream};
use mio::util::Slab;
use mio::Socket;
use mio::buf::{RingBuf};
use mio::{Interest, PollOpt, NonBlock, Token, EventLoop, Handler, ReadH... | -> Result<()>
where S: Store, M: StateMachine {
let mut read = 0;
match self.stream.read(self.current_read.get_mut()) {
Ok(Some(r)) => {
// Just read `r` bytes.
read = r;
},
Ok(None) => panic!("We just got read... | fn readable<S, M>(&mut self, event_loop: &mut EventLoop<Server<S, M>>, replica: &mut Replica<S,M>) | random_line_split |
server.rs | use std::thread;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::collections::VecDeque;
use std::io::BufReader;
// MIO
use mio::tcp::{listen, TcpListener, TcpStream};
use mio::util::Slab;
use mio::Socket;
use mio::buf::{RingBuf};
use mio::{Interest, PollOpt, NonBlock, Token, EventLoop, Handler, ReadH... | ,
None => (),
}
},
_ => unimplemented!(),
}
} else if let Ok(client_req) = reader.get_root::<client_request::Reader>() {
let mut should_die = false;
// We will be responding.
match client... | {
// Won an election!
self.broadcast(builder_message);
} | conditional_block |
group.rs |
left * q.j,
-left * q.i,
q.w,
],
))
}
/// Computes the [direct sum](https://en.wikipedia.org/wiki/Block_matrix#Direct_sum)
/// of two matrices.
fn direct_sum(mat1: Matrix<f64>, mat2: Matrix<f64>) -> Matrix<f64> {
let dim1 = mat1.nrows();
let dim = dim1 + mat2.nr... |
/// Generates the trivial group of a certain dimension.
pub fn trivial(dim: usize) -> Self {
Self {
dim,
iter: Box::new(std::iter::once(Matrix::identity(dim, dim))),
}
}
/// Generates the group with the identity and a central inversion of a
/// certain dime... | {
let dim = self.dim;
Self {
dim,
iter: Box::new(self.map(move |x| {
let msg = "Size of matrix does not match expected dimension.";
assert_eq!(x.nrows(), dim, "{}", msg);
assert_eq!(x.ncols(), dim, "{}", msg);
x
... | identifier_body |
group.rs | ,
left * q.j,
-left * q.i,
q.w,
],
))
}
/// Computes the [direct sum](https://en.wikipedia.org/wiki/Block_matrix#Direct_sum)
/// of two matrices.
fn direct_sum(mat1: Matrix<f64>, mat2: Matrix<f64>) -> Matrix<f64> {
let dim1 = mat1.nrows();
let dim = dim1 + mat2.n... | let nn = n.norm_squared();
// Reflects every basis vector, builds a matrix from all of their images.
Matrix::from_columns(
&Matrix::identity(dim, dim)
.column_iter()
.map(|v| v - (2.0 * v.dot(&n) / nn) * &n)
.collect::<Vec<_>>(),
)
}
impl GenIter {
/// Buil... | random_line_split | |
group.rs |
left * q.j,
-left * q.i,
q.w,
],
))
}
/// Computes the [direct sum](https://en.wikipedia.org/wiki/Block_matrix#Direct_sum)
/// of two matrices.
fn direct_sum(mat1: Matrix<f64>, mat2: Matrix<f64>) -> Matrix<f64> {
let dim1 = mat1.nrows();
let dim = dim1 + mat2.nr... | (self, left: bool) -> Box<dyn GroupIter> {
if self.dim!= 3 {
panic!("Quaternions can only be generated from 3D matrices.");
}
Box::new(
self.rotations()
.map(move |el| quat_to_mat(mat_to_quat(el), left)),
)
}
/// Returns the swirl symmetry... | quaternions | identifier_name |
task.rs | use notifier::Notifier;
use sender::Sender;
use futures::{self, future, Future, Async};
use futures::executor::{self, Spawn};
use std::{fmt, mem, panic, ptr};
use std::cell::Cell;
use std::sync::Arc;
use std::sync::atomic::{self, AtomicUsize, AtomicPtr};
use std::sync::atomic::Ordering::{AcqRel, Acquire, Release, Rel... | (&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Task")
.field("inner", self.inner())
.finish()
}
}
impl Clone for Task {
fn clone(&self) -> Task {
use std::isize;
const MAX_REFCOUNT: usize = (isize::MAX) as usize;
// Using a relaxed or... | fmt | identifier_name |
task.rs | use notifier::Notifier;
use sender::Sender;
use futures::{self, future, Future, Async};
use futures::executor::{self, Spawn};
use std::{fmt, mem, panic, ptr};
use std::cell::Cell;
use std::sync::Arc;
use std::sync::atomic::{self, AtomicUsize, AtomicPtr};
use std::sync::atomic::Ordering::{AcqRel, Acquire, Release, Rel... |
}
impl From<usize> for State {
fn from(src: usize) -> Self {
use self::State::*;
match src {
0 => Idle,
1 => Running,
2 => Notified,
3 => Scheduled,
4 => Complete,
_ => unreachable!(),
}
}
}
impl From<State> for ... | {
State::Idle
} | identifier_body |
task.rs | use notifier::Notifier;
use sender::Sender;
use futures::{self, future, Future, Async};
use futures::executor::{self, Spawn};
use std::{fmt, mem, panic, ptr};
use std::cell::Cell;
use std::sync::Arc;
use std::sync::atomic::{self, AtomicUsize, AtomicPtr};
use std::sync::atomic::Ordering::{AcqRel, Acquire, Release, Rel... |
impl Inner {
fn stub() -> Inner {
Inner {
next: AtomicPtr::new(ptr::null_mut()),
state: AtomicUsize::new(State::stub().into()),
ref_count: AtomicUsize::new(0),
future: Some(TaskFuture::Futures1(executor::spawn(Box::new(future::empty())))),
}
}
... |
// ===== impl Inner ===== | random_line_split |
file_hook.rs | use std::ffi::CStr;
use std::ptr::null_mut;
use arrayvec::ArrayVec;
use lazy_static::lazy_static;
use libc::c_void;
use super::scr;
use super::thiscall::Thiscall;
pub fn open_file_hook(
out: *mut scr::FileHandle,
path: *const u8,
params: *const scr::OpenParams,
orig: unsafe extern fn(
*mut sc... |
unsafe extern fn read_file(file: *mut scr::FileRead, out: *mut u8, size: u32) -> u32 {
let file = (*file).inner as *mut FileAllocation;
let buf = std::slice::from_raw_parts_mut(out, size as usize);
(*file).file.read(buf)
}
unsafe extern fn skip(file: *mut scr::FileRead, size: u32) {
let file = (*file... | {
let read = (*file).read;
let vtable = (*read).vtable;
(*vtable).skip.call2(read, size)
} | identifier_body |
file_hook.rs | use std::ffi::CStr;
use std::ptr::null_mut;
use arrayvec::ArrayVec;
use lazy_static::lazy_static;
use libc::c_void;
use super::scr;
use super::thiscall::Thiscall;
pub fn open_file_hook(
out: *mut scr::FileHandle,
path: *const u8,
params: *const scr::OpenParams,
orig: unsafe extern fn(
*mut sc... | true => match c_path.iter().rev().position(|&x| x == b'.') {
Some(period) => &c_path[..c_path.len() - period - 1],
None => c_path,
},
false => c_path,
};
if let Err(_) = buffer.try_extend_from_slice(c_path_for_switched_extension) {
return None;
}
i... | let c_path_for_switched_extension = match alt_extension.is_some() { | random_line_split |
file_hook.rs | use std::ffi::CStr;
use std::ptr::null_mut;
use arrayvec::ArrayVec;
use lazy_static::lazy_static;
use libc::c_void;
use super::scr;
use super::thiscall::Thiscall;
pub fn open_file_hook(
out: *mut scr::FileHandle,
path: *const u8,
params: *const scr::OpenParams,
orig: unsafe extern fn(
*mut sc... | (buffer: &'static [u8], handle: *mut scr::FileHandle) {
let inner = Box::new(FileAllocation {
file: FileState {
buffer,
pos: 0,
},
read: scr::FileRead {
vtable: &*FILE_READ_VTABLE,
inner: null_mut(),
},
peek: scr::FilePeek {
... | memory_buffer_to_bw_file_handle | identifier_name |
net.rs | // Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... |
}
}
| {
// `Client` is already dropped, no need to disconnect again.
} | conditional_block |
net.rs | // Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... | <R: tl::RemoteCall>(
&mut self,
request: &R,
) -> Result<R::Return, InvocationError> {
let (response, rx) = oneshot::channel();
// TODO add a test this (using handle with client dropped)
if let Err(_) = self.tx.send(Request::Rpc {
request: request.to_bytes(),
... | invoke | identifier_name |
net.rs | // Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... | }
} | } | random_line_split |
net.rs | // Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... | sender
};
// TODO handle -404 (we had a previously-valid authkey, but server no longer knows about it)
// TODO all up-to-date server addresses should be stored in the session for future initial connections
let _remote_config = sender
.invoke(&tl::functions::InvokeWithLayer {
... | {
let transport = transport::Full::new();
let addr = DC_ADDRESSES[dc_id as usize];
let mut sender = if let Some(auth_key) = config.session.auth_key.as_ref() {
info!(
"creating a new sender with existing auth key to dc {} {:?}",
dc_id, addr
);
sender::connect... | identifier_body |
main.rs | use crate::{
config::{save_config, Config},
repo::Repo,
};
use anyhow::{anyhow, bail, Context, Result};
use clap::{AppSettings, Clap};
use lazy_static::lazy_static;
use regex::Regex;
use std::env;
use std::io::{self, Read};
use url::Url;
mod config;
mod git;
mod github;
mod gitlab;
mod repo;
lazy_static! {
... | {
Git,
Saved,
}
impl ScriptSource {
fn parse(script: &str, action: ScriptAction) -> Result<ScriptSource> {
if let Some(matches) = API_SOURCE_REGEX.captures(script) {
let repo = matches
.name("alias")
.expect("No alias matched")
.as_str()
... | SourceType | identifier_name |
main.rs | use crate::{
config::{save_config, Config},
repo::Repo,
};
use anyhow::{anyhow, bail, Context, Result};
use clap::{AppSettings, Clap};
use lazy_static::lazy_static;
use regex::Regex;
use std::env;
use std::io::{self, Read};
use url::Url;
mod config;
mod git;
mod github;
mod gitlab;
mod repo;
lazy_static! {
... | SourceType::Git => git::GitRepo::from_src(&self),
};
let rref = self.rref.clone().unwrap_or("HEAD".to_owned());
Ok(repo.fetch_script(&self.script_name, &rref, fresh).await?)
}
}
async fn validate_api_repo(
uri: &str,
username: Option<String>,
password: Password,
) -... | .get(&self.repo)
.ok_or(anyhow!("Repo `{}` was not found", &self.repo))?
.box_clone(), | random_line_split |
main.rs | use crate::{
config::{save_config, Config},
repo::Repo,
};
use anyhow::{anyhow, bail, Context, Result};
use clap::{AppSettings, Clap};
use lazy_static::lazy_static;
use regex::Regex;
use std::env;
use std::io::{self, Read};
use url::Url;
mod config;
mod git;
mod github;
mod gitlab;
mod repo;
lazy_static! {
... | .context("Failed to save updated config")?;
println!("Repo `{}` was successfully added", &name);
}
RepoCommand::Remove { name } => {
if!config.repo.contains_key(&name) {
bail!("Repo `{}` was not found", &name);
... | {
if config.repo.contains_key(&name) {
bail!("A repository with the name `{}` already exists", &name);
}
let password_for_parse = match (password, password_env, password_stdin) {
(Some(pass), _, _) => Password::Saved(pass),
... | conditional_block |
ledger_manager.rs | use crate::crypto::hash::{H256, Hashable};
use crate::blockchain::Blockchain;
use crate::block::Content;
use crate::transaction::SignedTransaction;
use crate::utxo::UtxoState;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::sync::{Arc, Mutex};
use... | }
num_confirmed_votes.insert(*block, total_k_deep_votes);
}
}
for (proposer, votes) in num_confirmed_votes.iter() {
println!("proposer {:?} votes {}", proposer, *votes);
if *votes > (num_voter_chains / 2) {
new_leade... | {
//TODO: We might also need number of voter blocks at a particular level of a voter chain
//This is not urgent as we can **assume**, there is one block at each level
let voters_info = &locked_blockchain.proposer2voterinfo[block];
if voter... | conditional_block |
ledger_manager.rs | use crate::crypto::hash::{H256, Hashable};
use crate::blockchain::Blockchain;
use crate::block::Content;
use crate::transaction::SignedTransaction;
use crate::utxo::UtxoState;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::sync::{Arc, Mutex};
use... | {
pub last_level_processed: u32,
pub leader_sequence: Vec<H256>,
pub proposer_blocks_processed: HashSet<H256>,
pub tx_confirmed: HashSet<H256>,
pub tx_count: usize,
}
//ledger-manager will periodically loop and confirm the transactions
pub struct LedgerManager {
pub ledger_manager_state: Ledg... | LedgerManagerState | identifier_name |
ledger_manager.rs | use crate::crypto::hash::{H256, Hashable};
use crate::blockchain::Blockchain;
use crate::block::Content;
use crate::transaction::SignedTransaction;
use crate::utxo::UtxoState;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::sync::{Arc, Mutex};
use... |
fn get_leader_sequence(&mut self) -> Vec<H256> {
let locked_blockchain = self.blockchain.lock().unwrap();
let mut leader_sequence: Vec<H256> = vec![];
//TODO: This is a workaround for now till we have some DS which asserts that
//all voter chains at a particular level has... | {
loop{
//Step 1
//let leader_sequence = self.get_leader_sequence();
//This one uses the algorithm described in Prism Paper
let leader_sequence = self.get_confirmed_leader_sequence();
//Step 2
let tx_sequence = sel... | identifier_body |
ledger_manager.rs | use crate::crypto::hash::{H256, Hashable};
use crate::blockchain::Blockchain;
use crate::block::Content;
use crate::transaction::SignedTransaction;
use crate::utxo::UtxoState;
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use std::sync::{Arc, Mutex};
use... | }
fn confirm_transactions(&mut self, tx_sequence: &Vec<SignedTransaction>) {
self.ledger_manager_state.tx_count += tx_sequence.len();
// println!("Number of transactions considered yet {}", self.ledger_manager_state.tx_count);
let mut locked_utxostate = self.utxo_state.lock().unwrap();
... | self.ledger_manager_state.proposer_blocks_processed.insert(*leader);
}
tx_sequence | random_line_split |
rtc_api.rs | #![allow(dead_code)]
use bitflags::*;
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub enum Weekday {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
impl Default for Weekday {
fn default() -> Self { Weekday::Sunday }
}
#[derive(Deb... | (settings: &[u8]) -> Option<u64> {
const CTL3: usize = 0;
const SECS: usize = 1;
const MINS: usize = 2;
const HOURS: usize = 3;
const DAYS: usize = 4;
// note 5 is skipped - this is weekdays, and is unused
const MONTHS: usize = 6;
const YEARS: usize = 7;
if ((settings[CTL3] & 0xE0)!=... | rtc_to_seconds | identifier_name |
rtc_api.rs | #![allow(dead_code)]
use bitflags::*;
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub enum Weekday {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
impl Default for Weekday {
fn default() -> Self { Weekday::Sunday }
}
#[derive(Deb... |
pub fn to_binary(bcd: u8) -> u8 {
(bcd & 0xf) + ((bcd >> 4) * 10)
} | } | random_line_split |
mod.rs | //! Extensions to [`Target`](super::Target) which add support for various
//! subsets of the GDB Remote Serial Protocol.
//!
//! ### Note: Missing Protocol Extensions
//!
//! `gdbstub`'s development is guided by the needs of its contributors, with
//! new features being added on an "as-needed" basis.
//!
//! If there's... | //! methods!
//!
//! Aside from the cognitive complexity of having so many methods on a single
//! trait, this approach had numerous other drawbacks as well:
//!
//! - Implementations that did not implement all available protocol extensions
//! still had to "pay" for the unused packet parsing/handler code, resultin... | //! to the extreme, would have resulted in literally _hundreds_ of associated | random_line_split |
main.rs | extern crate cgmath;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate image;
extern crate lodepng;
extern crate offscreen_gl_context;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
extern crate winit;
use euclid::Size2D;
use gleam::gl;
use offscreen_gl_context::{ColorAttachmentT... | gl_Position = scale * vec4(0.5 * a_Pos, 0.0, 1.0);
}
";
const FS_SHADER: &'static str = "
#version 150 core
in vec4 v_Color;
out vec4 Target0;
void main() {
Target0 = v_Color;
}
";
const VERTICES: &'static [[f32;2];3] = &[
[-1.0, -0.57],
[ 1.0, -0.57],
... | v_Color = vec4(a_Color, 1.0); | random_line_split |
main.rs | extern crate cgmath;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate image;
extern crate lodepng;
extern crate offscreen_gl_context;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
extern crate winit;
use euclid::Size2D;
use gleam::gl;
use offscreen_gl_context::{ColorAttachmentT... | () -> GlHandles {
GlHandles {
vao: Cell::new(0 as gl::GLuint),
vbos: Cell::new([0,0]),
program: Cell::new(0 as gl::GLuint),
scale: Cell::new(0.0),
}
}
}
const CLEAR_COLOR: (f32, f32, f32, f32) = (0.0, 0.2, 0.3, 1.0);
const WIN_WIDTH: i32 = 256;
const ... | new | identifier_name |
main.rs | extern crate cgmath;
extern crate euclid;
extern crate gleam;
extern crate glutin;
extern crate image;
extern crate lodepng;
extern crate offscreen_gl_context;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
extern crate winit;
use euclid::Size2D;
use gleam::gl;
use offscreen_gl_context::{ColorAttachmentT... |
}
fn compile_shaders(handles: &GlHandles) {
handles.program.set(gl::create_program());
if handles.program.get() == (0 as gl::GLuint) {
panic!("Failed to create shader program");
}
add_shader(handles.program.get(), VS_SHADER, gl::VERTEX_SHADER);
add_shader(handles.program.get(), FS_SHADER,... | {
if !log.is_empty() {
println!("Warnings detected on shader:\n{}", log);
}
gl::attach_shader(program, id);
} | conditional_block |
types.rs | extern crate "rustc-serialize" as rustc_serialize;
extern crate uuid;
use uuid::Uuid;
use rustc_serialize::{json, Encodable, Decodable};
use rustc_serialize::base64::{ToBase64, FromBase64, Config, CharacterSet, Newline};
use types::NodeState::{Leader, Follower, Candidate};
use types::TransactionState::{Polling, Accept... | <T: Encodable + Decodable + Send + Clone> {
current_term: u64,
voted_for: Option<u64>, // request_vote cares if this is `None`
log: File,
last_index: u64, // The last index of the file.
last_term: u64, // The last index of the file.
marker: marker::PhantomData<T>, /... | PersistentState | identifier_name |
types.rs | extern crate "rustc-serialize" as rustc_serialize;
extern crate uuid;
use uuid::Uuid;
use rustc_serialize::{json, Encodable, Decodable};
use rustc_serialize::base64::{ToBase64, FromBase64, Config, CharacterSet, Newline};
use types::NodeState::{Leader, Follower, Candidate};
use types::TransactionState::{Polling, Accept... | // Add 2,3 again. (4 should be purged)
assert_eq!(state.append_entries(1, 2,
vec![(2, "Two".to_string()),
(3, "Three".to_string())]),
Ok(()));
assert_eq!(state.get_last_index(), 3);
fs::remove_file(&path.clone());
} | (3, "Three".to_string()),
(4, "Four".to_string())]),
Ok(()));
assert_eq!(state.get_last_index(), 4); | random_line_split |
types.rs | extern crate "rustc-serialize" as rustc_serialize;
extern crate uuid;
use uuid::Uuid;
use rustc_serialize::{json, Encodable, Decodable};
use rustc_serialize::base64::{ToBase64, FromBase64, Config, CharacterSet, Newline};
use types::NodeState::{Leader, Follower, Candidate};
use types::TransactionState::{Polling, Accept... | ;
self.last_term = last_term;
Ok(())
}
fn encode(entry: T) -> String {
let json_encoded = json::encode(&entry)
.unwrap(); // TODO: Don't unwrap.
json_encoded.as_bytes().to_base64(Config {
char_set: CharacterSet::UrlSafe,
newline: Newline::LF,
... | { prev_log_index + number as u64 } | conditional_block |
feature_table.rs | //! # Feature Table
//!
//! Data model and parsers for the DDBJ/ENA/GenBank Feature Table.
//!
//! See: http://www.insdc.org/files/feature_table.html
use nom::{
IResult,
branch::{
alt,
},
bytes::complete::{
tag,
take_while_m_n,
take_while,
take_while1,
},
character::{
is_alphanumeri... | expect(
"340..565",
LocOp::Loc(Loc::Local(Local::Span {
from: Position::Point(Point(340)),
to: Position::Point(Point(565)),
before_from: false,
after_to: false
})));
expect(
"<345..500",
LocOp::Loc(Loc::Local(Local::Span {
from: Position::... | random_line_split | |
feature_table.rs | //! # Feature Table
//!
//! Data model and parsers for the DDBJ/ENA/GenBank Feature Table.
//!
//! See: http://www.insdc.org/files/feature_table.html
use nom::{
IResult,
branch::{
alt,
},
bytes::complete::{
tag,
take_while_m_n,
take_while,
take_while1,
},
character::{
is_alphanumeri... | ))(input)
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Loc {
Remote { within: String, at: Local },
Local(Local)
}
impl <'a, E : ParseError<&'a str>> Nommed<&'a str, E> for Loc {
fn nom(input: &'a str) -> IResult<&'a str, Loc, E> {
let parse_accession = take_while1(|c| {
let b = c as u8;
is_alpha... | {
let parse_within = map(
tuple((Point::nom, tag("."), Point::nom)),
|(from, _, to)| Local::Within { from, to });
let parse_span = map(
tuple((
opt(tag("<")), Position::nom, tag(".."), opt(tag(">")), Position::nom)),
|(before_from, from, _, after_to, to)| Local::Span {
f... | identifier_body |
feature_table.rs | //! # Feature Table
//!
//! Data model and parsers for the DDBJ/ENA/GenBank Feature Table.
//!
//! See: http://www.insdc.org/files/feature_table.html
use nom::{
IResult,
branch::{
alt,
},
bytes::complete::{
tag,
take_while_m_n,
take_while,
take_while1,
},
character::{
is_alphanumeri... | {
key: String,
location: LocOp,
qualifiers: Vec<Qualifier>
}
// impl <'a, E : ParseError<&'a str>> Nommed<&'a str, E> for FeatureRecord {
// fn nom(input: &'a str) -> IResult<&'a str, FeatureRecord, E> {
// }
// }
/// An ID that's valid within the feature table.
///
/// This is:
/// * At least one let... | FeatureRecord | identifier_name |
condition_strategy_generators.rs | use crate::ai_utils::playout_result;
use crate::competing_optimizers::StrategyOptimizer;
use crate::condition_strategy::{
Condition, ConditionKind, ConditionStrategy, EvaluatedPriorities, EvaluationData, Rule,
};
use crate::representative_sampling::NewFractalRepresentativeSeedSearch;
use crate::seed_system::{Seed, Si... |
let mut verification_seeds: Vec<_> = verification_seeds
.into_iter()
.map(|s| HillClimbSeedInfo {
seed: s,
current_score: playout_result(&seed_search.starting_state, s.view(), ¤t).score,
})
.collect();
let mut improvements = 0;
... | {
extra_seeds = (verification_seeds.len()..num_verification_seeds)
.map(|_| SingleSeed::new(rng))
.collect::<Vec<_>>();
verification_seeds.extend(extra_seeds.iter());
} | conditional_block |
condition_strategy_generators.rs | use crate::ai_utils::playout_result;
use crate::competing_optimizers::StrategyOptimizer;
use crate::condition_strategy::{
Condition, ConditionKind, ConditionStrategy, EvaluatedPriorities, EvaluationData, Rule,
};
use crate::representative_sampling::NewFractalRepresentativeSeedSearch;
use crate::seed_system::{Seed, Si... | tweak_rules(&mut result.rules, state, rng, &promising_conditions);
result
}
} | .collect();
let mut result = self.clone(); | random_line_split |
condition_strategy_generators.rs | use crate::ai_utils::playout_result;
use crate::competing_optimizers::StrategyOptimizer;
use crate::condition_strategy::{
Condition, ConditionKind, ConditionStrategy, EvaluatedPriorities, EvaluationData, Rule,
};
use crate::representative_sampling::NewFractalRepresentativeSeedSearch;
use crate::seed_system::{Seed, Si... | }
}
}
StrategyGeneratorsWithSharedRepresenativeSeeds {
seed_search: NewFractalRepresentativeSeedSearch::new(
starting_state,
SingleSeedGenerator::new(ChaCha8Rng::from_rng(rng).unwrap()),
Default::default(),
),
generators,
}
}
pub fn step(&mut sel... | {
let mut generators = Vec::new();
for steps in (0..=8).map(|i| 1 << i) {
for num_verification_seeds in (0..=5).map(|i| 1 << i) {
for &start in &[HillClimbStart::NewRandom, HillClimbStart::FromSeedSearch] {
for &kind in &[
HillClimbKind::BunchOfRandomChanges,
Hill... | identifier_body |
condition_strategy_generators.rs | use crate::ai_utils::playout_result;
use crate::competing_optimizers::StrategyOptimizer;
use crate::condition_strategy::{
Condition, ConditionKind, ConditionStrategy, EvaluatedPriorities, EvaluationData, Rule,
};
use crate::representative_sampling::NewFractalRepresentativeSeedSearch;
use crate::seed_system::{Seed, Si... | <'a> {
pub seed: &'a SingleSeed<CombatChoiceLineagesKind>,
pub current_score: f64,
}
impl GeneratorKind {
pub fn min_playouts_before_culling(&self) -> usize {
match self {
&GeneratorKind::HillClimb { steps,.. } => steps.min(32),
}
}
pub fn gen_strategy(&self, seed_search: &SeedSearch, rng: &mut... | HillClimbSeedInfo | identifier_name |
runner.rs | use core::fmt::{Display, Formatter, Result as FmtResult};
use std::error::Error as StdError;
use std::sync::mpsc::{sync_channel, SyncSender, TryRecvError, TrySendError};
use std::thread::{sleep, spawn};
use std::time::{Duration, Instant};
use std::{cell::RefCell, sync::mpsc::Receiver};
use skulpin_renderer::{ash, Logi... | #[inline]
pub fn with_mut<F, R>(f: F) -> R
where
F: FnOnce(&mut State) -> R,
{
Self::STATE.with(|x| f(x.borrow_mut().as_mut().expect(Self::PANIC_MESSAGE)))
}
pub fn last_update_time() -> Duration {
Self::STATE.with(|x| {
x.borrow()
.as_ref()
... | F: FnOnce(&State) -> R,
{
Self::STATE.with(|x| f(x.borrow().as_ref().expect(Self::PANIC_MESSAGE)))
}
| random_line_split |
runner.rs | use core::fmt::{Display, Formatter, Result as FmtResult};
use std::error::Error as StdError;
use std::sync::mpsc::{sync_channel, SyncSender, TryRecvError, TrySendError};
use std::thread::{sleep, spawn};
use std::time::{Duration, Instant};
use std::{cell::RefCell, sync::mpsc::Receiver};
use skulpin_renderer::{ash, Logi... |
}
impl From<VkResult> for Error {
fn from(result: VkResult) -> Self {
Error::RendererError(result)
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct ID(u64);
impl ID {
pub fn next() -> Self {
Self(State::with_mut(|x| {
let id = x.id_keeper;
x.id_keeper += 1;... | {
match self {
Error::RendererError(e) => Some(e),
}
} | identifier_body |
runner.rs | use core::fmt::{Display, Formatter, Result as FmtResult};
use std::error::Error as StdError;
use std::sync::mpsc::{sync_channel, SyncSender, TryRecvError, TrySendError};
use std::thread::{sleep, spawn};
use std::time::{Duration, Instant};
use std::{cell::RefCell, sync::mpsc::Receiver};
use skulpin_renderer::{ash, Logi... | () -> Duration {
Self::STATE.with(|x| {
x.borrow()
.as_ref()
.expect(Self::PANIC_MESSAGE)
.time_state
.elapsed()
})
}
pub fn last_update_time_draw() -> Duration {
Self::STATE.with(|x| {
x.borrow()
... | elapsed | identifier_name |
humantoken.rs | $name
,)*
];
};
}
define_prefixes! {
quetta Q 30 1000000000000000000000000000000,
ronna R 27 1000000000000000000000000000,
yotta Y 24 1000000000000000000000000,
zetta Z ... |
attos: BigInt,
}
impl From<&TokenAmount> for Pretty {
fn from(value: &TokenAmount) -> Self {
Self {
attos: value.atto().clone(),
}
}
}
pub trait TokenAmountPretty {
fn pretty(&self) -> Pretty;
}
impl TokenAmountPretty fo... | etty { | identifier_name |
humantoken.rs | ).map_err(nom2anyhow)?;
let (input, scale) = opt(permit_trailing_ws(si_scale))(input).map_err(nom2anyhow)?;
if!input.is_empty() {
bail!("Unexpected trailing input: {input}")
}
Ok((big_decimal, scale))
}
fn permit_trailing_ws<'a, F, O, E: ParseError<&'a str>>(
... | quickcheck! {
fn parser_no_panic(s: String) -> () {
let _ = parse(&s);
}
} | random_line_split | |
humantoken.rs | $name
,)*
];
};
}
define_prefixes! {
quetta Q 30 1000000000000000000000000000000,
ronna R 27 1000000000000000000000000000,
yotta Y 24 1000000000000000000000000,
zetta Z ... | input,
nom::error::ErrorKind::Alt,
)))
}
/// Take a float from the front of `input`
fn bigdecimal<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, BigDecimal, E>
where
E: FromExternalError<&'a str, ParseBigDecimalError>,
{
map_res(recogniz... | // Try the longest matches first, so we don't e.g match `a` instead of `atto`,
// leaving `tto`.
let mut scales = si::SUPPORTED_PREFIXES
.iter()
.flat_map(|scale| {
std::iter::once(&scale.name)
.chain(scale.units)
.... | identifier_body |
lib.rs | // LNP/BP lLibraries implementing LNPBP specifications & standards
// Written in 2021-2022 by
// Dr. Maxim Orlovsky <orlovsky@pandoraprime.ch>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. ... | /// Type for wrapping Vec<u8> data in cases you need to do a convenient
/// enum variant display derives with `#[display(inner)]`
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
#[derive(
Wrapper, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, De... | }
| random_line_split |
lib.rs | // LNP/BP lLibraries implementing LNPBP specifications & standards
// Written in 2021-2022 by
// Dr. Maxim Orlovsky <orlovsky@pandoraprime.ch>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. ... | <Value>(std::marker::PhantomData<Value>);
#[cfg(feature = "serde")]
impl<'de, ValueT> Visitor<'de> for Bech32Visitor<ValueT>
where
ValueT: FromBech32Str,
{
type Value = ValueT;
fn expecting(
&self,
formatter: &mut std::fmt::Formatter,
) -> std::fmt::Result {
formatter.write_str... | Bech32Visitor | identifier_name |
lib.rs | //! JSON-RPC client implementation.
#![deny(missing_docs)]
use failure::{format_err, Fail};
use futures::sync::{mpsc, oneshot};
use futures::{future, prelude::*};
use jsonrpc_core::{Error, Params};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use std::marker::PhantomData;
pub mod tra... |
#[derive(Clone)]
struct AddClient(TypedClient);
impl From<RpcChannel> for AddClient {
fn from(channel: RpcChannel) -> Self {
AddClient(channel.into())
}
}
impl AddClient {
fn add(&self, a: u64, b: u64) -> impl Future<Item = u64, Error = RpcError> {
self.0.call_method("add", "u64", (a, b))
}
fn ... | use crate::{RpcChannel, RpcError, TypedClient};
use jsonrpc_core::{self as core, IoHandler};
use jsonrpc_pubsub::{PubSubHandler, Subscriber, SubscriptionId};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; | random_line_split |
lib.rs | //! JSON-RPC client implementation.
#![deny(missing_docs)]
use failure::{format_err, Fail};
use futures::sync::{mpsc, oneshot};
use futures::{future, prelude::*};
use jsonrpc_core::{Error, Params};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use std::marker::PhantomData;
pub mod tra... |
}
#[cfg(test)]
mod tests {
use super::*;
use crate::transports::local;
use crate::{RpcChannel, RpcError, TypedClient};
use jsonrpc_core::{self as core, IoHandler};
use jsonrpc_pubsub::{PubSubHandler, Subscriber, SubscriptionId};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[derive(Clon... | {
let args = serde_json::to_value(subscribe_params)
.expect("Only types with infallible serialisation can be used for JSON-RPC");
let params = match args {
Value::Array(vec) => Params::Array(vec),
Value::Null => Params::None,
_ => {
return future::Either::A(future::err(RpcError::Other(format_err!(
... | identifier_body |
lib.rs | //! JSON-RPC client implementation.
#![deny(missing_docs)]
use failure::{format_err, Fail};
use futures::sync::{mpsc, oneshot};
use futures::{future, prelude::*};
use jsonrpc_core::{Error, Params};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use std::marker::PhantomData;
pub mod tra... | <T: Serialize, R: DeserializeOwned +'static>(
&self,
subscribe: &str,
subscribe_params: T,
topic: &str,
unsubscribe: &str,
returns: &'static str,
) -> impl Future<Item = TypedSubscriptionStream<R>, Error = RpcError> {
let args = serde_json::to_value(subscribe_params)
.expect("Only types with infallibl... | subscribe | identifier_name |
mod.rs | },
}
}
}
impl GLContextTrait for GLContext {
fn get_attributes(&self) -> GLContextAttributes {
todo!()
}
// This does not correctly handle unsetting a window.
fn set_window(
&mut self,
window: Option<&impl raw_window_handle::HasRawWindowHandle>,
) -> Resul... |
fn swap_buffers(&mut self) {
if let Some(device_context) = self.device_context {
unsafe {
SwapBuffers(device_context);
}
}
}
fn resize(&mut self) {}
// wglSwapIntervalEXT sets VSync for the window bound to the current context.
// However he... | {
unsafe {
let window_device_context = self.device_context.unwrap_or(std::ptr::null_mut());
error_if_false(wglMakeCurrent(window_device_context, self.context_ptr))
}
} | identifier_body |
mod.rs | },
}
}
}
impl GLContextTrait for GLContext {
fn get_attributes(&self) -> GLContextAttributes {
todo!()
}
// This does not correctly handle unsetting a window.
fn set_window(
&mut self,
window: Option<&impl raw_window_handle::HasRawWindowHandle>,
) -> Resul... |
}
}
}
}
impl GLContextBuilder {
pub fn build(&self) -> Result<GLContext, ()> {
Ok(new_opengl_context(
self.gl_attributes.color_bits,
self.gl_attributes.alpha_bits,
self.gl_attributes.depth_bits,
self.gl_attributes.stencil_bits,
... | {
panic!("Failed to release device context");
} | conditional_block |
mod.rs | },
}
}
}
impl GLContextTrait for GLContext {
fn get_attributes(&self) -> GLContextAttributes {
todo!()
}
// This does not correctly handle unsetting a window.
fn set_window(
&mut self,
window: Option<&impl raw_window_handle::HasRawWindowHandle>,
) -> Resul... | (&self, address: &str) -> *const core::ffi::c_void {
get_proc_address_inner(self.opengl_module, address)
}
}
fn get_proc_address_inner(opengl_module: HMODULE, address: &str) -> *const core::ffi::c_void {
unsafe {
let name = std::ffi::CString::new(address).unwrap();
let mut result = wglG... | get_proc_address | identifier_name |
mod.rs | },
}
}
}
impl GLContextTrait for GLContext {
fn get_attributes(&self) -> GLContextAttributes {
todo!()
}
// This does not correctly handle unsetting a window.
fn set_window(
&mut self,
window: Option<&impl raw_window_handle::HasRawWindowHandle>,
) -> Resu... | _ => unreachable!(),
})
.unwrap();
let window_device_context = if let Some(_window) = window {
if let Some(current_device_context) = self.device_context {
ReleaseDC(window_handle, current_device_context);
... | RawWindowHandle::Windows(handle) => handle.hwnd as HWND, | random_line_split |
facade.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::common_utils::common::get_proxy_or_connect;
use crate::repository_manager::types::RepositoryOutput;
use anyhow::{format_err, Error};
use fidl_f... |
Err(err) => {
return Err(format_err!("Listing Repositories failed with error {:?}", err))
}
};
}
/// Add a new source to an existing repository.
///
/// params format uses RepositoryConfig, example:
/// {
/// "repo_url": "fuchsia-pkg://exampl... | {
let return_value = to_value(&repos)?;
return Ok(return_value);
} | conditional_block |
facade.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::common_utils::common::get_proxy_or_connect;
use crate::repository_manager::types::RepositoryOutput;
use anyhow::{format_err, Error};
use fidl_f... | }
fn proxy(&self) -> Result<RepositoryManagerProxy, Error> {
get_proxy_or_connect::<RepositoryManagerMarker>(&self.proxy)
}
/// Lists repositories using the repository_manager fidl service.
///
/// Returns a list containing repository info in the format of
/// RepositoryConfig.
... |
#[cfg(test)]
fn new_with_proxy(proxy: RepositoryManagerProxy) -> Self {
Self { proxy: RwLock::new(Some(proxy)) } | random_line_split |
facade.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::common_utils::common::get_proxy_or_connect;
use crate::repository_manager::types::RepositoryOutput;
use anyhow::{format_err, Error};
use fidl_f... | () {
let repo_config = make_test_repo_config();
assert_value_round_trips_as(
repo_config,
json!(
{
"repo_url": "fuchsia-pkg://example.com",
"root_keys":[
{
"type":"ed25519",
... | serde_repo_configuration | identifier_name |
facade.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::common_utils::common::get_proxy_or_connect;
use crate::repository_manager::types::RepositoryOutput;
use anyhow::{format_err, Error};
use fidl_f... |
/// Fetches repositories using repository_manager.list FIDL service.
async fn fetch_repos(&self) -> Result<Vec<RepositoryConfig>, anyhow::Error> {
let (iter, server_end) = fidl::endpoints::create_proxy()?;
self.proxy()?.list(server_end)?;
let mut repos = vec![];
loop {
... | {
let add_request: RepositoryConfig = from_value(args)?;
fx_log_info!("Add Repo request received {:?}", add_request);
let res = self.proxy()?.add(add_request.into()).await?;
match res.map_err(zx::Status::from_raw) {
Ok(()) => Ok(to_value(RepositoryOutput::Success)?),
... | identifier_body |
transaction.rs | //! The `transaction` module provides functionality for creating log transactions.
use bincode::serialize;
use hash::{Hash, Hasher};
use serde::Serialize;
use sha2::Sha512;
use signature::{Keypair, KeypairUtil, Signature};
use solana_sdk::pubkey::Pubkey;
use std::mem::size_of;
pub const SIGNED_DATA_OFFSET: usize = si... | <T: Serialize>(
from_keypair: &Keypair,
transaction_keys: &[Pubkey],
program_id: Pubkey,
userdata: &T,
last_id: Hash,
fee: u64,
) -> Self {
let program_ids = vec![program_id];
let accounts = (0..=transaction_keys.len() as u8).collect();
let ins... | new | identifier_name |
transaction.rs | //! The `transaction` module provides functionality for creating log transactions.
use bincode::serialize;
use hash::{Hash, Hasher};
use serde::Serialize;
use sha2::Sha512;
use signature::{Keypair, KeypairUtil, Signature};
use solana_sdk::pubkey::Pubkey;
use std::mem::size_of;
pub const SIGNED_DATA_OFFSET: usize = si... | data.extend_from_slice(&fee_data);
let program_ids = serialize(&self.program_ids).expect("serialize program_ids");
data.extend_from_slice(&program_ids);
let instructions = serialize(&self.instructions).expect("serialize instructions");
data.extend_from_slice(&instructions);
... | data.extend_from_slice(&last_id_data);
let fee_data = serialize(&self.fee).expect("serialize fee"); | random_line_split |
transaction.rs | //! The `transaction` module provides functionality for creating log transactions.
use bincode::serialize;
use hash::{Hash, Hasher};
use serde::Serialize;
use sha2::Sha512;
use signature::{Keypair, KeypairUtil, Signature};
use solana_sdk::pubkey::Pubkey;
use std::mem::size_of;
pub const SIGNED_DATA_OFFSET: usize = si... |
}
/// An atomic transaction
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct Transaction {
/// A digital signature of `account_keys`, `program_ids`, `last_id`, `fee` and `instructions`, signed by `Pubkey`.
pub signature: Signature,
/// The `Pubkeys` that are executing this transa... | {
let userdata = serialize(userdata).unwrap();
Instruction {
program_ids_index,
userdata,
accounts,
}
} | identifier_body |
main.rs | extern crate getopts;
extern crate hyper;
extern crate futures;
extern crate tokio_core;
extern crate hyper_tls;
extern crate pretty_env_logger;
extern crate ftp;
use std::io::Read;
use getopts::Options;
use std::str;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::io::stdin;
use std::env;
use ... | match file.write_all(&x) {
Err(why) => {
panic!("couldn't write to {}: {}", display,
why.description())
},
Ok(_) => (),
}
}
println!("successfully wrote to {}", display);
}
fn extract_file_name_if_empty_string(fullpath:... |
for x in &finally { | random_line_split |
main.rs | extern crate getopts;
extern crate hyper;
extern crate futures;
extern crate tokio_core;
extern crate hyper_tls;
extern crate pretty_env_logger;
extern crate ftp;
use std::io::Read;
use getopts::Options;
use std::str;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::io::stdin;
use std::env;
use ... | // https://doc.rust-lang.org/std/macro.panic.html
let matches = match opts.parse(&commandline_args[1..]){
Ok(m) => { m }
Err(f) => {panic!(f.to_string())}
};
// Handle help flags
if matches.opt_present("h"){
let brief = format!("Usage: {} FILE [options]", program);
print!("... | {
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
pretty_env_logger::init().unwrap();
// Using args() instead of args_os(), cause they never panic
let commandline_args: Vec<_> = env::args().collect();
let program = commandline_args[0].clone();
// Use the getopts package Options str... | identifier_body |
main.rs | extern crate getopts;
extern crate hyper;
extern crate futures;
extern crate tokio_core;
extern crate hyper_tls;
extern crate pretty_env_logger;
extern crate ftp;
use std::io::Read;
use getopts::Options;
use std::str;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::io::stdin;
use std::env;
use ... | (url: hyper::Uri, destination: &str){
let mut core = tokio_core::reactor::Core::new().unwrap();
let client = Client::configure().connector(::hyper_tls::HttpsConnector::new(4, &core.handle()).unwrap()).build(&core.handle());
let work = client.get(url);
let reponse = core.run(work).unwrap();
let buf2 =... | https_download_single_file | identifier_name |
update_webhook_message.rs | //! Update a message created by a webhook via execution.
use crate::{
client::Client,
error::Error as HttpError,
request::{
self,
validate_inner::{self, ComponentValidationError, ComponentValidationErrorType},
AuditLogReason, AuditLogReasonError, Form, NullableField, Request,
},... | (
self,
) -> (
UpdateWebhookMessageErrorType,
Option<Box<dyn Error + Send + Sync>>,
) {
(self.kind, self.source)
}
}
impl Display for UpdateWebhookMessageError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match &self.kind {
UpdateWebhookMessa... | into_parts | identifier_name |
update_webhook_message.rs | //! Update a message created by a webhook via execution.
use crate::{
client::Client,
error::Error as HttpError,
request::{
self,
validate_inner::{self, ComponentValidationError, ComponentValidationErrorType},
AuditLogReason, AuditLogReasonError, Form, NullableField, Request,
},... |
// `self` needs to be consumed and the client returned due to parameters
// being consumed in request construction.
fn request(&mut self) -> Result<Request, HttpError> {
let mut request = Request::builder(&Route::UpdateWebhookMessage {
message_id: self.message_id.0,
token: ... | {
self.fields.payload_json = Some(payload_json);
self
} | identifier_body |
update_webhook_message.rs | //! Update a message created by a webhook via execution.
use crate::{
client::Client,
error::Error as HttpError,
request::{
self,
validate_inner::{self, ComponentValidationError, ComponentValidationErrorType},
AuditLogReason, AuditLogReasonError, Form, NullableField, Request,
},... | /// of the original message is unaffected and only the embed(s) are
/// modified.
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_embed_builder::EmbedBuilder;
/// use twilight_model::id::{MessageId, WebhookId};
///
/// # #[tokio::main] async fn main() -> Result<()... | /// Create an embed and update the message with the new embed. The content | random_line_split |
update_webhook_message.rs | //! Update a message created by a webhook via execution.
use crate::{
client::Client,
error::Error as HttpError,
request::{
self,
validate_inner::{self, ComponentValidationError, ComponentValidationErrorType},
AuditLogReason, AuditLogReasonError, Form, NullableField, Request,
},... |
self.fields.components = Some(NullableField(components));
Ok(self)
}
/// Set the content of the message.
///
/// Pass `None` if you want to remove the message content.
///
/// Note that if there is are no embeds then you will not be able to remove
/// the content of the m... | {
validate_inner::components(components).map_err(|source| {
let (kind, inner_source) = source.into_parts();
match kind {
ComponentValidationErrorType::ComponentCount { count } => {
UpdateWebhookMessageError {
... | conditional_block |
mode.rs | use std::{io,process,str,thread,time};
use std::io::Error;
use std::result::Result;
use regex::Regex;
use serde::{Serialize,Deserialize};
use crate::{fileio,util};
#[derive(Debug)]
pub struct InputMode {
width:String,
height:String,
rate:String,
name:String,
display:String,
}
impl InputMode {
... | .arg(&mode.name)
.arg(&mode.clock)
.arg(&mode.h_disp)
.arg(&mode.h_sync_start)
.arg(&mode.h_sync_end)
.arg(&mode.h_total)
.arg(&mode.v_disp)
.arg(&mode.v_sync_start)
.arg(&mode.v_sync_end)
.arg(&mode.v_total)
.arg(&mode.flags);
if verbose ... | cmd.arg("--newmode") | random_line_split |
mode.rs | use std::{io,process,str,thread,time};
use std::io::Error;
use std::result::Result;
use regex::Regex;
use serde::{Serialize,Deserialize};
use crate::{fileio,util};
#[derive(Debug)]
pub struct InputMode {
width:String,
height:String,
rate:String,
name:String,
display:String,
}
impl InputMode {
... | }
cmd = process::Command::new("xrandr");
cmd.arg("--addmode").arg(display).arg(&mode.name);
cmd.output()?;
Ok(())
}
| {
let mut cmd = process::Command::new("xrandr");
cmd.arg("--newmode")
.arg(&mode.name)
.arg(&mode.clock)
.arg(&mode.h_disp)
.arg(&mode.h_sync_start)
.arg(&mode.h_sync_end)
.arg(&mode.h_total)
.arg(&mode.v_disp)
.arg(&mode.v_sync_start)
.arg... | identifier_body |
mode.rs | use std::{io,process,str,thread,time};
use std::io::Error;
use std::result::Result;
use regex::Regex;
use serde::{Serialize,Deserialize};
use crate::{fileio,util};
#[derive(Debug)]
pub struct InputMode {
width:String,
height:String,
rate:String,
name:String,
display:String,
}
impl InputMode {
... | (w: Option<&str>, h: Option<&str>, r: Option<&str>, d: Option<&str>, n: Option<&str>, t: Option<&str>, f: Option<&str>, test: bool, save: bool, verbose: bool) -> Result<(),Error> {
let current_modes = get_current_modes(verbose)?;
// Use first current display mode for parameters not supplied
// and as the fa... | add_mode | identifier_name |
ic4164.rs | the column address is put onto the address pins and the active-low
/// column address strobe pin CAS is set low.
///
/// The chip has three basic modes of operation, controlled by the active-low write-enable
/// (WE) pin with some help from CAS. If WE is high, then the chip is in read mode after the
/// address is set... | else {
self.col = Some(pins_to_value(&self.addr_pins) as u8);
if high!(self.pins[WE]) {
self.read();
} else {
self.data = Some(if high!(self.pins[D]) { 1 } else { 0 });
self.write();
... | {
float!(self.pins[Q]);
self.col = None;
self.data = None;
} | conditional_block |
ic4164.rs | then the column address is put onto the address pins and the active-low
/// column address strobe pin CAS is set low.
///
/// The chip has three basic modes of operation, controlled by the active-low write-enable
/// (WE) pin with some help from CAS. If WE is high, then the chip is in read mode after the
/// address i... | // 1 is written to address 0x0000 at this point
set!(tr[CAS]);
set!(tr[RAS]);
set!(tr[WE]);
clear!(tr[RAS]);
clear!(tr[CAS]);
let value = high!(tr[Q]);
set!(tr[CAS]);
set!(tr[RAS]);
| clear!(tr[WE]); | random_line_split |
ic4164.rs | the column address is put onto the address pins and the active-low
/// column address strobe pin CAS is set low.
///
/// The chip has three basic modes of operation, controlled by the active-low write-enable
/// (WE) pin with some help from CAS. If WE is high, then the chip is in read mode after the
/// address is set... | () {
let (_, tr, _) = before_each();
// Write is happening at 0x0000, so we don't need to set addresses at all
set!(tr[D]);
clear!(tr[WE]);
clear!(tr[RAS]);
clear!(tr[CAS]);
// 1 is written to address 0x0000 at this point
set!(tr[CAS]);
set!(tr[RA... | read_write_one_bit | identifier_name |
ic4164.rs | the column address is put onto the address pins and the active-low
/// column address strobe pin CAS is set low.
///
/// The chip has three basic modes of operation, controlled by the active-low write-enable
/// (WE) pin with some help from CAS. If WE is high, then the chip is in read mode after the
/// address is set... | clear!(tr[CAS]);
let value = high!(tr[Q]);
set!(tr[CAS]);
set!(tr[RAS]);
| {
let (_, tr, _) = before_each();
// Write is happening at 0x0000, so we don't need to set addresses at all
set!(tr[D]);
clear!(tr[RAS]);
clear!(tr[CAS]);
// in read mode, Q should be 0 because no data has been written to 0x0000 yet
assert!(
low!(tr[Q... | identifier_body |
corebuilder.rs | use crate::{
error::CoreError,
logger::Logger,
warrior::{Instruction, Warrior},
};
use rand::Rng;
use super::{Core, CoreInstruction};
use std::collections::VecDeque;
#[derive(Debug)]
pub struct CoreBuilder {
pub(super) core_size: usize,
pub(super) cycles_before_tie: usize,
pub(super) initial_in... | self.separation = separation;
self
}
/// This is the range available for warriors to write information
/// to core. Attempts to write outside the limits of this range
/// result in writing within the local writable range. The range
/// is centered on the current instruction. Thus... | /// warrior to the first instruction of the next warrior.
/// Separation can be set to `Random`, meaning separations will be
/// chosen randomly from those larger than the minimum separation.
pub fn separation(&mut self, separation: Separation) -> &mut Self { | random_line_split |
corebuilder.rs | use crate::{
error::CoreError,
logger::Logger,
warrior::{Instruction, Warrior},
};
use rand::Rng;
use super::{Core, CoreInstruction};
use std::collections::VecDeque;
#[derive(Debug)]
pub struct CoreBuilder {
pub(super) core_size: usize,
pub(super) cycles_before_tie: usize,
pub(super) initial_in... | (&mut self, warriors: &[Warrior]) -> Result<&mut Self, CoreError> {
for warrior in warriors {
if warrior.len() > self.instruction_limit {
return Err(CoreError::WarriorTooLong(
warrior.len(),
self.instruction_limit,
warrior.m... | load_warriors | identifier_name |
corebuilder.rs | use crate::{
error::CoreError,
logger::Logger,
warrior::{Instruction, Warrior},
};
use rand::Rng;
use super::{Core, CoreInstruction};
use std::collections::VecDeque;
#[derive(Debug)]
pub struct CoreBuilder {
pub(super) core_size: usize,
pub(super) cycles_before_tie: usize,
pub(super) initial_in... |
/// Each warrior can spawn multiple additional tasks. This variable sets the maximum
/// number of tasks allowed per warrior. In other words, this is the size of each warrior's task queue.
pub fn maximum_number_of_tasks(&mut self, maximum_number_of_tasks: usize) -> &mut Self {
self.maximum_number_... | {
self.instruction_limit = instruction_limit;
self
} | identifier_body |
corebuilder.rs | use crate::{
error::CoreError,
logger::Logger,
warrior::{Instruction, Warrior},
};
use rand::Rng;
use super::{Core, CoreInstruction};
use std::collections::VecDeque;
#[derive(Debug)]
pub struct CoreBuilder {
pub(super) core_size: usize,
pub(super) cycles_before_tie: usize,
pub(super) initial_in... |
if warrior.is_empty() {
return Err(CoreError::EmptyWarrior(
warrior.metadata.name().unwrap_or("Unnamed").to_owned(),
));
};
}
self.warriors = warriors.to_vec();
Ok(self)
}
/// Use a `Logger` to log the battle... | {
return Err(CoreError::WarriorTooLong(
warrior.len(),
self.instruction_limit,
warrior.metadata.name().unwrap_or("Unnamed").to_owned(),
));
} | conditional_block |
nbd.rs | //! Utility functions for working with nbd devices
use rpc::mayastor::*;
use crate::{
csi::{NodeStageVolumeRequest, NodeStageVolumeResponse},
device,
format::probed_format,
mount::{match_mount, mount_fs, Fs},
};
use enclose::enclose;
use futures::{
future::{err, ok, Either},
Future,
};
use glob... | () -> usize {
glob("/sys/class/block/nbd*").unwrap().count()
}
}
impl From<String> for NbdDevInfo {
fn from(e: String) -> Self {
let instance: u32 = e.replace("/dev/nbd", "").parse().unwrap();
NbdDevInfo::create(instance).unwrap()
}
}
| num_devices | identifier_name |
nbd.rs | //! Utility functions for working with nbd devices
use rpc::mayastor::*;
use crate::{
csi::{NodeStageVolumeRequest, NodeStageVolumeResponse},
device,
format::probed_format,
mount::{match_mount, mount_fs, Fs},
};
use enclose::enclose;
use futures::{
future::{err, ok, Either},
Future,
};
use glob... | else {
let msg = format!(
"Failed to stop nbd device {} for {}",
nbd_disk.nbd_device, nbd_disk.bdev_name
);
error!("{}", msg);
Box::new(err(Status::new(Code::Internal, msg)))
... | {
info!(
"Stopped NBD device {} with bdev {}",
nbd_disk.nbd_device, nbd_disk.bdev_name
);
NbdDevInfo::from(nbd_disk.nbd_device).put_back();
Box::new(ok(Response::new(Null {})))
... | conditional_block |
nbd.rs | //! Utility functions for working with nbd devices
use rpc::mayastor::*;
use crate::{
csi::{NodeStageVolumeRequest, NodeStageVolumeResponse},
device,
format::probed_format,
mount::{match_mount, mount_fs, Fs},
};
use enclose::enclose;
use futures::{
future::{err, ok, Either},
Future,
};
use glob... |
}
impl fmt::Debug for NbdDevInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "nbd{} ({}:{})", self.instance, self.major, self.minor)
}
}
pub fn nbd_stage_volume(
socket: String,
msg: &NodeStageVolumeRequest,
filesystem: Fs,
mnt_opts: Vec<String>,
) -> Box<
d... | {
write!(f, "/dev/nbd{}", self.instance)
} | identifier_body |
nbd.rs | //! Utility functions for working with nbd devices
use rpc::mayastor::*;
use crate::{
csi::{NodeStageVolumeRequest, NodeStageVolumeResponse},
device,
format::probed_format,
mount::{match_mount, mount_fs, Fs},
};
use enclose::enclose;
use futures::{
future::{err, ok, Either},
Future,
};
use glob... | }
impl From<String> for NbdDevInfo {
fn from(e: String) -> Self {
let instance: u32 = e.replace("/dev/nbd", "").parse().unwrap();
NbdDevInfo::create(instance).unwrap()
}
} | random_line_split | |
main.rs | use crate::argon2id13::Salt;
use actix_web::{get, post, web, HttpRequest, HttpResponse};
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use futures::StreamExt;
use google_authenticator::{ErrorCorrectionLevel, GoogleAuthenticator};
use hmac::{Hmac, Mac, NewMac};
use lazy_static::lazy_static;
u... |
// récupère le code dans le header
let input_code: &str = req.headers().get("Code").unwrap().to_str().unwrap();
if!auth.verify_code(&user.secret, &input_code, 0, 0) {
println!("Mauvais code.");
return HttpResponse::Unauthorized().finish();
}
// si ok, un token est envoyé à l'utilis... | }
}; | random_line_split |
main.rs | use crate::argon2id13::Salt;
use actix_web::{get, post, web, HttpRequest, HttpResponse};
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use futures::StreamExt;
use google_authenticator::{ErrorCorrectionLevel, GoogleAuthenticator};
use hmac::{Hmac, Mac, NewMac};
use lazy_static::lazy_static;
u... | oad, req: HttpRequest) -> HttpResponse {
// lire et vérifier le Token
if!check_token(&req) {
return HttpResponse::NonAuthoritativeInformation().finish();
}
// lire le body
let mut bytes = web::BytesMut::new();
while let Some(item) = body.next().await {
let item = item.unwrap();
... | ::Payl | identifier_name |
main.rs | use crate::argon2id13::Salt;
use actix_web::{get, post, web, HttpRequest, HttpResponse};
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use futures::StreamExt;
use google_authenticator::{ErrorCorrectionLevel, GoogleAuthenticator};
use hmac::{Hmac, Mac, NewMac};
use lazy_static::lazy_static;
u... |
}
| }
}
}
return false; | conditional_block |
main.rs | use crate::argon2id13::Salt;
use actix_web::{get, post, web, HttpRequest, HttpResponse};
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use futures::StreamExt;
use google_authenticator::{ErrorCorrectionLevel, GoogleAuthenticator};
use hmac::{Hmac, Mac, NewMac};
use lazy_static::lazy_static;
u... | let mut contents = String::new();
current_file
.read_to_string(&mut contents)
.expect("Unable to read the file");
let meta: Metadata = serde_json::from_str(&contents).unwrap();
if meta.username.contains(&user_name.to_string()) {
... | r le Token
if !check_token(&req) {
return HttpResponse::NonAuthoritativeInformation().finish();
}
let user_name: &str = req.headers().get("Username").unwrap().to_str().unwrap();
// préparation des clés pour AES-GCM et du nonce
let key_aes = Key::from_slice(b"an example very very secret key.... | identifier_body |
lib.register_lints.rs | will be overwritten.
store.register_lints(&[
#[cfg(feature = "internal")]
utils::internal_lints::CLIPPY_LINTS_INTERNAL,
#[cfg(feature = "internal")]
utils::internal_lints::COLLAPSIBLE_SPAN_LINT_CALLS,
#[cfg(feature = "internal")]
utils::internal_lints::COMPILER_LINT_FUNCTIONS,
#[cfg(featur... | comparison_chain::COMPARISON_CHAIN,
copies::BRANCHES_SHARING_CODE,
copies::IFS_SAME_COND,
copies::IF_SAME_THEN_ELSE,
copies::SAME_FUNCTIONS_IN_IF_CONDITION,
copy_iterator::COPY_ITERATOR,
create_dir::CREATE_DIR,
dbg_macro::DBG_MACRO,
default::DEFAULT_TRAIT_ACCESS,
default::FIELD_R... | collapsible_if::COLLAPSIBLE_ELSE_IF,
collapsible_if::COLLAPSIBLE_IF,
collapsible_match::COLLAPSIBLE_MATCH, | random_line_split |
main.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::rc::Rc;
use std::cell::Cell;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::u32;
extern crate chariot_drs as lib;
use lib::DrsFile as Archive;
extern crate number_prefix;
use number_prefix::{binary_pre... | (
title: &str,
window_type: gtk::WindowType,
action: gtk::FileChooserAction,
) -> Option<PathBuf> {
let dialog = FileChooserDialog::new(Some(title), Some(&Window::new(window_type)), action);
dialog.add_button("_Cancel", gtk::ResponseType::Cancel.into());
match action {
gtk::FileChooserA... | select_dir_dialog | identifier_name |
main.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::rc::Rc;
use std::cell::Cell;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::u32;
extern crate chariot_drs as lib;
use lib::DrsFile as Archive;
extern crate number_prefix;
use number_prefix::{binary_pre... | let count_str = if selected_count == 0 || selected_count == store_len {
"all".into()
} else {
format!("({})", selected_count)
};
extract_button.set_label(&format!("Extract {}", count_str))
});
}
fn select_dir_dialog(
title: &str,
window_type: gtk::Wi... | random_line_split | |
main.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::rc::Rc;
use std::cell::Cell;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::u32;
extern crate chariot_drs as lib;
use lib::DrsFile as Archive;
extern crate number_prefix;
use number_prefix::{binary_pre... |
fn convert_size(s: String) -> u32 {
let v = s.split(' ').collect::<Vec<&str>>();
let exp = match v.get(1) {
Some(&"B") => 0,
Some(&"KiB") => 1,
Some(&"MiB") => 2,
Some(&"GiB") => 3,
_ => panic!("Unable to convert size: `{}`", s),
... | {
s
} | identifier_body |
block.rs | //! Implementations of cryptographic attacks against block ciphers.
use utils::data::Data;
use utils::metrics;
use victims::block::{EcbOrCbc, EcbWithSuffix, EcbWithAffixes, EcbUserProfile, CbcCookie};
/// Determine whether a block cipher is using ECB or CBC mode.
///
/// Given a black box which encrypts (padded) user... | (cbc_cookie_box: &CbcCookie) -> Data {
// First, provide the user data "aaaaaaaaaaaaaaaa:admin<true:aa<a" and get the
// resulting token as raw bytes.
let token = cbc_cookie_box.make_token("aaaaaaaaaaaaaaaa:admin<true:aa<a");
let mut bytes = token.bytes().to_vec();
// Now, by flipping some of the ... | craft_cbc_admin_token | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.