file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
main.rs
#[macro_use] extern crate log; extern crate simplelog; use futures::future; use futures::future::{BoxFuture, FutureExt}; use reqwest as request; use base64::encode; use dirs::home_dir; use futures::io::SeekFrom; use regex::Regex; use request::header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE, USER_AGENT}; use scraper::...
// Utility Functions /// fn get_checked_listings() -> Vec<String> { let mut checked_mls: Vec<String> = vec![]; if let Ok(lines) = read_lines(&get_sure_filepath("listings.txt")) { for line in lines { if let Ok(l) = line { checked_mls.push(String::from(l.trim())) } } } checked_mls } fn write_checked_...
ror!( "error sending message: {:?}\n\t└──{}\n\t└──{:?}", res.status(), res.text().await?, params ) } Ok(()) } /// /
conditional_block
main.rs
// Copyright 2020 Xavier Gillard // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, di...
} /// In addition to a dynamic programming (DP) model of the problem you want to solve, /// the branch and bound with MDD algorithm (and thus ddo) requires that you provide /// an additional relaxation allowing to control the maximum amount of space used by /// the decision diagrams that are compiled. /// /// That...
{ state.contains(var.id()) }
identifier_body
main.rs
// Copyright 2020 Xavier Gillard // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, di...
if comment.is_match(line) { continue; } if let Some(caps) = pb_decl.captures(line) { let n = caps["vars"].to_string().parse::<usize>()?; let full = (0..n).collect(); g.nb_vars = n; g.neighbors = vec![full; n]; g.wei...
{ continue; }
conditional_block
main.rs
// Copyright 2020 Xavier Gillard // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, di...
fn initial_state(&self) -> Self::State { (0..self.nb_variables()).collect() } fn initial_value(&self) -> isize { 0 } fn transition(&self, state: &Self::State, decision: Decision) -> Self::State { let mut res = state.clone(); res.remove(decision.variable.id()); ...
fn nb_variables(&self) -> usize { self.nb_vars }
random_line_split
main.rs
// Copyright 2020 Xavier Gillard // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, di...
(&self, variable: Variable, state: &Self::State, f: &mut dyn DecisionCallback) { if state.contains(variable.id()) { f.apply(Decision{variable, value: YES}); f.apply(Decision{variable, value: NO }); } else { f.apply(Decision{variable, value: NO }); } } ...
for_each_in_domain
identifier_name
main.rs
mod4 ); // 負の時の対策 let disc = if mod4 == 1 { d } else { 4 * d }; writeln_report!(r"$D = {}$となる.", disc); disc } fn is_int(x: f64) -> bool { (x - x.round()).abs() < 1e-8 } #[allow(clippy::cognitive_complexity, clippy::nonminimal_bool)] fn calc_negative(disc: i64) -> Result<Vec<(i64, i64, i64...
} } writeln_report!(); writeln_report!(r"その上で$a \leqq c, c > 0$となるような$a, c$を求める."); writeln_report!(r"\begin{{itemize}}"); // 条件を満たす a, c を求める. let mut res = Vec::new(); for b in bs { let do_report = b >= 0; if do_report { writeln_report!( ...
if has_zero { "0$, " } else { "$" }, nonzero.format(r"$, $\pm ") );
random_line_split
main.rs
mod4 ); // 負の時の対策 let disc = if mod4 == 1 { d } else { 4 * d }; writeln_report!(r"$D = {}$となる.", disc); disc } fn is_int(x: f64) -> bool { (x - x.round()).abs() < 1e-8 } #[allow(clippy::cognitive_complexity, clippy::nonminimal_bool)] fn calc_negative(disc: i64) -> Result<Vec<(i64, i64, i64)...
a, c ); return true; } let left_failure = if!(-a < b) { format!(r"$-a < b$について${} \not< {}$", -a, b) } else if!(b <= a) { format!(r"$b \leqq a$について${} \not\leqq {}$", b, a) } else if!(a < c) { format!(r"$a < c$に...
writeln_report!( r"これは右側の不等式$0 \leqq {} \leqq {} = {}$満たす.", b,
conditional_block
main.rs
ppy::nonminimal_bool)] fn calc_negative(disc: i64) -> Result<Vec<(i64, i64, i64)>, String> { writeln_report!("まず,条件を満たす$b$の候補を計算する.$b$の範囲は"); // b の範囲を求める (exclusive) let maxb = { let sqrt = (disc.abs() as f64 / 3.0).sqrt(); let is_int = is_int(sqrt); // 1.3 -> 2, 2.9 -> 3, 4.0 -> 5 ...
rue;
identifier_name
main.rs
mod4 ); // 負の時の対策 let disc = if mod4 == 1 { d } else { 4 * d }; writeln_report!(r"$D = {}$となる.", disc); disc } fn is_int(x: f64) -> bool { (x - x.round()).abs() < 1e-8 } #[allow(clippy::cognitive_complexity, clippy::nonminimal_bool)] fn calc_negative(disc: i64) -> Result<Vec<(i64, i64, i64)>...
let ac4 = b * b - disc; if ac4 % 4!= 0 { writeln_report!("$4ac = {}$となり,これは整数解を持たない.", ac4); continue; } let ac = ac4 / 4; writeln_report!("$4ac = {}$より$ac = {}$.", ac4, ac); write_report!("よって$(a, c) = $"); let mut first = true; f...
b$は{}であるから,", disc, if disc % 2 == 0 { "偶数" } else { "奇数" } ); let bs = ((minb + 1)..0).filter(|x| x.abs() % 2 == disc % 2); if bs.clone().collect_vec().is_empty() { writeln_report!(r"条件を満たす$b$はない."); return Err("no cands".to_string()); } writeln_report!(r"条件を満たす$b$は...
identifier_body
csr.rs
/* Copyright 2020 Brandon Lucia <blucia@gmail.com> 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 agreed to in writing...
} /// Take an edge list in and produce a CSR out /// (u,v) pub fn new(numv: usize, ref el: Vec<(usize, usize)>) -> CSR { const NUMCHUNKS: usize = 16; let chunksz: usize = if numv > NUMCHUNKS { numv / NUMCHUNKS } else { 1 }; /*TODO: Para...
/*return the graph, g*/ g
random_line_split
csr.rs
/* Copyright 2020 Brandon Lucia <blucia@gmail.com> 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 agreed to in writing...
{ v: usize, e: usize, vtxprop: Vec<f64>, offsets: Vec<usize>, neighbs: Vec<usize>, } impl CSR { pub fn get_vtxprop(&self) -> &[f64] { &self.vtxprop } pub fn get_mut_vtxprop(&mut self) -> &mut [f64] { &mut self.vtxprop } pub fn get_v(&self) -> usize { s...
CSR
identifier_name
csr.rs
/* Copyright 2020 Brandon Lucia <blucia@gmail.com> 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 agreed to in writing...
pub fn get_v(&self) -> usize { self.v } pub fn get_e(&self) -> usize { self.e } pub fn get_offsets(&self) -> &Vec<usize> { &self.offsets } pub fn get_neighbs(&self) -> &[usize] { &self.neighbs } /// Build a random edge list /// This method re...
{ &mut self.vtxprop }
identifier_body
main.rs
#[macro_use] extern crate clap; extern crate ansi_term; extern crate atty; extern crate regex; extern crate ignore; extern crate num_cpus; pub mod lscolors; pub mod fshelper; mod app; use std::env; use std::error::Error; use std::io::Write; use std::ops::Deref; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use ...
let r = write!(&mut std::io::stdout(), "{}{}{}", prefix, path_str, separator); if r.is_err() { // Probably a broken pipe. Exit gracefully. process::exit(0); } } } /// Recursively scan the given search path and search for files / pathnames matching the pattern. fn s...
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate ansi_term; extern crate atty; extern crate regex; extern crate ignore; extern crate num_cpus; pub mod lscolors; pub mod fshelper; mod app; use std::env; use std::error::Error; use std::io::Write; use std::ops::Deref; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use ...
else if is_directory { &ls_colors.directory } else if is_executable(metadata.as_ref()) { &ls_colors.executable } else { // Look up file name let o_style = component_path.file_name() ...
{ &ls_colors.symlink }
conditional_block
main.rs
#[macro_use] extern crate clap; extern crate ansi_term; extern crate atty; extern crate regex; extern crate ignore; extern crate num_cpus; pub mod lscolors; pub mod fshelper; mod app; use std::env; use std::error::Error; use std::io::Write; use std::ops::Deref; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use ...
(root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) { let (tx, rx) = channel(); let walker = WalkBuilder::new(root) .hidden(config.ignore_hidden) .ignore(config.read_ignore) .git_ignore(config.read_ignore) .pare...
scan
identifier_name
doc_upsert.rs
//! The `doc upsert` command performs a KV upsert operation. use super::util::convert_nu_value_to_json_value; use crate::cli::error::{client_error_to_shell_error, serialize_error}; use crate::cli::util::{ cluster_identifiers_from, get_active_cluster, namespace_from_args, NuValueMap, }; use crate::client::{ClientEr...
} if let Some(i) = id { if let Some(c) = content { return Some((i, c)); } } } None }); let mut all_items = vec![]; for item in filtered.chain(input_args) { let value = serde_json::to_...
random_line_split
doc_upsert.rs
//! The `doc upsert` command performs a KV upsert operation. use super::util::convert_nu_value_to_json_value; use crate::cli::error::{client_error_to_shell_error, serialize_error}; use crate::cli::util::{ cluster_identifiers_from, get_active_cluster, namespace_from_args, NuValueMap, }; use crate::client::{ClientEr...
( state: Arc<Mutex<State>>, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let results = run_kv_store_ops(state, engine_state, stack, call, input, build_req)?; Ok(Value::List { vals: results, span: cal...
run_upsert
identifier_name
doc_upsert.rs
//! The `doc upsert` command performs a KV upsert operation. use super::util::convert_nu_value_to_json_value; use crate::cli::error::{client_error_to_shell_error, serialize_error}; use crate::cli::util::{ cluster_identifiers_from, get_active_cluster, namespace_from_args, NuValueMap, }; use crate::client::{ClientEr...
fn run_upsert( state: Arc<Mutex<State>>, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let results = run_kv_store_ops(state, engine_state, stack, call, input, build_req)?; Ok(Value::List { vals: results, ...
{ KeyValueRequest::Set { key, value, expiry } }
identifier_body
doc_upsert.rs
//! The `doc upsert` command performs a KV upsert operation. use super::util::convert_nu_value_to_json_value; use crate::cli::error::{client_error_to_shell_error, serialize_error}; use crate::cli::util::{ cluster_identifiers_from, get_active_cluster, namespace_from_args, NuValueMap, }; use crate::client::{ClientEr...
if k.clone() == content_column { content = convert_nu_value_to_json_value(&v, span).ok(); } } if let Some(i) = id { if let Some(c) = content { return Some((i, c)); } } } ...
{ id = v.as_string().ok(); }
conditional_block
mock_cr50_agent.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { anyhow::Error, fidl_fuchsia_tpm_cr50::{ InsertLeafResponse, PinWeaverRequest, PinWeaverRequestStream, TryAuthFailed, TryAuthR...
/// Adds a successful TryAuth response. pub(crate) fn add_try_auth_success_response( mut self, root_hash: Hash, cred_metadata: Vec<u8>, mac: Hash, ) -> Self { let success = TryAuthSuccess { root_hash: Some(root_hash), cred_metadata: Some(cred...
{ self.responses.push_back(MockResponse::RemoveLeaf { root_hash }); self }
identifier_body
mock_cr50_agent.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { anyhow::Error, fidl_fuchsia_tpm_cr50::{ InsertLeafResponse, PinWeaverRequest, PinWeaverRequestStream, TryAuthFailed, TryAuthR...
} _ => { panic!("Next mock response type was {:?} but expected TryAuth.", next_response) } }; } // GetLog and LogReplay are unimplemented as testing log replay is out // of scope for pwauth-credmgr integration tests...
{ resp.send(&mut std::result::Result::Ok(response)) .expect("failed to send response"); }
conditional_block
mock_cr50_agent.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { anyhow::Error, fidl_fuchsia_tpm_cr50::{ InsertLeafResponse, PinWeaverRequest, PinWeaverRequestStream, TryAuthFailed, TryAuthR...
( request: PinWeaverRequest, next_response: MockResponse, he_secret: &Arc<Mutex<Vec<u8>>>, ) { // Match the next response with the request, panicking if requests are out // of the expected order. match request { PinWeaverRequest::GetVersion { responder: resp } => { match next...
handle_request
identifier_name
mock_cr50_agent.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { anyhow::Error, fidl_fuchsia_tpm_cr50::{ InsertLeafResponse, PinWeaverRequest, PinWeaverRequestStream, TryAuthFailed, TryAuthR...
), }; } PinWeaverRequest::RemoveLeaf { params: _, responder: resp } => { match next_response { MockResponse::RemoveLeaf { root_hash } => { resp.send(&mut std::result::Result::Ok(root_hash)) .expect("failed...
} _ => panic!( "Next mock response type was {:?} but expected InsertLeaf.", next_response
random_line_split
lib.rs
//! A tiny and incomplete wasm interpreter //! //! This module contains a tiny and incomplete wasm interpreter built on top of //! `walrus`'s module structure. Each `Interpreter` contains some state //! about the execution of a wasm instance. The "incomplete" part here is //! related to the fact that this is *only* use...
(&mut self, id: FunctionId, module: &Module) -> Option<&[u32]> { self.descriptor.truncate(0); // We should have a blank wasm and LLVM stack at both the start and end // of the call. assert_eq!(self.sp, self.mem.len() as i32); self.call(id, module, &[]); assert_eq!(self.s...
interpret_descriptor
identifier_name
lib.rs
//! A tiny and incomplete wasm interpreter //! //! This module contains a tiny and incomplete wasm interpreter built on top of //! `walrus`'s module structure. Each `Interpreter` contains some state //! about the execution of a wasm instance. The "incomplete" part here is //! related to the fact that this is *only* use...
for (arg, val) in local.args.iter().zip(args) { frame.locals.insert(*arg, *val); } for (instr, _) in block.instrs.iter() { frame.eval(instr); if frame.done { break; } } self.scratch.last().cloned() } } struct ...
{ let func = module.funcs.get(id); log::debug!("starting a call of {:?} {:?}", id, func.name); log::debug!("arguments {:?}", args); let local = match &func.kind { walrus::FunctionKind::Local(l) => l, _ => panic!("can only call locally defined functions"), ...
identifier_body
lib.rs
//! A tiny and incomplete wasm interpreter //! //! This module contains a tiny and incomplete wasm interpreter built on top of //! `walrus`'s module structure. Each `Interpreter` contains some state //! about the execution of a wasm instance. The "incomplete" part here is //! related to the fact that this is *only* use...
impl Interpreter { /// Creates a new interpreter from a provided `Module`, precomputing all /// information necessary to interpret further. /// /// Note that the `module` passed in to this function must be the same as /// the `module` passed to `interpret` below. pub fn new(module: &Module) -> R...
}
random_line_split
lib.rs
//! A tiny and incomplete wasm interpreter //! //! This module contains a tiny and incomplete wasm interpreter built on top of //! `walrus`'s module structure. Each `Interpreter` contains some state //! about the execution of a wasm instance. The "incomplete" part here is //! related to the fact that this is *only* use...
} // All other instructions shouldn't be used by our various // descriptor functions. LLVM optimizations may mean that some // of the above instructions aren't actually needed either, but // the above instructions have empirically been required when ...
{ let ty = self.module.types.get(self.module.funcs.get(e.func).ty()); let args = (0..ty.params().len()) .map(|_| stack.pop().unwrap()) .collect::<Vec<_>>(); self.interp.call(e.func, self.module, &args); ...
conditional_block
maze.rs
//! I would like to approach the problem in two distinct ways //! //! One of them is floodfill - solution is highly suboptimal in terms of computational complexity, //! but it parallelizes perfectly - every iteration step recalculates new maze path data basing //! entirely on previous iteration. The aproach has a probl...
// I have feeling it is strongly suboptimal; Actually as both directions are encoded as 4 // bits, just precalculated table would be best solution let mut min = 4; for dir in [Self::LEFT, Self::RIGHT, Self::UP, Self::DOWN].iter() { let mut d = *dir; if!self.has_a...
pub fn min_rotation(self, other: Self) -> usize {
random_line_split
maze.rs
//! I would like to approach the problem in two distinct ways //! //! One of them is floodfill - solution is highly suboptimal in terms of computational complexity, //! but it parallelizes perfectly - every iteration step recalculates new maze path data basing //! entirely on previous iteration. The aproach has a probl...
{ Empty, Wall, /// Empty field with known distance from the start of the maze /// It doesn't need to be the closes path - it is distance calulated using some path Calculated(Dir, usize), } /// Whole maze reprezentation pub struct Maze { /// All fields flattened maze: Box<[Field]>, /// ...
Field
identifier_name
maze.rs
//! I would like to approach the problem in two distinct ways //! //! One of them is floodfill - solution is highly suboptimal in terms of computational complexity, //! but it parallelizes perfectly - every iteration step recalculates new maze path data basing //! entirely on previous iteration. The aproach has a probl...
/// Rotates left pub fn left(mut self) -> Self { let down = (self.0 & 1) << 3; self.0 >>= 1; self.0 |= down; self } /// Rotates right pub fn right(mut self) -> Self { let left = (self.0 & 8) >> 3; self.0 <<= 1; self.0 |= left; self.0...
{ let h = match from_x.cmp(&to_x) { Ordering::Less => Self::LEFT, Ordering::Greater => Self::RIGHT, Ordering::Equal => Self::NONE, }; let v = match from_y.cmp(&to_y) { Ordering::Less => Self::UP, Ordering::Greater => Self::DOWN, ...
identifier_body
lib.rs
pub use glam::*; use image::DynamicImage; pub use std::time; pub use wgpu::util::DeviceExt; use wgpu::ShaderModule; pub use winit::{ dpi::{PhysicalSize, Size}, event::{Event, *}, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowAttributes}, }; pub type Index = u16; #[repr(u32)] #[derive(Cl...
} pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) { self.configure( &device, &SurfaceHandlerConfiguration { width, height, sample_count: self.sample_count(), }, ); } pub fn con...
{ SampleCount::Single }
conditional_block
lib.rs
pub use glam::*; use image::DynamicImage; pub use std::time; pub use wgpu::util::DeviceExt; use wgpu::ShaderModule; pub use winit::{ dpi::{PhysicalSize, Size}, event::{Event, *}, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowAttributes}, }; pub type Index = u16; #[repr(u32)] #[derive(Cl...
(window: &Window) -> Self { pollster::block_on(Self::new_async(window)) } pub async fn new_async(window: &Window) -> Self { let instance = wgpu::Instance::new(wgpu::Backends::PRIMARY); let surface = unsafe { instance.create_surface(window) }; let adapter = instance ....
new
identifier_name
lib.rs
pub use glam::*; use image::DynamicImage; pub use std::time; pub use wgpu::util::DeviceExt; use wgpu::ShaderModule; pub use winit::{ dpi::{PhysicalSize, Size}, event::{Event, *}, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowAttributes}, }; pub type Index = u16; #[repr(u32)] #[derive(Cl...
pub fn create_render_pass_resources(&self) -> Result<RenderPassResources, wgpu::SurfaceError> { Ok(RenderPassResources { command_encoder: self.device.create_command_encoder(&Default::default()), surface_texture: self.surface_handler.surface.get_current_frame()?.output, ...
{ self.surface_handler.multisample_state() }
identifier_body
lib.rs
pub use glam::*; use image::DynamicImage; pub use std::time; pub use wgpu::util::DeviceExt; use wgpu::ShaderModule; pub use winit::{ dpi::{PhysicalSize, Size}, event::{Event, *}, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowAttributes}, }; pub type Index = u16; #[repr(u32)] #[derive(Cl...
usage: wgpu::BufferUsages, ) -> wgpu::Buffer { self.device .create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: Self::as_buffer_contents(contents), usage, }) } pub fn create_index_buffer(...
fn create_buffer<T>( &self, label: &str, contents: &[T],
random_line_split
main.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod disk; mod isolation; mod net; mod runtime; mod share; mod ssh; mod types; mod utils; mod vm; use std::env; use std::ffi::OsS...
{ /// Json-encoded file for VM machine configuration #[arg(long)] machine_spec: JsonFile<MachineOpts>, /// Json-encoded file describing paths of binaries required by VM #[arg(long)] runtime_spec: JsonFile<RuntimeOpts>, #[clap(flatten)] vm_args: VMArgs, } /// Spawn a container and execu...
RunCmdArgs
identifier_name
main.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod disk; mod isolation; mod net; mod runtime; mod share; mod ssh; mod types; mod utils; mod vm; use std::env; use std::ffi::OsS...
if!orig_args.output_dirs.is_empty() { return Err(anyhow!( "Test command must not specify --output-dirs. \ This will be parsed from env and test command parameters instead." )); } let envs = get_test_envs(cli_envs); #[derive(Debug, Parser)] struct TestArgsPar...
{ return Err(anyhow!("Test command must specify --timeout-secs.")); }
conditional_block
main.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod disk; mod isolation; mod net; mod runtime; mod share; mod ssh; mod types; mod utils; mod vm; use std::env; use std::ffi::OsS...
) .init(); Platform::set()?; debug!("Args: {:?}", env::args()); let cli = Cli::parse(); match &cli.command { Commands::Isolate(args) => respawn(args), Commands::Run(args) => run(args), Commands::Test(args) => test(args), } } #[cfg(test)] mod test { use s...
.with( tracing_subscriber::EnvFilter::builder() .with_default_directive(LevelFilter::INFO.into()) .from_env() .expect("Invalid logging level set by env"),
random_line_split
error.rs
//! 9P error representations. //! //! In 9P2000 errors are represented as strings. //! All the error strings in this module are imported from include/net/9p/error.c of Linux kernel. //! //! By contrast, in 9P2000.L, errors are represented as numbers (errno). //! Using the Linux system errno numbers is the expected beha...
} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::No(ref e) => write!(f, "System error: {}", e.desc()), Error::Io(ref e) => write!(f, "I/O error: {}", e), } } } impl stderror::Error for Error { fn description...
random_line_split
error.rs
//! 9P error representations. //! //! In 9P2000 errors are represented as strings. //! All the error strings in this module are imported from include/net/9p/error.c of Linux kernel. //! //! By contrast, in 9P2000.L, errors are represented as numbers (errno). //! Using the Linux system errno numbers is the expected beha...
} impl From<nix::Error> for Error { fn from(e: nix::Error) -> Self { Error::No(e.errno()) } } /// The system errno definitions. /// /// # Protocol /// 9P2000.L pub mod errno { extern crate nix; pub use self::nix::errno::Errno::*; } /// 9P error strings imported from Linux. /// /// # Protocol...
{ Error::No(e) }
identifier_body
error.rs
//! 9P error representations. //! //! In 9P2000 errors are represented as strings. //! All the error strings in this module are imported from include/net/9p/error.c of Linux kernel. //! //! By contrast, in 9P2000.L, errors are represented as numbers (errno). //! Using the Linux system errno numbers is the expected beha...
(e: &io::Error) -> nix::errno::Errno { e.raw_os_error() .map(nix::errno::from_i32) .unwrap_or_else(|| match e.kind() { NotFound => ENOENT, PermissionDenied => EPERM, ConnectionRefused => ECONNREFUSED, ConnectionReset => ECONNRESET, Connection...
errno_from_ioerror
identifier_name
mod.rs
generation: u32, index: u32, } pub(crate) enum AllocAtWithoutReplacement { Exists(EntityLocation), DidNotExist, ExistsWithWrongGeneration, } impl Entity { #[cfg(test)] pub(crate) const fn new(index: u32, generation: u32) -> Entity { Entity { index, generation } } /// An entit...
(&mut self, entity: Entity) -> Option<EntityLocation> { self.verify_flushed(); let loc = if entity.index as usize >= self.meta.len() { self.pending.extend((self.meta.len() as u32)..entity.index); let new_free_cursor = self.pending.len() as IdCursor; *self.free_cursor...
alloc_at
identifier_name
mod.rs
<'de>, { let id: u64 = serde::de::Deserialize::deserialize(deserializer)?; Ok(Entity::from_bits(id)) } } impl fmt::Debug for Entity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}v{}", self.index, self.generation) } } impl SparseSetIndex for Entity { ...
/// /// This does not include entities that have been reserved but have never been /// allocated yet. ///
random_line_split
mod.rs
generation: u32, index: u32, } pub(crate) enum AllocAtWithoutReplacement { Exists(EntityLocation), DidNotExist, ExistsWithWrongGeneration, } impl Entity { #[cfg(test)] pub(crate) const fn new(index: u32, generation: u32) -> Entity { Entity { index, generation } } /// An entit...
else if let Some(index) = self.pending.iter().position(|item| *item == entity.index) { self.pending.swap_remove(index); let new_free_cursor = self.pending.len() as IdCursor; *self.free_cursor.get_mut() = new_free_cursor; self.len += 1; AllocAtWithoutReplaceme...
{ self.pending.extend((self.meta.len() as u32)..entity.index); let new_free_cursor = self.pending.len() as IdCursor; *self.free_cursor.get_mut() = new_free_cursor; self.meta .resize(entity.index as usize + 1, EntityMeta::EMPTY); self.len += 1; ...
conditional_block
mod.rs
generation: u32, index: u32, } pub(crate) enum AllocAtWithoutReplacement { Exists(EntityLocation), DidNotExist, ExistsWithWrongGeneration, } impl Entity { #[cfg(test)] pub(crate) const fn new(index: u32, generation: u32) -> Entity { Entity { index, generation } } /// An entit...
/// Increments the `generation` of a freed [`Entity`]. The next entity ID allocated with this /// `index` will count `generation` starting from the prior `generation` + the specified /// value + 1. /// /// Does nothing if no entity with this `index` has been allocated yet. pub(crate) fn reserv...
{ // SAFETY: Caller guarantees that `index` a valid entity index self.meta.get_unchecked_mut(index as usize).location = location; }
identifier_body
windows.rs
//! Windows-specific types for signal handling. //! //! This module is only defined on Windows and contains the primary `Event` type //! for receiving notifications of events. These events are listened for via the //! `SetConsoleCtrlHandler` function which receives events of the type //! `CTRL_C_EVENT` and `CTRL_BREAK_...
() -> IoFuture<Event> { Event::ctrl_break_handle(&Handle::current()) } /// Creates a new stream listening for the `CTRL_BREAK_EVENT` events. /// /// This function will register a handler via `SetConsoleCtrlHandler` and /// deliver notifications to the returned stream. pub fn ctrl_break_...
ctrl_break
identifier_name
windows.rs
//! Windows-specific types for signal handling. //! //! This module is only defined on Windows and contains the primary `Event` type //! for receiving notifications of events. These events are listened for via the //! `SetConsoleCtrlHandler` function which receives events of the type //! `CTRL_C_EVENT` and `CTRL_BREAK_...
self.reg.clear_read_ready(Ready::readable())?; self.reg .get_ref() .inner .borrow() .as_ref() .unwrap() .1 .set_readiness(mio::Ready::empty()) .expect("failed to set readiness"); Ok(Async::Ready(Some(()))) ...
}
random_line_split
extern_crate.rs
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! ...
// Update the spans of the `::` tokens to lie in the function for punct in path .segments .pairs_mut() .map(|p| p.into_tuple().1) .flatten() { punct.spans = [function.span(); 2]; } let mut args_list = TokenStream::new(); args_list.append_separated( fu...
arguments: PathArguments::None, });
random_line_split
extern_crate.rs
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! ...
stream } } /// Generates the code for a function inside a `extern_crate` module. fn render_function( function: &ForeignItemFn, tokens: &mut TokenStream, path: &Path, visibility: &TokenStream, ) { tokens.append_all(&function.attrs); let doc_header = generate_extern_crate_fn_docs(pat...
{ let mut stream = TokenStream::new(); stream.append_all(&self.attrs); let vis = &self.visibility; stream.append_all(quote! { #vis }); stream.append_all(quote! { mod }); stream.append(self.ident.clone()); let mut content = TokenStream::new(); content.appe...
identifier_body
extern_crate.rs
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! ...
(input: ParseStream) -> syn::Result<Self> { let attrs = input.call(Attribute::parse_outer)?; let visibility = input.parse()?; let mod_token = input.parse()?; let ident = input.parse()?; let content; let braces = braced!(content in input); let mut impl_blocks = V...
parse
identifier_name
extern_crate.rs
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! ...
else if <ItemUse as Parse>::parse(&content.fork()).is_ok() { imports.push(content.parse()?); } else if <ForeignItemFn as Parse>::parse(&content.fork()).is_ok() { functions.push(content.parse()?); } else { modules.push(content.parse().map_err(|err|...
{ impl_blocks.push(content.parse()?); }
conditional_block
lib.rs
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::any::Any; use std::borrow::Cow; use std::fmt::Display; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use crossbeam::channel::{Receiver, Sender}; use tuikit::prelude::{Event as TermEvent, *}; pub use crate::ansi::AnsiS...
} //------------------------------------------------------------------------------ // Display Context pub enum Matches<'a> { None, CharIndices(&'a [usize]), CharRange(usize, usize), ByteRange(usize, usize), } pub struct DisplayContext<'a> { pub text: &'a str, pub score: i32, pub matches: ...
{ Cow::Borrowed(self.as_ref()) }
identifier_body
lib.rs
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::any::Any; use std::borrow::Cow; use std::fmt::Display; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use crossbeam::channel::{Receiver, Sender}; use tuikit::prelude::{Event as TermEvent, *}; pub use crate::ansi::AnsiS...
/// want, you could still use `downcast` to retain the pointer to the original struct. fn output(&self) -> Cow<str> { self.text() } /// we could limit the matching ranges of the `get_text` of the item. /// providing (start_byte, end_byte) of the range fn get_matching_ranges(&self) -> Op...
/// Get output text(after accept), default to `text()` /// Note that this function is intended to be used by the caller of skim and will not be used by /// skim. And since skim will return the item back in `SkimOutput`, if string is not what you
random_line_split
lib.rs
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::any::Any; use std::borrow::Cow; use std::fmt::Display; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use crossbeam::channel::{Receiver, Sender}; use tuikit::prelude::{Event as TermEvent, *}; pub use crate::ansi::AnsiS...
() -> Self { CaseMatching::Smart } } #[derive(PartialEq, Eq, Clone, Debug)] #[allow(dead_code)] pub enum MatchRange { ByteRange(usize, usize), // range of bytes Chars(Vec<usize>), // individual character indices matched } pub type Rank = [i32; 4]; #[derive(Clone)] pub struct MatchResult { ...
default
identifier_name
dynamic_store.rs
// Copyright 2017 Amagicom AB. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
} } /// Sets the value of the given key. Overwrites existing values. /// Returns `true` on success, false on failure. pub fn set<S: Into<CFString>, V: CFPropertyListSubClass>(&self, key: S, value: V) -> bool { self.set_raw(key, &value.into_CFPropertyList()) } /// Sets the valu...
{ None }
conditional_block
dynamic_store.rs
// Copyright 2017 Amagicom AB. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
} /// The raw callback used by the safe `SCDynamicStore` to convert from the `SCDynamicStoreCallBack` /// to the `SCDynamicStoreCallBackT` unsafe extern "C" fn convert_callback<T>( store_ref: SCDynamicStoreRef, changed_keys_ref: CFArrayRef, context_ptr: *mut c_void, ) { let store = SCDynamicStore::wra...
{ unsafe { let run_loop_source_ref = SCDynamicStoreCreateRunLoopSource( kCFAllocatorDefault, self.as_concrete_TypeRef(), 0, ); CFRunLoopSource::wrap_under_create_rule(run_loop_source_ref) } }
identifier_body
dynamic_store.rs
// Copyright 2017 Amagicom AB. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
( &self, callback_context: SCDynamicStoreCallBackContext<T>, ) -> SCDynamicStoreContext { // move the callback context struct to the heap and "forget" it. // It will later be brought back into the Rust typesystem and freed in // `release_callback_context` let info_ptr...
create_context
identifier_name
dynamic_store.rs
// Copyright 2017 Amagicom AB. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to...
let info_ptr = Box::into_raw(Box::new(callback_context)); SCDynamicStoreContext { version: 0, info: info_ptr as *mut _ as *mut c_void, retain: None, release: Some(release_callback_context::<T>), copyDescription: None, } } } declar...
// It will later be brought back into the Rust typesystem and freed in // `release_callback_context`
random_line_split
filter_list.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Filter-list view widget use super::{driver, Driver, Li...
result } fn iter_vec_from(&self, start: usize, limit: usize) -> Vec<(Self::Key, Self::Item)> { let view = self.view.borrow(); let end = self.len().min(start + limit); if start >= end { return Vec::new(); } let mut v = Vec::with_capacity(end - start);...
{ // remove the updated item from our filtered list self.view.borrow_mut().retain(|item| item != key); }
conditional_block
filter_list.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Filter-list view widget use super::{driver, Driver, Li...
fn update_self(&self) -> Option<UpdateHandle> { self.refresh() } } impl<K, M, T: ListData + UpdatableHandler<K, M> +'static, F: Filter<T::Item>> UpdatableHandler<K, M> for FilteredList<T, F> { fn handle(&self, key: &K, msg: &M) -> Option<UpdateHandle> { self.data.handle(key, msg) }...
{ self.filter.update_handle() }
identifier_body
filter_list.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Filter-list view widget use super::{driver, Driver, Li...
(&self) -> usize { self.view.borrow().len() } fn contains_key(&self, key: &Self::Key) -> bool { self.get_cloned(key).is_some() } fn get_cloned(&self, key: &Self::Key) -> Option<Self::Item> { // Check the item against our filter (probably O(1)) instead of using // our fi...
len
identifier_name
filter_list.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Filter-list view widget use super::{driver, Driver, Li...
} } impl< D: Directional, T: ListData + UpdHandler<T::Key, V::Msg>, F: Filter<T::Item>, V: Driver<T::Item>, > FilterListView<D, T, F, V> { /// Construct a new instance with explicit direction and view pub fn new_with_dir_driver(direction: D, view: V, data: T, filter: F) -...
/// Set the direction of contents pub fn set_direction(&mut self, direction: Direction) -> TkAction { self.list.set_direction(direction)
random_line_split
mod.rs
//! `types` module contains types necessary for Fluent runtime //! value handling. //! The core struct is [`FluentValue`] which is a type that can be passed //! to the [`FluentBundle::format_pattern`](crate::bundle::FluentBundle) as an argument, it can be passed //! to any Fluent Function, and any function may return i...
(v: Option<T>) -> Self { match v { Some(v) => v.into(), None => FluentValue::None, } } }
from
identifier_name
mod.rs
//! `types` module contains types necessary for Fluent runtime //! value handling. //! The core struct is [`FluentValue`] which is a type that can be passed //! to the [`FluentBundle::format_pattern`](crate::bundle::FluentBundle) as an argument, it can be passed //! to any Fluent Function, and any function may return i...
} impl<'source> From<&'source str> for FluentValue<'source> { fn from(s: &'source str) -> Self { FluentValue::String(s.into()) } } impl<'source> From<Cow<'source, str>> for FluentValue<'source> { fn from(s: Cow<'source, str>) -> Self { FluentValue::String(s) } } impl<'source, T> From...
{ FluentValue::String(s.into()) }
identifier_body
mod.rs
//! `types` module contains types necessary for Fluent runtime //! value handling. //! The core struct is [`FluentValue`] which is a type that can be passed //! to the [`FluentBundle::format_pattern`](crate::bundle::FluentBundle) as an argument, it can be passed //! to any Fluent Function, and any function may return i...
match self { FluentValue::String(s) => w.write_str(s), FluentValue::Number(n) => w.write_str(&n.as_string()), FluentValue::Custom(s) => w.write_str(&scope.bundle.intls.stringify_value(&**s)), FluentValue::Error => Ok(()), FluentValue::None => Ok(()), ...
} }
random_line_split
staged_file.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fidl_fuchsia_io as fio, fuchsia_zircon as zx, rand::{thread_rng, Rng}, tracing::warn, }; const TEMPFILE_RANDOM_LENGTH: usize = 8usize; ...
&temp_filename, fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE | fio::OpenFlags::CREATE, ) .await?; Ok(StagedFile { dir_proxy, temp_filename, file_proxy }) } /// Writes data to the backing staged file proxy. //...
let temp_filename = generate_tempfile_name(tempfile_prefix); let file_proxy = fuchsia_fs::directory::open_file( dir_proxy,
random_line_split
staged_file.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fidl_fuchsia_io as fio, fuchsia_zircon as zx, rand::{thread_rng, Rng}, tracing::warn, }; const TEMPFILE_RANDOM_LENGTH: usize = 8usize; ...
} } } if failures.is_empty() { Ok(()) } else { Err(failures) } } } /// Generates a temporary filename using |thread_rng| to append random chars to /// a given |prefix|. fn generate_tempfile_name(prefix: &str) -> String { // G...
{ if let Err(unlink_err) = unlink_res { failures.push(StagedFileError::UnlinkError(zx::Status::from_raw( unlink_err, ))); } }
conditional_block
staged_file.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fidl_fuchsia_io as fio, fuchsia_zircon as zx, rand::{thread_rng, Rng}, tracing::warn, }; const TEMPFILE_RANDOM_LENGTH: usize = 8usize; ...
{ /// Invalid arguments. #[error("Invalid arguments to create a staged file: {0}")] InvalidArguments(String), /// Failed to open a file or directory. #[error("Failed to open: {0}")] OpenError(#[from] fuchsia_fs::node::OpenError), /// Failed during a FIDL call. #[error("Failed during F...
StagedFileError
identifier_name
staged_file.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fidl_fuchsia_io as fio, fuchsia_zircon as zx, rand::{thread_rng, Rng}, tracing::warn, }; const TEMPFILE_RANDOM_LENGTH: usize = 8usize; ...
let dirents = fuchsia_fs::directory::readdir(&dir).await.unwrap(); assert_eq!(dirents.len(), 3); assert!(file_exists_with_data(&dir, "real-001", b"real-001".as_ref()).await); assert!(file_exists_with_data(&dir, "real-002", b"real-002".as_ref()).await); assert!(file_exists_with_da...
{ let tmp_dir = TempDir::new().unwrap(); let dir = fuchsia_fs::directory::open_in_namespace( tmp_dir.path().to_str().unwrap(), fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE, ) .expect("could not open temp dir"); // Write a variety of sta...
identifier_body
result.rs
//! Operation result structures and helpers. //! //! Most LDAP operations return an [`LdapResult`](struct.LdapResult.html). This module //! contains its definition, as well as that of a number of wrapper structs and //! helper methods, which adapt LDAP result and error handling to be a closer //! match to Rust conventi...
(pub LdapResult); impl CompareResult { /// If the result code is 5 (compareFalse) or 6 (compareTrue), return the corresponding /// boolean value wrapped in `Ok()`, otherwise wrap the `LdapResult` part in an `LdapError`. pub fn equal(self) -> Result<bool> { match self.0.rc { 5 => Ok(fals...
CompareResult
identifier_name
result.rs
//! Operation result structures and helpers. //! //! Most LDAP operations return an [`LdapResult`](struct.LdapResult.html). This module //! contains its definition, as well as that of a number of wrapper structs and //! helper methods, which adapt LDAP result and error handling to be a closer //! match to Rust conventi...
/// interface, but there are scenarios where this would preclude intentional /// incorporation of error conditions into query design. Instead, the struct /// implements helper methods, [`success()`](#method.success) and /// [`non_error()`](#method.non_error), which may be used for ergonomic error /// handling when simp...
/// This structure faithfully replicates the components dictated by the standard, /// and is distinctly C-like with its reliance on numeric codes for the indication /// of outcome. It would be tempting to hide it behind an automatic `Result`-like
random_line_split
deflate.rs
use super::Source; use super::huffman::Huffman; use super::bitstream::BitStream; use super::bufferedwriter::BufferedWriter; struct DynamicBlock { // If we encounter a repeat, we should set our state so that we keep producing // repeats until they run out, instead of reading from the bit stream. repeats_remaining: u...
} impl <'a> Source<Option<u8>> for DEFLATEReader<'a> { fn next(self: &mut DEFLATEReader<'a>) -> Option<u8> { // We set this field when we have finished with a block or haven't started yet // this field tells us that we should begin reading a new block which involves // decoding all the headers and huffman tree...
{ DEFLATEReader{ buffered_writer: BufferedWriter::new(), bit_stream: BitStream::new(input), has_seen_final_block: false, current_block: None, } }
identifier_body
deflate.rs
use super::Source; use super::huffman::Huffman; use super::bitstream::BitStream; use super::bufferedwriter::BufferedWriter; struct DynamicBlock { // If we encounter a repeat, we should set our state so that we keep producing // repeats until they run out, instead of reading from the bit stream. repeats_remaining: u...
<'a> { // The following two fields are used to manage input/output buffered_writer: BufferedWriter, bit_stream: BitStream<'a>, // The following two fields control if we read another block has_seen_final_block: bool, current_block: Option<DynamicBlock>, } const BTYPE_DYNAMIC : u8 = 0b10; impl <'a> DEFLATEReader...
DEFLATEReader
identifier_name
deflate.rs
use super::Source; use super::huffman::Huffman; use super::bitstream::BitStream; use super::bufferedwriter::BufferedWriter; struct DynamicBlock { // If we encounter a repeat, we should set our state so that we keep producing // repeats until they run out, instead of reading from the bit stream. repeats_remaining: u...
println!("Literal/Length Huffman = {:?}", result); result } fn read_distance_huffman(length: usize, input_stream: &mut BitStream, code_length_huffman: &Huffman<usize>) -> Huffman<usize> { let alphabet = (0..length).collect(); let lengths = DynamicBlock::read_code_lengths(length, input_stream, code_length_huf...
let result = Huffman::new(&alphabet, &lengths);
random_line_split
deflate.rs
use super::Source; use super::huffman::Huffman; use super::bitstream::BitStream; use super::bufferedwriter::BufferedWriter; struct DynamicBlock { // If we encounter a repeat, we should set our state so that we keep producing // repeats until they run out, instead of reading from the bit stream. repeats_remaining: u...
}, Huffman::Leaf(value) => *value, Huffman::DeadEnd => panic!("Reached dead end!"), } } fn next(&mut self, bit_stream: &mut BitStream) -> DEFLATEResult { if self.repeats_remaining > 0 { self.repeats_remaining -= 1; return DEFLATEResult::Repeat(self.last_repeat_distance) } let value = Dynamic...
{ DynamicBlock::get_next_huffman_encoded_value(zero, input_stream) }
conditional_block
main.rs
// #! global // #![warn()] enable // #![allow()] disable #![allow(non_snake_case)] #![allow(dead_code)] use hmac::Hmac; use http::method; use openssl::{hash, pkcs5::pbkdf2_hmac}; use reqwest::Client; use std::{borrow::Borrow, collections::{HashMap, VecDeque}, default, ops::Index}; use std::{fs::File, usize}; // use sh...
} fn md5str(s: String) -> String { let mut hasher = md5::Md5::new(); hasher.input_str(&s); hasher.result_str() } fn escapeUri(s: String) -> String { // let s = String::from("/xx/中文.log"); if s == "" { let _s = String::from("中文"); } let escape: [u32; 8] = [ 0xffffffff, 0xfc0...
} Ok(()) }
random_line_split
main.rs
// #! global // #![warn()] enable // #![allow()] disable #![allow(non_snake_case)] #![allow(dead_code)] use hmac::Hmac; use http::method; use openssl::{hash, pkcs5::pbkdf2_hmac}; use reqwest::Client; use std::{borrow::Borrow, collections::{HashMap, VecDeque}, default, ops::Index}; use std::{fs::File, usize}; // use sh...
yper::Method, url:String, headers: HashMap<String,String>, body: Vec<u8>){ match hyper::Request::builder().method(method).uri(url).body(body){ Ok(req) => { for (key,value) in headers{ if key.to_lowercase() == "host"{ // req. ...
Some(Value ) => Value.to_string(), None => host } } /// FIXME fn doHTTPRequest(&mut self,method: h
identifier_body
main.rs
// #! global // #![warn()] enable // #![allow()] disable #![allow(non_snake_case)] #![allow(dead_code)] use hmac::Hmac; use http::method; use openssl::{hash, pkcs5::pbkdf2_hmac}; use reqwest::Client; use std::{borrow::Borrow, collections::{HashMap, VecDeque}, default, ops::Index}; use std::{fs::File, usize}; // use sh...
(self) -> Self { self } } impl UpYunConfig { fn new(Bucket: String, Operator: String, Password: String) -> Self{ UpYunConfig{ Bucket:Bucket, Operator:Operator, Password: Password, ..Default::default() } } fn build(mut self) -> Self...
build
identifier_name
main.rs
// #! global // #![warn()] enable // #![allow()] disable #![allow(non_snake_case)] #![allow(dead_code)] use hmac::Hmac; use http::method; use openssl::{hash, pkcs5::pbkdf2_hmac}; use reqwest::Client; use std::{borrow::Borrow, collections::{HashMap, VecDeque}, default, ops::Index}; use std::{fs::File, usize}; // use sh...
.to_string(), ":".to_string(), sign_str, ]; let _back_str = back_vec.concat(); } #[test] fn hmac_test() { let value = "xx".as_bytes(); let key = "yy".as_bytes(); assert_eq!( "3124cf1daef6d713c312065988652d8b7fca587e".to_string(), ...
ring> = vec![ "Upyun".to_string(), "Operator"
conditional_block
fs.rs
use core_collections::borrow::ToOwned; use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom}; use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use mem; use path::{PathBuf, Path}; use string::String; use sys_common::AsInner; use vec::Vec; use syscall::{open, dup, close, fpath, fstat, f...
} remove_dir(path) } /// Removes a file from the filesystem pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> { let path_str = path.as_ref().as_os_str().as_inner(); unlink(path_str).and(Ok(())).map_err(|x| Error::from_sys(x)) }
{ try!(remove_file(&child.path())); }
conditional_block
fs.rs
use core_collections::borrow::ToOwned; use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom}; use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use mem; use path::{PathBuf, Path}; use string::String; use sys_common::AsInner; use vec::Vec; use syscall::{open, dup, close, fpath, fstat, f...
self.mode = mode as u16; } fn from_mode(mode: u32) -> Self { Permissions { mode: mode as u16 } } } pub struct DirEntry { path: PathBuf, } impl DirEntry { pub fn file_name(&self) -> &Path { unsafe { mem::transmute(self.path.file_name().unwrap().to_str()....
random_line_split
fs.rs
use core_collections::borrow::ToOwned; use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom}; use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use mem; use path::{PathBuf, Path}; use string::String; use sys_common::AsInner; use vec::Vec; use syscall::{open, dup, close, fpath, fstat, f...
} impl FromRawFd for File { unsafe fn from_raw_fd(fd: RawFd) -> Self { File { fd: fd } } } impl IntoRawFd for File { fn into_raw_fd(self) -> RawFd { let fd = self.fd; mem::forget(self); fd } } impl Read for File { fn read(&mut self, buf: &mut [...
{ self.fd }
identifier_body
fs.rs
use core_collections::borrow::ToOwned; use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom}; use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use mem; use path::{PathBuf, Path}; use string::String; use sys_common::AsInner; use vec::Vec; use syscall::{open, dup, close, fpath, fstat, f...
<P: AsRef<Path>>(path: P) -> Result<()> { if let Some(parent) = path.as_ref().parent() { try!(create_dir_all(&parent)); } if let Err(_err) = metadata(&path) { try!(create_dir(&path)); } Ok(()) } /// Copy the contents of one file to another pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>...
create_dir_all
identifier_name
localization.rs
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 agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTI...
} } /* //// impl<T> std::fmt::Debug for ArgSource<T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Arg Resolver {:p}", self.0) } } /// Helper to impl display for slices of displayable things. struct PrintLocales<'a, T>(&'a [T]); imp...
{ false }
conditional_block
localization.rs
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 agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTI...
( mut self, key: &'static str, f: fn(&T, &Env) -> ArgValue, //// ////f: impl Fn(&T, &Env) -> FluentValue<'static> +'static, ) -> Self { self.args .get_or_insert(Vec::new()) .push((key, ArgSource(f))) .expect("with arg failed"); //// ...
with_arg
identifier_name
localization.rs
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 agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARR...
} } impl<T: Data> LocalizedString<T> { /// Add a named argument and a corresponding [`ArgClosure`]. This closure /// is a function that will return a value for the given key from the current /// environment and data. /// /// [`ArgClosure`]: type.ArgClosure.html pub fn with_arg( mut ...
*/ ////
random_line_split
localization.rs
an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Localization handling. //! //! Localization is backed by [Fluent], via [fluent-rs]. //! //! In Druid, the main way ...
{ // TODO Ok(()) }
identifier_body
filesystem.rs
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{...
(filename: &String) -> String { format!("{}/{}", constants::DATA_DIR, filename) } // Returns messages to be gossiped pub fn handle_failed_node(failed_id: &String) -> BoxedErrorResult<Vec<SendableOperation>> { match heartbeat::is_master() { true => { let mut generated_operations: Vec<Sendabl...
distributed_file_path
identifier_name
filesystem.rs
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{...
} Err(format!("No new owners available for file {}", filename).into()) }, None => Err(format!("No owner found for file {}", filename).into()) } } fn distributed_file_path(filename: &String) -> String { format!("{}/{}", constants::DATA_DIR, filename) } // Returns messag...
{ return Ok(potential_owner.clone()); }
conditional_block
filesystem.rs
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{...
// TODO: This function makes the entire system assume there are always at least two nodes in the system // and the file must have an owner or else the operation will not work correctly. This is fine for now // but it is worth improving sooner rather than later (make distinct Error types to differentiate, e...
random_line_split
filesystem.rs
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{...
async fn handle_connection(mut connection: async_std::net::TcpStream) -> BoxedErrorResult<()> { let (operation, source) = connection.try_read_operation().await?; // TODO: Think about what standard we want with these let _generated_operations = operation.execute(source)?; Ok(()) } // Helpers fn gen_fi...
{ let server = globals::SERVER_SOCKET.read(); let mut incoming = server.incoming(); while let Some(stream) = incoming.next().await { let connection = stream?; log(format!("Handling connection from {:?}", connection.peer_addr())); spawn(handle_connection(connection)); } Ok(()...
identifier_body
main.rs
mod utils; use chrono::{DateTime, Utc, TimeZone}; use actix::{Actor, Handler, Message, AsyncContext}; use actix_web::{http, web, HttpResponse, App}; use actix_web::middleware::cors::Cors; use futures::{Future}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use log::debug; use crate::utils::ErrSt...
; } } struct Downloader; impl Actor for Downloader { type Context = actix::Context<Self>; } impl Handler<DownloadFeed> for Downloader { type Result = <DownloadFeed as Message>::Result; fn handle(&mut self, msg: DownloadFeed, _: &mut Self::Context) -> Self::Result { let channel = rss::Channel:...
{ feed.merge(msg.feed) }
conditional_block
main.rs
mod utils; use chrono::{DateTime, Utc, TimeZone}; use actix::{Actor, Handler, Message, AsyncContext}; use actix_web::{http, web, HttpResponse, App}; use actix_web::middleware::cors::Cors; use futures::{Future}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use log::debug; use crate::utils::ErrSt...
server.start(); Ok(()) } pub fn main() -> Result<(), std::io::Error> { std::env::set_var("RUST_LOG", "actix_web=debug,rssreader=debug"); env_logger::init(); actix::System::run(|| {actix_main().expect("App crashed");} ) }
server.listen(l)? } else { server.bind("[::1]:8000")? }; println!("Started HTTP server on {:?}", server.addrs_with_scheme().iter().map(|(a, s)| format!("{}://{}/", s, a)).collect::<Vec<_>>());
random_line_split
main.rs
mod utils; use chrono::{DateTime, Utc, TimeZone}; use actix::{Actor, Handler, Message, AsyncContext}; use actix_web::{http, web, HttpResponse, App}; use actix_web::middleware::cors::Cors; use futures::{Future}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use log::debug; use crate::utils::ErrSt...
{ pub title: Option<String>, pub link: Option<String>, pub content: Option<String>, pub pub_date: Option<DateTime<Utc>>, pub guid: String, pub unread: bool, } #[derive(Clone, Debug, Serialize)] struct Feed { pub title: String, pub last_updated: DateTime<Utc>, pub items: Vec<Item>, ...
Item
identifier_name
sssmc39_scheme.rs
// Copyright 2019 The Grin Developers // // 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 agree...
); Ok(dms) } /// Decodes all Mnemonics to a list of shares and performs error checking fn decode_mnemonics(mnemonics: &[Vec<String>]) -> Result<Vec<GroupShare>, Error> { let mut shares = vec![]; if mnemonics.is_empty() { return Err(ErrorKind::Mnemonic( "List of mnemonics is empty.".to_string(), ))?; } let...
&ems.share_value, passphrase, ems.iteration_exponent, ems.identifier,
random_line_split
sssmc39_scheme.rs
// Copyright 2019 The Grin Developers // // 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 agree...
)?; for s in &mns { println!("{}", s); } let result = combine_mnemonics(&flatten_mnemonics(&mns)?, "")?; println!("Single 3 of 5 Decoded: {:?}", result); assert_eq!(result, master_secret); // work through some varying sized secrets let mut master_secret = b"\x0c\x94\x90\xbcn\xd6\xbc\xbf\xac>\xbe}\xe...
{ let master_secret = b"\x0c\x94\x90\xbcn\xd6\xbc\xbf\xac>\xbe}\xeeV\xf2P".to_vec(); // single 3 of 5 test, splat out all mnemonics println!("Single 3 of 5 Encoded: {:?}", master_secret); let mns = generate_mnemonics(1, &[(3, 5)], &master_secret, "", 0)?; for s in &mns { println!("{}", s); } let resul...
identifier_body
sssmc39_scheme.rs
// Copyright 2019 The Grin Developers // // 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 agree...
let check_len = mnemonics[0].len(); for m in mnemonics { if m.len()!= check_len { return Err(ErrorKind::Mnemonic( "Invalid set of mnemonics. All mnemonics must have the same length.".to_string(), ))?; } shares.push(Share::from_mnemonic(m)?); } let check_share = shares[0].clone(); for s in shares....
{ return Err(ErrorKind::Mnemonic( "List of mnemonics is empty.".to_string(), ))?; }
conditional_block
sssmc39_scheme.rs
// Copyright 2019 The Grin Developers // // 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 agree...
(mnemonics: &[Vec<String>]) -> Result<Vec<GroupShare>, Error> { let mut shares = vec![]; if mnemonics.is_empty() { return Err(ErrorKind::Mnemonic( "List of mnemonics is empty.".to_string(), ))?; } let check_len = mnemonics[0].len(); for m in mnemonics { if m.len()!= check_len { return Err(ErrorKind::Mn...
decode_mnemonics
identifier_name
lib.rs
if next.is_null() || CellHeader::next_cell_is_invalid(neighbors) { None } else { Some(&*next) } } #[inline] unsafe fn prev_checked( _neighbors: &Neighbors<'a, CellHeader<'a>>, prev: *const CellHeader<'a>, ) -> Option<&'a CellHeader<'a>> { ...
// properly aligned? if self.header.is_aligned_to(align) { previous.set(self.next_free()); let allocated = self.as_allocated_cell(policy); return Some(allocated); } None } fn insert_into_free_list<'b>( &'b self, head: &'b Cell...
random_line_split
lib.rs
next_cell_is_invalid(neighbors: &Neighbors<'a, Self>) { neighbors.clear_next_bit_2(); } fn size(&self) -> Bytes { let data = unsafe { (self as *const CellHeader<'a>).offset(1) }; let data = data as usize; let next = self.neighbors.next_unchecked(); let next = next as us...
dealloc
identifier_name
lib.rs
if next.is_null() || CellHeader::next_cell_is_invalid(neighbors) { None } else { Some(&*next) } } #[inline] unsafe fn prev_checked( _neighbors: &Neighbors<'a, CellHeader<'a>>, prev: *const CellHeader<'a>, ) -> Option<&'a CellHeader<'a>> { ...
}) } unsafe fn alloc_impl(&self, layout: Layout) -> Result<NonNull<u8>, AllocErr> { let size = Bytes(layout.size()); let align = if layout.align() == 0 { Bytes(1) } else { Bytes(layout.align()) }; if size.0 == 0 { // Ensure t...
{ if align <= size_of::<usize>() { if let Some(head) = self.size_classes.get(size) { let policy = size_classes::SizeClassAllocPolicy(&self.head); let policy = &policy as &dyn AllocPolicy<'a>; return head.with_exclusive_access(|head| { ...
identifier_body