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
rcu.rs
//! Reset and clock unit use crate::pac::RCU; use riscv::interrupt; use crate::time::Hertz; use core::cmp; /// Extension trait that sets up the `RCU` peripheral pub trait RcuExt { /// Configure the clocks of the `RCU` peripheral fn configure(self) -> UnconfiguredRcu; } impl RcuExt for RCU { fn configure...
} } None }; let (d, m) = calculate_pll(hxtal_freq, target_sysclk).expect("invalid sysclk value"); predv0_bits = d - 1; pllmf = m; } else { // IRC8M/2 is used as an...
{ let pllmf; if let Some(hxtal_freq) = self.hxtal { // Use external clock + divider pllsel_bit = true; let calculate_pll = |source: u32, target: u32| -> Option<(u8, u8)> { const PLL_IN_MIN: u32 = 600_000; l...
conditional_block
lib.rs
#![doc(html_root_url = "https://docs.rs/broadword/0.2.2")] //! Broadword operations treat a `u64` as a parallel vector of eight `u8`s or `i8`s. //! This module also provides a population count function [`count_ones`](fn.count_ones.html) and a //! select function [`select1`](fn.select1.html). //! //! The algorithms here...
} quickcheck! { fn u_nz8_prop(argument: (u64, u64, u64, u64)) -> bool { let n = hash(&argument); let r = u_nz8(n); for i in 0..8 { let ni = get_bits(n, 8 * i, 8); let ri = get_bits(r, 8 * i, 8); if (ni!= 0)!= (ri == 0x8...
random_line_split
lib.rs
#![doc(html_root_url = "https://docs.rs/broadword/0.2.2")] //! Broadword operations treat a `u64` as a parallel vector of eight `u8`s or `i8`s. //! This module also provides a population count function [`count_ones`](fn.count_ones.html) and a //! select function [`select1`](fn.select1.html). //! //! The algorithms here...
i8, b: i8, c: i8, d: i8, e: i8, f: i8, g: i8, h: i8) -> u64 { u(a as u8, b as u8, c as u8, d as u8, e as u8, f as u8, g as u8, h as u8) } fn hash<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } }
as u64) << 56) | ((b as u64) << 48) | ((c as u64) << 40) | ((d as u64) << 32) | ((e as u64) << 24) | ((f as u64) << 16) | ((g as u64) << 8) | (h as u64) } fn i(a:
identifier_body
lib.rs
#![doc(html_root_url = "https://docs.rs/broadword/0.2.2")] //! Broadword operations treat a `u64` as a parallel vector of eight `u8`s or `i8`s. //! This module also provides a population count function [`count_ones`](fn.count_ones.html) and a //! select function [`select1`](fn.select1.html). //! //! The algorithms here...
ssert_eq!(64, count_ones(0xFFFF_FFFF_FFFF_FFFF)); } fn count_ones_prop_base(word: u64) -> bool { count_ones(word) == word.count_ones() as usize } quickcheck! { fn count_ones_prop(word: u64) -> bool { count_ones_prop_base(word) } fn count_ones_prop_hash(word...
f_ffff_ffff_ffff() { a
identifier_name
lib.rs
#![doc(html_root_url = "https://docs.rs/broadword/0.2.2")] //! Broadword operations treat a `u64` as a parallel vector of eight `u8`s or `i8`s. //! This module also provides a population count function [`count_ones`](fn.count_ones.html) and a //! select function [`select1`](fn.select1.html). //! //! The algorithms here...
nds the index of the `r`th one bit in `x`, returning 72 when not found. /// /// Branchless. Uses the broadword algorithm from Vigna. /// Note that bits are numbered from least-significant to most. #[inline] #[allow(clippy::many_single_char_names)] pub fn select1_raw(r: usize, x: u64) -> usize { let r = r as u64; ...
lt)} } /// Fi
conditional_block
uart.rs
//! Universal asynchronous receiver/transmitter with EasyDMA (UARTE) //! //! The driver provides only tranmission functionlity //! //! Author //! ------------------- //! //! * Author: Niklas Adolfsson <niklasadolfsson1@gmail.com> //! * Date: March 10 2018 use core::cell::Cell; use kernel; use kernel::common::regs::{Re...
{ regs: *const UarteRegisters, client: Cell<Option<&'static kernel::hil::uart::Client>>, buffer: kernel::common::take_cell::TakeCell<'static, [u8]>, remaining_bytes: Cell<usize>, offset: Cell<usize>, } #[derive(Copy, Clone)] pub struct UARTParams { pub baud_rate: u32, } /// UARTE0 handle // T...
Uarte
identifier_name
uart.rs
//! Universal asynchronous receiver/transmitter with EasyDMA (UARTE) //! //! The driver provides only tranmission functionlity //! //! Author //! ------------------- //! //! * Author: Niklas Adolfsson <niklasadolfsson1@gmail.com> //! * Date: March 10 2018 use core::cell::Cell; use kernel; use kernel::common::regs::{Re...
pub pselrts: ReadWrite<u32, Psel::Register>, // 0x508-0x50c pub pseltxd: ReadWrite<u32, Psel::Register>, // 0x50c-0x510 pub pselcts: ReadWrite<u32, Psel::Register>, // 0x510-0x514 pub pselrxd: ReadWrite<u32, Psel::Register>, // 0x514-0x518 _reserved14: [u32; 3], ...
pub errorsrc: ReadWrite<u32, ErrorSrc::Register>, // 0x480-0x484 _reserved12: [u32; 31], // 0x484-0x500 pub enable: ReadWrite<u32, Uart::Register>, // 0x500-0x504 _reserved13: [u32; 1], // 0x504-0x508
random_line_split
uart.rs
//! Universal asynchronous receiver/transmitter with EasyDMA (UARTE) //! //! The driver provides only tranmission functionlity //! //! Author //! ------------------- //! //! * Author: Niklas Adolfsson <niklasadolfsson1@gmail.com> //! * Date: March 10 2018 use core::cell::Cell; use kernel; use kernel::common::regs::{Re...
client.transmit_complete(buffer, kernel::hil::uart::Error::CommandComplete); }); }); } // Not all bytes have been transmitted then update offset and continue transmitting else { self.set_dma_pointer_to_buffer...
{ regs.event_endtx.write(Event::READY::CLEAR); let tx_bytes = regs.txd_amount.get() as usize; let rem = self.remaining_bytes.get(); // More bytes transmitted than requested `return silently` // Cause probably a hardware fault // FIXME: Progate err...
conditional_block
plonk_util.rs
use crate::partition::get_subgroup_shift; use crate::witness::Witness; use crate::{ifft_with_precomputation_power_of_2, msm_execute_parallel, AffinePoint, CircuitBuilder, Curve, FftPrecomputation, Field, HaloCurve, MsmPrecomputation, Polynomial, PolynomialCommitment, ProjectivePoint, Target, NUM_ROUTED_WIRES}; use rayo...
<F: Field>(coeffs: &[F], x: F) -> F { let mut ans = F::ZERO; let mut x_pow = F::ONE; for &c in coeffs { ans = ans + (c * x_pow); x_pow = x_pow * x; } ans } /// Compute `[x^0, x^1,..., x^(n - 1)]`. pub fn powers<F: Field>(x: F, n: usize) -> Vec<F> { let mut powers = Vec::new(); ...
eval_poly
identifier_name
plonk_util.rs
use crate::partition::get_subgroup_shift; use crate::witness::Witness; use crate::{ifft_with_precomputation_power_of_2, msm_execute_parallel, AffinePoint, CircuitBuilder, Curve, FftPrecomputation, Field, HaloCurve, MsmPrecomputation, Polynomial, PolynomialCommitment, ProjectivePoint, Target, NUM_ROUTED_WIRES}; use rayo...
}
{ type F = <Tweedledee as Curve>::ScalarField; let us = (0..10).map(|_| F::rand()).collect::<Vec<_>>(); let x = F::rand(); assert_eq!( F::inner_product(&halo_s(&us), &powers(x, 1 << 10)), halo_g(x, &us) ); }
identifier_body
plonk_util.rs
use crate::partition::get_subgroup_shift; use crate::witness::Witness; use crate::{ifft_with_precomputation_power_of_2, msm_execute_parallel, AffinePoint, CircuitBuilder, Curve, FftPrecomputation, Field, HaloCurve, MsmPrecomputation, Polynomial, PolynomialCommitment, ProjectivePoint, Target, NUM_ROUTED_WIRES}; use rayo...
if bit_lo { endo_p_p } else { endo_p_n } } else if bit_lo { p_p } else { p_n }; acc = acc.double() + s; } acc.to_affine() } pub fn eval_poly<F: Field>(coeffs: &[F], x: F) -> F { let ...
let s = if bit_hi {
random_line_split
plonk_util.rs
use crate::partition::get_subgroup_shift; use crate::witness::Witness; use crate::{ifft_with_precomputation_power_of_2, msm_execute_parallel, AffinePoint, CircuitBuilder, Curve, FftPrecomputation, Field, HaloCurve, MsmPrecomputation, Polynomial, PolynomialCommitment, ProjectivePoint, Target, NUM_ROUTED_WIRES}; use rayo...
; let (c, d) = if bit_hi { (sign, zero) } else { (zero, sign) }; a = a.double() + c; b = b.double() + d; } a * C::ZETA_SCALAR + b } /// Compute `[n(s)].P` for a given `s`, where `n` is the injective function related to the Halo /// endomorphism. pub fn halo_n_mul<C: HaloCurve>(s_bits:...
{ C::ScalarField::NEG_ONE }
conditional_block
main.rs
#![no_std] #![no_main] use core::cell::RefCell; use cortex_m::{asm::wfi, interrupt::Mutex}; use cortex_m_rt::entry; use embedded_hal::spi::MODE_1; use stm32f4xx_hal as hal; use hal::{ adc::config::{Align, Clock, Continuous, Resolution, Scan}, gpio::{gpioa, Output, PushPull, gpioc::{PC10, PC11, PC12}, Alterna...
}); static mut SPI3: Option<TypeSpi3> = None; static mut MOTOR: Option<TypeMotor> = None; unsafe{ let mut spi3 = SPI3.get_or_insert_with(|| { cortex_m::interrupt::free(|cs| { G_SPI3.borrow(cs).replace(None).unwrap() }) }); let device = p...
{ let _ = tim.wait(); }
conditional_block
main.rs
#![no_std] #![no_main] use core::cell::RefCell; use cortex_m::{asm::wfi, interrupt::Mutex}; use cortex_m_rt::entry; use embedded_hal::spi::MODE_1; use stm32f4xx_hal as hal; use hal::{ adc::config::{Align, Clock, Continuous, Resolution, Scan}, gpio::{gpioa, Output, PushPull, gpioc::{PC10, PC11, PC12}, Alterna...
/* // LED Debug cortex_m::interrupt::free(|cs| { if let Some(ref mut led) = G_LED.borrow(cs).borrow_mut().as_mut() { led.toggle().unwrap(); } }); */ } #[interrupt] fn TIM2() { cortex_m::interrupt::free(|cs| { if let Some(ref mut tim) = G_TIM.borrow(cs).borr...
{ // current sensing unsafe { let max_sample:u32 = (1 << 12) - 1; let device = pac::Peripherals::steal(); device.ADC1.sr.modify(|_, w| w.jeoc().clear_bit()); let jdr1_data = device.ADC1.jdr1.read().jdata().bits(); let jdr1_offset = 48u32; let so1 = ( ( (u32::fro...
identifier_body
main.rs
#![no_std] #![no_main] use core::cell::RefCell; use cortex_m::{asm::wfi, interrupt::Mutex}; use cortex_m_rt::entry; use embedded_hal::spi::MODE_1; use stm32f4xx_hal as hal; use hal::{ adc::config::{Align, Clock, Continuous, Resolution, Scan}, gpio::{gpioa, Output, PushPull, gpioc::{PC10, PC11, PC12}, Alterna...
() { // current sensing unsafe { let max_sample:u32 = (1 << 12) - 1; let device = pac::Peripherals::steal(); device.ADC1.sr.modify(|_, w| w.jeoc().clear_bit()); let jdr1_data = device.ADC1.jdr1.read().jdata().bits(); let jdr1_offset = 48u32; let so1 = ( ( (u32::...
ADC
identifier_name
main.rs
#![no_std] #![no_main] use core::cell::RefCell; use cortex_m::{asm::wfi, interrupt::Mutex}; use cortex_m_rt::entry; use embedded_hal::spi::MODE_1; use stm32f4xx_hal as hal; use hal::{ adc::config::{Align, Clock, Continuous, Resolution, Scan}, gpio::{gpioa, Output, PushPull, gpioc::{PC10, PC11, PC12}, Alterna...
static G_MOTOR: Mutex<RefCell<Option<TypeMotor>>> = Mutex::new(RefCell::new(None)); static G_TIM: Mutex<RefCell<Option<Timer<TIM2>>>> = Mutex::new(RefCell::new(None)); static mut CURRENT_A: f32 = 0.0; static mut CURRENT_B: f32 = 0.0; static mut CURRENT_C: f32 = 0.0; static mut MOT_ANGLE: u16 = 0; static mut MOT_ANGL...
type TypeEncoder<'a> = AS5048A<'a, TypeSpi3, gpioa::PA3<Output<PushPull>>>; //static G_AS5048A: Mutex<RefCell<Option<TypeEncoder>>> = Mutex::new(RefCell::new(None)); type TypeMotor = Motor;
random_line_split
wgl.rs
use crate::{conv, device::Device, native, Backend, GlContainer, PhysicalDevice, QueueFamily}; use std::{ ffi::{CString, OsStr}, iter, mem, os::{raw::c_void, windows::ffi::OsStrExt}, ptr, }; use glow::Context as _; use hal::{adapter::Adapter, format as f, image, window}; use arrayvec::ArrayVec; us...
extent: config.extent, fbos: iter::once(fbo).collect(), }); Ok(()) } unsafe fn unconfigure_swapchain(&mut self, device: &Device) { let gl = &device.share.context; if let Some(old) = self.swapchain.take() { for fbo in old.fbos { ...
); self.swapchain = Some(Swapchain { context,
random_line_split
wgl.rs
use crate::{conv, device::Device, native, Backend, GlContainer, PhysicalDevice, QueueFamily}; use std::{ ffi::{CString, OsStr}, iter, mem, os::{raw::c_void, windows::ffi::OsStrExt}, ptr, }; use glow::Context as _; use hal::{adapter::Adapter, format as f, image, window}; use arrayvec::ArrayVec; us...
else { GetProcAddress(lib, sym.as_ptr()) as *const _ } }); Entry { hwnd, hdc: hdc as _, wgl, lib, } } } } impl Drop for Entry { fn drop(&mut self) { unsafe {...
{ addr as *const _ }
conditional_block
wgl.rs
use crate::{conv, device::Device, native, Backend, GlContainer, PhysicalDevice, QueueFamily}; use std::{ ffi::{CString, OsStr}, iter, mem, os::{raw::c_void, windows::ffi::OsStrExt}, ptr, }; use glow::Context as _; use hal::{adapter::Adapter, format as f, image, window}; use arrayvec::ArrayVec; us...
} impl window::PresentationSurface<Backend> for Surface { type SwapchainImage = native::ImageView; unsafe fn configure_swapchain( &mut self, device: &Device, config: window::SwapchainConfig, ) -> Result<(), window::CreationError> { let gl = &device.share.context; ...
{ true }
identifier_body
wgl.rs
use crate::{conv, device::Device, native, Backend, GlContainer, PhysicalDevice, QueueFamily}; use std::{ ffi::{CString, OsStr}, iter, mem, os::{raw::c_void, windows::ffi::OsStrExt}, ptr, }; use glow::Context as _; use hal::{adapter::Adapter, format as f, image, window}; use arrayvec::ArrayVec; us...
(&self) { unsafe { self.ctxt.make_current(self.hdc); } } } /// Owned context for swapchains which soley is required for presentation. #[derive(Debug)] pub(crate) struct PresentContext { /// Owned wgl context. ctxt: Context, /// Device context of the corresponding presentati...
make_current
identifier_name
particle.rs
use std::{ mem::size_of, num::{NonZeroU32, NonZeroU8}, }; use crate::{ client::{ entity::particle::Particle, render::{ create_texture, pipeline::{Pipeline, PushConstantUpdate}, world::{Camera, WorldPipelineBase}, Palette, TextureData, ...
else { *pix *= i as u8; } } let (diffuse_data, _) = palette.translate(&pixels); create_texture( device, queue, Some(&format!("particle texture {}", i)), ...
{ *pix = 0xFF; }
conditional_block
particle.rs
use std::{ mem::size_of, num::{NonZeroU32, NonZeroU8}, }; use crate::{ client::{ entity::particle::Particle, render::{ create_texture, pipeline::{Pipeline, PushConstantUpdate}, world::{Camera, WorldPipelineBase}, Palette, TextureData, ...
(&self) -> &wgpu::RenderPipeline { &self.pipeline } pub fn bind_group_layouts(&self) -> &[wgpu::BindGroupLayout] { &self.bind_group_layouts } pub fn vertex_buffer(&self) -> &wgpu::Buffer { &self.vertex_buffer } pub fn record_draw<'a, 'b, P>( &'a self, p...
pipeline
identifier_name
particle.rs
use std::{ mem::size_of, num::{NonZeroU32, NonZeroU8}, }; use crate::{ client::{ entity::particle::Particle, render::{ create_texture, pipeline::{Pipeline, PushConstantUpdate}, world::{Camera, WorldPipelineBase}, Palette, TextureData, ...
visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler { filtering: true, comparison: false, }, count: None, }, // per-index texture array wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT...
} const BIND_GROUP_LAYOUT_ENTRIES: &[wgpu::BindGroupLayoutEntry] = &[ wgpu::BindGroupLayoutEntry { binding: 0,
random_line_split
particle.rs
use std::{ mem::size_of, num::{NonZeroU32, NonZeroU8}, }; use crate::{ client::{ entity::particle::Particle, render::{ create_texture, pipeline::{Pipeline, PushConstantUpdate}, world::{Camera, WorldPipelineBase}, Palette, TextureData, ...
Self::set_push_constants( pass, Update(bump.alloc(VertexPushConstants { transform: camera.view_projection() * translation * rotation, })), Retain, Update(bump.alloc(FragmentPushConstants { ...
{ use PushConstantUpdate::*; pass.set_pipeline(self.pipeline()); pass.set_vertex_buffer(0, self.vertex_buffer.slice(..)); pass.set_bind_group(0, &self.bind_group, &[]); // face toward camera let Angles { pitch, yaw, roll } = camera.angles(); let rotation = Angle...
identifier_body
main.rs
fmt::{Display, Formatter, Result as FmtResult}; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::str::FromStr; use anyhow::{anyhow, Error as AnyErr, Result as AnyResult}; use clap::{App, Arg}; use log::debug; use slotmap::SlotMap; use aoc::grid::{Compass, Position, Turn}; use aoc::intcomp:...
.ok_or_else(|| anyhow!("No line after items"))? .trim(); } assert!( next.is_empty(), "Expected line after items to be empty, got '{}'", next ); next = lines .next() ...
random_line_split
main.rs
::{Display, Formatter, Result as FmtResult}; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::str::FromStr; use anyhow::{anyhow, Error as AnyErr, Result as AnyResult}; use clap::{App, Arg}; use log::debug; use slotmap::SlotMap; use aoc::grid::{Compass, Position, Turn}; use aoc::intcomp::{I...
explorer.goto("Security Checkpoint")?; let err = match explorer.left_wall_step() { Ok(()) => return Ok(explorer), Err(e) => e, }; match err.downcast::<Ejection>() { Ok(e) => log::info!(" {}", e), Err(e) => return Err(e), } } ...
{ let total = 1 << items.len(); for n in 0..total { let mut explorer = initial_explorer.clone(); let cur_items: BTreeSet<String> = items .iter() .enumerate() .filter_map(|(i, item)| { if (n & (1 << i)) == 0 { None ...
identifier_body
main.rs
Display, Formatter, Result as FmtResult}; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::str::FromStr; use anyhow::{anyhow, Error as AnyErr, Result as AnyResult}; use clap::{App, Arg}; use log::debug; use slotmap::SlotMap; use aoc::grid::{Compass, Position, Turn}; use aoc::intcomp::{IntC...
(&self) -> usize { self.rooms.len() } pub fn is_empty(&self) -> bool { self.rooms.is_empty() } pub fn contains(&self, room: &Room) -> bool { self.rooms_by_name.contains_key(&room.name) } fn get(&self, key: Key) -> &Room { self.rooms.get(key).unwrap() } ...
len
identifier_name
main.rs
::{Display, Formatter, Result as FmtResult}; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::str::FromStr; use anyhow::{anyhow, Error as AnyErr, Result as AnyResult}; use clap::{App, Arg}; use log::debug; use slotmap::SlotMap; use aoc::grid::{Compass, Position, Turn}; use aoc::intcomp::{I...
} } // fn north(&mut self) -> anyhow::Result<String> { // self.process_str("north") // } // fn south(&mut self) -> anyhow::Result<String> { // self.process_str("south") // } // fn east(&mut self) -> anyhow::Result<String> { // self.process_str("east") // }...
{ let output = out.as_string()?; log::warn!("process_str failure on input {}, output: {}", input, output); Err(e) }
conditional_block
gridview.rs
} Some(result) } // this will take commands_to_finalize from the old snapshot into the new // one if an error is found produced pub fn correct(&mut self, blobs: &[impl Blob]) -> Option<Snapshot> { let blob_matching = self.match_with_blobs(blobs)?; let mut was_error = fal...
];
random_line_split
gridview.rs
for mut cmd in self.commands_to_finalize.drain(..) { debug!("Sending command back for replanning: {:#?}", cmd); if let Err((mut cmd, err)) = gridview.plan(cmd) { cmd.abort(err); } } } pub fn droplet_info(&self, pid_option: Option<ProcessId>) -> Vec<D...
pub fn snapshot_ensure(&mut self) { if self.planned.is_empty() { let last = self.completed.last().unwrap(); self.planned.push_back(last.new_with_same_droplets()) } } pub fn exec_snapshot(&self) -> &Snapshot { self.completed.last().unwrap() } fn tic...
{ self.planned.back_mut().unwrap() }
identifier_body
gridview.rs
{ Disappeared, DidNotMove, Moved { from: Location, to: Location }, } impl Snapshot { pub fn new_with_same_droplets(&self) -> Snapshot { let mut new_snapshot = Snapshot::default(); new_snapshot.droplets = self.droplets.clone(); // clear out the destination because we're doing t...
DropletDiff
identifier_name
wix.rs
use super::common; use super::path_utils::{copy, Options}; use super::settings::Settings; use handlebars::{to_json, Handlebars}; use lazy_static::lazy_static; use regex::Regex; use serde::Serialize; use sha2::Digest; use uuid::Uuid; use zip::ZipArchive; use std::collections::BTreeMap; use std::fs::{create_dir_all, re...
{ /// the GUID to use on the WIX XML. guid: String, /// the id to use on the WIX XML. id: String, /// the binary path. path: String, } /// A Resource file to bundle with WIX. /// This data structure is needed because WIX requires each path to have its own `id` and `guid`. #[derive(Serialize, Clone)] struc...
Binary
identifier_name
wix.rs
use super::common; use super::path_utils::{copy, Options}; use super::settings::Settings; use handlebars::{to_json, Handlebars}; use lazy_static::lazy_static; use regex::Regex; use serde::Serialize; use sha2::Digest; use uuid::Uuid; use zip::ZipArchive; use std::collections::BTreeMap; use std::fs::{create_dir_all, re...
arch.to_string(), wxs_file_name.to_string(), format!( "-dSourceDir={}", settings.binary_path(main_binary).display() ), ]; let candle_exe = wix_toolset_path.join("candle.exe"); common::print_info(format!("running candle for {}", wxs_file_name).as_str())?; let mut cmd = Command::new(...
{ let arch = match settings.binary_arch() { "x86_64" => "x64", "x86" => "x86", target => { return Err(crate::Error::ArchError(format!( "unsupported target: {}", target ))) } }; let main_binary = settings .binaries() .iter() .find(|bin| bin.main()) .ok_o...
identifier_body
wix.rs
use super::common; use super::path_utils::{copy, Options}; use super::settings::Settings; use handlebars::{to_json, Handlebars}; use lazy_static::lazy_static; use regex::Regex; use serde::Serialize; use sha2::Digest; use uuid::Uuid; use zip::ZipArchive; use std::collections::BTreeMap; use std::fs::{create_dir_all, re...
.directories .iter() .position(|f| f.name == directory_name); if index.is_some() { // the directory entry is already a part of the chain let dir = directory_entry .directories .get_mut(index.expect("Unable to get index")) ...
random_line_split
cursor.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...
T: Clone, { #[inline] fn clone(&self) -> Self { Cursor { inner: self.inner.clone(), pos: self.pos } } #[inline] fn clone_from(&mut self, other: &Self) { self.inner.clone_from(&other.inner); self.pos = other.pos; } } impl<T> io::Seek for Cursor<T> where T: AsRef<...
where
random_line_split
cursor.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...
(&mut self) -> io::Result<()> { Ok(()) } } impl<A> Write for Cursor<Vec<u8, A>> where A: Allocator, { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { vec_write(&mut self.pos, &mut self.inner, buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { ...
flush
identifier_name
cursor.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...
// Pad if pos is above the current len. if pos > vec.len() { let diff = pos - vec.len(); // Unfortunately, `resize()` would suffice but the optimiser does not // realise the `reserve` it does can be eliminated. So we do it manually // to eliminate that extra branch let s...
{ // We want our vec's total capacity // to have room for (pos+buf_len) bytes. Reserve allocates // based on additional elements from the length, so we need to // reserve the difference vec.reserve(desired_cap - vec.len()); }
conditional_block
cursor.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...
} impl<A> Write for Cursor<Vec<u8, A>> where A: Allocator, { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { vec_write(&mut self.pos, &mut self.inner, buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { vec_write_vectored(&mut self.pos, &mut self.in...
{ Ok(()) }
identifier_body
lib.rs
#![deny( absolute_paths_not_starting_with_crate, ambiguous_associated_items, ambiguous_glob_reexports, anonymous_parameters, arithmetic_overflow, array_into_iter, asm_sub_register, bad_asm_style, bindings_with_variant_name, break_with_label_and_loop, byte_slice_in_packed_stru...
{ client::create(connection_string) }
identifier_body
lib.rs
#![deny( absolute_paths_not_starting_with_crate, ambiguous_associated_items, ambiguous_glob_reexports, anonymous_parameters, arithmetic_overflow, array_into_iter, asm_sub_register, bad_asm_style, bindings_with_variant_name, break_with_label_and_loop, byte_slice_in_packed_stru...
(connection_string: &str) -> Result<client::Client, RedisError> { client::create(connection_string) }
create
identifier_name
lib.rs
#![deny( absolute_paths_not_starting_with_crate, ambiguous_associated_items, ambiguous_glob_reexports, anonymous_parameters, arithmetic_overflow, array_into_iter, asm_sub_register, bad_asm_style, bindings_with_variant_name, break_with_label_and_loop, byte_slice_in_packed_stru...
/// extern crate simple_redis; /// /// fn main() { /// match simple_redis::create("redis://127.0.0.1:6379/") { /// Ok(client) => println!("Created Redis Client"), /// Err(error) => println!("Unable to create Redis client: {}", error) /// } /// } /// ``` pub fn create(connection_string: &str) -> ...
/// /// ```
random_line_split
structs.rs
use super::*; use mio::{ *, event::Evented, }; use ::std::{ io, io::{ Read, Write, ErrorKind, }, time, }; #[derive(Debug)] pub struct Middleman { stream: mio::net::TcpStream, buf: Vec<u8>, buf_occupancy: usize, payload_bytes: Option<u32>, } impl Middl...
return Ok(Some(msg)); } else { poll.poll(events, timeout).expect("poll() failed inside `recv_blocking()`"); if let Some(t) = timeout { // update remaining timeout let since = started_at.elapsed(); if ...
// message ready to go. Exiting loop
random_line_split
structs.rs
use super::*; use mio::{ *, event::Evented, }; use ::std::{ io, io::{ Read, Write, ErrorKind, }, time, }; #[derive(Debug)] pub struct Middleman { stream: mio::net::TcpStream, buf: Vec<u8>, buf_occupancy: usize, payload_bytes: Option<u32>, } impl Middl...
let started_at = time::Instant::now(); let mut res = None; loop { for event in events.iter() { let tok = event.token(); if res.is_none() && tok == my_tok { if! event.readiness().is_readable() { continue; ...
{ // trivial case. // message was already sitting in the buffer. return Ok(Some(msg)); }
conditional_block
structs.rs
use super::*; use mio::{ *, event::Evented, }; use ::std::{ io, io::{ Read, Write, ErrorKind, }, time, }; #[derive(Debug)] pub struct Middleman { stream: mio::net::TcpStream, buf: Vec<u8>, buf_occupancy: usize, payload_bytes: Option<u32>, } impl Middl...
(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.stream.reregister(poll, token, interest, opts) } fn deregister(&self, poll: &Poll) -> io::Result<()> { self.stream.deregister(poll) } }
reregister
identifier_name
structs.rs
use super::*; use mio::{ *, event::Evented, }; use ::std::{ io, io::{ Read, Write, ErrorKind, }, time, }; #[derive(Debug)] pub struct Middleman { stream: mio::net::TcpStream, buf: Vec<u8>, buf_occupancy: usize, payload_bytes: Option<u32>, } impl Middl...
} impl Evented for Middleman { fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.stream.register(poll, token, interest, opts) } fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<...
{ &mut self.0 }
identifier_body
main.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Overnet daemon for Fuchsia #![deny(missing_docs)] mod mdns; use failure::{Error, ResultExt}; use fidl_fuchsia_overnet::{ MeshControllerRequest, ...
() -> App { let node = Node::new( AppRuntime, NodeOptions::new() .set_quic_server_key_file(Box::new("/pkg/data/cert.key".to_string())) .set_quic_server_cert_file(Box::new("/pkg/data/cert.crt".to_string())), ) .unwrap(); App { node_id: ...
new
identifier_name
main.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Overnet daemon for Fuchsia #![deny(missing_docs)] mod mdns; use failure::{Error, ResultExt}; use fidl_fuchsia_overnet::{ MeshControllerRequest, ...
async fn at(when: fasync::Time, f: impl FnOnce()) { fasync::Timer::new(when).await; f(); } impl App { /// Create a new instance of App fn new() -> App { let node = Node::new( AppRuntime, NodeOptions::new() .set_quic_server_key_file(Box::new("/pkg/data/ce...
{ APP.with(|rcapp| f(&mut rcapp.borrow_mut())) }
identifier_body
main.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Overnet daemon for Fuchsia #![deny(missing_docs)] mod mdns; use failure::{Error, ResultExt}; use fidl_fuchsia_overnet::{ MeshControllerRequest, ...
OvernetRequest::ConnectToService { node, service_name, chan,.. } => { app.node.connect_to_service(node.id.into(), &service_name, chan) } }); if let Err(e) = result { log::warn!("Error servicing request: {:?}", e); } } Ok(()) } enum In...
{ fasync::spawn_local(run_list_peers(responder)); Ok(()) }
conditional_block
main.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Overnet daemon for Fuchsia #![deny(missing_docs)] mod mdns; use failure::{Error, ResultExt}; use fidl_fuchsia_overnet::{ MeshControllerRequest, ...
trait ListPeersResponder { fn respond( self, peers: &mut dyn ExactSizeIterator<Item = &mut fidl_fuchsia_overnet::Peer>, ) -> Result<(), fidl::Error>; } impl ListPeersResponder for ServiceConsumerListPeersResponder { fn respond( self, peers: &mut dyn ExactSizeIterator<Item = ...
}
random_line_split
lib.rs
//! This crate provides the [`quote!`] macro for turning Rust syntax tree data //! structures into tokens of source code. //! //! [`quote!`]: macro.quote.html //! //! Procedural macros in Rust receive a stream of tokens as input, execute //! arbitrary Rust code to determine how to manipulate those tokens, and produce /...
b fn append_to_tokens<T: ToTokens>(stream: &mut TokenStream, to_tokens: &T) { to_tokens.to_tokens(stream); } pub fn append_group( stream: &mut TokenStream, inner: TokenStream, delimiter: Delimiter, span: Span, ) { let mut group = Group::new(delimiter, inner);...
let s: TokenStream = s.parse().expect("invalid token stream"); stream.extend(s.into_iter().map(|mut t| { t.set_span(span); t })); } pu
identifier_body
lib.rs
//! This crate provides the [`quote!`] macro for turning Rust syntax tree data //! structures into tokens of source code. //! //! [`quote!`]: macro.quote.html //! //! Procedural macros in Rust receive a stream of tokens as input, execute //! arbitrary Rust code to determine how to manipulate those tokens, and produce /...
&mut TokenStream, punct: char, spacing: Spacing, span: Span) { let mut punct = Punct::new(punct, spacing); punct.set_span(span); stream.append(punct); } pub fn append_stringified_tokens(stream: &mut TokenStream, s: &str, span: Span) { let s: TokenStream = s.parse().expect("inva...
unct(stream:
identifier_name
lib.rs
//! This crate provides the [`quote!`] macro for turning Rust syntax tree data //! structures into tokens of source code. //! //! [`quote!`]: macro.quote.html //! //! Procedural macros in Rust receive a stream of tokens as input, execute //! arbitrary Rust code to determine how to manipulate those tokens, and produce /...
/// # ; /// ``` /// /// The solution is to perform token-level manipulations using the APIs provided /// by Syn and proc-macro2. /// /// ```edition2018 /// # use proc_macro2::{self as syn, Span}; /// # use quote::quote; /// # /// # let ident = syn::Ident::new("i", Span::call_site()); /// # /// let concatenated = format...
/// quote! { /// let mut _#ident = 0; /// }
random_line_split
tpl.rs
//! TeX templating //! //! The `tpl` module contains a way of constructing a TeX-document programmatically. It ensures //! documents are well-formed syntactically, but not semantically (e.g. it is possible to express //! documents that contain multiple `\documentclass` macro calls inside the document but not a //! `\be...
} impl TexElement for OptArgs { fn write_tex(&self, writer: &mut dyn Write) -> io::Result<()> { if!self.0.is_empty() { writer.write_all(b"[")?; write_list(writer, ",", self.0.iter())?; writer.write_all(b"]")?; } Ok(()) } } /// A set of arguments. /...
{ OptArgs(vec![elem.into_tex_element()]) }
identifier_body
tpl.rs
//! TeX templating //! //! The `tpl` module contains a way of constructing a TeX-document programmatically. It ensures //! documents are well-formed syntactically, but not semantically (e.g. it is possible to express //! documents that contain multiple `\documentclass` macro calls inside the document but not a //! `\be...
(&self, writer: &mut dyn Write) -> io::Result<()> { writer.write_all(b"{")?; for child in &self.0 { child.write_tex(writer)?; } writer.write_all(b"}")?; Ok(()) } } /// Grouping of elements. /// /// Groups multiple elements together; when output they are written i...
write_tex
identifier_name
tpl.rs
//! TeX templating //! //! The `tpl` module contains a way of constructing a TeX-document programmatically. It ensures //! documents are well-formed syntactically, but not semantically (e.g. it is possible to express //! documents that contain multiple `\documentclass` macro calls inside the document but not a //! `\be...
newline: false, } } } impl TexElement for MacroCall { fn write_tex(&self, writer: &mut dyn Write) -> io::Result<()> { writer.write_all(br"\")?; self.ident.write_tex(writer)?; self.opt_args.write_tex(writer)?; self.args.write_tex(writer)?; if self.newl...
args,
random_line_split
tpl.rs
//! TeX templating //! //! The `tpl` module contains a way of constructing a TeX-document programmatically. It ensures //! documents are well-formed syntactically, but not semantically (e.g. it is possible to express //! documents that contain multiple `\documentclass` macro calls inside the document but not a //! `\be...
arg.write_tex(writer)?; } Ok(()) } /// A raw, unescaped piece of tex code. /// /// Tex is not guaranteed to be UTF-8 encoded, thus `RawTex` internally keeps bytes. The value will /// be inserted into the document without any escaping. The value is unchecked, thus it is possible /// to create syntacti...
{ writer.write_all(separator.as_bytes())?; }
conditional_block
minijail.rs
sys::signal, unistd::{self, chown, pipe}, }; use npk::manifest::{Dev, Mount, MountFlag}; use std::{ fmt, iter, ops, os::unix::prelude::RawFd, path::{Path, PathBuf}, pin::Pin, task::{Context, Poll}, }; use tokio::{ fs, io::{self, unix::AsyncFd, AsyncBufReadExt, AsyncRead, AsyncWriteE...
// Configure UID jail.change_uid(self.uid); // Configure PID jail.change_gid(self.gid); // Update the capability mask if specified if let Some(capabilities) = &manifest.capabilities { // TODO: the capabilities should be passed as an array jail.u...
{ let seccomp_config = tmpdir_path.join("seccomp"); let mut f = fs::File::create(&seccomp_config) .await .map_err(|e| Error::Io("Failed to create seccomp configuraiton".to_string(), e))?; let s = itertools::join(seccomp.iter().map(|(k, v)| format!("{}:...
conditional_block
minijail.rs
sys::signal, unistd::{self, chown, pipe}, }; use npk::manifest::{Dev, Mount, MountFlag}; use std::{ fmt, iter, ops, os::unix::prelude::RawFd, path::{Path, PathBuf}, pin::Pin, task::{Context, Poll}, }; use tokio::{ fs, io::{self, unix::AsyncFd, AsyncBufReadExt, AsyncRead, AsyncWriteE...
(&self) -> Result<(), Error> { // Just make clippy happy if false { Err(Error::Stop) } else { Ok(()) } } pub(crate) async fn start(&self, container: &Container) -> Result<Process, Error> { let root = &container.root; let manifest = &contai...
shutdown
identifier_name
minijail.rs
sys::signal, unistd::{self, chown, pipe}, }; use npk::manifest::{Dev, Mount, MountFlag}; use std::{ fmt, iter, ops, os::unix::prelude::RawFd, path::{Path, PathBuf}, pin::Pin, task::{Context, Poll}, }; use tokio::{ fs, io::{self, unix::AsyncFd, AsyncBufReadExt, AsyncRead, AsyncWriteE...
} #[derive(Debug)] pub struct Minijail { log_fd: i32, event_tx: EventTx, run_dir: PathBuf, data_dir: PathBuf, uid: u32, gid: u32, } impl Minijail { pub(crate) fn new( event_tx: EventTx, run_dir: &Path, data_dir: &Path, uid: u32, gid: u32, ) -> R...
{ &mut self.0 }
identifier_body
minijail.rs
}, sys::signal, unistd::{self, chown, pipe}, }; use npk::manifest::{Dev, Mount, MountFlag}; use std::{ fmt, iter, ops, os::unix::prelude::RawFd, path::{Path, PathBuf}, pin::Pin, task::{Context, Poll}, }; use tokio::{ fs, io::{self, unix::AsyncFd, AsyncBufReadExt, AsyncRead, AsyncWrit...
let proc = Path::new("/proc"); jail.mount_bind(&proc, &proc, false) .map_err(Error::Minijail)?; jail.remount_proc_readonly(); // If there's no explicit mount for /dev add a minimal variant if!container .manifest .mounts .contains_key(&...
async fn setup_mounts( &self, jail: &mut MinijailHandle, container: &Container, ) -> Result<(), Error> {
random_line_split
mod.rs
use std::error::Error as StdError; use std::ffi::{CStr, CString}; use std::fmt; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::collections::HashSet; use std::fs::File; use digest::{Digest, FixedOutput}; use nix::fcntl::{fcntl, ...
io::Error::new(io::ErrorKind::Other, e) } impl SandboxingStrategy for UserChangeStrategy { fn preexec(&self) -> io::Result<()> { if let Some(ref wd) = self.workdir { std::fs::create_dir_all(wd)?; nix::unistd::chown(wd, self.set_user, self.set_group) .map_err(|err...
E: Into<Box<dyn StdError + Send + Sync>>, {
random_line_split
mod.rs
use std::error::Error as StdError; use std::ffi::{CStr, CString}; use std::fmt; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::collections::HashSet; use std::fs::File; use digest::{Digest, FixedOutput}; use nix::fcntl::{fcntl, ...
(self) -> ContainerImage { assert!(self.disk_linked, "must be disk-linked"); ContainerImage { file: self.expected_path, mounts: Vec::new(), } } pub fn finalize_executable(self) -> Executable { Executable { file: self.storage.into_owned_fd(), ...
finalize_container
identifier_name
mod.rs
use std::error::Error as StdError; use std::ffi::{CStr, CString}; use std::fmt; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::collections::HashSet; use std::fs::File; use digest::{Digest, FixedOutput}; use nix::fcntl::{fcntl, ...
Ok(ForkResult::Parent { child,.. }) => Ok(child), Err(err) => Err(io::Error::new(io::ErrorKind::Other, err)), } }
{ if let Err(err) = exec_artifact_child(e, &c) { event!(Level::WARN, "failed to execute: {:?}", err); std::process::exit(1); } else { unreachable!(); } }
conditional_block
mod.rs
use std::error::Error as StdError; use std::ffi::{CStr, CString}; use std::fmt; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::collections::HashSet; use std::fs::File; use digest::{Digest, FixedOutput}; use nix::fcntl::{fcntl, ...
pub fn new_on_disk(name: &str, capacity: i64, root: &Path) -> io::Result<ExecutableFactory> { let mut full_path = root.to_owned(); full_path.push(name); let storage = File::create(&full_path)?; Ok(ExecutableFactory { storage, expected_path: full_path, ...
{ let mut mem_fd = MemFdOptions::new() .cloexec(true) .allow_sealing(true) .with_capacity(capacity) .set_mode(Mode::S_IRWXU | Mode::S_IRGRP | Mode::S_IXGRP | Mode::S_IROTH | Mode::S_IXOTH) .open(name) .map_err(|e| nix_error_to_io_error(e))?...
identifier_body
systems.rs
// будем юзать Behaviour Tree AI //Главный скрипт работает по системе выбор-условие-действие (selector-condition-action). //Выбор — своеобразный аналог оператора switch() в языках программирования. // В «теле» элемента выбора происходит выбор одного из заданных наборов действий // в зависимости от условия. //Условие...
conditional_block
systems.rs
// будем юзать Behaviour Tree AI //Главный скрипт работает по системе выбор-условие-действие (selector-condition-action). //Выбор — своеобразный аналог оператора switch() в языках программирования. // В «теле» элемента выбора происходит выбор одного из заданных наборов действий // в зависимости от условия. //Условие...
identifier_body
systems.rs
// будем юзать Behaviour Tree AI //Главный скрипт работает по системе выбор-условие-действие (selector-condition-action). //Выбор — своеобразный аналог оператора switch() в языках программирования. // В «теле» элемента выбора происходит выбор одного из заданных наборов действий // в зависимости от условия. //Условие...
// 5. Утомился. // 6. Нет событий. // 7. Монстр насытился. // 8. Монстр напился. if self.event_time.to(PreciseTime::now()) > Duration::seconds(WORLD_SPEED) { let mut behaviour_event = entity.get_component::<BehaviourEvent>(); // события let monst...
жда.
identifier_name
systems.rs
// будем юзать Behaviour Tree AI //Главный скрипт работает по системе выбор-условие-действие (selector-condition-action). //Выбор — своеобразный аналог оператора switch() в языках программирования. // В «теле» элемента выбора происходит выбор одного из заданных наборов действий // в зависимости от условия. //Условие...
behaviour_event.event = 6; println!("ошибка/инициализация текущего события, теперь он {}", 6); } else if monster_attr.power < 960 && self.event_last!= 5 { behaviour_event.event = 5; // наступает событие - УСТАЛ self.event_last = behaviour_event...
if self.event_time.to(PreciseTime::now()) > Duration::seconds(WORLD_SPEED) { let mut behaviour_event = entity.get_component::<BehaviourEvent>(); // события let monster_attr = entity.get_component::<MonsterAttributes>(); // события if behaviour_event.event == 0 { ...
random_line_split
builder.rs
//! builders for tag path and tag use crate::DebugLevel; use std::fmt; pub use anyhow::Result; /// builder to build tag full path /// /// # Examples /// ```rust,ignore /// use plctag::builder::*; /// use plctag::RawTag; /// /// fn main() { /// let timeout = 100; /// let path = PathBuilder::de...
/// generic attribute. /// Required. Determines the type of the PLC protocol. #[inline] pub fn protocol(&mut self, protocol: Protocol) -> &mut Self { self.protocol = Some(protocol); self } /// generic attribute. /// Optional. All tags are treated as arrays. Tag...
{ self.debug = Some(level); self }
identifier_body
builder.rs
//! builders for tag path and tag use crate::DebugLevel; use std::fmt; pub use anyhow::Result; /// builder to build tag full path /// /// # Examples /// ```rust,ignore /// use plctag::builder::*; /// use plctag::RawTag; /// /// fn main() { /// let timeout = 100; /// let path = PathBuilder::de...
(&mut self, gateway: impl AsRef<str>) -> &mut Self { self.gateway = Some(gateway.as_ref().to_owned()); self } /// - EIP /// This is the full name of the tag. For program tags, prepend Program:<program name>. where <program name> is the name of the program in which the tag is created ...
gateway
identifier_name
builder.rs
//! builders for tag path and tag use crate::DebugLevel; use std::fmt; pub use anyhow::Result; /// builder to build tag full path /// /// # Examples /// ```rust,ignore /// use plctag::builder::*; /// use plctag::RawTag; /// /// fn main() { /// let timeout = 100; /// let path = PathBuilder::de...
} if let Some(yes) = self.use_connected_msg { path_buf.push(format!("use_connected_msg={}", yes as u8)); } } Protocol::ModBus => {} } if let Some(ref gateway) = self.gateway { path_buf.pus...
random_line_split
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos). // The `quote!` macro requires deep recursion. #![recursi...
let span = item.generics.span(); errors.push(Error::new("Logos currently supports permits a single lifetime generic.").span(span)); None } }; let mut parse_attr = |attr: &Attribute| -> Result<(), error::SpannedError> { if attr.path.is_ident("logos") { ...
{ let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums"); let super_span = item.span(); let size = item.variants.len(); let name = &item.ident; let mut extras: Option<Ident> = None; let mut error = None; let mut mode = Mode::Utf8; let mut errors = Vec::n...
identifier_body
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos). // The `quote!` macro requires deep recursion. #![recursi...
(input: TokenStream) -> TokenStream { let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums"); let super_span = item.span(); let size = item.variants.len(); let name = &item.ident; let mut extras: Option<Ident> = None; let mut error = None; let mut mode = Mod...
logos
identifier_name
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos). // The `quote!` macro requires deep recursion. #![recursi...
#[extras] attribute is deprecated. Use #[logos(extras = Type)] instead.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(attr.span())); } Ok(()) }; for attr in &item.attrs { ...
const ERR: &str = "\
random_line_split
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos). // The `quote!` macro requires deep recursion. #![recursi...
} let root = graph.push(root); graph.shake(root); // panic!("{:#?}\n\n{} nodes", graph, graph.nodes().iter().filter_map(|n| n.as_ref()).count()); let generator = Generator::new(name, &this, root, &graph); let body = generator.generate(); let tokens = impl_logos(quote! { use ::lo...
{ break; }
conditional_block
substrate_like.rs
// Copyright 2017, 2021 Parity Technologies // // 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...
fn extension_node( _partial: impl Iterator<Item = u8>, _nbnibble: usize, _child: ChildReference<<H as Hasher>::Out>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node( _children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, _maybe_value: Option<V...
output }
random_line_split
substrate_like.rs
// Copyright 2017, 2021 Parity Technologies // // 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...
value, }) } , } } } impl<H> NodeCodecT for NodeCodec<H> where H: Hasher, { const ESCAPE_HEADER: Option<u8> = Some(trie_constants::ESCAPE_COMPACT_HEADER); type Error = Error; type HashOut = H::Out; fn hashed_null_node() -> <H as Hasher>::Out { H::hash(<Self as NodeCodecT>::empty_node()) } fn d...
{ let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1...
conditional_block
substrate_like.rs
// Copyright 2017, 2021 Parity Technologies // // 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...
{ Leaf, BranchNoValue, BranchWithValue, HashedValueLeaf, HashedValueBranch, } impl Encode for NodeHeader { fn encode_to<T: Output +?Sized>(&self, output: &mut T) { match self { NodeHeader::Null => output.push_byte(trie_constants::EMPTY_TRIE), NodeHeader::Branch(true, nibble_count) => encode_size_and...
NodeKind
identifier_name
substrate_like.rs
// Copyright 2017, 2021 Parity Technologies // // 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...
/// Decode size only from stream input and header byte. fn decode_size(first: u8, input: &mut impl Input, prefix_mask: usize) -> Result<usize, Error> { let max_value = 255u8 >> prefix_mask; let mut result = (first & max_value) as usize; if result < max_value as usize { return Ok(result) } result -= 1; while r...
{ for b in size_and_prefix_iterator(size, prefix, prefix_mask) { out.push_byte(b) } }
identifier_body
metrics.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Defines the metrics system. //! //! # Design //! The main design goals of this system are: //! * Use lockless operations, preferably ones that don't require anything other than //! simple reads/write...
} /// Structure storing all metrics while enforcing serialization support on them. #[derive(Default, Serialize)] pub struct FirecrackerMetrics { utc_timestamp_ms: SerializeToUtcTimestampMs, /// API Server related metrics. pub api_server: ApiServerMetrics, /// A block device's related metrics. pub ...
{ serializer.serialize_i64(chrono::Utc::now().timestamp_millis()) }
identifier_body
metrics.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Defines the metrics system. //! //! # Design //! The main design goals of this system are: //! * Use lockless operations, preferably ones that don't require anything other than //! simple reads/write...
#[test] fn test_serialize() { let s = serde_json::to_string(&FirecrackerMetrics::default()); assert!(s.is_ok()); } }
M2_INITIAL_COUNT + NUM_THREADS_TO_SPAWN * NUM_INCREMENTS_PER_THREAD ); }
random_line_split
metrics.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Defines the metrics system. //! //! # Design //! The main design goals of this system are: //! * Use lockless operations, preferably ones that don't require anything other than //! simple reads/write...
() -> SeccompMetrics { let mut def_syscalls = vec![]; for _syscall in 0..SYSCALL_MAX { def_syscalls.push(SharedMetric::default()); } SeccompMetrics { num_faults: SharedMetric::default(), bad_syscalls: def_syscalls, } } } /// Metrics specif...
default
identifier_name
metrics.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Defines the metrics system. //! //! # Design //! The main design goals of this system are: //! * Use lockless operations, preferably ones that don't require anything other than //! simple reads/write...
res } } // The following structs are used to define a certain organization for the set of metrics we // are interested in. Whenever the name of a field differs from its ideal textual representation // in the serialized form, we can use the #[serde(rename = "name")] attribute to, well, rename it. /// Metr...
{ self.1.store(snapshot, Ordering::Relaxed); }
conditional_block
decode.rs
/* Copyright 2013 10gen Inc. * * 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 to in writi...
fn _jscript(&mut self) -> Result<Document, ~str> { let s = self._string(); //using this to avoid irrefutable pattern error match s { UString(s) => Ok(JScript(s)), _ => Err(~"invalid string found in javascript") } } ///Parse a scoped javascript object....
///Parse a javascript object.
random_line_split
decode.rs
/* Copyright 2013 10gen Inc. * * 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 to in writi...
///Parse a javascript object. fn _jscript(&mut self) -> Result<Document, ~str> { let s = self._string(); //using this to avoid irrefutable pattern error match s { UString(s) => Ok(JScript(s)), _ => Err(~"invalid string found in javascript") } } /...
{ let s = match self._string() { UString(rs) => rs, _ => return Err(~"invalid string found in dbref") }; let d = self.stream.aggregate(12); Ok(DBRef(s, ~ObjectId(d))) }
identifier_body
decode.rs
/* Copyright 2013 10gen Inc. * * 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 to in writi...
() { let mut doc = BsonDocument::new(); doc.put(~"foo", DBRef(~"bar", ~ObjectId(~[0u8,1,2,3,4,5,6,7,8,9,10,11]))); let stream: ~[u8] = ~[30,0,0,0,12,102,111,111,0,4,0,0,0,98,97,114,0,0,1,2,3,4,5,6,7,8,9,10,11,0]; assert_eq!(decode(stream).unwrap(), doc) } //TODO: get bson string...
test_dbref_encode
identifier_name
interop.rs
use crate::network::{self, get, post}; use anyhow::{anyhow, Result}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use url::Url; use wptfyi::interop::{Category, FocusArea}; use wptfyi::metadata::MetadataEntry; use wptfyi::result::Status; use wptfyi::search::{AndClause, Clause, Labe...
pub fn write_browser_interop_scores( browsers: &[&str], scores: &[interop::ScoreRow], interop_2023_data: &interop::YearData, ) -> Result<()> { let browser_columns = interop_columns(&interop_2023_data.focus_areas); let data_path = Path::new("../docs/interop-2023/scores.csv"); let out_f = File:...
{ let mut total_score: u64 = 0; for column in columns { let column = format!("{}-{}", browser, column); let score = row .get(&column) .ok_or_else(|| anyhow!("Failed to get column {}", column))?; let value: u64 = score .parse::<u64>() .map_e...
identifier_body
interop.rs
use crate::network::{self, get, post}; use anyhow::{anyhow, Result}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use url::Url; use wptfyi::interop::{Category, FocusArea}; use wptfyi::metadata::MetadataEntry; use wptfyi::result::Status; use wptfyi::search::{AndClause, Clause, Labe...
let browser_list = maybe_browser_list.unwrap(); writer.write_record([ "Test", "Firefox Failures", "Chrome Failures", "Safari Failures", "Bugs", ])?; for result in results.results.iter() { let mut scores = vec![String::new(), String::new(), String::new()]...
{ return Err(anyhow!("Didn't get results for all three browsers")); }
conditional_block
interop.rs
use crate::network::{self, get, post}; use anyhow::{anyhow, Result}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use url::Url; use wptfyi::interop::{Category, FocusArea}; use wptfyi::metadata::MetadataEntry; use wptfyi::result::Status; use wptfyi::search::{AndClause, Clause, Labe...
(wptfyi: &Wptfyi, client: &reqwest::blocking::Client) -> Result<Vec<result::Run>> { let mut runs = wptfyi.runs(); for product in ["chrome", "firefox", "safari"].iter() { runs.add_product(product, "experimental") } runs.add_label("master"); runs.set_max_count(100); Ok(run::parse(&get(clie...
get_run_data
identifier_name
interop.rs
use crate::network::{self, get, post}; use anyhow::{anyhow, Result}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use url::Url; use wptfyi::interop::{Category, FocusArea}; use wptfyi::metadata::MetadataEntry; use wptfyi::result::Status; use wptfyi::search::{AndClause, Clause, Labe...
let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let mut headers = Vec::with_capacity(browsers.len() + 1); headers.push("date"); headers.extend_from_slice(browsers); writer.write_record(...
random_line_split
lib.rs
name { #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] ...
} ///This returns the value read on the supplied analog input pin. You ///will need to register additional analog modules to enable this ///function for devices such as the Gertboard, quick2Wire analog ///board, etc. pub fn analog_read(&self) -> u16 { unsafe { ...
High }
conditional_block
lib.rs
{ #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] ...
ode: PwmMode) { unsafe { bindings::pwmSetMode(mode as libc::c_int); } } ///This sets the range register in the PWM generator. The default is 1024. pub fn set_range(&self, value: u16) { unsafe { bindings::pwmSetRange(value as li...
&self, m
identifier_name
lib.rs
name { #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] ...
#[inline] pub fn number(&self) -> libc::c_int { let &SoftPwmPin(number, _) = self; number } /// Sets the duty cycle. /// /// `value` has to be in the interval [0,100]. pub fn pwm_write(&self, value: libc::c_int) { unsafe { ...
unsafe { bindings::softPwmCreate(pin, 0, 100); } SoftPwmPin(pin, PhantomData) }
identifier_body
lib.rs
$name { #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] ...
/// /// Unfortunately the C implementation does not allow userdata to be passed around, /// so the callback must be able to determine what caused the interrupt just by the /// function that was invoked. /// /// See https://github.com/Ogeon/rust-wiringpi/pull/28 for ...
/// The callback function does not need to be reentrant. /// /// The callback must be an actual function (not a closure!), and must be using /// the extern "C" modifier so that it can be passed to the wiringpi library, /// and called from C code.
random_line_split
lib.rs
//! This is a platform-agnostic Rust driver for the Sensirion STS30, STS31, and STS35 //! high-accuracy, low-power, I2C digital temperature sensors, based on the //! [`embedded-hal`] traits. //! //! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal //! //! TODO: More information here. //! //! The driv...
// write and read private methods /// Write an I2C command to the sensor fn send_command(&mut self, command: Command) -> Result<(), Error<E>> { self.i2c .write(self.address, &command.as_bytes()) .map_err(Error::I2C) } /// Read and check the CRC. /// Returns a Result w...
self.i2c }
identifier_body
lib.rs
//! This is a platform-agnostic Rust driver for the Sensirion STS30, STS31, and STS35 //! high-accuracy, low-power, I2C digital temperature sensors, based on the //! [`embedded-hal`] traits. //! //! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal //! //! TODO: More information here. //! //! The driv...
// }
// 20 // }
random_line_split
lib.rs
//! This is a platform-agnostic Rust driver for the Sensirion STS30, STS31, and STS35 //! high-accuracy, low-power, I2C digital temperature sensors, based on the //! [`embedded-hal`] traits. //! //! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal //! //! TODO: More information here. //! //! The driv...
ConversionRate::_10Hz => { match r { Repeatability::High => [0x27, 0x37], Repeatability::Medium => [0x27, 0x21], Repeatability::Low => [0x27, 0x2A], } }...
match r { Repeatability::High => [0x23, 0x34], Repeatability::Medium => [0x23, 0x22], Repeatability::Low => [0x23, 0x29], } },
conditional_block
lib.rs
//! This is a platform-agnostic Rust driver for the Sensirion STS30, STS31, and STS35 //! high-accuracy, low-power, I2C digital temperature sensors, based on the //! [`embedded-hal`] traits. //! //! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal //! //! TODO: More information here. //! //! The driv...
elf, r: Repeatability) -> Repeatability{ self.repeatability = r; r } // pub fn into_continuous(self, rate: ConversionRate) -> Result<Sts3x<I2C, marker::mode::Continuous>, ModeChangeError<E, Self>> // /// Reset the state of the driver, to be used if there was a "general call" on the I2C bu...
eatability(&mut s
identifier_name
softmax.rs
use alumina_core::{ base_ops::{OpInstance, OpSpecification}, errors::{ExecutionError, GradientError, OpBuildError, ShapePropError}, exec::ExecutionContext, grad::GradientContext, graph::{Graph, Node, NodeID}, shape_prop::ShapePropContext, util::wrap_dim, }; use indexmap::{indexset, IndexMap, IndexSet}; use ndarr...
(&self, mapping: &IndexMap<Node, Node>) -> Self { Self { logits: mapping.get(&self.logits).unwrap_or(&self.logits).clone(), output_grad: mapping.get(&self.output_grad).unwrap_or(&self.output_grad).clone(), logits_grad: mapping.get(&self.logits_grad).unwrap_or(&self.logits_grad).clone(), axis: self.axis, ...
clone_with_nodes_changed
identifier_name
softmax.rs
use alumina_core::{ base_ops::{OpInstance, OpSpecification}, errors::{ExecutionError, GradientError, OpBuildError, ShapePropError}, exec::ExecutionContext, grad::GradientContext, graph::{Graph, Node, NodeID}, shape_prop::ShapePropContext, util::wrap_dim, }; use indexmap::{indexset, IndexMap, IndexSet}; use ndarr...
}) } } /// SoftmaxBack OpInstance #[derive(Clone, Debug)] pub struct SoftmaxBackInstance { logits: NodeID, logits_grad: NodeID, output_grad: NodeID, axis: usize, } impl OpInstance for SoftmaxBackInstance { fn type_name(&self) -> &'static str { "SoftmaxBack" } fn as_specification(&self, graph: &Graph) -> ...
axis: self.axis,
random_line_split