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 |
|---|---|---|---|---|
utils.rs | use std::ffi::{c_void, CStr};
use std::mem::{MaybeUninit, size_of_val, transmute};
use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut};
use itertools::Itertools;
use log::error;
use ntapi::ntpebteb::PEB;
use ntapi::ntpsapi::{NtQueryInformationProcess, PROCESS_BASIC_INFORMATION, ProcessBasicInformation};
use... |
pub unsafe fn get_executable_description(exe: &Path) -> Result<String, ()> {
let exe_utf16 = exe.to_str().unwrap().to_utf16_null();
let mut handle: DWORD = 0;
let size = GetFileVersionInfoSizeW(exe_utf16.as_ptr(), &mut handle);
if size == 0 {
error!("GetFileVersionInfoSizeW, err={}, exe={}", ... | {
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if process == null_mut() {
return Err(Error::new("OpenProcess").into());
};
let _close_process = close_handle(process);
let mut name = [0u16; 32 * 1024];
let length = GetModuleFileNameExW(process, null_mut(), na... | identifier_body |
utils.rs | use std::ffi::{c_void, CStr};
use std::mem::{MaybeUninit, size_of_val, transmute}; |
use itertools::Itertools;
use log::error;
use ntapi::ntpebteb::PEB;
use ntapi::ntpsapi::{NtQueryInformationProcess, PROCESS_BASIC_INFORMATION, ProcessBasicInformation};
use ntapi::ntrtl::RTL_USER_PROCESS_PARAMETERS;
use winapi::shared::guiddef::GUID;
use winapi::shared::minwindef::{BOOL, DWORD, FALSE, LPARAM, TRUE};
u... | use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut}; | random_line_split |
utils.rs | use std::ffi::{c_void, CStr};
use std::mem::{MaybeUninit, size_of_val, transmute};
use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut};
use itertools::Itertools;
use log::error;
use ntapi::ntpebteb::PEB;
use ntapi::ntpsapi::{NtQueryInformationProcess, PROCESS_BASIC_INFORMATION, ProcessBasicInformation};
use... | (_config: &Config, mut pid: u32)
-> wrapperrs::Result<RequesterInfo> {
let mut process_stack = Vec::new();
while pid!= 0 {
let window = find_primary_window(pid);
process_stack.push((pid, window));
pid = get_parent_pid(pid);
}
let main_process = process_stack.iter()
.f... | collect_requester_info | identifier_name |
mod.rs | Debug, serde::Serialize, serde::Deserialize)]
enum Msg {
SetupMsg(SetupMsg),
CommMsg(CommMsg),
}
// Control messages exchanged during the setup phase only
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
enum SetupMsg {
MyPortInfo(MyPortInfo),
LeaderWave { wave_leader: ConnectorId },
... | }
// One of two endpoints for a control channel with a connector on either end.
// The underlying transport is TCP, so we use an inbox buffer to allow
// discrete payload receipt.
struct NetEndpoint {
inbox: Vec<u8>,
stream: TcpStream,
}
// Datastructure used during the setup phase representing a NetEndpoint ... | Equivalent,
New(Predicate),
Nonexistant, | random_line_split |
mod.rs | , serde::Serialize, serde::Deserialize)]
enum Msg {
SetupMsg(SetupMsg),
CommMsg(CommMsg),
}
// Control messages exchanged during the setup phase only
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
enum SetupMsg {
MyPortInfo(MyPortInfo),
LeaderWave { wave_leader: ConnectorId },
Leader... |
}
// No errors! Time to modify `cu`
// create a new component and identifier
let Connector { phased, unphased: cu } = self;
let new_cid = cu.ips.id_manager.new_component_id();
cu.proto_components.insert(new_cid, cu.proto_description.new_component(module_name, identifier,... | {
return Err(Ace::WrongPortPolarity { port, expected_polarity });
} | conditional_block |
mod.rs | if the round fails.
struct RoundCtx {
solution_storage: SolutionStorage,
spec_var_stream: SpecVarStream,
payload_inbox: Vec<(PortId, SendPayloadMsg)>,
deadline: Option<Instant>,
ips: IdAndPortState,
}
// A trait intended to limit the access of the ConnectorUnphased structure
// such that we don't ... | fmt | identifier_name | |
mod.rs | , serde::Serialize, serde::Deserialize)]
enum Msg {
SetupMsg(SetupMsg),
CommMsg(CommMsg),
}
// Control messages exchanged during the setup phase only
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
enum SetupMsg {
MyPortInfo(MyPortInfo),
LeaderWave { wave_leader: ConnectorId },
Leader... |
fn new_spec_var_stream(&self) -> SpecVarStream {
// Spec var stream starts where the current port_id stream ends, with gap of SKIP_N.
// This gap is entirely unnecessary (i.e. 0 is fine)
// It's purpose is only to make SpecVars easier to spot in logs.
// E.g. spot the spec var: { v0... | {
Self {
connector_id,
port_suffix_stream: Default::default(),
component_suffix_stream: Default::default(),
}
} | identifier_body |
obj.rs | libcalls that relocations are applied
/// against.
///
/// Note that this isn't typically used. It's only used for SSE-disabled
/// builds without SIMD on x86_64 right now.
libcall_symbols: HashMap<LibCall, SymbolId>,
ctrl_plane: ControlPlane,
}
impl<'a> ModuleTextBuilder<'a> {
/// Create... | ///
/// Returns the symbol associated with the function as well as the range
/// that the function resides within the text section.
pub fn append_func(
&mut self,
name: &str,
compiled_func: &'a CompiledFunction<impl CompiledFuncEnv>,
resolve_reloc_target: impl Fn(FuncInde... | /// within `CompiledFunction` and the return value must be an index where
/// the target will be defined by the `n`th call to `append_func`. | random_line_split |
obj.rs | calls that relocations are applied
/// against.
///
/// Note that this isn't typically used. It's only used for SSE-disabled
/// builds without SIMD on x86_64 right now.
libcall_symbols: HashMap<LibCall, SymbolId>,
ctrl_plane: ControlPlane,
}
impl<'a> ModuleTextBuilder<'a> {
/// Creates a ... | self.unwind_info.push(off, body_len, info);
}
for r in compiled_func.relocations() {
match r.reloc_target {
// Relocations against user-defined functions means that this is
// a relocation against a module-local function, typically a
... | {
let body = compiled_func.buffer.data();
let alignment = compiled_func.alignment;
let body_len = body.len() as u64;
let off = self
.text
.append(true, &body, alignment, &mut self.ctrl_plane);
let symbol_id = self.obj.add_symbol(Symbol {
name:... | identifier_body |
obj.rs | calls that relocations are applied
/// against.
///
/// Note that this isn't typically used. It's only used for SSE-disabled
/// builds without SIMD on x86_64 right now.
libcall_symbols: HashMap<LibCall, SymbolId>,
ctrl_plane: ControlPlane,
}
impl<'a> ModuleTextBuilder<'a> {
/// Creates a ... | (&mut self) {
self.text.force_veneers();
}
/// Appends the specified amount of bytes of padding into the text section.
///
/// This is only useful when fuzzing and/or debugging cranelift itself and
/// for production scenarios `padding` is 0 and this function does nothing.
pub fn append... | force_veneers | identifier_name |
obj.rs | calls that relocations are applied
/// against.
///
/// Note that this isn't typically used. It's only used for SSE-disabled
/// builds without SIMD on x86_64 right now.
libcall_symbols: HashMap<LibCall, SymbolId>,
ctrl_plane: ControlPlane,
}
impl<'a> ModuleTextBuilder<'a> {
/// Creates a ... |
for r in compiled_func.relocations() {
match r.reloc_target {
// Relocations against user-defined functions means that this is
// a relocation against a module-local function, typically a
// call between functions. The `text` field is given priority ... | {
self.unwind_info.push(off, body_len, info);
} | conditional_block |
util.rs | use libc;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::net::TcpStream as StdTcpStream;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use bytes::{BufMut, BytesMut};
use futures::future::Either;
use futures::sync::mpsc::Sender;
use futures::{Async, Future, IntoFuture, Poll, ... | <F: IntoFuture> {
action: F,
inner: Either<F::Future, Delay>,
options: BackoffRetryBuilder,
}
impl<F> Future for BackoffRetry<F>
where
F: IntoFuture + Clone,
{
type Item = F::Item;
type Error = Option<F::Error>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
... | BackoffRetry | identifier_name |
util.rs | use libc;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::net::TcpStream as StdTcpStream;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use bytes::{BufMut, BytesMut};
use futures::future::Either;
use futures::sync::mpsc::Sender;
use futures::{Async, Future, IntoFuture, Poll, ... | if self.interval > 0 {
let s_interval = self.interval as f64 / 1000f64;
info!(self.log, "stats";
"egress" => format!("{:2}", egress / s_interval),
"ingress" => format!("{:2}", ingress / s_interval),
"ingress-m" => format!("{:2}", ingress_m / s_interva... | add_metric!(INGRESS_METRICS, ingress_m, "ingress-metric");
add_metric!(AGG_ERRORS, agr_errors, "agg-error");
add_metric!(PARSE_ERRORS, parse_errors, "parse-error");
add_metric!(PEER_ERRORS, peer_errors, "peer-error");
add_metric!(DROPS, drops, "drop"); | random_line_split |
util.rs | use libc;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::net::TcpStream as StdTcpStream;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use bytes::{BufMut, BytesMut};
use futures::future::Either;
use futures::sync::mpsc::Sender;
use futures::{Async, Future, IntoFuture, Poll, ... |
}
#[cfg(test)]
pub(crate) fn new_test_graphite_name(s: &'static str) -> MetricName {
let mut intermediate = Vec::new();
intermediate.resize(9000, 0u8);
let mode = bioyino_metric::name::TagFormat::Graphite;
MetricName::new(s.into(), mode, &mut intermediate).unwrap()
}
// A future to send own stats. N... | {
let is_leader = IS_LEADER.load(Ordering::SeqCst);
if is_leader != acquired {
warn!(log, "leader state change: {} -> {}", is_leader, acquired);
}
IS_LEADER.store(acquired, Ordering::SeqCst);
} | conditional_block |
util.rs | use libc;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::net::TcpStream as StdTcpStream;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use bytes::{BufMut, BytesMut};
use futures::future::Either;
use futures::sync::mpsc::Sender;
use futures::{Async, Future, IntoFuture, Poll, ... |
}
impl BackoffRetryBuilder {
pub fn spawn<F>(self, action: F) -> BackoffRetry<F>
where
F: IntoFuture + Clone,
{
let inner = Either::A(action.clone().into_future());
BackoffRetry { action, inner, options: self }
}
}
/// TCP client that is able to reconnect with customizable set... | {
Self {
delay: 500,
delay_mul: 2f32,
delay_max: 10000,
retries: 25,
}
} | identifier_body |
listing.rs | use actix_web::http::StatusCode;
use actix_web::{fs, http, Body, FromRequest, HttpRequest, HttpResponse, Query, Result};
use bytesize::ByteSize;
use futures::stream::once;
use htmlescape::encode_minimal as escape_html_entity;
use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
use serde::Deserialize;
use s... | (&self) -> bool {
self.entry_type == EntryType::Directory
}
/// Returns whether the entry is a file
pub fn is_file(&self) -> bool {
self.entry_type == EntryType::File
}
/// Returns whether the entry is a symlink
pub fn is_symlink(&self) -> bool {
self.entry_type == Entr... | is_dir | identifier_name |
listing.rs | use actix_web::http::StatusCode;
use actix_web::{fs, http, Body, FromRequest, HttpRequest, HttpResponse, Query, Result};
use bytesize::ByteSize;
use futures::stream::once;
use htmlescape::encode_minimal as escape_html_entity;
use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
use serde::Deserialize;
use s... | /// Type of the entry
pub entry_type: EntryType,
/// URL of the entry
pub link: String,
/// Size in byte of the entry. Only available for EntryType::File
pub size: Option<bytesize::ByteSize>,
/// Last modification date
pub last_modification_date: Option<SystemTime>,
}
impl Entry {
... | /// Entry
pub struct Entry {
/// Name of the entry
pub name: String,
| random_line_split |
app.rs | //! Contains the main types a user needs to interact with to configure and run a skulpin app
use crate::skia_safe;
use crate::winit;
use super::app_control::AppControl;
use super::input_state::InputState;
use super::time_state::TimeState;
use super::util::PeriodicEvent;
use skulpin_renderer::LogicalSize;
use skulpin... | match *self {
AppError::RafxError(ref e) => e.fmt(fmt),
AppError::WinitError(ref e) => e.fmt(fmt),
}
}
}
impl From<RafxError> for AppError {
fn from(result: RafxError) -> Self {
AppError::RafxError(result)
}
}
impl From<winit::error::OsError> for AppError {
... | fn fmt(
&self,
fmt: &mut core::fmt::Formatter,
) -> core::fmt::Result { | random_line_split |
app.rs | //! Contains the main types a user needs to interact with to configure and run a skulpin app
use crate::skia_safe;
use crate::winit;
use super::app_control::AppControl;
use super::input_state::InputState;
use super::time_state::TimeState;
use super::util::PeriodicEvent;
use skulpin_renderer::LogicalSize;
use skulpin... |
}
if app_control.should_terminate_process() {
*control_flow = winit::event_loop::ControlFlow::Exit
}
});
}
}
| {} | conditional_block |
app.rs | //! Contains the main types a user needs to interact with to configure and run a skulpin app
use crate::skia_safe;
use crate::winit;
use super::app_control::AppControl;
use super::input_state::InputState;
use super::time_state::TimeState;
use super::util::PeriodicEvent;
use skulpin_renderer::LogicalSize;
use skulpin... | (result: winit::error::OsError) -> Self {
AppError::WinitError(result)
}
}
pub struct AppUpdateArgs<'a, 'b, 'c> {
pub app_control: &'a mut AppControl,
pub input_state: &'b InputState,
pub time_state: &'c TimeState,
}
pub struct AppDrawArgs<'a, 'b, 'c, 'd> {
pub app_control: &'a AppControl,... | from | identifier_name |
neexe.rs | use bitflags::bitflags;
use byteorder::{ByteOrder, LE};
use custom_error::custom_error;
use crate::util::read_pascal_string;
use enum_primitive::*;
use nom::{apply, count, do_parse, le_u8, le_u16, le_u32, named, named_args, tag, take};
macro_rules! try_parse (
($result: expr, $error: expr) => (match $result {
Ok((_... | {
pub linker_major_version: u8,
pub linker_minor_version: u8,
pub entry_table_offset: u16,
pub entry_table_size: u16,
pub crc: u32,
pub flags: NEFlags,
pub auto_data_segment_index: u16,
pub heap_size: u16,
pub stack_size: ... | NEHeader | identifier_name |
neexe.rs | use bitflags::bitflags;
use byteorder::{ByteOrder, LE};
use custom_error::custom_error;
use crate::util::read_pascal_string;
use enum_primitive::*;
use nom::{apply, count, do_parse, le_u8, le_u16, le_u32, named, named_args, tag, take};
macro_rules! try_parse (
($result: expr, $error: expr) => (match $result {
Ok((_... | min_code_swap_size: le_u16 >>
win_version_minor: le_u8 >>
win_version_major: le_u8 >>
(NEHeader {
linker_major_version,
linker_minor_version,
entry_table_offset,
entry_table_size,
crc,
flags: NEFlags::from_bits_truncate(flags),
auto_data_segment_index,
heap_size,
... | segment_thunk_offset: le_u16 >> | random_line_split |
neexe.rs | use bitflags::bitflags;
use byteorder::{ByteOrder, LE};
use custom_error::custom_error;
use crate::util::read_pascal_string;
use enum_primitive::*;
use nom::{apply, count, do_parse, le_u8, le_u16, le_u32, named, named_args, tag, take};
macro_rules! try_parse (
($result: expr, $error: expr) => (match $result {
Ok((_... | else {
NEResourcesIterator {
table: self.raw_header,
index: 0,
table_kind: NEResourceKind::Integer(0xffff),
offset_shift: 0,
block_index: 1,
block_len: 0,
finished: true
}
}
}
pub fn has_resource_table(&self) -> bool {
// In DIRAPI.DLL from Director for Windows, the resource ta... | {
NEResourcesIterator::new(&self.raw_header[self.header.resource_table_offset as usize..])
} | conditional_block |
hashed.rs | //! Implementation using ordered keys with hashes and robin hood hashing.
use std::default::Default;
use timely_sort::Unsigned;
use ::hashable::{Hashable, HashOrdered};
use super::{Trie, Cursor, Builder, MergeBuilder, TupleBuilder};
const MINIMUM_SHIFT : usize = 4;
const BLOAT_FACTOR : f64 = 1.1;
// I would like t... |
}
fn push_merge(&mut self, other1: (&Self::Trie, usize, usize), other2: (&Self::Trie, usize, usize)) -> usize {
// just rebinding names to clarify code.
let (trie1, mut lower1, upper1) = other1;
let (trie2, mut lower2, upper2) = other2;
debug_assert!(upper1 <= trie1.keys.len());
debug_assert!(upper2 <... | {
let other_basis = other.lower(lower); // from where in `other` the offsets do start.
let self_basis = self.vals.boundary(); // from where in `self` the offsets must start.
for index in lower .. upper {
let other_entry = &other.keys[index];
let new_entry = if other_entry.is_some() {
Entry::new(
... | conditional_block |
hashed.rs | //! Implementation using ordered keys with hashes and robin hood hashing.
use std::default::Default;
use timely_sort::Unsigned;
use ::hashable::{Hashable, HashOrdered};
use super::{Trie, Cursor, Builder, MergeBuilder, TupleBuilder};
const MINIMUM_SHIFT : usize = 4;
const BLOAT_FACTOR : f64 = 1.1;
// I would like t... |
#[inline]
fn push_tuple(&mut self, (key, val): (K, L::Item)) {
// we build up self.temp, and rely on self.boundary() to drain self.temp.
let temp_len = self.temp.len();
if temp_len == 0 || self.temp[temp_len-1].key!= key {
if temp_len > 0 { debug_assert!(self.temp[temp_len-1].key < key); }
let boundary ... | {
HashedBuilder {
temp: Vec::with_capacity(cap),
keys: Vec::with_capacity(cap),
vals: L::with_capacity(cap),
}
} | identifier_body |
hashed.rs | //! Implementation using ordered keys with hashes and robin hood hashing.
use std::default::Default;
use timely_sort::Unsigned;
use ::hashable::{Hashable, HashOrdered};
use super::{Trie, Cursor, Builder, MergeBuilder, TupleBuilder};
const MINIMUM_SHIFT : usize = 4;
const BLOAT_FACTOR : f64 = 1.1;
// I would like t... | (other1: &Self::Trie, other2: &Self::Trie) -> Self {
HashedBuilder {
temp: Vec::new(),
keys: Vec::with_capacity(other1.keys() + other2.keys()),
vals: L::with_capacity(&other1.vals, &other2.vals),
}
}
/// Copies fully formed ranges (note plural) of keys from another trie.
///
/// While the ranges are fu... | with_capacity | identifier_name |
hashed.rs | //! Implementation using ordered keys with hashes and robin hood hashing.
use std::default::Default;
use timely_sort::Unsigned;
use ::hashable::{Hashable, HashOrdered};
use super::{Trie, Cursor, Builder, MergeBuilder, TupleBuilder};
const MINIMUM_SHIFT : usize = 4;
const BLOAT_FACTOR : f64 = 1.1;
// I would like t... | else {
self.pos = self.bounds.1;
}
}
#[inline(never)]
fn seek(&mut self, storage: &HashedLayer<K, L>, key: &Self::Key) {
// leap to where the key *should* be, or at least be soon after.
// let key_hash = key.hashed();
// only update position if shift is large. otherwise leave it alone.
if self.shif... | } | random_line_split |
mapper.rs | use std::{
borrow::Cow,
cmp::{Ordering, Reverse},
collections::HashMap,
sync::Arc,
};
use bathbot_macros::{command, HasName, SlashCommand};
use bathbot_model::ScoreSlim;
use bathbot_psql::model::configs::{ListSize, MinimizedPp};
use bathbot_util::{
constants::{GENERAL_ISSUE, OSU_API_ISSUE},
mat... | let hits_b = b.score.total_hits();
let ratio_a = a.score.statistics.count_miss as f32 / hits_a as f32;
let ratio_b = b.score.statistics.count_miss as f32 / hits_b as f32;
ratio_b
.partial_cmp(&ratio_a)
... | .count_miss
.cmp(&a.score.statistics.count_miss)
.then_with(|| {
let hits_a = a.score.total_hits(); | random_line_split |
mapper.rs | use std::{
borrow::Cow,
cmp::{Ordering, Reverse},
collections::HashMap,
sync::Arc,
};
use bathbot_macros::{command, HasName, SlashCommand};
use bathbot_model::ScoreSlim;
use bathbot_psql::model::configs::{ListSize, MinimizedPp};
use bathbot_util::{
constants::{GENERAL_ISSUE, OSU_API_ISSUE},
mat... | (ctx: Arc<Context>, msg: &Message, args: Args<'_>) -> Result<()> {
match Mapper::args(Some(GameModeOption::Taiko), args, None) {
Ok(args) => mapper(ctx, msg.into(), args).await,
Err(content) => {
msg.error(&ctx, content).await?;
Ok(())
}
}
}
#[command]
#[desc("H... | prefix_mappertaiko | identifier_name |
mapper.rs | use std::{
borrow::Cow,
cmp::{Ordering, Reverse},
collections::HashMap,
sync::Arc,
};
use bathbot_macros::{command, HasName, SlashCommand};
use bathbot_model::ScoreSlim;
use bathbot_psql::model::configs::{ListSize, MinimizedPp};
use bathbot_util::{
constants::{GENERAL_ISSUE, OSU_API_ISSUE},
mat... | None => match config.osu.take() {
Some(user_id) => UserId::Id(user_id),
None => return require_link(&ctx, &orig).await,
},
};
let mapper = args.mapper.cow_to_ascii_lowercase();
let mapper_args = UserArgs::username(&ctx, mapper.as_ref()).await.mode(mode);
let mapp... | {
let msg_owner = orig.user_id()?;
let mut config = match ctx.user_config().with_osu_id(msg_owner).await {
Ok(config) => config,
Err(err) => {
let _ = orig.error(&ctx, GENERAL_ISSUE).await;
return Err(err);
}
};
let mode = args
.mode
.ma... | identifier_body |
dp.rs | // 我们开始学习动态规划吧
use std::cmp::min;
// https://leetcode-cn.com/problems/maximum-subarray
// 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = nums[0];
let mut ans = nums[0];
for i in 1..nums.len() {
if sum > 0 {
// add positive sum means larger
... | let col = grid[0].len();
for i in 0..row {
for j in 0..col {
if i == 0 && j == 0 {
// pass
} else if i == 0 {
grid[i][j] += grid[i][j-1];
} else if j == 0 {
grid[i][j] += grid[i-1][j];
} else {
... | dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
} else {
// 遇到障碍了,但一开始我们就是初始化为0的,所以这里其实可以不写
dp[i][j] = 0;
}
}
}
return dp[row-1][col-1];
}
// https://leetcode-cn.com/problems/re-space-lcci/
pub fn respace(dictionary: Vec<String>,... | identifier_body |
dp.rs | // 我们开始学习动态规划吧
use std::cmp::min;
// https://leetcode-cn.com/problems/maximum-subarray
// 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = nums[0];
let mut ans = nums[0];
for i in 1..nums.len() {
if sum > 0 {
// add positive sum means larger
... | st[r-1][c];
} else {
cost[r][c] = grid[r][c] + min(cost[r-1][c], cost[r][c-1]);
}
}
}
return cost[row-1][col-1];
}
// https://leetcode-cn.com/problems/generate-parentheses/solution/
pub fn generate_parenthesis(n: i32) -> Vec<String> {
if n == 0 {
ret... | d[r][c] + co | identifier_name |
dp.rs | // 我们开始学习动态规划吧
use std::cmp::min;
// https://leetcode-cn.com/problems/maximum-subarray
// 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = nums[0];
let mut ans = nums[0];
for i in 1..nums.len() {
if sum > 0 {
// add positive sum means larger
... | +1]) + triangle[i][j];
}
}
return dp[0];
}
// https://leetcode-cn.com/problems/nge-tou-zi-de-dian-shu-lcof/solution/
pub fn two_sum(n: i32) -> Vec<f64> {
let mut res = vec![1./6.;6];
for i in 1..n as usize {
let mut temp = vec![0.0; 5 * i + 6];
for j in 0..res.len() {
... | ("i, j = {}, {}", i, j);
dp[j] = dp[j].min(dp[j | conditional_block |
dp.rs | // 我们开始学习动态规划吧
use std::cmp::min;
// https://leetcode-cn.com/problems/maximum-subarray | let mut ans = nums[0];
for i in 1..nums.len() {
if sum > 0 {
// add positive sum means larger
sum += nums[i];
} else {
// start from new one means larger
sum = nums[i];
}
// ans always store the largest sum
ans = std::cmp::... | // 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = nums[0]; | random_line_split |
lib.rs | pub struct Keys<'a, K, V> {
inner: Iter<'a, K, V>,
}
impl<'a, K, V> Iterator for Keys<'a, K, V> {
type Item = &'a K;
#[inline]
fn next(&mut self) -> Option<&'a K> {
self.inner.next().map(|(k, _)| k)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_... | // use alloc::vec::Vec;
/// Iterator over the keys | random_line_split | |
lib.rs | k)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
//#[derive(Clone)]
/// Iterator over the values
pub struct Values<'a, K, V> {
inner: Iter<'a, K, V>,
}
impl<'a, K, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
#[inline]
fn next(... | (&self) -> Keys<'_, K, V> {
Keys { inner: self.iter() }
}
/// An iterator visiting all values in arbitrary order.
/// The iterator element type is `&'a V`.
pub fn values(&self) -> Values<'_, K, V> {
Values { inner: self.iter() }
}
/// Inserts a key-value pair into the map.
... | keys | identifier_name |
lib.rs | }
}
impl<K, V> PartialEq for Node<K, V>
where
K: PartialEq,
V: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash && self.key == other.key && self.value == other.value
}
}
impl<K, V> Node<K, V> {
#[inline]
const fn new(key: K, value: V, hash: u64) -> Self {
... | {
IterMut {
inner: [].iter_mut(),
}
} | identifier_body | |
lib.rs | k)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
//#[derive(Clone)]
/// Iterator over the values
pub struct Values<'a, K, V> {
inner: Iter<'a, K, V>,
}
impl<'a, K, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
#[inline]
fn next(... |
}
return false;
}
true
}
}
/// An iterator over the entries of a `Map`.
///
/// This struct is created by the [`iter`](./struct.Map.html#method.iter)
/// method on [`Map`](./struct.Map.html). See its documentation for more.
pub struct Iter<'a, K, V> {
inner: slice::It... | {
continue;
} | conditional_block |
lib.rs | //! A lock-free, eventually consistent, concurrent multi-value map.
//!
//! This map implementation allows reads and writes to execute entirely in parallel, with no
//! implicit synchronization overhead. Reads never take locks on their critical path, and neither
//! do writes assuming there is a single writer (multi-wr... | <K, V>(self) -> (WriteHandle<K, V, M, S>, ReadHandle<K, V, M, S>)
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
V: Eq + Hash,
M:'static + Clone,
{
let inner = if let Some(cap) = self.capacity {
Inner::with_capacity_and_hasher(self.meta, cap, self.hasher)... | assert_stable | identifier_name |
lib.rs | //! A lock-free, eventually consistent, concurrent multi-value map.
//!
//! This map implementation allows reads and writes to execute entirely in parallel, with no
//! implicit synchronization overhead. Reads never take locks on their critical path, and neither
//! do writes assuming there is a single writer (multi-wr... | else {
Inner::with_hasher(self.meta, self.hasher)
};
let (mut w, r) = left_right::new_from_empty(inner);
w.append(write::Operation::MarkReady);
(WriteHandle::new(w), ReadHandle::new(r))
}
}
/// Create an empty eventually consistent map.
///
/// Use the [`Options`](./s... | {
Inner::with_capacity_and_hasher(self.meta, cap, self.hasher)
} | conditional_block |
lib.rs | //! A lock-free, eventually consistent, concurrent multi-value map.
//!
//! This map implementation allows reads and writes to execute entirely in parallel, with no
//! implicit synchronization overhead. Reads never take locks on their critical path, and neither
//! do writes assuming there is a single writer (multi-wr... | /// of the same key.
#[allow(clippy::type_complexity)]
pub unsafe fn assert_stable<K, V>(self) -> (WriteHandle<K, V, M, S>, ReadHandle<K, V, M, S>)
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
V: Eq + Hash,
M:'static + Clone,
{
let inner = if let Some(c... | /// same inputs. For keys of type `K`, the result must also be consistent between different clones | random_line_split |
lib.rs | //! A lock-free, eventually consistent, concurrent multi-value map.
//!
//! This map implementation allows reads and writes to execute entirely in parallel, with no
//! implicit synchronization overhead. Reads never take locks on their critical path, and neither
//! do writes assuming there is a single writer (multi-wr... |
}
/// Create an empty eventually consistent map.
///
/// Use the [`Options`](./struct.Options.html) builder for more control over initialization.
///
/// If you want to use arbitrary types for the keys and values, use [`new_assert_stable`].
#[allow(clippy::type_complexity)]
pub fn new<K, V>() -> (
WriteHandle<K, ... | {
let inner = if let Some(cap) = self.capacity {
Inner::with_capacity_and_hasher(self.meta, cap, self.hasher)
} else {
Inner::with_hasher(self.meta, self.hasher)
};
let (mut w, r) = left_right::new_from_empty(inner);
w.append(write::Operation::MarkReady);... | identifier_body |
physical_plan.rs | with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or... |
pub fn memory_size(&self) -> usize {
self.columns.values().map(|c| c.memory_size()).sum()
}
}
macro_rules! build_literal_array {
($LEN:expr, $BUILDER:ident, $VALUE:expr) => {{
let mut builder = $BUILDER::new($LEN);
for _ in 0..$LEN {
builder.append_value($VALUE)?;
... | } | random_line_split |
physical_plan.rs | a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the... | compile_aggregate_expressions | identifier_name | |
time_zones.rs | use core::fmt;
use super::{NaiveDateTime, DateTime, UnixTimestamp, Month, DayOfTheWeek};
use num::{div_floor, positive_rem};
pub trait TimeZone {
fn from_timestamp(&self, t: UnixTimestamp) -> NaiveDateTime;
fn to_timestamp(&self, d: &NaiveDateTime) -> Result<UnixTimestamp, LocalTimeConversionError>;
}
/// Whe... | FixedOffsetFromUtc {
FixedOffsetFromUtc::from_hours_and_minutes(1, 0)
}
fn offset_during_dst(&self) -> FixedOffsetFromUtc {
FixedOffsetFromUtc::from_hours_and_minutes(2, 0)
}
fn is_in_dst(&self, t: UnixTimestamp) -> bool {
use Month::*;
let d = DateTime::from_timestamp... | ide_dst(&self) -> | identifier_name |
time_zones.rs | use core::fmt;
use super::{NaiveDateTime, DateTime, UnixTimestamp, Month, DayOfTheWeek};
use num::{div_floor, positive_rem}; | fn to_timestamp(&self, d: &NaiveDateTime) -> Result<UnixTimestamp, LocalTimeConversionError>;
}
/// When a time zone makes clock jump forward or back at any instant in time
/// (for example twice a year with daylight-saving time, a.k.a. summer-time period)
/// This error is returned when either:
///
/// * Clocks w... |
pub trait TimeZone {
fn from_timestamp(&self, t: UnixTimestamp) -> NaiveDateTime; | random_line_split |
selector.rs | use std::collections::hash_map;
use std::fmt;
use std::mem;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use sys;
use sys::fuchsia::{
assert_fuchsia_ready_repr, epoll_event_to_ready, poll_opts_to_wait_async, EventedFd,
... | .push(Event::new(epoll_event_to_ready(events), token));
Ok(false)
}
}
}
/// Register event interests for the given IO handle with the OS
pub fn register_fd(
&self,
handle: &zircon::Handle,
fd: &EventedFd,
token: Token,
... | random_line_split | |
selector.rs | use std::collections::hash_map;
use std::fmt;
use std::mem;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use sys;
use sys::fuchsia::{
assert_fuchsia_ready_repr, epoll_event_to_ready, poll_opts_to_wait_async, EventedFd,
... | (&self) -> &Arc<zircon::Port> {
&self.port
}
/// Reregisters all registrations pointed to by the `tokens_to_rereg` list
/// if `has_tokens_to_rereg`.
fn reregister_handles(&self) -> io::Result<()> {
// We use `Ordering::Acquire` to make sure that we see all `tokens_to_rereg`
// ... | port | identifier_name |
selector.rs | use std::collections::hash_map;
use std::fmt;
use std::mem;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use sys;
use sys::fuchsia::{
assert_fuchsia_ready_repr, epoll_event_to_ready, poll_opts_to_wait_async, EventedFd,
... |
None => zircon::ZX_TIME_INFINITE,
};
let packet = match self.port.wait(deadline) {
Ok(packet) => packet,
Err(zircon::Status::ErrTimedOut) => return Ok(false),
Err(e) => Err(e)?,
};
let observed_signals = match packet.contents() {
... | {
let nanos = duration
.as_secs()
.saturating_mul(1_000_000_000)
.saturating_add(duration.subsec_nanos() as u64);
zircon::deadline_after(nanos)
} | conditional_block |
selector.rs | use std::collections::hash_map;
use std::fmt;
use std::mem;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use sys;
use sys::fuchsia::{
assert_fuchsia_ready_repr, epoll_event_to_ready, poll_opts_to_wait_async, EventedFd,
... |
pub fn register_handle(
&self,
handle: zx_handle_t,
token: Token,
interests: Ready,
poll_opts: PollOpt,
) -> io::Result<()> {
if poll_opts.is_level() &&!poll_opts.is_oneshot() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
... | {
self.token_to_fd.lock().unwrap().remove(&token);
// We ignore NotFound errors since oneshots are automatically deregistered,
// but mio will attempt to deregister them manually.
self.port
.cancel(&*handle, token.0 as u64)
.map_err(io::Error::from)
.... | identifier_body |
window.rs | use std::{collections::HashMap, sync::Arc};
use log::warn;
use unicode_segmentation::UnicodeSegmentation;
use crate::{
bridge::GridLineCell,
editor::{grid::CharacterGrid, style::Style, AnchorInfo, DrawCommand, DrawCommandBatcher},
renderer::{LineFragment, WindowDrawCommand},
};
pub enum WindowType {
... |
pub fn redraw(&self) {
self.send_command(WindowDrawCommand::Clear);
// Draw the lines from the bottom up so that underlines don't get overwritten by the line
// below.
for row in (0..self.grid.height).rev() {
self.redraw_line(row);
}
}
pub fn hide(&self... | {
self.grid.clear();
self.send_command(WindowDrawCommand::Clear);
} | identifier_body |
window.rs | use std::{collections::HashMap, sync::Arc};
use log::warn;
use unicode_segmentation::UnicodeSegmentation;
use crate::{
bridge::GridLineCell,
editor::{grid::CharacterGrid, style::Style, AnchorInfo, DrawCommand, DrawCommandBatcher},
renderer::{LineFragment, WindowDrawCommand},
};
pub enum WindowType {
... | (&self, command: WindowDrawCommand) {
self.draw_command_batcher
.queue(DrawCommand::Window {
grid_id: self.grid_id,
command,
})
.ok();
}
fn send_updated_position(&self) {
self.send_command(WindowDrawCommand::Position {
... | send_command | identifier_name |
window.rs | use std::{collections::HashMap, sync::Arc};
use log::warn;
use unicode_segmentation::UnicodeSegmentation;
use crate::{
bridge::GridLineCell,
editor::{grid::CharacterGrid, style::Style, AnchorInfo, DrawCommand, DrawCommandBatcher},
renderer::{LineFragment, WindowDrawCommand},
};
pub enum WindowType {
... |
self.redraw_line(row);
if row > 0 {
self.redraw_line(row - 1);
}
} else {
warn!("Draw command out of bounds");
}
}
pub fn scroll_region(
&mut self,
top: u64,
bottom: u64,
left: u64,
right: u... | {
self.redraw_line(row + 1);
} | conditional_block |
window.rs | use std::{collections::HashMap, sync::Arc};
use log::warn;
use unicode_segmentation::UnicodeSegmentation;
use crate::{
bridge::GridLineCell,
editor::{grid::CharacterGrid, style::Style, AnchorInfo, DrawCommand, DrawCommandBatcher},
renderer::{LineFragment, WindowDrawCommand},
};
pub enum WindowType {
... | }
let line_fragment = LineFragment {
text,
window_left: start,
window_top: row_index,
width,
style: style.clone(),
};
(start + width, line_fragment)
}
// Redraw line by calling build_line_fragment starting at 0
//... | }
// Add the grid cell to the cells to render.
text.push_str(character); | random_line_split |
font_atlas.rs | #[macro_use]
extern crate glium;
use euclid::Rect;
use font_kit::font::Font;
use glium::backend::Facade;
use glium::texture::Texture2d;
use glium::{glutin, Surface};
use lyon_path::math::{Angle, Point, Vector};
use lyon_path::Segment;
use msdfgen::{compute_msdf, recolor_contours, Contour, PathCollector};
use std::coll... |
})
}
}
| {} | conditional_block |
font_atlas.rs | #[macro_use]
extern crate glium;
use euclid::Rect;
use font_kit::font::Font;
use glium::backend::Facade;
use glium::texture::Texture2d;
use glium::{glutin, Surface};
use lyon_path::math::{Angle, Point, Vector};
use lyon_path::Segment;
use msdfgen::{compute_msdf, recolor_contours, Contour, PathCollector};
use std::coll... | }
(contours, transformation)
}
#[derive(Copy, Clone)]
struct Vertex2D {
position: [f32; 2],
uv: [f32; 2],
color: [f32; 3],
}
glium::implement_vertex!(Vertex2D, position, uv, color);
/// All the information required to render a character from a string
#[derive(Clone, Copy, Debug)]
struct RenderCha... | }
} | random_line_split |
font_atlas.rs | #[macro_use]
extern crate glium;
use euclid::Rect;
use font_kit::font::Font;
use glium::backend::Facade;
use glium::texture::Texture2d;
use glium::{glutin, Surface};
use lyon_path::math::{Angle, Point, Vector};
use lyon_path::Segment;
use msdfgen::{compute_msdf, recolor_contours, Contour, PathCollector};
use std::coll... |
/// Get a glyph ID for a character, its contours, and the typographic bounds for that glyph
/// TODO: this should also return font.origin() so we can offset the EM-space
/// computations by it. However, on freetype that always returns 0 so for the
/// moment we'll get away without it
fn get_glyph(font: &Font, chr: ch... | {
use font_kit::family_name::FamilyName;
use font_kit::properties::{Properties, Style};
use font_kit::source::SystemSource;
let source = SystemSource::new();
source
.select_best_match(
&[FamilyName::Serif],
Properties::new().style(Style::Normal),
)
.e... | identifier_body |
font_atlas.rs | #[macro_use]
extern crate glium;
use euclid::Rect;
use font_kit::font::Font;
use glium::backend::Facade;
use glium::texture::Texture2d;
use glium::{glutin, Surface};
use lyon_path::math::{Angle, Point, Vector};
use lyon_path::Segment;
use msdfgen::{compute_msdf, recolor_contours, Contour, PathCollector};
use std::coll... | {
position: [f32; 2],
uv: [f32; 2],
color: [f32; 3],
}
glium::implement_vertex!(Vertex2D, position, uv, color);
/// All the information required to render a character from a string
#[derive(Clone, Copy, Debug)]
struct RenderChar {
/// The position of the vertices
verts: Rect<f32>,
/// The UV ... | Vertex2D | identifier_name |
conpty.rs | ::{ReadFile, WriteFile};
use crate::pty::conpty::winapi::um::handleapi::*;
use crate::pty::conpty::winapi::um::minwinbase::STILL_ACTIVE;
use crate::pty::conpty::winapi::um::namedpipeapi::CreatePipe;
use crate::pty::conpty::winapi::um::processthreadsapi::*;
use crate::pty::conpty::winapi::um::winbase::EXTENDED_STARTUPIN... |
fn cmdline(&self) -> Result<(Vec<u16>, Vec<u16>), Error> {
let mut cmdline = Vec::<u16>::new();
let exe = Self::search_path(&self.args[0]);
Self::append_quoted(&exe, &mut cmdline);
// Ensure that we nul terminate the module name, otherwise we'll
// ask CreateProcessW to s... | {
self.input.replace(input);
self.output.replace(output);
self.hpc.replace(con);
self
} | identifier_body |
conpty.rs | ::{ReadFile, WriteFile};
use crate::pty::conpty::winapi::um::handleapi::*;
use crate::pty::conpty::winapi::um::minwinbase::STILL_ACTIVE;
use crate::pty::conpty::winapi::um::namedpipeapi::CreatePipe;
use crate::pty::conpty::winapi::um::processthreadsapi::*;
use crate::pty::conpty::winapi::um::winbase::EXTENDED_STARTUPIN... | (exe: &OsStr) -> OsString {
if let Some(path) = env::var_os("PATH") {
let extensions = env::var_os("PATHEXT").unwrap_or(".EXE".into());
for path in env::split_paths(&path) {
// Check for exactly the user's string in this path dir
let candidate = path.join(... | search_path | identifier_name |
conpty.rs | ::{ReadFile, WriteFile};
use crate::pty::conpty::winapi::um::handleapi::*;
use crate::pty::conpty::winapi::um::minwinbase::STILL_ACTIVE;
use crate::pty::conpty::winapi::um::namedpipeapi::CreatePipe;
use crate::pty::conpty::winapi::um::processthreadsapi::*;
use crate::pty::conpty::winapi::um::winbase::EXTENDED_STARTUPIN... |
}
}
impl OwnedHandle {
fn try_clone(&self) -> Result<Self, IoError> {
if self.handle == INVALID_HANDLE_VALUE || self.handle.is_null() {
return Ok(OwnedHandle {
handle: self.handle,
});
}
let proc = unsafe { GetCurrentProcess() };
let mut... | {
unsafe { CloseHandle(self.handle) };
} | conditional_block |
conpty.rs | eapi::{ReadFile, WriteFile};
use crate::pty::conpty::winapi::um::handleapi::*;
use crate::pty::conpty::winapi::um::minwinbase::STILL_ACTIVE;
use crate::pty::conpty::winapi::um::namedpipeapi::CreatePipe;
use crate::pty::conpty::winapi::um::processthreadsapi::*;
use crate::pty::conpty::winapi::um::winbase::EXTENDED_START... | &mut bytes_required,
)
};
let mut data = Vec::with_capacity(bytes_required);
// We have the right capacity, so force the vec to consider itself
// that length. The contents of those bytes will be maintained
// by the win32 apis used in this impl.
... | unsafe {
InitializeProcThreadAttributeList(
ptr::null_mut(),
num_attributes,
0, | random_line_split |
helpers.rs | //! A module with ide helpers for high-level ide features.
pub mod import_assets;
pub mod insert_use;
pub mod merge_imports;
pub mod rust_doc;
pub mod generated_lints;
use std::collections::VecDeque;
use base_db::FileId;
use either::Either;
use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef,... | (path: &hir::ModPath) -> ast::Path {
let _p = profile::span("mod_path_to_ast");
let mut segments = Vec::new();
let mut is_abs = false;
match path.kind {
hir::PathKind::Plain => {}
hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
hir::PathKind::Super(n) => seg... | mod_path_to_ast | identifier_name |
helpers.rs | //! A module with ide helpers for high-level ide features.
pub mod import_assets;
pub mod insert_use;
pub mod merge_imports;
pub mod rust_doc;
pub mod generated_lints;
use std::collections::VecDeque;
use base_db::FileId;
use either::Either;
use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef,... | let mut path = path.split(':');
let trait_ = path.next_back()?;
let std_crate = path.next()?;
let std_crate = self.find_crate(std_crate)?;
let mut module = std_crate.root_module(db);
for segment in path {
module = module.children(db).find_map(|child| {
... | Some(res)
}
fn find_def(&self, path: &str) -> Option<ScopeDef> {
let db = self.0.db; | random_line_split |
helpers.rs | //! A module with ide helpers for high-level ide features.
pub mod import_assets;
pub mod insert_use;
pub mod merge_imports;
pub mod rust_doc;
pub mod generated_lints;
use std::collections::VecDeque;
use base_db::FileId;
use either::Either;
use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef,... |
pub fn core_convert_Into(&self) -> Option<Trait> {
self.find_trait("core:convert:Into")
}
pub fn core_option_Option(&self) -> Option<Enum> {
self.find_enum("core:option:Option")
}
pub fn core_result_Result(&self) -> Option<Enum> {
self.find_enum("core:result:Result")
... | {
self.find_trait("core:convert:From")
} | identifier_body |
pool.rs | Send + 'a);
struct Work {
func: WorkInner<'static>
}
struct JobStatus {
wait: bool,
job_finished: mpsc::Receiver<Result<(), ()>>,
}
/// A token representing a job submitted to the thread pool.
///
/// This helps ensure that a job is finished before borrowed resources
/// in the job (and the pool itself) ... | Ok(false) => {
// ignore return, because we
// need to wait until the
// workers have exited (i.e,
// the Err arm above... | // closed, done!
Ok(true) | Err(_) => break, | random_line_split |
pool.rs | + 'a);
struct | {
func: WorkInner<'static>
}
struct JobStatus {
wait: bool,
job_finished: mpsc::Receiver<Result<(), ()>>,
}
/// A token representing a job submitted to the thread pool.
///
/// This helps ensure that a job is finished before borrowed resources
/// in the job (and the pool itself) are invalidated.
///
///... | Work | identifier_name |
pool.rs | + 'a);
struct Work {
func: WorkInner<'static>
}
struct JobStatus {
wait: bool,
job_finished: mpsc::Receiver<Result<(), ()>>,
}
/// A token representing a job submitted to the thread pool.
///
/// This helps ensure that a job is finished before borrowed resources
/// in the job (and the pool itself) are i... |
}
}
}
},
move |(needwork_tx, shared)| {
let mut iter = iter.into_iter().fuse().enumerate();
drop(needwork_tx);
... | {
break
} | conditional_block |
needless_pass_by_ref_mut.rs | use super::needless_pass_by_value::requires_exact_signature;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::source::snippet;
use clippy_utils::{get_parent_node, is_from_proc_macro, is_self};
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::Applicability;
use rustc_hir:... |
fn copy(&mut self, _cmt: &euv::PlaceWithHirId<'tcx>, _id: HirId) {
self.prev_bind = None;
}
fn fake_read(
&mut self,
cmt: &rustc_hir_typeck::expr_use_visitor::PlaceWithHirId<'tcx>,
cause: FakeReadCause,
_id: HirId,
) {
if let euv::Place {
ba... | {
self.prev_bind = None;
if let euv::Place {
projections,
base: euv::PlaceBase::Local(vid),
..
} = &cmt.place
{
if !projections.is_empty() {
self.add_mutably_used_var(*vid);
}
}
} | identifier_body |
needless_pass_by_ref_mut.rs | use super::needless_pass_by_value::requires_exact_signature;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::source::snippet;
use clippy_utils::{get_parent_node, is_from_proc_macro, is_self};
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::Applicability;
use rustc_hir:... | (
&mut self,
cmt: &rustc_hir_typeck::expr_use_visitor::PlaceWithHirId<'tcx>,
cause: FakeReadCause,
_id: HirId,
) {
if let euv::Place {
base:
euv::PlaceBase::Upvar(UpvarId {
var_path: UpvarPath { hir_id: vid },
... | fake_read | identifier_name |
needless_pass_by_ref_mut.rs | use super::needless_pass_by_value::requires_exact_signature;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::source::snippet;
use clippy_utils::{get_parent_node, is_from_proc_macro, is_self};
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::Applicability;
use rustc_hir:... |
}
}
}
}
#[derive(Default)]
struct MutablyUsedVariablesCtxt {
mutably_used_vars: HirIdSet,
prev_bind: Option<HirId>,
prev_move_to_closure: HirIdSet,
aliases: HirIdMap<HirId>,
async_closures: FxHashSet<LocalDefId>,
}
impl MutablyUsedVariablesCtxt {
fn add_mutably_used_va... | {
span_lint_hir_and_then(
cx,
NEEDLESS_PASS_BY_REF_MUT,
cx.tcx.hir().local_def_id_to_hir_id(*fn_def_id),
sp,
"this argument is a mutable reference, but not used mutably",
... | conditional_block |
needless_pass_by_ref_mut.rs | use super::needless_pass_by_value::requires_exact_signature;
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::source::snippet;
use clippy_utils::{get_parent_node, is_from_proc_macro, is_self};
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::Applicability;
use rustc_hir:... | &mut self,
cx: &LateContext<'tcx>,
kind: FnKind<'tcx>,
decl: &'tcx FnDecl<'tcx>,
body: &'tcx Body<'_>,
span: Span,
fn_def_id: LocalDefId,
) {
if span.from_expansion() {
return;
}
let hir_id = cx.tcx.hir().local_def_id_to_hi... |
impl<'tcx> LateLintPass<'tcx> for NeedlessPassByRefMut<'tcx> {
fn check_fn( | random_line_split |
messenger.rs | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... | (&self, _peer_node_id: &PublicKey, msg: &msgs::OnionMessage) {
let control_tlvs_ss = match self.keys_manager.ecdh(Recipient::Node, &msg.blinding_point, None) {
Ok(ss) => ss,
Err(e) => {
log_error!(self.logger, "Failed to retrieve node secret: {:?}", e);
return
}
};
let onion_decode_ss = {
let... | handle_onion_message | identifier_name |
messenger.rs | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... | public_key: new_pubkey,
hop_data: new_packet_bytes,
hmac: next_hop_hmac,
};
let onion_message = msgs::OnionMessage {
blinding_point: match next_blinding_override {
Some(blinding_point) => blinding_point,
None => {
let blinding_factor = {
let mut sha = Sha256::engin... | version: 0, | random_line_split |
messenger.rs | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... |
}
/// Errors that may occur when [sending an onion message].
///
/// [sending an onion message]: OnionMessenger::send_onion_message
#[derive(Debug, PartialEq)]
pub enum SendError {
/// Errored computing onion message packet keys.
Secp256k1(secp256k1::Error),
/// Because implementations such as Eclair will drop oni... | {
match self {
Destination::Node(_) => 1,
Destination::BlindedRoute(BlindedRoute { blinded_hops, .. }) => blinded_hops.len(),
}
} | identifier_body |
joint_feldman.rs | //! Implements the Distributed Key Generation protocol from
//! [Pedersen](https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_21.pdf).
//! The protocol runs at minimum in two phases and at most in three phases.
use super::common::*;
use crate::primitives::{
group::Group,
phases::{Phase0, Phase1, Phas... | qual: group,
public: add_public,
share: ds,
})
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::primitives::{
common::tests::{check2, full_dkg, id_out, id_resp, invalid2, invalid_shares, setup_group},
default_threshold,
};
use std... | random_line_split | |
joint_feldman.rs | //! Implements the Distributed Key Generation protocol from
//! [Pedersen](https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_21.pdf).
//! The protocol runs at minimum in two phases and at most in three phases.
use super::common::*;
use crate::primitives::{
group::Group,
phases::{Phase0, Phase1, Phas... |
// check if the public key is part of the group
let index = group
.index(&public_key)
.ok_or(DKGError::PublicKeyNotFound)?;
// Generate a secret polynomial and commit to it
let secret = PrivatePoly::<C>::new_from(group.threshold - 1, rng);
let public = se... | {
return Err(DKGError::PrivateKeyInvalid);
} | conditional_block |
joint_feldman.rs | //! Implements the Distributed Key Generation protocol from
//! [Pedersen](https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_21.pdf).
//! The protocol runs at minimum in two phases and at most in three phases.
use super::common::*;
use crate::primitives::{
group::Group,
phases::{Phase0, Phase1, Phas... |
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound = "C::Scalar: DeserializeOwned")]
/// DKG Stage which waits to receive the shares from the previous phase's participants
/// as input. After processing the shares, if there were any complaints it will generate
/// a bundle of responses for the next phase... | {
let bundle = create_share_bundle(
self.info.index,
&self.info.secret,
&self.info.public,
&self.info.group,
rng,
)?;
let dw = DKGWaitingShare { info: self.info };
Ok((dw, Some(bundle)))
} | identifier_body |
joint_feldman.rs | //! Implements the Distributed Key Generation protocol from
//! [Pedersen](https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_21.pdf).
//! The protocol runs at minimum in two phases and at most in three phases.
use super::common::*;
use crate::primitives::{
group::Group,
phases::{Phase0, Phase1, Phas... | <R: RngCore>(
private_key: C::Scalar,
group: Group<C>,
rng: &mut R,
) -> Result<DKG<C>, DKGError> {
// get the public key
let mut public_key = C::Point::one();
public_key.mul(&private_key);
// make sure the private key is not identity element nor neutral elem... | new_rand | identifier_name |
paging.rs | >, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
#![allow(dead_code)]
use crate::arch::x86_64::kernel::irq;
use crate::arch::x86_64::kernel::processor;
use crate::arch::x86_64::kernel::BOOT_INFO;
use crate::arch::x86_64::mm::{physicalmem, virtualmem};
use cr... | else {
None
}
}
fn drop_user_space(&mut self) {
let last = 1 << PAGE_MAP_BITS;
let table_address = self as *const PageTable<L> as usize;
for index in 0..last {
if self.entries[index].is_present() && self.entries[index].is_user() {
// currently, the user space uses only 4KB pages
if L::LEVEL >... | {
if L::LEVEL > S::MAP_LEVEL {
let subtable = self.subtable::<S>(page);
subtable.get_page_table_entry::<S>(page)
} else {
Some(self.entries[index])
}
} | conditional_block |
paging.rs | >, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
#![allow(dead_code)]
use crate::arch::x86_64::kernel::irq;
use crate::arch::x86_64::kernel::processor;
use crate::arch::x86_64::kernel::BOOT_INFO;
use crate::arch::x86_64::mm::{physicalmem, virtualmem};
use cr... | {}
impl PageSize for BasePageSize {
const SIZE: usize = 0x1000;
const MAP_LEVEL: usize = 0;
const MAP_EXTRA_FLAG: PageTableEntryFlags = PageTableEntryFlags::BLANK;
}
/// A 2 MiB page mapped in the PD.
#[derive(Clone, Copy)]
pub enum LargePageSize {}
impl PageSize for LargePageSize {
const SIZE: usize = 0x200000;
... | BasePageSize | identifier_name |
paging.rs | >, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
#![allow(dead_code)]
use crate::arch::x86_64::kernel::irq;
use crate::arch::x86_64::kernel::processor;
use crate::arch::x86_64::kernel::BOOT_INFO;
use crate::arch::x86_64::mm::{physicalmem, virtualmem};
use cr... |
pub fn get_physical_address<S: PageSize>(virtual_address: usize) -> usize {
debug!("Getting physical address for {:#X}", virtual_address);
let page = Page::<S>::including_address(virtual_address);
let root_pagetable = unsafe { &mut *PML4_ADDRESS };
let address = root_pagetable
.get_page_table_entry(page)
.ex... | {
debug!("Looking up Page Table Entry for {:#X}", virtual_address);
let page = Page::<S>::including_address(virtual_address);
let root_pagetable = unsafe { &mut *PML4_ADDRESS };
root_pagetable.get_page_table_entry(page)
} | identifier_body |
paging.rs | MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
#![allow(dead_code)]
use crate::arch::x86_64::kernel::irq;
use crate::arch::x86_64::kernel::processor;
use crate::arch::x86_64::kernel::BOOT_INFO;
use crate::arch::x86_64::mm::{physicalmem, virtualmem};
use... |
/// A Page Directory (PD), with numeric level 1 and PT subtables.
enum PD {}
impl PageTableLevel for PD {
const LEVEL: usize = 1;
}
impl PageTableLevelWithSubtables for PD {
type SubtableLevel = PT;
}
/// A Page Table (PT), with numeric level 0 and no subtables.
enum PT {}
impl PageTableLevel for PT {
const LEVEL... | } | random_line_split |
inherents.rs | use nimiq_account::StakingContract;
use nimiq_block::{ForkProof, MacroBlock, MacroHeader, SkipBlockInfo};
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_database as db;
use nimiq_keys::Address;
use nimiq_primitives::{
account::AccountType,
coin::Coin,
policy::Policy,
slots_allocation::{Ja... | (&self) -> Inherent {
// Create the FinalizeEpoch inherent.
Inherent::FinalizeEpoch
}
}
| finalize_previous_epoch | identifier_name |
inherents.rs | use nimiq_account::StakingContract;
use nimiq_block::{ForkProof, MacroBlock, MacroHeader, SkipBlockInfo};
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_database as db;
use nimiq_keys::Address;
use nimiq_primitives::{
account::AccountType,
coin::Coin,
policy::Policy,
slots_allocation::{Ja... | None
};
// Create the JailedValidator struct.
let jailed_validator = JailedValidator {
slots: proposer_slot.validator.slots,
validator_address: proposer_slot.validator.address,
offense_event_block: fork_proof.header1.block_number,
};
... | } else { | random_line_split |
inherents.rs | use nimiq_account::StakingContract;
use nimiq_block::{ForkProof, MacroBlock, MacroHeader, SkipBlockInfo};
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_database as db;
use nimiq_keys::Address;
use nimiq_primitives::{
account::AccountType,
coin::Coin,
policy::Policy,
slots_allocation::{Ja... | };
// Calculate the slots that will receive rewards.
// Rewards are for the previous batch (to give validators time to report misbehavior)
let penalized_set = staking_contract
.punished_slots
.previous_batch_punished_slots();
// Total reward for the previo... | {
let prev_macro_info = &state.macro_info;
// Special case for first batch: Batch 0 is finalized by definition.
if Policy::batch_at(macro_header.block_number) - 1 == 0 {
return vec![];
}
// Get validator slots
// NOTE: Fields `current_slots` and `previous_sl... | identifier_body |
inherents.rs | use nimiq_account::StakingContract;
use nimiq_block::{ForkProof, MacroBlock, MacroHeader, SkipBlockInfo};
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_database as db;
use nimiq_keys::Address;
use nimiq_primitives::{
account::AccountType,
coin::Coin,
policy::Policy,
slots_allocation::{Ja... | else {
break;
}
}
// Compute reward from slot reward and number of eligible slots. Also update the burned
// reward from the number of penalized slots.
let reward = slot_reward
.checked_mul(num_eligible_slots as u64)
... | {
assert!(num_eligible_slots > 0);
penalized_set_iter.next();
num_eligible_slots -= 1;
num_penalized_slots += 1;
} | conditional_block |
testclient.rs | extern crate byteorder;
extern crate clap;
extern crate data_encoding;
extern crate env_logger;
#[macro_use] extern crate log;
extern crate qrcodegen;
extern crate saltyrtc_client;
extern crate saltyrtc_task_relayed_data;
extern crate tokio_core;
use std::env;
use std::io::Write;
use std::process;
use std::sync::{Arc,... | let pubkey = HEXLOWER.decode(b"4242424242424242424242424242424242424242424242424242424242424242").unwrap();
let auth_token = HEXLOWER.decode(b"2323232323232323232323232323232323232323232323232323232323232323").unwrap();
let server_pubkey = HEXLOWER.decode(b"133713371337133713371337133713371337133... | ake_qrcode_data() {
| identifier_name |
testclient.rs | extern crate byteorder;
extern crate clap;
extern crate data_encoding;
extern crate env_logger;
#[macro_use] extern crate log;
extern crate qrcodegen;
extern crate saltyrtc_client;
extern crate saltyrtc_task_relayed_data;
extern crate tokio_core;
use std::env;
use std::io::Write;
use std::process;
use std::sync::{Arc,... | .required(true)
.default_value("f77fe623b6977d470ac8c7bf7011c4ad08a1d126896795db9d2b4b7a49ae1045")
.help("The SaltyRTC server public permanent key");
let arg_ping_interval = Arg::with_name(ARG_PING_INTERVAL)
.short('i')
.takes_value(true)
.value_name("SECONDS")
.requ... |
// Set up CLI arguments
let arg_srv_host = Arg::with_name(ARG_SRV_HOST)
.short('h')
.takes_value(true)
.value_name("SRV_HOST")
.required(true)
.default_value("server.saltyrtc.org")
.help("The SaltyRTC server hostname");
let arg_srv_port = Arg::with_name(ARG_S... | identifier_body |
testclient.rs | extern crate byteorder;
extern crate clap;
extern crate data_encoding;
extern crate env_logger;
#[macro_use] extern crate log;
extern crate qrcodegen;
extern crate saltyrtc_client;
extern crate saltyrtc_task_relayed_data;
extern crate tokio_core;
use std::env;
use std::io::Write;
use std::process;
use std::sync::{Arc,... | client.read().unwrap().auth_token().unwrap().secret_key_bytes(),
&server_pubkey,
);
// Print connection info
println!("\n#====================#");
println!("Host: {}:{}", server_host, server_port);
match role {
Role::Initiator => {
println!("Pubkey: {}", HEXLOWER... | server_host,
server_port,
pubkey.as_bytes(), | random_line_split |
main.rs | mod cmd;
mod config;
mod edit;
mod error;
mod fmt;
mod opts;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
use std::process::{self, Command, Stdio};
use atty::Stream::{Stderr, Stdout};
use prettyprint::{PagingMode, PrettyPrinter};
use quote::qu... |
// Based on https://github.com/rsolomo/cargo-check
fn apply_args(cmd: &mut Command, args: &Args, outfile: &Path) {
let mut line = Line::new("cargo");
line.arg("rustc");
if args.tests && args.test.is_none() {
line.arg("--profile=test");
} else {
line.arg("--profile=check");
}
... |
match env::var_os("RUSTFMT") {
Some(which) => {
if which.is_empty() {
None
} else {
Some(PathBuf::from(which))
}
}
None => toolchain_find::find_installed_component("rustfmt"),
}
}
| identifier_body |
main.rs | mod cmd;
mod config;
mod edit;
mod error;
mod fmt;
mod opts;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
use std::process::{self, Command, Stdio};
use atty::Stream::{Stderr, Stdout};
use prettyprint::{PagingMode, PrettyPrinter};
use quote::qu... | () -> Result<i32> {
const NO_RUN_NIGHTLY: &str = "CARGO_EXPAND_NO_RUN_NIGHTLY";
let maybe_nightly =!definitely_not_nightly();
if maybe_nightly || env::var_os(NO_RUN_NIGHTLY).is_some() {
return cargo_expand();
}
let mut nightly = Command::new("cargo");
nightly.arg("+nightly");
night... | cargo_expand_or_run_nightly | identifier_name |
main.rs | mod cmd;
mod config;
mod edit;
mod error;
mod fmt;
mod opts;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
use std::process::{self, Command, Stdio};
use atty::Stream::{Stderr, Stdout};
use prettyprint::{PagingMode, PrettyPrinter};
use quote::qu... | })
}
fn definitely_not_nightly() -> bool {
let mut cmd = Command::new(cargo_binary());
cmd.arg("--version");
let output = match cmd.output() {
Ok(output) => output,
Err(_) => return false,
};
let version = match String::from_utf8(output.stdout) {
Ok(version) => version... | }
} | random_line_split |
main.rs | mod cmd;
mod config;
mod edit;
mod error;
mod fmt;
mod opts;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
use std::process::{self, Command, Stdio};
use atty::Stream::{Stderr, Stdout};
use prettyprint::{PagingMode, PrettyPrinter};
use quote::qu... |
if args.frozen {
line.arg("--frozen");
}
if args.locked {
line.arg("--locked");
}
for unstable_flag in &args.unstable_flags {
line.arg("-Z");
line.arg(unstable_flag);
}
line.arg("--");
line.arg("-o");
line.arg(outfile);
line.arg("-Zunstable-op... |
line.arg(if atty::is(Stderr) { "always" } else { "never" });
}
| conditional_block |
miner.rs | use crate::network::message::{Message};
use crate::network::server::Handle as ServerHandle;
use std::sync::{Arc, Mutex};
use crate::crypto::hash::{H256, Hashable, H160};
use crate::blockchain::Blockchain;
use crate::block::{Block,Header,Content};
use crate::crypto::merkle::{MerkleTree};
use crate::transaction::{Transa... | thread::sleep(interval);
}
}
} | thread::sleep(interval);
}
}
let interval = time::Duration::from_micros(1000 as u64); | random_line_split |
miner.rs | use crate::network::message::{Message};
use crate::network::server::Handle as ServerHandle;
use std::sync::{Arc, Mutex};
use crate::crypto::hash::{H256, Hashable, H160};
use crate::blockchain::Blockchain;
use crate::block::{Block,Header,Content};
use crate::crypto::merkle::{MerkleTree};
use crate::transaction::{Transa... | (&self) {
self.control_chan.send(ControlSignal::Exit).unwrap();
}
pub fn start(&self, lambda: u64) {
self.control_chan
.send(ControlSignal::Start(lambda))
.unwrap();
}
}
impl Context {
pub fn start(mut self) {
thread::Builder::new()
.name("mine... | exit | identifier_name |
miner.rs | use crate::network::message::{Message};
use crate::network::server::Handle as ServerHandle;
use std::sync::{Arc, Mutex};
use crate::crypto::hash::{H256, Hashable, H160};
use crate::blockchain::Blockchain;
use crate::block::{Block,Header,Content};
use crate::crypto::merkle::{MerkleTree};
use crate::transaction::{Transa... | if check {
let mut blockchain = self.blockchain.lock().unwrap();
let tip_hash = blockchain.insert(&newBlock);
//info!("MINER: NEW BLOCK ADDED");
miner_counter += 1;
... | {
let mut contents = newBlock.Content.content.clone();
//let mut state = self.state.lock().unwrap();
let mut stateWitness = self.stateWitness.lock().unwrap();
let mut mempool = self.mempool.lock().unwrap();
... | conditional_block |
graphics.rs | use crate::mthelper::SharedRef;
use bedrock as br;
use br::{
CommandBuffer, CommandPool, Device, Instance, InstanceChild, PhysicalDevice, Queue,
SubmissionBatch,
};
use log::{debug, info, warn};
use std::ops::Deref;
pub type InstanceObject = SharedRef<br::InstanceObject>;
pub type DeviceObject = Shar... | #[cfg(feature = "debug")]
{
ib.add_extension("VK_EXT_debug_utils");
debug!("Debug reporting activated");
}
let instance = SharedRef::new(ib.create()?);
#[cfg(feature = "debug")]
let _debug_instance = br::DebugUtilsMessengerCreateInfo::new(... | warn!("Validation Layer is not found!");
}
| random_line_split |
graphics.rs | use crate::mthelper::SharedRef;
use bedrock as br;
use br::{
CommandBuffer, CommandPool, Device, Instance, InstanceChild, PhysicalDevice, Queue,
SubmissionBatch,
};
use log::{debug, info, warn};
use std::ops::Deref;
pub type InstanceObject = SharedRef<br::InstanceObject>;
pub type DeviceObject = Shar... | (
&mut self,
batches: &[br::vk::VkSubmitInfo],
fence: &mut (impl br::Fence + br::VkHandleMut),
) -> br::Result<()> {
self.graphics_queue
.q
.get_mut()
.submit_raw(batches, Some(fence))
}
/// Submits any commands as transient comman... | submit_buffered_commands_raw | identifier_name |
graphics.rs | use crate::mthelper::SharedRef;
use bedrock as br;
use br::{
CommandBuffer, CommandPool, Device, Instance, InstanceChild, PhysicalDevice, Queue,
SubmissionBatch,
};
use log::{debug, info, warn};
use std::ops::Deref;
pub type InstanceObject = SharedRef<br::InstanceObject>;
pub type DeviceObject = Shar... |
pub const fn visible_from_host(&self) -> bool {
self.has_property_flags(br::MemoryPropertyFlags::HOST_VISIBLE)
}
pub const fn is_host_coherent(&self) -> bool {
self.has_property_flags(br::MemoryPropertyFlags::HOST_COHERENT)
}
pub const fn is_host_cached(&self) -> bool {... | {
self.has_property_flags(br::MemoryPropertyFlags::DEVICE_LOCAL)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.