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
#![allow(clippy::float_cmp)] #![allow(clippy::inline_always)] #![allow(clippy::many_single_char_names)] #![allow(clippy::needless_lifetimes)] #![allow(clippy::needless_return)] #![allow(clippy::or_fun_call)] #![allow(clippy::too_many_arguments)] #![allow(clippy::redundant_field_names)] #![allow(clippy::enum_variant_nam...
.value_name("N") .help("Number of samples per pixel") .takes_value(true) .validator(|s| { usize::from_str(&s) .and(Ok(())) .or(Err("must be an integer".to_string())) }), ...
{ let mut t = Timer::new(); // Parse command line arguments. let args = App::new("Psychopath") .version(VERSION) .about("A slightly psychotic path tracer") .arg( Arg::with_name("input") .short("i") .long("input") .value_nam...
identifier_body
main.rs
#![allow(clippy::float_cmp)] #![allow(clippy::inline_always)] #![allow(clippy::many_single_char_names)] #![allow(clippy::needless_lifetimes)] #![allow(clippy::needless_return)] #![allow(clippy::or_fun_call)] #![allow(clippy::too_many_arguments)] #![allow(clippy::redundant_field_names)] #![allow(clippy::enum_variant_nam...
() { let mut t = Timer::new(); // Parse command line arguments. let args = App::new("Psychopath") .version(VERSION) .about("A slightly psychotic path tracer") .arg( Arg::with_name("input") .short("i") .long("input") .value_name("...
main
identifier_name
main.rs
#![allow(clippy::float_cmp)] #![allow(clippy::inline_always)] #![allow(clippy::many_single_char_names)] #![allow(clippy::needless_lifetimes)] #![allow(clippy::needless_return)] #![allow(clippy::or_fun_call)] #![allow(clippy::too_many_arguments)] #![allow(clippy::redundant_field_names)] #![allow(clippy::enum_variant_nam...
let arena = Arena::new().with_block_size((1 << 20) * 4); let mut r = parse_scene(&arena, child).unwrap_or_else(|e| { e.print(&psy_contents); panic!("Parse error."); }); if let Some(spp) = args.value_of("spp") { ...
if !args.is_present("serialized_output") { println!("Building scene..."); }
random_line_split
elements.rs
/* Copyright 2018 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
fn size_hint(&self) -> (usize, Option<usize>) { let count = self.reader.get_count() as usize; (count, Some(count)) } } /// A reader for the element section of a WebAssembly module. #[derive(Clone)] pub struct ElementSectionReader<'a> { reader: BinaryReader<'a>, count: u32, } impl<'a> ...
{ if self.err || self.left == 0 { return None; } let result = self.reader.read(); self.err = result.is_err(); self.left -= 1; Some(result) }
identifier_body
elements.rs
/* Copyright 2018 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
/// ``` pub fn read<'b>(&mut self) -> Result<Element<'b>> where 'a: 'b, { let elem_start = self.reader.original_position(); // The current handling of the flags is largely specified in the `bulk-memory` proposal, // which at the time this commend is written has been merge...
/// for _ in 0..items_reader.get_count() { /// let item = items_reader.read().expect("item"); /// println!(" Item: {:?}", item); /// } /// }
random_line_split
elements.rs
/* Copyright 2018 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
let kind = if flags & 0b001!= 0 { if flags & 0b010!= 0 { ElementKind::Declared } else { ElementKind::Passive } } else { let table_index = if flags & 0b010 == 0 { 0 } else { self.r...
{ return Err(BinaryReaderError::new( "invalid flags byte in element segment", self.reader.original_position() - 1, )); }
conditional_block
elements.rs
/* Copyright 2018 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
(&self) -> u32 { self.count } /// Reads content of the element section. /// /// # Examples /// /// ```no_run /// # let data: &[u8] = &[]; /// use wasmparser::{ElementSectionReader, ElementKind}; /// let mut element_reader = ElementSectionReader::new(data, 0).unwrap(); //...
get_count
identifier_name
framebuffer.rs
// Copyright (c) 2016 The vulkano developers // 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. All files in the project carrying such // notice may not be co...
where Rp: RenderPassDescAttachmentsList<At> { #[inline] fn check_attachments_list(&self, atch: At) -> Result<Box<AttachmentsList + Send + Sync>, FramebufferCreationError> { self.render_pass.check_attachments_list(atch) } } unsafe impl<C, Rp, A> RenderPassDescClearValues<C> for Framebuffer<Rp, A...
} } unsafe impl<At, Rp, A> RenderPassDescAttachmentsList<At> for Framebuffer<Rp, A>
random_line_split
framebuffer.rs
// Copyright (c) 2016 The vulkano developers // 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. All files in the project carrying such // notice may not be co...
<Ia>(render_pass: Rp, dimensions: [u32; 3], attachments: Ia) -> Result<Arc<Framebuffer<Rp, Box<AttachmentsList + Send + Sync>>>, FramebufferCreationError> where Rp: RenderPassAbstract + RenderPassDescAttachmentsList<Ia> { let device = render_pass.device().clone(); // This...
new
identifier_name
framebuffer.rs
// Copyright (c) 2016 The vulkano developers // 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. All files in the project carrying such // notice may not be co...
} // Checking the dimensions against the attachments. if let Some(dims_constraints) = attachments.intersection_dimensions() { if dims_constraints[0] < dimensions[0] || dims_constraints[1] < dimensions[1] || dims_constraints[2] < dimensions[2] { ...
{ return Err(FramebufferCreationError::DimensionsTooLarge); }
conditional_block
main.rs
!("just an integer: {:?}", (5u32)); let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:\n{}", matrix); println!("Transpose:\n{}", transpose(matrix)); } fn analyze_slice(slice...
else { println!("`i` is `{:?}`. Try again.", i); optional = Some(i + 1); } } } fn isDivisibleBy(lhs: u32, rhs: u32) -> bool { if (rhs == 0) { return false; } lhs % rhs == 0 } impl Point { fn origin() -> Point { Point { x: 0.0, y: 0.0 } } fn...
{ println!("Number is: {}", i); optional = None; }
conditional_block
main.rs
println!("just an integer: {:?}", (5u32)); let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:\n{}", matrix); println!("Transpose:\n{}", transpose(matrix)); } fn analyze_sli...
println!("2 in v1: {}", a1.iter().any(|&x| x == 2)); println!("2 in v2: {}", a2.iter().any(|&x| x == 2)); let mut iter1 = v1.iter(); let mut into_iter = v2.into_iter(); println!("Find 2 in v1: {:?}", iter1.find(|&&x| x == 2)); println!("Find 2 in v1: {:?}", into_iter.find(|&x| x == 2)); ...
random_line_split
main.rs
!("just an integer: {:?}", (5u32)); let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:\n{}", matrix); println!("Transpose:\n{}", transpose(matrix)); } fn analyze_slice(slice...
() { let random_number = 0.3444; let animal = random_animal(random_number); println!( "You've randomly chosen an animal, and it says {}", animal.noise() ); } use std::ops; struct Foo; struct Bar; #[derive(Debug)] struct FooBar; #[derive(Debug)] struct BarFoo; impl ops::Add<Bar> for F...
dyReturn
identifier_name
main.rs
!("just an integer: {:?}", (5u32)); let tuple = (1, "hello", 4.5, true); let (a, b, c, d) = tuple; println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); let matrix = Matrix(1.1, 1.2, 2.1, 2.2); println!("Matrix:\n{}", matrix); println!("Transpose:\n{}", transpose(matrix)); } fn analyze_slice(slice...
mem::drop(farewel); }; apply(diary); let double = |x| 2 * x; println!("3 doubled: {}", apply_to_3(double)); let closure = || println!("I am closure"); call_me(function); call_me(closure); } fn create_fn() -> impl Fn() { let text = "Fn".to_owned(); move || println!("Thi...
{ let x = 30; println!("x: {:?}", x); let y = apply_to_3(|x| x + 20); println!("y: {:?}", y); let greeting = "Hello"; let mut farewel = "Goodby".to_owned(); let diary = || { println!("I said {}", greeting); farewel.push_str("!!!!!"); println!("Than I screemed {}...
identifier_body
dec.rs
comment on this rule: "The instantiation of type schemes allows different occurrences of // a single longvid to assume different types." Exp::LongVid(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; Ok(instantiate(st, &val_info.ty_scheme)) } // SML Definition (3) ...
pub fn ck(cx: &Cx, st: &mut State, dec: &Located<Dec<StrRef>>) -> Result<Env> { match &dec.val { // SML Definition (15) Dec::Val(ty_vars, val_binds) => { let mut cx_cl; let cx = if ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, t...
{ fun_infos .iter() .map(|(&name, fun_info)| { let ty = fun_info .args .iter() .rev() .fold(Ty::Var(fun_info.ret), |ac, &tv| { Ty::Arrow(Ty::Var(tv).into(), ac.into()) }); (name, ValInfo::val(TyScheme::mono(ty))) }) .collect() }
identifier_body
dec.rs
comment on this rule: "The instantiation of type schemes allows different occurrences of // a single longvid to assume different types." Exp::LongVid(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; Ok(instantiate(st, &val_info.ty_scheme)) } // SML Definition (3) ...
Dec::Fun(ty_vars, fval_binds) => { let mut cx_cl; let cx = if ty_vars.is_empty() { cx } else { cx_cl = cx.clone(); insert_ty_vars(&mut cx_cl, st, ty_vars)?; &cx_cl }; let mut fun_infos = HashMap::with_capacity(fval_binds.len()); for fval_bind in fv...
random_line_split
dec.rs
comment on this rule: "The instantiation of type schemes allows different occurrences of // a single longvid to assume different types." Exp::LongVid(vid) => { let val_info = get_val_info(get_env(&cx.env, vid)?, vid.last)?; Ok(instantiate(st, &val_info.ty_scheme)) } // SML Definition (3) ...
(cx: &Cx, st: &mut State, cases: &Cases<StrRef>) -> Result<(Vec<Located<Pat>>, Ty, Ty)> { let arg_ty = Ty::Var(st.new_ty_var(false)); let res_ty = Ty::Var(st.new_ty_var(false)); let mut pats = Vec::with_capacity(cases.arms.len()); // SML Definition (14) for arm in cases.arms.iter() { let (val_env, pat_ty,...
ck_cases
identifier_name
parser.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
#[must_use] /// Read the next character from the input if it matches the target. fn read_given_char(&mut self, target: char) -> Option<()> { self.read_atomically(|p| { p.read_char().and_then(|c| if c == target { Some(()) } else { None }) }) } /// Helper for reading sepa...
self.state = tail; char::from(b) }) }
random_line_split
parser.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
(s: &str) -> Result<Ipv6Addr, AddrParseError> { Self::parse_ascii(s.as_bytes()) } } impl SocketAddrV4 { /// Parse an IPv4 socket address from a slice of bytes. /// /// ``` /// #![feature(addr_parse_ascii)] /// /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let socket = ...
from_str
identifier_name
parser.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
// Read a number off the front of the input in the given radix, stopping // at the first non-digit character or eof. Fails if the number has more // digits than max_digits or if there is no number. #[allow(clippy::if_same_then_else)] fn read_number<T: ReadNumberHelper>( &mut self, ...
{ self.read_atomically(move |p| { if index > 0 { p.read_given_char(sep)?; } inner(p) }) }
identifier_body
cubic64.rs
// Copyright 2012 Google Inc. // Copyright 2020 Yevhenii Reizner // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use super::point64::{Point64, SearchAxis}; use super::quad64; use super::Scalar64; #[cfg(all(not(feature = "std"), feature = "no-std-float"))] use...
continue; } t = next_t; } let test_at_t = self.point_at_t(t); cubic_at_t = test_at_t; calc_pos = cubic_at_t.axis_coord(x_axis); calc_dist = calc_pos - axis_intercept; if calc_pos.approximately...
{ let next_t = t + last_step; if next_t > max { return -1.0; } let more_pt = self.point_at_t(next_t); if more_pt.x.approximately_equal_half(cubic_at_t.x) && more_pt.y.approximately_equal_half(cubic_a...
conditional_block
cubic64.rs
// Copyright 2012 Google Inc. // Copyright 2020 Yevhenii Reizner // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use super::point64::{Point64, SearchAxis}; use super::quad64; use super::Scalar64; #[cfg(all(not(feature = "std"), feature = "no-std-float"))] use...
} if (a + b + c + d).approximately_zero() { // 1 is one root let mut num = quad64::roots_real(a, a + b, -d, s); for i in 0..num { if s[i].almost_dequal_ulps(1.0) { return num; } } s[num] = 1.0; num += 1; return num;...
return num;
random_line_split
cubic64.rs
// Copyright 2012 Google Inc. // Copyright 2020 Yevhenii Reizner // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use super::point64::{Point64, SearchAxis}; use super::quad64; use super::Scalar64; #[cfg(all(not(feature = "std"), feature = "no-std-float"))] use...
(src: &[f64]) -> (f64, f64, f64, f64) { let mut a = src[6]; // d let mut b = src[4] * 3.0; // 3*c let mut c = src[2] * 3.0; // 3*b let d = src[0]; // a a -= d - c + b; // A = -a + 3*b - 3*c + d b += 3.0 * d - 2.0 * c; // B = 3*a - 6*b + 3*c c -= 3.0 * d; // C = -3*a + 3*b (a, b, c, d...
coefficients
identifier_name
cubic64.rs
// Copyright 2012 Google Inc. // Copyright 2020 Yevhenii Reizner // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use super::point64::{Point64, SearchAxis}; use super::quad64; use super::Scalar64; #[cfg(all(not(feature = "std"), feature = "no-std-float"))] use...
} } debug_assert!(found_roots < 3); t[found_roots] = 0.0; found_roots += 1; } } found_roots } fn roots_real(a: f64, b: f64, c: f64, d: f64, s: &mut [f64; 3]) -> usize { if a.approximately_zero() && a.approximately_zero_when_...
{ let mut s = [0.0; 3]; let real_roots = roots_real(a, b, c, d, &mut s); let mut found_roots = quad64::push_valid_ts(&s, real_roots, t); 'outer: for index in 0..real_roots { let t_value = s[index]; if !t_value.approximately_one_or_less() && t_value.between(1.0, 1.00005) { for...
identifier_body
serde_snapshot.rs
use { crate::{ accounts::Accounts, accounts_db::{AccountStorageEntry, AccountsDB, AppendVecId, BankHashInfo}, accounts_index::Ancestors, append_vec::AppendVec, bank::{Bank, BankFieldsToDeserialize, BankRc, Builtins}, blockhash_queue::BlockhashQueue, epoch_stak...
frozen_account_pubkeys: &[Pubkey], account_paths: &[PathBuf], append_vecs_path: P, debug_keys: Option<Arc<HashSet<Pubkey>>>, additional_builtins: Option<&Builtins>, ) -> Result<Bank, Error> where E: Into<AccountStorageEntry>, P: AsRef<Path>, { let mut accounts_db = reconstruct_accountsdb...
genesis_config: &GenesisConfig,
random_line_split
serde_snapshot.rs
use { crate::{ accounts::Accounts, accounts_db::{AccountStorageEntry, AccountsDB, AppendVecId, BankHashInfo}, accounts_index::Ancestors, append_vec::AppendVec, bank::{Bank, BankFieldsToDeserialize, BankRc, Builtins}, blockhash_queue::BlockhashQueue, epoch_stak...
<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer, { C::serialize_bank_and_storage(serializer, self) } } struct SerializableAccountsDB<'a, C> { accounts_db: &'a AccountsDB, slot: Slot, account_storage_entries: &'a [SnapshotStorage]...
serialize
identifier_name
serde_snapshot.rs
use { crate::{ accounts::Accounts, accounts_db::{AccountStorageEntry, AccountsDB, AppendVecId, BankHashInfo}, accounts_index::Ancestors, append_vec::AppendVec, bank::{Bank, BankFieldsToDeserialize, BankRc, Builtins}, blockhash_queue::BlockhashQueue, epoch_stak...
let mut remaining_slots_to_process = storage.len(); // Remap the deserialized AppendVec paths to point to correct local paths let mut storage = storage .into_iter() .map(|(slot, mut slot_storage)| { let now = Instant::now(); if now.duration_since(last_log_update).as_se...
{ let mut accounts_db = AccountsDB::new(account_paths.to_vec(), cluster_type); let AccountsDbFields(storage, version, slot, bank_hash_info) = accounts_db_fields; // convert to two level map of slot -> id -> account storage entry let storage = { let mut map = HashMap::new(); for (slot, ...
identifier_body
store.rs
/*! Bit management The `BitStore` trait defines constants and associated functions suitable for managing the bit patterns of a fundamental, and is the constraint for the storage type of the data structures of the rest of the crate. The other types in this module provide stronger rules about how indices map to concret...
use core::{ cmp::Eq, fmt::{ Binary, Debug, Display, LowerHex, UpperHex, }, mem::size_of, ops::{ BitAnd, BitAndAssign, BitOrAssign, Not, Shl, ShlAssign, Shr, ShrAssign, }, }; #[cfg(feature = "atomic")] use core::sync::atomic::{ self, Ordering::Relaxed, }; #[cfg(not(feature = "atomic")...
use crate::{ cursor::Cursor, indices::BitIdx, };
random_line_split
store.rs
/*! Bit management The `BitStore` trait defines constants and associated functions suitable for managing the bit patterns of a fundamental, and is the constraint for the storage type of the data structures of the rest of the crate. The other types in this module provide stronger rules about how indices map to concret...
#[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_or(*C::mask(bit), Relaxed); } #[inline(always)] fn invert_bit<C>(&self, bit: BitIdx<u16>) where C: Cursor { self.fetch_xor(*C::mask(bit), Relaxed); } #[inline(always)] fn load(&self) -> u16 { self.load(Relaxed) } } ...
self.fetch_and(!*C::mask(bit), Relaxed); }
identifier_body
store.rs
/*! Bit management The `BitStore` trait defines constants and associated functions suitable for managing the bit patterns of a fundamental, and is the constraint for the storage type of the data structures of the rest of the crate. The other types in this module provide stronger rules about how indices map to concret...
self) -> u64 { self.load(Relaxed) } } } #[cfg(not(feature = "atomic"))] fn _cell() { impl BitAccess<u8> for Cell<u8> { #[inline(always)] fn clear_bit<C>(&self, bit: BitIdx<u8>) where C: Cursor { self.set(self.get() &!*C::mask(bit)); } #[inline(always)] fn set_bit<C>(&self, bit: BitIdx<u8>) where C: Curs...
ad(&
identifier_name
store.rs
/*! Bit management The `BitStore` trait defines constants and associated functions suitable for managing the bit patterns of a fundamental, and is the constraint for the storage type of the data structures of the rest of the crate. The other types in this module provide stronger rules about how indices map to concret...
else { *self &=!mask; } } /// Gets a specific bit in an element. /// /// # Safety /// /// This method cannot be called from within a `&BitSlice` context; it may /// only be called by construction of an `&Self` reference from a `Self` /// element directly. /// /// # Parameters /// /// - `place`: A bit...
*self |= mask; }
conditional_block
peer.rs
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK}; use crate::network::Network; use crate::peer::atomic_reader::AtomicReader; use crate::util::rx::{Observable, Observer, Single, Subject}; use crate::util::{secs_since, Error, Result}; use snowflake::ProcessUniqueId; use std::f...
}; if!filter.connectable(&their_version) { return Err(Error::IllegalState("Peer filtered out".to_string())); } let now = secs_since(UNIX_EPOCH) as i64; *self.time_delta.lock().unwrap() = now - their_version.timestamp; *self.version.lock().unwrap() = Some(the...
{ // Connect over TCP let tcp_addr = SocketAddr::new(self.ip, self.port); let mut tcp_stream = TcpStream::connect_timeout(&tcp_addr, CONNECT_TIMEOUT)?; tcp_stream.set_nodelay(true)?; // Disable buffering tcp_stream.set_read_timeout(Some(HANDSHAKE_READ_TIMEOUT))?; tcp_stre...
identifier_body
peer.rs
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK}; use crate::network::Network; use crate::peer::atomic_reader::AtomicReader; use crate::util::rx::{Observable, Observer, Single, Subject}; use crate::util::{secs_since, Error, Result}; use snowflake::ProcessUniqueId; use std::f...
// Always check the connected flag right after the blocking read so we exit right away, // and also so that we don't mistake errors with the stream shutting down if!tpeer.connected.load(Ordering::Relaxed) { return; } ma...
None => Message::read(&mut tcp_reader, magic), };
random_line_split
peer.rs
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK}; use crate::network::Network; use crate::peer::atomic_reader::AtomicReader; use crate::util::rx::{Observable, Observer, Single, Subject}; use crate::util::{secs_since, Error, Result}; use snowflake::ProcessUniqueId; use std::f...
(&self) -> Result<Version> { match &*self.version.lock().unwrap() { Some(ref version) => Ok(version.clone()), None => Err(Error::IllegalState("Not connected".to_string())), } } fn connect_internal(peer: &Arc<Peer>, version: Version, filter: Arc<dyn PeerFilter>) { ...
version
identifier_name
peer.rs
use crate::messages::{Message, MessageHeader, Ping, Version, NODE_BITCOIN_CASH, NODE_NETWORK}; use crate::network::Network; use crate::peer::atomic_reader::AtomicReader; use crate::util::rx::{Observable, Observer, Single, Subject}; use crate::util::{secs_since, Error, Result}; use snowflake::ProcessUniqueId; use std::f...
_ => return Err(Error::BadData("Unexpected command".to_string())), }; // Write our verack debug!("{:?} Write {:#?}", self, Message::Verack); Message::Verack.write(&mut tcp_stream, magic)?; // Write a ping message because this seems to help with connection weirdness...
{}
conditional_block
mod.rs
/// /// ```no_run /// # #[macro_use] extern crate vulkano; /// # fn main() { /// use vulkano::{ /// instance::{Instance, InstanceCreateInfo, InstanceExtensions}, /// Version, VulkanLibrary, /// }; /// /// let library = VulkanLibrary::new().unwrap(); /// let _instance = Instance::new( /// library, /// In...
pub fn library(&self) -> &Arc<VulkanLibrary> { &self.library } /// Returns the Vulkan version supported by the instance. /// /// This is the lower of the /// [driver's supported version](crate::VulkanLibrary::api_version) and /// [`max_api_version`](Instance::max_api_version). #...
/// Returns the Vulkan library used to create this instance. #[inline]
random_line_split
mod.rs
}; (std::cmp::min(max_api_version, api_version), max_api_version) }; // VUID-VkApplicationInfo-apiVersion-04010 assert!(max_api_version >= Version::V1_0); let supported_extensions = library.supported_extensions_with_layers(enabled_layers.iter().map(St...
from
identifier_name
mod.rs
/// ```no_run /// # #[macro_use] extern crate vulkano; /// # fn main() { /// use vulkano::{ /// instance::{Instance, InstanceCreateInfo, InstanceExtensions}, /// Version, VulkanLibrary, /// }; /// /// let library = VulkanLibrary::new().unwrap(); /// let _instance = Instance::new( /// library, /// Insta...
/// Returns an iterator that enumerates the physical devices available. /// /// # Examples /// /// ```no_run /// # use vulkano::{ /// # instance::{Instance, InstanceExtensions}, /// # Version, VulkanLibrary, /// # }; /// /// # let library = VulkanLibrary::new().unwr...
{ &self.enabled_layers }
identifier_body
vcf.rs
use std::{ fmt::{self, Write as fmtWrite}, io::{self, BufWriter, Write}, }; use log::Level::Trace; use compress_io::{ compress::{CompressIo, Writer}, compress_type::CompressType, }; use r_htslib::*; use crate::{ model::{freq_mle, AlleleRes, N_QUAL, MAX_PHRED, ModelRes}, mann_whitney::mann_whitney,...
// Filter cutoffs let snv_soft_lim = self.cfg.snv_threshold(ThresholdType::Soft); let indel_soft_lim = self.cfg.indel_threshold(ThresholdType::Soft); let desc = vr.adesc.as_ref().unwrap_or(&self.all_desc); // Extra per allele results let mut all_res: Vec<_> = vr.alleles.iter()....
// Reference allele let ref_ix = vr.alleles[0].ix;
random_line_split
vcf.rs
use std::{ fmt::{self, Write as fmtWrite}, io::{self, BufWriter, Write}, }; use log::Level::Trace; use compress_io::{ compress::{CompressIo, Writer}, compress_type::CompressType, }; use r_htslib::*; use crate::{ model::{freq_mle, AlleleRes, N_QUAL, MAX_PHRED, ModelRes}, mann_whitney::mann_whitney,...
let snv_soft_lim = self.cfg.snv_threshold(ThresholdType::Soft); let indel_soft_lim = self.cfg.indel_threshold(ThresholdType::Soft); let desc = vr.adesc.as_ref().unwrap_or(&self.all_desc); // Extra per allele results let mut all_res: Vec<_> = vr.alleles.iter().map(|ar| { // Av...
{ let x = vr.x; let raw_depth = cts.iter().fold(0, |t, x| t + x[0] + x[1]); let thresh = 0.05 / (self.seq_len as f64); // Sort alleles by frequency (keeping reference alleles at position 0) vr.alleles[1..].sort_unstable_by(|a1, a2| a2.res.freq.partial_cmp(&a1.res.freq).unwrap()); ...
identifier_body
vcf.rs
use std::{ fmt::{self, Write as fmtWrite}, io::{self, BufWriter, Write}, }; use log::Level::Trace; use compress_io::{ compress::{CompressIo, Writer}, compress_type::CompressType, }; use r_htslib::*; use crate::{ model::{freq_mle, AlleleRes, N_QUAL, MAX_PHRED, ModelRes}, mann_whitney::mann_whitney,...
{ pub(crate) res: AlleleRes, pub(crate) ix: usize, } pub(crate) struct VcfRes { pub(crate) alleles: Vec<Allele>, pub(crate) adesc: Option<Vec<AllDesc>>, pub(crate) x: usize, pub(crate) phred: u8, } // Additional allele specific results #[derive(Default, Copy, Clone)] struct ExtraRes { flt: u32, ...
Allele
identifier_name
vcf.rs
use std::{ fmt::{self, Write as fmtWrite}, io::{self, BufWriter, Write}, }; use log::Level::Trace; use compress_io::{ compress::{CompressIo, Writer}, compress_type::CompressType, }; use r_htslib::*; use crate::{ model::{freq_mle, AlleleRes, N_QUAL, MAX_PHRED, ModelRes}, mann_whitney::mann_whitney,...
else { 1.0 }; // Wilcoxon-Mann-Whitney test for quality bias between the major (most frequent) // allele and all minor alleles let wilcox = if ar.ix!= major_idx { mann_whitney(qcts, major_idx, ar.ix).unwrap_or(1.0) } else { 1.0 }; // Set allele freq. flags ...
{ let k = ar.ix; let k1 = major_idx; let all_cts = [cts[k][0], cts[k1][0], cts[k][1], cts[k1][1]]; let fs = self.ftest.fisher(&all_cts); if ar.res.freq < 0.75 && fs <= thresh { flt |= FLT_FS } fs }
conditional_block
hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use cra...
self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, raw_line)) => { if let HunkPlus(_, _) = self.state { // We have just entered a new subhunk; process the previous one // and flus...
{ use DiffType::*; use State::*; // A true hunk line should start with one of: '+', '-', ' '. However, handle_hunk_line // handles all lines until the state transitions away from the hunk states. if !self.test_hunk_line() { return Ok(false); } // Don'...
identifier_body
hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use cra...
(&self) -> bool { matches!( self.state, State::HunkHeader(_, _, _, _) | State::HunkZero(_, _) | State::HunkMinus(_, _) | State::HunkPlus(_, _) ) } /// Handle a hunk line, i.e. a minus line, a plus line, or an unchanged line...
test_hunk_line
identifier_name
hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use cra...
if let State::HunkHeader(_, parsed_hunk_header, line, raw_line) = &self.state.clone() { self.emit_hunk_header_line(parsed_hunk_header, line, raw_line)?; } self.state = match new_line_state(&self.line, &self.raw_line, &self.state, self.config) { Some(HunkMinus(diff_type, r...
|| self.painter.plus_lines.len() > self.config.line_buffer_size { self.painter.paint_buffered_minus_and_plus_lines(); }
random_line_split
hunk.rs
use std::cmp::min; use lazy_static::lazy_static; use crate::cli; use crate::config::{delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State, StateMachine}; use crate::paint::{prepare, prepare_raw_line}; use crate::style; use crate::utils::process::{self, CallingProcess}; use cra...
// 1. Given the previous line state, compute the new line diff type. These are basically the // same, except that a string prefix is converted into an integer number of parents (prefix // length). let diff_type = match prev_state { HunkMinus(Unified, _) | HunkZero(Unified, _) ...
{ return Some(HunkZero( Unified, maybe_raw_line(new_raw_line, config.zero_style.is_raw, 0, &[], config), )); }
conditional_block
formatter.rs
use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::str; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, ...
/// thousands getter pub fn thousands(&self) -> bool { self.thousands } /// precision getter pub fn precision(&self) -> Option<usize> { self.precision } /// set precision to None, used for formatting int, float, etc pub fn set_precision(&mut self, precision: Option<us...
{ self.width }
identifier_body
formatter.rs
use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::str; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, ...
if end - pos >= 1 && rest[pos] as char == '#' { format.alternate = true; pos += 1; } // The special case for 0-padding (backwards compat) if!fill_specified && end - pos >= 1 && rest[pos] == '0' as u8 { format.fill = '0'; if!align_specified { format.align = '=...
// If the next character is #, we're in alternate mode. This only // applies to integers.
random_line_split
formatter.rs
use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::str; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, ...
(&self) -> bool { self.alternate } // sign_aware_zero_pad // Not supported /// type getter pub fn ty(&self) -> Option<char> { self.ty } /// UNSTABLE: in the future, this may return true if all validty /// checks for a float return true /// return true if ty is valid ...
alternate
identifier_name
formatter.rs
use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::str; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, ...
} } else { // Not having a precision after a dot is an error. if consumed == 0 { return Err(FmtError::Invalid( "Format specifier missing precision".to_string(), )); } } pos += consumed; } ...
{ format.precision = v; }
conditional_block
align.rs
AlignMode::Global | AlignMode::Blockwise(_) => InternalMode::Global, } } } trait Align { fn align(&self, algo: &AlignAlgorithm, mode: InternalMode, x: &[u8], y: &[u8]) -> Vec<Op>; } /// Determines whether to use the banded variant of the algorithm with given k-mer length /// and window size #...
yaddr += size } } } (v, xaddr, yaddr) } } fn ops_pattern_subrange(mut ops: &[Op]) -> (&[Op], usize) { let mut ret_addr = 0; if let [Op::Yclip(addr), rest @..] = ops { ops = rest; ret_addr += addr; } while let [Op::Del, ...
}));
random_line_split
align.rs
{ Local, Global, Semiglobal, } impl From<AlignMode> for InternalMode { fn from(value: AlignMode) -> Self { match value { AlignMode::Local => InternalMode::Local, AlignMode::Global | AlignMode::Blockwise(_) => InternalMode::Global, } } } trait Align { fn...
InternalMode
identifier_name
align.rs
AlignMode::Global | AlignMode::Blockwise(_) => InternalMode::Global, } } } trait Align { fn align(&self, algo: &AlignAlgorithm, mode: InternalMode, x: &[u8], y: &[u8]) -> Vec<Op>; } /// Determines whether to use the banded variant of the algorithm with given k-mer length /// and window size #[d...
Op::Del => { v.push(AlignElement { xaddr, xbyte: None, yaddr, ybyte: Some(y[yaddr]), }); yaddr += 1; } Op::Xclip(si...
{ v.push(AlignElement { xaddr, xbyte: Some(x[xaddr]), yaddr, ybyte: None, }); xaddr += 1; }
conditional_block
efi.rs
use core::ffi::c_void; use core::fmt; const ERROR_BIT: usize = 1 << (core::mem::size_of::<usize>() * 8 - 1); #[derive(Clone, Copy)] #[repr(transparent)] pub struct EFI_HANDLE(*mut c_void); #[derive(PartialEq, Debug)] #[repr(usize)] pub enum EFI_STATUS { /// The operation completed successfully. SUCCESS ...
} } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(C)] pub struct MemoryMapKey(usize); #[repr(C)] #[derive(Copy, Clone)] pub struct EFI_MEMORY_DESCRIPTOR { pub Type: EFI_MEMORY_TYPE, padding: u32, pub PhysicalStart: u64, pub VirtualStart: u64, pub NumberOfPages: u64, pub Attribute: u64, } impl fmt::D...
{ let string = match *self { EFI_MEMORY_TYPE::EfiReservedMemoryType => "ReservedMemory", EFI_MEMORY_TYPE::EfiLoaderCode => "LoaderCode", EFI_MEMORY_TYPE::EfiLoaderData => "LoaderData", EFI_MEMORY_TYPE::EfiBootServicesCode => "BootServicesCode", EFI_MEMORY_TYPE::EfiBootServicesData => ...
identifier_body
efi.rs
use core::ffi::c_void; use core::fmt; const ERROR_BIT: usize = 1 << (core::mem::size_of::<usize>() * 8 - 1); #[derive(Clone, Copy)] #[repr(transparent)] pub struct EFI_HANDLE(*mut c_void); #[derive(PartialEq, Debug)] #[repr(usize)] pub enum EFI_STATUS { /// The operation completed successfully. SUCCESS ...
{ pub Hdr: EFI_TABLE_HEADER, // Task Priority Services dummy1: [usize;2], // Memory Services pub AllocatePages: unsafe extern "C" fn(Type: EFI_ALLOCATE_TYPE, MemoryType: EFI_MEMORY_TYPE, Pages:usize, Memory: &mut u64) -> EFI_STATUS, dymmy2a: [usize;1], pub GetMemoryMap: unsafe extern "C" fn(MemoryMapSize:...
EFI_BOOT_SERVICES
identifier_name
efi.rs
use core::ffi::c_void; use core::fmt; const ERROR_BIT: usize = 1 << (core::mem::size_of::<usize>() * 8 - 1); #[derive(Clone, Copy)] #[repr(transparent)] pub struct EFI_HANDLE(*mut c_void); #[derive(PartialEq, Debug)] #[repr(usize)] pub enum EFI_STATUS { /// The operation completed successfully. SUCCESS ...
// Library Services dummy9a: [usize;2], pub LocateProtocol: unsafe extern "C" fn (Protocol: &EFI_GUID, Registration: *mut c_void, Interface: &mut *mut c_void) -> EFI_STATUS, dummy9b: [usize;2], // 32-bit CRC Services dummy10: [usize;1], // Miscellaneous Services dummy11: [usize;3], } #[repr(C)] pub stru...
dummy7: [usize;2], // Open and Close Protocol Services dummy8: [usize;3],
random_line_split
prio_bitmap.rs
//! Provides `FixedPrioBitmap`, a bit array structure supporting //! logarithmic-time bit scan operations. use core::{convert::TryFrom, fmt}; use super::{ctz::trailing_zeros, BinInteger, Init}; /// The maximum bit count supported by [`FixedPrioBitmap`]. pub const FIXED_PRIO_BITMAP_MAX_LEN: usize = WORD_LEN * WORD_LEN...
); gen_test!( #[cfg(any(target_pointer_width = "64", target_pointer_width = "128"))] mod size_100000, 100000 ); }
gen_test!( #[cfg(any(target_pointer_width = "32", target_pointer_width = "64", target_pointer_width = "128"))] mod size_10000, 10000
random_line_split
prio_bitmap.rs
//! Provides `FixedPrioBitmap`, a bit array structure supporting //! logarithmic-time bit scan operations. use core::{convert::TryFrom, fmt}; use super::{ctz::trailing_zeros, BinInteger, Init}; /// The maximum bit count supported by [`FixedPrioBitmap`]. pub const FIXED_PRIO_BITMAP_MAX_LEN: usize = WORD_LEN * WORD_LEN...
}) } fn enum_set_bits(bitmap: &impl PrioBitmap, bitmap_len: usize) -> Vec<usize> { (0..bitmap_len).filter(|&i| bitmap.get(i)).collect() } fn test_inner<T: PrioBitmap>(bytecode: Vec<u8>, size: usize) { let mut subject = T::INIT; let mut reference = BTreePrioBitmap::new();...
None }
conditional_block
prio_bitmap.rs
//! Provides `FixedPrioBitmap`, a bit array structure supporting //! logarithmic-time bit scan operations. use core::{convert::TryFrom, fmt}; use super::{ctz::trailing_zeros, BinInteger, Init}; /// The maximum bit count supported by [`FixedPrioBitmap`]. pub const FIXED_PRIO_BITMAP_MAX_LEN: usize = WORD_LEN * WORD_LEN...
-> Self { Self(BTreeSet::new()) } fn enum_set_bits(&self) -> Vec<usize> { self.0.iter().cloned().collect() } fn clear(&mut self, i: usize) { self.0.remove(&i); } fn set(&mut self, i: usize) { self.0.insert(i); } ...
w()
identifier_name
criterion.rs
use std::cmp; use std::fmt::Show; use std::io::Command; use std::num; use bencher::Bencher; use fs; use outliers::Outliers; use plot; use statistics::{Estimate,Estimates,Mean,Median,MedianAbsDev,Sample,StdDev}; use stream::Stream; use target::{Function,FunctionFamily,Program,Target}; use time::prefix::{Mili,Nano}; use...
/// Changes the size of a sample /// /// A sample consists of severals measurements #[experimental] pub fn sample_size(&mut self, n: uint) -> &mut Criterion { self.sample_size = n; self } /// Changes the significance level /// /// Significance level to use for hypo...
{ self.nresamples = n; self }
identifier_body
criterion.rs
use std::cmp; use std::fmt::Show; use std::io::Command; use std::num; use bencher::Bencher; use fs; use outliers::Outliers; use plot; use statistics::{Estimate,Estimates,Mean,Median,MedianAbsDev,Sample,StdDev}; use stream::Stream; use target::{Function,FunctionFamily,Program,Target}; use time::prefix::{Mili,Nano}; use...
(&mut self, sl: f64) -> &mut Criterion { assert!(sl > 0.0 && sl < 1.0); self.significance_level = sl; self } /// Changes the warm up time /// /// The program/function under test is executed during `warm_up_time` ms before the real /// measurement starts #[experimental] ...
significance_level
identifier_name
criterion.rs
use std::cmp; use std::fmt::Show; use std::io::Command; use std::num; use bencher::Bencher; use fs; use outliers::Outliers; use plot; use statistics::{Estimate,Estimates,Mean,Median,MedianAbsDev,Sample,StdDev}; use stream::Stream; use target::{Function,FunctionFamily,Program,Target}; use time::prefix::{Mili,Nano}; use...
} } fn format_time(ns: f64) -> String { if ns < 1.0 { format!("{:>6} ps", format_short(ns * 1e3)) } else if ns < num::pow(10.0, 3) { format!("{:>6} ns", format_short(ns)) } else if ns < num::pow(10.0, 6) { format!("{:>6} us", format_short(ns / 1e3)) } else if ns < num::pow(1...
random_line_split
mod.rs
pub(crate) mod css; mod css_function; mod error; pub mod formalargs; mod imports; mod media; pub mod selectors; mod span; pub(crate) mod strings; mod unit; pub(crate) mod util; pub mod value; pub(crate) use self::strings::name; pub use error::ParseError; pub(crate) use span::DebugBytes; pub(crate) use span::{position,...
}; let (input, body) = match next.fragment() { b"{" => map(body_block2, Some)(input)?, b";" => (input, None), b"" => (input, None), _ => (input, None), // error? }; let (input, _) = opt_spacelike(input)?; Ok((input, ns_or_prop_item(name, val, body, pos))) } use crat...
let (input, next) = if val.is_some() { alt((tag("{"), tag(";"), tag("")))(input)? } else { tag("{")(input)?
random_line_split
mod.rs
pub(crate) mod css; mod css_function; mod error; pub mod formalargs; mod imports; mod media; pub mod selectors; mod span; pub(crate) mod strings; mod unit; pub(crate) mod util; pub mod value; pub(crate) use self::strings::name; pub use error::ParseError; pub(crate) use span::DebugBytes; pub(crate) use span::{position,...
(data: &[u8]) -> Result<Value, Error> { let data = code_span(data); let value = all_consuming(value_expression)(data.borrow()); Ok(ParseError::check(value)?) } #[test] fn test_parse_value_data_1() -> Result<(), Error> { let v = parse_value_data(b"17em")?; assert_eq!(Value::Numeric(Numeric::new(17, ...
parse_value_data
identifier_name
mod.rs
pub(crate) mod css; mod css_function; mod error; pub mod formalargs; mod imports; mod media; pub mod selectors; mod span; pub(crate) mod strings; mod unit; pub(crate) mod util; pub mod value; pub(crate) use self::strings::name; pub use error::ParseError; pub(crate) use span::DebugBytes; pub(crate) use span::{position,...
}; Ok(( rest, Item::AtRule { name, args: args.map_or(Value::Null, x_args), body, pos: start.up_to(&input).to_owned(), }, )) } fn expression_argument(input: Span) -> PResult<Value> { terminated(value_expression, opt(tag(";")))(inpu...
{ let (input, args) = terminated(opt(unknown_rule_args), opt(ignore_space))(input)?; fn x_args(value: Value) -> Value { match value { Value::Variable(name, _pos) => { Value::Literal(SassString::from(format!("${name}"))) } Value::Map(map) => Val...
identifier_body
game.rs
use crate::abtest::ABTestMode; use crate::debug::DebugMode; use crate::edit::EditMode; use crate::helpers::ID; use crate::mission::MissionEditMode; use crate::render::DrawOptions; use crate::sandbox::SandboxMode; use crate::tutorial::TutorialMode; use crate::ui::{EditorState, Flags, ShowEverything, UI}; use abstutil::e...
(&self, canvas: &Canvas) { println!( "********************************************************************************" ); println!("UI broke! Primary sim:"); self.ui.primary.sim.dump_before_abort(); if let Mode::ABTest(ref abtest) = self.mode { if let Som...
dump_before_abort
identifier_name
game.rs
use crate::abtest::ABTestMode; use crate::debug::DebugMode; use crate::edit::EditMode; use crate::helpers::ID; use crate::mission::MissionEditMode; use crate::render::DrawOptions; use crate::sandbox::SandboxMode; use crate::tutorial::TutorialMode; use crate::ui::{EditorState, Flags, ShowEverything, UI}; use abstutil::e...
rng.gen_range(0.0, bounds.max_y), ); canvas.cam_zoom = 10.0; canvas.center_on_map_pt(at); Screensaver { line: Line::new(at, goto), started: Instant::now(), } } fn update( &mut self, rng: &mut XorShiftRng, inpu...
let goto = Pt2D::new( rng.gen_range(0.0, bounds.max_x),
random_line_split
game.rs
use crate::abtest::ABTestMode; use crate::debug::DebugMode; use crate::edit::EditMode; use crate::helpers::ID; use crate::mission::MissionEditMode; use crate::render::DrawOptions; use crate::sandbox::SandboxMode; use crate::tutorial::TutorialMode; use crate::ui::{EditorState, Flags, ShowEverything, UI}; use abstutil::e...
.map .all_lanes() .choose(&mut rng) .and_then(|l| ID::Lane(l.id).canonical_point(&game.ui.primary)) }) .expect("Can't get canonical_point of a random building or lane"); if splash { ctx.canvas.center_...
{ let splash = !flags.no_splash && !format!("{}", flags.sim_flags.load.display()).contains("data/save"); let mut rng = flags.sim_flags.make_rng(); let mut game = GameState { mode: Mode::Sandbox(SandboxMode::new(ctx)), ui: UI::new(flags, ctx), }; ...
identifier_body
sparse.rs
//! # Sparse vector //! //! Wrapping a `Vec<(usize, _)>`, fixed size. use std::{fmt, mem}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::{Debug, Display}; use std::iter::Sum; use std::marker::PhantomData; use std::ops::{Add, AddAssign, DivAssign, Mul, MulAssign, Neg}; use...
(&mut self, i: usize, value: F) { debug_assert!(i < self.len); debug_assert!(value.borrow().is_not_zero()); match self.get_data_index(i) { Ok(index) => self.data[index].1 = value, Err(index) => self.data.insert(index, (i, value)), } } fn get(&self, index...
set
identifier_name
sparse.rs
//! # Sparse vector //! //! Wrapping a `Vec<(usize, _)>`, fixed size. use std::{fmt, mem}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::{Debug, Display}; use std::iter::Sum; use std::marker::PhantomData; use std::ops::{Add, AddAssign, DivAssign, Mul, MulAssign, Neg}; use...
} }
writeln!(f)
random_line_split
sparse.rs
//! # Sparse vector //! //! Wrapping a `Vec<(usize, _)>`, fixed size. use std::{fmt, mem}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::{Debug, Display}; use std::iter::Sum; use std::marker::PhantomData; use std::ops::{Add, AddAssign, DivAssign, Mul, MulAssign, Neg}; use...
/// Whether this vector has zero size. fn is_empty(&self) -> bool { self.len == 0 } /// The size of this vector in memory. fn size(&self) -> usize { self.data.len() } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Create a `SparseV...
{ self.len }
identifier_body
sparse.rs
//! # Sparse vector //! //! Wrapping a `Vec<(usize, _)>`, fixed size. use std::{fmt, mem}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::fmt::{Debug, Display}; use std::iter::Sum; use std::marker::PhantomData; use std::ops::{Add, AddAssign, DivAssign, Mul, MulAssign, Neg}; use...
, Ordering::Greater => { match other.data[other_lowest..].binary_search_by_key(&self_sought, |&(i, _)| i) { Err(diff) => { self_lowest += 1; other_lowest += diff; }, ...
{ match self.data[self_lowest..].binary_search_by_key(&other_sought, |&(i, _)| i) { Err(diff) => { self_lowest += diff; other_lowest += 1; }, Ok(diff) => { ...
conditional_block
lib.rs
// Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
/// /// Run a Future on a tokio Runtime as a new Task, and return a Future handle to it. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, th...
{ let _context = self.handle.enter(); f() }
identifier_body
lib.rs
// Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
log::debug!( "waiting for {} session end task(s) to complete", inner.task_set.len() ); let mut timeout = tokio::time::sleep(timeout).boxed(); loop { tokio::select! { // Use biased mode to prefer an expired timeout over joining on remaining tasks. biased; // E...
if inner.task_set.is_empty() { return; }
random_line_split
lib.rs
// Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
<F>(&self, name: &str, handle: &Handle, task: F) where F: Future<Output = ()>, F: Send +'static, { let task = future_with_correct_context(task); let mut guard = self.inner.lock(); let inner = match &mut *guard { Some(inner) => inner, None => { log::warn!( "Session e...
spawn_on
identifier_name
lib.rs
// Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
} }
{ log::debug!( "{} session end task(s) failed to complete within timeout: {}", inner.task_set.len(), inner.id_to_name.values().join(", "), ); inner.task_set.abort_all(); }
conditional_block
traphandlers.rs
//! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. use crate::VMInterrupts; use backtrace::Backtrace; use std::any::Any; use std::cell::Cell; use std::error::Error; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Once; use wasmtim...
backtrace, maybe_interrupted, }) } UnwindReason::Panic(panic) => { debug_assert_eq!(ret, 0); std::panic::resume_unwind(panic) } } } /// Checks and/or initializes the wasm native ...
{ let _reset = self.update_stack_limit()?; let ret = tls::set(&self, || closure(&self)); match self.unwind.replace(UnwindReason::None) { UnwindReason::None => { debug_assert_eq!(ret, 1); Ok(()) } UnwindReason::UserTrap(data) => ...
identifier_body
traphandlers.rs
//! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. use crate::VMInterrupts; use backtrace::Backtrace; use std::any::Any; use std::cell::Cell; use std::error::Error; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Once; use wasmtim...
(val: Ptr) -> Ptr { // Mark the current thread as handling interrupts for this specific // CallThreadState: may clobber the previous entry. super::super::sys::register_tls(val); PTR.with(|p| p.replace(val)) } #[inline(never)] // see module docs for why t...
replace
identifier_name
traphandlers.rs
//! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. use crate::VMInterrupts; use backtrace::Backtrace; use std::any::Any; use std::cell::Cell; use std::error::Error; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Once; use wasmtim...
} /// Invokes the contextually-defined context's out-of-gas function. /// /// (basically delegates to `wasmtime::Store::out_of_gas`) pub fn out_of_gas() { tls::with(|state| state.unwrap().trap_info.out_of_gas()) } /// Temporary state stored on the stack which is registered in the `tls` module /// below for calls ...
random_line_split
traphandlers.rs
//! WebAssembly trap handling, which is built on top of the lower-level //! signalhandling mechanisms. use crate::VMInterrupts; use backtrace::Backtrace; use std::any::Any; use std::cell::Cell; use std::error::Error; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Once; use wasmtim...
}; struct Reset<'a>(bool, &'a AtomicUsize); impl Drop for Reset<'_> { fn drop(&mut self) { if self.0 { self.1.store(usize::max_value(), SeqCst); } } } Ok(Reset(reset_stack_limit, &interrupts.stack_lim...
{ // The stack limit was previously set by a previous wasm // call on the stack. We leave the original stack limit for // wasm in place in that case, and don't reset the stack // limit when we're done. false }
conditional_block
lifecycle.rs
env, process, mem::{ MaybeUninit, }, sync::{ atomic::Ordering, }, path::{ Path, }, ffi::{ OsStr, }, }; use thread_id; use atomig::{Atom}; use once_cell::{ sync::{ OnceCell, }, }; use crate::*; use crate::MrapiStatusFlag::*; use crate::internal::db::{ MrapiDatabas...
let mrapi_db = MrapiDatabase::global_db(); // 3) Add the process/node/domain to the database let mut d: usize = 0; let mut n: usize = 0; let mut p: usize = 0; // First see if this domain already exists for d in 0..MRAPI_MAX_DOMAINS { let packed = &mrapi_db.domains[d].state.load(Order...
MRAPI_TID.with(|id| { id.set(tid); }); // Seed random number generator os_srand(tid);
random_line_split
mod.rs
/// Purpose of these submudules is to create a recursive page table hierarchy /// with four levels of pagetables in it. /// To acomplish this a enum Hierarchy to differentiate between the top three /// levels and the fourth. As a result of this we can extract the addresses stored /// in the first three levels then jump...
use core::ops::Range; // Create a temporary page at some page number, in this case 0xcafebabe let mut temporary_page = TemporaryPage::new(Page { number: 0xcafebabe }, allocator); // Created by constructor let mut active_table = unsafe { ActivePageTable::new() }; // Created by constructor...
} /// Remaps the kernel sections by creating a temporary page. pub fn remap_the_kernel<A>(allocator: &mut A, boot_info: &BootInformation, sdt_loc: &mut SDT_Loc) -> ActivePageTable where A: FrameAllocator{
random_line_split
mod.rs
/// Purpose of these submudules is to create a recursive page table hierarchy /// with four levels of pagetables in it. /// To acomplish this a enum Hierarchy to differentiate between the top three /// levels and the fourth. As a result of this we can extract the addresses stored /// in the first three levels then jump...
/// Returns inclusive range iterator of pages pub fn range_inclusive(start: Page, end: Page) -> PageIter { PageIter { start: start, end: end } } } pub struct PageIter { start: Page, end: Page } impl Iterator for PageIter { type Item = Page; fn nex...
{ (self.number >> 0) & 0o777 }
identifier_body
mod.rs
/// Purpose of these submudules is to create a recursive page table hierarchy /// with four levels of pagetables in it. /// To acomplish this a enum Hierarchy to differentiate between the top three /// levels and the fourth. As a result of this we can extract the addresses stored /// in the first three levels then jump...
(&self) -> usize { (self.number >> 0) & 0o777 } /// Returns inclusive range iterator of pages pub fn range_inclusive(start: Page, end: Page) -> PageIter { PageIter { start: start, end: end } } } pub struct PageIter { start: Page, end: Page } imp...
p1_index
identifier_name
mod.rs
/// Purpose of these submudules is to create a recursive page table hierarchy /// with four levels of pagetables in it. /// To acomplish this a enum Hierarchy to differentiate between the top three /// levels and the fourth. As a result of this we can extract the addresses stored /// in the first three levels then jump...
} } let ioapic_start = Frame::containing_address(sdt_loc.ioapic_start); let ioapic_end = Frame::containing_address(sdt_loc.ioapic_end); for frame in Frame::range_inclusive(ioapic_start, ioapic_end) { if mapper.is_unused(&frame, allocator) { mappe...
{ mapper.identity_map(next_header_frame, PRESENT, allocator); }
conditional_block
module.rs
display = "Cannot find method with pointer {:?}.", _0)] pub struct CannotFindMethod(language_server::MethodPointer); #[allow(missing_docs)] #[derive(Fail, Clone, Debug)] #[fail(display = "The definition with crumbs {:?} is not a direct child of the module.", _0)] pub struct NotDirectChild(ast::Crumbs); // =========...
add_line(Some(ast)); if blank_line == BlankLinePlacement::After { add_line(None); } Ok(()) } /// Add a new method definition to the module. pub fn add_method( &mut self, method: definition::ToAdd, location: Placement, parser: &pa...
{ add_line(None); }
conditional_block
module.rs
display = "Cannot find method with pointer {:?}.", _0)] pub struct CannotFindMethod(language_server::MethodPointer); #[allow(missing_docs)] #[derive(Fail, Clone, Debug)] #[fail(display = "The definition with crumbs {:?} is not a direct child of the module.", _0)] pub struct NotDirectChild(ast::Crumbs); // =========...
( &mut self, parser: &parser::Parser, to_add: import::Info, ) -> Option<usize> { (!self.contains_import(to_add.id())).then(|| self.add_import(parser, to_add)) } /// Place the line with given AST in the module's body. /// /// Unlike `add_line` (which is more low-level...
add_import_if_missing
identifier_name
module.rs
(display = "Cannot find method with pointer {:?}.", _0)] pub struct CannotFindMethod(language_server::MethodPointer); #[allow(missing_docs)] #[derive(Fail, Clone, Debug)] #[fail(display = "The definition with crumbs {:?} is not a direct child of the module.", _0)] pub struct NotDirectChild(ast::Crumbs); // ========...
/// The segments of all parent modules, from the top module to the direct parent. Does **not** /// include project name. pub parent_modules: Vec<ImString>, } impl Id { /// Create module id from list of segments. The list shall not contain the project name nor /// namespace. Fails if the list is emp...
pub struct Id { /// The last segment being a module name. For project's main module it should be equal /// to [`PROJECTS_MAIN_MODULE`]. pub name: ImString,
random_line_split
init.rs
// Copyright (c) 2021 ESRLabs // // 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 agre...
set_no_new_privs(true); // Capabilities drop_capabilities(manifest.capabilities.as_ref()); // Close and dup fds file_descriptors(fds); // Clone match clone(CloneFlags::empty(), Some(SIGCHLD as i32)) { Ok(result) => match result { unistd::ForkResult::Parent { child } =>...
setgroups(groups); // No new privileges
random_line_split
init.rs
// Copyright (c) 2021 ESRLabs // // 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 agre...
(value: bool) { #[cfg(target_os = "android")] const PR_SET_CHILD_SUBREAPER: c_int = 36; #[cfg(not(target_os = "android"))] use libc::PR_SET_CHILD_SUBREAPER; let value = if value { 1u64 } else { 0u64 }; let result = unsafe { nix::libc::prctl(PR_SET_CHILD_SUBREAPER, value, 0, 0, 0) }; Errno::...
set_child_subreaper
identifier_name
init.rs
// Copyright (c) 2021 ESRLabs // // 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 agre...
fn setgroups(groups: &[u32]) { let result = unsafe { nix::libc::setgroups(groups.len(), groups.as_ptr()) }; Errno::result(result) .map(drop) .expect("Failed to set supplementary groups"); } /// Drop capabilities fn drop_capabilities(cs: Option<&HashSet<caps::Capability>>) { let mut bounded...
{ unistd::setsid().expect("Failed to call setsid"); }
identifier_body
oid.rs
use crate::*; use alloc::borrow::Cow; #[cfg(not(feature = "std"))] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::{ convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr, }; #[cfg(feature = "bigint")] use num_bigint::BigUint; use num_trait...
} #[cfg(feature = "std")] impl ToDer for Oid<'_> { fn to_der_len(&self) -> Result<usize> { // OID/REL-OID tag will not change header size, so we don't care here let header = Header::new( Class::Universal, false, Self::TAG, Length::Definite(self.asn1.l...
impl DerAutoDerive for Oid<'_> {} impl<'a> Tagged for Oid<'a> { const TAG: Tag = Tag::Oid;
random_line_split
oid.rs
use crate::*; use alloc::borrow::Cow; #[cfg(not(feature = "std"))] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::{ convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr, }; #[cfg(feature = "bigint")] use num_bigint::BigUint; use num_trait...
if max_bits > 64 { return None; } Some(SubIdentifierIterator { oid: self, pos: 0, first: false, n: PhantomData, }) } pub fn from_ber_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> { let (rem, any) = Any::f...
{ // Check that every arc fits into u64 let bytes = if self.relative { &self.asn1 } else if self.asn1.is_empty() { &[] } else { &self.asn1[1..] }; let max_bits = bytes .iter() .fold((0usize, 0usize), |(max, cur),...
identifier_body
oid.rs
use crate::*; use alloc::borrow::Cow; #[cfg(not(feature = "std"))] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::{ convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr, }; #[cfg(feature = "bigint")] use num_bigint::BigUint; use num_trait...
() { let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert_eq!(oid, oid! {1.2.840.113549.1.1.1}); let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap(); assert!(compare_oid(&oid)); } #[test] fn oid_to_der() { let oid = super::oid! {1.2.840.11354...
test_compare_oid
identifier_name
oid.rs
use crate::*; use alloc::borrow::Cow; #[cfg(not(feature = "std"))] use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::{ convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr, }; #[cfg(feature = "bigint")] use num_bigint::BigUint; use num_trait...
} Some(res) } } impl<'a, N: Repr> FusedIterator for SubIdentifierIterator<'a, N> {} impl<'a, N: Repr> ExactSizeIterator for SubIdentifierIterator<'a, N> { fn len(&self) -> usize { if self.oid.relative { self.oid.asn1.iter().filter(|o| (*o >> 7) == 0u8).count() } el...
{ break; }
conditional_block
map.rs
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::cmp; use game::rect::*; use game::tile::*; use game::object::*; use game::draw_info::*; use game::is_blocked; pub struct Map { tiles: Vec<Tile>, width:i32, height:i32, out_of_bounds_tile: Tile, } //TODO Maybe one day we can implemen...
fn create_v_tunnel(&mut self, y1: i32, y2: i32, x: i32) { for y in cmp::min(y1, y2)..(cmp::max(y1, y2) + 1) { self.set(x,y, Tile::empty()); } } fn create_h_tunnel(&mut self, x1: i32, x2: i32, y: i32) { for x in cmp::min(x1, x2)..(cmp::max(x1, x2) + 1) { self...
{ for x in (room.x1 + 1) .. room.x2 { for y in (room.y1 + 1) .. room.y2 { self.set(x,y,Tile::empty()); } } }
identifier_body
map.rs
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::cmp; use game::rect::*; use game::tile::*; use game::object::*; use game::draw_info::*; use game::is_blocked; pub struct Map { tiles: Vec<Tile>, width:i32, height:i32, out_of_bounds_tile: Tile, } //TODO Maybe one day we can implemen...
let y = rng.gen_range(0, map.height()); let tile_blocked = is_blocked(x,y, &map, objects); if!tile_blocked { let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc // create an orc Obj...
random_line_split
map.rs
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::cmp; use game::rect::*; use game::tile::*; use game::object::*; use game::draw_info::*; use game::is_blocked; pub struct Map { tiles: Vec<Tile>, width:i32, height:i32, out_of_bounds_tile: Tile, } //TODO Maybe one day we can implemen...
} let sim_steps = 6; for _ in 0.. sim_steps { map.caves_sim_step(); } let max_spawn_chances = 200; let mut spawn_attempts = 0; let desired_monsters = 15; let mut spawn_amount = 0; while spawn_attempts < max_spawn...
{ *tile = Tile::empty(); }
conditional_block
map.rs
#![allow(dead_code)] extern crate rand; use rand::Rng; use std::cmp; use game::rect::*; use game::tile::*; use game::object::*; use game::draw_info::*; use game::is_blocked; pub struct Map { tiles: Vec<Tile>, width:i32, height:i32, out_of_bounds_tile: Tile, } //TODO Maybe one day we can implemen...
(width:i32, height:i32, default_tile:Tile) -> Self { assert!(width > 0, "width must be greater than 0!"); assert!(height > 0, "height must be greater than 0!"); Map { tiles: vec![default_tile; (height * width) as usize], width:width, height:height, ...
new
identifier_name
encode.rs
use super::constants::{CR, DEFAULT_LINE_SIZE, DOT, ESCAPE, LF, NUL}; use super::errors::EncodeError; use std::fs::File; use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write}; use std::path::Path; /// Options for encoding. /// The entry point for encoding a file (part) /// to a file or (TCP) stream. #[deriv...
211, 212, 213, 214, 215, 216,217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 61, 64, 1, 2, 3, ...
133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 13, 10, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, ...
random_line_split