file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | use futures_util::future::Either;
use futures_util::stream::StreamExt;
use std::collections::{BTreeMap, HashMap};
use std::io::{self};
use structopt::StructOpt;
use termion::raw::IntoRawMode;
use tokio::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Lay... | lines.push(Text::styled(
format!(" {}{}\n", frame, offset),
Style::default().modifier(Modifier::DIM),
));
}
}
lines.push(Text::raw("\n"));
}
terminal.draw(|mut f| {
let chunks = Layout::default()
... | } else { | random_line_split |
main.rs | use futures_util::future::Either;
use futures_util::stream::StreamExt;
use std::collections::{BTreeMap, HashMap};
use std::io::{self};
use structopt::StructOpt;
use termion::raw::IntoRawMode;
use tokio::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Lay... |
}
Either::Right(key) => {
let key = key?;
if let termion::event::Key::Char('q') = key {
break;
}
}
}
}
terminal.clear()?;
Ok(())
})
}
fn draw<B: ... | {
assert!(inframe.is_some());
stack.push_str(line.trim());
stack.push(';');
} | conditional_block |
main.rs | use futures_util::future::Either;
use futures_util::stream::StreamExt;
use std::collections::{BTreeMap, HashMap};
use std::io::{self};
use structopt::StructOpt;
use termion::raw::IntoRawMode;
use tokio::prelude::*;
use tui::backend::Backend;
use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Lay... | .direction(Direction::Vertical)
.margin(2)
.constraints([Constraint::Percentage(100)].as_ref())
.split(f.size());
Block::default()
.borders(Borders::ALL)
.title("Common thread fan-out points")
.title_style(Style::default().fg(Color::Ma... | {
let opt = Opt::from_args();
if termion::is_tty(&io::stdin().lock()) {
eprintln!("Don't type input to this program, that's silly.");
return Ok(());
}
let stdout = io::stdout().into_raw_mode()?;
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend... | identifier_body |
sql_utils.rs | //! Module for SQL Utility functions
use diesel::prelude::*;
use std::{
borrow::Cow,
fs::File,
io::BufReader,
path::Path,
};
use crate::error::IOErrorToError;
use super::archive::import::{
detect_archive_type,
import_ytdlr_json_archive,
ArchiveType,
ImportProgress,
};
/// All migrations from "libytdlr/migra... |
#[test]
fn test_input_unknown_archive() {
let string0 = "
youtube ____________
youtube ------------
youtube aaaaaaaaaaaa
soundcloud 0000000000
";
let (path, _tempdir) = write_file_with_content(string0, "unknown_ytdl");
let pgcounter = RwLock::new(Vec::<ImportProgress>::new());
let re... | {
return |imp| c.write().expect("write failed").push(imp);
} | identifier_body |
sql_utils.rs | //! Module for SQL Utility functions
use diesel::prelude::*;
use std::{
borrow::Cow,
fs::File,
io::BufReader,
path::Path,
};
use crate::error::IOErrorToError;
use super::archive::import::{
detect_archive_type,
import_ytdlr_json_archive,
ArchiveType,
ImportProgress,
};
/// All migrations from "libytdlr/migra... |
assert!(res.is_err());
let res = match res {
Ok(_) => panic!("Expected a Error value"),
Err(err) => err,
};
assert!(res
.to_string()
.contains("Unknown Archive type to migrate, maybe try importing"));
assert_eq!(0, pgcounter.read().expect("read failed").len());
}
#[test]
fn test_... | random_line_split | |
sql_utils.rs | //! Module for SQL Utility functions
use diesel::prelude::*;
use std::{
borrow::Cow,
fs::File,
io::BufReader,
path::Path,
};
use crate::error::IOErrorToError;
use super::archive::import::{
detect_archive_type,
import_ytdlr_json_archive,
ArchiveType,
ImportProgress,
};
/// All migrations from "libytdlr/migra... | ,
ArchiveType::JSON => {
debug!("Applying Migration from JSON to SQLite");
// handle case where the input path matches the changed path
if migrate_to_path == archive_path {
return Err(crate::Error::other(
"Migration cannot be done: Input path matches output path (setting extension to \".db\")",
... | {
return Err(crate::Error::other(
"Unknown Archive type to migrate, maybe try importing",
))
} | conditional_block |
sql_utils.rs | //! Module for SQL Utility functions
use diesel::prelude::*;
use std::{
borrow::Cow,
fs::File,
io::BufReader,
path::Path,
};
use crate::error::IOErrorToError;
use super::archive::import::{
detect_archive_type,
import_ytdlr_json_archive,
ArchiveType,
ImportProgress,
};
/// All migrations from "libytdlr/migra... | (c: &RwLock<Vec<ImportProgress>>) -> impl FnMut(ImportProgress) + '_ {
return |imp| c.write().expect("write failed").push(imp);
}
#[test]
fn test_input_unknown_archive() {
let string0 = "
youtube ____________
youtube ------------
youtube aaaaaaaaaaaa
soundcloud 0000000000
";
let (path, _... | callback_counter | identifier_name |
scheduler.rs | scheduler.stop_waiting(process)
}
}
#[derive(Copy, Clone)]
struct StackPointer(*mut u64);
#[export_name = "__lumen_builtin_spawn"]
pub extern "C" fn builtin_spawn(to: Term, msg: Term) -> Term |
#[export_name = "__lumen_builtin_yield"]
pub unsafe extern "C" fn process_yield() -> bool {
let s = <Scheduler as rt_core::Scheduler>::current();
// NOTE: We always set root=false here because the root
// process never invokes this function
s.process_yield(/* root= */ false)
}
#[naked]
#[inline(never... | {
unimplemented!()
} | identifier_body |
scheduler.rs | scheduler.stop_waiting(process)
}
}
#[derive(Copy, Clone)]
struct StackPointer(*mut u64);
#[export_name = "__lumen_builtin_spawn"]
pub extern "C" fn builtin_spawn(to: Term, msg: Term) -> Term {
unimplemented!()
}
#[export_name = "__lumen_builtin_yield"]
pub unsafe extern "C" fn process_yield() -> bool {
... | (&self, priority: Priority) -> usize {
self.run_queues.read().run_queue_len(priority)
}
/// Returns true if the given process is in the current scheduler's run queue
#[cfg(test)]
pub fn is_run_queued(&self, value: &Arc<Process>) -> bool {
self.run_queues.read().contains(value)
}
... | run_queue_len | identifier_name |
scheduler.rs | scheduler.stop_waiting(process)
}
}
#[derive(Copy, Clone)]
struct StackPointer(*mut u64);
#[export_name = "__lumen_builtin_spawn"]
pub extern "C" fn builtin_spawn(to: Term, msg: Term) -> Term {
unimplemented!()
}
#[export_name = "__lumen_builtin_yield"]
pub unsafe extern "C" fn process_yield() -> bool {
... |
Err(_) => {
panic!("invalid term kind: {}", kind);
}
}
ptr::null_mut()
}
/// Called when the current process has finished executing, and has
/// returned all the way to its entry function. This marks the process
/// as exiting (if it wasn't already), and then yields to the schedul... | {
unimplemented!("unhandled use of malloc for {:?}", tk);
} | conditional_block |
scheduler.rs | scheduler.stop_waiting(process)
}
}
#[derive(Copy, Clone)]
struct StackPointer(*mut u64);
#[export_name = "__lumen_builtin_spawn"]
pub extern "C" fn builtin_spawn(to: Term, msg: Term) -> Term {
unimplemented!()
}
#[export_name = "__lumen_builtin_yield"]
pub unsafe extern "C" fn process_yield() -> bool {
... | pub enum Run {
/// Run the process now
Now(Arc<Process>),
/// There was a process in the queue, but it needs to be delayed because it is `Priority::Low`
/// and hadn't been delayed enough yet. Ask the `RunQueue` again for another process.
/// -- https://github.com/erlang/otp/blob/fe2b1323a3866ed0a9... | }
}
/// What to run | random_line_split |
svh_visitor.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | SawGenerics,
SawFn,
SawTraitItem,
SawImplItem,
SawStructField,
SawVariant,
SawPath,
SawBlock,
SawPat,
SawLocal,
SawArm,
SawExpr(SawExprComponent<'a>),
SawStmt(SawStmtComponent),
}
/// SawExprComponent carries all of the information that we want
/// to include in the ... | SawTy, | random_line_split |
svh_visitor.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn visit_path(&mut self, path: &'tcx Path, _: ast::NodeId) {
debug!("visit_path: st={:?}", self.st);
SawPath.hash(self.st); visit::walk_path(self, path)
}
fn visit_block(&mut self, b: &'tcx Block) {
debug!("visit_block: st={:?}", self.st);
SawBlock.hash(self.st); visit::wa... | {
debug!("visit_struct_field: st={:?}", self.st);
SawStructField.hash(self.st); visit::walk_struct_field(self, s)
} | identifier_body |
svh_visitor.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&mut self, v: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
debug!("visit_variant: st={:?}", self.st);
SawVariant.hash(self.st);
// walk_variant does not call walk_generics, so do it here.
visit::walk_generics(self, g);
visit::walk_variant(self, v, g, item_id)
}
... | visit_variant | identifier_name |
config.rs | //! Configuration for the iroh CLI.
use std::{
collections::HashMap,
env, fmt,
path::{Path, PathBuf},
str::FromStr,
};
use anyhow::{anyhow, bail, Result};
use config::{Environment, File, Value};
use iroh_net::{
defaults::{default_eu_derp_region, default_na_derp_region},
derp::{DerpMap, DerpReg... | () -> Self {
Self {
// TODO(ramfox): this should probably just be a derp map
derp_regions: [default_na_derp_region(), default_eu_derp_region()].into(),
}
}
}
impl Config {
/// Make a config using a default, files, environment variables, and commandline flags.
///
... | default | identifier_name |
config.rs | //! Configuration for the iroh CLI.
use std::{
collections::HashMap,
env, fmt,
path::{Path, PathBuf},
str::FromStr,
};
use anyhow::{anyhow, bail, Result};
use config::{Environment, File, Value};
use iroh_net::{
defaults::{default_eu_derp_region, default_na_derp_region},
derp::{DerpMap, DerpReg... |
/// Get the path for this [`IrohPath`] by joining the name to a root directory.
pub fn with_root(self, root: impl AsRef<Path>) -> PathBuf {
let path = root.as_ref().join(self);
path
}
}
/// The configuration for the iroh cli.
#[derive(PartialEq, Eq, Debug, Deserialize, Serialize, Clone)]
... | {
let mut root = iroh_data_root()?;
if !root.is_absolute() {
root = std::env::current_dir()?.join(root);
}
Ok(self.with_root(root))
} | identifier_body |
config.rs | //! Configuration for the iroh CLI.
use std::{
collections::HashMap,
env, fmt,
path::{Path, PathBuf},
str::FromStr,
};
use anyhow::{anyhow, bail, Result};
use config::{Environment, File, Value};
use iroh_net::{
defaults::{default_eu_derp_region, default_na_derp_region},
derp::{DerpMap, DerpReg... | }
}
impl FromStr for IrohPaths {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
Ok(match s {
"keypair" => Self::Keypair,
"blobs.v0" => Self::BaoFlatStoreComplete,
"blobs-partial.v0" => Self::BaoFlatStorePartial,
_ => bail!("unknown fi... | IrohPaths::Keypair => "keypair",
IrohPaths::BaoFlatStoreComplete => "blobs.v0",
IrohPaths::BaoFlatStorePartial => "blobs-partial.v0",
} | random_line_split |
utils.rs | // Copyright (c) 2011 Jan Kokemüller
// Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// 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 wit... | >(
&self,
channel: usize,
iter: impl Iterator<Item = U>,
mut func: impl FnMut(&'a S, U),
) {
assert!(channel < self.channels);
for (v, u) in Iterator::zip(self.data.chunks_exact(self.channels), iter) {
func(&v[channel], u)
}
}
#[inline]
... | reach_sample_zipped<U | identifier_name |
utils.rs | // Copyright (c) 2011 Jan Kokemüller
// Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// 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 wit... | const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);
#[inline(always)]
fn as_f64_raw(self) -> f64 {
self as f64
}
}
impl Sample for i32 {
const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);
#[inline(always)]
fn as_f64_raw(self) -> f64 {
self as f64
}
}
/// An extension-trait to... | }
}
impl Sample for i16 { | random_line_split |
utils.rs | // Copyright (c) 2011 Jan Kokemüller
// Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// 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 wit... |
impl Sample for i16 {
const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);
#[inline(always)]
fn as_f64_raw(self) -> f64 {
self as f64
}
}
impl Sample for i32 {
const MAX_AMPLITUDE: f64 = -(Self::MIN as f64);
#[inline(always)]
fn as_f64_raw(self) -> f64 {
self as f64
}
}
//... | self
}
} | identifier_body |
mul_fixed.rs | Advice, Column, ConstraintSystem, Constraints, Error, Expression, Fixed, Selector,
VirtualCells,
},
poly::Rotation,
};
use lazy_static::lazy_static;
use pasta_curves::{arithmetic::CurveAffine, pallas};
pub mod base_field_elem;
pub mod full_width;
pub mod short;
lazy_static! {
static ref TWO_S... | config.running_sum_coords_gate(meta);
config
}
/// Check that each window in the running sum decomposition uses the correct y_p
/// and interpolated x_p.
///
/// This gate is used both in the mul_fixed::base_field_elem and mul_fixed::short
/// helpers, which decompose the scala... | }
| random_line_split |
mul_fixed.rs | Advice, Column, ConstraintSystem, Constraints, Error, Expression, Fixed, Selector,
VirtualCells,
},
poly::Rotation,
};
use lazy_static::lazy_static;
use pasta_curves::{arithmetic::CurveAffine, pallas};
pub mod base_field_elem;
pub mod full_width;
pub mod short;
lazy_static! {
static ref TWO_SC... | pl From<&EccScalarFixedShort> for ScalarFixed {
fn from(scalar_fixed: &EccScalarFixedShort) -> Self {
Self::Short(scalar_fixed.clone())
}
}
impl From<&EccBaseFieldElemFixed> for ScalarFixed {
fn from(base_field_elem: &EccBaseFieldElemFixed) -> Self {
Self::BaseFieldElem(base_field_elem.clon... | Self::FullWidth(scalar_fixed.clone())
}
}
im | identifier_body |
mul_fixed.rs | Advice, Column, ConstraintSystem, Constraints, Error, Expression, Fixed, Selector,
VirtualCells,
},
poly::Rotation,
};
use lazy_static::lazy_static;
use pasta_curves::{arithmetic::CurveAffine, pallas};
pub mod base_field_elem;
pub mod full_width;
pub mod short;
lazy_static! {
static ref TWO_SC... | ) -> Vec<Value<pallas::Scalar>> {
let running_sum_to_windows = |zs: Vec<AssignedCell<pallas::Base, pallas::Base>>| {
(0..(zs.len() - 1))
.map(|idx| {
let z_cur = zs[idx].value();
let z_next = zs[idx + 1].value();
let word = z... | s_field(&self | identifier_name |
terminal.rs | //! Provides a low-level terminal interface
use std::io;
use std::time::Duration;
use mortal::{self, PrepareConfig, PrepareState, TerminalReadGuard, TerminalWriteGuard};
use crate::sys;
pub use mortal::{CursorMode, Signal, SignalSet, Size};
/// Default `Terminal` interface
pub struct DefaultTerminal(mortal::Termina... | (&mut self) -> io::Result<()> {
self.move_to_first_column()
}
fn set_cursor_mode(&mut self, mode: CursorMode) -> io::Result<()> {
self.set_cursor_mode(mode)
}
fn write(&mut self, s: &str) -> io::Result<()> {
self.write_str(s)
}
fn flush(&mut self) -> io::Result<()> {
... | move_to_first_column | identifier_name |
terminal.rs | //! Provides a low-level terminal interface
use std::io;
use std::time::Duration;
use mortal::{self, PrepareConfig, PrepareState, TerminalReadGuard, TerminalWriteGuard};
use crate::sys;
pub use mortal::{CursorMode, Signal, SignalSet, Size};
/// Default `Terminal` interface
pub struct DefaultTerminal(mortal::Termina... |
fn move_left(&mut self, n: usize) -> io::Result<()> {
self.move_left(n)
}
fn move_right(&mut self, n: usize) -> io::Result<()> {
self.move_right(n)
}
fn move_to_first_column(&mut self) -> io::Result<()> {
self.move_to_first_column()
}
fn set_cursor_mode(&mut self, ... | {
self.move_down(n)
} | identifier_body |
terminal.rs | //! Provides a low-level terminal interface
use std::io;
use std::time::Duration;
use mortal::{self, PrepareConfig, PrepareState, TerminalReadGuard, TerminalWriteGuard};
use crate::sys;
pub use mortal::{CursorMode, Signal, SignalSet, Size};
/// Default `Terminal` interface
pub struct DefaultTerminal(mortal::Termina... |
/// Flushes any currently buffered output data.
///
/// `TerminalWriter` instances may not buffer data on all systems.
///
/// Data must be flushed when the `TerminalWriter` instance is dropped.
fn flush(&mut self) -> io::Result<()>;
}
impl DefaultTerminal {
/// Opens access to the termina... | ///
/// The terminal interface shall not automatically move the cursor to the next
/// line when `write` causes a character to be written to the final column.
fn write(&mut self, s: &str) -> io::Result<()>; | random_line_split |
test_expand.rs | use super::utils::check;
use hex_literal::hex;
#[test]
fn aes128_expand_key_test() {
use super::aes128::expand_key;
let keys = [0x00; 16];
check(
unsafe { &expand_key(&keys) },
&[
[0x0000000000000000, 0x0000000000000000],
[0x6263636362636363, 0x6263636362636363],
... | ],
);
let keys = hex!("6920e299a5202a6d656e636869746f2a");
check(
unsafe { &expand_key(&keys) },
&[
[0x6920e299a5202a6d, 0x656e636869746f2a],
[0xfa8807605fa82d0d, 0x3ac64e6553b2214f],
[0xcf75838d90ddae80, 0xaa1be0e5f9a9c1aa],
[0x180d2f... | random_line_split | |
test_expand.rs | use super::utils::check;
use hex_literal::hex;
#[test]
fn aes128_expand_key_test() {
use super::aes128::expand_key;
let keys = [0x00; 16];
check(
unsafe { &expand_key(&keys) },
&[
[0x0000000000000000, 0x0000000000000000],
[0x6263636362636363, 0x6263636362636363],
... | ],
);
let keys = [0xff; 24];
check(
unsafe { &expand_key(&keys) },
&[
[0xffffffffffffffff, 0xffffffffffffffff],
[0xffffffffffffffff, 0xe8e9e9e917161616],
[0xe8e9e9e917161616, 0xe8e9e9e917161616],
[0xadaeae19bab8b80f, 0x525151e6454747f0... | {
use super::aes192::expand_key;
let keys = [0x00; 24];
check(
unsafe { &expand_key(&keys) },
&[
[0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x6263636362636363],
[0x6263636362636363, 0x6263636362636363],
[0x9b9898c9f9fbfbaa,... | identifier_body |
test_expand.rs | use super::utils::check;
use hex_literal::hex;
#[test]
fn aes128_expand_key_test() {
use super::aes128::expand_key;
let keys = [0x00; 16];
check(
unsafe { &expand_key(&keys) },
&[
[0x0000000000000000, 0x0000000000000000],
[0x6263636362636363, 0x6263636362636363],
... | () {
use super::aes256::expand_key;
let keys = [0x00; 32];
check(
unsafe { &expand_key(&keys) },
&[
[0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000],
[0x6263636362636363, 0x6263636362636363],
[0xaafbfbfbaafbfb... | aes256_expand_key_test | identifier_name |
day11.rs | use std::{collections::HashSet, io::Write};
use itertools::Itertools;
use snafu::Snafu;
type Result<T> = std::result::Result<T, Error>;
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone)]
enum Item {
Chip(char),
Generator(char),
ChipAndGenerator,
}
impl std::str::FromStr for Item {
type Err = Er... |
}
impl std::fmt::Debug for Item {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Item::Chip(id) => write!(f, "{}M", id),
Item::Generator(id) => write!(f, "{}G", id),
Item::ChipAndGenerator => write!(f, "<>"),
}
}
}
#[deriv... | {
let s: Vec<char> = s.chars().collect();
if s.len() != 2 {
return Err(Error::ParseItem {
data: s[0].to_string(),
});
}
match s[1] {
'M' => Ok(Item::Chip(s[0])),
'G' => Ok(Item::Generator(s[0])),
_ => Err(Error:... | identifier_body |
day11.rs | use std::{collections::HashSet, io::Write};
use itertools::Itertools;
use snafu::Snafu;
type Result<T> = std::result::Result<T, Error>;
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone)]
enum Item {
Chip(char),
Generator(char),
ChipAndGenerator,
}
impl std::str::FromStr for Item {
type Err = Er... | (&self) -> usize {
self.floors
.iter()
.enumerate()
.map(|(i, f)| f.len() * (i + 1) * 10)
.sum::<usize>()
}
fn is_success(&self) -> bool {
for floor in &self.floors[..self.floors.len() - 1] {
if!floor.is_empty() {
return fa... | score | identifier_name |
day11.rs | use std::{collections::HashSet, io::Write};
use itertools::Itertools;
use snafu::Snafu;
type Result<T> = std::result::Result<T, Error>;
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone)]
enum Item {
Chip(char),
Generator(char),
ChipAndGenerator,
}
impl std::str::FromStr for Item {
type Err = Er... | for floor in &self.floors[..self.floors.len() - 1] {
if!floor.is_empty() {
return false;
}
}
true
}
fn get_neighbors(&self) -> Vec<State> {
let mut out = Vec::new();
// calculate valid floors that the elevator can move to
... | .map(|(i, f)| f.len() * (i + 1) * 10)
.sum::<usize>()
}
fn is_success(&self) -> bool { | random_line_split |
sink.rs | from(tmpfile_path.to_str().unwrap());
input_file_path.push_str("_input");
let input_file_path = PathBuf::from(input_file_path);
let input_file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&input_file_pat... | else {
unsafe {
libc::dup2(dev_null_fd, libc::STDERR_FILENO);
}
}
unsafe {
libc::close(dev_null_fd);
}
unsafe {
// Close the pipe ends used by our pa... | {
//unsafe {
// let fd = self.stderr_file.as_ref().unwrap().0.as_raw_fd();
// libc::dup2(fd, libc::STDERR_FILENO);
// libc::close(fd);
//}
} | conditional_block |
sink.rs | .create(true)
.truncate(true)
.open(&path)
.unwrap();
stderr_file = Some((file, path));
}
Ok(AflSink {
path,
args,
workdir,
input_channel,
input_file: (input_file, input_f... | write | identifier_name | |
sink.rs | child_pid {
-1 => return Err(anyhow!("Fork failed!")),
0 => {
/*
Child
Be aware that we are forking a potentially multithreaded application
here. Since fork() only copies the calling thread, the environment
might be... |
log::trace!("Child terminated, getting exit status"); | random_line_split | |
player.rs | use std::collections::HashMap;
use std::convert::TryInto;
use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};
use dbus::arg::RefArg;
use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
use dbus::blocking::BlockingSender;
use dbus::blocking::{Connection, Proxy};
use dbus:... | .map(|reply| {
reply
.get1()
.expect("GetNameOwner must have name as first member")
})
}
fn query_all_player_buses(c: &Connection) -> Result<Vec<String>, String> {
let list_names = Message::new_method_call(
"org.freedesktop.DBus",
"/",
... | c.send_with_reply_and_block(get_name_owner, Duration::from_millis(100))
.map_err(|e| e.to_string()) | random_line_split |
player.rs | use std::collections::HashMap;
use std::convert::TryInto;
use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};
use dbus::arg::RefArg;
use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
use dbus::blocking::BlockingSender;
use dbus::blocking::{Connection, Proxy};
use dbus:... |
fn parse_player_metadata<T: arg::RefArg>(
metadata_map: HashMap<String, T>,
) -> Result<Option<Metadata>, String> {
debug!("metadata_map = {:?}", metadata_map);
let file_path_encoded = match metadata_map.get("xesam:url") {
Some(url) => url
.as_str()
.ok_or("url metadata shou... | {
query_player_property::<String>(p, "PlaybackStatus").map(|v| parse_playback_status(&v))
} | identifier_body |
player.rs | use std::collections::HashMap;
use std::convert::TryInto;
use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};
use dbus::arg::RefArg;
use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
use dbus::blocking::BlockingSender;
use dbus::blocking::{Connection, Proxy};
use dbus:... | (&self) -> Duration {
self.position
}
}
fn query_player_property<T>(p: &ConnectionProxy, name: &str) -> Result<T, String>
where
for<'b> T: dbus::arg::Get<'b>,
{
p.get("org.mpris.MediaPlayer2.Player", name)
.map_err(|e| e.to_string())
}
pub fn query_player_position(p: &ConnectionProxy) -> Re... | position | identifier_name |
did.rs | #[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::string::ToString as _;
use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt::Debug;
use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use core::hash::Hash;
use core::hash::Hasher;
... |
// Replace prefix /.
[b'/', b'.'] => {
input = &input[..1];
}
// Replace prefix /../
[b'/', b'.', b'.', b'/',..] => {
input = &input[3..];
output.pop();
}
// Replace prefix /..
[b'/', b'.', b'.'] => {
input = &input... | {
input = &input[2..];
} | conditional_block |
did.rs | #[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::string::ToString as _;
use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt::Debug;
use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use core::hash::Hash;
use core::hash::Hasher;
... |
}
impl Display for DID {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_fmt(format_args!("{}", self.as_str()))
}
}
impl AsRef<str> for DID {
fn as_ref(&self) -> &str {
self.data.as_ref()
}
}
impl FromStr for DID {
type Err = Error;
fn from_str(string: &str) -> Result<Self, Self::Err> {... | {
f.write_fmt(format_args!("{:?}", self.as_str()))
} | identifier_body |
did.rs | #[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::string::ToString as _;
use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt::Debug;
use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use core::hash::Hash;
use core::hash::Hasher;
... | self.core.path(self.as_str())
}
/// Returns the [`DID`] method query, if any.
#[inline]
pub fn query(&self) -> Option<&str> {
self.core.query(self.as_str())
}
/// Returns the [`DID`] method fragment, if any.
#[inline]
pub fn fragment(&self) -> Option<&str> {
self.core.fragment(self.as_str(... | #[inline]
pub fn path(&self) -> &str { | random_line_split |
did.rs | #[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::string::ToString as _;
use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt::Debug;
use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use core::hash::Hash;
use core::hash::Hasher;
... | (path: &str) -> Cow<str> {
fn next_segment(input: impl AsRef<[u8]>) -> Option<usize> {
match input.as_ref() {
[b'/', input @..] => next_segment(input).map(|index| index + 1),
input => input.iter().position(|byte| *byte == b'/'),
}
}
let mut output: Path = Path::new();
let mu... | remove_dot_segments | identifier_name |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ... | (
entry: &Entry<V1_0>,
instance: &Instance<V1_0>,
window: &winit::Window,
physical_device: PhysicalDevice,
device: &Device<V1_0>,
) -> Result<(Swapchain, SwapchainKHR), vk::Result> {
let surface = create_surface(entry, instance, window).unwrap();
let surface_loader =
Surface::new(ent... | create_swapchain | identifier_name |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ... | let semaphore_create_info = vk::SemaphoreCreateInfo {
s_type: vk::StructureType::SemaphoreCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
};
device.create_semaphore(&semaphore_create_info, None)
}
unsafe extern "system" fn vulkan_debug_callback(
_: vk::DebugReportFla... | random_line_split | |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ... |
fn create_instance(entry: &Entry<V1_0>) -> Instance<V1_0> {
let app_name = CString::new("Niagara-rs").unwrap();
let raw_name = app_name.as_ptr();
let appinfo = vk::ApplicationInfo {
s_type: vk::StructureType::ApplicationInfo,
api_version: vk_make_version!(1, 0, 36),
p_application_n... | {
Entry::new().unwrap()
} | identifier_body |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
p... | (a: &mut Self, b: &mut Self, choice: Choice) {
// what TweetNacl originally does
// let mask: i64 =!(b - 1);
// TweetNacl translated to Choice language
// let mask: i64 =!(choice.unwrap_u8() as i64) - 1);
// `subtle` definition, which is equivalent
// let mask: i64 = -(ch... | conditional_swap | identifier_name |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
p... | assert!(bool::from(maybe_one.ct_eq(&FieldElement::ONE)));
assert_eq!(maybe_one, FieldElement::ONE);
}
#[test]
fn test_imaginary() {
let minus_one = -&FieldElement::ONE;
let i_squared = &FieldElement::I * &FieldElement::I;
assert_eq!(minus_one, i_squared);
}
... | assert_eq!(maybe_one.to_bytes(), FieldElement::ONE.to_bytes()); | random_line_split |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
p... |
}
sqrt
}
}
impl ConstantTimeEq for FieldElement {
fn ct_eq(&self, other: &Self) -> Choice {
let canonical_self = self.to_bytes();
let canonical_other = other.to_bytes();
canonical_self.ct_eq(&canonical_other)
}
}
impl PartialEq for FieldElement {
fn eq(&self,... | {
sqrt = &sqrt * self;
} | conditional_block |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
p... |
}
impl<'a, 'b> Mul<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
fn mul(self, other: &'b FieldElement) -> FieldElement {
// start with so-called "schoolbook multiplication"
// TODO: nicer way to do this with iterators?
let mut pre_product: [i64; 31] = Default::d... | {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x -= y;
}
} | identifier_body |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend... | } | random_line_split | |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend... |
}
}
}
/// This enum is used for delegating actions to higher level event loops.
enum DelegateEvent {
Quit,
SwitchToAlign,
SwitchToUnalign,
OpenDialog(CursiveCallback),
}
/// Converts an event to a delegation
fn delegate_action(action: Action) -> Option<DelegateEvent> {
match action {
... | {
sink.send(Box::new(|siv: &mut Cursive| {
siv.call_on_name("aligned", |view: &mut Aligned| {
view.process_action(&mut Dummy, otherwise);
})
.expect("Could not send new data to view");
}))
... | conditional_block |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend... | () -> cursive::theme::Theme {
use cursive::theme::{BaseColor::*, Color::*, PaletteColor::*};
let mut cursiv_theme = cursive::theme::load_default();
cursiv_theme.palette[Background] = Dark(Black);
cursiv_theme
}
/// Forwards `AlignedMessage`s from the alignment thread into callbacks for the cursive inst... | cursiv_theme | identifier_name |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a st... |
}
impl PushActiveSetEntry {
const BLOOM_FALSE_RATE: f64 = 0.1;
const BLOOM_MAX_BITS: usize = 1024 * 8 * 4;
fn get_nodes<'a>(
&'a self,
origin: &'a Pubkey,
// If true forces gossip push even if the node has pruned the origin.
mut should_force_push: impl FnMut(&Pubkey) -> bo... | {
&self.0[get_stake_bucket(stake)]
} | identifier_body |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a st... | (
&self,
node: &Pubkey, // Gossip node.
origin: &Pubkey, // CRDS value owner
) {
if let Some(bloom_filter) = self.0.get(node) {
bloom_filter.add(origin);
}
}
fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of no... | prune | identifier_name |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a st... | #[test]
fn test_push_active_set_entry() {
const NUM_BLOOM_FILTER_ITEMS: usize = 100;
let mut rng = ChaChaRng::from_seed([147u8; 32]);
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let weights: Vec<_> = repeat_with(|| rng.gen_range(1..1000)).take(20).coll... | random_line_split | |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a st... | else {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&key| key!= origin)));
}
}
// Assert that each filter already prunes the key.
fo... | {
assert!(entry.get_nodes(origin, |_| false).eq(keys));
} | conditional_block |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use ser... | start_freq,
end_freq,
start_force,
end_force,
start_force.norm(),
)
}
/// This function validates the geometry of the world. The function should be called, because it
/// guarantees overflows later on in the simulation.
///
/// # ... | {
println!("Geometry:");
println!(
"\tWorld size: ({}, {}, {})",
self.size.x, self.size.y, self.size.z
);
for (i, bbox) in self.objects.iter().enumerate() {
println!("\t{}: {}", i, bbox);
}
println!("{}", self.simulation_config);
... | identifier_body |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use ser... | (&self, i: usize, frequency: f32) -> Vector3<f32> {
// Progress bar
let bbox = &self.objects[i].bbox();
let dx = bbox.x1 - bbox.x0 + 4;
let dy = bbox.y1 - bbox.y0 + 4;
let dz = bbox.z1 - bbox.z0 + 4;
let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len())... | force_on_for_freq | identifier_name |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use ser... | // Check for intersection with other objects
for (j, bbox_2) in expanded_boxes.iter().enumerate() {
if i < j && bbox_1.intersects(&bbox_2) {
return Err(WorldError::ShapesIntersect {
index_1: i,
index_2: j,
... | random_line_split | |
algorithm.rs | #![allow(unknown_lints)]
#![warn(clippy::all)]
extern crate ndarray;
extern crate petgraph;
extern crate rand;
extern crate sprs;
use crate::protocol_traits::graph::{Graph, GraphObject, Id, Metadata};
use crate::protocol_traits::ledger::LedgerView;
use crate::types::walk::{RandomWalk, RandomWalks, SeedSet};
use crate... | ledger_view: &L,
) -> Osrank
where
L: LedgerView,
G: Graph,
<G::Node as GraphObject>::Id: Eq + Clone + Hash,
{
let total_walks = random_walks.len();
let node_visits = random_walks.count_visits(&node_id);
Fraction::from(1.0 - ledger_view.get_damping_factors().project)
* Osrank::new(no... | node_id: Id<G::Node>, | random_line_split |
algorithm.rs | #![allow(unknown_lints)]
#![warn(clippy::all)]
extern crate ndarray;
extern crate petgraph;
extern crate rand;
extern crate sprs;
use crate::protocol_traits::graph::{Graph, GraphObject, Id, Metadata};
use crate::protocol_traits::ledger::LedgerView;
use crate::types::walk::{RandomWalk, RandomWalks, SeedSet};
use crate... | <G, I>
where
I: Eq + Hash,
{
network_view: G,
pub walks: RandomWalks<I>,
}
fn walks<'a, L, G: 'a, RNG>(
starting_nodes: impl Iterator<Item = &'a Id<G::Node>>,
network: &G,
ledger_view: &L,
mut rng: RNG,
get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64,
) -> RandomWalks<Id... | WalkResult | identifier_name |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedF... | {
ExternModule::new(
vm,
record!{
resume => primitive::<fn(&'vm Thread) -> Result<(), String>>("std.thread.prim.resume", resume),
(yield_ "yield") => primitive::<fn(())>("std.thread.prim.yield", yield_),
spawn => primitive!(1 std::thread::prim::spawn),
... | identifier_body | |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedF... | thread: RootedThread,
action: WithVM<'vm, FunctionRef<Action>>,
) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> {
struct SpawnFuture<F>(Mutex<Option<F>>);
impl<F> fmt::Debug for SpawnFuture<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Future")
}
... |
#[cfg(not(target_arch = "wasm32"))]
fn spawn_on<'vm>( | random_line_split |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedF... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Traverseable for Sender<T> {
fn traverse(&self, _gc: &mut Gc) {
// No need to traverse in Sender as values can only be accessed through Receiver
}
}
impl<T> Sender<T> {
fn send(&... | fmt | identifier_name |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {... | poll: poll,
socket: None,
};
let mut events = Events::with_capacity(1024);
info!("Starting GDB stub on port 4567...");
let mut last_halt = BreakData::new(BreakReason::Trapped, &mut debugger.ctx(Arm9));
't: loop {
... | let mut connection = Connection {
listener: &listener, | random_line_split |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {... | <'a, 'b: 'a> {
dbg: &'a mut dbgcore::DbgContext<'b>,
last_halt: &'a mut BreakData,
}
const TOKEN_LISTENER: mio::Token = mio::Token(1024);
const TOKEN_CLIENT: mio::Token = mio::Token(1025);
pub struct GdbStub {
debugger: dbgcore::DbgCore,
gdb_thread: Option<thread::JoinHandle<msgs::Client<Message>>>
}
... | GdbCtx | identifier_name |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {... |
}
fn handle_gdb_cmd_q(cmd: &str, _ctx: &mut GdbCtx) -> Result<String> {
let mut s = cmd.splitn(2, ':');
let ty = parse_next(&mut s)?;
let mut out = String::new();
match ty {
"fThreadInfo" => out += "m0000000000000001",
"sThreadInfo" => out += "l",
"C" => out += "QC0000000000000... | {
let reason_str = match self.reason {
BreakReason::Breakpoint => format!(";{}:", "swbreak"),
_ => String::new(),
};
format!("T05{:02X}:{:08X};{:02X}:{:08X}{};", 15, self.r15.swap_bytes(),
13, self.r13.swap_bytes(),
... | identifier_body |
spinning_square.rs | // Copyright 2018 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::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
... |
Ok(())
}
}
fn make_app_assistant_fut(
app_sender: &AppSender,
) -> LocalBoxFuture<'_, Result<AppAssistantPtr, Error>> {
let f = async move {
let assistant = Box::new(SpinningSquareAppAssistant::new(app_sender.clone()));
Ok::<AppAssistantPtr, Error>(assistant)
};
Box::pin(f)... | {
if keyboard_event.phase == input::keyboard::Phase::Pressed
|| keyboard_event.phase == input::keyboard::Phase::Repeat
{
match code_point {
SPACE => self.toggle_rounded(),
B => self.move_backward(),
F => ... | conditional_block |
spinning_square.rs | // Copyright 2018 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::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
... | }
#[derive(Debug)]
pub struct ToggleRoundedMessage {}
#[derive(Debug)]
pub struct ToggleDirectionMessage {}
struct SpinningSquareFacet {
direction: Direction,
square_color: Color,
rounded: bool,
start: Time,
square_path: Option<Path>,
size: Size,
}
impl SpinningSquareFacet {
fn new(squar... | match self {
Self::Clockwise => Self::CounterClockwise,
Self::CounterClockwise => Self::Clockwise,
}
} | random_line_split |
spinning_square.rs | // Copyright 2018 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::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
... | (&mut self, new_size: &Size) -> Result<(), Error> {
self.scene_details = None;
self.ensure_scene_built(*new_size);
Ok(())
}
fn get_scene(&mut self, size: Size) -> Option<&mut Scene> {
self.ensure_scene_built(size);
Some(&mut self.scene_details.as_mut().unwrap().scene)
... | resize | identifier_name |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// B... | (&self) -> Package {
if let Some(ref package) = self.package {
Package::Package(package.clone())
} else {
Package::Default
}
}
// valid target: --example, --bin, --bench
fn get_target(&self) -> Target {
if let Some(ref example) = self.example {
... | get_package | identifier_name |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// B... |
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Package::Default => {
write!(f, "Default: search all packages for example/bin/bench")
}
Package::Package(s) => write!(f, "{}", s),
}
}
}
im... | {
match p {
Package::Default => Packages::Default,
Package::Package(s) => Packages::Packages(vec![s]),
}
} | identifier_body |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// B... |
#[derive(Debug, StructOpt)]
#[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)]
pub(crate) struct AppConfig {
/// List available templates
#[structopt(short = "l", long)]
pub(crate) list_templates: bool,
/// Specify the instruments template to run
///
/// To see available temp... | )]
Instruments(AppConfig),
} | random_line_split |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::ch... |
command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?;
capabilities::reset_effective(command)?;
if let Some(caps) = &proc.capabilities {
capabilities::drop_privileges(caps, command)?;
}
// Take care of LISTEN_FDS used for systemd-active-socket. If the value is
//... | {
rootfs::prepare_rootfs(
spec,
rootfs,
namespaces
.clone_flags
.contains(sched::CloneFlags::CLONE_NEWUSER),
)
.with_context(|| "Failed to prepare rootfs")?;
// change the root of filesystem of the process to the rootfs... | conditional_block |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::ch... | "LISTEN_FDS entered is malformed: {:?}. Ignore the value.",
&value
);
args.preserve_fds
}
};
// clean up and handle perserved fds.
cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?;
// notify parents ... | log::warn!( | random_line_split |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::ch... | () -> Result<()> {
// Open a fd without the CLOEXEC flag. Rust automatically adds the flag,
// so we use fcntl::open here for more control.
let fd = fcntl::open("/dev/null", fcntl::OFlag::O_RDWR, sys::stat::Mode::empty())?;
cleanup_file_descriptors(fd - 1).with_context(|| "Failed to clea... | test_cleanup_file_descriptors | identifier_name |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::ch... | })
.collect();
Ok(fds)
}
// Cleanup any extra file descriptors, so the new container process will not
// leak a file descriptor from before execve gets executed. The first 3 fd will
// stay open: stdio, stdout, and stderr. We would further preserve the next
// "preserve_fds" number of fds. Set the... | {
const PROCFS_FD_PATH: &str = "/proc/self/fd";
ensure_procfs(Path::new(PROCFS_FD_PATH))
.with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?;
let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)?
.filter_map(|entry| match entry {
Ok(entry) => Some(entry.path())... | identifier_body |
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
l... | identifier_name | ||
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
l... | for (i, v) in v.iter().enumerate() {
println!("{} is at index {}", v, i);
}
// a is at index 0
// a is at index 1
// a is at index 2
}
//
実はいつもつかうlet文もパターンの考え方を使っている
pub fn let_statement_uses_pattern() {
// let PATTERN = EXPRESSION;
// ここでマッチしたものを変数_xに束縛することを意味するパターン
// なんでもいいよ... | _as_long_as_vector_has_values() {
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top) = stack.pop() {
println!("vector has {} on the top", top);
}
// vector has 3 on the top
// vector has 2 on the top
// vector has 1 on the top
}
// ... | identifier_body |
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
l... | Message::Quit,
Message::Move { x: 3, y: 4 },
Message::Write("Hello!".to_string()),
Message::ChangeColor(Color::Rgb(0, 255, 128)),
Message::ChangeColor(Color::Hsv(0, 0, 0)),
];
for msg in msgs.iter() {
match msg {
Message::Quit => {
pri... | let msgs = vec![ | random_line_split |
tools.rs | //! Download management for external tools and applications. Locate and automatically download
//! applications (if needed) to use them in the build pipeline.
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, ensure, Context, Result};
use async_compression::tokio::bufread::GzipDecoder;
use directories_next::... | .nth(1)
.with_context(|| format!("missing or malformed version output: {}", text))?
.to_owned(),
Application::WasmOpt => format!(
"version_{}",
text.split(' ')
.nth(2)
.with_context(|| format!(... | let text = text.trim();
let formatted_version = match self {
Application::WasmBindgen => text
.split(' ') | random_line_split |
tools.rs | //! Download management for external tools and applications. Locate and automatically download
//! applications (if needed) to use them in the build pipeline.
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, ensure, Context, Result};
use async_compression::tokio::bufread::GzipDecoder;
use directories_next::... | (&self, version: &str) -> Result<String> {
Ok(match self {
Self::WasmBindgen => format!(
"https://github.com/rustwasm/wasm-bindgen/releases/download/{version}/wasm-bindgen-{version}-x86_64-{target}.tar.gz",
version = version,
target = self.target()?
... | url | identifier_name |
tools.rs | //! Download management for external tools and applications. Locate and automatically download
//! applications (if needed) to use them in the build pipeline.
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, ensure, Context, Result};
use async_compression::tokio::bufread::GzipDecoder;
use directories_next::... |
/// Path of the executable within the downloaded archive.
fn path(&self) -> &str {
if cfg!(windows) {
match self {
Self::WasmBindgen => "wasm-bindgen.exe",
Self::WasmOpt => "bin/wasm-opt.exe",
}
} else {
match self {
... | {
match self {
Self::WasmBindgen => "wasm-bindgen",
Self::WasmOpt => "wasm-opt",
}
} | identifier_body |
mod.rs | //! This module handles connections to Content Manager Server
//! First you connect into the ip using a tcp socket
//! Then reads/writes into it
//!
//! Packets are sent at the following format: packet_len + packet_magic + data
//! packet length: u32
//! packet magic: VT01
//!
//! Apparently, bytes received are in litt... |
_ => {
unimplemented!()
}
};
}
Ok(())
}
}
#[cfg(not(feature = "websockets"))]
#[async_trait]
impl Connection<TcpStream> for SteamConnection<TcpStream> {
/// Opens a tcp stream to specified IP
async fn new_connection(ip_addr: ... | {
handle_encryption_negotiation(sender.clone(), connection_state, packet_message).unwrap();
} | conditional_block |
mod.rs | //! This module handles connections to Content Manager Server
//! First you connect into the ip using a tcp socket
//! Then reads/writes into it
//!
//! Packets are sent at the following format: packet_len + packet_magic + data
//! packet length: u32
//! packet magic: VT01
//!
//! Apparently, bytes received are in litt... | (mut self) -> Result<(), ConnectionError> {
let (sender, mut receiver): (UnboundedSender<DynBytes>, UnboundedReceiver<DynBytes>) =
mpsc::unbounded_channel();
let connection_state = &mut self.state;
let (stream_rx, stream_tx) = self.stream.into_split();
let mut framed_read =... | main_loop | identifier_name |
mod.rs | //! This module handles connections to Content Manager Server
//! First you connect into the ip using a tcp socket
//! Then reads/writes into it
//!
//! Packets are sent at the following format: packet_len + packet_magic + data
//! packet length: u32
//! packet magic: VT01
//!
//! Apparently, bytes received are in litt... | #[inline]
async fn write_packets(&mut self, data: &[u8]) -> Result<(), Box<dyn Error>> {
let mut output_buffer = BytesMut::with_capacity(1024);
trace!("payload size: {} ", data.len());
output_buffer.extend_from_slice(&(data.len() as u32).to_le_bytes());
output_buffer.extend_fro... | }
| random_line_split |
mod.rs | //! This module handles connections to Content Manager Server
//! First you connect into the ip using a tcp socket
//! Then reads/writes into it
//!
//! Packets are sent at the following format: packet_len + packet_magic + data
//! packet length: u32
//! packet magic: VT01
//!
//! Apparently, bytes received are in litt... | match packet_message.emsg() {
EMsg::ChannelEncryptRequest | EMsg::ChannelEncryptResponse | EMsg::ChannelEncryptResult => {
handle_encryption_negotiation(sender.clone(), connection_state, packet_message).unwrap();
}
_ => {
... | {
let (sender, mut receiver): (UnboundedSender<DynBytes>, UnboundedReceiver<DynBytes>) =
mpsc::unbounded_channel();
let connection_state = &mut self.state;
let (stream_rx, stream_tx) = self.stream.into_split();
let mut framed_read = FramedRead::new(stream_rx, PacketMessageC... | identifier_body |
lib.rs | // The MIT License (MIT)
// Copyright (c) 2018 Matrix.Zhang <113445886@qq.com>
// 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... | z_id: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct DayuQueryDetail {
pub phone_num: String,
pub send_date: String,
pub send_status: u8,
pub receive_date: String,
pub template_code: String,
pub content: String,
pub err_code: String,
}
... | se {
pub bi | identifier_name |
lib.rs | // The MIT License (MIT)
// Copyright (c) 2018 Matrix.Zhang <113445886@qq.com>
// 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... | #[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct DayuFailResponse {
pub code: String,
pub message: String,
pub request_id: String,
}
impl Display for DayuFailResponse {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", serde_json:... | random_line_split | |
lib.rs | // The MIT License (MIT)
// Copyright (c) 2018 Matrix.Zhang <113445886@qq.com>
// 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... | }
}
| page_size > MAX_PAGE_SIZE {
return Err(DayuError::PageTooLarge(page_size));
}
let send_date = send_date.format("%Y%m%d").to_string();
let page_size = page_size.to_string();
let current_page = current_page.to_string();
do_request!(
self,
... | identifier_body |
lib.rs | // The MIT License (MIT)
// Copyright (c) 2018 Matrix.Zhang <113445886@qq.com>
// 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... | u.sign_name.is_empty() {
return Err(DayuError::ConfigAbsence("sign_name"));
}
let timestamp = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
TextNonce::sized(32)
.map_err(DayuError::TextNonce)
.map(|v| v.to_string())
.and_then(|text_nonce| {
let mut... | urn Err(DayuError::ConfigAbsence("access_secret"));
}
if day | conditional_block |
main.rs | #![allow(dead_code)]
#![allow(unused_variables)]
use std::collections::{HashMap, HashSet};
use std::io::stdin;
use std::mem;
mod pm;
// const MEANING_OF_LIFE: u16 = 456; // no fixed address
fn main() {
// primitive_types ();
// operators();
// scope_and_shadowing();
// println!("const MEANING_OF_L... | () {
let a = 123;
println!("a = {}", a);
let a = 777;
println!("a = {}", a);
{
let a = 888;
let b = 456;
println!("a = {}, b = {}", a, b);
}
}
fn operators() {
//arithmetic operators
let mut a = 2 + 3 * 4;
println!("{}", a);
a += 1;
a -= 2;
pr... | scope_and_shadowing | identifier_name |
main.rs | #![allow(dead_code)]
#![allow(unused_variables)]
use std::collections::{HashMap, HashSet};
use std::io::stdin;
use std::mem;
mod pm;
// const MEANING_OF_LIFE: u16 = 456; // no fixed address
fn main() {
// primitive_types ();
// operators();
// scope_and_shadowing();
// println!("const MEANING_OF_L... | Color::Cmyk { cyan: a, magenta: b, yellow: c, black: d } => println!("cmyk({},{},{},{})", a, b,
c, d),
}
}
fn structures() {
struct Point {
x: f64,
y: f64,
}
let p = Point { x: 34.5, y: 4.0 };
prin... | {
enum Color {
Red,
Green,
Blue,
RgbColor(u8, u8, u8),
//tuple
Cmyk { cyan: u8, magenta: u8, yellow: u8, black: u8 }, //struct
}
let c: Color = Color::Cmyk { cyan: 0, magenta: 128, yellow: 0, black: 0 };
match c {
Color::Red => println!("r"),
... | identifier_body |
main.rs | #![allow(dead_code)]
#![allow(unused_variables)]
use std::collections::{HashMap, HashSet};
use std::io::stdin;
use std::mem;
mod pm;
// const MEANING_OF_LIFE: u16 = 456; // no fixed address
fn main() {
// primitive_types ();
// operators();
// scope_and_shadowing();
// println!("const MEANING_OF_L... | for (key, value) in &shapes {
println!("key: {}, value: {}", key, value);
}
shapes.entry("circle".into()).or_insert(1);
{
let actual = shapes.entry("circle".into()).or_insert(2);
*actual = 0;
}
println!("{:?}", shapes);
let _1_5: HashSet<_> = (1..=5).collect();
... | println!("a square has {} sides", shapes["square"]);
shapes.insert("square".into(), 5);
println!("{:?}", shapes);
| random_line_split |
main.rs | #![allow(dead_code)]
#![allow(unused_variables)]
use std::collections::{HashMap, HashSet};
use std::io::stdin;
use std::mem;
mod pm;
// const MEANING_OF_LIFE: u16 = 456; // no fixed address
fn main() {
// primitive_types ();
// operators();
// scope_and_shadowing();
// println!("const MEANING_OF_L... |
}
}
}
fn unions() {
let mut iof = IntOrFloat { i: 123 };
iof.i = 234;
let value = unsafe { iof.i };
println!("iof.i = {}", value);
process_value(IntOrFloat { i: 5 })
}
fn enums() {
enum Color {
Red,
Green,
Blue,
RgbColor(u8, u8, u8),
//tup... | {
println!("value = {}", f)
} | conditional_block |
main.rs | use std::{env, io, fmt};
use std::time::{Duration, SystemTime};
use std::error::Error;
use std::collections::HashMap;
use tokio::sync;
use tokio::net::UdpSocket;
use log::{debug, info, warn};
use futures::select;
use futures::future::FutureExt;
// Delta between NTP epoch (1900-01-01 00:00:00) and Unix epoch (1970-01-... |
#[cfg(test)]
mod tests {
use crate::timetag_to_unix;
#[test]
fn time_tag_to_unix_1() {
// 2^32 / 2 fractional seconds, i.e. 500,000μs
assert_eq!(timetag_to_unix(3_608_146_800, 2_147_483_648), (1_399_158_000, 500_000));
}
#[test]
fn time_tag_to_unix_2() {
assert_eq!(tim... |
let addr = env::args().nth(1).unwrap_or_else(|| "127.0.0.1:4560".to_string());
Server::new(&addr).await?.run().await
} | random_line_split |
main.rs | use std::{env, io, fmt};
use std::time::{Duration, SystemTime};
use std::error::Error;
use std::collections::HashMap;
use tokio::sync;
use tokio::net::UdpSocket;
use log::{debug, info, warn};
use futures::select;
use futures::future::FutureExt;
// Delta between NTP epoch (1900-01-01 00:00:00) and Unix epoch (1970-01-... | (&mut self) -> Result<&[u8], io::Error> {
let (size, _) = self.socket.recv_from(&mut self.buf).await?;
Ok(&self.buf[..size])
}
/// Handles /flush messages.
fn handle_msg_flush(&mut self, msg: &rosc::OscMessage) {
match msg.args.first() {
Some(rosc::OscType::String(tag)) ... | recv_udp_packet | identifier_name |
main.rs | use std::{env, io, fmt};
use std::time::{Duration, SystemTime};
use std::error::Error;
use std::collections::HashMap;
use tokio::sync;
use tokio::net::UdpSocket;
use log::{debug, info, warn};
use futures::select;
use futures::future::FutureExt;
// Delta between NTP epoch (1900-01-01 00:00:00) and Unix epoch (1970-01-... |
}
impl Error for ServerError {}
impl From<io::Error> for ServerError {
fn from(err: io::Error) -> Self {
Self::Io(err)
}
}
impl From<rosc::OscError> for ServerError {
fn from(err: rosc::OscError) -> Self {
Self::Osc(err)
}
}
#[tokio::main]
async fn main() -> Result<(), io::Error> {... | {
match self {
Self::Io(err) => write!(f, "IO error: {}", err),
Self::Osc(err) => write!(f, "Failed to decode OSC packet: {:?}", err),
Self::Protocol(err) => write!(f, "{}", err),
}
} | identifier_body |
lz4.rs | }
if self.cur == self.input.len() { break }
// Read off the next i16 offset
{
let back = (self.bump() as usize) | ((self.bump() as usize) << 8);
debug!("found back {}", back);
self.start = self.end - back;
}
... | // FIXME: find out why slicing syntax fails tests
//self.output[self.dest_pos as usize.. (self.dest_pos + len) as usize] = self.input[pos as uint.. (pos + len) as uint];
for i in 0..(len as usize) {
self.output[self.dest_pos as usize + i] = self.input[pos as usize + i];
}
... | ln -= RUN_MASK;
while ln > 254 {
self.output[self.dest_pos as usize] = 255;
self.dest_pos += 1;
ln -= 255;
}
self.output[self.dest_pos as usize] = ln as u8;
self.dest_pos += 1;
}
| conditional_block |
lz4.rs | }
if self.cur == self.input.len() { break }
// Read off the next i16 offset
{
let back = (self.bump() as usize) | ((self.bump() as usize) << 8);
debug!("found back {}", back);
self.start = self.end - back;
}
... | > {
w: W,
buf: Vec<u8>,
tmp: Vec<u8>,
wrote_header: bool,
limit: usize,
}
impl<W: Write> Encoder<W> {
/// Creates a new encoder which will have its output written to the given
/// output stream. The output stream can be re-acquired by calling
/// `finish()`
///
/// NOTE: compres... | coder<W | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.