file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | #![feature(rustc_private)]
extern crate im;
extern crate pretty;
extern crate rustc_ast;
extern crate rustc_driver;
extern crate rustc_errors;
extern crate rustc_hir;
extern crate rustc_interface;
extern crate rustc_metadata;
extern crate rustc_middle;
extern crate rustc_session;
extern crate rustc_span;
mod ast_to_ru... | }
let json_string = String::from_utf8(stdout).expect(" ⚠️ Failed reading cargo output");
serde_json::from_str(&json_string).expect(" ⚠️ Error reading to manifest")
};
// Pick the package of the given name or the only package available.
let package = if let Some(package_name) = pac... | {
let manifest: Manifest = {
let mut output = Command::new("cargo");
let mut output_args = if let Some(manifest_path) = manifest {
vec!["--manifest-path".to_string(), manifest_path]
} else {
Vec::<String>::new()
};
output_args.extend_from_slice(&[
... | identifier_body |
eth.rs | }
}
impl<const TD: usize, const RD: usize> Default for DesRing<TD, RD> {
fn default() -> Self {
Self::new()
}
}
///
/// Ethernet DMA
///
pub struct EthernetDMA<const TD: usize, const RD: usize> {
ring: &'static mut DesRing<TD, RD>,
eth_dma: stm32::ETHERNET_DMA,
}
///
/// Ethernet MAC
///
p... | number_packets_dropped | identifier_name | |
eth.rs | move in ETH_MAC, ETH_MTL, ETH_DMA.
///
/// Sets up the descriptor structures, sets up the peripheral
/// clocks and GPIO configuration, and configures the ETH MAC and
/// DMA peripherals. Automatically sets slew rate to VeryHigh.
/// If you wish to use another configuration, please see
/// [new_unchecked](new_unchecke... | {
let eth_dma = &*stm32::ETHERNET_DMA::ptr();
eth_dma
.dmacsr
.write(|w| w.nis().set_bit().ri().set_bit().ti().set_bit());
let _ = eth_dma.dmacsr.read();
let _ = eth_dma.dmacsr.read(); // Delay 2 peripheral clocks
} | identifier_body | |
eth.rs | // before the DMA engine is enabled.)
unsafe {
let dma = &*stm32::ETHERNET_DMA::ptr();
dma.dmactx_dlar
.write(|w| w.bits(&self.td[0] as *const _ as u32));
dma.dmactx_rlr.write(|w| w.tdrl().bits(TD as u16 - 1));
dma.dmactx_dtpr
... | // Contains first buffer of packet AND contains last buf of
// packet AND no errors AND not a contex descriptor
self.rdes3
& (EMAC_DES3_FD | EMAC_DES3_LD | EMAC_DES3_ES | EMAC_DES3_CTXT)
== (EMAC_DES3_FD | EMAC_DES3_LD)
}
/// Return true if this RDes is not curre... | // Write-back descriptor is valid if:
// | random_line_split |
types.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Loaded representation for runtime types.
use libra_types::{
account_address::AccountAddress,
vm_error::{StatusCode, VMStatus},
};
use move_core_types::{
identifier::Identifier,
language_storage::{StructTag, TypeTag}... | Signer => debug_write!(buf, "signer"),
Vector(elem_ty) => {
debug_write!(buf, "vector<")?;
elem_ty.debug_print(buf)?;
debug_write!(buf, ">")
}
Struct(struct_ty) => struct_ty.debug_print(buf),
Reference(ty) => {
... | Address => debug_write!(buf, "address"), | random_line_split |
types.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Loaded representation for runtime types.
use libra_types::{
account_address::AccountAddress,
vm_error::{StatusCode, VMStatus},
};
use move_core_types::{
identifier::Identifier,
language_storage::{StructTag, TypeTag}... | (&self) -> VMResult<bool> {
use FatType::*;
match self {
Bool | U8 | U64 | U128 | Address | Reference(_) | MutableReference(_) => Ok(false),
Signer => Ok(true),
Vector(ty) => ty.is_resource(),
Struct(struct_ty) => Ok(struct_ty.is_resource),
//... | is_resource | identifier_name |
types.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Loaded representation for runtime types.
use libra_types::{
account_address::AccountAddress,
vm_error::{StatusCode, VMStatus},
};
use move_core_types::{
identifier::Identifier,
language_storage::{StructTag, TypeTag}... | }
pub fn is_resource(&self) -> VMResult<bool> {
use FatType::*;
match self {
Bool | U8 | U64 | U128 | Address | Reference(_) | MutableReference(_) => Ok(false),
Signer => Ok(true),
Vector(ty) => ty.is_resource(),
Struct(struct_ty) => Ok(struct_t... | {
use FatType::*;
let res = match self {
Bool => TypeTag::Bool,
U8 => TypeTag::U8,
U64 => TypeTag::U64,
U128 => TypeTag::U128,
Address => TypeTag::Address,
Signer => TypeTag::Signer,
Vector(ty) => TypeTag::Vector(Box::n... | identifier_body |
hash2curve.rs | fn from_okm(data: &GenericArray<u8, Self::Length>) -> Self {
const F_2_288: FieldElement = FieldElement::from_hex(
"000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000",
);
let mut d0 = FieldBytes::default();
d0[12..].copy_from_s... |
}
panic!("deriving key failed");
}
}
#[test]
fn from_okm_fuzz() {
let mut wide_order = GenericArray::default();
wide_order[24..].copy_from_slice(&NistP384::ORDER.to_be_byte_array());
let wide_order = NonZero::new(U576::from_be_byte_array(wide_order)... | {
assert_eq!(scalar.to_bytes().as_slice(), test_vector.sk_sm);
continue 'outer;
} | conditional_block |
hash2curve.rs | fn from_okm(data: &GenericArray<u8, Self::Length>) -> Self {
const F_2_288: FieldElement = FieldElement::from_hex(
"000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000",
);
let mut d0 = FieldBytes::default();
d0[12..].copy_from_s... | },
TestVector {
dst: b"DeriveKeyPairVOPRF10-\x02\x00\x04",
key_info: b"test key",
seed: &hex!("a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3"),
sk_sm: &hex!("0fcba4a204f67d6c13f780e... | {
struct TestVector {
dst: &'static [u8],
key_info: &'static [u8],
seed: &'static [u8],
sk_sm: &'static [u8],
}
const TEST_VECTORS: &[TestVector] = &[
TestVector {
dst: b"DeriveKeyPairVOPRF10-\x00\x00\x04",
... | identifier_body |
hash2curve.rs | fn from_okm(data: &GenericArray<u8, Self::Length>) -> Self {
const F_2_288: FieldElement = FieldElement::from_hex(
"000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000",
);
let mut d0 = FieldBytes::default();
d0[12..].copy_from_... |
const DST: &[u8] = b"QUUX-V01-CS02-with-P384_XMD:SHA-384_SSWU_RO_";
const TEST_VECTORS: &[TestVector] = &[
TestVector {
msg: b"",
p_x: hex!("eb9fe1b4f4e14e7140803c1d99d0a93cd823d2b024040f9c067a8eca1f5a2eeac9ad604973527a356f3fa3aeff0e4d83"),
p... | q1_x: [u8; 48],
q1_y: [u8; 48],
} | random_line_split |
hash2curve.rs | fn from_okm(data: &GenericArray<u8, Self::Length>) -> Self {
const F_2_288: FieldElement = FieldElement::from_hex(
"000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000",
);
let mut d0 = FieldBytes::default();
d0[12..].copy_from_s... | () {
struct TestVector {
msg: &'static [u8],
p_x: [u8; 48],
p_y: [u8; 48],
u_0: [u8; 48],
u_1: [u8; 48],
q0_x: [u8; 48],
q0_y: [u8; 48],
q1_x: [u8; 48],
q1_y: [u8; 48],
}
const DST: &[u8]... | hash_to_curve | identifier_name |
mod.rs | pub mod context;
pub mod types;
///////////////////// Validation Helpers /////////////////////
use std::collections::HashMap;
use crate::frontend::validate::types::Type;
use crate::frontend::parse::ast;
///////////////////// TYPES /////////////////////
// NOTE: Offsets are i32 for Cranelift
/// Stores struct defin... | // e.g.: `let x: u32 = y.a;`
// FieldAlias(),
}
pub struct AllocationTable {
// Map of ((function_name, variable name) -> variable's usage)
pub allocations: HashMap<(String, String), MemoryUsage>,
}
impl AllocationTable {
pub fn new() -> Self {
Self {
allocations: HashMap::new(... | // TODO: References an existing variable -> ??
// e.g.: `let x: &u32 = &y;`
// Borrow(&'input str),
// TODO: Aliases a field of an existing variable -> ?? | random_line_split |
mod.rs | pub mod context;
pub mod types;
///////////////////// Validation Helpers /////////////////////
use std::collections::HashMap;
use crate::frontend::validate::types::Type;
use crate::frontend::parse::ast;
///////////////////// TYPES /////////////////////
// NOTE: Offsets are i32 for Cranelift
/// Stores struct defin... | (&mut self, name: &str) -> Result<&mut VariableData, String> {
if let Some(&index) = self.all_variables.get(name) {
return Ok(self.scopes[index].get_var_data_mut(name));
}
Err(format!("No variable `{}` in scope", name))
}
// NOTE: Program is valid at this point. No safety c... | get_variable_mut | identifier_name |
mod.rs | pub mod context;
pub mod types;
///////////////////// Validation Helpers /////////////////////
use std::collections::HashMap;
use crate::frontend::validate::types::Type;
use crate::frontend::parse::ast;
///////////////////// TYPES /////////////////////
// NOTE: Offsets are i32 for Cranelift
/// Stores struct defin... | else {
Err(format!("Type `{}` is not valid", t))
}
}
}
}
/// Returns alignment of the type in bytes
fn alignment_of(&self, t: &Type) -> usize {
match t {
// TODO: Alignment should be same as pointer type
Type::Referenc... | {
Ok(())
} | conditional_block |
value.rs | // Copyright 2019 The Starlark in Rust 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable la... | }
}
fn get_hash(&self) -> Result<u64, ValueError> {
Ok(self
.content
.iter()
.map(|v| v.precomputed_hash)
.map(Wrapping)
.fold(Wrapping(0_u64), |acc, v| acc + v)
.0)
}
not_supported!(mul, set_at);
not_supported!(attr... | } else {
Err(ValueError::IncorrectParameterType) | random_line_split |
value.rs | // Copyright 2019 The Starlark in Rust 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable la... | else {
let mut v = v.clone();
v.downcast_apply_mut(|x: &mut Set| -> ValueResult {
x.mutability.test()?;
f(&mut x.content)
})
}
}
pub fn compare<Return>(
v1: &Value,
v2: &Value,
f: &Fn(
&LinkedHashSe... | {
Err(ValueError::IncorrectParameterType)
} | conditional_block |
value.rs | // Copyright 2019 The Starlark in Rust 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable la... |
fn is_descendant(&self, other: &TypedValue) -> bool {
self.content
.iter()
.any(|x| x.value.same_as(other) || x.value.is_descendant(other))
}
fn slice(
&self,
start: Option<Value>,
stop: Option<Value>,
stride: Option<Value>,
) -> ValueResu... | {
Ok(Value::new(
self.content.contains(&ValueWrapper::new(other.clone())?),
))
} | identifier_body |
value.rs | // Copyright 2019 The Starlark in Rust 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable la... | () -> Self {
Set {
mutability: IterableMutability::Mutable,
content: LinkedHashSet::new(),
}
}
}
impl Set {
pub fn empty() -> Value {
Value::new(Set::default())
}
pub fn from<V: Into<Value>>(values: Vec<V>) -> Result<Value, ValueError> {
let mut ... | default | identifier_name |
general.rs | extern crate serenity;
use serenity::{framework::standard::{
help_commands,
macros::{ command, group, help},
Args,
CommandGroup, CommandResult, HelpOptions,
}, model::{channel::{Message,ReactionType}, id::UserId }, prelude::*};
use serenity::utils::Colour;
// use serenity::model::appli... |
if let Some(description) = &guild.description {
e.field("Description",description,false);
};
e.field("Members",number_users,true)
//.field("MSG",number_msgs,true)
.field("Channels",number_channels,true)
.field("Roles",... | et guild = match ctx.cache.guild(&msg.guild_id.unwrap()).await {
Some(guild) => guild,
None => {
msg.reply(ctx, "Error" ).await;
return Ok(());
}
};
let number_users = guild.member_count;
// let number_msgs = channel.message_count;
let number_cha... | identifier_body |
general.rs | extern crate serenity;
use serenity::{framework::standard::{
help_commands,
macros::{ command, group, help},
Args,
CommandGroup, CommandResult, HelpOptions,
}, model::{channel::{Message,ReactionType}, id::UserId }, prelude::*};
use serenity::utils::Colour;
// use serenity::model::appli... | atar_url().unwrap());
};
e
});
m
});
msg.await.unwrap();
Ok(())
}
| ap());
}
else {
e.title(&person[0].name);
e.image(person[0].av | conditional_block |
general.rs | extern crate serenity;
use serenity::{framework::standard::{
help_commands,
macros::{ command, group, help},
Args,
CommandGroup, CommandResult, HelpOptions,
}, model::{channel::{Message,ReactionType}, id::UserId }, prelude::*};
use serenity::utils::Colour;
// use serenity::model::appli... | // }
// #[check]
// #[name = "Bot"]
// async fn bot_check(ctx: &Context, msg: &Message) -> CheckResult {
// if let Some(member) = msg.member(&ctx.cache) {
// let user = member.user.read();
// user.bot.into()
// } else {
// false.into()
// }
// }
#[command]
#[description = "Bot will... | random_line_split | |
general.rs | extern crate serenity;
use serenity::{framework::standard::{
help_commands,
macros::{ command, group, help},
Args,
CommandGroup, CommandResult, HelpOptions,
}, model::{channel::{Message,ReactionType}, id::UserId }, prelude::*};
use serenity::utils::Colour;
// use serenity::model::appli... | &Context, msg: &Message) -> CommandResult {
let phrase = format!("HIIII {}",&msg.author.name);
msg.reply(&ctx, phrase).await?;
// msg.reply(&ctx, msg.author_nick(&ctx).await.unwrap()).await?;
// msg.reply(&ctx, &msg.author.name).await?;
// msg.reply(&ctx, &msg.member.unwrap().nick.unwrap()).await?;... | x: | identifier_name |
haystack.rs | //! Haystacks.
//!
//! A *haystack* refers to any linear structure which can be split or sliced
//! into smaller, non-overlapping parts. Examples are strings and vectors.
//!
//! ```rust
//! let haystack: &str = "hello"; // a string slice (`&str`) is a haystack.
//! let (a, b) = haystack.split_at(4); // it can b... | &'h str> {
/// Reinterprets the string span as a byte-array span.
#[inline]
pub fn as_bytes(self) -> Span<&'h [u8]> {
Span {
haystack: self.haystack.as_bytes(),
range: self.range,
}
}
}
impl<H: Haystack> Span<H>
where H::Target: Hay // FIXME: RFC 2089 or 2289
{
... | aystack, range }
}
}
impl<'h> Span< | identifier_body |
haystack.rs | //! Haystacks.
//!
//! A *haystack* refers to any linear structure which can be split or sliced
//! into smaller, non-overlapping parts. Examples are strings and vectors.
//!
//! ```rust
//! let haystack: &str = "hello"; // a string slice (`&str`) is a haystack.
//! let (a, b) = haystack.split_at(4); // it can b... | A::empty()
}
#[inline]
unsafe fn split_around(self, range: Range<A::Index>) -> [Self; 3] {
[
self.slice_unchecked(self.start_index()..range.start),
self.slice_unchecked(range.clone()),
self.slice_unchecked(range.end..self.end_index()),
]
}
#[i... | identifier_name | |
haystack.rs | //! Haystacks.
//!
//! A *haystack* refers to any linear structure which can be split or sliced
//! into smaller, non-overlapping parts. Examples are strings and vectors.
//!
//! ```rust
//! let haystack: &str = "hello"; // a string slice (`&str`) is a haystack.
//! let (a, b) = haystack.split_at(4); // it can b... | &self,
range: Range<<Self::Target as Hay>::Index>,
subrange: Range<<Self::Target as Hay>::Index>,
) -> Range<<Self::Target as Hay>::Index>;
}
impl<H: Haystack> SpanBehavior for H
where H::Target: Hay // FIXME: RFC 2089 or 2289
{
#[inline]
default fn take(&mut self) -> Self {
... | &self,
range: Range<<Self::Target as Hay>::Index>,
) -> Range<<Self::Target as Hay>::Index>;
fn do_restore_range( | random_line_split |
tokio_ct.rs | use
{
crate :: { SpawnHandle, LocalSpawnHandle, JoinHandle, BlockingHandle },
std :: { fmt, rc::Rc, future::Future, convert::TryFrom },
tokio :: { task::LocalSet, runtime::{ Builder, Runtime, Handle, RuntimeFlavor } },
futures_task :: { FutureObj, LocalFuture... | ( &self, future: FutureObj<'static, ()> ) -> Result<(), SpawnError>
{
// We drop the tokio JoinHandle, so the task becomes detached.
//
drop( self.local.spawn_local(future) );
Ok(())
}
}
impl LocalSpawn for TokioCt
{
fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()> ) -> Result<(), SpawnErro... | spawn_obj | identifier_name |
tokio_ct.rs | use
{
crate :: { SpawnHandle, LocalSpawnHandle, JoinHandle, BlockingHandle },
std :: { fmt, rc::Rc, future::Future, convert::TryFrom },
tokio :: { task::LocalSet, runtime::{ Builder, Runtime, Handle, RuntimeFlavor } },
futures_task :: { FutureObj, LocalFuture... | }
#[ cfg(all( feature = "timer", not(feature="tokio_timer" )) ) ]
//
#[ cfg_attr( nightly, doc(cfg(all( feature = "timer", feature = "tokio_ct" ))) ) ]
//
impl crate::Timer for TokioCt
{
fn sleep( &self, dur: std::time::Duration ) -> futures_core::future::BoxFuture<'static, ()>
{
Box::pin( futures_timer::Delay::... | let handle = self.local.spawn_local( future );
Ok( JoinHandle::tokio(handle) )
} | random_line_split |
tokio_ct.rs | use
{
crate :: { SpawnHandle, LocalSpawnHandle, JoinHandle, BlockingHandle },
std :: { fmt, rc::Rc, future::Future, convert::TryFrom },
tokio :: { task::LocalSet, runtime::{ Builder, Runtime, Handle, RuntimeFlavor } },
futures_task :: { FutureObj, LocalFuture... |
}
impl TokioCt
{
/// Create a new `TokioCt`. Uses a default current thread [`Runtime`] setting timers and io depending
/// on the features enabled on _async_executors_.
//
pub fn new() -> Result<Self, TokioCtErr>
{
let mut builder = Builder::new_current_thread();
#[ cfg( feature = "tokio_io" ) ]
//
b... | {
match handle.runtime_flavor()
{
RuntimeFlavor::CurrentThread => Ok( Self
{
spawner: Spawner::Handle( handle ) ,
local: Rc::new( LocalSet::new() ) ,
}),
_ => Err( handle ),
}
} | identifier_body |
lib.rs | /*!
Faster, growable buffering reader for when there's little to no need to modify data, nor to keep it alive past next read.
`std::io::BufReader` works by copying data from its internal buffer into user-provided `Vec`/`String`,
or, in case of `.lines()`, by emitting new heap-allocated `String` for each iteration.
Whi... |
}
impl<R: Read, B: Buffer> BufRefReader<R, B>
where Error: From<B::Error>
{
/// Creates buffered reader with default options. Look for [`BufRefReaderBuilder`](struct.BufRefReaderBuilder.html) for tweaks.
pub fn new(src: R) -> Result<BufRefReader<R, B>, B::Error> {
BufRefReaderBuilder::new(src)
.build()
}
//... | {
unimplemented!()
} | identifier_body |
lib.rs | /*!
Faster, growable buffering reader for when there's little to no need to modify data, nor to keep it alive past next read.
`std::io::BufReader` works by copying data from its internal buffer into user-provided `Vec`/`String`,
or, in case of `.lines()`, by emitting new heap-allocated `String` for each iteration.
Whi... | Error: From<B::Error>,
{
// two spaces, three spaces, two spaces
let mut r = BufRefReaderBuilder::new(&b" lorem ipsum "[..])
.capacity(4)
.build::<B>()
.unwrap();
assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..]));
assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..]));
assert_eq!(r.re... | use std::fmt::Debug;
fn read_until_empty_lines<B: Buffer>()
where
B::Error: Debug, | random_line_split |
lib.rs | /*!
Faster, growable buffering reader for when there's little to no need to modify data, nor to keep it alive past next read.
`std::io::BufReader` works by copying data from its internal buffer into user-provided `Vec`/`String`,
or, in case of `.lines()`, by emitting new heap-allocated `String` for each iteration.
Whi... | () { read::<MmapBuffer>() }
fn read_words<B: Buffer>(cap: usize, read: usize)
where
B::Error: Debug,
Error: From<B::Error>,
{
let mut r = BufRefReaderBuilder::new(WORDS)
.capacity(cap)
.build::<B>()
.unwrap();
let mut words = WORDS.chunks(read);
while let Ok(Some(slice_buf)) = r.read(read) {
l... | read_mmap | identifier_name |
mod.rs | use std::collections::HashMap;
use std::ptr::NonNull;
use std::fmt::Debug;
use once_cell::sync::OnceCell;
use bit_vec::BitVec;
use crate::tag::{TagType, TagTypeKey};
use crate::util::OpaquePtr;
mod state;
mod property;
mod util;
pub use state::*;
pub use property::*;
pub use util::*;
/// A basic block defined by ... |
/// Get the block state from the given save ID.
pub fn get_state_from(&self, sid: u32) -> Option<&'static BlockState> {
self.ordered_states.get(sid as usize).copied()
}
/// Get the default state from the given block name.
pub fn get_block_from_name(&self, name: &str) -> Option<&'static Blo... | /// Get the save ID from the given state.
pub fn get_sid_from(&self, state: &'static BlockState) -> Option<u32> {
let (_, block_offset) = *self.block_to_indices.get(&state.get_block().get_key())?;
Some(block_offset + state.get_index() as u32)
} | random_line_split |
mod.rs | use std::collections::HashMap;
use std::ptr::NonNull;
use std::fmt::Debug;
use once_cell::sync::OnceCell;
use bit_vec::BitVec;
use crate::tag::{TagType, TagTypeKey};
use crate::util::OpaquePtr;
mod state;
mod property;
mod util;
pub use state::*;
pub use property::*;
pub use util::*;
/// A basic block defined by ... | (&mut self, tag_type: &'static TagType) {
self.tag_stores.insert(tag_type.get_key(), TagStore::Small(Vec::new()));
}
/// Set or unset a tag to some blocks.
pub fn set_blocks_tag<I>(&mut self, tag_type: &'static TagType, enabled: bool, blocks: I) -> Result<(), ()>
where
I: IntoIterator<I... | register_tag_type | identifier_name |
mod.rs | use std::collections::HashMap;
use std::ptr::NonNull;
use std::fmt::Debug;
use once_cell::sync::OnceCell;
use bit_vec::BitVec;
use crate::tag::{TagType, TagTypeKey};
use crate::util::OpaquePtr;
mod state;
mod property;
mod util;
pub use state::*;
pub use property::*;
pub use util::*;
/// A basic block defined by ... | } else {
vec.push(block);
}
}
} else if let Some(idx) = idx {
vec.swap_remove(idx);
}
}
if let TagStore::Big(vec) = store {
let (id... | {
const MAX_SMALL_LEN: usize = 8;
let store = self.tag_stores.get_mut(&tag_type.get_key()).ok_or(())?;
for block in blocks {
if let TagStore::Small(vec) = store {
let idx = vec.iter().position(move |&b| b == block);
if enabled {
... | identifier_body |
lib.rs | extern crate num_bigint;
use num_bigint::BigInt;
use poseidon_rs::Poseidon;
use wasm_bindgen::prelude::*;
///////////////////////////////////////////////////////////////////////////////
// EXPORTED FUNCTIONS FUNCTIONS
///////////////////////////////////////////////////////////////////////////////
#[wasm_bindgen]
pub ... |
///////////////////////////////////////////////////////////////////////////////
// TESTS
///////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
use super::*;
use num_bigint::{Sign, ToBigInt};
#[test]
fn should_hash_strings() {
let str_claim =... | {
let mut claim_bytes = num.to_bytes_be().1;
while claim_bytes.len() < 32 {
claim_bytes = [&[0], &claim_bytes[..]].concat();
}
claim_bytes
} | identifier_body |
lib.rs | extern crate num_bigint;
use num_bigint::BigInt;
use poseidon_rs::Poseidon;
use wasm_bindgen::prelude::*;
///////////////////////////////////////////////////////////////////////////////
// EXPORTED FUNCTIONS FUNCTIONS
///////////////////////////////////////////////////////////////////////////////
#[wasm_bindgen]
pub ... | () {
let hex_claim = "0x045a126cbbd3c66b6d542d40d91085e3f2b5db3bbc8cda0d59615deb08784e4f833e0bb082194790143c3d01cedb4a9663cb8c7bdaaad839cb794dd309213fcf30";
let b64_hash = digest_hex_claim(hex_claim);
assert_eq!(b64_hash, "nGOYvS4aqqUVAT9YjWcUzA89DlHPWaooNpBTStOaHRA=");
let hex_claim = ... | should_hash_hex_claims | identifier_name |
lib.rs | extern crate num_bigint;
use num_bigint::BigInt;
use poseidon_rs::Poseidon;
use wasm_bindgen::prelude::*;
///////////////////////////////////////////////////////////////////////////////
// EXPORTED FUNCTIONS FUNCTIONS
///////////////////////////////////////////////////////////////////////////////
#[wasm_bindgen]
pub ... | let hex_claim = "0x043f10ff1b295bf4d2f24c40c93cce04210ae812dd5ad1a06d5dafd9a2e18fa1247bdf36bef6a9e45e97d246cfb8a0ab25c406cf6fe7569b17e83fd6d33563003a";
let b64_hash = digest_hex_claim(hex_claim);
assert_eq!(b64_hash, "CCxtK0qT7cTxCS7e4uONSHcPQdbQzBqrC3GQvFz4KwA=");
let len = base64::deco... | assert_eq!(len, 32);
| random_line_split |
reader.rs | //a Imports
use crate::{Char, Error, Result, StreamPosition};
//a Constants
/// [BUFFER_SIZE] is the maximum number of bytes held in the UTF-8
/// character reader from the incoming stream. The larger the value,
/// the larger the data read requests from the stream. This value must be larger than `BUFFER_SLACK`.
/// ... | r
},
}
}
},
}
}
}
//zz All done
}
//ip Iterator for Reader - iterate over characters
//
// allow missing doc code examples for this as it *has* an example but
// rustdo... | { // no valid data - check it is just incomplete, or an actual error
match e.error_len() {
None => { // incomplete UTF-8 fetch more
match self.fetch_input()? {
0 => { // ... and eof reached when incom... | conditional_block |
reader.rs | //a Imports
use crate::{Char, Error, Result, StreamPosition};
//a Constants
/// [BUFFER_SIZE] is the maximum number of bytes held in the UTF-8
/// character reader from the incoming stream. The larger the value,
/// the larger the data read requests from the stream. This value must be larger than `BUFFER_SLACK`.
/// ... | type Item = Result<char>;
//mp next - return next character or None if end of file
fn next(&mut self) -> Option<Self::Item> {
match self.next_char() {
Ok(Char::Char(ch)) => Some(Ok(ch)),
Ok(_) => None,
Err(x) => Some(Err(x)),
}
... | impl <'a, R:std::io::Read> Iterator for &'a mut Reader<R> {
// we will be counting with usize | random_line_split |
reader.rs | //a Imports
use crate::{Char, Error, Result, StreamPosition};
//a Constants
/// [BUFFER_SIZE] is the maximum number of bytes held in the UTF-8
/// character reader from the incoming stream. The larger the value,
/// the larger the data read requests from the stream. This value must be larger than `BUFFER_SLACK`.
/// ... | (&self) -> bool {
self.start == self.end
}
//mp borrow_buffer
/// Borrow the data held in the [Reader]'s buffer.
pub fn borrow_buffer(&self) -> &[u8] {
&self.current[self.start..self.end]
}
//mp borrow_pos
/// Borrow the stream position of the next character to be returned
... | buffer_is_empty | identifier_name |
reader.rs | //a Imports
use crate::{Char, Error, Result, StreamPosition};
//a Constants
/// [BUFFER_SIZE] is the maximum number of bytes held in the UTF-8
/// character reader from the incoming stream. The larger the value,
/// the larger the data read requests from the stream. This value must be larger than `BUFFER_SLACK`.
/// ... |
//zz All done
}
| {
match self.next_char() {
Ok(Char::Char(ch)) => Some(Ok(ch)),
Ok(_) => None,
Err(x) => Some(Err(x)),
}
} | identifier_body |
address.rs | use bech32::{u5, FromBase32, ToBase32};
use extended_primitives::Buffer;
use handshake_encoding::{Decodable, DecodingError, Encodable};
use std::fmt;
use std::str::FromStr;
#[cfg(feature = "json")]
use encodings::ToHex;
#[cfg(feature = "json")]
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Vis... | }
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct AddressVisitor;
impl<'de> Visitor<'de> for AddressVisitor {
type Value = Address;
fn expecting(&self, formatter: &mut fmt::Formatter) -> f... | {
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`version` or `hash`")
}
... | identifier_body |
address.rs | use bech32::{u5, FromBase32, ToBase32};
use extended_primitives::Buffer;
use handshake_encoding::{Decodable, DecodingError, Encodable};
use std::fmt;
use std::str::FromStr;
#[cfg(feature = "json")]
use encodings::ToHex;
#[cfg(feature = "json")]
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Vis... | #[cfg(feature = "json")]
impl serde::Serialize for Address {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
let mut state = s.serialize_struct("Address", 2)?;
state.serialize_field("version", &self.version)?;
state.serialize_field("hash", &self.hash... | }
(version[0].to_u8(), hash)
}
| random_line_split |
address.rs | use bech32::{u5, FromBase32, ToBase32};
use extended_primitives::Buffer;
use handshake_encoding::{Decodable, DecodingError, Encodable};
use std::fmt;
use std::str::FromStr;
#[cfg(feature = "json")]
use encodings::ToHex;
#[cfg(feature = "json")]
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Vis... |
version = Some(map.next_value()?);
}
Field::Hash => {
if hash.is_some() {
return Err(de::Error::duplicate_field("hash"));
}
has... | {
return Err(de::Error::duplicate_field("version"));
} | conditional_block |
address.rs | use bech32::{u5, FromBase32, ToBase32};
use extended_primitives::Buffer;
use handshake_encoding::{Decodable, DecodingError, Encodable};
use std::fmt;
use std::str::FromStr;
#[cfg(feature = "json")]
use encodings::ToHex;
#[cfg(feature = "json")]
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Vis... | (&self) -> bool {
self.version == 31
}
pub fn is_unspendable(&self) -> bool {
self.is_null_data()
}
pub fn to_bech32(&self) -> String {
//Also todo this should probably just be in toString, and should use writers so that we
//don't allocate.
//@todo this should ... | is_null_data | identifier_name |
time_driver.rs | use core::cell::Cell;
use core::convert::TryInto;
use core::sync::atomic::{compiler_fence, Ordering};
use core::{mem, ptr};
use atomic_polyfill::{AtomicU32, AtomicU8};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::blocking_mutex::Mutex;
use embassy_time::driver::{AlarmHandle, Driver... | (&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) {
critical_section::with(|cs| {
let alarm = self.get_alarm(cs, alarm);
alarm.callback.set(callback as *const ());
alarm.ctx.set(ctx);
})
}
fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64... | set_alarm_callback | identifier_name |
time_driver.rs | use core::cell::Cell;
use core::convert::TryInto;
use core::sync::atomic::{compiler_fence, Ordering};
use core::{mem, ptr};
use atomic_polyfill::{AtomicU32, AtomicU8};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::blocking_mutex::Mutex;
use embassy_time::driver::{AlarmHandle, Driver... | #[cfg(time_driver_tim15)]
#[interrupt]
fn $irq() {
DRIVER.on_interrupt()
}
};
}
// Clock timekeeping works with something we call "periods", which are time intervals
// of 2^15 ticks. The Clock counter value is 16 bits, so one "overflow cycle" is 2 periods.
//
// A `peri... | random_line_split | |
time_driver.rs | use core::cell::Cell;
use core::convert::TryInto;
use core::sync::atomic::{compiler_fence, Ordering};
use core::{mem, ptr};
use atomic_polyfill::{AtomicU32, AtomicU8};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::blocking_mutex::Mutex;
use embassy_time::driver::{AlarmHandle, Driver... |
fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) {
critical_section::with(|cs| {
let alarm = self.get_alarm(cs, alarm);
alarm.callback.set(callback as *const ());
alarm.ctx.set(ctx);
})
}
fn set_alarm(&self, alarm: ... | {
let id = self.alarm_count.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| {
if x < ALARM_COUNT as u8 {
Some(x + 1)
} else {
None
}
});
match id {
Ok(id) => Some(AlarmHandle::new(id)),
Err(_) => N... | identifier_body |
mod.rs | , vendor_info),
Version(major, minor, None, vendor_info) =>
write!(f, "Version({}.{}, {})", major, minor, vendor_info),
}
}
}
/// A unique platform identifier that does not change between releases
#[deriving(Eq, PartialEq, Show)]
pub struct PlatformName {
/// The company res... | {
assert_eq!(Version::parse("1"), Err("1"));
assert_eq!(Version::parse("1."), Err("1."));
assert_eq!(Version::parse("1 h3l1o. W0rld"), Err("1 h3l1o. W0rld"));
assert_eq!(Version::parse("1. h3l1o. W0rld"), Err("1. h3l1o. W0rld"));
assert_eq!(Version::parse("1.2.3"), Ok(Version(1, ... | identifier_body | |
mod.rs | allocated string from the implementation using
/// `glGetString`. Fails if it `GLenum` cannot be handled by the
/// implementation's `gl::GetString` function.
fn get_string(name: gl::types::GLenum) -> &'static str {
let ptr = gl::GetString(name) as *const i8;
if!ptr.is_null() {
// This should be safe t... | error!("Ignored unsupported GL Request: {}", request)
}
},
super::BindAttribute(slot, buffer, count, el_type, stride, offset) => {
let gl_type = match el_type {
a::Int(_, a::U8, a::Unsigned) => gl::UNSIGNED_BYTE,
... | } else { | random_line_split |
mod.rs | string from the implementation using
/// `glGetString`. Fails if it `GLenum` cannot be handled by the
/// implementation's `gl::GetString` function.
fn get_string(name: gl::types::GLenum) -> &'static str {
let ptr = gl::GetString(name) as *const i8;
if!ptr.is_null() {
// This should be safe to mark as ... | (src: &'static str) -> Result<Version, &'static str> {
let (version, vendor_info) = match src.find(' ') {
Some(i) => (src.slice_to(i), src.slice_from(i + 1)),
None => (src, ""),
};
// TODO: make this even more lenient so that we can also accept
// `<major> "." <m... | parse | identifier_name |
edit_ops.rs | // Copyright 2020 The xi-editor 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 ag... | <BT, AT>(
base: &Rope,
regions: &[SelRegion],
before_text: BT,
after_text: AT,
) -> RopeDelta
where
BT: Into<Rope>,
AT: Into<Rope>,
{
let mut builder = DeltaBuilder::new(base.len());
let before_rope = before_text.into();
let after_rope = after_text.into();
for region in regions {... | surround | identifier_name |
edit_ops.rs | // Copyright 2020 The xi-editor 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 ag... | else {
None
};
(delete_sel_regions(base, &deletions), kill_ring)
}
/// Deletes the given regions.
pub(crate) fn delete_sel_regions(base: &Rope, sel_regions: &[SelRegion]) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
for region in sel_regions {
let iv = Interval::new... | {
let saved = extract_sel_regions(base, &deletions).unwrap_or_default();
Some(Rope::from(saved))
} | conditional_block |
edit_ops.rs | // Copyright 2020 The xi-editor 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 ag... |
(delete_sel_regions(base, &deletions), kill_ring)
}
/// Deletes the given regions.
pub(crate) fn delete_sel_regions(base: &Rope, sel_regions: &[SelRegion]) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
for region in sel_regions {
let iv = Interval::new(region.min(), region.max()... | {
// We compute deletions as a selection because the merge logic
// is convenient. Another possibility would be to make the delta
// builder able to handle overlapping deletions (with union semantics).
let mut deletions = Selection::new();
for &r in regions {
if r.is_caret() {
le... | identifier_body |
edit_ops.rs | // Copyright 2020 The xi-editor 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 ag... |
fn outdent(base: &Rope, lines: BTreeSet<usize>, tab_text: &str) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
for line in lines {
let offset = LogicalLines.line_col_to_offset(base, line, 0);
let tab_offset = LogicalLines.line_col_to_offset(base, line, tab_text.len());
... | random_line_split | |
generate.rs | /*fn search(width: usize, height: usize, words: &[Word], tries: &[&Trie], acrosses: &mut Vec<Word>) {
if height == acrosses.len() {
let downs: Vec<Word> = (0..width).map(|x| (0..height).map(|y| acrosses[y][x]).collect()).collect();
if!iproduct!(acrosses.iter(), downs.iter()).any(|(a, b)| a == b) {
... | clues.insert("CHEAP", "Overpowered, in the 90's");
clues.insert("RAG", "with \"on\", tease");
clues.insert("OVA", "Largest human cells");
clues.insert("RALLY", "Make a comeback, as a military force");
clues.insert("ANTS", "Pants' contents?");
clues.insert("EDIT", "Amend");
clues.insert("AGAR... | clues.insert("ICETEA", "???");
clues.insert("DOB", "Important date: abbr"); | random_line_split |
generate.rs | /*fn search(width: usize, height: usize, words: &[Word], tries: &[&Trie], acrosses: &mut Vec<Word>) {
if height == acrosses.len() {
let downs: Vec<Word> = (0..width).map(|x| (0..height).map(|y| acrosses[y][x]).collect()).collect();
if!iproduct!(acrosses.iter(), downs.iter()).any(|(a, b)| a == b) {
... | ];
for c in line.chars() {
if c == '█' {
row.push(Cell::Black);
} else {
row.push(Cell::White(Letter::from_unicode(c)));
}
}
rows.push(row);
}
let grid = Grid::new((rows[0].len(), rows.len()), |x, y| rows[y][x]);
pri... | ow = vec![ | identifier_name |
generate.rs | /*fn search(width: usize, height: usize, words: &[Word], tries: &[&Trie], acrosses: &mut Vec<Word>) {
if height == acrosses.len() {
let downs: Vec<Word> = (0..width).map(|x| (0..height).map(|y| acrosses[y][x]).collect()).collect();
if!iproduct!(acrosses.iter(), downs.iter()).any(|(a, b)| a == b) {
... | //dictionary.push(Word::from_str("bamboozled").unwrap());
//dictionary.push(Word::from_str("shortchanged").unwrap());
/* let windows = windows(&grid, |cell| {
match cell {
Cell::Black => true,
_ => false,
}
});
make_choices(&dictiona... | RT);
let mut rows = vec![];
for line in reader.records() {
let mut row = vec![];
for cell in line?.iter() {
row.push(match cell {
"!" => Cell::Black,
"" => Cell::White(None),
letter => Cell::White(Some(Letter::from_unicode(letter.chars(... | identifier_body |
ctl.rs | use std::{path::PathBuf, process::ExitCode};
use crate::daemon::{config::CliArg, tracing::LogLevel, Config, ObservableState};
use tracing_subscriber::util::SubscriberInitExt;
const USAGE_MSG: &str = "\
usage: ntp-ctl validate [-c PATH]
ntp-ctl status [-f FORMAT] [-c PATH] [-o PATH]
ntp-ctl -h | ntp-ctl ... | () -> std::io::Result<ExitCode> {
let options = match NtpDaemonOptions::try_parse_from(std::env::args()) {
Ok(options) => options,
Err(msg) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, msg)),
};
match options.action {
NtpCtlAction::Help => {
printl... | main | identifier_name |
ctl.rs | use std::{path::PathBuf, process::ExitCode};
use crate::daemon::{config::CliArg, tracing::LogLevel, Config, ObservableState};
use tracing_subscriber::util::SubscriberInitExt;
const USAGE_MSG: &str = "\
usage: ntp-ctl validate [-c PATH]
ntp-ctl status [-f FORMAT] [-c PATH] [-o PATH]
ntp-ctl -h | ntp-ctl ... | let observation = config
.observability
.observe
.observation_path
.unwrap_or_else(|| PathBuf::from("/run/ntpd-rs/observe"));
match options.format {
Format::Plain => print_state(Format::Plain, observation).await,
... | let config = config.unwrap_or_default();
| random_line_split |
ctl.rs | use std::{path::PathBuf, process::ExitCode};
use crate::daemon::{config::CliArg, tracing::LogLevel, Config, ObservableState};
use tracing_subscriber::util::SubscriberInitExt;
const USAGE_MSG: &str = "\
usage: ntp-ctl validate [-c PATH]
ntp-ctl status [-f FORMAT] [-c PATH] [-o PATH]
ntp-ctl -h | ntp-ctl ... |
},
CliArg::Argument(option, value) => match option.as_str() {
"-c" | "--config" => {
options.config = Some(PathBuf::from(value));
}
"-f" | "--format" => match value.as_str() {
"pl... | {
Err(format!("invalid option provided: {option}"))?;
} | conditional_block |
util.rs | //! Utility traits and functions.
use std::ffi;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::result;
use std::time;
use anyhow::{Context as ResultExt, Error, Result};
use fs2::{lock_contended_error, FileExt};
use crate::context::{Context, SettingsExt};
/// Returns ... | fn _submodule_update(repo: &Repository, todo: &mut Vec<Repository>) -> Result<(), Error> {
for mut submodule in repo.submodules()? {
submodule.update(true, None)?;
todo.push(submodule.open()?);
}
Ok(())
}
let mut repos = Vec::ne... | }
/// Recursively update Git submodules.
pub fn submodule_update(repo: &Repository) -> Result<(), Error> { | random_line_split |
util.rs | //! Utility traits and functions.
use std::ffi;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::result;
use std::time;
use anyhow::{Context as ResultExt, Error, Result};
use fs2::{lock_contended_error, FileExt};
use crate::context::{Context, SettingsExt};
/// Returns ... | {
/// The temporary directory or file path.
path: Option<PathBuf>,
}
impl TempPath {
/// Create a new `TempPath` based on an original path, the temporary
/// filename will be placed in the same directory with a deterministic name.
///
/// # Errors
///
/// If the temporary path already ... | TempPath | identifier_name |
util.rs | //! Utility traits and functions.
use std::ffi;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::result;
use std::time;
use anyhow::{Context as ResultExt, Error, Result};
use fs2::{lock_contended_error, FileExt};
use crate::context::{Context, SettingsExt};
/// Returns ... |
/// Fetch a Git repository.
pub fn fetch(repo: &Repository) -> anyhow::Result<()> {
with_fetch_options(|mut opts| {
repo.find_remote("origin")
.context("failed to find remote `origin`")?
.fetch(&DEFAULT_REFSPECS, Some(&mut opts), None)?;
Ok(())
... | {
with_fetch_options(|mut opts| {
let repo = Repository::init(dir)?;
repo.remote("origin", url.as_str())?
.fetch(&DEFAULT_REFSPECS, Some(&mut opts), None)?;
Ok(repo)
})
.with_context(s!("failed to git clone `{}`", url))
} | identifier_body |
bignum.rs | /* Copyright (c) Fortanix, Inc.
*
* Licensed under the GNU General Public License, version 2 <LICENSE-GPL or
* https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version
* 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your
* option. This file may not be copied, modified, or ... | () {
use std::str::FromStr;
fn mod_sqrt_test(a: &str, n: &str, expected: &str) {
let a = Mpi::from_str(a).unwrap();
let n = Mpi::from_str(n).unwrap();
let expected = Mpi::from_str(expected).unwrap();
let mut computed = a.mod_sqrt(&n).unwrap();
/*
If x = (a*a) mo... | test_mod_sqrt_fn | identifier_name |
bignum.rs | /* Copyright (c) Fortanix, Inc.
*
* Licensed under the GNU General Public License, version 2 <LICENSE-GPL or
* https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version
* 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your
* option. This file may not be copied, modified, or ... | n.to_binary()
}
#[test]
fn test_base58_encode() {
fn test_base58_rt(input: &[u8], expected: &str) {
assert_eq!(base58_encode(input).unwrap(), expected);
assert_eq!(base58_decode(expected).unwrap(), input);
}
test_base58_rt(b"", "");
test_base58_rt(&[32], "Z");
test_base58_rt(&... | {
let radix: i64 = 58;
let mut n = Mpi::new(0)?;
fn base58_val(b: u8) -> mbedtls::Result<usize> {
for (i, c) in BASE58_ALPHABET.iter().enumerate() {
if *c == b {
return Ok(i);
}
}
Err(mbedtls::Error::Base64InvalidCharacter)
}
for c i... | identifier_body |
bignum.rs | /* Copyright (c) Fortanix, Inc.
*
* Licensed under the GNU General Public License, version 2 <LICENSE-GPL or
* https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version
* 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your
* option. This file may not be copied, modified, or ... | #[cfg(feature = "std")]
#[test]
fn test_jacobi_fn() {
use std::str::FromStr;
fn jacobi_symbol_test(a: &str, n: &str, expected: i32) {
let a = Mpi::from_str(a).unwrap();
let n = Mpi::from_str(n).unwrap();
let j = a.jacobi(&n).unwrap();
//println!("a={} n={} J={}", a, n, j);
... | }
| random_line_split |
bignum.rs | /* Copyright (c) Fortanix, Inc.
*
* Licensed under the GNU General Public License, version 2 <LICENSE-GPL or
* https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version
* 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your
* option. This file may not be copied, modified, or ... |
assert_eq!(computed, expected);
}
// Tests generated by Sagemath
mod_sqrt_test("2", "7", "4");
mod_sqrt_test("5", "469289024411159", "234325000312516");
mod_sqrt_test(
"458050473005020050313790240477",
"905858848829014223214249213947",
"12647408626047957484571419433... | {
computed = (&n - &computed).unwrap();
} | conditional_block |
lib.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... | ;
<EnclaveRegistry<T>>::insert(enclave_idx, &enclave);
Ok(())
}
fn remove_enclave(sender: &T::AccountId) -> DispatchResult {
ensure!(
<EnclaveIndex<T>>::contains_key(sender),
<Error<T>>::InexistentEnclave
);
let index_to_remove = <EnclaveIndex<T>... | {
let enclaves_count = Self::enclave_count()
.checked_add(1)
.ok_or("[Teerex]: Overflow adding new enclave to registry")?;
<EnclaveIndex<T>>::insert(sender, enclaves_count);
<EnclaveCount>::put(enclaves_count);
enclaves_count
} | conditional_block |
lib.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... |
}
impl<T: Config> OnTimestampSet<T::Moment> for Module<T> {
fn on_timestamp_set(moment: T::Moment) {
Self::unregister_silent_workers(moment)
}
}
mod benchmarking;
#[cfg(test)]
mod mock;
mod test_utils;
#[cfg(test)]
mod tests;
pub mod weights;
| {
use sp_runtime::traits::CheckedSub;
let elapsed_time = <timestamp::Pallet<T>>::get()
.checked_sub(&T::Moment::saturated_from(report_timestamp))
.ok_or("Underflow while calculating elapsed time since report creation")?;
if elapsed_time < T::MomentsPerDay::get() {
... | identifier_body |
lib.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... | (index_to_remove: u64, new_enclaves_count: u64) -> DispatchResult {
if index_to_remove!= new_enclaves_count {
let last_enclave = <EnclaveRegistry<T>>::get(&new_enclaves_count);
<EnclaveRegistry<T>>::insert(index_to_remove, &last_enclave);
<EnclaveIndex<T>>::insert(last_enclav... | swap_and_pop | identifier_name |
lib.rs | /*
Copyright 2021 Integritee AG and Supercomputing Systems AG
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... | CallConfirmed(AccountId, H256),
BlockConfirmed(AccountId, H256),
}
);
decl_storage! {
trait Store for Module<T: Config> as Teerex {
// Simple lists are not supported in runtime modules as theoretically O(n)
// operations can be executed while only being charged O(1), see substra... | random_line_split | |
mod.rs | .
// See the License for the specific language governing permissions and
// limitations under the License.
pub use self::metadata::{BinaryAttribute, IndexState, IndexType, ViewWithMetadata};
use std::{borrow::Cow, fmt, iter::Peekable, marker::PhantomData};
use super::{
db::{Change, ChangesMut, ChangesRef, ForkIt... | pub trait ChangeSet {
fn as_ref(&self) -> Option<&ViewChanges>;
/// Provides mutable reference to changes. The implementation for a `RawAccessMut` type
/// should always return `Some(_)`.
fn as_mut(&mut self) -> Option<&mut ViewChanges>;
}
/// No-op implementation used in `Snapshot`.
impl ChangeSet for... | random_line_split | |
mod.rs |
// See the License for the specific language governing permissions and
// limitations under the License.
pub use self::metadata::{BinaryAttribute, IndexState, IndexType, ViewWithMetadata};
use std::{borrow::Cow, fmt, iter::Peekable, marker::PhantomData};
use super::{
db::{Change, ChangesMut, ChangesRef, ForkIte... |
fn as_mut(&mut self) -> Option<&mut ViewChanges> {
None
}
}
impl ChangeSet for ChangesRef {
fn as_ref(&self) -> Option<&ViewChanges> {
Some(&*self)
}
fn as_mut(&mut self) -> Option<&mut ViewChanges> {
None
}
}
impl ChangeSet for ChangesMut<'_> {
fn as_ref(&self) ->... | {
None
} | identifier_body |
mod.rs |
// See the License for the specific language governing permissions and
// limitations under the License.
pub use self::metadata::{BinaryAttribute, IndexState, IndexType, ViewWithMetadata};
use std::{borrow::Cow, fmt, iter::Peekable, marker::PhantomData};
use super::{
db::{Change, ChangesMut, ChangesRef, ForkIte... |
}
}
}
struct ChangesIter<'a, T: Iterator + 'a> {
inner: Peekable<T>,
_lifetime: PhantomData<&'a ()>,
}
/// Iterator over a set of changes.
impl<'a, T> ChangesIter<'a, T>
where
T: Iterator<Item = (&'a Vec<u8>, &'a Change)>,
{
fn new(iterator: T) -> Self {
ChangesIter {
... | {
self.ended = true;
None
} | conditional_block |
mod.rs |
// See the License for the specific language governing permissions and
// limitations under the License.
pub use self::metadata::{BinaryAttribute, IndexState, IndexType, ViewWithMetadata};
use std::{borrow::Cow, fmt, iter::Peekable, marker::PhantomData};
use super::{
db::{Change, ChangesMut, ChangesRef, ForkIte... | (&mut self) -> Option<(&[u8], &[u8])> {
loop {
match self.inner.peek() {
Some((key, &Change::Put(ref value))) => {
return Some((key.as_slice(), value.as_slice()));
}
Some((_, &Change::Delete)) => {}
None => {
... | peek | identifier_name |
network.rs | extern crate openssl;
extern crate rand;
extern crate reqwest;
use crate::utils;
use crate::mojang::{Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;... | loop {
/*let now = SystemTime::now();
let time_since = now.duration_since(last_tick_time).unwrap().as_millis();
if time_since > 50 {
last_tick_time = now;
}
*/
self.receive_clients();
self.receive_packets();
... | random_line_split | |
network.rs | extern crate openssl;
extern crate rand;
extern crate reqwest;
use crate::utils;
use crate::mojang::{Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;... |
fn start(mut self) {
println!("Listening for connections...");
//let mut last_tick_time = SystemTime::now();
loop {
/*let now = SystemTime::now();
let time_since = now.duration_since(last_tick_time).unwrap().as_millis();
if time_since > 50 {
... | { // TODO: Clean up maybe
let mut finished_indicies = Vec::new();
for (i, pending) in self.mojang.has_joined_pending.iter().enumerate() {
if pending.result.is_some() {
finished_indicies.push(i);
}
}
for index in finished_indicies {
let ... | identifier_body |
network.rs | extern crate openssl;
extern crate rand;
extern crate reqwest;
use crate::utils;
use crate::mojang::{Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;... | (&mut self) {
let num_clients = self.clients.len();
for client in 0..num_clients {
let mut packets = self.clients[client]
.connection
.receive_packets();
for packet_batch in packets.drain(..) {
for packet in PacketDecoder::new_batch(p... | receive_packets | identifier_name |
network.rs | extern crate openssl;
extern crate rand;
extern crate reqwest;
use crate::utils;
use crate::mojang::{Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;... |
}
fn poll_mojang(&mut self) { // TODO: Clean up maybe
let mut finished_indicies = Vec::new();
for (i, pending) in self.mojang.has_joined_pending.iter().enumerate() {
if pending.result.is_some() {
finished_indicies.push(i);
}
}
for index i... | {
self.clients.push(client);
} | conditional_block |
color.rs | //!
//! A library providing simple `Color` and `Gradient` types along with useful transformations and
//! presets.
//!
//!
//! Inspiration taken from [elm-lang's color module]
//! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
//!
//!
//! Module for working with colors. ... | pub fn light_brown() -> Color { rgb_bytes(233, 185, 110) }
/// Chocolate - Regular - #C17D11
pub fn brown() -> Color { rgb_bytes(193, 125, 17 ) }
/// Chocolate - Dark - #8F5902
pub fn dark_brown() -> Color { rgb_bytes(143, 89 , 2 ) }
/// Straight Black.
pub fn black() -> Color { rgb_bytes(0 ... | /// Chocolate - Light - #E9B96E | random_line_split |
color.rs | //!
//! A library providing simple `Color` and `Gradient` types along with useful transformations and
//! presets.
//!
//!
//! Inspiration taken from [elm-lang's color module]
//! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
//!
//!
//! Module for working with colors. ... | (self, h: f32, s: f32, l: f32, a: f32) -> Self {
self.color(hsla(h, s, l, a))
}
/// Set the color of the widget from hsl values.
fn hsl(self, h: f32, s: f32, l: f32) -> Self {
self.color(hsl(h, s, l))
}
}
| hsla | identifier_name |
color.rs | //!
//! A library providing simple `Color` and `Gradient` types along with useful transformations and
//! presets.
//!
//!
//! Inspiration taken from [elm-lang's color module]
//! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
//!
//!
//! Module for working with colors. ... |
else {
(clampf32((1.0 - r) * 0.75 + r),
clampf32((1.0 - g) * 0.25 + g),
clampf32((1.0 - b) * 0.25 + b))
}
};
let a = clampf32((1.0 - a) * 0.75 + a);
rgba(r, g, b, a)
}
/// Return the Color's invert.
pub fn in... | { (r + 0.4, g + 0.2, b + 0.2) } | conditional_block |
color.rs | //!
//! A library providing simple `Color` and `Gradient` types along with useful transformations and
//! presets.
//!
//!
//! Inspiration taken from [elm-lang's color module]
//! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
//!
//!
//! Module for working with colors. ... |
/// Return either black or white, depending which contrasts the Color the most. This will be
/// useful for determining a readable color for text on any given background Color.
pub fn plain_contrast(self) -> Color {
if self.luminance() > 0.5 { black() } else { white() }
}
/// Extract the ... | {
match *self {
Color::Rgba(r, g, b, _) => (r + g + b) / 3.0,
Color::Hsla(_, _, l, _) => l,
}
} | identifier_body |
lib.rs | //! Hindley–Milner type inference for arithmetic expressions parsed
//! by the [`arithmetic-parser`] crate.
//!
//! This crate allows parsing type annotations as a part of a [`Grammar`], and to infer
//! and check types for expressions / statements produced by `arithmetic-parser`.
//! Type inference is *partially* comp... | / Grammar with support of type annotations. Works as a decorator.
///
/// # Examples
///
/// ```
/// use arithmetic_parser::grammars::{F32Grammar, Parse};
/// use arithmetic_typing::Annotated;
///
/// # fn main() -> anyhow::Result<()> {
/// let code = "x: [Num] = (1, 2, 3);";
/// let ast = Annotated::<F32Grammar>::pars... | ConstraintSet::default()
}
}
// | identifier_body |
lib.rs | //! Hindley–Milner type inference for arithmetic expressions parsed
//! by the [`arithmetic-parser`] crate.
//!
//! This crate allows parsing type annotations as a part of a [`Grammar`], and to infer
//! and check types for expressions / statements produced by `arithmetic-parser`.
//! Type inference is *partially* comp... | : InputSpan<'a>) -> NomResult<'a, Self::Type> {
use nom::combinator::map;
map(TypeAst::parse, |ast| ast.extra)(input)
}
}
/// Supports all syntax features.
impl<T: ParseLiteral> Parse<'_> for Annotated<T> {
type Base = Self;
const FEATURES: Features = Features::all();
}
| type(input | identifier_name |
lib.rs | //! Hindley–Milner type inference for arithmetic expressions parsed
//! by the [`arithmetic-parser`] crate.
//!
//! This crate allows parsing type annotations as a part of a [`Grammar`], and to infer
//! and check types for expressions / statements produced by `arithmetic-parser`.
//! Type inference is *partially* comp... | /// # assert_eq!(ast.statements.len(), 1);
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Annotated<T>(PhantomData<T>);
impl<T: ParseLiteral> ParseLiteral for Annotated<T> {
type Lit = T::Lit;
fn parse_literal(input: InputSpan<'_>) -> NomResult<'_, Self::Lit> {
<T as ParseLiteral>::parse_lit... | /// let code = "x: [Num] = (1, 2, 3);";
/// let ast = Annotated::<F32Grammar>::parse_statements(code)?; | random_line_split |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use clap::{App, Arg};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
u... |
}
fn read_train_data(labels: impl AsRef<Path>, features: impl AsRef<Path>) -> TrainData {
let (output_size, labels) = read_file_as_tensors(labels);
let (input_size, features) = read_file_as_tensors(features);
let data_pair = labels
.into_par_iter()
.zip_eq(features)
.filter(|(output, ... | {
TrainDataPair { input, output }
} | identifier_body |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use clap::{App, Arg};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
u... | (labels: impl AsRef<Path>, features: impl AsRef<Path>) -> TrainData {
let (output_size, labels) = read_file_as_tensors(labels);
let (input_size, features) = read_file_as_tensors(features);
let data_pair = labels
.into_par_iter()
.zip_eq(features)
.filter(|(output, _)| output.value_count... | read_train_data | identifier_name |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use clap::{App, Arg};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
u... | input: input_value,
output: output_value,
} = &data;
assert_eq!(output_value.value_count(), 1);
input.set_value(input_value.clone().into());
output.set_expect_output(output_value.clone());
... | let mut accuracy = 0f64;
for data in &data_pair[range] {
let TrainDataPair { | random_line_split |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use clap::{App, Arg};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
u... | else {
0.
}
}
};
sum_of_loss += *output_loss.get([]).unwrap() as f64;
if back_propagate {
output.clear_gradient_all();
output.b... | {
1.
} | conditional_block |
shader.rs | #![allow(dead_code)]
use std;
use math::*;
use rendering::gl;
use std::fmt::Write;
#[derive(Copy, Clone, Debug)]
pub struct Shader {
pub gl_handle: u32,
pub proj_loc: i32,
pub view_loc: i32,
}
impl Shader {
pub fn new(vertex_shader_src: &str, fragment_shader_src: &str) -> Result<Shader, String> {
use std::ff... | let (v,f) = self.finalize_source();
let mut s = Shader::new(&v, &f)?;
for (idx, attrib_name) in attributes.iter().enumerate() {
unsafe {
gl::BindAttribLocation(s.gl_handle, 1 + idx as u32, attrib_name.as_ptr());
}
}
unsafe {
gl::BindAttribLocation(s.gl_handle, 0, b"position\0".as_ptr() as _);
... | .collect::<Vec<_>>();
| random_line_split |
shader.rs | #![allow(dead_code)]
use std;
use math::*;
use rendering::gl;
use std::fmt::Write;
#[derive(Copy, Clone, Debug)]
pub struct Shader {
pub gl_handle: u32,
pub proj_loc: i32,
pub view_loc: i32,
}
impl Shader {
pub fn new(vertex_shader_src: &str, fragment_shader_src: &str) -> Result<Shader, String> {
use std::ff... |
pub fn attribute(mut self, name: &str, ty: &str) -> Self {
if name == "position" {
println!("Tried to overwrite 'position' attribute while building shader - ignoring");
return self
}
self.attributes.push(format!("{} {}", ty, name)); self
}
pub fn varying(mut self, name: &str, ty: &str) -> Self {
se... | {
self.uniforms.push(format!("{} u_{}", ty, name)); self
} | identifier_body |
shader.rs | #![allow(dead_code)]
use std;
use math::*;
use rendering::gl;
use std::fmt::Write;
#[derive(Copy, Clone, Debug)]
pub struct Shader {
pub gl_handle: u32,
pub proj_loc: i32,
pub view_loc: i32,
}
impl Shader {
pub fn new(vertex_shader_src: &str, fragment_shader_src: &str) -> Result<Shader, String> {
use std::ff... | <V>(&self, uniform: &str, v: V) where V: Into<Vec3> {
assert!(self.is_bound(), "Tried to set uniform '{}' on unbound shader", uniform);
unsafe {
let v = v.into();
gl::Uniform3f(self.get_uniform_loc(&uniform), v.x, v.y, v.z);
}
}
pub fn set_uniform_vec4<V>(&self, uniform: &str, v: V) where V: Into<Vec4> ... | set_uniform_vec3 | identifier_name |
shader.rs | #![allow(dead_code)]
use std;
use math::*;
use rendering::gl;
use std::fmt::Write;
#[derive(Copy, Clone, Debug)]
pub struct Shader {
pub gl_handle: u32,
pub proj_loc: i32,
pub view_loc: i32,
}
impl Shader {
pub fn new(vertex_shader_src: &str, fragment_shader_src: &str) -> Result<Shader, String> {
use std::ff... | else {
gl_position.push_str("vec4(position, 0.0, 1.0);\n");
}
self.vertex_body = format!("{}{}", gl_position, self.vertex_body);
let mut bodies = [&mut self.vertex_body, &mut self.fragment_body];
for (sh, body) in [&mut vert_src, &mut frag_src].iter_mut().zip(bodies.iter_mut()) {
write!(sh, "\n{}\n", v... | {
gl_position.push_str("vec4(position, 1.0);\n");
} | conditional_block |
mod.rs | x1 && v.1 >= y0 && v.1 < y1
}
fn restore_view_plugins(docks: &[DockHandle],
view_plugins: &mut ViewPlugins,
info: &mut HashMap<u64, PluginInstanceInfo>) {
for dock in docks.iter() {
if!view_plugins.get_view(ViewHandle(dock.0)).is_some() {
let inf... |
let ui = &instance.ui;
Imgui::init_state(ui.api);
let pos = ui.get_window_pos();
let size = ui.get_window_size();
Imgui::mark_show_popup(ui.api, is_inside(mouse, pos, size) && show_context_menu);
// Draw drag zone
if let &Some((handle, rect)) = overlay {
... | {
Imgui::begin_window_child("tabs", 20.0);
let mut borders = Vec::with_capacity(tab_names.len());
// TODO: should repeated window names be avoided?
for (i, name) in tab_names.iter().enumerate() {
if Imgui::tab(name,
i == ws_co... | conditional_block |
mod.rs | < x1 && v.1 >= y0 && v.1 < y1
}
fn restore_view_plugins(docks: &[DockHandle],
view_plugins: &mut ViewPlugins,
info: &mut HashMap<u64, PluginInstanceInfo>) {
for dock in docks.iter() {
if!view_plugins.get_view(ViewHandle(dock.0)).is_some() {
let i... | session: &mut Session,
show_context_menu: bool,
mouse: (f32, f32),
overlay: &Option<(DockHandle, Rect)>)
-> WindowState {
let ws_container = match ws.root_area
.as_mut()
.and_then(|root| root.ge... | }
fn update_view(ws: &mut Workspace,
view_plugins: &mut ViewPlugins,
handle: ViewHandle, | random_line_split |
mod.rs | x1 && v.1 >= y0 && v.1 < y1
}
fn restore_view_plugins(docks: &[DockHandle],
view_plugins: &mut ViewPlugins,
info: &mut HashMap<u64, PluginInstanceInfo>) {
for dock in docks.iter() {
if!view_plugins.get_view(ViewHandle(dock.0)).is_some() {
let inf... | (&self, view_plugins: &mut ViewPlugins) -> bool {
// TODO: Use setting for this name
for handle in self.ws.get_docks() {
if let Some(plugin) = view_plugins.get_view(ViewHandle(handle.0)) {
if plugin.name == "Source Code View" {
return true;
... | has_source_code_view | identifier_name |
mod.rs | x1 && v.1 >= y0 && v.1 < y1
}
fn restore_view_plugins(docks: &[DockHandle],
view_plugins: &mut ViewPlugins,
info: &mut HashMap<u64, PluginInstanceInfo>) {
for dock in docks.iter() {
if!view_plugins.get_view(ViewHandle(dock.0)).is_some() {
let inf... | context_menu_data: None,
statusbar: Statusbar::new(),
custom_menu_height: 0.0,
config_backend: None,
view_rename_state: ViewRenameState::None,
};
res.initialize_workspace_state();
Ok(res)
}
pub fn pre_update(&mut self) {
... | {
let options = WindowOptions {
resize: true,
scale: Scale::X1,
..WindowOptions::default()
};
let win = try!(minifb::Window::new("ProDBG", width, height, options));
let ws = Workspace::new(Rect::new(0.0, 0.0, width as f32, (height - 20) as f32));
... | identifier_body |
stack.rs | // Copyright 2017-2018 the authors. See the 'Copyright and license' section of the
// README.md file at the top-level directory of this repository.
//
// Licensed under the Apache License, Version 2.0 (the LICENSE-APACHE file) or
// the MIT license (the LICENSE-MIT file) at your option. This file may not be
// copied, ... | (&self) -> Option<NonNull<SlabHeader>> {
self.next
}
fn prev(&self) -> Option<NonNull<SlabHeader>> {
self.prev
}
fn set_next(&mut self, next: Option<NonNull<SlabHeader>>) {
self.next = next;
}
fn set_prev(&mut self, prev: Option<NonNull<SlabHeader>>) {
self.prev =... | next | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.