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 |
|---|---|---|---|---|
source_contributions.rs | extern crate clap;
extern crate csv;
extern crate reqwest;
extern crate serde;
extern crate failure;
#[macro_use]
extern crate failure_derive;
use clap::{App, Arg};
use csv::StringRecord;
use reqwest::{Client, Url};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use std::{thread, time};
use std::collection... | match repo_url.split('/').collect::<Vec<&str>>().as_slice() {
[_, "", "github.com", owner, repo] => Ok((owner, repo)),
_ => Err(AppError::MetadataExtractionFailed {
repo_url: repo_url.to_string(),
}),
}
}
// Extract the contribution relative to this project. For now only Git... | fn extract_github_owner_and_repo(repo_url: &str) -> Result<(&str, &str), AppError> { | random_line_split |
lib.rs | /*!
This crate implements various macros detailed in [The Little Book of Rust Macros](https://danielkeep.github.io/tlborm/).
If you use selective macro importing, you should make sure to *always* use the `tlborm_util` macro, as most macros in this crate depend on it being present.
*/
/**
Forces the parser to interpre... |
This is typically used to replace elements of an arbitrary token sequence with some fixed expression.
See [TLBoRM: Repetition replacement](https://danielkeep.github.io/tlborm/book/pat-repetition-replacement.html).
## Examples
```rust
# #[macro_use(replace_expr, tlborm_util)] extern crate tlborm;
# fn main() {
macro... | /**
Utility macro that takes a token tree and an expression, expanding to the expression. | random_line_split |
mod.rs | use game::PieceType::BLACK;
use game::PieceType::WHITE;
use game::players::ai::IdiotAi;
use self::board::Board;
use self::coord::CoordinationFlat;
use self::players::LocalHumanPlayer;
use self::players::Player;
use std::char;
use std::fmt;
mod board;
mod players;
mod coord {
use std::fmt;
/// Define coordina... | (&self) -> board::BoardPieceType {
match self {
PieceType::BLACK => board::BoardPieceType::BLACK,
PieceType::WHITE => board::BoardPieceType::WHITE,
}
}
}
impl fmt::Display for PieceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self... | to_board_piece_type | identifier_name |
mod.rs | use game::PieceType::BLACK;
use game::PieceType::WHITE;
use game::players::ai::IdiotAi;
use self::board::Board;
use self::coord::CoordinationFlat;
use self::players::LocalHumanPlayer;
use self::players::Player;
use std::char;
use std::fmt;
mod board;
mod players;
mod coord {
use std::fmt;
/// Define coordina... | self
}
/// Set the second player (Uses black piece)
pub fn set_second_player(&mut self, player_type: GameBuilderPlayerType) -> &mut Self {
self.second_player = player_type;
self
}
pub fn build(&self) -> Game {
Game::new(
GameBuilder::create_player(self.f... | pub fn set_first_player(&mut self, player_type: GameBuilderPlayerType) -> &mut Self {
self.first_player = player_type; | random_line_split |
mod.rs | use game::PieceType::BLACK;
use game::PieceType::WHITE;
use game::players::ai::IdiotAi;
use self::board::Board;
use self::coord::CoordinationFlat;
use self::players::LocalHumanPlayer;
use self::players::Player;
use std::char;
use std::fmt;
mod board;
mod players;
mod coord {
use std::fmt;
/// Define coordina... |
}
if score >= 5 {
return true;
}
}
false
}
}
| {
let mut a = self.board.get(next_coord.unwrap());
while next_coord.is_ok() && a.is_ok() && a.unwrap() == last_player_color {
score += 1;
next_coord = move_dir_reverse(&next_coord.unwrap(), dir);
a = self.boa... | conditional_block |
mod.rs | use game::PieceType::BLACK;
use game::PieceType::WHITE;
use game::players::ai::IdiotAi;
use self::board::Board;
use self::coord::CoordinationFlat;
use self::players::LocalHumanPlayer;
use self::players::Player;
use std::char;
use std::fmt;
mod board;
mod players;
mod coord {
use std::fmt;
/// Define coordina... |
/// Get the current player
fn get_current_player(&self) -> &Box<Player> {
&self.players[self.current_player]
}
/// Get the current player mutable reference
fn get_current_player_mut(&mut self) -> &mut Box<Player> {
&mut self.players[self.current_player]
}
/// Check the ga... | {
if self.current_player == 0 {
&mut self.players[1]
} else {
&mut self.players[0]
}
} | identifier_body |
lib.rs | use chrono::{DateTime, NaiveDateTime, Utc};
use gexiv2_sys;
use gpx::read;
use gpx::TrackSegment;
use gpx::{Gpx, Track};
use log::*;
use regex::Regex;
use reqwest::Url;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error;
use std::fs;
use std::fs::File;
use std::io;
use std::io::pr... | (dir: &Path) -> Vec<Photo> {
let mut photos: Vec<Photo> = Vec::new();
unsafe {
gexiv2_sys::gexiv2_log_set_level(gexiv2_sys::GExiv2LogLevel::MUTE);
}
for entry in fs::read_dir(dir).unwrap() {
let img_path = entry.unwrap().path();
let file_metadata = rexiv2::Metadata::new_from_pa... | parse_photos | identifier_name |
lib.rs | use chrono::{DateTime, NaiveDateTime, Utc};
use gexiv2_sys;
use gpx::read;
use gpx::TrackSegment;
use gpx::{Gpx, Track};
use log::*;
use regex::Regex;
use reqwest::Url;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error;
use std::fs;
use std::fs::File;
use std::io;
use std::io::pr... |
None
}
pub fn parse_photos(dir: &Path) -> Vec<Photo> {
let mut photos: Vec<Photo> = Vec::new();
unsafe {
gexiv2_sys::gexiv2_log_set_level(gexiv2_sys::GExiv2LogLevel::MUTE);
}
for entry in fs::read_dir(dir).unwrap() {
let img_path = entry.unwrap().path();
let file_metadat... | {
res.sort_unstable_by_key(|r| r.datetime.timestamp());
return Some(res);
} | conditional_block |
lib.rs | use chrono::{DateTime, NaiveDateTime, Utc};
use gexiv2_sys;
use gpx::read;
use gpx::TrackSegment;
use gpx::{Gpx, Track};
use log::*;
use regex::Regex;
use reqwest::Url; | use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use tera::{compile_templates, Context, Tera};
#[derive(Serialize, Deserialize)]
pub struct Coordinate {
lon: f64,
lat: f64,
}
pub struct Photo {
path: PathBuf,
datetime: Naive... | use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error;
use std::fs;
use std::fs::File; | random_line_split |
stateless.rs | /// PROJECT: Stateless Blockchain Experiment.
///
/// DESCRIPTION: This repository implements a UTXO-based stateless blockchain on Substrate using an
/// RSA accumulator. In this scheme, validators only need to track a single accumulator value and
/// users only need to store their own UTXOs and membership proofs. Unle... | {
input: UTXO,
output: UTXO,
witness: Vec<u8>,
// Would in practice include a signature here.
}
pub trait Trait: system::Trait {
type Event: From<Event> + Into<<Self as system::Trait>::Event>;
}
decl_storage! {
trait Store for Module<T: Trait> as Stateless {
State get(get_state): U204... | Transaction | identifier_name |
stateless.rs | /// PROJECT: Stateless Blockchain Experiment.
///
/// DESCRIPTION: This repository implements a UTXO-based stateless blockchain on Substrate using an
/// RSA accumulator. In this scheme, validators only need to track a single accumulator value and
/// users only need to store their own UTXOs and membership proofs. Unle... | /// The module declaration.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
// Initialize generic event
fn deposit_event() = default;
/// Receive request to execute a transaction.
/// Verify the contents of a transaction and temporarily add it to a queue of v... | decl_module! { | random_line_split |
stateless.rs | /// PROJECT: Stateless Blockchain Experiment.
///
/// DESCRIPTION: This repository implements a UTXO-based stateless blockchain on Substrate using an
/// RSA accumulator. In this scheme, validators only need to track a single accumulator value and
/// users only need to store their own UTXOs and membership proofs. Unle... |
#[test]
fn test_del() {
with_externalities(&mut new_test_ext(), || {
let elems = vec![U2048::from(3), U2048::from(5), U2048::from(7)];
// Collect witnesses for the added elements
let witnesses = witnesses::create_all_mem_wit(Stateless::get_state(), &elems);
... | {
with_externalities(&mut new_test_ext(), || {
let elems = vec![U2048::from(3), U2048::from(5), U2048::from(7)];
let (state, _, _) = accumulator::batch_add(Stateless::get_state(), &elems);
assert_eq!(state, U2048::from(5));
});
} | identifier_body |
mod.rs | mod base;
mod breakpoints;
mod desc;
mod monitor;
mod resume;
mod thread;
mod traits;
mod utils;
use super::arch::RuntimeArch;
use crate::{BreakpointCause, CoreStatus, Error, HaltReason, Session};
use gdbstub::stub::state_machine::GdbStubStateMachine;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::num::... | }
fn support_target_description_xml_override(
&mut self,
) -> Option<TargetDescriptionXmlOverrideOps<'_, Self>> {
Some(self)
}
fn support_breakpoints(&mut self) -> Option<BreakpointsOps<'_, Self>> {
Some(self)
}
fn support_memory_map(&mut self) -> Option<MemoryMapO... | type Arch = RuntimeArch;
type Error = Error;
fn base_ops(&mut self) -> BaseOps<'_, Self::Arch, Self::Error> {
BaseOps::MultiThread(self) | random_line_split |
mod.rs | mod base;
mod breakpoints;
mod desc;
mod monitor;
mod resume;
mod thread;
mod traits;
mod utils;
use super::arch::RuntimeArch;
use crate::{BreakpointCause, CoreStatus, Error, HaltReason, Session};
use gdbstub::stub::state_machine::GdbStubStateMachine;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::num::... | <'a> {
/// The probe-rs session object
session: &'a Mutex<Session>,
/// A list of core IDs for this stub
cores: Vec<usize>,
/// TCP listener accepting incoming connections
listener: TcpListener,
/// The current GDB stub state machine
gdb: Option<GdbStubStateMachine<'a, RuntimeTarget<'a>... | RuntimeTarget | identifier_name |
mod.rs | mod base;
mod breakpoints;
mod desc;
mod monitor;
mod resume;
mod thread;
mod traits;
mod utils;
use super::arch::RuntimeArch;
use crate::{BreakpointCause, CoreStatus, Error, HaltReason, Session};
use gdbstub::stub::state_machine::GdbStubStateMachine;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::num::... |
HaltReason::Step => MultiThreadStopReason::DoneStep,
_ => MultiThreadStopReason::SignalWithThread {
tid,
signal: Signal::SIGINT,
... | {
// Some architectures do not allow us to distinguish between hardware and software breakpoints, so we just treat `Unknown` as hardware breakpoints.
MultiThreadStopReason::HwBreak(tid)
} | conditional_block |
packet_codec.rs | use std::io::Cursor;
use std::net::SocketAddr;
use std::u16;
use byteorder::{NetworkEndian, WriteBytesExt};
use bytes::Bytes;
use futures::sync::mpsc;
use futures::{future, Future, IntoFuture, Sink};
use num_traits::ToPrimitive;
use slog::{error, o, warn, Logger};
use tokio;
use crate::algorithms as algs;
use crate::... | con.1.resender.ack_packet(p_type, ack_id);
} else if p_type.is_voice() {
// Seems to work better without assembling the first 3 voice packets
// Use handle_voice_packet to assemble fragmented voice packets
/*let mut res = Self::handle_voice_packet(&logger, params, &header, p_data);
le... | PacketType::CommandLow
};
| conditional_block |
packet_codec.rs | use std::io::Cursor;
use std::net::SocketAddr;
use std::u16;
use byteorder::{NetworkEndian, WriteBytesExt};
use bytes::Bytes;
use futures::sync::mpsc;
use futures::{future, Future, IntoFuture, Sink};
use num_traits::ToPrimitive;
use slog::{error, o, warn, Logger};
use tokio;
use crate::algorithms as algs;
use crate::... | (
&mut self,
(addr, packet): (SocketAddr, InPacket),
) -> impl Future<Item = (), Error = Error>
{
// Find the right connection
let cons = self.connections.read();
if let Some(con) =
cons.get(&CM::get_connection_key(addr, &packet)).cloned()
{
// If we are a client and have only a single connection, w... | handle_udp_packet | identifier_name |
packet_codec.rs | use std::io::Cursor;
use std::net::SocketAddr;
use std::u16;
use byteorder::{NetworkEndian, WriteBytesExt};
use bytes::Bytes;
use futures::sync::mpsc;
use futures::{future, Future, IntoFuture, Sink};
use num_traits::ToPrimitive;
use slog::{error, o, warn, Logger};
use tokio;
use crate::algorithms as algs;
use crate::... | packet,
)
.into_future()
} else {
drop(cons);
let is_client = self.is_client;
tokio::spawn(future::lazy(move || {
if let Err(e) = Self::connection_handle_udp_packet(
&logger,
in_packet_observer,
in_command_observer,
is_client,
&con,
addr,
packet... | {
// Find the right connection
let cons = self.connections.read();
if let Some(con) =
cons.get(&CM::get_connection_key(addr, &packet)).cloned()
{
// If we are a client and have only a single connection, we will do the
// work inside this future and not spawn a new one.
let logger = self.logger.new(o... | identifier_body |
packet_codec.rs | use std::io::Cursor;
use std::net::SocketAddr;
use std::u16;
use byteorder::{NetworkEndian, WriteBytesExt};
use bytes::Bytes;
use futures::sync::mpsc;
use futures::{future, Future, IntoFuture, Sink};
use num_traits::ToPrimitive;
use slog::{error, o, warn, Logger};
use tokio;
use crate::algorithms as algs;
use crate::... | logger: &Logger,
in_packet_observer: LockedHashMap<
String,
Box<InPacketObserver<CM::AssociatedData>>,
>,
in_command_observer: LockedHashMap<
String,
Box<InCommandObserver<CM::AssociatedData>>,
>,
is_client: bool,
connection: &ConnectionValue<CM::AssociatedData>,
_: SocketAddr,
mut packet:... | random_line_split | |
shell.rs | ]
}
fn eval(&self, cwd: &mut PathBuf) {
match self.path() {
"echo" => {
for arg in &self.args[1..] {
kprint!("{} ", arg);
}
kprintln!("");
},
"panic" => panic!("ARE YOU THE BRAIN SPECIALIST?"),
... | }
fn ls(cwd: &PathBuf, args: &[&str]) {
let mut rel_dir = cwd.clone();
let mut changed_dir = false;
let mut show_hidden = false;
for arg in args {
if *arg == "-a" {
show_hidden = true;
continue
}
if changed_dir {
continue
}
i... | }
}
}
return true | random_line_split |
shell.rs |
}
fn eval(&self, cwd: &mut PathBuf) {
match self.path() {
"echo" => {
for arg in &self.args[1..] {
kprint!("{} ", arg);
}
kprintln!("");
},
"panic" => panic!("ARE YOU THE BRAIN SPECIALIST?"),
... |
fn mkdir(cwd: &PathBuf, args: &[&str]) {
let abs_path = match get_abs_path(cwd, args[0]) {
Some(p) => p,
None => return
};
let dir_metadata = fat32::vfat::Metadata {
name: String::from(abs_path.file_name().unwrap().to_str().unwrap()),
created: fat32::vfat::Timestamp::defau... | {
let mut raw_path: PathBuf = PathBuf::from(dir_arg);
if !raw_path.is_absolute() {
raw_path = cwd.clone().join(raw_path);
}
let abs_path = match canonicalize(raw_path) {
Ok(p) => p,
Err(_) => {
kprintln!("\ninvalid arg: {}", dir_arg);
return None;
... | identifier_body |
shell.rs |
}
fn eval(&self, cwd: &mut PathBuf) {
match self.path() {
"echo" => {
for arg in &self.args[1..] {
kprint!("{} ", arg);
}
kprintln!("");
},
"panic" => panic!("ARE YOU THE BRAIN SPECIALIST?"),
... | (cwd: &mut PathBuf, path: &str) -> bool {
if path.len() == 0 { return true }
if &path[0..1] == "/" {
// cwd.clear() not implemented in shim :(
while cwd.pop() {}
}
for part in path.split('/') {
// Remove any / that makes its way in
let part = part.replace("/", "");
... | cd | identifier_name |
client_conn.rs | //! Single client connection
use std::io;
use std::result::Result as std_Result;
use std::sync::Arc;
use error;
use error::Error;
use result;
use exec::CpuPoolOption;
use solicit::end_stream::EndStream;
use solicit::frame::settings::*;
use solicit::header::*;
use solicit::StreamId;
use solicit::DEFAULT_SETTINGS;
u... | {
write_tx: UnboundedSender<ClientToWriteMessage>,
}
unsafe impl Sync for ClientConn {}
pub struct StartRequestMessage {
pub headers: Headers,
pub body: HttpStreamAfterHeaders,
pub resp_tx: oneshot::Sender<Response>,
}
enum ClientToWriteMessage {
Start(StartRequestMessage),
WaitForHandshake(... | ClientConn | identifier_name |
client_conn.rs | //! Single client connection
use std::io;
use std::result::Result as std_Result;
use std::sync::Arc;
use error;
use error::Error;
use result;
use exec::CpuPoolOption;
use solicit::end_stream::EndStream;
use solicit::frame::settings::*; |
use futures::future::Future;
use futures::stream::Stream;
use futures::sync::mpsc::unbounded;
use futures::sync::mpsc::UnboundedSender;
use futures::sync::oneshot;
use tls_api::TlsConnector;
use tokio_core::reactor;
use tokio_io::AsyncRead;
use tokio_io::AsyncWrite;
use tokio_timer::Timer;
use tokio_tls_api;
use so... | use solicit::header::*;
use solicit::StreamId;
use solicit::DEFAULT_SETTINGS;
use service::Service; | random_line_split |
client_conn.rs | //! Single client connection
use std::io;
use std::result::Result as std_Result;
use std::sync::Arc;
use error;
use error::Error;
use result;
use exec::CpuPoolOption;
use solicit::end_stream::EndStream;
use solicit::frame::settings::*;
use solicit::header::*;
use solicit::StreamId;
use solicit::DEFAULT_SETTINGS;
u... |
let status_1xx = match headers_place {
HeadersPlace::Initial => {
let status = headers.status();
let status_1xx = status >= 100 && status <= 199;
if status_1xx && end_stream == EndStream::Yes {
warn!("1xx headers and end stream: ... | {
warn!("invalid headers: {:?}: {:?}", e, headers);
self.send_rst_stream(stream_id, ErrorCode::ProtocolError)?;
return Ok(None);
} | conditional_block |
mod.rs | //! Kit for creating a a handler for batches of events
//!
//! Start here if you want to implement a handler for processing of events
use std::fmt;
use std::time::{Duration, Instant};
pub use bytes::Bytes;
use futures::future::BoxFuture;
pub type BatchHandlerFuture<'a> = BoxFuture<'a, BatchPostAction>;
use crate::na... | )?,
}
Ok(())
}
}
/// A factory that creates `BatchHandler`s.
///
/// # Usage
///
/// A `BatchHandlerFactory` can be used in two ways:
///
/// * It does not contain any state it shares with the created `BatchHandler`s.
/// This is useful when incoming data is partitioned in a way that a... | event_type_partition.partition() | random_line_split |
mod.rs | //! Kit for creating a a handler for batches of events
//!
//! Start here if you want to implement a handler for processing of events
use std::fmt;
use std::time::{Duration, Instant};
pub use bytes::Bytes;
use futures::future::BoxFuture;
pub type BatchHandlerFuture<'a> = BoxFuture<'a, BatchPostAction>;
use crate::na... | (&self) -> Option<&EventTypeName> {
self.event_type_and_partition().0
}
pub fn partition(&self) -> Option<&PartitionId> {
self.event_type_and_partition().1
}
pub fn event_type_and_partition(&self) -> (Option<&EventTypeName>, Option<&PartitionId>) {
match self {
Hand... | event_type | identifier_name |
lib.rs | use std::num::ParseIntError;
use std::{error, iter};
use std::fmt;
use serde_json;
use serde_with::{ serde_as, DefaultOnError };
use crate::ParseError::MissingNode;
use lazy_static::lazy_static; // 1.3.0
use regex::Regex;
use serde::{Deserializer, Deserialize, Serialize, de};
use serde_json::{Error, Value};
use web_s... | use peg;
use chrono::NaiveDate; | random_line_split | |
lib.rs | id }
}
}
#[serde_as]
#[derive(Deserialize, Debug, PartialEq)]
pub struct Province {
name: String,
#[serde(default)]
owner: Option<String>,
/// Small hack: make the remainder pops.
/// This, shockingly, actually works for any subfield we can think of,
/// so it's actually the magic backtrac... |
/// convert a function to serde's json
pub fn to_json(&self) -> serde_json::Value {
match self {
Node::Line((_, arr)) | Node::List(arr) => {
// Object if any element has a child
// List if none do
// Undefined if both
if let S... | {
match self {
Node::Line((name, _)) => re.is_match(name),
_ => false,
}
} | identifier_body |
lib.rs | id }
}
}
#[serde_as]
#[derive(Deserialize, Debug, PartialEq)]
pub struct Province {
name: String,
#[serde(default)]
owner: Option<String>,
/// Small hack: make the remainder pops.
/// This, shockingly, actually works for any subfield we can think of,
/// so it's actually the magic backtrac... | (&self) -> Box<dyn Iterator<Item = &T> + '_> {
match self {
SingleOrMany::None => Box::new(iter::empty()),
SingleOrMany::Single(elem) => Box::new(iter::once(elem)),
SingleOrMany::Many(elems) => Box::new(elems.iter()),
}
}
}
#[wasm_bindgen]
#[derive(Deserialize, D... | values | identifier_name |
lib.rs | id }
}
}
#[serde_as]
#[derive(Deserialize, Debug, PartialEq)]
pub struct Province {
name: String,
#[serde(default)]
owner: Option<String>,
/// Small hack: make the remainder pops.
/// This, shockingly, actually works for any subfield we can think of,
/// so it's actually the magic backtrac... |
} else {
map.insert(name.to_string(), object.clone());
}
}
/// In-place modify to be parseable.
/// See the comment above for countries for rationale.
/// Call on root.
pub fn raise(&mut self) {
if let Node::List(nodes) = self {
// Get the first coun... | {
// create list
seen.push(name);
map.insert(name.to_string(), serde_json::Value::Array(vec![prior.clone(), object.clone()]));
} | conditional_block |
iter.rs | ///! source::iter: source code content iterator, with interner
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::ops::{Add, AddAssign};
use super::{SourceContext, SourceFile, FileId};
pub const EOF: char = ... | (&self) -> FileId {
FileId::new(self.files.len() as u32 + 1)
}
pub fn finish(mut self) {
let content_length = self.content.len();
self.content.truncate(content_length - 3);
self.files.push(SourceFile{
path: self.path,
endlines: get_endlines(&self.content)... | get_file_id | identifier_name |
iter.rs | ///! source::iter: source code content iterator, with interner
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::ops::{Add, AddAssign};
use super::{SourceContext, SourceFile, FileId};
pub const EOF: char = ... | fn get_endlines(content: &str) -> Vec<usize> {
content.char_indices().filter(|(_, c)| c == &'\n').map(|(i, _)| i).collect()
}
// this iterator is the exact first layer of processing above source code content,
// logically all location information comes from position created by the next function
//
// this iterato... | hasher.finish()
}
// get LF byte indexes | random_line_split |
iter.rs | ///! source::iter: source code content iterator, with interner
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::ops::{Add, AddAssign};
use super::{SourceContext, SourceFile, FileId};
pub const EOF: char = ... |
}
// this is currently an u128, but I suspect that it can fit in u64
// for current small test until even first bootstrap version, the string id and span should be easily fit in u64
// for "dont-know-whether-exist very large program",
// considering these 2 ids increase accordingly, squash `u32::MAX - id` and span t... | {
f.debug_tuple("IsId").field(&self.0.get()).finish()
} | identifier_body |
read_state.rs | use crate::{IncomingRewriter, StreamChangeData};
/// Is a given read operation "peek" or "consume"?
#[derive(Clone, Copy)]
pub enum | {
/// A read operation which advances the buffer, and reads from it.
ConsumingRead,
/// A read operation which reads from the buffer but doesn't advance it.
PeekingRead,
}
impl Default for ReadIsPeek {
fn default() -> Self {
ReadIsPeek::ConsumingRead
}
}
impl ReadIsPeek {
/// Ret... | ReadIsPeek | identifier_name |
read_state.rs | use crate::{IncomingRewriter, StreamChangeData};
/// Is a given read operation "peek" or "consume"?
#[derive(Clone, Copy)]
pub enum ReadIsPeek {
/// A read operation which advances the buffer, and reads from it.
ConsumingRead,
/// A read operation which reads from the buffer but doesn't advance it.
Pe... | stallone::debug!(
"Saving just-rewritten bytes that were peeked",
num_just_rewritten_bytes: usize = just_rewritten_bytes.len(),
);
}
self.rewritten_bytes.extend_from_slice(just_rewritten_bytes);
... | if !just_rewritten_bytes.is_empty() { | random_line_split |
read_state.rs | use crate::{IncomingRewriter, StreamChangeData};
/// Is a given read operation "peek" or "consume"?
#[derive(Clone, Copy)]
pub enum ReadIsPeek {
/// A read operation which advances the buffer, and reads from it.
ConsumingRead,
/// A read operation which reads from the buffer but doesn't advance it.
Pe... |
}
impl ReadIsPeek {
/// Return `PeekingRead` if the [`libc::MSG_PEEK`] bit is set in `flags.`
/// Otherwise, return `ConsumingRead`.
pub fn from_flags(flags: libc::c_int) -> Self {
if (flags & libc::MSG_PEEK) == 0 {
ReadIsPeek::ConsumingRead
} else {
ReadIsPeek::Pee... | {
ReadIsPeek::ConsumingRead
} | identifier_body |
read_state.rs | use crate::{IncomingRewriter, StreamChangeData};
/// Is a given read operation "peek" or "consume"?
#[derive(Clone, Copy)]
pub enum ReadIsPeek {
/// A read operation which advances the buffer, and reads from it.
ConsumingRead,
/// A read operation which reads from the buffer but doesn't advance it.
Pe... |
if let Some(relative_remove_index) = stream_change_data.remove_byte {
let remove_index = start_rewriting_index + relative_remove_index;
stallone::debug!(
"Removing byte from stream",
stream_change_data: StreamChangeData = stream_change_data,
... | {
let add_index = start_rewriting_index + relative_add_index;
stallone::debug!(
"Inserting byte into stream",
stream_change_data: StreamChangeData = stream_change_data,
start_rewriting_index: usize = start_rewriting_index,
add_index... | conditional_block |
demuxer.rs | use crate::error::*;
use crate::buffer::Buffered;
use std::any::Any;
use std::io::SeekFrom;
use std::sync::Arc;
use crate::common::*;
use crate::data::packet::Packet;
use crate::stream::Stream;
/// Events processed by a demuxer analyzing a source.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Event {
/// A... |
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::data::packet::Packet;
use std::io::SeekFrom;
struct DummyDes {
d: Descr,
}
struct DummyDemuxer {}
impl Demuxer for DummyDemuxer {
fn read_headers(
&mut self,
buf: &mut dyn Buffered,
... | {
None
} | conditional_block |
demuxer.rs | use crate::error::*;
use crate::buffer::Buffered;
use std::any::Any;
use std::io::SeekFrom;
use std::sync::Arc;
use crate::common::*;
use crate::data::packet::Packet;
use crate::stream::Stream;
/// Events processed by a demuxer analyzing a source.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Event {
/// A... | {
d: Descr,
}
struct DummyDemuxer {}
impl Demuxer for DummyDemuxer {
fn read_headers(
&mut self,
buf: &mut dyn Buffered,
_info: &mut GlobalInfo,
) -> Result<SeekFrom> {
let len = buf.data().len();
if 9 > len {
... | DummyDes | identifier_name |
demuxer.rs | use crate::error::*;
use crate::buffer::Buffered;
use std::any::Any;
use std::io::SeekFrom;
use std::sync::Arc;
use crate::common::*;
use crate::data::packet::Packet;
use crate::stream::Stream;
/// Events processed by a demuxer analyzing a source.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Event {
/// A... | }
if let Event::MoreDataNeeded(size) = event {
return Err(Error::MoreDataNeeded(size));
}
if let Event::NewPacket(ref mut pkt) = event {
if pkt.t.timebase.is_none() {
if let Some(st) = self
... | self.info.streams.push(st.clone()); | random_line_split |
demuxer.rs | use crate::error::*;
use crate::buffer::Buffered;
use std::any::Any;
use std::io::SeekFrom;
use std::sync::Arc;
use crate::common::*;
use crate::data::packet::Packet;
use crate::stream::Stream;
/// Events processed by a demuxer analyzing a source.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Event {
/// A... |
use crate::buffer::*;
use std::io::Cursor;
#[test]
fn read_headers() {
let buf = b"dummy header";
let r = AccReader::with_capacity(4, Cursor::new(buf));
let d = DUMMY_DES.create();
let mut c = Context::new(d, r);
c.read_headers().unwrap();
}
#[test]
... | {
let demuxers: &[&'static dyn Descriptor<OutputDemuxer = DummyDemuxer>] = &[DUMMY_DES];
demuxers.probe(b"dummy").unwrap();
} | identifier_body |
db_transaction.rs | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | impl Display for DbKey {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
DbKey::Metadata(MetadataKey::ChainHeight) => f.write_str("Current chain height"),
DbKey::Metadata(MetadataKey::AccumulatedWork) => f.write_str("Total accumulated work"),
DbKey::M... | }
| random_line_split |
db_transaction.rs | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | (&mut self, delete: DbKey) {
self.operations.push(WriteOperation::Delete(delete));
}
/// Inserts a transaction kernel into the current transaction.
pub fn insert_kernel(&mut self, kernel: TransactionKernel, update_mmr: bool) {
let hash = kernel.hash();
self.insert(DbKeyValuePair::Tr... | delete | identifier_name |
db_transaction.rs | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... |
}
impl Display for DbKey {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
DbKey::Metadata(MetadataKey::ChainHeight) => f.write_str("Current chain height"),
DbKey::Metadata(MetadataKey::AccumulatedWork) => f.write_str("Total accumulated work"),
DbKe... | {
match self {
DbValue::Metadata(MetadataValue::ChainHeight(_)) => f.write_str("Current chain height"),
DbValue::Metadata(MetadataValue::AccumulatedWork(_)) => f.write_str("Total accumulated work"),
DbValue::Metadata(MetadataValue::PruningHorizon(_)) => f.write_str("Pruning h... | identifier_body |
lib.rs | #![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file ... |
let (start_byte, stop_byte) = self.fasta_index.offset(tid, start, stop)?;
//println!("offset for chr {}:{}-{} is {}-{}", tid, start, stop, start_byte, stop_byte);
Ok(FastaView(&self.mmap[start_byte..stop_byte]))
}
/// Use tid to return a view of an entire chromosome.
///
/// R... | {
return Err(io::Error::new(
io::ErrorKind::Other,
"Invalid query interval",
));
} | conditional_block |
lib.rs | #![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file ... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fai() {
let ir = IndexedFasta::from_file("test/genome.fa").unwrap();
assert_eq!(ir.fai().names().len(), 3);
assert_eq!(ir.fai().tid("ACGT-25"), Some(2));
assert_eq!(ir.fai().tid("NotFound"), None);
assert_eq!(ir.... | {
BaseCounts {
a: 0,
c: 0,
g: 0,
t: 0,
n: 0,
other: 0,
}
} | identifier_body |
lib.rs | #![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file ... | let ioerr =
|e, msg| io::Error::new(io::ErrorKind::InvalidData, format!("{}:{}", msg, e));
chromosomes.push(FaiRecord {
len: p[1]
.parse()
.map_err(|e| ioerr(e, "Error parsing chr len in.fai"))?,
offset: p[2]
... |
name_map.insert(p[0].to_owned());
| random_line_split |
lib.rs | #![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file ... | (&self, tid: usize) -> io::Result<&String> {
self.name_map.get_index(tid).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Chromomsome tid was out of bounds")
})
}
/// Return the names of the chromosomes from the fasta index in the same order as in the
/// `.fai`. You can u... | name | identifier_name |
backend.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... | -> (H::Out, Self::Transaction)
where
I1: IntoIterator<Item=(Vec<u8>, Option<Vec<u8>>)>,
I2i: IntoIterator<Item=(Vec<u8>, Option<Vec<u8>>)>,
I2: IntoIterator<Item=(Vec<u8>, I2i)>,
<H as Hasher>::Out: Ord,
{
let mut txs: Self::Transaction = Default::default();
let mut child_roots: Vec<_> = Default::default... | random_line_split | |
backend.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... | (&self, storage_key: &[u8], key: &[u8]) -> Result<Option<H::Out>, Self::Error> {
self.child_storage(storage_key, key).map(|v| v.map(|v| H::hash(&v)))
}
/// true if a key exists in storage.
fn exists_storage(&self, key: &[u8]) -> Result<bool, Self::Error> {
Ok(self.storage(key)?.is_some())
}
/// true if a key... | child_storage_hash | identifier_name |
backend.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... | else {
root_map = Some(map);
}
}
// root handling
if let Some(map) = root_map.take() {
root = Some(insert_into_memory_db::<H, _>(
&mut mdb,
map.clone().into_iter().chain(new_child_roots.into_iter())
)?);
}
let root = match root {
Some(root) => root,
None => insert_into_memory_db::<... | {
let ch = insert_into_memory_db::<H, _>(&mut mdb, map.clone().into_iter())?;
new_child_roots.push((storage_key.clone(), ch.as_ref().into()));
} | conditional_block |
backend.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... |
fn for_keys_with_prefix<F: FnMut(&[u8])>(&self, prefix: &[u8], f: F) {
self.inner.get(&None).map(|map| map.keys().filter(|key| key.starts_with(prefix)).map(|k| &**k).for_each(f));
}
fn for_keys_in_child_storage<F: FnMut(&[u8])>(&self, storage_key: &[u8], mut f: F) {
self.inner.get(&Some(storage_key.to_vec()))... | {
Ok(self.inner.get(&None).map(|map| map.get(key).is_some()).unwrap_or(false))
} | identifier_body |
mod.rs | // High-level Internal Representation of GObject artifacts
//
// Here we provide a view of the world in terms of what GObject knows:
// classes, interfaces, signals, etc.
//
// We construct this view of the world from the raw Abstract Syntax
// Tree (AST) from the previous stage.
use std::collections::HashMap;
use pr... |
fn extract_inputs(&mut self, punc: &'ast Punctuated<syn::FnArg, Token!(,)>) -> Result<Vec<FnArg<'ast>>> {
punc.iter().map(|arg| {
match *arg {
syn::FnArg::Captured(syn::ArgCaptured { ref pat, ref ty,.. }) => {
let (name, mutbl) = match *pat {
... | {
match *output {
ReturnType::Type(_, ref boxt) => self.extract_ty(boxt),
ReturnType::Default => Ok(Ty::Unit),
}
} | identifier_body |
mod.rs | // High-level Internal Representation of GObject artifacts
//
// Here we provide a view of the world in terms of what GObject knows:
// classes, interfaces, signals, etc.
//
// We construct this view of the world from the raw Abstract Syntax
// Tree (AST) from the previous stage.
use std::collections::HashMap;
use pr... | }
}
}
Ok(())
}
pub fn iter<'a>(&'a self) -> impl Iterator<Item = &'a Class> + 'a {
self.items.values()
}
}
impl<'ast> Class<'ast> {
fn translate_slot(&mut self, item: &'ast ast::ImplItem) -> Result<Slot<'ast>> {
assert_eq!(item.attrs.len(), ... | random_line_split | |
mod.rs | // High-level Internal Representation of GObject artifacts
//
// Here we provide a view of the world in terms of what GObject knows:
// classes, interfaces, signals, etc.
//
// We construct this view of the world from the raw Abstract Syntax
// Tree (AST) from the previous stage.
use std::collections::HashMap;
use pr... | (&self) -> usize {
self.items.len()
}
pub fn get(&self, name: &str) -> &Class {
self.items.iter().find(|c| c.1.name == name).unwrap().1
}
fn add(&mut self, ast_class: &'ast ast::Class) -> Result<()>
{
let prev = self.items.insert(ast_class.name, Class {
name: as... | len | identifier_name |
merkle.rs | // LNP/BP client-side-validation foundation libraries implementing LNPBP
// specifications & standards (LNPBP-4, 7, 8, 9, 42, 81)
//
// Written in 2019-2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neigh... | engine_proto,
iter,
depth + 1,
(div % 2 + len % 2) / 2 == 1,
Some(empty_node),
);
assert_eq!(
height1,
height2,
"merklization algorithm failure: height of subtrees is not equal \
(width = {}, de... | {
let div = len / 2 + len % 2;
let (node1, height1) = merklize_inner(
engine_proto,
// Normally we should use `iter.by_ref().take(div)`, but currently
// rust compilers is unable to parse recursion with generic types
iter.by_ref().take(div).collect::<Vec<... | conditional_block |
merkle.rs | // LNP/BP client-side-validation foundation libraries implementing LNPBP
// specifications & standards (LNPBP-4, 7, 8, 9, 42, 81)
//
// Written in 2019-2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neigh... |
}
impl<L> FromIterator<L> for MerkleSource<L>
where
L: CommitEncode,
{
fn from_iter<T: IntoIterator<Item = L>>(iter: T) -> Self {
iter.into_iter().collect::<Vec<_>>().into()
}
}
impl<L> CommitEncode for MerkleSource<L>
where
L: ConsensusMerkleCommit,
{
fn commit_encode<E: io::Write>(&self... | { Self(collection.into_iter().collect()) } | identifier_body |
merkle.rs | // LNP/BP client-side-validation foundation libraries implementing LNPBP
// specifications & standards (LNPBP-4, 7, 8, 9, 42, 81)
//
// Written in 2019-2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neigh... | let iter = if extend {
iter.chain(vec![empty_node]).collect::<Vec<_>>().into_iter()
} else {
iter.collect::<Vec<_>>().into_iter()
};
let (node2, height2) = merklize_inner(
engine_proto,
iter,
depth + 1,
(div % 2 + l... | depth + 1,
false,
Some(empty_node),
);
| random_line_split |
merkle.rs | // LNP/BP client-side-validation foundation libraries implementing LNPBP
// specifications & standards (LNPBP-4, 7, 8, 9, 42, 81)
//
// Written in 2019-2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neigh... | <E: io::Write>(&self, e: E) -> usize {
let leafs = self.0.iter().map(L::consensus_commit);
merklize(L::MERKLE_NODE_PREFIX, leafs).0.commit_encode(e)
}
}
impl<L> ConsensusCommit for MerkleSource<L>
where
L: ConsensusMerkleCommit + CommitEncode,
{
type Commitment = MerkleNode;
#[inline]
... | commit_encode | identifier_name |
mod.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... | prometheus_future::with_poll_durations(poll_duration, poll_start, task);
// The logic of `AssertUnwindSafe` here is ok considering that we throw
// away the `Future` after it has panicked.
panic::AssertUnwindSafe(inner).catch_unwind()
};
futures::pin_mut!(task);
match select(on_exit, t... | let poll_duration =
metrics.poll_duration.with_label_values(&[name, group, task_type_label]);
let poll_start =
metrics.poll_start.with_label_values(&[name, group, task_type_label]);
let inner = | random_line_split |
mod.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... | ,
TaskType::Blocking => {
let handle = self.tokio_handle.clone();
self.tokio_handle.spawn_blocking(move || {
handle.block_on(future);
});
},
}
}
}
impl sp_core::traits::SpawnNamed for SpawnTaskHandle {
fn spawn_blocking(
&self,
name: &'static str,
group: Option<&'static str>,
future:... | {
self.tokio_handle.spawn(future);
} | conditional_block |
mod.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... | {
essential_failed_tx: TracingUnboundedSender<()>,
inner: SpawnTaskHandle,
}
impl SpawnEssentialTaskHandle {
/// Creates a new `SpawnEssentialTaskHandle`.
pub fn new(
essential_failed_tx: TracingUnboundedSender<()>,
spawn_task_handle: SpawnTaskHandle,
) -> SpawnEssentialTaskHandle {
SpawnEssentialTaskHandl... | SpawnEssentialTaskHandle | identifier_name |
mod.rs | // Copyright © 2020 Brian Merchant.
//
// 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 accordi... | pub const_retractive: f64,
/// Stiffness of cytoplasm.
pub stiffness_cyto: f64,
/// Rate of Rho GTPase GDI unbinding and subsequent membrane attachment.
pub k_mem_on_vertex: f64,
/// Rate of Rho GTPase membrane disassociation.
pub k_mem_off: f64,
/// Diffusion rate of Rho GTPase on membr... | /// Stiffness of edge.
pub stiffness_edge: f64,
/// Rac1 mediated protrusive force constant.
pub const_protrusive: f64,
/// RhoA mediated protrusive force constant. | random_line_split |
mod.rs | // Copyright © 2020 Brian Merchant.
//
// 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 accordi... | {
/// Viscosity value used to calculate change in position of a
/// vertex due to calculated forces on it.
pub vertex_eta: f64,
pub interactions: InteractionParams,
}
impl RawWorldParameters {
pub fn refine(&self, bq: &CharacteristicQuantities) -> WorldParameters {
WorldParameters {
... | orldParameters | identifier_name |
main.rs | eprintln!("ignore reason: {:?}", e);
}
}
}
Ok(StarDict { directories: items })
}
/// Get the Ifo struct, which is parsed from the.ifo file.
pub fn info(&self) -> Vec<&ifo::Ifo> {
let mut items = Vec::with_capacity(self.directories.len()... | {
//html js css page etc.
if let Ok(fname) = str::from_utf8(&surl.word) {
let mut pfile = path::PathBuf::from(dictdir);
pfile.push(fname);
if let Ok(mut f) = fs::File::open(pfile) {
if f.read_to_end(&mut ... | conditional_block | |
main.rs |
impl StarDict {
/// Create a StarDict struct from a system path. in the path,
/// there should be some directories. each directory contains
/// the dict files, like.ifo,.idx,.dict, etc.
/// The dictionary will be sorted by its directory name.
pub fn new(root: &path::Path) -> Result<StarDict, resul... |
/// Search from all dictionaries. using the specified regular expression.
/// to match the beginning of a word, use `^`, the ending of a word, use `$`.
pub fn search<'a>(&'a self, reg: &'a Regex) -> WordMergeIter<dictionary::IdxIter> {
let mut wordit = Vec::with_capacity(2 * self.directories.len())... | {
let mut wordit = Vec::with_capacity(2 * self.directories.len());
let mut cur = Vec::with_capacity(2 * self.directories.len());
for d in self.directories.iter() {
let mut x = d.neighbors(word, off);
let mut s = d.neighbors_syn(word, off);
cur.push(x.next());
... | identifier_body |
main.rs | <T: Iterator<Item = Vec<u8>>> {
wordit: Vec<T>,
cur: Vec<Option<Vec<u8>>>,
}
impl<'a, T: Iterator<Item = Vec<u8>>> Iterator for WordMergeIter<T> {
type Item = Vec<u8>;
fn next(&mut self) -> Option<Self::Item> {
let l = self.cur.len();
if l == 0 {
return None;
}
... | WordMergeIter | identifier_name | |
main.rs |
WordMergeIter { wordit, cur }
}
/// Search from all dictionaries. using the specified regular expression.
/// to match the beginning of a word, use `^`, the ending of a word, use `$`.
pub fn search<'a>(&'a self, reg: &'a Regex) -> WordMergeIter<dictionary::IdxIter> {
let mut wordit = V... | if surl.path[0] == b'n' {
stream.write(b"text/plain")?; | random_line_split | |
lib.rs | // Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in w... | // instead of requiring callers always to set AUTOCXX_INC.
// On Windows, the canonical path begins with a UNC prefix that cannot be passed to
// the MSVC compiler, so dunce::canonicalize() is used instead of std::fs::canonicalize()
// See:
// * https://github.com/dtolnay/cxx/pu... | let inc_dirs = std::env::split_paths(&inc_dirs);
// TODO consider if we can or should look up the include path automatically | random_line_split |
lib.rs | // Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in w... |
/// Generate the Rust bindings. Call `generate` first.
pub fn generate_rs(&self) -> TokenStream2 {
match &self.state {
State::NotGenerated => panic!("Call generate() first"),
State::Generated(itemmod, _) => itemmod.to_token_stream(),
State::NothingGenerated | State:... | {
let full_header = self.build_header();
let full_header = format!("{}\n\n{}", KNOWN_TYPES.get_prelude(), full_header,);
builder = builder.header_contents("example.hpp", &full_header);
builder
} | identifier_body |
lib.rs | // Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in w... | (&self) -> Result<Vec<PathBuf>> {
self.determine_incdirs()
}
}
| include_dirs | identifier_name |
lib.rs | //! `hull` is Theseus's shell for basic interactive systems operations.
//!
//! Just as the hull is the outermost layer or "shell" of a boat or ship,
//! this crate `hull` is the shell of the "Ship of Theseus" (this OS).
//!
//! Functionally, this is similar to bash, zsh, fish, etc.
//!
//! This shell will eventually s... | .map_err(Error::SpawnFailed)?
.argument(args.into_iter().map(ToOwned::to_owned).collect::<Vec<_>>())
.block()
.spawn()
.unwrap();
let task_ref = task.clone();
let id = task.id;
// TODO: Double arc :(
app_io::insert_child_streams(id,... | {
let namespace_dir = task::get_my_current_task()
.map(|t| t.get_namespace().dir().clone())
.expect("couldn't get namespace dir");
let crate_name = format!("{cmd}-");
let mut matching_files = namespace_dir
.get_files_starting_with(&crate_name)
.in... | identifier_body |
lib.rs | //! `hull` is Theseus's shell for basic interactive systems operations.
//!
//! Just as the hull is the outermost layer or "shell" of a boat or ship,
//! this crate `hull` is the shell of the "Ship of Theseus" (this OS).
//!
//! Functionally, this is similar to bash, zsh, fish, etc.
//!
//! This shell will eventually s... | while let Some(ParsedTask { command, args }) = task {
if iter.peek().is_none() {
if let Some(result) = self.execute_builtin(command, &args) {
self.jobs.lock().remove(&job_id);
return result.map(|_| None);
} else {
... | }
drop(jobs);
| random_line_split |
lib.rs | //! `hull` is Theseus's shell for basic interactive systems operations.
//!
//! Just as the hull is the outermost layer or "shell" of a boat or ship,
//! this crate `hull` is the shell of the "Ship of Theseus" (this OS).
//!
//! Functionally, this is similar to bash, zsh, fish, etc.
//!
//! This shell will eventually s... | (&mut self, line: &str) -> Result<()> {
let parsed_line = ParsedLine::from(line);
if parsed_line.is_empty() {
return Ok(());
}
// TODO: Use line editor history.
self.history.push(line.to_owned());
for (job_str, job) in parsed_line.background {
i... | execute_line | identifier_name |
models.rs | /// How our data look?
// Main logs contains when bot started to run, what is total log amount
// Keywords logs contains indivitual keyword with their own logs
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
type Account = String... | // println!("Backup done");
let mut no_of_main_log_cleared = 0;
{
if count == 0 {
let ms = &mut statistics.main_stats;
ms.error_counts = 0;
ms.log_counts = 0;
ms.no_api_calls = 0;
ms.no_internal_api_calls = 0;
}
let main_... | random_line_split | |
models.rs | /// How our data look?
// Main logs contains when bot started to run, what is total log amount
// Keywords logs contains indivitual keyword with their own logs
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
type Account = String... |
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct BackupStatistics {
stats: MainStats,
keyword: HashMap<KeywordId, Vec<Log>>,
}
// // We might want to reanalyze previous record for that we are providing ability to
// // use old database.
// pub async fn load_old_database() -> Option<Statistics> ... | {
main_stats.last_updated_at = crate::helpers::current_time_string();
if input.r#type == "error" {
main_stats.error_counts += 1;
ks.stats.error_counts += 1;
}
main_stats.log_counts += 1;
ks.stats.log_counts += 1;
... | conditional_block |
models.rs | /// How our data look?
// Main logs contains when bot started to run, what is total log amount
// Keywords logs contains indivitual keyword with their own logs
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
type Account = String... | {
pub id: u64,
pub last_updated_at: String,
pub error_counts: u64,
pub log_counts: u64,
pub name: Option<String>,
pub keyword: Option<String>,
pub placement: Option<u64>,
pub running: Option<bool>,
pub ads_running: Option<bool>,
pub ads_position: Option<u64>,
pub current_pr... | KeywordStat | identifier_name |
main.rs | use std::ops::Deref;
use std::path::PathBuf;
use serde::Deserialize;
use structopt::StructOpt;
use tmux_interface::{AttachSession, NewSession, NewWindow, SelectWindow, SendKeys, SplitWindow, TmuxInterface};
const ORIGINAL_WINDOW_NAME: &str = "__DEFAULT__";
#[derive(Debug, Deserialize)]
struct Setup {
file: Option<S... | }
Err(err) => {
eprintln!("Unable to create new session: {}", err);
return;
}
}
}
// We rename the first window, so we can locate and remove it later.
match tmux.rename_window(None, ORIGINAL_WINDOW_NAME) {
Ok(v) => if!v.status.success() {
eprintln!("Unable to rename default window: {:?}", v)... | random_line_split | |
main.rs | use std::ops::Deref;
use std::path::PathBuf;
use serde::Deserialize;
use structopt::StructOpt;
use tmux_interface::{AttachSession, NewSession, NewWindow, SelectWindow, SendKeys, SplitWindow, TmuxInterface};
const ORIGINAL_WINDOW_NAME: &str = "__DEFAULT__";
#[derive(Debug, Deserialize)]
struct Setup {
file: Option<S... |
}
}
None
}
#[derive(Debug, PartialEq, Copy, Clone)]
enum Ordinal {
North,
South,
East,
West,
}
impl Ordinal {
fn opposite(&self) -> Ordinal {
match self {
Ordinal::North => Ordinal::South,
Ordinal::South => Ordinal::North,
Ordinal::East => Ordinal::West,
Ordinal::West => Ordinal::East,
}
}... | {
return Some((left_index, right_index, *ordinal));
} | conditional_block |
main.rs | use std::ops::Deref;
use std::path::PathBuf;
use serde::Deserialize;
use structopt::StructOpt;
use tmux_interface::{AttachSession, NewSession, NewWindow, SelectWindow, SendKeys, SplitWindow, TmuxInterface};
const ORIGINAL_WINDOW_NAME: &str = "__DEFAULT__";
#[derive(Debug, Deserialize)]
struct Setup {
file: Option<S... | {
x: u8,
y: u8,
length: u8,
}
fn determine_rectangles(layout: &str) -> Vec<Rect> {
let (width, height, chars) = sanitise_input(layout);
macro_rules! point {
($index:ident) => {{
let x = $index % width;
let y = $index / width;
(x, y)
}};
}
let mut index = 0usize;
let mut rects = vec![];
let ... | Edge | identifier_name |
t_usefulness.rs | #![allow(clippy::excessive_precision)]
use wide::*;
use bytemuck::*;
#[test]
fn unpack_modify_and_repack_rgba_values() {
let mask = u32x4::from(0xFF);
//
let input = u32x4::from([0xFF0000FF, 0x00FF00FF, 0x0000FFFF, 0x000000FF]);
// unpack
let r_actual = cast::<_, i32x4>(input >> 24).round_float();
let g... |
fn kernel_i16(data: [i16x8; 8]) -> [i16x8; 8] {
// kernel x
let a2 = data[2];
let a6 = data[6];
let b0 = a2.saturating_add(a6).mul_scale_round_n(to_fixed(0.5411961));
let c0 = b0
.saturating_sub(a6)
.saturating_sub(a6.mul_scale_round_n(to_fixed(0.847759065)));
let c1 = b0.saturati... | {
(x * 32767.0 + 0.5) as i16
} | identifier_body |
t_usefulness.rs | #![allow(clippy::excessive_precision)]
use wide::*;
use bytemuck::*;
#[test]
fn unpack_modify_and_repack_rgba_values() {
let mask = u32x4::from(0xFF);
//
let input = u32x4::from([0xFF0000FF, 0x00FF00FF, 0x0000FFFF, 0x000000FF]);
// unpack
let r_actual = cast::<_, i32x4>(input >> 24).round_float();
let g... | let a_expected = f32x4::from([255.0, 255.0, 255.0, 255.0]);
assert_eq!(r_expected, r_actual);
assert_eq!(g_expected, g_actual);
assert_eq!(b_expected, b_actual);
assert_eq!(a_expected, a_actual);
// modify some of the data
let r_new = (r_actual - f32x4::from(1.0)).max(f32x4::from(0.0));
let g_new = (g_... | let r_expected = f32x4::from([255.0, 0.0, 0.0, 0.0]);
let g_expected = f32x4::from([0.0, 255.0, 0.0, 0.0]);
let b_expected = f32x4::from([0.0, 0.0, 255.0, 0.0]); | random_line_split |
t_usefulness.rs | #![allow(clippy::excessive_precision)]
use wide::*;
use bytemuck::*;
#[test]
fn unpack_modify_and_repack_rgba_values() {
let mask = u32x4::from(0xFF);
//
let input = u32x4::from([0xFF0000FF, 0x00FF00FF, 0x0000FFFF, 0x000000FF]);
// unpack
let r_actual = cast::<_, i32x4>(input >> 24).round_float();
let g... | (data: [i16x8; 8]) -> [i16x8; 8] {
// kernel x
let a2 = data[2];
let a6 = data[6];
let b0 = a2.saturating_add(a6).mul_scale_round_n(to_fixed(0.5411961));
let c0 = b0
.saturating_sub(a6)
.saturating_sub(a6.mul_scale_round_n(to_fixed(0.847759065)));
let c1 = b0.saturating_add(a2.mul_sca... | kernel_i16 | identifier_name |
useful.rs | use rand::{Rng, thread_rng};
use serenity::builder::CreateEmbed;
use serenity::client::Context;
use serenity::model::channel::Message;
use tokio_postgres::{Error, NoTls, types::ToSql};
use crate::format_emojis;
const POSTGRE: &'static str = "host=192.168.1.146 user=postgres";
pub const GRIST_TYPES: (&'stat... | lse if author_exile == 4 {
send_embed(ctx, msg, exile_4[rand_index as usize]).await;
}
}
pub trait InVec: std::cmp::PartialEq + Sized {
fn in_vec(self, vector: Vec<Self>) -> bool {
vector.contains(&self)
}
}
impl<T> InVec for T where T: std::cmp::PartialEq {}
pub trait Conver... |
send_embed(ctx, msg, exile_3[rand_index as usize]).await;
} e | conditional_block |
useful.rs | use rand::{Rng, thread_rng};
use serenity::builder::CreateEmbed;
use serenity::client::Context;
use serenity::model::channel::Message;
use tokio_postgres::{Error, NoTls, types::ToSql};
use crate::format_emojis;
const POSTGRE: &'static str = "host=192.168.1.146 user=postgres";
pub const GRIST_TYPES: (&'stat... | let new_vec = self.into_iter().rev().collect::<Vec<_>>();
let mut return_string = "".to_owned();
for x in new_vec {
return_string = format!("{}\n{}", return_string, x);
}
if return_string.replace("\n", "") == "" {
return "Empty".to_owned()
}... |
impl<T: std::fmt::Display> FormatVec for Vec<T> {
fn format_vec(&self) -> String {
| random_line_split |
useful.rs | use rand::{Rng, thread_rng};
use serenity::builder::CreateEmbed;
use serenity::client::Context;
use serenity::model::channel::Message;
use tokio_postgres::{Error, NoTls, types::ToSql};
use crate::format_emojis;
const POSTGRE: &'static str = "host=192.168.1.146 user=postgres";
pub const GRIST_TYPES: (&'stat... | (statement: &str) -> Result<(), Error> {
let (client, connection) = tokio_postgres::connect(POSTGRE, NoTls).await.unwrap();
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});
let _ = client.execu... | sqlstatement | identifier_name |
main.rs | use tetra::graphics::text::{Text, Font};
use tetra::graphics::{self, Color, Texture, DrawParams};
use tetra::math::Vec2;
use tetra::input::{self, Key};
use tetra::{Context, ContextBuilder, State};
// visual consts
const SCREEN_WIDTH: i32 = 1280;
const SCREEN_HEIGHT: i32 = 720;
const FONT_SIZE: f32 = 32.0;
const PADDIN... |
}
fn update_ball(&mut self, _ctx: &mut Context){
self.update_ai(_ctx);
self.ball.position += self.ball.velocity;
if!self.simulated {
GameState::update_collision(&mut self.ball, &self.player_paddle);
GameState::update_collision(&mut self.ball, &self.enemy_paddle... | {
GameState::apply_collision_response(ball, paddle);
} | conditional_block |
main.rs | use tetra::graphics::text::{Text, Font};
use tetra::graphics::{self, Color, Texture, DrawParams};
use tetra::math::Vec2;
use tetra::input::{self, Key};
use tetra::{Context, ContextBuilder, State};
// visual consts
const SCREEN_WIDTH: i32 = 1280;
const SCREEN_HEIGHT: i32 = 720;
const FONT_SIZE: f32 = 32.0;
const PADDIN... | {
ball_texture: Texture,
position: Vec2<f32>,
velocity: Vec2<f32>,
}
impl Ball {
fn reset(&mut self){
self.position = Vec2::new(
(SCREEN_WIDTH as f32)/2.0 - (self.ball_texture.width() as f32)/2.0,
(SCREEN_HEIGHT as f32)/2.0 - (self.ball_texture.height() as f32)/2.0
... | Ball | identifier_name |
main.rs | use tetra::graphics::text::{Text, Font};
use tetra::graphics::{self, Color, Texture, DrawParams};
use tetra::math::Vec2;
use tetra::input::{self, Key};
use tetra::{Context, ContextBuilder, State};
// visual consts
const SCREEN_WIDTH: i32 = 1280;
const SCREEN_HEIGHT: i32 = 720;
const FONT_SIZE: f32 = 32.0;
const PADDIN... | fn draw_paddle(ctx: &mut Context, paddle: &Paddle){
graphics::draw(ctx, &paddle.paddle_texture, paddle.position)
}
fn handle_inputs(&mut self, ctx: &mut Context){
if input::is_key_down(ctx, Key::W) {
self.player_paddle.position.y -= PADDLE_SPEED;
}
if input::is_k... | }
| random_line_split |
ffi.rs | // Take a look at the license at the top of the repository in the LICENSE file.
use core_foundation_sys::base::{mach_port_t, CFAllocatorRef};
use core_foundation_sys::dictionary::{CFDictionaryRef, CFMutableDictionaryRef};
use core_foundation_sys::string::CFStringRef;
use libc::{c_char, kern_return_t}; |
#[allow(non_camel_case_types)]
pub type io_object_t = mach_port_t;
#[allow(non_camel_case_types)]
pub type io_iterator_t = io_object_t;
#[allow(non_camel_case_types)]
pub type io_registry_entry_t = io_object_t;
// This is a hack, `io_name_t` should normally be `[c_char; 128]` but Rust makes it very annoying
// to dea... |
// Note: IOKit is only available on MacOS up until very recent iOS versions: https://developer.apple.com/documentation/iokit | random_line_split |
ffi.rs | // Take a look at the license at the top of the repository in the LICENSE file.
use core_foundation_sys::base::{mach_port_t, CFAllocatorRef};
use core_foundation_sys::dictionary::{CFDictionaryRef, CFMutableDictionaryRef};
use core_foundation_sys::string::CFStringRef;
use libc::{c_char, kern_return_t};
// Note: IOKit... | {
pub version: u16,
pub length: u16,
pub cpu_plimit: u32,
pub gpu_plimit: u32,
pub mem_plimit: u32,
}
#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))]
#[repr(C)]
pub struct KeyData_keyInfo_t {
pub data_size: u32,
pub data_type: ... | KeyData_pLimitData_t | identifier_name |
lib.rs | //! This crate allows running a process with a timeout, with the option to
//! terminate it automatically afterward. The latter is surprisingly difficult
//! to achieve on Unix, since process identifiers can be arbitrarily reassigned
//! when no longer used. Thus, it would be extremely easy to inadvertently
//! termina... | (&self, formatter: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
impl From<process::ExitStatus> for ExitStatus {
#[inline]
fn from(value: process::ExitStatus) -> Self {
#[cfg_attr(windows, allow(clippy::useless_conversion))]
Self(value.into())
}
}
/// Equivalen... | fmt | identifier_name |
lib.rs | //! This crate allows running a process with a timeout, with the option to
//! terminate it automatically afterward. The latter is surprisingly difficult
//! to achieve on Unix, since process identifiers can be arbitrarily reassigned
//! when no longer used. Thus, it would be extremely easy to inadvertently
//! termina... |
#[inline]
fn with_timeout(
&'a mut self,
time_limit: Duration,
) -> Self::ExitStatusTimeout {
Self::ExitStatusTimeout::new(self, time_limit)
}
#[inline]
fn with_output_timeout(self, time_limit: Duration) -> Self::OutputTimeout {
Self::OutputTimeout::new(self, t... | {
imp::Handle::new(self).map(Terminator)
} | identifier_body |
lib.rs | //! This crate allows running a process with a timeout, with the option to
//! terminate it automatically afterward. The latter is surprisingly difficult
//! to achieve on Unix, since process identifiers can be arbitrarily reassigned
//! when no longer used. Thus, it would be extremely easy to inadvertently
//! termina... | ///
/// Instances can only be constructed using [`ChildExt::terminator`].
#[derive(Debug)]
pub struct Terminator(imp::Handle);
impl Terminator {
/// Terminates a process as immediately as the operating system allows.
///
/// Behavior should be equivalent to calling [`Child::kill`] for the same
/// proc... | mod timeout;
/// A wrapper that stores enough information to terminate a process. | random_line_split |
app.rs | // vim: tw=80
use std::{
collections::{btree_map, BTreeMap},
error::Error,
mem,
num::NonZeroUsize,
ops::AddAssign,
};
use cfg_if::cfg_if;
use ieee754::Ieee754;
use nix::{
sys::time::TimeSpec,
time::{clock_gettime, ClockId},
};
use regex::Regex;
cfg_if! {
if #[cfg(target_os = "freebsd")... | {
name: String,
nunlinked: u64,
nunlinks: u64,
nread: u64,
reads: u64,
nwritten: u64,
writes: u64,
}
impl Snapshot {
fn compute(&self, prev: Option<&Self>, etime: f64) -> Element {
if let Some(prev) = prev {
Element {
name: self.na... | Snapshot | identifier_name |
app.rs | // vim: tw=80
use std::{
collections::{btree_map, BTreeMap},
error::Error,
mem,
num::NonZeroUsize,
ops::AddAssign,
};
use cfg_if::cfg_if;
use ieee754::Ieee754;
use nix::{
sys::time::TimeSpec,
time::{clock_gettime, ClockId},
};
use regex::Regex;
cfg_if! {
if #[cfg(target_os = "freebsd")... | } else {
match self.depth {
None => None,
Some(x) => NonZeroUsize::new(x.get() - 1),
}
}
}
pub fn on_minus(&mut self) {
self.sort_idx = match self.sort_idx {
Some(0) => None,
Some(old) => Some(old - 1),
... | None => NonZeroUsize::new(1),
Some(x) => NonZeroUsize::new(x.get() + 1),
} | random_line_split |
bip32.rs | FromBase58, ToBase58};
/// A chain code
pub struct ChainCode([u8,..32]);
impl_array_newtype!(ChainCode, u8, 32)
impl_array_newtype_show!(ChainCode)
impl_array_newtype_encodable!(ChainCode, u8, 32)
/// A fingerprint
pub struct Fingerprint([u8,..4]);
impl_array_newtype!(Fingerprint, u8, 4)
impl_array_ne... | data.slice(45, 78)).map_err(|e|
OtherBase58Error(e.to_string())))
})
}
}
#[cfg(test)]
mod tests {
use serialize::hex::FromHex;
use test::{Bencher, black_box};
use network::constants::{Network, Bitcoin};
use util::base58::{FromBase58, ToBase58};
use... | {
if data.len() != 78 {
return Err(InvalidLength(data.len()));
}
let cn_int = u64_from_be_bytes(data.as_slice(), 9, 4) as u32;
let child_number = if cn_int < (1 << 31) { Normal(cn_int) }
else { Hardened(cn_int - (1 << 31)) };
Ok(ExtendedPubKey {
network: match da... | identifier_body |
bip32.rs | FromBase58, ToBase58};
/// A chain code
pub struct ChainCode([u8,..32]);
impl_array_newtype!(ChainCode, u8, 32)
impl_array_newtype_show!(ChainCode)
impl_array_newtype_encodable!(ChainCode, u8, 32)
/// A fingerprint
pub struct Fingerprint([u8,..4]);
impl_array_newtype!(Fingerprint, u8, 4)
impl_array_ne... | (master: &ExtendedPrivKey, path: &[ChildNumber])
-> Result<ExtendedPrivKey, Error> {
let mut sk = *master;
for &num in path.iter() {
sk = try!(sk.ckd_priv(num));
}
Ok(sk)
}
/// Private->Private child key derivation
pub fn ckd_priv(&self, i: ChildNumber) -> Result<Extended... | from_path | identifier_name |
bip32.rs | FromBase58, ToBase58};
/// A chain code
pub struct ChainCode([u8,..32]);
impl_array_newtype!(ChainCode, u8, 32)
impl_array_newtype_show!(ChainCode)
impl_array_newtype_encodable!(ChainCode, u8, 32)
/// A fingerprint
pub struct Fingerprint([u8,..4]); | impl Default for Fingerprint {
fn default() -> Fingerprint { Fingerprint([0, 0, 0, 0]) }
}
/// Extended private key
#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Show)]
pub struct ExtendedPrivKey {
/// The network this key is to be used on
pub network: Network,
/// How many derivations this key is fro... | impl_array_newtype!(Fingerprint, u8, 4)
impl_array_newtype_show!(Fingerprint)
impl_array_newtype_encodable!(Fingerprint, u8, 4)
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.