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 |
|---|---|---|---|---|
decoder.rs | use crate::ebml;
use crate::schema::{Schema, SchemaDict};
use crate::vint::{read_vint, UnrepresentableLengthError};
use chrono::{DateTime, NaiveDateTime, Utc};
use err_derive::Error;
use log_derive::{logfn, logfn_inputs};
use std::convert::TryFrom;
pub trait ReadEbmlExt: std::io::Read {
#[logfn(ok = "TRACE", err =... | eadContentError {
#[error(display = "Date")]
Date(#[error(cause)] std::io::Error),
#[error(display = "Utf8")]
Utf8(#[error(cause)] std::io::Error),
#[error(display = "UnsignedInteger")]
UnsignedInteger(#[error(cause)] std::io::Error),
#[error(display = "Integer")]
Integer(#[error(cause)]... | // スタックからこのタグを捨てる
self.stack.pop();
}
Ok(true)
}
}
#[derive(Debug, Error)]
pub enum R | conditional_block |
decoder.rs | use crate::ebml;
use crate::schema::{Schema, SchemaDict};
use crate::vint::{read_vint, UnrepresentableLengthError};
use chrono::{DateTime, NaiveDateTime, Utc};
use err_derive::Error;
use log_derive::{logfn, logfn_inputs};
use std::convert::TryFrom;
pub trait ReadEbmlExt: std::io::Read {
#[logfn(ok = "TRACE", err =... |
}
impl From<ReadContentError> for DecodeError {
fn from(o: ReadContentError) -> Self {
DecodeError::ReadContent(o)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum State {
Tag,
Size,
Content,
}
pub struct Decoder<'a, D: SchemaDict<'a>> {
schema: &'a D,
... | {
DecodeError::ReadVint(o)
} | identifier_body |
decoder.rs | use crate::ebml;
use crate::schema::{Schema, SchemaDict};
use crate::vint::{read_vint, UnrepresentableLengthError};
use chrono::{DateTime, NaiveDateTime, Utc};
use err_derive::Error;
use log_derive::{logfn, logfn_inputs};
use std::convert::TryFrom;
pub trait ReadEbmlExt: std::io::Read {
#[logfn(ok = "TRACE", err =... | (o: ReadContentError) -> Self {
DecodeError::ReadContent(o)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum State {
Tag,
Size,
Content,
}
pub struct Decoder<'a, D: SchemaDict<'a>> {
schema: &'a D,
state: State,
buffer: Vec<u8>,
cursor: usize,
to... | from | identifier_name |
string_pool.rs | use crate::expat_external_h::XML_Char;
use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert};
use crate::lib::xmltok::{ENCODING, XML_Convert_Result};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec as BumpVec;
use fallible_collections::FallibleBox;
use libc::c_int;
use std::cell::{Cell, RefCell};
... | () -> Result<Self, ()> {
let bump = Bump::try_with_capacity(INIT_BLOCK_SIZE).map_err(|_| ())?;
let boxed_bump = Box::try_new(bump).map_err(|_| ())?;
Ok(StringPool(Some(InnerStringPool::new(
boxed_bump,
|bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))),
)... | try_new | identifier_name |
string_pool.rs | use crate::expat_external_h::XML_Char;
use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert};
use crate::lib::xmltok::{ENCODING, XML_Convert_Result};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec as BumpVec;
use fallible_collections::FallibleBox;
use libc::c_int;
use std::cell::{Cell, RefCell};
... |
/// Resets the current Bump and deallocates its contents.
/// The `inner` method must never be called here as it assumes
/// self.0 is never `None`
pub(crate) fn clear(&mut self) {
let mut inner_pool = self.0.take();
let mut bump = inner_pool.unwrap().into_head();
bump.reset(... | {
self.inner().rent(|vec| {
let mut vec = vec.borrow_mut();
while *s != 0 {
if !vec.append_char(*s) {
return false;
}
s = s.offset(1)
}
true
})
} | identifier_body |
string_pool.rs | use crate::expat_external_h::XML_Char;
use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert};
use crate::lib::xmltok::{ENCODING, XML_Convert_Result};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec as BumpVec;
use fallible_collections::FallibleBox;
use libc::c_int;
use std::cell::{Cell, RefCell};
... | pool.copy_c_string(S.as_ptr())
};
assert_eq!(new_string.unwrap(), [A, C, D, D, C, NULL]);
assert!(pool.append_char(B));
pool.current_slice(|s| assert_eq!(s, [B]));
let new_string2 = unsafe {
pool.copy_c_string_n(S.as_ptr(), 4)
};
assert_eq!(new_string2.unwrap(), [B, C, D, ... | let new_string = unsafe { | random_line_split |
string_pool.rs | use crate::expat_external_h::XML_Char;
use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert};
use crate::lib::xmltok::{ENCODING, XML_Convert_Result};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec as BumpVec;
use fallible_collections::FallibleBox;
use libc::c_int;
use std::cell::{Cell, RefCell};
... |
s = s.offset(1)
}
true
})
}
/// Resets the current Bump and deallocates its contents.
/// The `inner` method must never be called here as it assumes
/// self.0 is never `None`
pub(crate) fn clear(&mut self) {
let mut inner_pool = self.0.take(... | {
return false;
} | conditional_block |
lib.rs | //! A library for analysis of Boolean networks. As of now, the library supports:
//! - Regulatory graphs with monotonicity and observability constraints.
//! - Boolean networks, possibly with partially unknown and parametrised update functions.
//! - Full SBML-qual support for import/export as well as custom string ... | {
name: String,
arity: u32,
}
/// Describes an interaction between two `Variables` in a `RegulatoryGraph`
/// (or a `BooleanNetwork`).
///
/// Every regulation can be *monotonous*, and can be set as *observable*:
///
/// - Monotonicity is either *positive* or *negative* and signifies that the influence of th... | Parameter | identifier_name |
lib.rs | //! A library for analysis of Boolean networks. As of now, the library supports:
//! - Regulatory graphs with monotonicity and observability constraints.
//! - Boolean networks, possibly with partially unknown and parametrised update functions.
//! - Full SBML-qual support for import/export as well as custom string ... | pub struct ModelAnnotation {
value: Option<String>,
inner: HashMap<String, ModelAnnotation>,
} | random_line_split | |
post_trees.rs | use std::collections::HashMap;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::{Scope, Stream};
use colored::*;
use crate::event::{Event, ID};
use crate::operators::active_posts::StatUpdate;
use crate::operators::active_pos... | (&self, num_spaces: usize) {
let spaces = " ".repeat(num_spaces);
println!("{}---- ooo_events", spaces);
for (post_id, events) in self.ooo_events.iter() {
println!(
"{}{:?} -- \n{} {}",
spaces,
post_id,
spaces,
... | dump_ooo_events | identifier_name |
post_trees.rs | use std::collections::HashMap;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::{Scope, Stream};
use colored::*;
use crate::event::{Event, ID};
use crate::operators::active_posts::StatUpdate;
use crate::operators::active_pos... | let node = Node { person_id: comment.person_id, root_post_id: root_post_id };
self.root_of.insert(comment.comment_id, node);
(Some(reply_to_id), Some(root_post_id))
} else {
(Some(reply_to_id), None)
}
... | {
match event {
Event::Post(post) => {
let node = Node { person_id: post.person_id, root_post_id: post.post_id };
self.root_of.insert(post.post_id, node);
(None, Some(post.post_id))
}
Event::Like(like) => {
// li... | identifier_body |
post_trees.rs | use std::collections::HashMap;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::{Scope, Stream};
use colored::*;
use crate::event::{Event, ID};
use crate::operators::active_posts::StatUpdate;
use crate::operators::active_pos... | /// will handle only a subset of the posts.
///
/// "Reply to comments" events are broadcasted to all workers
/// as they don't carry the root post id in the payload.
///
/// When the `post_trees` operator receives an Reply event that
/// cannot match to any currently received comment, it stores
/// it in an out-of-ord... | /// In case of multiple workers, an upstream `exchange` operator
/// will partition the events by root post id. Thus this operator | random_line_split |
worker.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_cac... | (
&mut self,
module_specifier: &ModuleSpecifier,
) -> Result<(), AnyError> {
let id = self.preload_main_module(module_specifier).await?;
self.evaluate_module(id).await
}
fn wait_for_inspector_session(&mut self) {
if self.should_break_on_first_statement {
self
.js_runtime
.... | execute_main_module | identifier_name |
worker.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_cac... | root_cert_store_provider: Default::default(),
npm_resolver: Default::default(),
blob_store: Default::default(),
extensions: Default::default(),
startup_snapshot: Default::default(),
create_params: Default::default(),
bootstrap: Default::default(),
stdio: Default::default(... | {
Self {
create_web_worker_cb: Arc::new(|_| {
unimplemented!("web workers are not supported")
}),
fs: Arc::new(deno_fs::RealFs),
module_loader: Rc::new(FsModuleLoader),
seed: None,
unsafely_ignore_certificate_errors: Default::default(),
should_break_on_first_stateme... | identifier_body |
worker.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_cac... |
let bootstrap_fn_global = {
let context = js_runtime.main_context();
let scope = &mut js_runtime.handle_scope();
let context_local = v8::Local::new(scope, context);
let global_obj = context_local.global(scope);
let bootstrap_str =
v8::String::new_external_onebyte_static(scope... | {
server.register_inspector(
main_module.to_string(),
&mut js_runtime,
options.should_break_on_first_statement
|| options.should_wait_for_inspector_session,
);
// Put inspector handle into the op state so we can put a breakpoint when
// executing a CJS entrypoi... | conditional_block |
worker.rs | // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use deno_broadcast_channel::InMemoryBroadcastChannel;
use deno_cac... | state = |state, options| {
state.put::<PermissionsContainer>(options.permissions);
state.put(ops::UnstableChecker { unstable: options.unstable });
state.put(ops::TestingFeaturesEnabled(options.enable_testing_features));
},
);
// Permissions: many ops depend on this
let u... | permissions: PermissionsContainer,
unstable: bool,
enable_testing_features: bool,
}, | random_line_split |
install.rs | use crate::alias::create_alias;
use crate::archive::{self, extract::Error as ExtractError, extract::Extract};
use crate::config::FrumConfig;
use crate::input_version::InputVersion;
use crate::outln;
use crate::version::Version;
use crate::version_file::get_user_version_for_directory;
use anyhow::Result;
use colored::Co... | ;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::Command;
use crate::config::FrumConfig;
use crate::version::Version;
use tempfile::tempdir;
#[test]
fn test_install_second_version() {
let config = FrumConfig {
base_dir: Some(tempdir().unwrap().p... | {
return Err(FrumError::CantBuildRuby {
stderr: format!(
"make install: {}",
String::from_utf8_lossy(&make_install.stderr).to_string()
),
});
} | conditional_block |
install.rs | use crate::alias::create_alias;
use crate::archive::{self, extract::Error as ExtractError, extract::Extract};
use crate::config::FrumConfig;
use crate::input_version::InputVersion;
use crate::outln;
use crate::version::Version;
use crate::version_file::get_user_version_for_directory;
use anyhow::Result;
use colored::Co... | () {
let config = FrumConfig {
base_dir: Some(tempdir().unwrap().path().to_path_buf()),
..Default::default()
};
Install {
version: Some(InputVersion::Full(Version::Semver(
semver::Version::parse("2.6.4").unwrap(),
))),
c... | test_install_default_version | identifier_name |
install.rs | use crate::alias::create_alias;
use crate::archive::{self, extract::Error as ExtractError, extract::Extract};
use crate::config::FrumConfig;
use crate::input_version::InputVersion;
use crate::outln;
use crate::version::Version;
use crate::version_file::get_user_version_for_directory;
use anyhow::Result; | use log::debug;
use reqwest::Url;
use std::io::prelude::*;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum FrumError {
#[error(transparent)]
HttpError(#[from] reqwest::Error),
#[error(transparent)]
IoError(#[from] std::io::E... | use colored::Colorize; | random_line_split |
install.rs | use crate::alias::create_alias;
use crate::archive::{self, extract::Error as ExtractError, extract::Extract};
use crate::config::FrumConfig;
use crate::input_version::InputVersion;
use crate::outln;
use crate::version::Version;
use crate::version_file::get_user_version_for_directory;
use anyhow::Result;
use colored::Co... |
fn package_url(mirror_url: Url, version: &Version) -> Url {
debug!("pakage url");
Url::parse(&format!(
"{}/{}/{}",
mirror_url.as_str().trim_end_matches('/'),
match version {
Version::Semver(version) => format!("{}.{}", version.major, version.minor),
_ => unreach... | {
#[cfg(unix)]
let extractor = archive::tar_xz::TarXz::new(response);
#[cfg(windows)]
let extractor = archive::zip::Zip::new(response);
extractor
.extract_into(path)
.map_err(|source| FrumError::ExtractError { source })?;
Ok(())
} | identifier_body |
resolve_recovers_from_http_errors.rs | // Copyright 2019 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.
/// This module tests the property that pkg_resolver does not enter a bad
/// state (successfully handles retries) when the TUF server errors while
/// ser... |
#[fuchsia::test]
async fn second_resolve_succeeds_disconnect_before_far_complete() {
let pkg = PackageBuilder::new("second_resolve_succeeds_disconnect_before_far_complete")
.add_resource_at(
"meta/large_file",
vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING].as_slice(),
... | {
let blob = vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING];
let pkg = PackageBuilder::new("second_resolve_succeeds_when_blob_errors_mid_download")
.add_resource_at("blobbity/blob", blob.as_slice())
.build()
.await
.unwrap();
let path_to_override = format!(
... | identifier_body |
resolve_recovers_from_http_errors.rs | // Copyright 2019 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.
/// This module tests the property that pkg_resolver does not enter a bad
/// state (successfully handles retries) when the TUF server errors while
/// ser... | .await
.unwrap();
verify_resolve_fails_then_succeeds(
pkg,
responder::ForPath::new("/2.snapshot.json", responder::OneByteShortThenDisconnect),
fidl_fuchsia_pkg::ResolveError::Internal,
)
.await
}
// The hyper clients used by the pkg-resolver to download blobs and TUF me... | let pkg = PackageBuilder::new("second_resolve_succeeds_when_tuf_metadata_update_fails")
.build() | random_line_split |
resolve_recovers_from_http_errors.rs | // Copyright 2019 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.
/// This module tests the property that pkg_resolver does not enter a bad
/// state (successfully handles retries) when the TUF server errors while
/// ser... | () {
let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_blob_404", 1).await;
let path_to_override = format!(
"/blobs/{}",
MerkleTree::from_reader(
extra_blob_contents("second_resolve_succeeds_when_blob_404", 0).as_slice()
)
.expect("merkle slice")
... | second_resolve_succeeds_when_blob_404 | identifier_name |
value_textbox.rs | // Copyright 2021 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | last_known_data: None,
validate_while_editing: true,
update_data_while_editing: false,
old_buffer: String::new(),
buffer: String::new(),
force_selection: None,
}
}
/// Builder-style method to set an optional [`ValidationDelegate`] ... | random_line_split | |
value_textbox.rs | // Copyright 2021 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | (&mut self, ctx: &mut EventCtx, data: &T) {
self.is_editing = false;
self.buffer = self.formatter.format(data);
ctx.request_update();
ctx.resign_focus();
self.send_event(ctx, TextBoxEvent::Cancel);
}
fn begin(&mut self, ctx: &mut EventCtx, data: &T) {
self.is_edi... | cancel | identifier_name |
value_textbox.rs | // Copyright 2021 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | }
self.send_event(ctx, TextBoxEvent::Invalid(err));
// our content isn't valid
// ideally we would flash the background or something
false
}
}
}
fn cancel(&mut self, ctx: &mut EventCtx, data: &T) {
self... | {
match self.formatter.value(&self.buffer) {
Ok(new_data) => {
*data = new_data;
self.buffer = self.formatter.format(data);
self.is_editing = false;
ctx.request_update();
self.send_event(ctx, TextBoxEvent::Complete);
... | identifier_body |
has_loc.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use proc_macro2::Ident;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use quote::ToToken... | (input: TokenStream) -> Result<TokenStream> {
let input = syn::parse2::<DeriveInput>(input)?;
match &input.data {
Data::Enum(data) => build_has_loc_enum(&input, data),
Data::Struct(data) => build_has_loc_struct(&input, data),
Data::Union(_) => Err(Error::new(input.span(), "Union not hand... | build_has_loc | identifier_name |
has_loc.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use proc_macro2::Ident;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use quote::ToToken... | }));
}
NestedMeta::Lit(Lit::Str(n)) => {
return Ok(Some(Field {
kind: FieldKind::Named(Cow::Owned(Ident::new(
&n.value(),
... | random_line_split | |
has_loc.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use proc_macro2::Ident;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use quote::ToToken... |
quote!(#field.loc_id())
}
FieldKind::None => todo!(),
FieldKind::Numbered(_) => todo!(),
}
} else {
let field = data
.fields
.iter()
.enumerate()
.map(|(i, field)| (i, field, SimpleType::from_type(&field... | {
// struct Foo {
// ...
// loc: LocId,
// }
let struct_name = &input.ident;
let default_select_field = handle_has_loc_attr(&input.attrs)?;
let loc_field = if let Some(f) = default_select_field {
match f.kind {
FieldKind::Named(name) => {
let name = n... | identifier_body |
main.rs | extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::GameControllerSubsystem;
use sdl2::controller::GameController;
use sdl2::controller::Button;
use sdl2::render::Canvas;
use sdl2::render::Texture;
use sdl2::render::TextureCreator;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use sdl2::control... |
}
}
Err(e) => {
panic!("{}", e);
}
}
}
fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T {
match res {
Ok(r) => {
r
}
Err(e) => {
panic!("{}", e);
}
}
}
fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) {
//Draw the title
let dst = {
... | {
panic!("{}", e);
} | conditional_block |
main.rs | extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::GameControllerSubsystem;
use sdl2::controller::GameController;
use sdl2::controller::Button;
use sdl2::render::Canvas;
use sdl2::render::Texture;
use sdl2::render::TextureCreator;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use sdl2::control... |
fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T {
match res {
Ok(r) => {
r
}
Err(e) => {
panic!("{}", e);
}
}
}
fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) {
//Draw the title
let dst = {
let query = texture.query();
let xpos = (SCREEN_W... | {
let color = Color::RGB(0, 255, 0);
match font.render(text).solid(color) {
Ok(surface) => {
match texture_creator.create_texture_from_surface(surface) {
Ok(t) => {
t
}
Err(e) => {
panic!("{}", e);
}
}
}
Err(e) => {
panic!("{}", e);
}
}
} | identifier_body |
main.rs | extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::GameControllerSubsystem;
use sdl2::controller::GameController;
use sdl2::controller::Button;
use sdl2::render::Canvas;
use sdl2::render::Texture;
use sdl2::render::TextureCreator;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use sdl2::control... | if!going_to_next_round {
//Start the timer
round_transition_timer = ticks;
//Increment round number
game_state.round_number += 1;
//Create round # texture
round_number_texture = text_texture(&format!("Round {}", game_state.round_number), &texture_creator, &font);
going_... | random_line_split | |
main.rs | extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::GameControllerSubsystem;
use sdl2::controller::GameController;
use sdl2::controller::Button;
use sdl2::render::Canvas;
use sdl2::render::Texture;
use sdl2::render::TextureCreator;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use sdl2::control... | <T: std::cmp::PartialOrd>(value: T, lower_bound: T, upper_bound: T) -> T{
let mut clamped_value = value;
if clamped_value < lower_bound {
clamped_value = lower_bound;
}
if clamped_value > upper_bound {
clamped_value = upper_bound;
}
clamped_value
}
fn main() {
let sdl_context = sdl2::init().unwrap();
let v... | clamp | identifier_name |
q19.rs | /*
LDBC SNB BI query 19. Interaction path between cities
https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf
*/
use differential_dataflow::collection::AsCollection;
use differential_dataflow::input::Input;
use differential_dataflow::operators::{Join, Count, Iterate, Reduce};
use timely::dataflow::ProbeHandle;... | (path: String, change_path: String, params: &Vec<String>) {
// unpack parameters
let param_city1 = params[0].parse::<u64>().unwrap();
let param_city2 = params[1].parse::<u64>().unwrap();
timely::execute_from_args(std::env::args(), move |worker| {
let mut timer = worker.timer();
let inde... | run | identifier_name |
q19.rs | /*
LDBC SNB BI query 19. Interaction path between cities
https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf
*/
use differential_dataflow::collection::AsCollection;
use differential_dataflow::input::Input;
use differential_dataflow::operators::{Join, Count, Iterate, Reduce};
use timely::dataflow::ProbeHandle;... | worker.dataflow::<usize,_,_>(|scope| {
let (located_in_input, locatedin) = scope.new_collection::<DynamicConnection, _>();
let (knows_input, knows) = scope.new_collection::<DynamicConnection, _>();
// creators for comments AND posts
let (has_creator_input, has_cr... | {
// unpack parameters
let param_city1 = params[0].parse::<u64>().unwrap();
let param_city2 = params[1].parse::<u64>().unwrap();
timely::execute_from_args(std::env::args(), move |worker| {
let mut timer = worker.timer();
let index = worker.index();
let peers = worker.peers();
... | identifier_body |
q19.rs | /*
LDBC SNB BI query 19. Interaction path between cities
https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf
*/
use differential_dataflow::collection::AsCollection;
use differential_dataflow::input::Input;
use differential_dataflow::operators::{Join, Count, Iterate, Reduce};
use timely::dataflow::ProbeHandle;... | &knows.map(|conn| (conn.a().clone(), conn.b().clone()))
)
;
// calculate weights starting from personB
let weights = bi_knows
.join_map( // join messages of personB
&has_creator.map(|conn| (conn.b().clone(), ... | random_line_split | |
lib.rs | HOSTNAME";
/// This variable holds the host name for the parent edge device. This name is used
/// by the edge agent to connect to parent edge hub for identity and twin operations.
const GATEWAY_HOSTNAME_KEY: &str = "IOTEDGE_GATEWAYHOSTNAME";
/// This variable holds the host name for the edge device. This name is use... | &iot_hub_name,
parent_hostname,
&device_id,
&settings,
runt_rx,
)?;
// This mpsc sender/receiver is used for getting notifications from the mgmt service
// indicating that the daemon should shut down and attempt to reprovision the device.
let mgmt_stop_and_reprov... | {
let iot_hub_name = workload_config.iot_hub_name().to_string();
let device_id = workload_config.device_id().to_string();
let (mgmt_tx, mgmt_rx) = oneshot::channel();
let (mgmt_stop_and_reprovision_tx, mgmt_stop_and_reprovision_rx) = mpsc::unbounded();
let mgmt = start_management::<M>(settings, ru... | identifier_body |
lib.rs | _runtime,
create_socket_channel_snd,
)?;
let url = settings.endpoints().aziot_identityd_url().clone();
let client = Arc::new(Mutex::new(identity_client::IdentityClient::new(
aziot_identity_common_http::ApiVersion::V2020_09_01,
&url,
)));
let ... | Error | identifier_name | |
lib.rs | UBHOSTNAME";
/// This variable holds the host name for the parent edge device. This name is used
/// by the edge agent to connect to parent edge hub for identity and twin operations.
const GATEWAY_HOSTNAME_KEY: &str = "IOTEDGE_GATEWAYHOSTNAME";
/// This variable holds the host name for the edge device. This name is u... | // Normally aziot-edged will stop all modules when it shuts down. But if it crashed,
// modules will continue to run. On Linux systems where aziot-edged is responsible for
// creating/binding the socket (e.g., CentOS 7.5, which uses systemd but does not
// support systemd socket activati... | };
};
info!("Finished provisioning edge device.");
| random_line_split |
day04.rs | //! # --- Day 4: Passport Processing ---
//!
//! You arrive at the airport only to realize that you grabbed your North Pole
//! Credentials instead of your passport. While these documents are extremely
//! similar, North Pole Credentials aren't issued by a country and therefore
//! aren't actually valid documentation f... | .filter_map(|x| Passport::from_hashmap(x))
.collect();
assert_eq!(
passports,
vec![
Passport {
ecl: "gry".into(),
pid: "860033327".into(),
eyr: 2020,
hcl: "#fffffd".into... | random_line_split | |
day04.rs | //! # --- Day 4: Passport Processing ---
//!
//! You arrive at the airport only to realize that you grabbed your North Pole
//! Credentials instead of your passport. While these documents are extremely
//! similar, North Pole Credentials aren't issued by a country and therefore
//! aren't actually valid documentation f... | () {
let input = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm";
let (_, kvs) = kvlist_parser(input).unwrap();
assert_eq!(
kvs,
vec![
("ecl", "gry"),
("pid", "860033327"),
("eyr", "2020"),
... | test_kvlist_parser | identifier_name |
tls_pstm_montgomery_reduce.rs |
use libc;
use libc::free;
extern "C" {
#[no_mangle]
fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void;
#[no_mangle]
fn xzalloc(size: size_t) -> *mut libc::c_void;
#[no_mangle]
fn pstm_clamp(a: *mut pstm_int);
#[no_mangle]
fn pstm_cmp_mag(a: *mut pstm_int, b: *mut ... | (
mut a: *mut pstm_int,
mut m: *mut pstm_int,
mut mp: pstm_digit,
mut paD: *mut pstm_digit,
mut paDlen: uint32,
) -> int32 {
let mut c: *mut pstm_digit = 0 as *mut pstm_digit; //bbox: was int16
let mut _c: *mut pstm_digit = 0 as *mut pstm_digit;
let mut tmpm: *mut pstm_digit = 0 as *mut pstm_digit;
le... | pstm_montgomery_reduce | identifier_name |
tls_pstm_montgomery_reduce.rs |
use libc;
use libc::free;
extern "C" {
#[no_mangle]
fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void;
#[no_mangle]
fn xzalloc(size: size_t) -> *mut libc::c_void;
#[no_mangle]
fn pstm_clamp(a: *mut pstm_int);
#[no_mangle]
fn pstm_cmp_mag(a: *mut pstm_int, b: *mut ... |
/* copy the input */
oldused = (*a).used;
x = 0i32;
while x < oldused {
*c.offset(x as isize) = *(*a).dp.offset(x as isize);
x += 1
}
x = 0i32;
while x < pa {
let mut cy: pstm_digit = 0i32 as pstm_digit;
/* get Mu for this round */
mu = (*c.offset(x as isize)).wrapping_mul(mp);
_c... | {
c = xzalloc((2i32 * pa + 1i32) as size_t) as *mut pstm_digit
//bbox
} | conditional_block |
tls_pstm_montgomery_reduce.rs | use libc;
use libc::free;
extern "C" {
#[no_mangle]
fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void;
#[no_mangle]
fn xzalloc(size: size_t) -> *mut libc::c_void;
#[no_mangle]
fn pstm_clamp(a: *mut pstm_int);
#[no_mangle]
fn pstm_cmp_mag(a: *mut pstm_int, b: *mut ps... | * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This General Public License does NOT permit incorporating this software
* into proprietary programs. If you are unable to comply with the GPL, a
* commercial license for this software may be purchased fr... | *
* The latest version of this code is available at http://www.matrixssl.org
*
* This software is open source; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by | random_line_split |
main.rs | use std::convert::TryInto;
use std::str::FromStr;
use anyhow::{anyhow, Context, Result};
use clap::{ArgEnum, Clap};
use gloryctl::macros::Event;
use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice};
#[derive(Clap)]
pub struct Opts {
#[clap(subcommand)]
cmd: Command,
}
#[derive(Clap)]
e... |
}
Rgb::Tail { speed, brightness } => {
conf.rgb_current_effect = Effect::Tail;
if let Some(spd) = speed {
conf.rgb_effect_parameters.tail.speed = spd.into();
}
if let Some(br) = brightness {
... | {
conf.rgb_effect_parameters.breathing.count = colors.len().try_into()?;
for (i, c) in colors.iter().enumerate() {
conf.rgb_effect_parameters.breathing.colors[i] = *c;
}
} | conditional_block |
main.rs | use std::convert::TryInto;
use std::str::FromStr;
use anyhow::{anyhow, Context, Result};
use clap::{ArgEnum, Clap};
use gloryctl::macros::Event;
use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice};
#[derive(Clap)]
pub struct Opts {
#[clap(subcommand)]
cmd: Command,
}
#[derive(Clap)]
e... | (s: &str) -> Result<Self, Self::Err> {
let (btn, act) = s
.split_once(':')
.context("Format: button:action-type[:action-params]")?;
let which = usize::from_str(btn)?;
let action = ButtonAction::from_str(act)?;
Ok(Self { which, action })
}
}
#[derive(Clap)]
#[cl... | from_str | identifier_name |
main.rs | use std::convert::TryInto;
use std::str::FromStr;
use anyhow::{anyhow, Context, Result};
use clap::{ArgEnum, Clap};
use gloryctl::macros::Event;
use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice};
#[derive(Clap)]
pub struct Opts {
#[clap(subcommand)]
cmd: Command,
}
#[derive(Clap)]
e... | }
}
impl Macro {
fn run(&self, dev: &mut GloriousDevice) -> Result<()> {
if self.bank > 3 {
return Err(anyhow!(
r"Only 2 macro banks are supported for now,
TODO find out how many the hardware supports without bricking it"
));
}
dev... |
conf.fixup_dpi_metadata();
dev.send_config(&conf)?;
Ok(()) | random_line_split |
proto2.rs | /*!
proto2.rs
A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29,
this supersedes the `grel::protocol` lib.
2020-01-23
*/
use serde::{Serialize, Deserialize};
/** The `Op` enum represents one of the `Room` operator subcommands. It is
used in the `Msg::Op(...)` variant of the `Msg` enum.
*/
#... | println!("Msg::Logout variant");
let m = Msg::logout("You have been logged out because you touch yourself at night.");
test_serde(&m);
println!("Msg::Name variant");
let m = Msg::Name(String::from("New Lewser"));
test_serde(&m);
println!("Msg::Jo... | {
println!("Msg::Text variant");
let m = Msg::Text {
who: String::from("gre luser"),
lines: vec!["This is a first line of text.".to_string(),
"Following the first is a second line of text.".to_string()],
};
test_serde(&m);
... | identifier_body |
proto2.rs | /*!
proto2.rs
A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29,
this supersedes the `grel::protocol` lib.
2020-01-23
*/
use serde::{Serialize, Deserialize};
/** The `Op` enum represents one of the `Room` operator subcommands. It is
used in the `Msg::Op(...)` variant of the `Msg` enum.
*/
#... | Misc {
what: "name".to_string(),
data: vec!["old name".to_string(),
"new name".to_string()],
alt: "\"old name\" is now known as \"new name\".".to_string(),
};
// when the Room operator changes
Misc {
what: "new_op".to_string(),
data: ["New ... | // when a user changes his or her name | random_line_split |
proto2.rs | /*!
proto2.rs
A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29,
this supersedes the `grel::protocol` lib.
2020-01-23
*/
use serde::{Serialize, Deserialize};
/** The `Op` enum represents one of the `Room` operator subcommands. It is
used in the `Msg::Op(...)` variant of the `Msg` enum.
*/
#... | (m: &Msg) {
let stringd = serde_json::to_string_pretty(m).unwrap();
println!("{}\n", &stringd);
let newm: Msg = serde_json::from_str(&stringd).unwrap();
assert_eq!(*m, newm);
}
#[test]
fn visual_serde() {
println!("Msg::Text variant");
let m = Msg::Text {... | test_serde | identifier_name |
promise_future_glue.rs | //! Gluing Rust's `Future` and JavaScript's `Promise` together.
//!
//! JavaScript's `Promise` and Rust's `Future` are two abstractions with the
//! same goal: asynchronous programming with eventual values. Both `Promise`s
//! and `Future`s represent a value that may or may not have been computed
//! yet. However, the ... | <'a>(
waiting: &'a mut RentToOwn<'a, WaitingOnInner<F>>,
) -> Poll<AfterWaitingOnInner<F>, GenericVoid<F>> {
let error = match waiting.future.poll() {
Ok(Async::NotReady) => {
return Ok(Async::NotReady);
}
Ok(Async::Ready(t)) => {
l... | poll_waiting_on_inner | identifier_name |
promise_future_glue.rs | //! Gluing Rust's `Future` and JavaScript's `Promise` together.
//!
//! JavaScript's `Promise` and Rust's `Future` are two abstractions with the
//! same goal: asynchronous programming with eventual values. Both `Promise`s
//! and `Future`s represent a value that may or may not have been computed
//! yet. However, the ... | enum Future2Promise<F>
where
F: Future,
<F as Future>::Item: ToJSValConvertible,
<F as Future>::Error: ToJSValConvertible,
{
/// Initially, we are waiting on the inner future to be ready or error.
#[state_machine_future(start, transitions(Finished, NotifyingOfError))]
WaitingOnInner {
fu... | random_line_split | |
promise_future_glue.rs | //! Gluing Rust's `Future` and JavaScript's `Promise` together.
//!
//! JavaScript's `Promise` and Rust's `Future` are two abstractions with the
//! same goal: asynchronous programming with eventual values. Both `Promise`s
//! and `Future`s represent a value that may or may not have been computed
//! yet. However, the ... | e
} else {
return ready(Finished(PhantomData));
}
}
}
Err(error) => {
let cx = JsRuntime::get();
unsafe {
rooted!(in(cx) let mut val = jsva... | {
let error = match waiting.future.poll() {
Ok(Async::NotReady) => {
return Ok(Async::NotReady);
}
Ok(Async::Ready(t)) => {
let cx = JsRuntime::get();
unsafe {
rooted!(in(cx) let mut val = jsval::UndefinedVa... | identifier_body |
lib.rs | //! An implementation of the [MD6 hash function](http://groups.csail.mit.edu/cis/md6), via FFI to reference implementation.
//!
//! For more information about MD6 visit its [official homepage](http://groups.csail.mit.edu/cis/md6).
//!
//! There are two APIs provided: one for single-chunk hashing and one for hashing of ... | ///
/// Storing and verifying results of all possible sizes.
///
/// ```
/// # use md6::Md6;
/// # use std::iter::FromIterator;
/// let mut result_64 = [0; 8];
/// let mut result_128 = [0; 16];
/// let mut result_256 = [0; 32];
/// let mut result_512 = [0; 64];
///
/// l... | ///
/// # Examples | random_line_split |
lib.rs | //! An implementation of the [MD6 hash function](http://groups.csail.mit.edu/cis/md6), via FFI to reference implementation.
//!
//! For more information about MD6 visit its [official homepage](http://groups.csail.mit.edu/cis/md6).
//!
//! There are two APIs provided: one for single-chunk hashing and one for hashing of ... | _state(&mut self.raw_state);
}
}
impl Error for Md6Error {
fn description(&self) -> &str {
match self {
&Md6Error::Fail => "Generic MD6 fail",
&Md6Error::BadHashbitlen => "Incorrect hashbitlen",
}
}
}
impl From<i32> for Md6Error {
/// Passing incorrect error va... | hash | identifier_name |
lib.rs | //!
//! Basic account support with an authenticator. Primarly used for development/testing.
//! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts.
//!
use anyhow::{bail, ensure};
use borsh::{BorshDeserialize, BorshSerialize};
use exonum_crypto::{hash, PublicKey, PUBLIC_KE... |
}
}
fn handle_query(
&self,
path: &str,
key: Vec<u8>,
view: &StoreView,
) -> Result<Vec<u8>, anyhow::Error> {
ensure!(key.len() > 0, "bad account key");
// return a serialized account for the given id.
match path {
"/" => {
... | {
let store = AccountStore::new();
let caller_acct = store.get(ctx.sender(), &view);
ensure!(caller_acct.is_some(), "user not found");
let acct = caller_acct.unwrap();
let updated = acct.update_pubkey(pubkey);
store.put(upd... | conditional_block |
lib.rs | //!
//! Basic account support with an authenticator. Primarly used for development/testing.
//! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts.
//!
use anyhow::{bail, ensure};
use borsh::{BorshDeserialize, BorshSerialize};
use exonum_crypto::{hash, PublicKey, PUBLIC_KE... |
pub struct AccountModule {
// PublicKeys of genesis accounts
genesis: Vec<[u8; 32]>,
}
impl AccountModule {
pub fn new(genesis: Vec<[u8; 32]>) -> Self {
Self { genesis }
}
}
impl AppModule for AccountModule {
fn name(&self) -> String {
ACCOUNT_APP_NAME.into()
}
// Load ge... | #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)]
pub enum Msgs {
Create(PublicKeyBytes),
ChangePubKey(PublicKeyBytes),
} | random_line_split |
lib.rs | //!
//! Basic account support with an authenticator. Primarly used for development/testing.
//! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts.
//!
use anyhow::{bail, ensure};
use borsh::{BorshDeserialize, BorshSerialize};
use exonum_crypto::{hash, PublicKey, PUBLIC_KE... | {
Create(PublicKeyBytes),
ChangePubKey(PublicKeyBytes),
}
pub struct AccountModule {
// PublicKeys of genesis accounts
genesis: Vec<[u8; 32]>,
}
impl AccountModule {
pub fn new(genesis: Vec<[u8; 32]>) -> Self {
Self { genesis }
}
}
impl AppModule for AccountModule {
fn name(&self... | Msgs | identifier_name |
lib.rs | //!
//! Basic account support with an authenticator. Primarly used for development/testing.
//! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts.
//!
use anyhow::{bail, ensure};
use borsh::{BorshDeserialize, BorshSerialize};
use exonum_crypto::{hash, PublicKey, PUBLIC_KE... |
#[test]
fn test_account_authenticator() {
// Check signature verification and nonce rules are enforced
let app = AppBuilder::new()
.set_authenticator(AccountAuthenticator {})
.with_app(AccountModule::new(get_genesis_accounts()));
let mut tester = TestKit::create(... | {
let mut tx = SignedTransaction::create(
user,
ACCOUNT_APP_NAME,
Msgs::Create([1u8; 32]), // fake data
nonce,
);
tx.sign(&secret_key);
tx
} | identifier_body |
packet_handler.rs | // Copyright 2020-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use bee_gossip::Multiaddr;
use futures::{
channel::oneshot,
future::{self, FutureExt},
stream::StreamExt,
};
use log::trace;
use tokio::select;
use tokio_stream::wrappers::UnboundedReceiverStream;
use crate::packets::{HeaderPacket... |
}
// Get the requested bytes. This will not panic because the loop above only exists if we
// have enough bytes to do this step.
let bytes = &self.buffer[self.offset..][..len];
// Increase the offset by the length of the byte slice.
self.offset += len;
bytes
... | {
// If we received an event, we push it to the buffer.
self.push_event(event);
} | conditional_block |
packet_handler.rs | // Copyright 2020-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use bee_gossip::Multiaddr;
use futures::{
channel::oneshot,
future::{self, FutureExt},
stream::StreamExt,
};
use log::trace;
use tokio::select;
use tokio_stream::wrappers::UnboundedReceiverStream;
use crate::packets::{HeaderPacket... | (receiver: EventRecv, shutdown: ShutdownRecv, address: Multiaddr) -> Self {
Self {
events: EventHandler::new(receiver),
shutdown,
// The handler should read a header first.
state: ReadState::Header,
address,
}
}
/// Fetch the header and... | new | identifier_name |
packet_handler.rs | // Copyright 2020-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use bee_gossip::Multiaddr;
use futures::{
channel::oneshot,
future::{self, FutureExt},
stream::StreamExt,
};
use log::trace;
use tokio::select;
use tokio_stream::wrappers::UnboundedReceiverStream;
use crate::packets::{HeaderPacket... | self.push_event(event);
}
}
// Get the requested bytes. This will not panic because the loop above only exists if we
// have enough bytes to do this step.
let bytes = &self.buffer[self.offset..][..len];
// Increase the offset by the length of the byte ... | random_line_split | |
instance.rs | use crate::{
create_idx_struct,
data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec},
small_indices::SmallIdx,
};
use anyhow::{anyhow, ensure, Error, Result};
use log::{info, trace};
use serde::Deserialize;
use std::{
fmt::{self, Display, Write as _},
io::{BufRead, Write},
mem,
... | }
/// Edges incident to a node, sorted by increasing indices.
pub fn node(
&self,
node: NodeIdx,
) -> impl Iterator<Item = EdgeIdx> + ExactSizeIterator + Clone + '_ {
self.node_incidences[node.idx()]
.iter()
.map(|(_, (edge, _))| *edge)
}
/// Nodes... | self.edge_incidences.len() | random_line_split |
instance.rs | use crate::{
create_idx_struct,
data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec},
small_indices::SmallIdx,
};
use anyhow::{anyhow, ensure, Error, Result};
use log::{info, trace};
use serde::Deserialize;
use std::{
fmt::{self, Display, Write as _},
io::{BufRead, Write},
mem,
... |
write!(writer, "v{}", CompressedIlpName(node))?;
}
writeln!(writer, " >= 1")?;
}
writeln!(writer, "Binaries")?;
write!(writer, " v{}", CompressedIlpName(self.nodes()[0]))?;
for &node in &self.nodes()[1..] {
write!(writer, " v{}", Com... | {
write!(writer, " + ")?;
} | conditional_block |
instance.rs | use crate::{
create_idx_struct,
data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec},
small_indices::SmallIdx,
};
use anyhow::{anyhow, ensure, Error, Result};
use log::{info, trace};
use serde::Deserialize;
use std::{
fmt::{self, Display, Write as _},
io::{BufRead, Write},
mem,
... | (&mut self, edge: EdgeIdx) {
trace!("Restoring edge {}", edge);
for (_idx, (node, entry_idx)) in self.edge_incidences[edge.idx()].iter().rev() {
self.node_incidences[node.idx()].restore(entry_idx.idx());
}
self.edges.restore(edge.idx());
}
/// Deletes all edges incid... | restore_edge | identifier_name |
lib.rs | use tokio::time::delay_for;
use core::time::Duration;
use anyhow::{anyhow, Result};
use channels::AGENT_CHANNEL;
use comm::{AgentEvent, Hub};
use config::Config;
use tokio::sync::RwLock;
use tokio::sync::RwLockReadGuard;
use tokio::sync::RwLockWriteGuard;
use crossbeam_channel::{Receiver, Sender};
use log::{debug, inf... |
let jh = self.runtime.spawn(async move {
info!("[Workload {}] Running.", id);
let start = Instant::now();
let result = workload.run().await;
let mills = start.elapsed().as_millis();
info!("[Workload {}] Duration: {}ms", id, mills as f64);
... | {
if self.state == AgentState::Stopped {
info!("Agent stopped, Not running workload {}. Work will be deferred until the agent starts.", workload.id);
let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle {
id: workload.id,
join_handle: None,
... | identifier_body |
lib.rs | use tokio::time::delay_for;
use core::time::Duration;
use anyhow::{anyhow, Result};
use channels::AGENT_CHANNEL;
use comm::{AgentEvent, Hub};
use config::Config;
use tokio::sync::RwLock;
use tokio::sync::RwLockReadGuard;
use tokio::sync::RwLockWriteGuard;
use crossbeam_channel::{Receiver, Sender};
use log::{debug, inf... |
AgentCommand::Stop => {
self.state = AgentState::Stopped;
channel.sender.send(AgentEvent::Stopped).unwrap();
}
}
}
/// Run a workload in the agent
/// This will capture the statistics of the workload run and store it in
/// the agent.
... | {} | conditional_block |
lib.rs | use tokio::time::delay_for;
use core::time::Duration;
use anyhow::{anyhow, Result};
use channels::AGENT_CHANNEL;
use comm::{AgentEvent, Hub};
use config::Config;
use tokio::sync::RwLock;
use tokio::sync::RwLockReadGuard;
use tokio::sync::RwLockWriteGuard;
use crossbeam_channel::{Receiver, Sender};
use log::{debug, inf... | use work::{Workload, WorkloadHandle, WorkloadStatus};
use async_trait::async_trait;
pub mod cfg;
pub mod comm;
pub mod plugins;
pub mod prom;
pub mod threads;
pub mod work;
pub mod channels {
pub const AGENT_CHANNEL: &'static str = "Agent";
}
// Configuration
lazy_static! {
static ref SETTINGS: RwLock<Confi... |
use tokio::runtime::Runtime;
| random_line_split |
lib.rs | use tokio::time::delay_for;
use core::time::Duration;
use anyhow::{anyhow, Result};
use channels::AGENT_CHANNEL;
use comm::{AgentEvent, Hub};
use config::Config;
use tokio::sync::RwLock;
use tokio::sync::RwLockReadGuard;
use tokio::sync::RwLockWriteGuard;
use crossbeam_channel::{Receiver, Sender};
use log::{debug, inf... | {
Start,
Schedule(Schedule, Workload),
Stop,
}
#[derive(Debug, Clone)]
pub struct FeatureConfig {
pub bind_address: [u8; 4],
pub bind_port: u16,
pub settings: HashMap<String, String>,
}
#[derive(Clone)]
pub struct AgentController {
pub agent: Arc<RwLock<Agent>>,
pub signal: Option<Send... | AgentCommand | identifier_name |
mod.rs | //! Tiles organised into chunks for efficiency and performance.
//!
//! Mostly everything in this module is private API and not intended to be used
//! outside of this crate as a lot goes on under the hood that can cause issues.
//! With that being said, everything that can be used with helping a chunk get
//! created ... | else {
error!("can not set tile to sprite layer {}", tile.z_order);
}
} else {
error!("sprite layer {} does not exist", tile.z_order);
}
}
/// Removes a tile from a sprite layer with a given index and z order.
pub(crate) fn remove_tile(&mut self, ind... | {
let raw_tile = RawTile {
index: tile.sprite_index,
color: tile.tint,
};
layer.inner.as_mut().set_tile(index, raw_tile);
} | conditional_block |
mod.rs | //! Tiles organised into chunks for efficiency and performance.
//!
//! Mostly everything in this module is private API and not intended to be used
//! outside of this crate as a lot goes on under the hood that can cause issues.
//! With that being said, everything that can be used with helping a chunk get
//! created ... |
/// Removes a layer from the specified layer.
pub(crate) fn remove_layer(&mut self, z_order: usize) {
self.sprite_layers.get_mut(z_order).take();
}
/// Sets the mesh for the chunk layer to use.
pub(crate) fn set_mesh(&mut self, z_order: usize, mesh: Handle<Mesh>) {
if let Some(lay... | {
// TODO: rename to swap and include it in the greater api
if self.sprite_layers.get(to_z).is_some() {
error!(
"sprite layer {} unexpectedly exists and can not be moved",
to_z
);
return;
}
self.sprite_layers.swap(from_... | identifier_body |
mod.rs | //! Tiles organised into chunks for efficiency and performance.
//!
//! Mostly everything in this module is private API and not intended to be used
//! outside of this crate as a lot goes on under the hood that can cause issues.
//! With that being said, everything that can be used with helping a chunk get
//! created ... | (&mut self, z_order: usize, index: usize) -> Option<&mut RawTile> {
self.sprite_layers.get_mut(z_order).and_then(|layer| {
layer
.as_mut()
.and_then(|layer| layer.inner.as_mut().get_tile_mut(index))
})
}
/// Gets a vec of all the tiles in the layer, if ... | get_tile_mut | identifier_name |
mod.rs | //! Tiles organised into chunks for efficiency and performance.
//!
//! Mostly everything in this module is private API and not intended to be used
//! outside of this crate as a lot goes on under the hood that can cause issues.
//! With that being said, everything that can be used with helping a chunk get
//! created ... |
/// Gets a reference to a tile from a provided z order and index.
pub(crate) fn get_tile(&self, z_order: usize, index: usize) -> Option<&RawTile> {
self.sprite_layers.get(z_order).and_then(|layer| {
layer
.as_ref()
.and_then(|layer| layer.inner.as_ref().get_til... | } | random_line_split |
process.rs | use crate::{FromInner, HandleTrait, Inner, IntoInner};
use std::convert::TryFrom;
use std::ffi::CString;
use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data;
use uv::{
uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill,
uv_process_options_t, uv_process_t, uv_spawn, uv_s... | {
handle: *mut uv_process_t,
}
impl ProcessHandle {
/// Create a new process handle
pub fn new() -> crate::Result<ProcessHandle> {
let layout = std::alloc::Layout::new::<uv_process_t>();
let handle = unsafe { std::alloc::alloc(layout) as *mut uv_process_t };
if handle.is_null() {
... | ProcessHandle | identifier_name |
process.rs | use crate::{FromInner, HandleTrait, Inner, IntoInner};
use std::convert::TryFrom;
use std::ffi::CString;
use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data;
use uv::{
uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill,
uv_process_options_t, uv_process_t, uv_spawn, uv_s... | /// 2).
const IGNORE = uv::uv_stdio_flags_UV_IGNORE as _;
/// Open a new pipe into `data.stream`, per the flags below. The `data.stream` field must
/// point to a PipeHandle object that has been initialized with `new`, but not yet opened
/// or connected.
const CREATE_PI... | pub struct StdioFlags: u32 {
/// No file descriptor will be provided (or redirected to `/dev/null` if it is fd 0, 1 or | random_line_split |
process.rs | use crate::{FromInner, HandleTrait, Inner, IntoInner};
use std::convert::TryFrom;
use std::ffi::CString;
use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data;
use uv::{
uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill,
uv_process_options_t, uv_process_t, uv_spawn, uv_s... | }
// CString will ensure we have a terminating null
let file = CString::new(options.file)?;
// For args, libuv-sys is expecting a "*mut *mut c_char". The only way to get a "*mut
// c_char" from a CString is via CString::into_raw() which will "leak" the memory from
// rus... | d.exit_cb = options.exit_cb;
}
| conditional_block |
ccm.rs | // Implementation of the AEAD CCM cipher as described in:
// https://datatracker.ietf.org/doc/html/rfc3610
//
// NOTE: Currently only fixed block sizes are supported.
use core::result::Result;
use common::ceil_div;
use crate::constant_eq;
use crate::utils::xor_inplace;
/// Number of bytes in an AES-128 key.
pub con... | <Block, Nonce> {
block: Block,
tag_size: usize,
length_size: usize,
nonce: Nonce,
}
impl<Block: BlockCipherBuffer, Nonce: AsRef<[u8]>> CCM<Block, Nonce> {
///
/// Arguments:
/// - block:
/// - tag_size: Number of bytes used to store the message authentication
/// tag.
/// - le... | CCM | identifier_name |
ccm.rs | // Implementation of the AEAD CCM cipher as described in:
// https://datatracker.ietf.org/doc/html/rfc3610
//
// NOTE: Currently only fixed block sizes are supported.
use core::result::Result;
use common::ceil_div;
use crate::constant_eq;
use crate::utils::xor_inplace;
/// Number of bytes in an AES-128 key.
pub con... | else { 0 }) << 6
| ((self.tag_size as u8 - 2) / 2) << 3
| (self.length_size as u8 - 1);
if self.length_size == 2 {
*array_mut_ref![block, block.len() - 2, 2] = (length as u16).to_be_bytes();
} else {
todo!();
}
}
fn setup_for_ctr_enc(&mu... | { 1 } | conditional_block |
ccm.rs | // Implementation of the AEAD CCM cipher as described in:
// https://datatracker.ietf.org/doc/html/rfc3610
//
// NOTE: Currently only fixed block sizes are supported.
use core::result::Result;
use common::ceil_div;
use crate::constant_eq;
use crate::utils::xor_inplace;
/// Number of bytes in an AES-128 key.
pub con... |
}
impl BlockCipherBuffer for AES128BlockEncryptor {
fn plaintext(&self) -> &[u8; BLOCK_SIZE] {
&self.plaintext
}
fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE] {
&mut self.plaintext
}
fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; B... | {
assert_eq!(key.len(), KEY_SIZE);
Self {
cipher: AESBlockCipher::create(key).unwrap(),
plaintext: [0u8; BLOCK_SIZE],
ciphertext: [0u8; BLOCK_SIZE],
}
} | identifier_body |
ccm.rs | // Implementation of the AEAD CCM cipher as described in:
// https://datatracker.ietf.org/doc/html/rfc3610
//
// NOTE: Currently only fixed block sizes are supported.
use core::result::Result;
use common::ceil_div;
use crate::constant_eq;
use crate::utils::xor_inplace;
/// Number of bytes in an AES-128 key.
pub con... | /// - tag_size: Number of bytes used to store the message authentication
/// tag.
/// - length_size: Number of bytes used to represent the message length.
/// - nonce:
pub fn new(block: Block, tag_size: usize, length_size: usize, nonce: Nonce) -> Self {
let nonce_size = 15 - length_size;
... | /// Arguments:
/// - block: | random_line_split |
protocol.rs | // Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, mer... | (&self) -> Self::InfoIter {
iter::once(b"/ipfs/id/1.0.0")
}
}
impl<C> InboundUpgrade<C> for IdentifyProtocolConfig
where
C: AsyncRead + AsyncWrite,
{
type Output = IdentifySender<Negotiated<C>>;
type Error = IoError;
type Future = FutureResult<Self::Output, IoError>;
fn upgrade_inbound... | protocol_info | identifier_name |
protocol.rs | // Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, mer... | )
});
let mut rt = Runtime::new().unwrap();
let _ = rt.block_on(future).unwrap();
});
let transport = TcpConfig::new();
let future = transport.dial(rx.recv().unwrap())
.unwrap()
.and_then(|socket| {
... | "/ip6/::1/udp/1000".parse().unwrap(),
],
protocols: vec!["proto1".to_string(), "proto2".to_string()],
},
&"/ip4/100.101.102.103/tcp/5000".parse().unwrap(), | random_line_split |
protocol.rs | // Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, mer... |
let listen_addrs = {
let mut addrs = Vec::new();
for addr in msg.take_listenAddrs().into_iter() {
addrs.push(bytes_to_multiaddr(addr)?);
}
addrs
};
let public_key = PublicKey::from_protobuf_encodin... | {
Multiaddr::try_from(bytes)
.map_err(|err| IoError::new(IoErrorKind::InvalidData, err))
} | identifier_body |
correctness_proof.rs | //! The proof of correct encryption of the given value.
//! For more details see section 5.2 of the whitepaper.
use super::errors::{ErrorKind, Fallible};
use crate::asset_proofs::{
encryption_proofs::{
AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge,
ZKProofRes... |
}
#[derive(PartialEq, Copy, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CorrectnessInitialMessage {
a: RistrettoPoint,
b: RistrettoPoint,
}
impl Encode for CorrectnessInitialMessage {
fn size_hint(&self) -> usize {
64
}
fn encode_to<W: Output>... | {
let scalar = <[u8; 32]>::decode(input)?;
let scalar = Scalar::from_canonical_bytes(scalar)
.ok_or_else(|| CodecError::from("CorrectnessFinalResponse is invalid"))?;
Ok(CorrectnessFinalResponse(scalar))
} | identifier_body |
correctness_proof.rs | //! The proof of correct encryption of the given value.
//! For more details see section 5.2 of the whitepaper.
use super::errors::{ErrorKind, Fallible};
use crate::asset_proofs::{
encryption_proofs::{
AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge,
ZKProofRes... | <I: Input>(input: &mut I) -> Result<Self, CodecError> {
let (a, b) = <([u8; 32], [u8; 32])>::decode(input)?;
let a = CompressedRistretto(a)
.decompress()
.ok_or_else(|| CodecError::from("CorrectnessInitialMessage 'a' point is invalid"))?;
let b = CompressedRistretto(b)
... | decode | identifier_name |
correctness_proof.rs | //! The proof of correct encryption of the given value.
//! For more details see section 5.2 of the whitepaper.
use super::errors::{ErrorKind, Fallible};
use crate::asset_proofs::{
encryption_proofs::{
AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge,
ZKProofRes... | /// A default implementation used for testing.
impl Default for CorrectnessInitialMessage {
fn default() -> Self {
CorrectnessInitialMessage {
a: RISTRETTO_BASEPOINT_POINT,
b: RISTRETTO_BASEPOINT_POINT,
}
}
}
impl UpdateTranscript for CorrectnessInitialMessage {
fn u... | random_line_split | |
main.rs | use rusttype::{point, Font, Glyph, Scale};
use winit::{
dpi::PhysicalSize,
event::*,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
#[repr(C)]
#[derive(Copy, Clone, Debug)]
struct Vertex {
position: [f32; 3],
tex_coords: [f32; 2],
}
impl Vertex {
fn desc<'a>() -> ... | (&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
self.size = new_size;
self.sc_desc.width = new_size.width;
self.sc_desc.height = new_size.height;
self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc);
}
fn render(&mut self) {
let frame = sel... | resize | identifier_name |
main.rs | use rusttype::{point, Font, Glyph, Scale};
use winit::{
dpi::PhysicalSize,
event::*,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
#[repr(C)]
#[derive(Copy, Clone, Debug)]
struct Vertex {
position: [f32; 3],
tex_coords: [f32; 2],
}
impl Vertex {
fn desc<'a>() -> ... | depth_bias: 0,
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
}),
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor {
format: sc_desc.format,
color... | cull_mode: wgpu::CullMode::Back, | random_line_split |
main.rs | use rusttype::{point, Font, Glyph, Scale};
use winit::{
dpi::PhysicalSize,
event::*,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
#[repr(C)]
#[derive(Copy, Clone, Debug)]
struct Vertex {
position: [f32; 3],
tex_coords: [f32; 2],
}
impl Vertex {
fn desc<'a>() -> ... | width: dimensions.0,
height: dimensions.1,
depth: 1,
};
let diffuse_texture = device.create_texture(&wgpu::TextureDescriptor {
size: size3d,
array_layer_count: 1,
mip_level_count: 1,
sample_count: 1,
dimensio... | {
//let diffuse_bytes = include_bytes!("../happy-tree.png");
let font_bytes = include_bytes!("../ttf/JetBrainsMono-Regular.ttf");
let font = Font::from_bytes(font_bytes as &[u8]).expect("Failed to create font");
let glyph = font
.glyph('c')
.scaled(Scale { x: 50.0... | identifier_body |
main.rs | , right, top, bottom) = rg3d::core::futures::join!(
resource_manager.request_texture("data/textures/skybox/front.jpg"),
resource_manager.request_texture("data/textures/skybox/back.jpg"),
resource_manager.request_texture("data/textures/skybox/left.jpg"),
resource_manager.request_texture("... | let clock = time::Instant::now();
let mut elapsed_time = 0.0;
event_loop.run(move |event, _, control_flow| { | random_line_split | |
main.rs | Node>;
// Our game logic will be updated at 60 Hz rate.
const TIMESTEP: f32 = 1.0 / 60.0;
#[derive(Default)]
struct InputController {
move_forward: bool,
move_backward: bool,
move_left: bool,
move_right: bool,
pitch: f32,
yaw: f32,
shoot: bool,
}
struct Player {
pivot: Handle<Node>,
... | () {
// Configure main window first.
| main | identifier_name |
main.rs | Node>;
// Our game logic will be updated at 60 Hz rate.
const TIMESTEP: f32 = 1.0 / 60.0;
#[derive(Default)]
struct InputController {
move_forward: bool,
move_backward: bool,
move_left: bool,
move_right: bool,
pitch: f32,
yaw: f32,
shoot: bool,
}
struct Player {
pivot: Handle<Node>,
... | .build(&mut scene.graph);
weapon_pivot
}]),
)
.with_skybox(create_skybox(resource_manager).await)
.build(&mut scene.graph);
camera
}])
.build(&mut scene... | {
// Create a pivot and attach a camera to it, move it a bit up to "emulate" head.
let camera;
let weapon_pivot;
let pivot = BaseBuilder::new()
.with_children(&[{
camera = CameraBuilder::new(
BaseBuilder::new()
.with... | identifier_body |
lib.rs | #![deny(
future_incompatible,
nonstandard_style,
rust_2018_compatibility,
rust_2018_idioms,
unused,
missing_docs
)]
//! # luomu-libpcap
//!
//! Safe and mostly sane Rust bindings for [libpcap](https://www.tcpdump.org/).
//!
//! We are split in two different crates:
//!
//! * `luomu-libpcap-sy... | (&self) -> u32 {
self.stats.ps_recv
}
/// Return number of packets dropped because there was no room in the
/// operating system's buffer when they arrived, because packets weren't
/// being read fast enough.
pub fn packets_dropped(&self) -> u32 {
self.stats.ps_drop
}
/// R... | packets_received | identifier_name |
lib.rs | #![deny(
future_incompatible,
nonstandard_style,
rust_2018_compatibility,
rust_2018_idioms,
unused,
missing_docs
)]
//! # luomu-libpcap
//!
//! Safe and mostly sane Rust bindings for [libpcap](https://www.tcpdump.org/).
//!
//! We are split in two different crates:
//!
//! * `luomu-libpcap-sy... | pub fn capture(&self) -> PcapIter<'_> {
PcapIter::new(&self.pcap_t)
}
/// Transmit a packet
pub fn inject(&self, buf: &[u8]) -> Result<usize> {
pcap_inject(&self.pcap_t, buf)
}
/// activate a capture
///
/// This is used to activate a packet capture to look at packets o... | random_line_split | |
macos.rs | #![cfg(target_os = "macos")]
use super::*;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
impl From<u32> for LocalProcessStatus {
fn from(s: u32) -> Self {
match s {
1 => Self::Idle,
2 => Self::Run,
3 => Self::Sleep,
4 => Se... | let nul = ptr.iter().position(|&c| c == 0)?;
let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string();
*ptr = ptr.get(nul + 1..)?;
// Find the position of the first non null byte. `.position()`
// will return None if we run off the end.
if let Some(not_nul) =... | {
use libc::c_int;
// The data in our buffer is laid out like this:
// argc - c_int
// exe_path - NUL terminated string
// argv[0] - NUL terminated string
// argv[1] - NUL terminated string
// ...
// argv[n] - NUL terminated string
// envp[0] - NUL terminated string
// ...
... | identifier_body |
macos.rs | #![cfg(target_os = "macos")]
use super::*;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
impl From<u32> for LocalProcessStatus {
fn from(s: u32) -> Self {
match s {
1 => Self::Idle,
2 => Self::Run,
3 => Self::Sleep,
4 => Se... | }
fn exe_for_pid(pid: libc::pid_t) -> PathBuf {
LocalProcessInfo::executable_path(pid as _).unwrap_or_else(PathBuf::new)
}
let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect();
fn build_proc(info: &libc::proc_bsdinfo, procs: &[libc::proc_bs... | parse_exe_and_argv_sysctl(buf) | random_line_split |
macos.rs | #![cfg(target_os = "macos")]
use super::*;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
impl From<u32> for LocalProcessStatus {
fn from(s: u32) -> Self {
match s {
1 => Self::Idle,
2 => Self::Run,
3 => Self::Sleep,
4 => Se... | (ptr: &mut &[u8]) -> Option<String> {
// Parse to the end of a null terminated string
let nul = ptr.iter().position(|&c| c == 0)?;
let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string();
*ptr = ptr.get(nul + 1..)?;
// Find the position of the first non null byte. `... | consume_cstr | identifier_name |
wallet.rs | store persistent state.
fn persistent_state_address(
network: NetworkId,
master_xpriv: &bip32::ExtendedPrivKey,
) -> String {
let child = bip32::ChildNumber::from_hardened_idx(350).unwrap();
let child_xpriv = master_xpriv.derive_priv(&SECP, &[child]).unwrap();
let child_... | error!("Address is labeled with unknown master xpriv fingerprint: {:?}", fp);
return Err(Error::CorruptNodeData);
};
let privkey = xpriv.derive_priv(&SECP, &[child])?.private_key;
Ok(privkey.key)
}
pub fn updates(&mut self) -> Result<Vec<Value>, Error> {
... | self.external_xpriv
} else if fp == self.internal_xpriv.fingerprint(&SECP) {
self.internal_xpriv
} else { | random_line_split |
wallet.rs | ]).unwrap();
let child_xpub = bip32::ExtendedPubKey::from_private(&SECP, &child_xpriv);
match network {
#[cfg(feature = "liquid")]
NetworkId::Elements(enet) => elements::Address::p2wpkh(
&child_xpub.public_key,
None,
coins::liq::add... | _make_fee_estimates | identifier_name | |
wallet.rs | let child = bip32::ChildNumber::from_hardened_idx(350).unwrap();
let child_xpriv = master_xpriv.derive_priv(&SECP, &[child]).unwrap();
let child_xpub = bip32::ExtendedPubKey::from_private(&SECP, &child_xpriv);
match network {
#[cfg(feature = "liquid")]
NetworkId::Eleme... | {
None
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.